checkstyle-5.6/ 40755 0 0 0 12026055055 10554 5ustar 0 0 checkstyle-5.6/.idea/ 40755 0 0 0 11511034155 11530 5ustar 0 0 checkstyle-5.6/.idea/copyright/ 40755 0 0 0 11511026736 13546 5ustar 0 0 checkstyle-5.6/.idea/libraries/ 40755 0 0 0 11511027065 13506 5ustar 0 0 checkstyle-5.6/.settings/ 40755 0 0 0 11714707710 12477 5ustar 0 0 checkstyle-5.6/config/ 40755 0 0 0 11451071611 12016 5ustar 0 0 checkstyle-5.6/contrib/ 40755 0 0 0 11451071612 12212 5ustar 0 0 checkstyle-5.6/contrib/bcel/ 40755 0 0 0 11451011230 13105 5ustar 0 0 checkstyle-5.6/contrib/bcel/docs/ 40755 0 0 0 11451071611 14046 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/ 40755 0 0 0 11451011230 13674 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/checkstyle/ 40755 0 0 0 11451011230 16032 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/checkstyle/com/ 40755 0 0 0 11451011230 16610 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/checkstyle/com/puppycrawl/ 40755 0 0 0 11451011230 21016 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/checkstyle/com/puppycrawl/tools/ 40755 0 0 0 11451011230 22156 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/checkstyle/com/puppycrawl/tools/checkstyle/ 40755 0 0 0 11451011230 24314 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/checkstyle/com/puppycrawl/tools/checkstyle/bcel/ 40755 0 0 0 11451071611 25232 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/checkstyle/com/puppycrawl/tools/checkstyle/bcel/checks/ 40755 0 0 0 11451071612 26473 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/checkstyle/com/puppycrawl/tools/checkstyle/bcel/classfile/ 40755 0 0 0 11451071612 27200 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/checkstyle/com/puppycrawl/tools/checkstyle/bcel/generic/ 40755 0 0 0 11451071612 26647 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/testinputs/ 40755 0 0 0 11451011230 16116 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/testinputs/com/ 40755 0 0 0 11451011230 16674 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/testinputs/com/puppycrawl/ 40755 0 0 0 11451011230 21102 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/testinputs/com/puppycrawl/tools/ 40755 0 0 0 11451011230 22242 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/testinputs/com/puppycrawl/tools/checkstyle/ 40755 0 0 0 11451011230 24400 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/testinputs/com/puppycrawl/tools/checkstyle/bcel/ 40755 0 0 0 11451011230 25305 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/testinputs/com/puppycrawl/tools/checkstyle/bcel/checks/ 40755 0 0 0 11451071612 26557 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/tests/ 40755 0 0 0 11451011230 15036 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/tests/com/ 40755 0 0 0 11451011230 15614 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/tests/com/puppycrawl/ 40755 0 0 0 11451011230 20022 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/tests/com/puppycrawl/tools/ 40755 0 0 0 11451011230 21162 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/tests/com/puppycrawl/tools/checkstyle/ 40755 0 0 0 11451011230 23320 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/tests/com/puppycrawl/tools/checkstyle/bcel/ 40755 0 0 0 11451071612 24237 5ustar 0 0 checkstyle-5.6/contrib/bcel/src/tests/com/puppycrawl/tools/checkstyle/bcel/checks/ 40755 0 0 0 11451071612 25477 5ustar 0 0 checkstyle-5.6/contrib/examples/ 40755 0 0 0 11451011230 14016 5ustar 0 0 checkstyle-5.6/contrib/examples/checks/ 40755 0 0 0 11521516632 15274 5ustar 0 0 checkstyle-5.6/contrib/examples/checks/com/ 40755 0 0 0 11451011230 16034 5ustar 0 0 checkstyle-5.6/contrib/examples/checks/com/mycompany/ 40755 0 0 0 11451011230 20050 5ustar 0 0 checkstyle-5.6/contrib/examples/checks/com/mycompany/checks/ 40755 0 0 0 11451071612 21322 5ustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/ 40755 0 0 0 11451011230 20242 5ustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/ 40755 0 0 0 11451011230 21402 5ustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/ 40755 0 0 0 11451011230 23540 5ustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/ 40755 0 0 0 11451011230 25000 5ustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/ 40755 0 0 0 11451071612 26136 5ustar 0 0 checkstyle-5.6/contrib/examples/conf/ 40755 0 0 0 11451071612 14755 5ustar 0 0 checkstyle-5.6/contrib/examples/filters/ 40755 0 0 0 11451011230 15466 5ustar 0 0 checkstyle-5.6/contrib/examples/filters/com/ 40755 0 0 0 11451011230 16244 5ustar 0 0 checkstyle-5.6/contrib/examples/filters/com/mycompany/ 40755 0 0 0 11451011230 20260 5ustar 0 0 checkstyle-5.6/contrib/examples/filters/com/mycompany/filters/ 40755 0 0 0 11451071612 21742 5ustar 0 0 checkstyle-5.6/contrib/examples/linkErrors2Source/ 40755 0 0 0 11451071612 17425 5ustar 0 0 checkstyle-5.6/contrib/examples/listeners/ 40755 0 0 0 11451011230 16026 5ustar 0 0 checkstyle-5.6/contrib/examples/listeners/com/ 40755 0 0 0 11451011230 16604 5ustar 0 0 checkstyle-5.6/contrib/examples/listeners/com/mycompany/ 40755 0 0 0 11451011230 20620 5ustar 0 0 checkstyle-5.6/contrib/examples/listeners/com/mycompany/listeners/ 40755 0 0 0 11451071612 22642 5ustar 0 0 checkstyle-5.6/contrib/examples/XInclude/ 40755 0 0 0 11451071612 15543 5ustar 0 0 checkstyle-5.6/contrib/hooks/ 40755 0 0 0 11451071612 13335 5ustar 0 0 checkstyle-5.6/contrib/usage/ 40755 0 0 0 11451011230 13304 5ustar 0 0 checkstyle-5.6/contrib/usage/src/ 40755 0 0 0 11451011231 14074 5ustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/ 40755 0 0 0 11451011230 16231 5ustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/ 40755 0 0 0 11451011230 17007 5ustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/ 40755 0 0 0 11451011230 21215 5ustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/ 40755 0 0 0 11451011230 22355 5ustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/ 40755 0 0 0 11451011230 24513 5ustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ 40755 0 0 0 11451011230 25753 5ustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/ 40755 0 0 0 11451071612 27071 5ustar 0 0 ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif 40755 0 0 0 11451071612 31345 5ustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/ 40755 0 0 0 11451011231 16316 5ustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/ 40755 0 0 0 11451011231 17074 5ustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/ 40755 0 0 0 11451011231 21302 5ustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/ 40755 0 0 0 11451011231 22442 5ustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/ 40755 0 0 0 11451011231 24600 5ustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/ 40755 0 0 0 11451071612 25715 5ustar 0 0 checkstyle-5.6/contrib/usage/src/tests/ 40755 0 0 0 11451011231 15236 5ustar 0 0 checkstyle-5.6/contrib/usage/src/tests/com/ 40755 0 0 0 11451011231 16014 5ustar 0 0 checkstyle-5.6/contrib/usage/src/tests/com/puppycrawl/ 40755 0 0 0 11451011231 20222 5ustar 0 0 checkstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/ 40755 0 0 0 11451011231 21362 5ustar 0 0 checkstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/ 40755 0 0 0 11451011231 23520 5ustar 0 0 checkstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/ 40755 0 0 0 11451011231 24760 5ustar 0 0 checkstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/ 40755 0 0 0 11451071612 26075 5ustar 0 0 checkstyle-5.6/contrib/usage/src/xdocs/ 40755 0 0 0 11451071612 15225 5ustar 0 0 checkstyle-5.6/src/ 40755 0 0 0 11451011233 11332 5ustar 0 0 checkstyle-5.6/src/checkstyle/ 40755 0 0 0 11451071612 13477 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/ 40755 0 0 0 11451011231 14244 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/ 40755 0 0 0 11451011231 16452 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/ 40755 0 0 0 11451011231 17612 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/ 40755 0 0 0 12026051077 21763 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/ 40755 0 0 0 12026051074 22531 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ 40755 0 0 0 12026051065 23220 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/ 40755 0 0 0 12026051060 25365 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/ 40755 0 0 0 12026051056 24475 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/ 40755 0 0 0 12026051054 24461 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/ 40755 0 0 0 12026051042 24464 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/ 40755 0 0 0 12026051040 25346 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/ 40755 0 0 0 12026051040 24441 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/ 40755 0 0 0 12026051037 24714 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ 40755 0 0 0 12026051034 25530 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/ 40755 0 0 0 12026051025 24623 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/ 40755 0 0 0 12026051022 24657 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/ 40755 0 0 0 12026051020 25005 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/ 40755 0 0 0 12026051017 24466 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/ 40755 0 0 0 12026051013 24503 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/ 40755 0 0 0 12026051011 24344 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/ 40755 0 0 0 12026051007 25350 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/doclets/ 40755 0 0 0 12026051004 23406 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/ 40755 0 0 0 12026051003 23420 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/grammars/ 40755 0 0 0 12026051001 23557 5ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/ 40755 0 0 0 11744233656 22562 5ustar 0 0 checkstyle-5.6/src/site/ 40755 0 0 0 11451071613 12306 5ustar 0 0 checkstyle-5.6/src/site/resources/ 40755 0 0 0 11451011232 14307 5ustar 0 0 checkstyle-5.6/src/site/resources/css/ 40755 0 0 0 11451071613 15110 5ustar 0 0 checkstyle-5.6/src/site/resources/images/ 40755 0 0 0 11451071613 15565 5ustar 0 0 checkstyle-5.6/src/testinputs/ 40755 0 0 0 11631376755 13603 5ustar 0 0 checkstyle-5.6/src/testinputs/com/ 40755 0 0 0 11451011232 14331 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/ 40755 0 0 0 11451011232 16537 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/ 40755 0 0 0 11451011232 17677 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/ 40755 0 0 0 11743001664 22051 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/ 40755 0 0 0 11451071614 24221 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/ 40755 0 0 0 11714704773 23325 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/ 40755 0 0 0 11451071614 23477 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/subdir/ 40755 0 0 0 11451071614 24767 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/ 40755 0 0 0 11453312066 23321 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/duplicates/ 40755 0 0 0 11451071614 24204 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/filters/ 40755 0 0 0 11451071614 23517 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/ 40755 0 0 0 12022111053 23643 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/header/ 40755 0 0 0 11451071614 23277 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/ 40755 0 0 0 11631376755 23562 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/ 40755 0 0 0 11650712756 24375 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/ 40755 0 0 0 11451071614 23456 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/bothfiles/ 40755 0 0 0 11451071614 25435 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkghtml/ 40755 0 0 0 11451071614 25124 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/ 40755 0 0 0 11451011232 25101 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/annotation/ 40755 0 0 0 11451071614 27265 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/invalidformat/ 40755 0 0 0 11451071614 27752 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/invalidinherit/ 40755 0 0 0 11451071614 30124 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/valid/ 40755 0 0 0 11451071614 26212 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/metrics/ 40755 0 0 0 11451071614 23515 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/naming/ 40755 0 0 0 11452563037 23326 5ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/whitespace/ 40755 0 0 0 11652651451 24211 5ustar 0 0 checkstyle-5.6/src/testinputs/resources/ 40755 0 0 0 11631376755 15615 5ustar 0 0 checkstyle-5.6/src/testinputs/resources/checkstyle/ 40755 0 0 0 11631376755 17753 5ustar 0 0 checkstyle-5.6/src/tests/ 40755 0 0 0 11451011233 12474 5ustar 0 0 checkstyle-5.6/src/tests/com/ 40755 0 0 0 11451011233 13252 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/ 40755 0 0 0 11451011233 15460 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/ 40755 0 0 0 11451011233 16620 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/ 40755 0 0 0 12026051000 20751 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/api/ 40755 0 0 0 12026050776 21545 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/ 40755 0 0 0 12026050775 22233 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/annotation/ 40755 0 0 0 12026050772 24402 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/blocks/ 40755 0 0 0 12026050771 23504 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/ 40755 0 0 0 12026050767 23477 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/ 40755 0 0 0 12026050755 23502 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/duplicates/ 40755 0 0 0 12026050754 24365 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/header/ 40755 0 0 0 12026050753 23457 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/ 40755 0 0 0 12026050753 23724 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/indentation/ 40755 0 0 0 12026050751 24541 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/ 40755 0 0 0 12026050750 23633 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/ 40755 0 0 0 12026050746 23677 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/modifier/ 40755 0 0 0 12026050745 24026 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/ 40755 0 0 0 12026050745 23501 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/regexp/ 40755 0 0 0 12026050743 23520 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/ 40755 0 0 0 12026050742 23362 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/ 40755 0 0 0 12026050737 24365 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/filters/ 40755 0 0 0 12026050734 22436 5ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/ 40755 0 0 0 12026050732 22575 5ustar 0 0 checkstyle-5.6/src/xdocs/ 40755 0 0 0 12022116557 12464 5ustar 0 0 checkstyle-5.6/.classpath100644 0 0 1467 11714710107 12643 0ustar 0 0 checkstyle-5.6/.hgeol100644 0 0 31 11470731704 11706 0ustar 0 0 [patterns] ** = native checkstyle-5.6/.hgignore100644 0 0 175 11511035417 12435 0ustar 0 0 syntax: glob .classpath .project .settings nbactions.xml nb-configuration.xml target glob:checkstyle.iml glob:.idea checkstyle-5.6/.hgtags100644 0 0 2720 12026054767 12141 0ustar 0 0 006ff800839cf442704c3b77d4299a5bf40c67a5 release1_2 034140fd6e3ccbce4a70f7b667b53d4c45b7876e release3_0 10c7d3c518949660072be2683719965ed8ef6a7a release4_0_beta_1 2535a640df78b36dd58e9a3733763928876f4598 release3_1 25726e116a0f3b2c28ff715e7454e30e0319095f release4_0_beta_4 2781981c78f8c6e3fcde25c7ef5afe5811bec78d release3_3 2e6deb49a15a4dff738aa43bbb5f78966a954c71 release1_3 33ce118ab2f3fd14de3b386a3299047e3e551cb1 release4_1 57062c0a6937c796dc1ae6f71e102ebd9f921182 release2_2 5b0e90e724872d5a81439cee5a00de8355e34004 v2-branch_lmp 5df66b7d0444ad09e7caeeb47fb4261a2faa24dd release4_2 6c0177d9f9860b48b246bed8b4b6069414995d41 release4_3 74be2c68f3ad94ef1b5eade56f643bced7cb75cb release4_0 7e5e82c8f3f073458797d7e353254c6c58a8b8df release2_0 881389454b55dedbba47eaf79c7f61586c0c39a6 release4_0_beta_3 88c4db001e1f737e4a0f288353ba48c1f5e2f0a9 release2_4 932f11b0f95d3b62ca7eeb0235131c5fdccc1312 release3_4 94e960aacb57e59df84118174da97473d1b0403f release4_0_beta_5 b076368dc89377846026b9a60ba216cfcae8844e release3_2 bb57c07ad4716ebee23e4f1311a8e6f9dccd414c release1_1 d3c0f8c8ab32e42c6eb13f46a67df924a60a210e bcel d703222b2db617100b334be34b8aec8e20f5ddaa release4_0_beta_2 f04dc97e5ed5abc8ffacf4d72976079db1d06d1b release3_5 f7a7cda05a98c60faeb06a5305710fa5b3cabccc release4_4 fe3d101a0af918374db7b03038698eee72bbc536 release1_4 1b7a252d5e1ed908e2dbac4db0ea6256b6e04575 release5_3 c3d24c009c007ecedfeee4038b7cb80b75a1d6d3 release5_4 055e288619a543833c465e00ef01d77ff6331e1f release5_5 checkstyle-5.6/.idea/.name100644 0 0 12 11511026736 12505 0ustar 0 0 checkstylecheckstyle-5.6/.idea/ant.xml100644 0 0 252 11511027746 13120 0ustar 0 0 checkstyle-5.6/.idea/compiler.xml100644 0 0 1426 11511027065 14166 0ustar 0 0 checkstyle-5.6/.idea/copyright/profiles_settings.xml100644 0 0 163 11511026736 20110 0ustar 0 0 checkstyle-5.6/.idea/encodings.xml100644 0 0 253 11511026736 14306 0ustar 0 0 checkstyle-5.6/.idea/libraries/Maven__antlr_antlr_2_7_7.xml100644 0 0 716 11511027065 21013 0ustar 0 0 checkstyle-5.6/.idea/libraries/Maven__commons_beanutils_commons_beanutils_core_1_8_3.xml100644 0 0 1165 11511027065 27040 0ustar 0 0 checkstyle-5.6/.idea/libraries/Maven__commons_cli_commons_cli_1_2.xml100644 0 0 1002 11511027065 23130 0ustar 0 0 checkstyle-5.6/.idea/libraries/Maven__commons_logging_commons_logging_1_1_1.xml100644 0 0 1074 11511027065 25116 0ustar 0 0 checkstyle-5.6/.idea/libraries/Maven__com_google_collections_google_collections_1_0.xml100644 0 0 1137 11511027065 26715 0ustar 0 0 checkstyle-5.6/.idea/libraries/Maven__com_sun_tools_1_5_0.xml100644 0 0 371 11511027065 21341 0ustar 0 0 checkstyle-5.6/.idea/libraries/Maven__junit_junit_4_8_1.xml100644 0 0 716 11511027065 21032 0ustar 0 0 checkstyle-5.6/.idea/libraries/Maven__org_apache_ant_ant_1_7_0.xml100644 0 0 744 11511027065 22260 0ustar 0 0 checkstyle-5.6/.idea/libraries/Maven__org_apache_ant_ant_launcher_1_7_0.xml100644 0 0 1043 11511027065 24152 0ustar 0 0 checkstyle-5.6/.idea/misc.xml100644 0 0 3233 11511027422 13302 0ustar 0 0 http://www.w3.org/1999/xhtml checkstyle-5.6/.idea/modules.xml100644 0 0 417 11511027065 14003 0ustar 0 0 checkstyle-5.6/.idea/uiDesigner.xml100644 0 0 21327 11511026736 14500 0ustar 0 0 checkstyle-5.6/.idea/vcs.xml100644 0 0 264 11511027065 13126 0ustar 0 0 checkstyle-5.6/.idea/workspace.xml100644 0 0 72514 11511034155 14376 0ustar 0 0 localhost 5050 1294216670888 1294216670888 checkstyle-5.6/.project100644 0 0 1062 11714707742 12331 0ustar 0 0 checkstyle org.eclipse.jdt.core.javabuilder org.eclipse.m2e.core.maven2Builder org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature checkstyle-5.6/.settings/org.eclipse.core.resources.prefs100644 0 0 321 11714707712 20765 0ustar 0 0 #Thu Feb 09 20:20:10 EST 2012 eclipse.preferences.version=1 encoding//src/checkstyle=iso-8859-1 encoding//src/testinputs/resources=iso-8859-1 encoding//src/tests=iso-8859-1 encoding/=iso-8859-1 checkstyle-5.6/.settings/org.eclipse.jdt.core.prefs100644 0 0 422 11451072360 17526 0ustar 0 0 #Thu Sep 30 21:30:56 EST 2010 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.source=1.5 checkstyle-5.6/.settings/org.eclipse.m2e.core.prefs100644 0 0 171 11714707705 17443 0ustar 0 0 #Thu Feb 09 20:20:05 EST 2012 activeProfiles= eclipse.preferences.version=1 resolveWorkspaceProjects=true version=1 checkstyle-5.6/.settings/org.maven.ide.eclipse.prefs100644 0 0 417 11451072357 17676 0ustar 0 0 #Thu Sep 30 21:30:55 EST 2010 activeProfiles= eclipse.preferences.version=1 fullBuildGoals=process-test-resources includeModules=false resolveWorkspaceProjects=true resourceFilterGoals=process-resources resources\:testResources skipCompilerPlugin=true version=1 checkstyle-5.6/ant-phase-compile.xml100644 0 0 2204 11451071611 14674 0ustar 0 0 checkstyle-5.6/ant-phase-verify.xml100644 0 0 3112 11453016761 14556 0ustar 0 0 checkstyle-5.6/build.xml100644 0 0 17007 11631376752 12532 0ustar 0 0

CheckStyle Audit

Designed for use with CheckStyle and Ant.




Summary

Files Errors Warnings

Authors

Name Errors Warnings

File
Author

Error Description Line
Back to top substring-after($path, '\') ab checkstyle-5.6/contrib/checkstyle-csv.xsl100644 0 0 723 11451071612 15750 0ustar 0 0 , , , , , checkstyle-5.6/contrib/checkstyle-frames-errors.xsl100644 0 0 35315 11451071612 20011 0ustar 0 0 CheckStyle Audit <h2>Frame Alert</h2> <p> This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. </p>

CheckStyle Audit

Designed for use with CheckStyle and Ant.


.bannercell { border: 0px; padding: 0px; } body { margin-left: 10; margin-right: 10; font:normal 80% arial,helvetica,sanserif; background-color:#FFFFFF; color:#000000; } .a td { background: #efefef; } .b td { background: #fff; } th, td { text-align: left; vertical-align: top; } th { font-weight:bold; background: #ccc; color: black; } table, th, td { font-size:100%; border: none } table.log tr td, tr th { } h2 { font-weight:bold; font-size:140%; margin-bottom: 5; } h3 { font-size:100%; font-weight:bold; background: #525D76; color: white; text-decoration: none; padding: 5px; margin-right: 2px; margin-left: 2px; margin-bottom: 0; }

Files

Summary

Files

Name Errors
files/.html files/ .html ../ ../ stylesheet.css

File

Error Description Line

Summary

Files Files with Errors Errors
Check Number of Violations
a b
checkstyle-5.6/contrib/checkstyle-frames.xsl100644 0 0 34307 11451071612 16477 0ustar 0 0 CheckStyle Audit <h2>Frame Alert</h2> <p> This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. </p>

CheckStyle Audit

Designed for use with CheckStyle and Ant.


.bannercell { border: 0px; padding: 0px; } body { margin-left: 10; margin-right: 10; font:normal 80% arial,helvetica,sanserif; background-color:#FFFFFF; color:#000000; } .a td { background: #efefef; } .b td { background: #fff; } th, td { text-align: left; vertical-align: top; } th { font-weight:bold; background: #ccc; color: black; } table, th, td { font-size:100%; border: none } table.log tr td, tr th { } h2 { font-weight:bold; font-size:140%; margin-bottom: 5; } h3 { font-size:100%; font-weight:bold; background: #525D76; color: white; text-decoration: none; padding: 5px; margin-right: 2px; margin-left: 2px; margin-bottom: 0; }

Files

Summary

Files

Name Errors
files/.html files/.html ../ ../ stylesheet.css

File

Error Description Line

Summary

Files Errors
a b
checkstyle-5.6/contrib/checkstyle-noframes-severity-sorted.xsl100644 0 0 17256 11451071612 22206 0ustar 0 0

CheckStyle Audit

Designed for use with CheckStyle and Ant.




Files

Name Errors Warnings Infos

File

Severity Error Description Line
Back to top

Summary

Files Errors Warnings Infos
a b
checkstyle-5.6/contrib/checkstyle-noframes-sorted.xsl100644 0 0 13223 11451071612 20324 0ustar 0 0

CheckStyle Audit

Designed for use with CheckStyle and Ant.




Files

Name Errors

File

Error Description Line
Back to top

Summary

Files Errors
a b
checkstyle-5.6/contrib/checkstyle-noframes.xsl100644 0 0 12410 11451071612 17023 0ustar 0 0

CheckStyle Audit

Designed for use with CheckStyle and Ant.




Files

Name Errors

File

Error Description Line
Back to top

Summary

Files Errors
a b
checkstyle-5.6/contrib/checkstyle-simple.xsl100644 0 0 3550 11451071612 16467 0ustar 0 0 Sun Coding Style Violations

Coding Style Check Results

Summary
Total files checked
Files with errors
Total errors
Errors per file

The following are violations of the Sun Coding-Style Standards:

File:
Line Number Error Message

checkstyle-5.6/contrib/checkstyle-text.xsl100644 0 0 1762 11451071612 16165 0ustar 0 0 Coding Style Check Results -------------------------- Total files checked: Files with errors: Total errors: Errors per file: File: : - checkstyle-5.6/contrib/examples/checks/all-checkstyle-checks.xml100644 0 0 152504 11521515665 22331 0ustar 0 0 checkstyle-5.6/contrib/examples/checks/com/mycompany/checks/LimitImplementationFiles.java100644 0 0 3630 11451071612 27233 0ustar 0 0 package com.mycompany.checks; import java.io.File; import com.puppycrawl.tools.checkstyle.api.*; /** * An example for a user provided FileSetCheck, * checks that the number of files does not excced a certain limit. * * This Class is provided for educational purposes only, we do not * consider it useful to check your production code. * * @author lkuehne */ public class LimitImplementationFiles extends AbstractFileSetCheck { /** * the maximium number of implementation files, * default is 100. */ private int max = 100; /** * Give user a chance to configure max in the * config file. * * @param aMax the user specified maximum. */ public void setMax(int aMax) { max = aMax; } /** * @see FileSetCheck */ public void process(File[] files) { if (files != null && files.length > max) { // figure out the file that contains the error final String path = files[max].getPath(); // message collector is used to collect error messages, // needs to be reset before starting to collect error messages // for a file. getMessageCollector().reset(); // message dispatcher is used to fire AuditEvents MessageDispatcher dispatcher = getMessageDispatcher(); // signal start of file to AuditListeners dispatcher.fireFileStarted(path); // log the message log(0, "max.files.exceeded", new Integer(max)); // you can call log() multiple times to flag multiple // errors in the same file // fire the errors for this file to the AuditListeners fireErrors(path); // signal end of file to AuditListeners dispatcher.fireFileFinished(path); } } } checkstyle-5.6/contrib/examples/checks/com/mycompany/checks/messages.properties100644 0 0 201 11451071612 25315 0ustar 0 0 max.files.exceeded=Too many implementation files, only {0} are allowed too.many.methods=Too many methods, only {0} are allowed checkstyle-5.6/contrib/examples/checks/com/mycompany/checks/MethodLimitCheck.java100644 0 0 3450 11451071612 25441 0ustar 0 0 package com.mycompany.checks; import com.puppycrawl.tools.checkstyle.api.*; public class MethodLimitCheck extends Check { /** the maximum number of methods per class/interface */ private int max = 30; /** * Give user a chance to configure max in the config file. * @param aMax the user specified maximum parsed from configuration property. */ public void setMax(int aMax) { max = aMax; } /** * We are interested in CLASS_DEF and INTERFACE_DEF Tokens. * @see Check */ public int[] getDefaultTokens() { return new int[]{TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF}; } /** * @see Check */ public void visitToken(DetailAST ast) { // the tree below a CLASS_DEF/INTERFACE_DEF looks like this: // CLASS_DEF // MODIFIERS // class name (IDENT token type) // EXTENDS_CLAUSE // IMPLEMENTS_CLAUSE // OBJBLOCK // { // some other stuff like variable declarations etc. // METHOD_DEF // more stuff, the users might mix methods, variables, etc. // METHOD_DEF // ...and so on // } // We use helper methods to navigate in the syntax tree // find the OBJBLOCK node below the CLASS_DEF/INTERFACE_DEF DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK); // count the number of direct children of the OBJBLOCK // that are METHOD_DEFS int methodDefs = objBlock.getChildCount(TokenTypes.METHOD_DEF); // report error if limit is reached if (methodDefs > max) { log(ast.getLineNo(), "too.many.methods", new Integer(max)); } } } checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/Attribute.java100644 0 0 5616 11451071612 31051 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2003 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.xpath; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Data holder for an XPath attribute of an element. The parent * element of an Attribute is a DetailAST. The name and value * of an Attribute are Strings. * @author Rick Giles */ public class Attribute { /** element owning this attribute */ private DetailAST mParent; /** name */ private String mName; /** value */ private String mValue; /** * Constructs an Attribute. * @param aParent the parent element. * @param aName the name. * @param aValue the value. */ public Attribute(DetailAST aParent, String aName, String aValue) { mParent = aParent; mName = aName; mValue = aValue; } /** Returns the name of the attribute. * @return the name of the attribute. */ public String getName() { return mName; } /** * Returns the value of the attribute. * @return the value of the attribute. */ public String getValue() { return mValue; } /** * Sets the name of the attribute. * @param aName The name to set. */ public void setName(String aName) { mName = aName; } /** * Sets the value of the attribute. * @param aValue The value to set. */ public void setValue(String aValue) { mValue = aValue; } /** * Returns the parent of the attribute. * @return the parent of the attribute. */ public DetailAST getParent() { return mParent; } /** * Sets the parent of the attribute. * @param aParent the parent of the attribute. */ public void setParent(DetailAST aParent) { mParent = aParent; } } ././@LongLink100644 0 0 157 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/AttributeAxisIterator.javacheckstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/AttributeAxisIte100644 0 0 6515 11451071612 31417 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2003 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.xpath; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.beanutils.BeanUtils; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Iterator for an attribute axis of an XPath element. The XPath * element is a DetailAST. Attributes correspond to bean * properties of the DetailAST. * @author Rick Giles */ public class AttributeAxisIterator implements Iterator { /** actual iterator */ private Iterator mIter = (new ArrayList()).iterator(); /** * Constructs a AttributeAxisIterator for a * DetailAST element. * @param aAST the DetailAST element */ public AttributeAxisIterator(DetailAST aAST) { Map props = new HashMap(); //use BeanUtils to get the properties try { props = BeanUtils.describe(aAST); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } // add attributes for the properties to a list and // set the iterator to an iterator over that list. final List attributes = new ArrayList(props.size()); final Set values = props.keySet(); for (Iterator iter = values.iterator(); iter.hasNext();) { final String name = (String) iter.next(); final String value = (String) props.get(name); attributes.add(new Attribute(aAST, name, value)); } mIter = attributes.iterator(); } /**@see java.util.Iterator#next() */ public Object next() { return mIter.next(); } /** @see java.util.Iterator#hasNext() */ public boolean hasNext() { return mIter.hasNext(); } /** @see java.util.Iterator#remove() */ public void remove() { mIter.remove(); } }././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/DocumentNavigator.javacheckstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/DocumentNavigato100644 0 0 31111 11451071612 31442 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2003 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.xpath; import java.util.ArrayList; import java.util.Iterator; import org.jaxen.DefaultNavigator; import org.jaxen.XPath; import org.jaxen.util.SingleObjectIterator; import org.saxpath.SAXPathException; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Navigates around a DetailAST, using XPath semantics. * Requires jaxen, http://jaxen.sourceforge.net and * saxpath, http://sourceforge.net/projects/saxpath/. * Idea shamelessly stolen from the equivalent PMD code (pmd.sourceforge.net). * @author Rick Giles */ public class DocumentNavigator extends DefaultNavigator { /** Iterator for an empty sequence */ private static final Iterator EMPTY_ITERATOR = new ArrayList().iterator(); /** * @see org.jaxen.DefaultNavigator#getAttributeName(java.lang.Object) */ public String getAttributeName(Object aObject) { return ((Attribute) aObject).getName(); } /** * @see org.jaxen.DefaultNavigator#getAttributeNamespaceUri */ public String getAttributeNamespaceUri(Object aObject) { return null; } /** * @see org.jaxen.DefaultNavigator#getAttributeQName(java.lang.Object) */ public String getAttributeQName(Object aObject) { return ((Attribute) aObject).getName(); } /** * @see org.jaxen.DefaultNavigator#getAttributeStringValue(java.lang.Object) */ public String getAttributeStringValue(Object aObject) { return ((Attribute) aObject).getValue(); } /** * @see org.jaxen.DefaultNavigator#getCommentStringValue(java.lang.Object) */ public String getCommentStringValue(Object aObject) { return null; } /** * @see org.jaxen.DefaultNavigator#getElementName(java.lang.Object) */ public String getElementName(Object aObject) { final int type = ((DetailAST) aObject).getType(); return TokenTypes.getTokenName(type); } /** * @see org.jaxen.DefaultNavigator#getElementNamespaceUri(java.lang.Object) */ public String getElementNamespaceUri(Object aObject) { return null; } /** * @see org.jaxen.DefaultNavigator#getElementQName(java.lang.Object) */ public String getElementQName(Object aObject) { return getElementName(aObject); } /** * @see org.jaxen.DefaultNavigator#getElementStringValue(java.lang.Object) */ public String getElementStringValue(Object aObject) { return null; } /** * @see org.jaxen.DefaultNavigator#getNamespacePrefix(java.lang.Object) */ public String getNamespacePrefix(Object aObject) { return null; } /** * @see org.jaxen.DefaultNavigator#getNamespaceStringValue(java.lang.Object) */ public String getNamespaceStringValue(Object aObject) { return null; } /** * @see org.jaxen.DefaultNavigator#getTextStringValue(java.lang.Object) */ public String getTextStringValue(Object aObject) { return null; } /** * @see org.jaxen.DefaultNavigator#isAttribute(java.lang.Object) */ public boolean isAttribute(Object aObject) { return aObject instanceof Attribute; } /** * @see org.jaxen.DefaultNavigator#isComment(java.lang.Object) */ public boolean isComment(Object aObject) { return false; } /** * @see org.jaxen.DefaultNavigator#isDocument(java.lang.Object) */ public boolean isDocument(Object aObject) { if (aObject instanceof DetailAST) { final DetailAST node = (DetailAST) aObject; return (node.getType() == TokenTypes.EOF); } else { return false; } } /** * @see org.jaxen.DefaultNavigator#isElement(java.lang.Object) */ public boolean isElement(Object aObject) { return aObject instanceof DetailAST; } /** * @see org.jaxen.DefaultNavigator#isNamespace(java.lang.Object) */ public boolean isNamespace(Object aObject) { return false; } /** * @see org.jaxen.DefaultNavigator#isProcessingInstruction(java.lang.Object) */ public boolean isProcessingInstruction(Object aObject) { return false; } /** * @see org.jaxen.DefaultNavigator#isText(java.lang.Object) */ public boolean isText(Object aObject) { return false; } /** * @see org.jaxen.DefaultNavigator#parseXPath(java.lang.String) */ public XPath parseXPath(String aObject) throws SAXPathException { return null; } /** * @see org.jaxen.Navigator#getParentNode(java.lang.Object) */ public Object getParentNode(Object aObject) { if (aObject instanceof DetailAST) { return ((DetailAST) aObject).getParent(); } else { return ((Attribute) aObject).getParent(); } } /** * @see org.jaxen.Navigator#getAttributeAxisIterator(java.lang.Object) */ public Iterator getAttributeAxisIterator(Object aObject) { final DetailAST contextNode = (DetailAST) aObject; return new AttributeAxisIterator(contextNode); } /** * Get an iterator over all of this node's children. * * @param aObject The context node for the child axis. * @return A possibly-empty iterator (not null). */ public Iterator getChildAxisIterator(Object aObject) { return new NodeIterator((DetailAST) aObject) { /** @see NodeIterator */ protected DetailAST getFirstNode(DetailAST aAST) { return getFirstChild(aAST); } /** @see NodeIterator */ protected DetailAST getNextNode(DetailAST aAST) { return getNextSibling(aAST); } }; } /** * Get a (single-member) iterator over this node's parent. * * @param aObject the context node for the parent axis. * @return A possibly-empty iterator (not null). */ public Iterator getParentAxisIterator(Object aObject) { if (isAttribute(aObject)) { return new SingleObjectIterator(((Attribute) aObject).getParent()); } else { DetailAST parent = ((DetailAST) aObject).getParent(); if (parent != null) { return new SingleObjectIterator(parent); } else { return EMPTY_ITERATOR; } } } /** * Get an iterator over all following siblings. * * @param aObject the context node for the sibling iterator. * @return A possibly-empty iterator (not null). */ public Iterator getFollowingSiblingAxisIterator(Object aObject) { return new NodeIterator((DetailAST) aObject) { /** @see NodeIterator */ protected DetailAST getFirstNode(DetailAST aAST) { return getNextNode(aAST); } /** @see NodeIterator */ protected DetailAST getNextNode(DetailAST aAST) { return getNextSibling(aAST); } }; } /** * Get an iterator over all preceding siblings. * * @param aObject The context node for the preceding sibling axis. * @return A possibly-empty iterator (not null). */ public Iterator getPrecedingSiblingAxisIterator(Object aObject) { return new NodeIterator((DetailAST) aObject) { /** @see NodeIterator */ protected DetailAST getFirstNode(DetailAST aAST) { return getNextNode(aAST); } /** @see NodeIterator */ protected DetailAST getNextNode(DetailAST aAST) { return getPreviousSibling(aAST); } }; } /** * Get an iterator over all following nodes, depth-first. * * @param aObject The context node for the following axis. * @return A possibly-empty iterator (not null). */ public Iterator getFollowingAxisIterator(Object aObject) { return new NodeIterator((DetailAST) aObject) { /** @see NodeIterator */ protected DetailAST getFirstNode(DetailAST aAST) { if (aAST == null) { return null; } else { final DetailAST sibling = getNextSibling(aAST); if (sibling == null) { return getFirstNode(aAST.getParent()); } else { return sibling; } } } /** @see NodeIterator */ protected DetailAST getNextNode(DetailAST aAST) { if (aAST == null) { return null; } else { DetailAST n = getFirstChild(aAST); if (n == null) { n = getNextSibling(aAST); } if (n == null) { return getFirstNode(aAST.getParent()); } else { return n; } } } }; } /** * Get an iterator over all preceding nodes, depth-first. * * @param aObject The context node for the preceding axis. * @return A possibly-empty iterator (not null). */ public Iterator getPrecedingAxisIterator(Object aObject) { return new NodeIterator((DetailAST) aObject) { /** @see NodeIterator */ protected DetailAST getFirstNode(DetailAST aAST) { if (aAST == null) { return null; } else { final DetailAST sibling = getPreviousSibling(aAST); if (sibling == null) { return getFirstNode(aAST.getParent()); } else { return sibling; } } } /** @see NodeIterator */ protected DetailAST getNextNode(DetailAST aAST) { if (aAST == null) { return null; } else { DetailAST n = getLastChild(aAST); if (n == null) { n = getPreviousSibling(aAST); } if (n == null) { return getFirstNode(aAST.getParent()); } else { return n; } } } }; } /** @see org.jaxen.Navigator#getDocumentNode(java.lang.Object) */ public Object getDocumentNode(Object aObject) { if (isDocument(aObject)) { return aObject; } else { return getDocumentNode(getParentNode(aObject)); } } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/jaxen_LICENSE.txtcheckstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/jaxen_LICENSE.tx100644 0 0 5044 11451071612 31062 0ustar 0 0 /*-- $Id: jaxen_LICENSE.txt,v 1.1 2003-07-23 14:22:41 rickgiles Exp $ Copyright (C) 2000-2002 bob mcwhirter & James Strachan. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the disclaimer that follows these conditions in the documentation and/or other materials provided with the distribution. 3. The name "Jaxen" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact license@jaxen.org. 4. Products derived from this software may not be called "Jaxen", nor may "Jaxen" appear in their name, without prior written permission from the Jaxen Project Management (pm@jaxen.org). In addition, we request (but do not require) that you include in the end-user documentation provided with the redistribution and/or in the software itself an acknowledgement equivalent to the following: "This product includes software developed by the Jaxen Project (http://www.jaxen.org/)." Alternatively, the acknowledgment may be graphical using the logos available at http://www.jaxen.org/ THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE Jaxen AUTHORS OR THE PROJECT CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This software consists of voluntary contributions made by many individuals on behalf of the Jaxen Project and was originally created by bob mcwhirter and James Strachan . For more information on the Jaxen Project, please see . */ ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/messages.propertiescheckstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/messages.propert100644 0 0 423 11451071612 31436 0ustar 0 0 block.empty=Empty {0} block. hex.case.constant="Case constant ''{0}'' must not start with ''0x'' or ''0X''. needBraces=''{0}'' construct must use '''{}'''s. short.variable.name=Short variable name ''{0}''. string.conditional=String literal {0} must not be an operand. ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/NodeIterator.javacheckstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/NodeIterator.jav100644 0 0 7137 11451071612 31344 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2003 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.xpath; import java.util.Iterator; import java.util.NoSuchElementException; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Iterator for DetailAST nodes in a syntax tree. * @author Rick Giles */ public abstract class NodeIterator implements Iterator { /** The DetailAST for this iterator */ private DetailAST mNode; /** * Constructs a NodeIterator for a DetailAST. * @param aAST the DetailAST. */ public NodeIterator(DetailAST aAST) { this.mNode = getFirstNode(aAST); } /** @see java.util.Iterator#hasNext() */ public boolean hasNext() { return mNode != null; } /** @see java.util.Iterator#next() */ public Object next() { if (mNode == null) { throw new NoSuchElementException(); } final DetailAST ret = mNode; mNode = getNextNode(mNode); return ret; } /** @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } /** * Gets the first node of an iterator over a DetailAST. * @param aAST the DetailAST. * @return the first node of an iterator over aAST. */ protected abstract DetailAST getFirstNode(DetailAST aAST); /** * Gets the next node for an iterator over a DetailAST. * @param aAST the DetailAST. * @return the next node of aAST. */ protected abstract DetailAST getNextNode(DetailAST aAST); /** * Gets the previous sibling of a DetailAST. * @param aAST the DetailAST. * @return the previous sibling of aAST. */ protected DetailAST getPreviousSibling(DetailAST aAST) { return aAST.getPreviousSibling(); } /** * Get the next sibling of a DetailAST. * @param aAST the DetailAST. * @return the next sibling of aAST. */ protected DetailAST getNextSibling(DetailAST aAST) { return (DetailAST) aAST.getNextSibling(); } /** * Get the first child of a DetailAST. * @param aAST the DetailAST. * @return the first child of aAST. */ protected DetailAST getFirstChild(DetailAST aAST) { return (DetailAST) aAST.getFirstChild(); } /** * Get the last child of a DetailAST. * @param aAST the DetailAST. * @return the last child of aAST. */ protected DetailAST getLastChild(DetailAST aAST) { return aAST.getLastChild(); } }checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/package.html100644 0 0 246 11451071612 30476 0ustar 0 0

Contains a Check for XPath semantics in a syntac tree.

././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/saxpath_LICENSE.txtcheckstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/saxpath_LICENSE.100644 0 0 6033 11451071612 31050 0ustar 0 0 /* * $Header: /opt/shared/tmp/checkstyle-cvsbackup/checkstyle/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/saxpath_LICENSE.txt,v 1.1 2003-07-23 14:22:41 rickgiles Exp $ * $Revision: 1.1 $ * $Date: 2003-07-23 14:22:41 $ * * ==================================================================== * * Copyright (C) 2000-2002 werken digital. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions, and the disclaimer that follows * these conditions in the documentation and/or other materials * provided with the distribution. * * 3. The name "SAXPath" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact license@saxpath.org. * * 4. Products derived from this software may not be called "SAXPath", nor * may "SAXPath" appear in their name, without prior written permission * from the SAXPath Project Management (pm@saxpath.org). * * In addition, we request (but do not require) that you include in the * end-user documentation provided with the redistribution and/or in the * software itself an acknowledgement equivalent to the following: * "This product includes software developed by the * SAXPath Project (http://www.saxpath.org/)." * Alternatively, the acknowledgment may be graphical using the logos * available at http://www.saxpath.org/ * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE SAXPath AUTHORS OR THE PROJECT * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * ==================================================================== * This software consists of voluntary contributions made by many * individuals on behalf of the SAXPath Project and was originally * created by bob mcwhirter and * James Strachan . For more information on the * SAXPath Project, please see . * * $Id: saxpath_LICENSE.txt,v 1.1 2003-07-23 14:22:41 rickgiles Exp $ */ checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/XPathCheck.java100644 0 0 7173 11451071612 31070 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2003 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.xpath; import java.util.Iterator; import org.jaxen.BaseXPath; import org.jaxen.JaxenException; import org.jaxen.XPath; import antlr.ASTFactory; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Checks for an XPath in the root AST. Path elements are named * according to token types. Attributes of an element are bean * properties. * Requires jaxen, http://jaxen.sourceforge.net and * saxpath, http://sourceforge.net/projects/saxpath/. * Idea shamelessly stolen from the equivalent PMD rule (pmd.sourceforge.net). * @author Rick Giles */ public class XPathCheck extends Check { /** XPath for this check */ private XPath mXPath; /** error message */ private String mMessage = "illegal.xpath"; /** @see com.puppycrawl.tools.checkstyle.api.Check#getDefaultTokens() */ public int[] getDefaultTokens() { return new int[0]; } /** @see com.puppycrawl.tools.checkstyle.api.Check */ public void beginTree(DetailAST aAST) { if (mXPath != null) { final ASTFactory factory = new ASTFactory(); factory.setASTNodeType(DetailAST.class.getName()); // TODO: Need to resolve if need a fake root node.... final DetailAST root = (DetailAST) factory.create(TokenTypes.EOF, "ROOT"); root.setFirstChild(aAST); try { final Iterator it = mXPath.selectNodes(aAST).iterator(); while (it.hasNext()) { final DetailAST node = (DetailAST) it.next(); log( node.getLineNo(), node.getColumnNo(), mMessage, new String[] {node.getText()}); } } catch (JaxenException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * Sets the error message for this check. * @param aMessage error message for this check. */ public void setMessage(String aMessage) { mMessage = aMessage; } /** * Sets the XPath for this check. * @param aXPath the XPath for this check. * @throws JaxenException if there is an error. */ public void setXPath(String aXPath) throws JaxenException { mXPath = new BaseXPath(aXPath, new DocumentNavigator()); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/xpath_config.xmlcheckstyle-5.6/contrib/examples/checks/com/puppycrawl/tools/checkstyle/checks/xpath/xpath_config.xml100644 0 0 3466 11451071612 31437 0ustar 0 0 checkstyle-5.6/contrib/examples/checks/mycompany_conf.xml100644 0 0 2253 11451071612 21132 0ustar 0 0 checkstyle-5.6/contrib/examples/conf/BlochEffectiveJava.xml100644 0 0 7714 11451071612 21257 0ustar 0 0 checkstyle-5.6/contrib/examples/conf/openorb.xml100644 0 0 12555 11451071612 17270 0ustar 0 0 checkstyle-5.6/contrib/examples/conf/template_config.xml100644 0 0 110215 11451071612 20774 0ustar 0 0 checkstyle-5.6/contrib/examples/filters/com/mycompany/filters/FilesFilter.java100644 0 0 1563 11451071612 25117 0ustar 0 0 package com.mycompany.filters; import org.apache.regexp.RE; import org.apache.regexp.RESyntaxException; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.Filter; import com.puppycrawl.tools.checkstyle.api.Utils; public class FilesFilter extends AutomaticBean implements Filter { private RE mFileRegexp; public FilesFilter() throws RESyntaxException { setFiles("^$"); } public boolean accept(AuditEvent aEvent) { final String fileName = aEvent.getFileName(); return ((fileName == null) || !mFileRegexp.match(fileName)); } public void setFiles(String aFilesPattern) throws RESyntaxException { mFileRegexp = Utils.getRE(aFilesPattern); } } checkstyle-5.6/contrib/examples/linkErrors2Source/build.xml100644 0 0 5275 11451071612 21354 0ustar 0 0 checkstyle-5.6/contrib/examples/linkErrors2Source/checkstyle-noframes.xsl100644 0 0 15125 11451071612 24244 0ustar 0 0

CheckStyle Audit

Designed for use with CheckStyle and Ant.




Files

Name Errors

File

Error Description Line
/.html#
Back to top

Summary

Files Errors
a b
checkstyle-5.6/contrib/examples/linkErrors2Source/readme.txt100644 0 0 441 11451071612 21477 0ustar 0 0 Example of an ant build file and stylesheet for generation of an HTML error report with links to source code, as discussed on sourceforge.net: checkstyle-user, http://sourceforge.net/mailarchive/forum.php?thread_id=4891991&forum_id=8139. Requires: java2html, http://www.java2html.de/checkstyle-5.6/contrib/examples/listeners/com/mycompany/listeners/CommonsLoggingListener.java100644 0 0 11016 11451071612 30251 0ustar 0 0 package com.mycompany.listeners; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogConfigurationException; import org.apache.commons.logging.LogFactory; import com.puppycrawl.tools.checkstyle.Checker; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AuditListener; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; /** * Jakarta Commons Logging listener. * Note: With Ant, do not use the SimpleLog as your logger implementation as it * causes an infinite loop since it writes to System.err, which Ant traps * and reroutes to the logger/listener layer. * Based on * org.apache.tools.ant.listener.CommonsLoggingListener>org.apache.tools.ant.listener.CommonsLoggingListener * @author Rick Giles */ public class CommonsLoggingListener implements AuditListener { /** cushion for avoiding StringBuffer.expandCapacity */ private static final int BUFFER_CUSHION = 30; /** true if the log factory has been initialized */ private boolean mInitialized = false; /** Factory for creating org.apache.commons.logging.Log instances */ private LogFactory mLogFactory; /** * Creates a CommonsLoggingListener. Initializes its log factory. * @throws CheckstyleException if if the implementation class is not * available or cannot be instantiated. */ public CommonsLoggingListener() throws CheckstyleException { try { mLogFactory = LogFactory.getFactory(); } catch (LogConfigurationException e) { throw new CheckstyleException("log configuration exception", e); } mInitialized = true; } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void auditStarted(AuditEvent aEvt) { if (mInitialized) { final Log log = mLogFactory.getInstance(Checker.class); log.info("Audit started."); } } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void auditFinished(AuditEvent aEvt) { if (mInitialized) { final Log log = mLogFactory.getInstance(Checker.class); log.info("Audit finished."); } } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void fileStarted(AuditEvent aEvt) { if (mInitialized) { final Log log = mLogFactory.getInstance(Checker.class); log.info("File \"" + aEvt.getFileName() + "\" started."); } } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void fileFinished(AuditEvent aEvt) { if (mInitialized) { final Log log = mLogFactory.getInstance(Checker.class); log.info("File \"" + aEvt.getFileName() + "\" finished."); } } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void addError(AuditEvent aEvt) { final SeverityLevel severityLevel = aEvt.getSeverityLevel(); if (mInitialized && !SeverityLevel.IGNORE.equals(severityLevel)) { final Log log = mLogFactory.getInstance(aEvt.getSourceName()); final String fileName = aEvt.getFileName(); final String message = aEvt.getMessage(); // avoid StringBuffer.expandCapacity final int bufLen = message.length() + BUFFER_CUSHION; final StringBuffer sb = new StringBuffer(bufLen); sb.append("Line: ").append(aEvt.getLine()); if (aEvt.getColumn() > 0) { sb.append(" Column: ").append(aEvt.getColumn()); } sb.append(" Message: ").append(message); if (aEvt.getSeverityLevel().equals(SeverityLevel.WARNING)) { log.warn(sb.toString()); } else if (aEvt.getSeverityLevel().equals(SeverityLevel.INFO)) { log.info(sb.toString()); } else { log.error(sb.toString()); } } } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void addException(AuditEvent aEvt, Throwable aThrowable) { if (mInitialized) { final Log log = mLogFactory.getInstance(aEvt.getSourceName()); log.error("Error auditing " + aEvt.getFileName(), aThrowable); } } } checkstyle-5.6/contrib/examples/listeners/com/mycompany/listeners/MailLogger.java100644 0 0 20344 11451071612 25647 0ustar 0 0 package com.mycompany.listeners; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Properties; import java.util.StringTokenizer; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.puppycrawl.tools.checkstyle.DefaultLogger; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AuditListener; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; /** * Buffers log messages from DefaultLogger, and sends an e-mail with the * results. The following Project properties are used to send the mail. *
    *
  • MailLogger.mailhost [default: localhost] - Mail server to use
  • * *
  • MailLogger.from [required] - Mail "from" address
  • *
  • MailLlistener.failure.notify [default: true] - Send build failure * e-mails?
  • *
  • MailLogger.success.notify [default: true] - Send build success * e-mails?
  • *
  • MailLogger.failure.to [required if failure mail to be sent] - Address * to send failure messages to
  • *
  • MailLogger.success.to [required if success mail to be sent] - Address * to send success messages to
  • *
  • MailLogger.failure.subject [default: "Build Failure"] - Subject of * failed build
  • *
  • MailLlistener.success.subject [default: "Build Success"] - Subject of * successful build
  • *
* These properties are set using standard property setting mechanisms * (command-line -D, ant <property>, etc).Properties can be overridden * by specifying the filename of a properties file in the * MailLogger.properties.file property . Any properties defined in that * file will override properties. * Based on * org.apache.tools.ant.listener.MailLogger>org.apache.tools.ant.listener.MailLogger * @author Erik Hatcher * ehatcher@apache.org * @author Rick Giles */ public class MailLogger implements AuditListener { /** output stream for logger */ private ByteArrayOutputStream mOutputStream; /** adapted listener */ private DefaultLogger mLogger; /** count of the number of errors and exceptions */ private int mErrors; /** * Constructs a MailLogger */ public MailLogger() { mOutputStream = new ByteArrayOutputStream(); mLogger = new DefaultLogger(mOutputStream, false); mErrors = 0; } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void auditStarted(AuditEvent aEvt) { mLogger.auditStarted(aEvt); } /** * Sends an e-mail with the log results. * @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void auditFinished(AuditEvent aEvt) { mLogger.auditFinished(aEvt); final Properties properties = System.getProperties(); // overlay specified properties file (if any), which overrides project // settings final Properties fileProperties = new Properties(); final String filename = (String) properties.get("MailLogger.properties.file"); if (filename != null) { InputStream is = null; try { is = new FileInputStream(filename); fileProperties.load(is); } catch (IOException ioe) { // ignore because properties file is not required ; } finally { if (is != null) { try { is.close(); } catch (IOException e) { ; } } } } for (Enumeration e = fileProperties.keys(); e.hasMoreElements();) { final String key = (String) e.nextElement(); final String value = fileProperties.getProperty(key); properties.put(key, value); } final boolean success = (mErrors == 0); final String prefix = success ? "success" : "failure"; try { final String mailhost = getValue(properties, "mailhost", "localhost"); final String from = getValue(properties, "from", null); final String toList = getValue(properties, prefix + ".to", null); final String subject = getValue(properties, prefix + ".subject", (success) ? "Checkstyle Audit Success" : "Checkstyle Audit Failure"); sendMail(mailhost, from, toList, subject, mOutputStream.toString()); } catch (Exception e) { System.out.println("MailLogger failed to send e-mail!"); e.printStackTrace(System.err); } } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void fileStarted(AuditEvent aEvt) { mLogger.fileStarted(aEvt); } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void fileFinished(AuditEvent aEvt) { mLogger.fileFinished(aEvt); } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void addError(AuditEvent aEvt) { if (SeverityLevel.ERROR.equals(aEvt.getSeverityLevel())) { mLogger.addError(aEvt); mErrors++; } } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void addException(AuditEvent aEvt, Throwable aThrowable) { mLogger.addException(aEvt, aThrowable); mErrors++; } /** * Gets the value of a property. * * @param aProperties Properties to obtain value from. * @param aName suffix of property name. "MailLogger." will be * prepended internally. * @param aDefaultValue value returned if not present in the properties. * Set to null to make required. * @return The value of the property, or default value. * @throws CheckstyleException if no default value is specified and the * property is not present in properties. */ private String getValue(Properties aProperties, String aName, String aDefaultValue) throws CheckstyleException { final String propertyName = "MailLogger." + aName; String value = (String) aProperties.get(propertyName); if (value == null) { value = aDefaultValue; } if (value == null) { throw new CheckstyleException( "Missing required parameter: " + propertyName); } return value; } /** * Send the mail * * @param aMailhost mail server * @param aFrom from address * @param aToList comma-separated recipient list * @param aSubject mail subject * @param aText mail body * @throws Exception if sending message fails */ private void sendMail(String aMailhost, String aFrom, String aToList, String aSubject, String aText) throws Exception { // Get system properties final Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", aMailhost); // Get session final Session session = Session.getDefaultInstance(props, null); // Define message final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(aFrom)); final StringTokenizer t = new StringTokenizer(aToList, ", ", false); while (t.hasMoreTokens()) { message.addRecipient( MimeMessage.RecipientType.TO, new InternetAddress(t.nextToken())); } message.setSubject(aSubject); message.setText(aText); Transport.send(message); } } checkstyle-5.6/contrib/examples/listeners/com/mycompany/listeners/VerboseListener.java100644 0 0 6537 11451071612 26730 0ustar 0 0 package com.mycompany.listeners; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AuditListener; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; /** * An AuditListener that reports every event to an output stream. * @author Rick Giles */ public class VerboseListener extends AutomaticBean implements AuditListener { /** where to write messages */ private PrintWriter mWriter = new PrintWriter(System.out); /** close output stream */ private boolean mCloseOut = false; /** total number of errors and exceptions */ private int mTotalErrors; /** number of errors and exceptions in the audit of one file */ private int mErrors; /** * Sets the output stream to a file. * @param aFileName name of the output file. * @throws FileNotFoundException if an error occurs. */ public void setFile(String aFileName) throws FileNotFoundException { final OutputStream out = new FileOutputStream(aFileName); mWriter = new PrintWriter(out); mCloseOut = true; } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void auditStarted(AuditEvent aEvt) { mTotalErrors = 0; mWriter.println("Audit started."); } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void auditFinished(AuditEvent aEvt) { mWriter.println("Audit finished. Total errors: " + mTotalErrors); mWriter.flush(); if (mCloseOut) { mWriter.close(); } } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void fileStarted(AuditEvent aEvt) { mErrors = 0; mWriter.println( "Started checking file '" + aEvt.getFileName() + "'."); } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void fileFinished(AuditEvent aEvt) { mWriter.println("Finished checking file '" + aEvt.getFileName() + "'. Errors: " + mErrors); } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void addError(AuditEvent aEvt) { printEvent(aEvt); if (SeverityLevel.ERROR.equals(aEvt.getSeverityLevel())) { mErrors++; mTotalErrors++; } } /** @see com.puppycrawl.tools.checkstyle.api.AuditListener */ public void addException(AuditEvent aEvt, Throwable aThrowable) { printEvent(aEvt); aThrowable.printStackTrace(System.out); mErrors++; mTotalErrors++; } /** * Prints event information to standard output. * @param aEvt the event to print. */ private void printEvent(AuditEvent aEvt) { mWriter.println("Logging error -" + " file: '" + aEvt.getFileName() + "'" + " line: " + aEvt.getLine() + " column: " + aEvt.getColumn() + " severity: " + aEvt.getSeverityLevel() + " message: " + aEvt.getMessage() + " source: " + aEvt.getSourceName()); } } checkstyle-5.6/contrib/examples/XInclude/config.xml100644 0 0 1145 11451071612 17630 0ustar 0 0 ]> checkstyle-5.6/contrib/examples/XInclude/index.html100644 0 0 13157 11451071612 17664 0ustar 0 0 XInclude Processing

XInclude Processing

Description

This is an example of how you can separate a Checkstyle configuration file into several files and process the configuration using XInclude processing. This requires a SAX parser that supports XML namespaces. First we give an example a SAX parser factory that produces parsers supporting XML namespaces and indicate how to configure your system to use this factory. Then we give an example XML configuration files with XInclude processing and an ant target that uses the Checkstyle ant task to check a Java source file with the configuration files.

Parsers

SAX parser factory NamespacesSAXParserFactoryImpl is an example of a factory that produces parsers supporting XML namespaces:

package com.puppycrawl.tools.checkstyle;

import org.apache.xerces.jaxp.SAXParserFactoryImpl;

/**
 * A parser factory that produces parsers that support XML namespaces. 
 * @author Rick Giles
 * @version May 28, 2004
 */
public class NamespacesSAXParserFactoryImpl extends SAXParserFactoryImpl
{
    /**
     * Constructs a NamespacesSAXParserFactoryImpl. Initializes
     * it to produce parsers that support XML namespaces. 
     */
    public NamespacesSAXParserFactoryImpl()
    {
        super();
        setNamespaceAware(true);
    }
}

In order to use NamespacesSAXParserFactoryImpl as the SAX parser factory, place NamespacesSAXParserFactoryImpl in the classpath and configure your system to load NamespacesSAXParserFactoryImpl as the SAXParserFactory. For example, you can create a file called jaxp.properties in the lib subdirectory of the JRE installation with contents

javax.xml.parsers.SAXParserFactory=com.puppycrawl.tools.checkstyle.NamespacesSAXParserFactoryImpl

XInclude processing requires an XML parser that implements XML inclusions. Here we use the Xerces parser that is in the ant distribution. In order to enable Xinclude processing, you can change the parser configuration by creating a file called xerces.properties in the lib subdirectory of the JRE installation with contents

org.apache.xerces.xni.parser.XMLParserConfiguration=org.apache.xerces.parsers.XIncludeParserConfiguration

Checkstyle Configuration

The Checkstyle configuration of this example is in two files. File config.xml has an internal DTD that supports xi:include elements:

<?xml version="1.0"?>
<!DOCTYPE module [
<!ELEMENT module (module|property|xi:include)*>
<!ATTLIST module name NMTOKEN #REQUIRED>

<!ELEMENT xi:include EMPTY>
<!ATTLIST xi:include
    href CDATA #REQUIRED
    xmlns:xi CDATA #REQUIRED
>

<!ELEMENT property EMPTY>
<!ATTLIST property
    name NMTOKEN #REQUIRED
    value CDATA #REQUIRED
    default CDATA #IMPLIED
>
]>
<module name="Checker">
    <module name="TreeWalker">
        <xi:include
            href="treewalker.xml"
            xmlns:xi="http://www.w3.org/2003/XInclude"/>
    </module>
</module>

The configuration in config.xml includes a second configuration file, treewalker.xml, that applies the TypeName module:

<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
    "-//Puppy Crawl//DTD Check Configuration 1.2//EN"
    "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
<module name="TypeName">
    <property name="format" value="${typename.format}"/>
</module>

Notice that the configuration of treewalker.xml applies property ${typename.format}. That propery is set in the following segment of an ant build file that uses the Checkstyle ant task to check file InputHeader.java with the configuration of config.xml:

    <taskdef
        resource="checkstyletask.properties"
        classpath="/path/to/checkstyle-all-@CHECKSTYLE_VERSION@.jar" />
    <target name="checkstyle" description="run checkstyle">
        <checkstyle file="InputHeader.java" config="config.xml">
            <property key="typename.format" value="xyz" />
        </checkstyle>
    </target>

checkstyle-5.6/contrib/examples/XInclude/NamespacesSAXParserFactoryImpl.java100644 0 0 1065 11451071612 24467 0ustar 0 0 package com.puppycrawl.tools.checkstyle; import org.apache.xerces.jaxp.SAXParserFactoryImpl; /** * A parser factory that produces parsers that support XML namespaces. * @author Rick Giles * @version May 28, 2004 */ public class NamespacesSAXParserFactoryImpl extends SAXParserFactoryImpl { /** * Constructs a NamespacesSAXParserFactoryImpl. Initializes * it to produce parsers that support XML namespaces. */ public NamespacesSAXParserFactoryImpl() { super(); setNamespaceAware(true); } } checkstyle-5.6/contrib/examples/XInclude/treewalker.xml100644 0 0 403 11451071612 20504 0ustar 0 0 checkstyle-5.6/contrib/hooks/git-pre-commit-hook.pl100644 0 0 3563 11451071612 17571 0ustar 0 0 #!/usr/bin/perl # # Pre-commit hook for running checkstyle on changed Java sources # # To use this you need: # 1. checkstyle's jar file somewhere # 2. a checkstyle XML check file somewhere # 3. To configure git: # * git config --add checkstyle.jar # * git config --add checkstyle.checkfile # * git config --add java.command [optional # defaults to assuming it's in your path] # 4. Put this in your .git/hooks directory as pre-commit # # Now, when you commit, you will be disallowed from doing so # until you pass your checkstyle checks. $command = "git-diff-index --cached HEAD 2>&1 | sed 's/^:.* //' | uniq"; open (FILES,$command . "|") || die "Cannot run '$command': $!\n"; $CONFIG_CHECK_FILE = "checkstyle.checkfile"; $CONFIG_JAR = "checkstyle.jar"; $CONFIG_JAVA = "java.command"; $check_file = `git config --get $CONFIG_CHECK_FILE`; $checkstyle_jar = `git config --get $CONFIG_JAR`; $java_command = `git config --get $CONFIG_JAVA`; if (!$check_file || !$checkstyle_jar) { die "You must configure checkstyle in your git config:\n" . "\t$CONFIG_CHECK_FILE - path to your checkstyle.xml file\n" . "\t$CONFIG_JAR - path to your checkstyle jar file\n" . "\t$CONFIG_JAVA - path to your java executable (optional)\n" ; } $java_command = "java" if (!$java_command); chomp $check_file; chomp $checkstyle_jar; chomp $java_command; $command = "$java_command -jar $checkstyle_jar -c $check_file"; @java_files = (); foreach () { chomp; next if (!(/\.java$/)); push @java_files,$_; $command .= " "; $command .= $_; } if ($#java_files >= 0) { if (&run_and_log_system ($command)) { print STDERR "Commit aborted.\n"; exit -1; } } exit 0; sub run_and_log_system { ($cmd) = @_; system $cmd; }checkstyle-5.6/contrib/JavadocCheckDefault.java100644 0 0 4103 11451071611 16761 0ustar 0 0 import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Tool that generates Javadoc description of the default tokens for a Check. * @author Rick Giles * @version 27-Nov-2002 */ public class JavadocCheckDefault { private static void usage() { System.out.println("Usage: java JavadocCheckDefault check element"); System.exit(0); } public static void main(String[] args) { if (args.length < 2) { usage(); } final String header = " *

By default the check will check the following " + args[1] + ":\n"; final String footer = ".\n *

\n"; final String prefix = " * {@link TokenTypes#"; try { final Class clazz = Class.forName(args[0]); final Check check = (Check) clazz.newInstance(); final int[] defaultTokens = check.getDefaultTokens(); if (defaultTokens.length > 0) { final StringBuffer buf = new StringBuffer(); buf.append(header); final ArrayList tokenNames = new ArrayList(); for (int i = 0; i < defaultTokens.length; i++) { tokenNames.add(TokenTypes.getTokenName(defaultTokens[i])); } Collections.sort(tokenNames); final Iterator it = tokenNames.iterator(); String token = (String) it.next(); buf.append(prefix + token + " " + token + "}"); while (it.hasNext()) { token = (String) it.next(); buf.append(",\n" + prefix + token + " " + token + "}"); } buf.append(footer); System.out.println(buf); } } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } } } ././@LongLink100644 0 0 161 12026055133 10246 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/AbstractUsageCheck.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/AbstractUsa100644 0 0 14675 11451071612 31362 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2005 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.usage; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.usage.transmogrify.ASTManager; import com.puppycrawl.tools.checkstyle.checks.usage.transmogrify.ClassManager; import com.puppycrawl.tools.checkstyle.checks.usage.transmogrify.Definition; import com.puppycrawl.tools.checkstyle.checks.usage.transmogrify.SymTabAST; import com.puppycrawl.tools.checkstyle.checks.usage.transmogrify. SymbolTableException; import java.util.Iterator; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; /** * Performs a usage check for fields, methods, parameters, variables. * @author Rick Giles */ public abstract class AbstractUsageCheck extends Check { /** the regexp to match against */ private Pattern mRegexp; /** the format string of the regexp */ private String mIgnoreFormat; /** * Constructs an AbstractUsageCheck. */ public AbstractUsageCheck() { setIgnoreFormat("^$"); } /** * Set the ignore format to the specified regular expression. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setIgnoreFormat(String aFormat) throws ConversionException { try { mRegexp = Utils.getPattern(aFormat); mIgnoreFormat = aFormat; } catch (PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } /** @return the regexp to match against */ public Pattern getRegexp() { return mRegexp; } /** @return the regexp format */ public String getIgnoreFormat() { return mIgnoreFormat; } /** @see com.puppycrawl.tools.checkstyle.api.Check */ public void beginTree(DetailAST aRootAST) { // use my class loader ClassManager.setClassLoader(getClassLoader()); final String fileName = getFileContents().getFilename(); getASTManager().addTree(fileName, aRootAST); } /** @see com.puppycrawl.tools.checkstyle.api.Check */ public void visitToken(DetailAST aAST) { if (mustCheckReferenceCount(aAST)) { final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT); Pattern regexp = getRegexp(); if ((regexp == null) || !regexp.matcher(nameAST.getText()).find()) { getASTManager().registerCheckNode(this, nameAST); } } } /** @see com.puppycrawl.tools.checkstyle.api.Check */ public void finishTree(DetailAST aAST) { if (aAST == null) { // we have nothing to check return; } try { final Set nodes = getASTManager().getCheckNodes(this); if (nodes != null) { applyTo(nodes); } } catch (SymbolTableException ste) { logError(ste); } getASTManager().removeCheck(this); } /** * Logs an exception. * @param aException the exception to log. */ public void logError(Exception aException) { log(0, "general.exception", new String[] {aException.getMessage()}); Utils.getExceptionLogger().debug("An exception occured.", aException); } /** * Determines the reference count for a DetailAST. * @param aAST the DetailAST to count. * @return the number of references to aAST. */ private int getReferenceCount(DetailAST aAST) { final SymTabAST ident = getASTManager().get(aAST); if (ident == null) { return 0; } final Definition definition = (Definition) ident.getDefinition(); if (definition != null) { return definition.getNumReferences(); } return 0; } /** * Returns the key for the Checkstyle error message. * @return the key for the Checkstyle error message. */ public abstract String getErrorKey(); /** * Determines whether the reference count of an aAST is required. * @param aAST the node to check. * @return true if the reference count of aAST is required. */ public abstract boolean mustCheckReferenceCount(DetailAST aAST); /** * Applies this check to a set of nodes. * @param aNodes the nodes to check. */ public void applyTo(Set aNodes) { final Iterator it = aNodes.iterator(); while (it.hasNext()) { final DetailAST nameAST = (DetailAST) it.next(); if (getReferenceCount(nameAST) == 1) { log( nameAST.getLineNo(), nameAST.getColumnNo(), getErrorKey(), nameAST.getText()); } } } /** * Gets the manager for AST nodes. * @return the AST manager. */ protected ASTManager getASTManager() { return ASTManager.getInstance(); } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/messages.propertiescheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/messages.pr100644 0 0 367 11451071612 31326 0ustar 0 0 one.method.private.field=Field ''{0}'' is used in only one method. unused.local=Unused local variable ''{0}''. unused.parameter=Unused parameter ''{0}''. unused.field=Unused private field ''{0}''. unused.method=Unused private method ''{0}''. ././@LongLink100644 0 0 160 12026055133 10245 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/messages_fi.propertiescheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/messages_fi100644 0 0 462 11451071612 31360 0ustar 0 0 one.method.private.field=Muuttujaa ''{0}'' k¤ytet¤¤n vain yhdess¤ metodissa. unused.local=K¤ytt¤m¤ton paikallinen muuttuja ''{0}''. unused.parameter=K¤ytt¤m¤tĥn parameteri ''{0}''. unused.field=K¤ytt¤m¤tĥn private muuttuja ''{0}''. unused.method=K¤ytt¤m¤tĥn private metodi ''{0}''. ././@LongLink100644 0 0 160 12026055133 10245 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/messages_fr.propertiescheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/messages_fr100644 0 0 435 11451071612 31371 0ustar 0 0 one.method.private.field=L''attribut privé ''{0}'' est utilisé dans une seule méthode. unused.local=Variable locale non utilisée ''{0}''. unused.parameter=Paramètre ''{0}'' inutilisé. unused.field=Attribut privé ''{0}'' inutilisé. unused.method=Méthode privée ''{0}'' inutilisée. ././@LongLink100644 0 0 171 12026055133 10247 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/OneMethodPrivateFieldCheck.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/OneMethodPr100644 0 0 12265 11451071612 31323 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2005 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.usage; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.Scope; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.usage.transmogrify.Definition; import com.puppycrawl.tools.checkstyle.checks.usage.transmogrify.Reference; import com.puppycrawl.tools.checkstyle.checks.usage.transmogrify.SymTabAST; /** *

Checks that a private field is used in more than one method, * constructor, or initializer. *

*

* Rationale: a private field used in only one method, constructor, or * initializer should be replaced by a local variable. *

*

* An example of how to configure the check is: *

*
 * <module name="usage.OneMethodPrivateField"/>
 * 
* * @author Rick Giles */ public class OneMethodPrivateFieldCheck extends AbstractUsageCheck { /** @see com.puppycrawl.tools.checkstyle.api.Check */ public int[] getDefaultTokens() { return new int[] { TokenTypes.VARIABLE_DEF, }; } /** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */ public String getErrorKey() { return "one.method.private.field"; } /** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */ public boolean mustCheckReferenceCount(DetailAST aAST) { final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS); return ((mods != null) && (ScopeUtils.getScopeFromMods(mods) == Scope.PRIVATE)); } /** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */ public void applyTo(Set aNodes) { // apply the check to each private field final Set methods = new HashSet(); final Iterator it = aNodes.iterator(); while (it.hasNext()) { methods.clear(); final DetailAST nameAST = (DetailAST) it.next(); // find methods using the field final Iterator refIt = getReferences(nameAST); while (refIt.hasNext()) { final Reference ref = (Reference) refIt.next(); final SymTabAST refNode = ref.getTreeNode(); final DetailAST refDetail = refNode.getDetailNode(); // don't need to check a self-reference if (refDetail == nameAST) { continue; } DetailAST parent = refDetail.getParent(); while (parent != null) { final int type = parent.getType(); if ((type == TokenTypes.METHOD_DEF) || (type == TokenTypes.CTOR_DEF) || (type == TokenTypes.INSTANCE_INIT) || (type == TokenTypes.STATIC_INIT)) { methods.add(parent); break; } // initializer for inner class? else if (type == TokenTypes.CLASS_DEF) { break; } parent = parent.getParent(); } } if (methods.size() == 1) { log( nameAST.getLineNo(), nameAST.getColumnNo(), getErrorKey(), nameAST.getText()); } } } /** * Returns the references to an AST. * @param aAST the AST for the references. * @return an iterator for the references to aAST. */ private Iterator getReferences(DetailAST aAST) { final SymTabAST ident = getASTManager().get(aAST); final Definition definition = (Definition) ident.getDefinition(); if (definition != null) { return definition.getReferences(); } final Set dummy = new HashSet(); return dummy.iterator(); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/package.htmlcheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/package.htm100644 0 0 266 11451071612 31257 0ustar 0 0

Contains the Usage checks that are bundled with the main distribution.

././@LongLink100644 0 0 177 12026055133 10255 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/AnonymousInnerClass.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 5002 11451071612 31441 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; public class AnonymousInnerClass extends ClassDef { protected SymTabAST _objblock; protected SymTabAST _classExtended; public AnonymousInnerClass(SymTabAST objblock, SymTabAST classExtended, Scope parentScope) { super(parentScope.getName() + "$" + parentScope.getEnclosingClass().getNextAnonymousId(), parentScope, objblock); _objblock = objblock; _classExtended = classExtended; } public void finishMakingDefinition() { if (_classExtended != null) { String extendedClassName = ASTUtil.constructDottedName(_classExtended); IClass superclass = getClassDefinition(extendedClassName); if (superclass != null) { setSuperclass(superclass); superclass.addSubclass(this); } } } } ././@LongLink100644 0 0 164 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ArrayDef.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 10407 11451071612 31466 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; //import com.puppycrawl.tools.checkstyle.checks.lint.parser.JavaTokenTypes; public class ArrayDef implements IClass { private final static IVariable LENGTH_MEMBER = new ArrayLengthMember(); private IClass _type; public ArrayDef(IClass type){ _type = type; } public IClass getType(){ return _type; } public IClass getSuperclass() { return new ArrayDef(getType().getSuperclass()); } public IClass[] getInterfaces() { return new IClass[0]; } public IClass[] getInnerClasses() { return new IClass[0]; } public IClass getClassDefinition(String name) { return null; } public IMethod getMethodDefinition(String name, ISignature signature) { return new ExternalClass(Object.class).getMethodDefinition(name, signature); } public IVariable getVariableDefinition(String name) { IVariable result = null; if (name.equals("length")) { result = LENGTH_MEMBER; } return result; } public void addSubclass(ClassDef subclass) {} public void addReference(Reference reference) {} public Iterator getReferences() { return new Vector().iterator(); } public int getNumReferences() { return 0; } public List getSubclasses() { return new ArrayList(); } public void addImplementor(ClassDef implementor) {} public List getImplementors() { return new ArrayList(); } public boolean isCompatibleWith(IClass type) { boolean result = false; if (type.equals(new ExternalClass(Object.class))) { result = true; } else if (type instanceof ArrayDef) { result = getType().isCompatibleWith(((ArrayDef)type).getType()); } return result; } public boolean isSourced() { return getType().isSourced(); } public String getName() { return getType().getName() + "[]"; } public String getQualifiedName() { return getType().getQualifiedName() + "[]"; } public boolean isPrimitive() { return false; } public boolean equals(Object obj) { boolean result = false; if (obj instanceof ArrayDef) { ArrayDef compared = (ArrayDef)obj; result = (getType().equals(compared.getType())); } return result; } public int hashCode() { return getType().hashCode(); } public String toString() { return getQualifiedName() + "[]"; } } ././@LongLink100644 0 0 175 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ArrayLengthMember.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 3735 11451071612 31454 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; public class ArrayLengthMember extends ExternalVariable { public ArrayLengthMember() { super(null); } public String getName() { return "length"; } public String getQualifiedName() { return getName(); } public IClass getType() { return LiteralResolver.getDefinition("int"); } } ././@LongLink100644 0 0 166 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ASTManager.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 15565 11451071612 31500 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2003 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import antlr.collections.AST; import com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck; /** * Manages AST trees and nodes. Capable of managing multiple parse trees, which * is useful for inter-file checks. * @author Rick Giles */ public final class ASTManager { /** singleton */ private static final ASTManager INSTANCE = new ASTManager(); /** * Maps DetailASTs to SymTabASTs. * A HashMap is acceptable provided DetailAST method hashCode() returns * distinct integers for distinct objects. * If not, a structure such as IdentityHashMap must be employed. */ private Map mMap = new HashMap(); /** root with subtrees for a set of files */ private SymTabAST mCompleteTree = null; /** Map for parse trees, keyed on File name */ private Map mTrees = new HashMap(); /** Set of checks and their nodes to check */ private Map mCheckNodes = new HashMap(); /** prevent client creation */ private ASTManager() { } /** * Returns the singleon ASTManager. * @return the singleon ASTManager. */ public static ASTManager getInstance() { return INSTANCE; } /** * Add the parse tree for a file to the set of parse trees. * Postcondition: since all checks are local to one source file, * all managed elements are cleared. * @param aFileName the name of the file. * @param aRoot the root of the AST. */ public void addTree(String aFileName, AST aRoot) { clear(); mTrees.put(aFileName, aRoot); } /** * Clears all managed elements. */ private void clear() { mCheckNodes.clear(); mTrees.clear(); mMap.clear(); mCompleteTree = null; } /** * Builds the complete tree for all added parse trees. * @throws SymbolTableException if there is an error. */ private void buildTree() throws SymbolTableException { mCompleteTree = SymTabASTFactory.create(0, "AST Root"); final Set keys = mTrees.keySet(); final Iterator it = keys.iterator(); while (it.hasNext()) { final String fileName = (String) it.next(); final File file = new File(fileName); final AST rootAST = (AST) mTrees.get(fileName); addToCompleteTree(file, rootAST); } // Walk of the complete tree. // TODO: This is a hack. Find a better way. new TableMaker(mCompleteTree).getTable(); } /** * Adds a file and a DetailAST to the root SymTabAST tree. Normally, the * DetailAST will be the parse tree for the file. * @param aFile the file to add. * @param aAST the DetailAST to add. */ private void addToCompleteTree(File aFile, AST aAST) { // add aFile to the root final SymTabAST fileNode = SymTabASTFactory.create(0, aFile.getAbsolutePath()); fileNode.setFile(aFile); mCompleteTree.addChild(fileNode); fileNode.setParent(mCompleteTree); // add aAST to aFile final SymTabAST child = SymTabASTFactory.create(aAST); child.setFile(aFile); fileNode.addChild(child); child.setParent(fileNode); fileNode.finishDefinition(aFile, mCompleteTree); } /** * Registers a node for checking. * @param aCheck the check to apply. * @param aNode the node to check. */ public void registerCheckNode(AbstractUsageCheck aCheck, AST aNode) { Set nodeSet = (Set) mCheckNodes.get(aCheck); if (nodeSet == null) { nodeSet = new HashSet(); nodeSet.add(aNode); mCheckNodes.put(aCheck, nodeSet); } else { nodeSet.add(aNode); } } /** * Gets the nodes to check with a usage check. * @param aCheck the usage check. * @return the nodes to check with aCheck. * @throws SymbolTableException if there is an error. */ public Set getCheckNodes(AbstractUsageCheck aCheck) throws SymbolTableException { // lazy initialization if (mCompleteTree == null) { buildTree(); } Set result = (Set) mCheckNodes.get(aCheck); if (result == null) { result = new HashSet(); } return result; } /** * Maps a AST to its associated SymTabAST. * @param aAST the AST. * @param aSymTabAST the SymTabAST associated with aAST. */ public void put(AST aAST, SymTabAST aSymTabAST) { mMap.put(aAST, aSymTabAST); } /** * Gets the SymTabAST associated with a AST. * @param aAST the AST. * @return the the SymTabAST associated with aAST. */ public SymTabAST get(AST aAST) { return (SymTabAST) mMap.get(aAST); } /** * Clears all associations from DetailsASTs to SymTabASTs. */ public void clearDetailsMap() { mMap.clear(); } /** * Determines whether the map from DetailsASTs to SymTabASTs is empty. * @return true if the map is empty. */ public boolean isEmptyDetailsMap() { return mMap.isEmpty(); } /** * Removes a check and its check nodes. Clears all managed elements if * last check removed. * @param aCheck the check to remove. */ public void removeCheck(AbstractUsageCheck aCheck) { mCheckNodes.remove(aCheck); if (mCheckNodes.isEmpty()) { clear(); } } } ././@LongLink100644 0 0 163 12026055133 10250 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ASTUtil.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 17130 11451071612 31466 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.io.File; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * ASTUtil is a Utility Class that contains utility code * for managing our SymTabAST. * * @see Definition * @see TypedDef */ public class ASTUtil { /** * gets a line number for the tree; if the current SymTabAST node does not have one associated * with it, traverse its children until a line number is found. Failure results in line * number value of 0. * * @param tree the SymTabAST to process * * @return int the resulting line number (0 if none is found) */ public static int getLine(SymTabAST tree) { SymTabAST indexedNode = tree; // find a node that actually has line number info if (indexedNode.getLineNo() == 0) { indexedNode = (SymTabAST) indexedNode.getFirstChild(); while (indexedNode != null && indexedNode.getLineNo() == 0) { indexedNode = (SymTabAST) indexedNode.getNextSibling(); } if (indexedNode == null) { // we're screwed indexedNode = tree; } } return indexedNode.getLineNo(); } /** * gets a column number for the tree; if the current SymTabAST node does not have one associated * with it, traverse its children until a column number is found. Failure results in column * number value of 0. * * @param tree the SymTabAST to process * * @return int the resulting line number (0 if none is found) */ public static int getColumn(SymTabAST tree) { SymTabAST indexedNode = tree; // find a node that actually has line number info // REDTAG -- a label's ':' is a real token and has (the wrong) column info // because it is the parent of the ident node that people will want if (indexedNode.getColumnNo() == 0 || indexedNode.getType() == TokenTypes.LABELED_STAT) { indexedNode = (SymTabAST) indexedNode.getFirstChild(); while (indexedNode != null && indexedNode.getColumnNo() == 0) { indexedNode = (SymTabAST) indexedNode.getNextSibling(); } if (indexedNode == null) { // we're screwed indexedNode = tree; } } return indexedNode.getColumnNo(); } /** * Builds the dotted name String representation of the object contained within * the SymTabAST. * * @return String * @param tree the SymTabAST contaning the entire hierarcy of the object */ public static String constructDottedName(SymTabAST tree) { String result; if (tree.getType() == TokenTypes.DOT) { SymTabAST left = (SymTabAST) tree.getFirstChild(); SymTabAST right = (SymTabAST) left.getNextSibling(); result = constructDottedName(left) + "." + constructDottedName(right); } else if (tree.getType() == TokenTypes.ARRAY_DECLARATOR) { StringBuffer buf = new StringBuffer(); SymTabAST left = (SymTabAST) tree.getFirstChild(); SymTabAST right = (SymTabAST) left.getNextSibling(); buf.append(constructDottedName(left)); if (right != null) { buf.append("."); buf.append(constructDottedName(right)); } buf.append(" []"); result = buf.toString(); } else if (tree.getType() == TokenTypes.METHOD_CALL) { result = constructDottedName((SymTabAST) tree.getFirstChild()) + "()"; } else { result = tree.getText(); } return result; } /** * Returns the Package name in the hierarchy represented by the SymTabAST. * * @return String * @param tree the SymTabAST contaning the entire hierarcy of the object */ public static String constructPackage(SymTabAST tree) { String fullName = constructDottedName(tree); return fullName.substring(0, fullName.lastIndexOf(".")); } /** * Returns the top Class name in the hierarchy represented by the SymTabAST. * * @return String * @param tree the SymTabAST contaning the entire hierarcy of the object */ public static String constructClass(SymTabAST tree) { String fullName = constructDottedName(tree); return fullName.substring( fullName.lastIndexOf(".") + 1, fullName.length()); } public static boolean treesBelowFilesAreEqual( SymTabAST firstRoot, File[] firstFiles, SymTabAST secondRoot, File[] secondFiles) { boolean result = true; if (firstFiles.length == secondFiles.length) { for (int i = 0; i < firstFiles.length; i++) { SymTabAST firstTree = (SymTabAST) getFileNode(firstRoot, firstFiles[i]) .getFirstChild(); SymTabAST secondTree = (SymTabAST) getFileNode(secondRoot, secondFiles[i]) .getFirstChild(); if (!firstTree.equalsList(secondTree)) { result = false; break; } } } else { result = false; } return result; } public static SymTabAST getFileNode(SymTabAST root, File file) { SymTabAST result = null; SymTabAST fileNode = (SymTabAST) root.getFirstChild(); while (fileNode != null && result == null) { if (file.equals(fileNode.getFile())) { result = fileNode; } fileNode = (SymTabAST) fileNode.getNextSibling(); } return result; } } ././@LongLink100644 0 0 165 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/BaseScope.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 6466 11451071612 31460 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; /** * the bottom scope of the scope stack, contains some extra information * to make resolution easier. */ public class BaseScope extends DefaultScope { private SymbolTable table; public BaseScope( SymbolTable symbolTable ) { super("~BASE~", null, null); this.table = symbolTable; } public boolean isBaseScope() { return true; } public void addDefinition(IPackage def) { elements.put(def.getName(), def); } /** * gets the package associated with a fully qualified name * * @param fullyQualifiedName the name of the package * * @return the package that was gotten */ public IPackage getPackageDefinition(String fullyQualifiedName) { return (IPackage)(table.getPackages().get(fullyQualifiedName)); } public IClass getClassDefinition(String name) { IClass result = null; result = LiteralResolver.getDefinition(name); if (result == null) { int lastDot = name.lastIndexOf("."); if (lastDot > 0) { String packageName = name.substring(0, lastDot); String className = name.substring(lastDot + 1); IPackage pkg = getPackageDefinition(packageName); if (pkg != null) { result = pkg.getClass(className); } } } if (result == null) { Class theClass = null; try { theClass = ClassManager.getClassLoader().loadClass(name); result = new ExternalClass(theClass); } catch (ClassNotFoundException e) { // no-op } catch (NoClassDefFoundError e) { // no-op, checkstyle bug 842781 } } return result; } } ././@LongLink100644 0 0 164 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/BlockDef.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 4275 11451071612 31454 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; /** * BlockDef is a Scope which contains * information about everything that defines a nameless block of java code. * There are provisions for keeping the name of several anonymous * blocks of java code within the same parent scope to have unique names. * * @see Scope * @see Resolvable */ public class BlockDef extends DefaultScope { private static long id = 0; public BlockDef(Scope parentScope, SymTabAST node) { super("~Anonymous~" + id++, parentScope, node); } } ././@LongLink100644 0 0 164 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ClassDef.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 25566 11451071612 31502 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; /** * ClassDef contains all the information needed to * represent a java class or interface. This includes the superclass, * whether it's a class or an interface, the interfaces it implements, * a list of its (direct?) subclasses, and the classes that implement * it if it is an interface * * @see Scope */ public class ClassDef extends DefaultScope implements IClass { private long id = 0; private IClass superclass = null; private List interfaces = new Vector(); private List subclasses = new Vector(); private List implementors = new Vector(); private Set importedPackages = new HashSet(); // variable definitions will use elements from parent private Set methods = new HashSet(); private Hashtable imports = new Hashtable(); private Vector unprocessedImports = null; protected MethodDef _defaultConstructor; public ClassDef(String name, Scope parentScope, SymTabAST node) { super(name, parentScope, node); _defaultConstructor = new DefaultConstructor(this); addDefinition(_defaultConstructor); } public long getNextAnonymousId() { return ++id; } public void setSuperclass(IClass newSuperclass) { this.superclass = newSuperclass; } public IClass getSuperclass() { return superclass; } public void addUnprocessedImports(Vector aImports) { unprocessedImports = (Vector) (aImports.clone()); } public Vector getUnprocessedImports() { return unprocessedImports; } public void importPackage(IPackage pkg) { importedPackages.add(pkg); } public void importClass(IClass imported) { imports.put(imported.getName(), imported); } // begin definitions interface public void addDefinition(MethodDef method) { if (method.getName().equals(getName())) { methods.remove(_defaultConstructor); } methods.add(method); } protected Enumeration getDefinitions() { Vector allElements = new Vector(); allElements.addAll(elements.values()); allElements.addAll(methods); allElements.addAll(labels.values()); allElements.addAll(classes.values()); return allElements.elements(); } public IClass getClassDefinition(String name) { IClass result = null; result = (ClassDef) (classes.get(name)); if (result == null) { result = (IClass) (imports.get(name)); } if (result == null) { Iterator it = importedPackages.iterator(); while (it.hasNext() && result == null) { IPackage pkg = (IPackage) it.next(); result = pkg.getClass(name); } } if (result == null) { result = getParentScope().getClassDefinition(name); } //TODO: check for a class in the same package? if (result == null) { final String packageName = getParentScope().getQualifiedName(); final String fullName = packageName + "." + name; Class theClass = null; try { theClass = ClassManager.getClassLoader().loadClass(fullName); result = new ExternalClass(theClass); } catch (ClassNotFoundException e) { // no-op } } return result; } public IMethod getMethodDefinition(String name, ISignature signature) { IMethod result = null; result = getDeclaredMethod(name, signature); if (result == null) { result = getMostCompatibleMethod(name, signature); } if (result == null) { if (superclass != null) { result = superclass.getMethodDefinition(name, signature); } } if (result == null) { IClass[] myInterfaces = getInterfaces(); for (int index = 0; index < myInterfaces.length && result == null; index++) { result = myInterfaces[index].getMethodDefinition(name, signature); } } // not sure why this is here -- inner classes, maybe? // regardless, write better if (result == null) { if (getParentScope() != null) { result = getParentScope().getMethodDefinition(name, signature); } } return result; } public IMethod getMostCompatibleMethod(String name, ISignature signature) { IMethod result = null; SortedSet compatibleMethods = new TreeSet(new MethodSpecificityComparator()); Iterator it = methods.iterator(); while (it.hasNext()) { MethodDef method = (MethodDef) it.next(); if (name.equals(method.getName())) { if (method.hasCompatibleSignature(signature)) { compatibleMethods.add(method); } } } if (!compatibleMethods.isEmpty()) { result = (IMethod) compatibleMethods.first(); } return result; } public IMethod getDeclaredMethod(String name, ISignature signature) { // finds methods declared by this class with the given signature IMethod result = null; Iterator it = methods.iterator(); while (it.hasNext()) { MethodDef method = (MethodDef) it.next(); if (name.equals(method.getName())) { if (method.hasSameSignature(signature)) { result = method; break; } } } return result; } public IVariable getVariableDefinition(String name) { IVariable result = null; // in keeping with getField in java.lang.Class // 1) current class // 2) direct superinterfaces // 3) superclass // then we do the parent scope in case its an inner class result = (VariableDef) (elements.get(name)); if (result == null) { IClass[] superinterfaces = getInterfaces(); for (int i = 0; i < superinterfaces.length && result == null; i++) { result = superinterfaces[i].getVariableDefinition(name); } } if (result == null) { if (superclass != null) { result = superclass.getVariableDefinition(name); } } if (result == null) { if (getParentScope() != null) { result = getParentScope().getVariableDefinition(name); } } return result; } // end definitions interface public void addInterface(IClass implemented) { interfaces.add(implemented); } public IClass[] getInterfaces() { IClass[] type = new IClass[0]; return (IClass[]) interfaces.toArray(type); } public ClassDef getEnclosingClass() { return this; } public void addSubclass(ClassDef subclass) { subclasses.add(subclass); } public List getSubclasses() { return subclasses; } public void addImplementor(ClassDef implementor) { implementors.add(implementor); } public List getImplementors() { return implementors; } public IClass[] getInnerClasses() { Iterator it = getClasses(); List result = new ArrayList(); while (it.hasNext()) { result.add(it.next()); } return (IClass[]) result.toArray(new IClass[0]); } public boolean isSuperclassOf(IClass possibleChild) { // justify my existence boolean result = subclasses.contains(possibleChild); /* Iterator it = subclasses.iterator(); while (it.hasNext() && !result) { IClass child = (IClass)it.next(); result = child.isSuperclassOf(possibleChild); } */ return result; } public boolean isCompatibleWith(IClass type) { boolean result = false; // check myself if (type.equals(this)) { result = true; } // check my superclass else if (superclass != null && superclass.isCompatibleWith(type)) { result = true; } // check my interfaces else if (!interfaces.isEmpty()) { Iterator it = interfaces.iterator(); while (it.hasNext() && !result) { IClass current = (IClass) it.next(); if (current.isCompatibleWith(type)) { result = true; } } } return result; } public boolean isPrimitive() { return false; } } ././@LongLink100644 0 0 200 12026055133 10240 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ClassImportException.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 3432 11451071612 31446 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; public class ClassImportException extends SymbolTableException { public ClassImportException(String name) { super(name); } }././@LongLink100644 0 0 170 12026055133 10246 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ClassManager.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 3672 11451071612 31454 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; public class ClassManager { private static ClassLoader _classLoader = ClassLoader.getSystemClassLoader(); public static void setClassLoader(ClassLoader classLoader) { _classLoader = classLoader; } public static ClassLoader getClassLoader() { return _classLoader; } }././@LongLink100644 0 0 176 12026055133 10254 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/DefaultConstructor.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 4712 11451071612 31450 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Vector; public class DefaultConstructor extends MethodDef { protected ClassDef _classConstructed; public DefaultConstructor(ClassDef classConstructed) { super(classConstructed.getName(), classConstructed, null); _classConstructed = classConstructed; } public IClass getType() { return _classConstructed; } public ISignature getSignature() { return new MethodSignature(new Vector()); } public boolean equals(Object o) { boolean result = false; if (o instanceof DefaultConstructor) { DefaultConstructor constructor = (DefaultConstructor)o; result = getType().equals(constructor.getType()); } return result; } public void setType() {} public void addParameter() {} public void addException() {} } ././@LongLink100644 0 0 170 12026055133 10246 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/DefaultScope.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 5744 11451071612 31456 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; public class DefaultScope extends Scope { public DefaultScope(String name, Scope parentScope, SymTabAST node) { super(name, parentScope, node); } public void addDefinition(IPackage def) { throw new UnsupportedOperationException(getClass().getName()); } public IClass getClassDefinition( String name ) { IClass result = (ClassDef)classes.get(name); if ( result == null && getParentScope() != null ) { result = getParentScope().getClassDefinition( name ); } return result; } public IMethod getMethodDefinition(String name, ISignature signature) { IMethod result = null; if (getParentScope() != null) { result = getParentScope().getMethodDefinition(name, signature); } return result; } public IVariable getVariableDefinition( String name ) { IVariable result = (VariableDef)elements.get(name); if ( result == null && getParentScope() != null ) { result = getParentScope().getVariableDefinition( name ); } return result; } public LabelDef getLabelDefinition(String name) { LabelDef result = (LabelDef)labels.get(name); if (result == null && getParentScope() != null) { result = getParentScope().getLabelDefinition(name); } return result; } } ././@LongLink100644 0 0 166 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/Definition.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 13443 11451071612 31471 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; /** * Definition contains basic information for everything * that is defined in a java source file. A definition has a list * of References, an Occurrence, a name, and * a parent Scope. * * @see Occurrence * @see Scope * @see Reference */ public abstract class Definition implements IDefinition, Comparable { private String _name = null; private Scope _parentScope = null; private SymTabAST _node = null; private SortedSet _references; private Occurrence _occurrence = null; public Definition(String name, Scope parentScope, SymTabAST node) { _name = name; _parentScope = parentScope; _node = node; _references = new TreeSet(); if ( node != null ) { _occurrence = new Occurrence( _node.getFile(), ASTUtil.getLine( _node ), ASTUtil.getColumn( _node )); } } public boolean isSourced() { return true; } /** * returns the name of the definition * * @return String */ public String getName() { return _name; } /** * returns the node in the AST that represents this definition * * @return the node in the AST that represents this definition */ public SymTabAST getTreeNode() { return _node; } /** * Adds a Reference to the collection of References * * @param reference the Reference to add */ public void addReference( Reference reference ) { _references.add( reference ); } /** * Returns the References to this definition * * @return the References to this definition */ public Iterator getReferences() { return _references.iterator(); } public int getNumReferences() { return _references.size(); } /** * Returns the scope in which this definition is defined * * @return the scope in which this definition is defined */ public Scope getParentScope() { return _parentScope; } /** * returns the fully qualifed name of this defintion. The name of * the parentScope and all of its parents are considered when constructing * this name. * * @return the fully qualified name of this definition */ public String getQualifiedName() { String nameToUse = _name; String result; if (_name == null) { nameToUse = "~NO NAME~"; } if (getParentScope() != null && !(getParentScope() instanceof BaseScope)) { result = getParentScope().getQualifiedName() + "." + nameToUse; } else { result = nameToUse; } return result; } /** * Returns the Occurrence for the location of this definition * * @return the Occurrence for the location of this definition */ public Occurrence getOccurrence() { return _occurrence; } /** * Returns the ClassDef that this scope is contained in. * * @return the ClassDef this definition is contained in */ public ClassDef getEnclosingClass() { ClassDef result = null; if ( getParentScope() != null ) { result = getParentScope().getEnclosingClass(); } return result; } public IPackage getEnclosingPackage() { IPackage result = null; if (getParentScope() != null) { result = getParentScope().getEnclosingPackage(); } return result; } /** * returns a String representation of the definition. This string includes * the class of the defintion and its qualified name * * @return String */ public String toString() { return getClass().getName() + "[" + getQualifiedName() + "]"; } public int compareTo(Object o) { int result = 0; if (!(o instanceof Definition)) { throw new ClassCastException(o.getClass().getName()); } result = getQualifiedName().compareTo(((Definition)o).getQualifiedName()); return result; } } ././@LongLink100644 0 0 177 12026055133 10255 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/DefinitionTraverser.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 11203 11451071612 31461 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Enumeration; import java.util.Iterator; public class DefinitionTraverser { protected SymbolTable _symbolTable; public DefinitionTraverser( SymbolTable symbolTable ) { _symbolTable = symbolTable; } public void traverse() { Enumeration packages = _symbolTable.getPackages().elements(); while ( packages.hasMoreElements() ) { traverse( (PackageDef)(packages.nextElement()) ); } } private void traverse( Definition def ) { if ( def instanceof PackageDef ) { traverse( (PackageDef)def ); } else if (def instanceof AnonymousInnerClass) { traverse((AnonymousInnerClass)def); } else if ( def instanceof ClassDef ) { traverse( (ClassDef)def ); } else if (def instanceof DefaultConstructor) { traverse((DefaultConstructor)def); } else if ( def instanceof MethodDef ) { traverse( (MethodDef)def ); } else if ( def instanceof BlockDef ) { traverse( (BlockDef)def ); } else if ( def instanceof VariableDef ) { traverse( (VariableDef)def ); } else if ( def instanceof LabelDef ) { traverse( (LabelDef)def ); } } private void traverse(PackageDef pkg) { handlePackage(pkg); traversePackage(pkg); } private void traverse(AnonymousInnerClass innerClass) { handleAnonymousInnerClass(innerClass); traverseChildren(innerClass); } private void traverse( ClassDef classDef ) { handleClass( classDef ); traverseChildren( classDef ); } private void traverse(DefaultConstructor constructor) { handleDefaultConstructor(constructor); } private void traverse( MethodDef method ) { handleMethod( method ); traverseChildren( method ); } private void traverse( BlockDef block ) { handleBlock( block ); traverseChildren( block ); } private void traverse( VariableDef variable ) { handleVariable( variable ); } private void traverse( LabelDef label ) { handleLabel( label ); } private void traversePackage(PackageDef pkg) { Iterator definitions = pkg.getClasses(); while (definitions.hasNext()) { ClassDef classDef = (ClassDef)definitions.next(); traverse(classDef); } } private void traverseChildren(Scope scope) { Enumeration definitions = scope.getDefinitions(); while ( definitions.hasMoreElements() ) { Definition def = (Definition)(definitions.nextElement()); traverse(def); } } protected void handlePackage( PackageDef pkg ) {} protected void handleAnonymousInnerClass(AnonymousInnerClass innerClass) {} protected void handleClass( ClassDef classDef ) {} protected void handleDefaultConstructor(DefaultConstructor constructor) {} protected void handleMethod( MethodDef method ) {} protected void handleBlock( BlockDef block ) {} protected void handleVariable( VariableDef variable ) {} protected void handleLabel( LabelDef label ) {} } ././@LongLink100644 0 0 167 12026055133 10254 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/DotIterator.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 6643 11451071612 31455 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * An iterator for dot ('.') delimited tokens. * * @version 1.0 * @since 1.0 * @see Iterator */ public class DotIterator implements Iterator { Iterator _nodesIter; List _nodes; public DotIterator(SymTabAST topNode) { _nodes = new ArrayList(); makeNodes(topNode); _nodesIter = _nodes.iterator(); } private void makeNodes(SymTabAST node) { if (node.getType() == TokenTypes.DOT) { SymTabAST left = (SymTabAST) node.getFirstChild(); SymTabAST right = (SymTabAST) left.getNextSibling(); makeNodes(left); makeNodes(right); } else { _nodes.add(node); } } /** * Returns true if the iteration has more elements. (In other words, * returns true if next would return an element rather than throwing an * exception.) * * @return true if the iterator has more elements. */ public boolean hasNext() { return _nodesIter.hasNext(); } /** * Returns the next portion of the dotted name. * * @return the next node in the dotted name. */ public Object next() { return _nodesIter.next(); } /** * Returns the next portion of the dotted name. * * @return the next node in the dotted name. */ public SymTabAST nextNode() { return (SymTabAST) _nodesIter.next(); } /** * Unsupported operation. * */ public void remove() { throw new UnsupportedOperationException(); } } ././@LongLink100644 0 0 171 12026055133 10247 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ExternalClass.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 24355 11451071612 31475 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; //import com.puppycrawl.tools.checkstyle.checks.lint.parser.DotUtils; public class ExternalClass extends ExternalDefinition implements IClass { private Class _javaClass; private List _subclasses; private List _implementors; private Set _methods; public ExternalClass(Class javaClass) { _javaClass = javaClass; _subclasses = new ArrayList(); _implementors = new ArrayList(); } public Class getJavaClass() { return _javaClass; } public String getName() { return getLocalName(); } private String getLocalName() { String fullName = _javaClass.getName(); return fullName.substring(fullName.lastIndexOf(".") + 1); } public IClass getSuperclass() { IClass result = null; Class javaSuperclass = _javaClass.getSuperclass(); if (javaSuperclass != null) { result = new ExternalClass(javaSuperclass); } else { if (_javaClass.isInterface()) { // according to Java, java.lang.Object is not the superclass of // interfaces, which makes sense. However, we need Object to be // the superclass of everything to make type compatibility work. result = new ExternalClass(Object.class); } } return result; } public IClass[] getInterfaces() { Class[] javaInterfaces = _javaClass.getInterfaces(); IClass[] result = new IClass[javaInterfaces.length]; // should we cache this? for (int i = 0; i < javaInterfaces.length; i++) { result[i] = new ExternalClass(javaInterfaces[i]); } return result; } public IClass getClassDefinition(String name) { IClass result = null; String qualifiedName = getQualifiedName() + "$" + name; Class[] classes = getJavaClass().getClasses(); for (int i = 0; i < classes.length; i++) { String candidateQualifiedName = classes[i].getName(); if (qualifiedName.equals(candidateQualifiedName)) { result = new ExternalClass(classes[i]); break; } } return result; } // REDTAG -- this should be a template method! public IVariable getVariableDefinition(String name) { IVariable result = null; Field javaField = null; try { javaField = _javaClass.getDeclaredField(name); } catch (NoSuchFieldException ignoreMe) {} if (javaField == null) { Class[] interfaces = _javaClass.getInterfaces(); for (int i = 0; i < interfaces.length && javaField == null; i++) { try { javaField = interfaces[i].getDeclaredField(name); } catch (NoSuchFieldException ignoreMe) {} } } if (javaField != null) { result = new ExternalVariable(javaField); } else { if (getSuperclass() != null) { result = getSuperclass().getVariableDefinition(name); } } return result; } public IMethod getMethodDefinition(String name, ISignature signature) { IMethod result = null; if (name.equals(getName())) { result = getConstructorDefinition(signature); } else { Method[] methods = _javaClass.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { if (name.equals(methods[i].getName())) { IMethod method = new ExternalMethod(methods[i]); if (method.hasSameSignature(signature)) { result = method; break; } } } if (result == null) { result = getMostCompatibleMethod(name, signature); } if (result == null) { if (getSuperclass() != null) { result = getSuperclass().getMethodDefinition(name, signature); } } if (result == null) { IClass[] interfaces = getInterfaces(); for (int i = 0; i < interfaces.length; i++) { result = interfaces[i].getMethodDefinition(name, signature); if (result != null) { break; } } } } return result; } public IMethod getMostCompatibleMethod(String name, ISignature signature) { IMethod result = null; SortedSet compatibleMethods = new TreeSet(new MethodSpecificityComparator()); Iterator it = getMethods().iterator(); while (it.hasNext()) { IMethod method = (IMethod)it.next(); if ( name.equals( method.getName() ) ) { if ( method.hasCompatibleSignature( signature ) ) { compatibleMethods.add(method); } } } if (!compatibleMethods.isEmpty()) { result = (IMethod)compatibleMethods.first(); } return result; } private Collection getMethods() { if (_methods == null) { _methods = new HashSet(); Method[] methods = _javaClass.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { _methods.add(new ExternalMethod(methods[i])); } } return _methods; } public IMethod getConstructorDefinition(ISignature signature) { IMethod result = null; if (_javaClass.isInterface()) { result = getInterfaceConstructor(signature); } else { result = getClassConstructor(signature); } return result; } private IMethod getInterfaceConstructor(ISignature signature) { IMethod result = null; if (signature.getParameters().length == 0) { result = new InterfaceConstructor(_javaClass); } return result; } private IMethod getClassConstructor(ISignature signature) { IMethod result = null; Constructor[] constructors = _javaClass.getConstructors(); for (int i = 0; i < constructors.length; i++) { IMethod constructor = new ExternalConstructor(constructors[i]); if (constructor.hasSameSignature(signature)) { result = constructor; break; } } if (result == null) { for (int i = 0; i < constructors.length; i++) { IMethod constructor = new ExternalConstructor(constructors[i]); if (constructor.hasCompatibleSignature(signature)) { result = constructor; break; } } } return result; } public boolean isCompatibleWith(IClass type) { boolean result = false; if (isPrimitive() && type.isPrimitive()) { result = PrimitiveClasses.typesAreCompatible((ExternalClass)type, this); } else { // check myself if (type.equals(this)) { result = true; } // check my superclass else if (getSuperclass() != null && getSuperclass().isCompatibleWith(type)) { result = true; } // check my interfaces else if (_javaClass.getInterfaces().length > 0) { Class[] interfaces = _javaClass.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (new ExternalClass(interfaces[i]).isCompatibleWith(type)) { result = true; break; } } } } return result; } public void addImplementor(ClassDef implementor) { _implementors.add(implementor); } public List getImplementors() { return _implementors; } public void addSubclass(ClassDef subclass) { _subclasses.add(subclass); } public List getSubclasses() { return _subclasses; } public String getQualifiedName() { return _javaClass.getName(); } public boolean isPrimitive() { return getJavaClass().isPrimitive(); } public IClass[] getInnerClasses() { Class[] innerJavaClasses = getJavaClass().getDeclaredClasses(); IClass[] result = new IClass[innerJavaClasses.length]; for (int i = 0; i < result.length; i++) { result[i] = new ExternalClass(innerJavaClasses[i]); } return result; } public String toString() { return getClass() + "[" + getQualifiedName() + "]"; } public boolean equals(Object o) { boolean result = false; if (o instanceof ExternalClass) { ExternalClass compared = (ExternalClass)o; result = (getJavaClass().equals(compared.getJavaClass())); } return result; } public int hashCode() { return getJavaClass().hashCode(); } } ././@LongLink100644 0 0 177 12026055133 10255 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ExternalConstructor.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 6656 11451071612 31461 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.lang.reflect.Constructor; public class ExternalConstructor extends ExternalDefinition implements IMethod { private Constructor _javaConstructor; private ISignature _signature; public ExternalConstructor(Constructor javaConstructor) { _javaConstructor = javaConstructor; _signature = new ExternalSignature(_javaConstructor.getParameterTypes()); } public String getName() { return _javaConstructor.getDeclaringClass().getName(); } public IClass getType() { return new ExternalClass(_javaConstructor.getDeclaringClass()); } public ISignature getSignature() { return _signature; } public boolean hasSameSignature(ISignature signature) { return getSignature().isSame(signature); } public boolean hasCompatibleSignature(ISignature signature) { return signature.isCompatibleWith(getSignature()); } public String getQualifiedName() { return getName() + getSignature(); } public Constructor getJavaConstructor() { return _javaConstructor; } public IClass[] getExceptions() { Class[] javaExceptions = getJavaConstructor().getExceptionTypes(); IClass[] result = new IClass[javaExceptions.length]; for (int i = 0; i < result.length; i++) { result[i] = new ExternalClass(javaExceptions[i]); } return result; } public String toString() { return getQualifiedName(); } public boolean equals(Object o) { boolean result = false; if (o instanceof ExternalConstructor) { ExternalConstructor constructor = (ExternalConstructor)o; result = getJavaConstructor().equals(constructor.getJavaConstructor()); } return result; } public int hashCode() { return getJavaConstructor().hashCode(); } } ././@LongLink100644 0 0 176 12026055133 10254 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ExternalDefinition.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 4012 11451071612 31441 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Iterator; import java.util.Vector; public abstract class ExternalDefinition implements IDefinition { public boolean isSourced() { return false; } public void addReference(Reference reference) {} public Iterator getReferences() { return new Vector().iterator(); } public int getNumReferences() { return 0; } }././@LongLink100644 0 0 172 12026055133 10250 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ExternalMethod.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 7751 11451071612 31456 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.lang.reflect.Method; /** * MethodDef contains all the pertinent information for * a method, including return type, formal parameters, and exceptions * thrown * * @see ClassDef * @see MethodSignature */ public class ExternalMethod extends ExternalDefinition implements IMethod { private Method _javaMethod; private ISignature _signature; public ExternalMethod(Method javaMethod) { _javaMethod = javaMethod; _signature = new ExternalSignature(_javaMethod.getParameterTypes()); } public String getName() { return _javaMethod.getName(); } /** * Returns the ClassDef for the return type of this method. * * @return the ClassDef for the return type of this method */ public IClass getType() { IClass result = null; if (_javaMethod.getReturnType().isArray()) { result = new ArrayDef(new ExternalClass(_javaMethod.getReturnType().getComponentType())); } else { result = new ExternalClass(_javaMethod.getReturnType()); } return result; } /** * Returns the signature of this method. * * @return the signature of this method */ public ISignature getSignature() { return _signature; } public boolean hasSameSignature(ISignature signature) { return _signature.isSame(signature); } public boolean hasCompatibleSignature(ISignature signature) { return signature.isCompatibleWith(getSignature()); } public String getQualifiedName() { return getName() + getSignature(); } public Method getJavaMethod() { return _javaMethod; } public IClass[] getExceptions() { Class[] javaExceptions = getJavaMethod().getExceptionTypes(); IClass[] result = new IClass[javaExceptions.length]; for (int i = 0; i < result.length; i++) { result[i] = new ExternalClass(javaExceptions[i]); } return result; } public String toString() { return getQualifiedName(); } public boolean equals(Object o) { boolean result = false; if (o instanceof ExternalMethod) { ExternalMethod compared = (ExternalMethod)o; result = getJavaMethod().equals(compared.getJavaMethod()); } return result; } public int hashCode() { return getJavaMethod().hashCode(); } } ././@LongLink100644 0 0 173 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ExternalPackage.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 5766 11451071612 31462 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.HashMap; import java.util.Map; /** * PackageDef contains all pertinent information about a * package. */ public class ExternalPackage extends ExternalDefinition implements IPackage { String _name; IPackage _parent; Map _packages; public ExternalPackage(String name, IPackage parent) { _name = name; _parent = parent; _packages = new HashMap(); } public IClass getClass(String name) { IClass result = null; try { Class theClass = ClassManager.getClassLoader().loadClass(getQualifiedName() + "." + name); result = new ExternalClass(theClass); } catch (ClassNotFoundException e) { // look elsewhere for the class } return result; } public void addDefinition(IPackage pkg) { _packages.put(pkg.getName(), pkg); } public IPackage getEnclosingPackage() { return _parent; } public String getName() { return _name; } public String getQualifiedName() { StringBuffer result = new StringBuffer(); if (_parent != null) { result.append(_parent.getQualifiedName()); result.append("."); } result.append(getName()); return result.toString(); } } ././@LongLink100644 0 0 175 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ExternalSignature.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 6763 11451071612 31460 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; public class ExternalSignature implements ISignature { private IClass[] _parameters; public ExternalSignature(Class[] parameters) { _parameters = new IClass[parameters.length]; for (int i = 0; i < parameters.length; i++) { if (parameters[i].isArray()) { _parameters[i] = new ArrayDef(new ExternalClass(parameters[i].getComponentType())); } else { _parameters[i] = new ExternalClass(parameters[i]); } } } /** * Whether this method signature is compatible with the signature of the * argument. That is to say, each type for this signature are subclasses, * subinterfaces, or implement the interface for each corresponding type * in the argument signature. * * @param signature the signature of the method definition being compared * @return whether the signatures are compatible */ public boolean isCompatibleWith(ISignature signature) { boolean result = true; if (_parameters.length == signature.getParameters().length) { for (int i = 0; i < _parameters.length; i++) { if (!getParameters()[i].isCompatibleWith(signature.getParameters()[i])) { result = false; break; } } } else { result = false; } return result; } public boolean isSame(ISignature signature) { return java.util.Arrays.equals(_parameters, signature.getParameters()); } public IClass[] getParameters() { return _parameters; } public String toString() { StringBuffer result = new StringBuffer(); result.append("("); for (int i = 0; i < _parameters.length; i++) { result.append(_parameters[i]); if (i < _parameters.length - 1) { result.append(", "); } } result.append(")"); return result.toString(); } } ././@LongLink100644 0 0 174 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ExternalVariable.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 5301 11451071612 31443 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.lang.reflect.Field; /** * VariableDef is a Definition that contains * information about the definition of a variable. * * @see Definition * @see TypedDef */ public class ExternalVariable extends ExternalDefinition implements IVariable { Field _javaField; public ExternalVariable(Field javaField) { _javaField = javaField; } public String getName() { return _javaField.getName(); } public String getQualifiedName() { return new ExternalClass(_javaField.getDeclaringClass()).getQualifiedName() + "." + getName(); } /** * Returns the Type of the variable. * * @see TypedDef * * @return the Type of the variable */ public IClass getType() { IClass result = null; if (_javaField.getType().isArray()) { result = new ArrayDef(new ExternalClass(_javaField.getType().getComponentType())); } else { result = new ExternalClass(_javaField.getType()); } return result; } } ././@LongLink100644 0 0 162 12026055133 10247 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/IClass.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 11510 11451071612 31462 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.List; /** * interface implemented by classes/interfaces definition, for source or * non-sourced classes and interfaces * The implementor of this class have all information about its inner classes, * methods, variables, subclasses, etc. * @see net.sourceforge.transmogrify.symtab.ClassDef * @see net.sourceforge.transmogrify.symtab.ExternalClass */ public interface IClass extends IDefinition { /** * gets superclass definition of this class * @return superclass of this class definition */ public IClass getSuperclass(); /** * gets interfaces definition implemented by this class definition * @return interfaces implemented */ public IClass[] getInterfaces(); /** * gets subclasses definition of this class definition * @return list of subclasses definition */ public List getSubclasses(); /** * gets class definition referenced by this class, including its inner classes, * imported classes, packages, and its parent scope referenced class definitions * @param name name of the class definition to be searched * @return class definition that matches the input name */ public IClass getClassDefinition(String name); /** * gets the method associated with the given name and signature * * @param name the name of the method * @param signature the signature (formal parameter types) of the method * * @return MethodDef * * @see MethodSignature */ public IMethod getMethodDefinition(String name, ISignature signature); /** * gets the VariableDef associated with the given name * * @param name the name of the variable * * @return VariableDef */ public IVariable getVariableDefinition(String name); // end definitions interface /** * adds ClassDef to the collection of (direct?) subclasses of * this class * * @param subclass the class to add * @return void */ public void addSubclass(ClassDef subclass); /** * adds ClassDef to the collection of implemented interfaces * of this class * * @param implementor the interface to add * @return void */ public void addImplementor(ClassDef implementor); /** * gets the list of ClassDefs that implmement this interface * * @return Vector the list of implementors */ public List getImplementors(); /** * verifies if the input type is equal to this class or its superclass or * its interfaces * @param type class to be compared with * @return true if the input type is equals * false otherwise */ public boolean isCompatibleWith(IClass type); /** * verifies if this class is of primitive Java type * @return true if the class is a primitive type * false otherwise */ public boolean isPrimitive(); /** * gets inner classes definition associated with this class * @return array of inner classes */ public IClass[] getInnerClasses(); } ././@LongLink100644 0 0 167 12026055133 10254 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/IDefinition.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 6322 11451071612 31447 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Iterator; /** * implemented by all definitions of the SymTabAST tree, including * source/non-sourced node * @see net.sourceforge.transmogrify.symtab.Definition * @see net.sourceforge.transmogrify.symtab.ExternalDefinition */ public interface IDefinition { /** * verifies if this definition node is source/non-sourced(with no source-code) * @return true if the node is parsed from a source code * false otherwise */ public boolean isSourced(); /** * gets the name that identified this particular definition/node * @return name for this definition */ public String getName(); /** * gets the fully qualified name of the definition, ie. dotted name for classes, * or method name with its signature for methods, etc * @return qualified name for this node */ public String getQualifiedName(); /** * adds any reference that this definition have to its collection of * _references * @param reference reference to be added which has SymTabAST node * @return void * @see net.sourceforge.transmogrify.symtab.antlr.SymTabAST */ public void addReference(Reference reference); /** * gets the collection of references refer to by this definition * @return iterator of the references */ public Iterator getReferences(); /** * gets the number of references refer to by this definition * @return number of references */ public int getNumReferences(); }././@LongLink100644 0 0 163 12026055133 10250 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/IMethod.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 5342 11451071612 31450 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; /** * MethodDef contains all the pertinent information for * a method, including return type, formal parameters, and exceptions * thrown * * @see ClassDef * @see MethodSignature * @see net.sourceforge.transmogrify.symtab.ExternalMethod * @see net.sourceforge.transmogrify.symtab.MethodDef */ public interface IMethod extends Typed { /** * Returns the signature of this method. * * @return the signature of this method */ public ISignature getSignature(); /** * verifies if the input signature is the same with signatures of this method * @return true if the two set signatures are equal * false otherwise */ public boolean hasSameSignature(ISignature signature); /** * verifies if the input signature type is compatible with this method signature * @return true if the two set of signatures are compatible * false otherwise */ public boolean hasCompatibleSignature(ISignature signature); public IClass[] getExceptions(); }././@LongLink100644 0 0 200 12026055133 10240 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/InterfaceConstructor.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 5751 11451071612 31454 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.lang.reflect.Constructor; import java.util.Vector; public class InterfaceConstructor extends ExternalDefinition implements IMethod { protected Class _classConstructed; public InterfaceConstructor(Class classConstructed) { _classConstructed = classConstructed; } public String getName() { return _classConstructed.getName(); } public IClass getType() { return new ExternalClass(_classConstructed); } public ISignature getSignature() { return new MethodSignature(new Vector()); } public boolean hasSameSignature(ISignature signature) { return getSignature().isSame(signature); } public boolean hasCompatibleSignature(ISignature signature) { return signature.isCompatibleWith(getSignature()); } public Constructor getJavaConstructor() { return null; } public IClass[] getExceptions() { return new IClass[0]; } public String getQualifiedName() { return getName() + getSignature(); } public boolean equals(Object o) { boolean result = false; if (o instanceof InterfaceConstructor) { InterfaceConstructor constructor = (InterfaceConstructor)o; result = getType().equals(constructor.getType()); } return result; } public int hashCode() { return getType().hashCode(); } } ././@LongLink100644 0 0 164 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/IPackage.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 4670 11451071612 31453 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; /** * PackageDef contains all pertinent information about a * package. * @see net.sourceforge.transmogrify.symtab.ExternalPackage * @see net.sourceforge.transmogrify.symtab.PackageDef */ public interface IPackage extends IDefinition { /** * return class definition associated with this package * @param name of the class to be returned * @return the class definition */ public IClass getClass(String name); /** * gets the Package definition of itself * @return Package definition */ public IPackage getEnclosingPackage(); /** * adds a package definition to its parent's list of package definitions * @param def package definition * @return void */ public void addDefinition(IPackage def); }././@LongLink100644 0 0 166 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ISignature.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 5172 11451071612 31451 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; /** * implemented by signatures of methods * @see net.sourceforge.transmogrify.symtab.MethodSignature * @see net.sourceforge.transmogrify.symtab.ExternalSignature */ public interface ISignature { public IClass[] getParameters(); /** * Whether this method signature is compatible with the signature of the * argument. That is to say, each type for this signature are subclasses, * subinterfaces, or implement the interface for each corresponding type * in the argument signature. * * @param signature the signature of the method definition being compared * @return whether the signatures are compatible */ public boolean isCompatibleWith(ISignature signature); /** * if both signature has the same set of parameters * @param signature signature to be compared * @return true if the two set of parameters are equal * false otherwise */ public boolean isSame(ISignature signature); } ././@LongLink100644 0 0 165 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/IVariable.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 3662 11451071612 31453 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; /** * contains information about type of a variable or its Field, * in case of non-source variable * @see net.sourceforge.transmogrify.symtab.VariableDef * @see net.sourceforge.transmogrify.symtab.ExternalVariable */ public interface IVariable extends Typed {}././@LongLink100644 0 0 164 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/LabelDef.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 3732 11451071612 31451 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; /** * LabelDef is a Definition that contains information * about the definition of a Label. * * @see Definition */ public class LabelDef extends Definition { public LabelDef( String name, Scope parentScope, SymTabAST node ) { super( name, parentScope, node ); } } ././@LongLink100644 0 0 173 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/LiteralResolver.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 13745 11451071612 31476 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.HashMap; import java.util.Map; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Resolves primitive identifiers (int, double) to their corresponding * ClassDef. This class uses the Singleton pattern. * * @author andrew * @version 1.0 * @since 1.0 */ public class LiteralResolver { private static Map intMap; private static Map nameMap; private static Map classMap; static { nameMap = new HashMap(); nameMap.put("boolean", new ExternalClass(Boolean.TYPE)); nameMap.put("byte", new ExternalClass(Byte.TYPE)); nameMap.put("char", new ExternalClass(Character.TYPE)); nameMap.put("short", new ExternalClass(Short.TYPE)); nameMap.put("int", new ExternalClass(Integer.TYPE)); nameMap.put("float", new ExternalClass(Float.TYPE)); nameMap.put("long", new ExternalClass(Long.TYPE)); nameMap.put("double", new ExternalClass(Double.TYPE)); intMap = new HashMap(); intMap.put( new Integer(TokenTypes.LITERAL_BOOLEAN), new ExternalClass(Boolean.TYPE)); intMap.put( new Integer(TokenTypes.LITERAL_BYTE), new ExternalClass(Byte.TYPE)); intMap.put( new Integer(TokenTypes.LITERAL_CHAR), new ExternalClass(Character.TYPE)); intMap.put( new Integer(TokenTypes.LITERAL_SHORT), new ExternalClass(Short.TYPE)); intMap.put( new Integer(TokenTypes.LITERAL_INT), new ExternalClass(Integer.TYPE)); intMap.put( new Integer(TokenTypes.LITERAL_FLOAT), new ExternalClass(Float.TYPE)); intMap.put( new Integer(TokenTypes.LITERAL_LONG), new ExternalClass(Long.TYPE)); intMap.put( new Integer(TokenTypes.LITERAL_DOUBLE), new ExternalClass(Double.TYPE)); intMap.put( new Integer(TokenTypes.STRING_LITERAL), new ExternalClass("".getClass())); classMap = new HashMap(); classMap.put( new ExternalClass(Boolean.TYPE), SymTabASTFactory.create(TokenTypes.LITERAL_BOOLEAN, "boolean")); classMap.put( new ExternalClass(Byte.TYPE), SymTabASTFactory.create(TokenTypes.LITERAL_BYTE, "byte")); classMap.put( new ExternalClass(Character.TYPE), SymTabASTFactory.create(TokenTypes.LITERAL_CHAR, "char")); classMap.put( new ExternalClass(Short.TYPE), SymTabASTFactory.create(TokenTypes.LITERAL_SHORT, "short")); classMap.put( new ExternalClass(Integer.TYPE), SymTabASTFactory.create(TokenTypes.LITERAL_INT, "int")); classMap.put( new ExternalClass(Float.TYPE), SymTabASTFactory.create(TokenTypes.LITERAL_FLOAT, "float")); classMap.put( new ExternalClass(Long.TYPE), SymTabASTFactory.create(TokenTypes.LITERAL_LONG, "long")); classMap.put( new ExternalClass(Double.TYPE), SymTabASTFactory.create(TokenTypes.LITERAL_DOUBLE, "double")); } /** * Returns a LiteralResolver * * @return a LiteralResolver */ public static LiteralResolver getResolver() { return new LiteralResolver(); } /** * Returns the ClassDef for a primitive type reference. * *

* We could probably do without passing in the context, if we could figure * out a way to access the base scope. *

* * @param literalType the JavaTokenType for the literal type * @param context the scope in which the search performed * @return returns the ClassDefcorresponding to the primitive * type */ public static IClass getDefinition(int literalType) { Integer key = new Integer(literalType); return (IClass) intMap.get(key); } public static IClass getDefinition(String name) { return (IClass) nameMap.get(name); } public static SymTabAST getASTNode(IClass primitive) { return (SymTabAST) classMap.get(primitive); } } ././@LongLink100644 0 0 165 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/MethodDef.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 11336 11451071612 31470 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.List; import java.util.Vector; /** * MethodDef contains all the pertinent information for * a method, including return type, formal parameters, and exceptions * thrown * * @see ClassDef * @see MethodSignature */ public class MethodDef extends DefaultScope implements IMethod { private IClass returnType; private List exceptions; private List parameters; public MethodDef(String name, Scope parentScope, SymTabAST node) { super(name, parentScope, node); parameters = new Vector(); } /** * Returns the ClassDef for the return type of this method. * * @return the ClassDef for the return type of this method */ public IClass getType() { return returnType; } /** * Sets the return type of this method. * * @param type the ClassDef for the return type */ public void setType(IClass type) { returnType = type; } /** * Adds a parameter to the collection of formal parameters * * @param parameter the VariableDef to add */ public void addParameter(VariableDef parameter) { parameters.add( parameter ); addDefinition(parameter); } /** * Whether this method has the same signature as the given signature. * * @param signature the MethodSignature to compare * * @return whether the signatures are equal */ public boolean hasSameSignature(ISignature signature) { return getSignature().equals(signature); } /** * Whether this method has a signature compatible with the given signature. * * @param signature the signature being compared * @return whether the signatures are compatible */ public boolean hasCompatibleSignature(ISignature signature) { return signature.isCompatibleWith(getSignature()); } /** * Returns the signature of this method. * * @return the signature of this method */ public ISignature getSignature() { Vector argTypes = new Vector(); for (int i = 0; i < parameters.size(); i++) { argTypes.add(getParameterAt(i).getType()); } return new MethodSignature(argTypes); } /** * Gets the ith parameter of this method * * @param i the index of the parameter * * @return the VariableDef of the ith parameter */ private VariableDef getParameterAt( int i ) { return (VariableDef)(parameters.get( i )); } /** * Adds an exception that this method throws. * * @param exception the exception to add */ public void addException(IClass exception) { if (exceptions == null) { exceptions = new Vector(); } exceptions.add(exception); } /** * Returns the exceptions this method throws * * @return the exceptions this method throws */ public IClass[] getExceptions() { return (IClass[])exceptions.toArray(new IClass[0]); } public String getQualifiedName() { return super.getQualifiedName() + getSignature(); } }././@LongLink100644 0 0 173 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/MethodSignature.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 10731 11451071612 31466 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Vector; /** * MethodSignature is used to resolve various methods * in the same scope of the same name based on formal parameter lists * * @see MethodDef */ public class MethodSignature implements ISignature{ private IClass[] _argTypes = null; public MethodSignature(IClass[] argTypes) { _argTypes = argTypes; } public MethodSignature(Vector argTypes) { _argTypes = new IClass[argTypes.size()]; argTypes.toArray(_argTypes); } /** * returns an array of the types of the arguments in the signature * * @return ClassDef[] */ public IClass[] getParameters() { return _argTypes; } /** * Whether this method signature is compatible with the signature of the * argument. That is to say, each type for this signature are subclasses, * subinterfaces, or implement the interface for each corresponding type * in the argument signature. * * @param signature the signature of the method definition being compared * @return whether the signatures are compatible */ public boolean isCompatibleWith(ISignature signature) { boolean result = true; IClass[] comparedArgTypes = signature.getParameters(); if (_argTypes.length != comparedArgTypes.length) { result = false; } else { for (int i = 0; i < _argTypes.length; i++) { // TODO: Checkstyle modification. Why can _argTypes[i] be null? // if (!_argTypes[i].isCompatibleWith(comparedArgTypes[i])) { if ((_argTypes[i] != null) && !_argTypes[i].isCompatibleWith(comparedArgTypes[i])) { result = false; break; } } } return result; } public boolean isSame(ISignature signature) { return equals(signature); } /** * compares two objects for equality. If the compared object is a * MethodSignature and the argTypes match, they are the * same * * @return boolean */ public boolean equals(Object o) { boolean result = false; if (o instanceof MethodSignature) { MethodSignature signature = (MethodSignature)o; result = java.util.Arrays.equals(getParameters(), signature.getParameters()); } return result; } /** * returns a String representation of this object. Includes information * about the types of the arguments in the signature * * @return String */ public String toString() { StringBuffer result = new StringBuffer( "(" ); for ( int i = 0; i < _argTypes.length; i++ ) { result.append( _argTypes[i] != null ? _argTypes[i].getName() : "[null]" ); if ( i < (_argTypes.length - 1) ) { result.append( ", " ); } } result.append( ")" ); return result.toString(); } } ././@LongLink100644 0 0 207 12026055133 10247 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/MethodSpecificityComparator.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 4317 11451071612 31451 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Comparator; public class MethodSpecificityComparator implements Comparator { public int compare(Object o1, Object o2) { int result = 0; IMethod method1 = (IMethod)o1; IMethod method2 = (IMethod)o2; if (method1.equals(method2)) { result = 0; } else { ISignature sig1 = method1.getSignature(); ISignature sig2 = method2.getSignature(); if (sig1.isCompatibleWith(sig2)) { result = -1; } else { result = 1; } } return result; } } ././@LongLink100644 0 0 165 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/NullClass.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 6002 11451071612 31442 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class NullClass implements IClass { public Iterator getReferences() { return new ArrayList().iterator(); } public int getNumReferences() { return 0; } public void addReference(Reference ref) {} public String getName() { return "null"; } public String getQualifiedName() { return getName(); } public boolean isSourced() { return false; } public IClass getSuperclass() { return null; } public IClass[] getInterfaces() { return new IClass[0]; } public IClass[] getInnerClasses() { return new IClass[0]; } public List getSubclasses() { return new ArrayList(); } public IClass getClassDefinition(String name) { return null; } public IMethod getMethodDefinition(String name, ISignature signature) { return null; } public IVariable getVariableDefinition(String name) { return null; } public void addSubclass(ClassDef subclass) {} public void addImplementor(ClassDef implementor) {} public List getImplementors() { return new ArrayList(); } public boolean isCompatibleWith(IClass type) { return true; } public boolean isPrimitive() { return false; } } ././@LongLink100644 0 0 166 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/Occurrence.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 7342 11451071612 31452 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.io.File; /** * Occurrence contains file and line number information. * It is used to denote the location of various Definintions * and References * * @see Reference * @see Definition */ public class Occurrence implements Comparable { private File _file; private int _line; private int _column; public Occurrence(File file, int line, int column) { _file = file; _line = line; _column = column; } public Occurrence(SymTabAST node) { _file = node.getFile(); _line = node.getLineNo(); _column = node.getColumnNo(); } /** * returns the File of this Occurrence * * @return File */ public File getFile() { return _file; } /** * returns the line number of this Occurrence * * @return the line number of this Occurrence */ public int getLine() { return _line; } /** * returns the column that this token starts at * * @return the column that this token starts at */ public int getColumn() { return _column; } public int compareTo(Object o) { if (!(o instanceof Occurrence)) { throw new ClassCastException(getClass().getName()); } Occurrence other = (Occurrence)o; int result = 0; result = getFile().compareTo(other.getFile()); if (result == 0) { result = getLine() - other.getLine(); } if (result == 0) { result = getColumn() - other.getColumn(); } return result; } public boolean equals(Object o) { boolean result = false; if (o instanceof Occurrence) { Occurrence occ = (Occurrence)o; result = (getFile().equals(occ.getFile()) && getLine() == occ.getLine() && getColumn() == occ.getColumn()); } return result; } public int hashCode() { return getFile().hashCode(); } public String toString() { return "[" + getFile() + ":" + getLine() + "," + getColumn() + "]"; } } ././@LongLink100644 0 0 166 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/PackageDef.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 4663 11451071612 31455 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; /** * PackageDef contains all pertinent information about a * package. */ public class PackageDef extends DefaultScope implements IPackage { public PackageDef(String name, Scope parentScope, SymTabAST node) { super(name, parentScope, node); } public LabelDef getLabelDefinition(String name) { throw new UnsupportedOperationException(getClass().getName()); } public IClass getClass(String name) { return (IClass)classes.get(name); } public IPackage getEnclosingPackage() { return this; } public IVariable getVariableDefinition(String name) { return null; } public void addDefinition(IPackage def) { if (elements.get(def.getName()) == null) { elements.put(def.getName(), def); } } } ././@LongLink100644 0 0 174 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/PrimitiveClasses.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 7302 11451071612 31446 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.ArrayList; import java.util.List; public class PrimitiveClasses { public static final ExternalClass BOOLEAN = new ExternalClass(Boolean.TYPE); public static final ExternalClass CHAR = new ExternalClass(Character.TYPE); public static final ExternalClass BYTE = new ExternalClass(Byte.TYPE); public static final ExternalClass SHORT = new ExternalClass(Short.TYPE); public static final ExternalClass INT = new ExternalClass(Integer.TYPE); public static final ExternalClass LONG = new ExternalClass(Long.TYPE); public static final ExternalClass FLOAT = new ExternalClass(Float.TYPE); public static final ExternalClass DOUBLE = new ExternalClass(Double.TYPE); private static List order; static { order = new ArrayList(); order.add(DOUBLE); order.add(FLOAT); order.add(LONG); order.add(INT); order.add(SHORT); order.add(BYTE); } public static boolean typesAreCompatible(ExternalClass hole, ExternalClass peg) { boolean result = false; if (hole.equals(BOOLEAN)) { result = peg.equals(BOOLEAN); } else if (hole.equals(CHAR)) { result = peg.equals(CHAR); } else if (peg.equals(CHAR)) { result = (hole.equals(CHAR) || order.indexOf(hole) <= order.indexOf(INT)); } else { result = (order.indexOf(hole) <= order.indexOf(peg)); } return result; } public static IClass unaryPromote(IClass type) { IClass result = type; if (type.equals(BYTE) || type.equals(SHORT) || type.equals(CHAR)) { result = INT; } return result; } public static IClass binaryPromote(IClass a, IClass b) { IClass result = null; if (a.equals(DOUBLE) || b.equals(DOUBLE)) { result = DOUBLE; } else if (a.equals(FLOAT) || b.equals(FLOAT)) { result = FLOAT; } else if (a.equals(LONG) || b.equals(LONG)) { result = LONG; } else { result = INT; } return result; } } ././@LongLink100644 0 0 167 12026055133 10254 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/QueryEngine.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 13157 11451071612 31473 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.io.File; import java.util.Iterator; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * a wrapper around a SymbolTable that makes Definition and * reference lookup easier */ public class QueryEngine { private SymbolTable symbolTable; private ScopeIndex index; public QueryEngine(SymbolTable aSymbolTable) { this.symbolTable = aSymbolTable; setIndex(); } /** * sets the scope index that this QueryEngine uses */ private void setIndex() { index = symbolTable.getScopeIndex(); } /** * gets a symbol from the associated symbol table * * @param name the name of the symbol to get * @param location the location of that symbol * * @return Object the (possibly null) result of the lookup */ public Reference getSymbol(String name, Occurrence location) { Scope enclosingScope = index.lookup(location); Reference result = enclosingScope.getSymbol(name, location); // REDTAG -- for cases like a label on the same line as the // block it names, e.g. 'bar: for(int i = 0; ...' if (result == null) { result = enclosingScope.getParentScope().getSymbol(name, location); } return result; } /** * gets the definition of the given symbol * * @param name the name of the symbol to consider * @param location the Occurrence that represents the * location of the symbol * * @return Definition the (possibly null) result of the lookup */ public IDefinition getDefinition(String name, Occurrence location) { Reference symbol = getSymbol(name, location); //if (symbol != null) { // System.out.println(" found " + name); //} //else { // System.out.println(" !could not find " + name); //} return resolveDefinition(symbol); } public IDefinition getDefinition(Occurrence location) { IDefinition result = null; SymTabAST node = getWordNodeAtOccurrence(location); if ( node != null ) { result = node.getDefinition(); } return result; } private IDefinition resolveDefinition(Reference reference) { IDefinition result = null; if ( reference != null ) { result = reference.getDefinition(); } return result; } /** * gets a collection of references determined by a symbol and location * * @param name the name of the symbol to consider * @param location the Occurrence that represents its location * * @return */ public Iterator getReferences(String name, Occurrence location) { Reference symbol = getSymbol(name, location); return resolveReferences(symbol); } public Iterator getReferences(Occurrence location) { Iterator result = null; SymTabAST node = getWordNodeAtOccurrence(location); if ( node != null && node.getDefinition() != null ) { result = node.getDefinition().getReferences(); } return result; } private Iterator resolveReferences(Reference reference) { return reference.getDefinition().getReferences(); } public SymTabAST getFileNode(File file) { return ASTUtil.getFileNode(symbolTable.getTree(), file); } private SymTabAST getWordNodeAtOccurrence(Occurrence location) { SymTabAST result = null; SymTabAST fileNode = getFileNode(location.getFile()); if ( fileNode != null ) { SymTabAST node = fileNode.getEnclosingNode(location.getLine(), location.getColumn()); if ( (node != null) && (node.getType() == TokenTypes.IDENT) ) { result = node; } } return result; } public String getWordAtOccurrence(Occurrence location ) { String result = null; SymTabAST node = getWordNodeAtOccurrence(location); if ( node != null ) { result = node.getText(); } return result; } } ././@LongLink100644 0 0 165 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/Reference.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 10407 11451071612 31466 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.io.File; /** * represents a place where a definition is used. There are two flavors * of references -- resolved (those that have a definition associated with * them) and unresolved (those that don't have a definition associated). * The goal of the resolution step is to get all of the references in the * symbol table to fall into the resolved category. */ public class Reference implements Comparable { private SymTabAST _node; private Occurrence _occurrence; public Reference( SymTabAST node ) { _node = node; _occurrence = new Occurrence( _node.getFile(), ASTUtil.getLine(_node), ASTUtil.getColumn(_node) ); } /** * gets the definition associated with this reference * * @return Definition the (possibly null) definition associated with * this reference */ public IDefinition getDefinition() { return _node.getDefinition(); } /** * return the node that was passed in during ctor */ public SymTabAST getTreeNode() { return _node; } /** * gets the occurrence of this reference * * @return Occurrence */ public Occurrence getOccurrence() { return _occurrence; } /** * gets the line where the node resides */ public int getLine() { return getOccurrence().getLine(); } /** * gets the column for where the node resides */ public int getColumn() { return getOccurrence().getColumn(); } /** * gets the enclosing file for the node */ public File getFile() { return getOccurrence().getFile(); } /** * gets the name of the reference * * @return String the name of the definition associated with this reference * if this reference is resolved, else null */ public String getName() { return _node.getName(); } /** * returns a string representation of the reference. * * @return String */ public String toString() { return getOccurrence().toString(); } /** * returns whether the References are equal * * @return whether the References are equal */ // REDTAG -- not finished public boolean equals(Object obj){ boolean result = false; if (obj instanceof Reference) { result = getOccurrence().equals(((Reference)obj).getOccurrence()); } return result; } public int compareTo(Object o) { if (!(o instanceof Reference)) { throw new ClassCastException(getClass().getName()); } return getOccurrence().compareTo(((Reference)o).getOccurrence()); } } ././@LongLink100644 0 0 174 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ReferenceCounter.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 6145 11451071612 31452 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * This class is for counting the reference */ public class ReferenceCounter extends ReferenceTool { private List _references = new ArrayList(); private List _resolvedReferences = new ArrayList(); private List _unresolvedReferences = new ArrayList(); public ReferenceCounter(SymbolTable table) { super(table.getTree()); countReferences(); } /** * Return the number of references */ public int numberOfReferences() { return _references.size(); } /** * Return the number of resolved references */ public int numberOfResolvedReferences() { return _resolvedReferences.size(); } public int numberOfUnresolvedReferences() { return _unresolvedReferences.size(); } public ListIterator getUnresolvedReferences() { return _unresolvedReferences.listIterator(); } private void countReferences() { handleNode( _tree ); } protected void handleNode( SymTabAST node ) { if (node.getType() == TokenTypes.IDENT && node.isMeaningful()) { _references.add( node ); if (node.getDefinition() != null && !(node.getDefinition() instanceof UnknownClass)) { _resolvedReferences.add( node ); } else { _unresolvedReferences.add( node ); } } walkChildren( node ); } } ././@LongLink100644 0 0 176 12026055133 10254 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ReferenceThreshold.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 5541 11451071612 31451 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Set; import java.util.TreeSet; public class ReferenceThreshold extends ReferenceTool { private Set _underreferencedDefinitions; private int _threshold; public ReferenceThreshold(SymbolTable table, int threshold) { super(table.getTree()); _threshold = threshold; _underreferencedDefinitions = new TreeSet(); go(); } private void go() { collectUnderreferencedDefinitions(); } private void collectUnderreferencedDefinitions() { handleNode(_tree); } protected void handleNode(SymTabAST node) { if (node.isMeaningful()) { IDefinition def = node.getDefinition(); if (def != null && def.getNumReferences() <= _threshold && def instanceof Definition) { // this is inheritently hackish // basically we want to ignore // all test cases and main() methods if (def.getQualifiedName().indexOf("test") < 0 && def.getQualifiedName().indexOf("main") < 0) { _underreferencedDefinitions.add(def); } } } walkChildren(node); } public Set getUnderreferencedDefinitions() { return _underreferencedDefinitions; } } ././@LongLink100644 0 0 171 12026055133 10247 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ReferenceTool.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 4430 11451071612 31445 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; public abstract class ReferenceTool { protected SymTabAST _tree = null; public ReferenceTool(SymTabAST tree) { _tree = tree; } protected void walkChildren( SymTabAST node ) { if ( node.getFirstChild() != null ) { walkSelfAndSiblings( (SymTabAST)node.getFirstChild() ); } } private void walkSelfAndSiblings( SymTabAST node ) { handleNode( node ); SymTabAST sibling = (SymTabAST)node.getNextSibling(); while ( sibling != null ) { handleNode( sibling ); sibling = (SymTabAST)sibling.getNextSibling(); } } protected abstract void handleNode(SymTabAST node); }././@LongLink100644 0 0 164 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/Resolver.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 203512 11451071612 31507 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogConfigurationException; import org.apache.commons.logging.LogFactory; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * The resolver is responsible for traversing all the various * definitions in a symbol table and resolving references in them. * * @see SymbolTable */ public class Resolver extends DefinitionTraverser { /** true if the log factory has been initialized */ private boolean mInitialized = false; /** Factory for creating org.apache.commons.logging.Log instances */ private LogFactory mLogFactory; /** * constructor with SymbolTable to be resolved */ public Resolver(SymbolTable symbolTable) { super(symbolTable); try { mLogFactory = LogFactory.getFactory(); } catch (LogConfigurationException e) { System.out.println("log configuration exception" + e); } mInitialized = true; } /** * resolves the symbol table * @return void * @see #traverse() */ public void resolve() { traverse(); } protected void handleSList(SymTabAST node, Scope scope) { SymTabASTIterator iterator = node.getChildren(); while (iterator.hasNext()) { SymTabAST current = iterator.nextChild(); resolveExpression(current, scope, null, true); } } protected void handleAnonymousInnerClass(AnonymousInnerClass innerClass) { SymTabAST objblock = innerClass.getTreeNode(); SymTabAST expression = (SymTabAST) objblock.getFirstChild(); while (expression != null) { resolveExpression(expression, innerClass, null, true); expression = (SymTabAST) expression.getNextSibling(); } } /** * processes a ClassDef and resolves references in it * * @param classDef the ClassDef to process */ protected void handleClass(ClassDef classDef) { SymTabAST node = classDef.getTreeNode(); if (node != null) { SymTabAST nameNode = node.findFirstToken(TokenTypes.IDENT); nameNode.setDefinition(classDef, classDef, true); SymTabAST extendsClause = node.findFirstToken(TokenTypes.EXTENDS_CLAUSE); if(extendsClause != null) { SymTabAST extendedClassNode = (SymTabAST) extendsClause.getFirstChild(); while (extendedClassNode != null) { IClass superClass = resolveClass(extendedClassNode, classDef, null, true); extendedClassNode.setDefinition(superClass, classDef, true); extendedClassNode = (SymTabAST) extendedClassNode.getNextSibling(); } } SymTabAST implementsNode = node.findFirstToken(TokenTypes.IMPLEMENTS_CLAUSE); if (implementsNode != null) { SymTabAST interfaceNode = (SymTabAST) (implementsNode.getFirstChild()); while (interfaceNode != null) { resolveClass(interfaceNode, classDef, null, true); interfaceNode = (SymTabAST) (interfaceNode.getNextSibling()); } } } } /** * processes a MethodDef and resolves references in it * * @param method the MethodDef to process */ protected void handleMethod(MethodDef method) { SymTabAST node = method.getTreeNode(); SymTabAST nameNode = node.findFirstToken(TokenTypes.IDENT); nameNode.setDefinition(method, method, true); // references to classes in return type SymTabAST returnTypeNode = node.findFirstToken(TokenTypes.TYPE); if (returnTypeNode != null) { // this is not a constructor resolveExpression(returnTypeNode, method, null, true); } SymTabAST throwsNode = node.findFirstToken(TokenTypes.LITERAL_THROWS); if (throwsNode != null) { SymTabAST exception = (SymTabAST) throwsNode.getFirstChild(); while (exception != null) { // handle Checkstyle grammar if (exception.getType() != TokenTypes.COMMA) { resolveClass(exception, method, null, true); } exception = (SymTabAST) exception.getNextSibling(); } } // references to classes in parameters // the body -- this would be better its own function SymTabAST slist = node.findFirstToken(TokenTypes.SLIST); if (slist != null) { handleSList(slist, method); } } /** * processes a BlockDef and resolves references in it * * @param block the BlockDef to process */ protected void handleBlock(BlockDef block) { SymTabAST node = block.getTreeNode(); switch (node.getType()) { case TokenTypes.LITERAL_FOR : handleFor(block); break; case TokenTypes.LITERAL_IF : handleIf(block); break; case TokenTypes.LITERAL_WHILE : handleWhileAndSynchronized(block); break; case TokenTypes.LITERAL_DO : handleDoWhile(block); break; case TokenTypes.LITERAL_TRY : case TokenTypes.LITERAL_FINALLY : SymTabAST slist = node.findFirstToken(TokenTypes.SLIST); handleSList(slist, block); break; case TokenTypes.LITERAL_CATCH : handleCatch(block); break; case TokenTypes.LITERAL_SWITCH : handleSwitch(block); break; case TokenTypes.SLIST : handleSList(node, block); break; case TokenTypes.EXPR : resolveExpression(node, block, null, true); break; case TokenTypes.INSTANCE_INIT : case TokenTypes.STATIC_INIT : handleSList((SymTabAST) node.getFirstChild(), block); break; case TokenTypes.LITERAL_SYNCHRONIZED : handleWhileAndSynchronized(block); break; case TokenTypes.LITERAL_ASSERT : handleAssert(block); break; default : if (mInitialized) { final Log log = mLogFactory.getInstance(this.getClass()); log.error( "Unhandled block " + block + " of type " + node.getType()); } } } /** * @param block */ private void handleAssert(BlockDef block) { SymTabAST node = block.getTreeNode(); SymTabAST conditional = (node.findFirstToken(TokenTypes.EXPR)); resolveExpression(conditional, block, null, true); SymTabAST message = (SymTabAST) conditional.getNextSibling(); while ((message != null) && (message.getType() != TokenTypes.EXPR)) { message = (SymTabAST) message.getNextSibling(); } if (message != null) { resolveExpression(message, block, null, true); } } /** * processes a switch statement and resolves references in it * * @param block the BlockDef to process */ private void handleSwitch(BlockDef block) { SymTabAST node = block.getTreeNode(); SymTabAST expr = node.findFirstToken(TokenTypes.EXPR); resolveExpression(expr, block, null, true); SymTabAST caseGroup = (SymTabAST) (expr.getNextSibling()); while (caseGroup != null && (caseGroup.getType() != TokenTypes.CASE_GROUP)) { caseGroup = (SymTabAST) caseGroup.getNextSibling(); } if (caseGroup != null) { while (caseGroup.getType() == TokenTypes.CASE_GROUP) { SymTabAST caseNode = caseGroup.findFirstToken(TokenTypes.LITERAL_CASE); while (caseNode != null && caseNode.getType() == TokenTypes.LITERAL_CASE) { resolveExpression( (SymTabAST) caseNode.getFirstChild(), block, null, true); caseNode = (SymTabAST) caseNode.getNextSibling(); } SymTabAST caseSlist = caseGroup.findFirstToken(TokenTypes.SLIST); handleSList(caseSlist, block); caseGroup = (SymTabAST) (caseGroup.getNextSibling()); } } } /** * processes a catch block and resolves references in it * * @param block the BlockDef to process */ private void handleCatch(BlockDef block) { SymTabAST node = block.getTreeNode(); SymTabAST slist = node.findFirstToken(TokenTypes.SLIST); handleSList(slist, block); } /** * processes a for loop and resolves references in it * * @param block the BlockDef to process */ private void handleFor(BlockDef block) { SymTabAST node = block.getTreeNode(); SymTabAST body; SymTabAST forEach = node.findFirstToken(TokenTypes.FOR_EACH_CLAUSE); if (forEach == null) { SymTabAST init = node.findFirstToken(TokenTypes.FOR_INIT); // only need to handle the elist case. if the init node is a variable // definition, the variable def will be handled later on in the resolution if (init.getFirstChild() != null) { if (init.getFirstChild().getType() == TokenTypes.ELIST) { resolveExpression( (SymTabAST) (init.getFirstChild()), block, null, true); } } SymTabAST cond = node.findFirstToken(TokenTypes.FOR_CONDITION); if (cond.getFirstChild() != null) { resolveExpression( (SymTabAST) (cond.getFirstChild()), block, null, true); } SymTabAST iterator = node.findFirstToken(TokenTypes.FOR_ITERATOR); if (iterator.getFirstChild() != null) { resolveExpression( (SymTabAST) (iterator.getFirstChild()), block, null, true); } body = (SymTabAST) (iterator.getNextSibling()); } else { resolveExpression( (forEach.findFirstToken(TokenTypes.EXPR)), block, null, true); body = (SymTabAST) (forEach.getNextSibling()); } //could be an SLIST, EXPR or an EMPTY_STAT if (body.getType() == TokenTypes.RPAREN) { body = (SymTabAST) body.getNextSibling(); } if (body.getType() == TokenTypes.SLIST) { handleSList(body, block); } else { resolveExpression(body, block, null, true); } } /** * processes an if statement and resolves references in it * * @param block the BlockDef to process */ private void handleIf(BlockDef block) { SymTabAST node = block.getTreeNode(); SymTabAST conditional = (node.findFirstToken(TokenTypes.EXPR)); resolveExpression(conditional, block, null, true); SymTabAST body = (SymTabAST) conditional.getNextSibling(); // Handle Checkstyle grammar if (body.getType() == TokenTypes.RPAREN) { body = (SymTabAST) body.getNextSibling(); } if (body != null) { if (body.getType() == TokenTypes.SLIST) { handleSList(body, block); } else { resolveExpression(body, block, null, true); } SymTabAST elseBody = (SymTabAST) body.getNextSibling(); //handle Checkstyle grammar while ((elseBody != null) && (elseBody.getType() != TokenTypes.LITERAL_ELSE)) { elseBody = (SymTabAST) elseBody.getNextSibling(); } /* if (elseBody != null && elseBody.getType() == TokenTypes.SLIST) { handleSList(elseBody, block); }else{ resolveExpression(elseBody, block, null, true); } */ if (elseBody != null) { elseBody = (SymTabAST) elseBody.getFirstChild(); } if (elseBody != null) { resolveExpression(elseBody, block.getParentScope(), null, true); } } } /** * processes a while loop and resolves references in it * * @param block the BlockDef to process */ private void handleWhileAndSynchronized(BlockDef block) { SymTabAST node = block.getTreeNode(); SymTabAST condition = (node.findFirstToken(TokenTypes.EXPR)); SymTabAST slist = (SymTabAST) (condition.getNextSibling()); // handle Checkstyle grammar if (slist.getType() == TokenTypes.RPAREN) { slist = (SymTabAST) slist.getNextSibling(); } resolveExpression(condition, block, null, true); handleSList(slist, block); } private void handleDoWhile(BlockDef block) { SymTabAST node = block.getTreeNode(); SymTabAST slist = (SymTabAST) node.getFirstChild(); SymTabAST condition = node.findFirstToken(TokenTypes.EXPR); handleSList(slist, block); resolveExpression(condition, block, null, true); } /** * processes a variable definition and resolves references in it * * @param variable the VariableDef to process */ protected void handleVariable(VariableDef variable) { SymTabAST node = variable.getTreeNode(); Scope location = variable.getParentScope(); SymTabAST nameNode = node.findFirstToken(TokenTypes.IDENT); nameNode.setDefinition(variable, location, true); SymTabAST typeNode = node.findFirstToken(TokenTypes.TYPE); resolveType(typeNode, location, null, true); SymTabAST assignmentNode = node.findFirstToken(TokenTypes.ASSIGN); if (assignmentNode != null) { resolveExpression( (SymTabAST) (assignmentNode.getFirstChild()), variable.getParentScope(), null, true); } } /** * processes a label and resolves references in it * * @param label the LabelDef to process */ protected void handleLabel(LabelDef label) { SymTabAST node = label.getTreeNode(); ((SymTabAST) node.getFirstChild()).setDefinition( label, label.getParentScope(), true); } /** * Resolves Java expressions, returning the type to which the expression * evalutes. If this is the reference creation phase, any references found during resolution are created and * resolved. * * @param expression the SymTabAST representing the expression * @param location the Scope in which the expression occours. * @param context the Scope in which the search for the * definition will start * @param referencePhase whether or not this is the reference phase of * table construction * * @return the ClassDef representing the type to which the * expression evalutes. */ public IClass resolveExpression( SymTabAST expression, Scope location, IClass context, boolean referencePhase) { IClass result = null; try { switch (expression.getType()) { case TokenTypes.TYPECAST : result = resolveTypecast( expression, location, context, referencePhase); break; case TokenTypes.EXPR : case TokenTypes.LITERAL_RETURN : if (expression.getFirstChild() != null) { result = resolveExpression( (SymTabAST) expression.getFirstChild(), location, context, referencePhase); } else { // YOU WRITE BAD CODE! } break; case TokenTypes.ELIST : SymTabAST child = (SymTabAST) (expression.getFirstChild()); while (child != null) { if (child.getType() != TokenTypes.COMMA) { resolveExpression( child, location, context, referencePhase); } child = (SymTabAST) (child.getNextSibling()); } break; case TokenTypes.IDENT : result = resolveIdent( expression, location, context, referencePhase); break; case TokenTypes.TYPE : result = resolveType( expression, location, context, referencePhase); break; case TokenTypes.METHOD_CALL : //case TokenTypes.SUPER_CTOR_CALL : result = resolveMethod( expression, location, context, referencePhase); break; case TokenTypes.LITERAL_THIS : result = resolveLiteralThis(expression, location, context); break; case TokenTypes.LITERAL_SUPER : result = resolveLiteralSuper(expression, location, context); break; case TokenTypes.DOT : result = resolveDottedName( expression, location, context, referencePhase); break; case TokenTypes.LITERAL_NEW : case TokenTypes.CTOR_CALL : case TokenTypes.SUPER_CTOR_CALL : result = resolveNew( expression, location, context, referencePhase); break; case TokenTypes.LITERAL_BOOLEAN : case TokenTypes.LITERAL_DOUBLE : case TokenTypes.LITERAL_FLOAT : case TokenTypes.LITERAL_LONG : case TokenTypes.LITERAL_INT : case TokenTypes.LITERAL_SHORT : case TokenTypes.LITERAL_BYTE : case TokenTypes.LITERAL_CHAR : result = resolvePrimitiveType( expression, location, context, referencePhase); break; case TokenTypes.NUM_INT : case TokenTypes.NUM_LONG : result = resolveNumInt(expression, location, context); break; case TokenTypes.NUM_FLOAT : case TokenTypes.NUM_DOUBLE : result = resolveNumFloat(expression, location, context); break; case TokenTypes.STRING_LITERAL : result = resolveStringLiteral(expression, location, context); break; case TokenTypes.CHAR_LITERAL : result = resolveCharLiteral(expression, location, context); break; case TokenTypes.ASSIGN : case TokenTypes.PLUS_ASSIGN : case TokenTypes.MINUS_ASSIGN : case TokenTypes.STAR_ASSIGN : case TokenTypes.DIV_ASSIGN : case TokenTypes.MOD_ASSIGN : case TokenTypes.SR_ASSIGN : case TokenTypes.BSR_ASSIGN : case TokenTypes.SL_ASSIGN : case TokenTypes.BAND_ASSIGN : case TokenTypes.BXOR_ASSIGN : case TokenTypes.BOR_ASSIGN : resolveAssignment( expression, location, context, referencePhase); break; case TokenTypes.LOR : case TokenTypes.LAND : case TokenTypes.NOT_EQUAL : case TokenTypes.EQUAL : case TokenTypes.LT : case TokenTypes.GT : case TokenTypes.LE : case TokenTypes.GE : result = resolveBooleanExpression( expression, location, context, referencePhase); break; case TokenTypes.LITERAL_INSTANCEOF : result = resolveInstanceOf( expression, location, context, referencePhase); break; case TokenTypes.LITERAL_TRUE : case TokenTypes.LITERAL_FALSE : result = resolveBooleanLiteral(expression, location, context); break; case TokenTypes.LNOT : result = resolveBooleanUnary( expression, location, context, referencePhase); break; case TokenTypes.INC : case TokenTypes.POST_INC : case TokenTypes.DEC : case TokenTypes.POST_DEC : case TokenTypes.UNARY_PLUS : case TokenTypes.UNARY_MINUS : result = resolveUnaryExpression( expression, location, context, referencePhase); break; case TokenTypes.PLUS : case TokenTypes.MINUS : case TokenTypes.DIV : case TokenTypes.STAR : case TokenTypes.BAND : case TokenTypes.BOR : case TokenTypes.BXOR : case TokenTypes.MOD : result = resolveArithmeticExpression( expression, location, context, referencePhase); break; case TokenTypes.LITERAL_BREAK : case TokenTypes.LITERAL_CONTINUE : resolveGoto(expression, location, context, referencePhase); break; case TokenTypes.LPAREN : result = resolveExpression( //TODO: child || sibling? (SymTabAST) (expression.getNextSibling()), //(SymTabAST) (expression.getFirstChild()), location, context, referencePhase); break; case TokenTypes.INDEX_OP : result = resolveArrayAccess( expression, location, context, referencePhase); break; case TokenTypes.LITERAL_NULL : result = new NullClass(); break; case TokenTypes.QUESTION : result = resolveQuestion( expression, location, context, referencePhase); break; case TokenTypes.LITERAL_CLASS : result = resolveLiteralClass(); break; case TokenTypes.ARRAY_INIT : resolveArrayInitializer( expression, location, context, referencePhase); break; case TokenTypes.LITERAL_THROW : resolveThrowExpression( expression, location, context, referencePhase); break; case TokenTypes.SL : case TokenTypes.SR : case TokenTypes.BSR : result = resolveShiftOperator( expression, location, context, referencePhase); break; case TokenTypes.BNOT : resolveBitwiseNot( expression, location, context, referencePhase); break; case TokenTypes.LITERAL_ASSERT : // resolveAssert( // expression, // location, // context, // referencePhase); break; case TokenTypes.RPAREN : case TokenTypes.EMPTY_STAT : // case TokenTypes.ML_COMMENT: // case TokenTypes.SL_COMMENT: case TokenTypes.VARIABLE_DEF : case TokenTypes.METHOD_DEF : case TokenTypes.CLASS_DEF : case TokenTypes.LITERAL_FOR : case TokenTypes.LITERAL_WHILE : case TokenTypes.LITERAL_IF : case TokenTypes.LITERAL_VOID : // case TokenTypes.LITERAL_INTERFACE: case TokenTypes.LITERAL_DO : case TokenTypes.LITERAL_SWITCH : case TokenTypes.LITERAL_STATIC : case TokenTypes.LITERAL_TRANSIENT : case TokenTypes.LITERAL_NATIVE : // case TokenTypes.LITERAL_threadsafe: case TokenTypes.LITERAL_SYNCHRONIZED : case TokenTypes.LITERAL_VOLATILE : case TokenTypes.LITERAL_TRY : case TokenTypes.LITERAL_CATCH : case TokenTypes.LITERAL_FINALLY : case TokenTypes.LABELED_STAT : case TokenTypes.LCURLY : case TokenTypes.RCURLY : case TokenTypes.SLIST : case TokenTypes.SEMI : case TokenTypes.COMMA : case TokenTypes.ARRAY_DECLARATOR : break; default : //TODO: throw exception if (mInitialized) { final Log log = mLogFactory.getInstance(this.getClass()); log.error( "Unhandled expression type: " + expression.getType()); } break; } } catch (Exception e) { result = new UnknownClass(expression.getText(), expression); // TODO: This really should be logged // if (mInitialized) { // final Log log = mLogFactory.getInstance(this.getClass()); // log.error("Error resolving near " + expression); // } } return result; } private IClass resolveTypecast( SymTabAST node, Scope location, IClass context, boolean referencePhase) { SymTabAST typeNode = (SymTabAST) node.getFirstChild(); SymTabAST exprNode = (SymTabAST) typeNode.getNextSibling(); //handle Checkstyle grammar if (exprNode.getType() == TokenTypes.RPAREN) { exprNode = (SymTabAST) exprNode.getNextSibling(); } IClass type = null; final SymTabAST child = (SymTabAST) typeNode.getFirstChild(); // TODO: Checkstyle change. // Do not create references from typecast. // Original transmogrify code is equivalent to // final boolean createReference = referencePhase; // which creates non-existant references for variables. final boolean createReference = false; if (child.getType() == TokenTypes.ARRAY_DECLARATOR) { type = new ArrayDef( resolveType( (SymTabAST) typeNode.getFirstChild(), location, context, createReference)); } else { type = resolveType(typeNode, location, context, createReference); } resolveExpression(exprNode, location, context, referencePhase); //TODO: Checkstyle change. Can this be ignored? if (type != null) { ((SymTabAST) typeNode.getFirstChild()).setDefinition( type, location, referencePhase); } return type; } private IClass resolveArrayAccess( SymTabAST node, Scope location, IClass context, boolean referencePhase) { SymTabAST arrayNode = (SymTabAST) (node.getFirstChild()); SymTabAST exprNode = (SymTabAST) (arrayNode.getNextSibling()); //resolve index expressions while (arrayNode.getType() == TokenTypes.INDEX_OP) { resolveExpression(exprNode, location, context, referencePhase); arrayNode = (SymTabAST) (arrayNode.getFirstChild()); exprNode = (SymTabAST) (arrayNode.getNextSibling()); } ArrayDef array = (ArrayDef) resolveExpression(arrayNode, location, context, referencePhase); resolveExpression(exprNode, location, context, referencePhase); return array.getType(); } private IClass resolveLiteralClass() { return new ExternalClass(Class.class); } /** * Resolves any dotted reference, returning the Scope * identified by the reference. * * @param tree the root node of the dotted reference * @param location the Scope in which the expression occours. * @param context the Scope in which the search for the * definition will start * @return the Scope indentified by the reference */ private IClass resolveDottedName( SymTabAST tree, Scope location, IClass context, boolean referencePhase) { IClass result = null; IClass localContext = context; String name = null; DotIterator it = new DotIterator(tree); while (it.hasNext()) { SymTabAST node = it.nextNode(); if (node.getType() != TokenTypes.COMMA) { localContext = resolveExpression( node, location, localContext, referencePhase); if (localContext == null) { node.setMeaningfulness(false); name = node.getText(); while (localContext == null && it.hasNext()) { SymTabAST next = it.nextNode(); name = name + "." + next.getText(); localContext = location.getClassDefinition(name); if (localContext != null && referencePhase) { next.setDefinition( localContext, location, referencePhase); } else { next.setMeaningfulness(false); } } } } } if (localContext != null) { result = localContext; } else { result = new UnknownClass(name, tree); } return result; } /** * Resolves a method call. * * @param methodNode the SymTabAST for the METHOD_CALL node * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * @param referencePhase whether or not this is the reference phase of * table construction * * @return the ClassDef for the type returned by the method */ private IClass resolveMethod( SymTabAST methodNode, Scope location, IClass context, boolean referencePhase) { IClass result = new UnknownClass(methodNode.getText(), methodNode); IClass newContext = null; if (context == null) { newContext = location.getEnclosingClass(); } else { newContext = context; } String name = null; boolean createReference = true; SymTabAST nameNode = (SymTabAST) (methodNode.getFirstChild()); SymTabAST parametersNode = (SymTabAST) (nameNode.getNextSibling()); ISignature signature = resolveParameters( parametersNode, location, context, referencePhase); if (nameNode.getType() == TokenTypes.IDENT) { name = nameNode.getText(); } else if ( nameNode.getType() == TokenTypes.LITERAL_SUPER || (nameNode.getType() == TokenTypes.SUPER_CTOR_CALL)) { IClass superclass = location.getEnclosingClass().getSuperclass(); newContext = superclass; name = superclass.getName(); createReference = false; } else if (nameNode.getType() == TokenTypes.LITERAL_THIS) { newContext = location.getEnclosingClass(); name = newContext.getName(); createReference = false; } else { // REDTAG -- doing dotted name resolution on its own SymTabAST contextNode = (SymTabAST) (nameNode.getFirstChild()); //TODO: handle Checkstyle grammar nameNode = (SymTabAST) contextNode.getNextSibling(); //skip to IDENT while (nameNode.getType() != TokenTypes.IDENT) { nameNode = (SymTabAST) nameNode.getNextSibling(); } name = nameNode.getText(); newContext = resolveExpression( contextNode, location, context, referencePhase); } if (newContext != null) { IMethod method = newContext.getMethodDefinition(name, signature); if (method != null) { if (createReference && referencePhase) { nameNode.setDefinition(method, location, referencePhase); } result = method.getType(); } } if (result == null) { result = new UnknownClass(methodNode.getText(), methodNode); } return result; } /** * resolves a literal "this" * * @param expression the SymTabAST of the expression * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * * @return the resulting scope of the expression (the type to which it evaluates) */ private IClass resolveLiteralThis( SymTabAST thisNode, Scope location, IClass context) { return location.getEnclosingClass(); } /** * resolves a literal "super" * * @param expression the SymTabAST of the expression * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * * @return the resulting scope of the expression (the type to which it evaluates) */ private IClass resolveLiteralSuper( SymTabAST superNode, Scope location, IClass context) { return location.getEnclosingClass().getSuperclass(); } private boolean newIsConstructor(SymTabAST newNode) { boolean result = false; SymTabAST typeNode = (SymTabAST) (newNode.getFirstChild().getNextSibling()); //handle Checkstyle grammar if (typeNode.getType() == TokenTypes.LPAREN) { typeNode = (SymTabAST) typeNode.getNextSibling(); } if (typeNode.getType() == TokenTypes.ELIST) { result = true; } return result; } /** * resolves and expression of type TokenTypes.TYPE * * @param expression the SymTabAST of the expression * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * @param referencePhase whether or not this is the reference phase of * table construction * @return the resulting scope of the expression (the type to which it evaluates) * @see #resolveDottedName(SymTabAST, Scope, IClass, boolean) * @see #resolveClassIdent(SymTabAST, Scope, IClass, boolean) */ public IClass resolveType( SymTabAST expr, Scope location, IClass context, boolean referencePhase) { IClass result = null; SymTabAST nameNode = (SymTabAST) expr.getFirstChild(); // TODO: Checkstyle change. // Do not create references from typecast. // Original transmogrify code is equivalent to // final boolean createReference = referencePhase; // which creates non-existant references for variables. final boolean createReference = false; if (nameNode.getType() == TokenTypes.DOT) { result = resolveDottedName(nameNode, location, context, createReference); } else { result = resolveClassIdent(nameNode, location, context, createReference); } return result; } /** * resolves Class type expression * @param expr node to be resolved * @param location scope of the expr * @param context context of the expr if exists * @param referencePhase true if this method is used to during * finding reference phase * false otherwise * @return IClass representing the type to which the * expression evalutes. * @see #resolveDottedName(SymTabAST, Scope, IClass, boolean) */ public IClass resolveClass( SymTabAST expr, Scope location, IClass context, boolean referencePhase) { IClass result = resolveDottedName(expr, location, context, referencePhase); if (result != null && referencePhase) { expr.setDefinition(result, location, referencePhase); } return result; } /** * resolves expression with JavaTokenTypes other than DOT * @param expr expression to be resolved * @param location scope of the expression * @param context context of the expression if any * @param referencePhase true if this method is used to during * finding reference phase * false otherwise * @return IClass representing the type to which the * expression evalutes. */ public IClass resolveClassIdent( SymTabAST expr, Scope location, IClass context, boolean referencePhase) { IClass result = location.getClassDefinition(expr.getText()); if (result != null) { expr.setDefinition(result, location, referencePhase); } return result; } private IClass resolveNew( SymTabAST newNode, Scope location, IClass context, boolean referencePhase) { IClass result; if (newIsConstructor(newNode)) { result = resolveConstructor(newNode, location, context, referencePhase); } else { result = resolveNewArray(newNode, location, context, referencePhase); } return result; } private IClass resolveNewArray( SymTabAST newNode, Scope location, IClass context, boolean referencePhase) { IClass arrayType; SymTabAST typeNode = (SymTabAST) (newNode.getFirstChild()); SymTabAST declaratorNode = (SymTabAST) (typeNode.getNextSibling()); SymTabAST initializerNode = (SymTabAST) (declaratorNode.getNextSibling()); arrayType = resolveClass(typeNode, location, context, referencePhase); if (declaratorNode.getFirstChild() != null) { resolveExpression( ((SymTabAST) declaratorNode.getFirstChild()), location, context, referencePhase); } if (initializerNode != null) { resolveArrayInitializer( initializerNode, location, context, referencePhase); } return new ArrayDef(arrayType); } private IClass resolveQuestion( SymTabAST question, Scope location, IClass context, boolean referencePhase) { SymTabAST test = (SymTabAST) question.getFirstChild(); while (test.getType() == TokenTypes.LPAREN) { test = (SymTabAST) test.getNextSibling(); } SymTabAST leftBranch = (SymTabAST) test.getNextSibling(); while (leftBranch.getType() == TokenTypes.RPAREN) { leftBranch = (SymTabAST) leftBranch.getNextSibling(); } SymTabAST rightBranch = (SymTabAST) leftBranch.getNextSibling(); while (rightBranch.getType() != TokenTypes.COLON) { rightBranch = (SymTabAST) rightBranch.getNextSibling(); } rightBranch = (SymTabAST) rightBranch.getNextSibling(); resolveExpression(test, location, context, referencePhase); IClass leftClass = resolveExpression(leftBranch, location, context, referencePhase); IClass rightClass = resolveExpression(rightBranch, location, context, referencePhase); return moreGeneral(leftClass, rightClass); } private IClass moreGeneral(IClass a, IClass b) { return (a.isCompatibleWith(b)) ? b : a; } /** * Resolves a constructor call. * * @param tree the root node of the constructor call * @return the ClassDef for the class instantiated by the * constructor */ private IClass resolveConstructor( SymTabAST constructor, Scope location, IClass context, boolean referencePhase) { IClass classConstructed = null; SymTabAST nameNode = (SymTabAST) (constructor.getFirstChild()); //SymTabAST parametersNode = (SymTabAST) (nameNode.getNextSibling()); SymTabAST parametersNode = constructor.findFirstToken(TokenTypes.ELIST); SymTabAST nameIdent = null; if (nameNode.getType() == TokenTypes.IDENT) { nameIdent = nameNode; } else { nameIdent = (SymTabAST) nameNode.getFirstChild().getNextSibling(); } classConstructed = resolveClass(nameNode, location, context, false); if (classConstructed != null) { MethodSignature signature = resolveParameters( parametersNode, location, context, referencePhase); IMethod constructorDef = classConstructed.getMethodDefinition( nameIdent.getText(), signature); if (constructorDef != null && referencePhase) { nameIdent.setDefinition( constructorDef, location, referencePhase); } } return classConstructed; } /** * Resolves the types found in a method call. Any references found * in the process are created. Returns a MethodSignature for * the types of the parameters. * * @param elist The SymTabAST for the list of parameters * @return the signature of the parameters */ private MethodSignature resolveParameters( SymTabAST elist, Scope location, IClass context, boolean referencePhase) { Vector parameters = new Vector(); SymTabAST expr = (SymTabAST) (elist.getFirstChild()); while (expr != null) { if (expr.getType() != TokenTypes.COMMA) { IClass parameter = resolveExpression((SymTabAST) (expr .getFirstChild()), location, context, referencePhase); parameters.add(parameter); } expr = (SymTabAST) (expr.getNextSibling()); } return new MethodSignature(parameters); } /** * Resolves an IDENT node of an AST, creating the appropriate reference and * returning the scope of the identifer. * * @param ident the IDENT node * @param location the Scope in which the IDENT is found * @return the Scope the identifier identifies */ private IClass resolveIdent( SymTabAST ident, Scope location, IClass context, boolean referencePhase) { IClass result = null; IDefinition def = null; String name = ident.getText(); // look for var if (context != null) { def = context.getVariableDefinition(name); } else { def = location.getVariableDefinition(name); } if (def != null) { result = ((IVariable) def).getType(); } else { // look for class if (context != null) { result = context.getClassDefinition(name); } else { result = location.getClassDefinition(name); } def = result; } if (def != null) { ident.setDefinition(def, location, referencePhase); } return result; } /** * Resolves a (binary) boolean expression. The left and right sides of the * expression * are resolved in the process. * * @param expression the SymTabAST representing the boolean * expression. * @return the Scope for the boolean primitive type. */ private IClass resolveBooleanExpression( SymTabAST expression, Scope location, IClass context, boolean referencePhase) { IClass result = null; SymTabAST leftChild = findLeftChild(expression); resolveExpression(leftChild, location, context, referencePhase); SymTabAST rightChild = findRightSibling(leftChild); resolveExpression(rightChild, location, context, referencePhase); result = LiteralResolver.getDefinition(TokenTypes.LITERAL_BOOLEAN); return result; } /** * resolves references in an assignment expression * * @param expression the SymTabAST of the expression * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * * @return the resulting scope of the expression (the type to which it evaluates) */ private IClass resolveAssignment( SymTabAST expression, Scope location, IClass context, boolean referencePhase) { IClass result = null; SymTabAST leftNode = (SymTabAST) (expression.getFirstChild()); SymTabAST rightNode = (SymTabAST) (leftNode.getNextSibling()); result = resolveExpression(leftNode, location, context, referencePhase); resolveExpression(rightNode, location, context, referencePhase); return result; } /** * Resolves a unary expression. Returns the type of the expression, * creating any references found along the way. Unary expressions are * increment (x++), decrement (x--), unary plus (+x), and unary minus (-x) * * @param expression the SymTabAST of the unary expression. * @return the Scope for the type to which the expression * evalutes. */ private IClass resolveUnaryExpression( SymTabAST expression, Scope location, IClass context, boolean referencePhase) { SymTabAST operatee = (SymTabAST) (expression.getFirstChild()); return resolveExpression(operatee, location, context, referencePhase); } /** * Resolves an arithmetic expression. Returns the Scope for * the type to which the expression resolves. Any references found during * resolution are created and resolved. * * @param expression the SymTabAST representing the arithmetic * expression. * * @return the Scope for the type to which the expression * evaluates. */ private IClass resolveArithmeticExpression( SymTabAST expression, Scope location, IClass context, boolean referencePhase) { IClass result = null; SymTabAST leftChild = findLeftChild(expression); IClass leftType = (resolveExpression(leftChild, location, context, referencePhase)); SymTabAST rightChild = findRightSibling(leftChild); IClass rightType = (resolveExpression(rightChild, location, context, referencePhase)); result = binaryResultType(leftType, rightType); return result; } /** * Finds the left child of a binary operator, skipping parentheses. * @param aExpression the node for the binary operator. * @return the node for the left child. */ private SymTabAST findLeftChild(SymTabAST aExpression) { SymTabAST leftChild = (SymTabAST) (aExpression.getFirstChild()); // handle Checkstyle grammar while (leftChild.getType() == TokenTypes.LPAREN) { leftChild = (SymTabAST) leftChild.getNextSibling(); } return leftChild; } /** * Finds the right sibling of the left child of a binary operator, * skipping parentheses. * @param aLeftChild the left child of a binary operator. * @return the node of the right sibling. */ private SymTabAST findRightSibling(SymTabAST aLeftChild) { SymTabAST rightChild = (SymTabAST) (aLeftChild.getNextSibling()); // handle Checkstyle grammar while ((rightChild != null) && (rightChild.getType() == TokenTypes.RPAREN)) { rightChild = (SymTabAST) rightChild.getNextSibling(); } return rightChild; } /** * Returns the ClassDef for the type to which arithmetic * expressions evaluate. * * @param a the ClassDef of the first operand. * @param b the ClassDef of the second operand. * * @return the ClassDef to which the expression evaluates. */ private IClass binaryResultType(IClass a, IClass b) { IClass result = null; // These may or may not be in line with the rules set forth in the java // language specification. Not being in line would be a BadThing(r). IClass string = new ExternalClass(java.lang.String.class); if (a.equals(string) || b.equals(string)) { result = string; } else if (a.equals(PrimitiveClasses.BOOLEAN)) { result = PrimitiveClasses.BOOLEAN; } else { result = PrimitiveClasses.binaryPromote( a, b); } return result; } /** * resolves references in an instanceof expression * * @param expression the SymTabAST of the expression * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * * @return the resulting scope of the expression (the type to which it evaluates) */ private IClass resolveInstanceOf( SymTabAST expression, Scope location, IClass context, boolean referencePhase) { SymTabAST leftNode = (SymTabAST) (expression.getFirstChild()); SymTabAST rightNode = (SymTabAST) (leftNode.getNextSibling()); resolveExpression(leftNode, location, context, referencePhase); SymTabAST classNameNode = (SymTabAST) (rightNode.getFirstChild()); resolveClass(classNameNode, location, context, referencePhase); return LiteralResolver.getDefinition(TokenTypes.LITERAL_BOOLEAN); } /** * resolves references in a a break statement * * @param expression the SymTabAST for the expression * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * * @return the Scope for the int primitive type */ private IClass resolveGoto( SymTabAST expression, Scope location, IClass context, boolean referencePhase) { SymTabAST label = (SymTabAST) (expression.getFirstChild()); // handle Checkstyle grammar if (label != null && (label.getType() != TokenTypes.SEMI)) { LabelDef def = location.getLabelDefinition(label.getText()); if (def != null) { label.setDefinition(def, location, referencePhase); } } return null; } private IClass resolvePrimitiveType( SymTabAST primitive, Scope location, IClass context, boolean referencePhase) { IClass result = LiteralResolver.getDefinition(primitive.getType()); primitive.setDefinition(result, location, referencePhase); return result; } /** * Returns the ClassDef of the int primitive type. This may * need to be amended, based on the Java Language spec, to return a long * if the literal is larger than an int can hold. * * @param expression the SymTabAST for the integer literal * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * * @return the Scope for the int primitive type */ private IClass resolveNumInt( SymTabAST expression, Scope location, IClass context) { return PrimitiveClasses.INT; } /** * Returns the ClassDef type of the float primitive type. * This may need to be amended, based on the Java Language spec, to return * a double if the literal is larger than a float can hold. * * @param expression the SymTabAST for the floating point literal * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * * @return the Scope for the float primitive type */ private IClass resolveNumFloat( SymTabAST expression, Scope location, IClass context) { return PrimitiveClasses.DOUBLE; } /** * Returns the ClassDef type of a string literal * * @param expression the SymTabAST for a string literal * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * * @return the Scope type of a string literal */ private IClass resolveStringLiteral( SymTabAST expression, Scope location, IClass context) { return LiteralResolver.getDefinition( TokenTypes.STRING_LITERAL); } /** * Returns the ClassDef type of a character literal * * @param expression the SymTabAST for a string literal * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * * @return the Scope type of a character literal */ private IClass resolveCharLiteral( SymTabAST expression, Scope location, IClass context) { return LiteralResolver.getDefinition( TokenTypes.LITERAL_CHAR); } /** * Describe resolveBooleanLiteral method here. * * @param expression the SymTabAST of the expression * @param location the Scope where the expression occurs * @param context the Scope in which the expression occurs * (where the search for a defintion begins) * * @return the Scope for the boolean primitive. */ private IClass resolveBooleanLiteral( SymTabAST expression, Scope location, IClass context) { return LiteralResolver.getDefinition(TokenTypes.LITERAL_BOOLEAN); } private IClass resolveBooleanUnary( SymTabAST expression, Scope location, IClass context, boolean referencePhase) { SymTabAST child = (SymTabAST) expression.getFirstChild(); resolveExpression(child, location, context, referencePhase); return LiteralResolver.getDefinition(TokenTypes.LITERAL_BOOLEAN); } /** * Resolves a constructor call. * * @param tree the root node of the constructor call * @return the ClassDef for the class instantiated by the * constructor */ private void resolveArrayInitializer( SymTabAST initializerNode, Scope location, IClass context, boolean referencePhase) { SymTabAST child = (SymTabAST) (initializerNode.getFirstChild()); while (child != null) { if (child.getType() != TokenTypes.COMMA) { resolveExpression(child, location, context, referencePhase); } child = (SymTabAST) (child.getNextSibling()); } } /** * Resolves a constructor call. * * @param tree the root node of the constructor call * @return the ClassDef for the class instantiated by the * constructor */ private void resolveThrowExpression( SymTabAST throwNode, Scope location, IClass context, boolean referencePhase) { SymTabAST nameNode = (SymTabAST) (throwNode.getFirstChild()); resolveExpression(nameNode, location, context, referencePhase); } private IClass resolveShiftOperator( SymTabAST expression, Scope location, IClass context, boolean referencePhase) { IClass result = null; SymTabAST leftChild = findLeftChild(expression); SymTabAST rightChild = findRightSibling(leftChild); result = resolveExpression(leftChild, location, context, referencePhase); resolveExpression(rightChild, location, context, referencePhase); result = PrimitiveClasses.unaryPromote(result); return result; } private IClass resolveBitwiseNot( SymTabAST expression, Scope location, IClass context, boolean referencePhase) { IClass result = null; SymTabAST child = (SymTabAST) expression.getFirstChild(); result = resolveExpression(child, location, context, referencePhase); result = PrimitiveClasses.unaryPromote(result); return result; } } ././@LongLink100644 0 0 161 12026055133 10246 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/Scope.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 10062 11451071612 31463 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; /** * Represents a scope of Java code. * * @author andrew mccormick, dave wood * @version 1.0 * @since 1.0 * @see Definition * @see Resolvable */ public abstract class Scope extends Definition { // rename to references? protected SortedSet referencesInScope = new TreeSet(); protected Hashtable elements = new Hashtable(); protected Hashtable labels = new Hashtable(); protected Hashtable classes = new Hashtable(); public Scope( String name, Scope parentScope, SymTabAST node ) { super( name, parentScope, node ); } public void addDefinition(VariableDef def) { elements.put(def.getName(), def); } public void addDefinition(BlockDef def) { elements.put(def.getName(), def); } public void addDefinition(ClassDef def) { classes.put(def.getName(), def); } public void addDefinition(LabelDef def) { labels.put(def.getName(), def); } public abstract void addDefinition(IPackage def); protected Enumeration getDefinitions() { Vector allElements = new Vector(); allElements.addAll(elements.values()); allElements.addAll(labels.values()); allElements.addAll(classes.values()); return allElements.elements(); } protected Iterator getClasses() { return classes.values().iterator(); } public abstract IMethod getMethodDefinition(String name, ISignature signature); public abstract IVariable getVariableDefinition(String name); public abstract LabelDef getLabelDefinition(String name); public abstract IClass getClassDefinition(String name); public Iterator getReferencesIn() { return referencesInScope.iterator(); } public Reference getSymbol(String name, Occurrence location) { Reference result = null; for (Iterator it = getReferencesIn(); it.hasNext(); ) { Reference reference = (Reference)it.next(); // if (name.equals(reference.getName())) { if (reference.getLine() == location.getLine() && reference.getColumn() == location.getColumn()) { result = reference; break; } // } } return result; } public void addReferenceInScope( Reference reference ) { referencesInScope.add( reference ); } } ././@LongLink100644 0 0 166 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/ScopeIndex.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 11601 11451071612 31463 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Hashtable; import java.util.Vector; /** * ScopeIndex provides methods for finding Scopes * related to a known Occurrence */ public class ScopeIndex { //This is a Hashtable full of Vectors. The keys to this hashtable are filenames. //Each vector contains all of the scope objects from the specific file. private Hashtable indexOfFiles = new Hashtable(); public Hashtable getIndex() { return indexOfFiles; } /** * returns the most specific Scope to which the specified * Occurence belongs. * * @param occ the Occurrence whose Scope we're interested in. * @return Scope */ public Scope lookup(Occurrence occ) { String key = occ.getFile().getAbsolutePath(); Vector scopeList = getFileVector(key); Scope result = findScope(scopeList, occ); return result; } /** * returns the most specific Scope to which the specified * Occurence belongs from the specified Vector * of Scopes. * * @param occ the Occurrence whose Scope we're interested in. * @param scopeList the Vector of Scopes to chose from. * @return Scope */ public Scope findScope(Vector scopeList, Occurrence occ) { int i = 0; Scope bestSoFar = (Scope) scopeList.elementAt(i); while (!bestSoFar .getTreeNode() .getSpan() .contains(occ.getLine(), occ.getColumn())) { i++; bestSoFar = (Scope) scopeList.elementAt(i); } for (; i < scopeList.size(); i++) { Scope currentScope = (Scope) scopeList.elementAt(i); if (currentScope .getTreeNode() .getSpan() .contains(occ.getLine(), occ.getColumn())) { if (bestSoFar .getTreeNode() .getSpan() .contains(currentScope.getTreeNode().getSpan())) { bestSoFar = currentScope; } } } return bestSoFar; } /** * adds a Scope to the ScopeIndex for searching. * * @param scope the Scope to add. */ public void addScope(Scope scope) { final SymTabAST SymTabAST = scope.getTreeNode(); SymTabAST.getFile(); Vector fileVector = getFileVector(scope.getTreeNode().getFile().getAbsolutePath()); fileVector.addElement(scope); } /** * returns the Vector containing the Scopes related * to the specified filename. * * @param fileName the fileName to find scopes for. * @return Vector */ private Vector getFileVector(String fileName) { Vector result = (Vector) indexOfFiles.get(fileName); if (result == null) { result = new Vector(); indexOfFiles.put(fileName, result); } return result; } }././@LongLink100644 0 0 160 12026055133 10245 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/Span.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 11220 11451071612 31460 0ustar 0 0 //Transmogrify License // //Copyright (c) 2001, ThoughtWorks, Inc. //All rights reserved. //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions //are met: //- Redistributions of source code must retain the above copyright notice, //this list of conditions and the following disclaimer. //- Redistributions in binary form must reproduce the above copyright //notice, this list of conditions and the following disclaimer in the //documentation and/or other materials provided with the distribution. //Neither the name of the ThoughtWorks, Inc. nor the names of its //contributors may be used to endorse or promote products derived from this //software without specific prior written permission. //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS //"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED //TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR //PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR //CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, //EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, //PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; //OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, //WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR //OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF //ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; public class Span { private int _startLine; private int _startColumn; private int _endLine; private int _endColumn; public Span() {} public Span(int startLine, int startColumn, int endLine, int endColumn) { setStart(startLine, startColumn); setEnd(endLine, endColumn); } public Span( Span span ) { this( span.getStartLine(), span.getStartColumn(), span.getEndLine(), span.getEndColumn() ); } public void setStart(int startLine, int startColumn) { _startLine = startLine; _startColumn = startColumn; } public void setEnd(int endLine, int endColumn) { _endLine = endLine; _endColumn = endColumn; } public int getStartLine() { return _startLine; } public int getStartColumn() { return _startColumn; } public int getEndLine() { return _endLine; } public int getEndColumn() { return _endColumn; } public boolean contains( Span span ) { return ( contains(span.getStartLine(), span.getStartColumn()) && contains( span.getEndLine(), span.getEndColumn()) ); } public boolean contains(int line, int column) { boolean afterStart = false; boolean beforeEnd = false; if ( getStartLine() < line ) { afterStart = true; } else if ( getStartLine() == line && getStartColumn() <= column ) { afterStart = true; } if ( getEndLine() > line ) { beforeEnd = true; } else if ( getEndLine() == line && getEndColumn() >= column ) { beforeEnd = true; } return ( afterStart && beforeEnd ); } protected boolean startsBefore( Span span ) { boolean result = false; if ( getStartLine() < span.getStartLine() ) { result = true; } else if ( getStartLine() == span.getStartLine() && getStartColumn() <= span.getStartColumn() ) { result = true; } return result; } protected boolean endsAfter( Span span ) { boolean result = false; if ( getEndLine() > span.getEndLine() ) { result = true; } else if ( getEndLine() == span.getEndLine() && getEndColumn() >= span.getEndColumn() ) { result = true; } return result; } public void compose( Span span ) { if ( span.startsBefore( this ) ) { setStart( span.getStartLine(), span.getStartColumn() ); } if ( span.endsAfter( this ) ) { setEnd( span.getEndLine(), span.getEndColumn() ); } } public boolean equals(Object o) { boolean result = false; if ( o instanceof Span ) { Span span = (Span)o; result = ( span.getStartLine() == getStartLine() && span.getStartColumn() == getStartColumn() && span.getEndLine() == getEndLine() && span.getEndColumn() == getEndColumn() ); } return result; } public String toString() { return "[" + getStartLine() + "," + getStartColumn() + ":" + getEndLine() + "," + getEndColumn() + "]"; } } ././@LongLink100644 0 0 167 12026055133 10254 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/SymbolTable.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 16505 11451071612 31473 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.io.File; import java.util.Hashtable; import java.util.Stack; /** * this class contains all of the definitions, references, and scopes * created by the system. * * Other stuff this class does: *
    *
  • holds the "base" scope containing primitive definitions *
  • holds the java.lang package *
  • holds the definition of java.lang.Object, which is the base class * of all class hierarchies *
  • kicks off the resolve step *
  • does some of the work of constructing object definitions *
*/ public class SymbolTable { private Hashtable packages = new Hashtable(); private Stack scopes = new Stack(); private ScopeIndex index = new ScopeIndex(); private File currentFile; private BaseScope baseScope; private SymTabAST root; // private boolean outOfDate; /** * constructor takes SymTabAST * @param aRoot root of the SymTabAST tree */ public SymbolTable(SymTabAST aRoot) { scopes = new Stack(); this.root = aRoot; baseScope = new BaseScope( this ); pushScope(baseScope); } /** * gets the root node * @return SymTabAST */ public SymTabAST getTree() { return root; } // /** // * sets the outOfDate data member to true // * @return void // */ // public void expire() { // outOfDate = true; // } // // /** // * sets outOfDate member to false // * @param lastUpdated // * @return void // */ // public void update(long lastUpdated) { // outOfDate = false; // } /** * returns the "base" scope * * @return Scope the base scope */ // REDTAG -- this should eventually be replaced by a call // to the lookup method that traverses scopes public BaseScope getBaseScope() { return baseScope; } /** * returns the current scope. Scopes are nested in a stack (FIFO queue) * and pushed/popped based on the structure of the AST * @return Scope */ public Scope getCurrentScope() { return (Scope)scopes.peek(); } /** * pushes a new scope onto the stack * * @param scope the Scope to push * @return void */ public void pushScope(Scope scope) { scopes.push(scope); } /** * pops a scope from the stack. * * @return Scope * */ public Scope popScope() { Scope scope = (Scope)(scopes.pop()); return scope; } /** * gets all packages stored in this symbol table * @return Hashtable */ public Hashtable getPackages() { // REDTAG -- think about making this available as something simpler, // perhaps an enumeration return packages; } /** * gets package by its name * @param name * @return PackageDef */ public PackageDef getPackage( String name ) { return (PackageDef)(packages.get( name )); } /** * adds PackageDef to its parent scope and stores the * PackageDef in packages * @param pkg * @param parent * @return void */ public void definePackage( PackageDef pkg, Scope parent ) { parent.addDefinition(pkg); packages.put(pkg.getQualifiedName(), pkg); } /** * defines a class in the symbol table. * * @param def the class to define * @return void * @see #indexScope(Scope) * @see #getCurrentScope() */ public void defineClass(ClassDef def) { indexScope(def); getCurrentScope().addDefinition(def); } /** * defines a method in the symbol table * * @param method the method to be defined * @return void * @see #indexScope(Scope) * @see #getCurrentScope() */ public void defineMethod(MethodDef method) { indexScope(method); ((ClassDef)getCurrentScope()).addDefinition(method); } /** * defines a variable in the symbol table * * @param v the variable to define * @return void * @see #getCurrentScope() */ public void defineVariable(VariableDef v) { getCurrentScope().addDefinition(v); } /** * defines a block within the symbol table * * @param blockDef the block to define * @return void * @see #indexScope(Scope) * @see #getCurrentScope() */ public void defineBlock(BlockDef blockDef) { indexScope(blockDef); getCurrentScope().addDefinition(blockDef); } /** * defines a label within the symbol table * * @param labelDef the label to define * @return void * @see #getCurrentScope() */ // REDTAG -- label does not define a new scope public void defineLabel(LabelDef labelDef) { getCurrentScope().addDefinition(labelDef); } /** * places a scope in the symbol table's index * * @param scope the scope to index * @return void */ public void indexScope(Scope scope) { index.addScope(scope); } /** * gets the symbol table's scope index * * @return ScopeIndex */ public ScopeIndex getScopeIndex() { return index; } /** * sets the current file that the symbol table is processing * * @param file the File to use * @return void */ public void setCurrentFile(File file) { currentFile = file; } /** * gets the file that the symbol table is currently processing * * @return File */ public File getCurrentFile() { return currentFile; } } ././@LongLink100644 0 0 200 12026055133 10240 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/SymbolTableException.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 3425 11451071612 31450 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; public class SymbolTableException extends Exception { public SymbolTableException(String message) { super(message); } }././@LongLink100644 0 0 165 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/SymTabAST.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 40205 11451071612 31465 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.io.File; import antlr.collections.AST; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * an extension of antlr.CommonAST that includes * extra information about the AST's location. This information * is the file and line number where the AST was created. * * To use this AST node in your tree structure, assuming your * antlr.TreeParser is called parser, use * * parser.setASTNOdeCLass(SymTabAST.class.getName()); * * make sure you also call setTokenObjectClass for the lexer as well * * * @see SymTabToken */ //TODO: Should be an adapter of DetailAST public class SymTabAST extends antlr.CommonASTWithHiddenTokens { private Scope _scope; private IDefinition _definition = null; private boolean _isMeaningful = true; private File _file; private int _line; private int _column; // parent is not used by Checkstyle // private SymTabAST parent; private Span _span; /** original syntax tree node */ private DetailAST detailNode; // /** // * gets parent of this node // * @return SymTabAST // */ // public SymTabAST getParent() { // return parent; // } // /** // * gets previous sibling of this node // * @return SymTabAST // */ // public SymTabAST getPreviousSibling() { // return prevSibling; // } /** * sets parent of this node * @param parent * @return void */ public void setParent(SymTabAST parent) { //parent is not used by Checkstyle // this.parent = parent; } /** * gets the scope of this node * @return Scope */ public Scope getScope() { return _scope; } /** * sets the scope of this node * @param scope * @return void */ public void setScope(Scope scope) { _scope = scope; } /** * sets Definition for this node * @param definition * @param scope * @return void * @see #setDefinition(IDefinition, Scope, boolean) */ public void setDefinition(IDefinition definition, Scope scope) { setDefinition(definition, scope, true); } /** * sets Definition for this node and adds Reference * to the _definition and scope * @param definition * @param scope * @param createReference * @return void * @see net.sourceforge.transmogrify.symtab.Reference */ public void setDefinition( IDefinition definition, Scope scope, boolean createReference) { _definition = definition; Reference reference = new Reference(this); if (scope != null) { scope.addReferenceInScope(reference); } if (definition.isSourced() && createReference) { _definition.addReference(reference); } } /** * gets _definitin * @return IDefinition */ public IDefinition getDefinition() { return _definition; } /** * tests if this node is meaningful or should be ignored * @return boolean */ public boolean isMeaningful() { return _isMeaningful; } /** * sets _isMeaningful member * @param isMeaningful * @return void */ public void setMeaningfulness(boolean isMeaningful) { _isMeaningful = isMeaningful; } /** * sets meaningfulness for this node and its children * @return void * @see #setMeaningfulness(boolean) */ public void ignoreChildren() { if (getType() == TokenTypes.IDENT) { setMeaningfulness(false); } SymTabAST child = (SymTabAST) getFirstChild(); while (child != null) { child.ignoreChildren(); child = (SymTabAST) child.getNextSibling(); } } /** * sets file where this node belong to * @param file * @return void */ public void setFile(File file) { _file = file; } /** * finishes process for adding node to its parent * @param file file where this node belongs to * @param parent parent of this node * @param previousSibling previous sibling of this node * @return Span the span of this node * @see #setFile(File) * @see #setParent(SymTabAST) * @see #setPreviousSibling(SymTabAST) * @see #finishChildren(File) * @see #setSpan(Span) */ public Span finishDefinition( File file, SymTabAST parent) { setFile(file); setParent(parent); Span result = finishChildren(file); if (getLineNo() != 0) { result.compose( new Span( getLineNo(), getColumnNo(), getLineNo(), getColumnNo() + ((getText() == null) ? 0 : getText().length() - 1))); } setSpan(result); return result; } /** * finishes children of this node definition process * @param file file where this node belongs to * @return Span * @see #finishDefinition(File, SymTabAST, SymTabAST) */ public Span finishChildren(File file) { Span result = null; SymTabAST current = (SymTabAST) getFirstChild(); if (current == null) { result = getSpan(); } else { while (current != null) { Span childSpan = current.finishDefinition(file, this); if (childSpan != null) { if (result == null) { result = new Span(childSpan); } else { result.compose(childSpan); } } current = (SymTabAST) current.getNextSibling(); } } return result; } /** * gets file where this node belongs to * @return File */ public File getFile() { return _file; } /** * sets the line where this node reside * @return void */ public void setLine(int line) { _line = line; } /** * gets the line where this node reside * @return int */ public int getLineNo() { return _line; } /** * sets the column where this node reside * @param column */ public void setColumn(int column) { _column = column; } /** * gets the column where this node reside * @return int */ public int getColumnNo() { return _column; } /** * gets the definition name of this node * @return String * @see net.sourceforge.transmogrify.symtab.IDefinition */ public String getName() { String result = null; if (_definition != null) { result = _definition.getName(); } return result; } /** * prints the line, column and file for this node for debugging purpose * @return String */ public String toString() { //StringBuffer resultBuffer = new StringBuffer(super.toString()); StringBuffer resultBuffer = new StringBuffer(prefixString(true)); resultBuffer.append("[" + getLineNo() + "," + getColumnNo() + "]"); //if ( getSpan() != null ) { // resultBuffer.append( " spans " + getSpan() ); //} resultBuffer.append(" in " + getFile()); //resultBuffer.append(" type: " + getType()); return resultBuffer.toString(); } public String prefixString(boolean verboseStringConversion) { StringBuffer b = new StringBuffer(); try { final String name = TokenTypes.getTokenName(getType()); // if verbose and type name not same as text (keyword probably) if (verboseStringConversion && !getText().equalsIgnoreCase(name)) { b.append('['); b.append(getText()); b.append(",<"); b.append(name); b.append(">]"); return b.toString(); } } catch (Exception ex) { ; } return getText(); } /** * gets Span of this node * @return Span */ public Span getSpan() { if ((_span == null)) { int endColumn = getColumnNo() + 1; final String text = getText(); if (text != null) { endColumn += text.length() - 1; } _span = new Span(getLineNo(), getColumnNo() + 1, getLineNo(), endColumn); } return _span; } /** * sets Span for this node * @param span * @return void */ public void setSpan(Span span) { _span = span; } // not used by Checkstyle // /** // * tests if this node is inside the span // * @param line // * @param column // * @return boolean true if this node is within the span // * false otherwise // */ // public boolean contains(int line, int column) { // return getSpan().contains(line, column); // } /** * gets enclosing node for this node based on line and column * @param line * @param column * @return SymTabAST * @see #getSpan() */ public SymTabAST getEnclosingNode(int line, int column) { SymTabAST result = null; if ((getSpan() != null) && (getSpan().contains(line, column))) { SymTabAST child = (SymTabAST) getFirstChild(); while (child != null && result == null) { result = child.getEnclosingNode(line, column); child = (SymTabAST) child.getNextSibling(); } // if none of the children contain it, I'm the best node if (result == null) { result = this; } } return result; } public AST getFirstChild() { if (super.getFirstChild() == null) { DetailAST childDetailAST = null; final DetailAST detailAST = getDetailNode(); if (detailAST != null) { childDetailAST = (DetailAST) detailAST.getFirstChild(); if (childDetailAST != null) { final SymTabAST child = SymTabASTFactory.create(childDetailAST); setFirstChild(child); child.setParent(this); child.setFile(getFile()); } } } return super.getFirstChild(); } public AST getNextSibling() { if (super.getNextSibling() == null) { DetailAST siblingDetailAST = null; final DetailAST detailAST = getDetailNode(); if (detailAST != null) { siblingDetailAST = (DetailAST) detailAST.getNextSibling(); if (siblingDetailAST != null) { final SymTabAST sibling = SymTabASTFactory.create(siblingDetailAST); setNextSibling(sibling); // sibling.setParent(this.getParent()); sibling.setFile(getFile()); } } } return super.getNextSibling(); } /** * initialized this node with input node * @param aAST the node to initialize from. Must be a * DetailAST object. */ public void initialize(AST aAST) { if (aAST != null) { super.initialize(aAST); final DetailAST detailAST = (DetailAST) aAST; setDetailNode(detailAST); _column = detailAST.getColumnNo() + 1; _line = detailAST.getLineNo(); } } /** * Gets first occurence of the child node with a certain type * @param type * @return SymTabAST * @see #getType() */ public SymTabAST findFirstToken(int type) { SymTabAST result = null; AST sibling = getFirstChild(); while (sibling != null) { if (sibling.getType() == type) { result = (SymTabAST) sibling; break; } sibling = sibling.getNextSibling(); } return result; } // not used by Checkstyle // /** // * adds a node to the last position of this node children // * @param child // * @return void // */ // public void addChild(SymTabAST child) // { // SymTabAST lastChild = (SymTabAST) getFirstChild(); // if (lastChild == null) { // setFirstChild(child); // child.setParent(this); // child.setNextSibling(null); // } // else { // while (lastChild.getNextSibling() != null) { // lastChild = (SymTabAST) lastChild.getNextSibling(); // } // lastChild.setNextSibling(child); // child.setNextSibling(null); // child.setParent(this); // } // } /** * Gets Iterator for this node * @return SymTabASTIterator */ public SymTabASTIterator getChildren() { return new SymTabASTIterator(this); } /** * Returns the DetailAST associated with this node. * @return the DetailAST associated with this node. */ public DetailAST getDetailNode() { return detailNode; } /** * Sets the DetailAST associated with this node. * @param aDetailAST the DetailAST associated with this node. */ public void setDetailNode(DetailAST aDetailAST) { detailNode = aDetailAST; ASTManager.getInstance().put(aDetailAST, this); } }././@LongLink100644 0 0 174 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/SymTabASTFactory.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 5550 11451071612 31451 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import antlr.ASTFactory; import antlr.collections.AST; /** * Factory for SymTabAST objects. * @author Rick Giles */ public class SymTabASTFactory { /** singleton factory */ private static ASTFactory factory; static { factory = new ASTFactory(); factory.setASTNodeClass(SymTabAST.class.getName()); } /** * Creates a SymTabAST with a given type and text. * @param aType the type for the new SymTabAST. * @param aText the text for the new SymTabAST. * @return the new SymTabAST. */ public static SymTabAST create(int aType, String aText) { return (SymTabAST) factory.create(aType, aText); } /** * Creates an SymTabAST from a given AST. * @param aAST the AST for the new SymTabAST. * @return the new SymTabAST. */ public static SymTabAST create(AST aAST) { return (SymTabAST) factory.create(aAST); } ///CLOVER:OFF /** prevent instantiation */ private SymTabASTFactory() { } ///CLOVER:ON } ././@LongLink100644 0 0 175 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/SymTabASTIterator.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 5771 11451071612 31456 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Iterator; import java.util.NoSuchElementException; /** * An iterator for the children of a tree node. * * @version 1.0 * @since 1.0 * @see Iterator */ public class SymTabASTIterator implements Iterator { private SymTabAST _current; /** * Creates a new SymTabASTIterator. * * @param parent the node whose children will be iterated over. */ public SymTabASTIterator(SymTabAST parent) { _current = (SymTabAST)parent.getFirstChild(); } /** * Whether the node has another child. (In other words, returns * true if next would return an element rather than * throwing an exception.) * * @return the next child node. */ public boolean hasNext() { return (_current != null); } /** * The next child node. * * @return the next child node. */ public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } Object result = _current; _current = (SymTabAST)_current.getNextSibling(); return result; } /** * The next child node. * * @return the next child node. */ public SymTabAST nextChild() { return (SymTabAST)next(); } /** * Unsupported operation */ public void remove() { throw new UnsupportedOperationException(); } } ././@LongLink100644 0 0 166 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/TableMaker.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 130210 11451071612 31501 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.io.File; import java.util.Enumeration; import java.util.Vector; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * this is the class that does the work of the "walking" step -- * going through the SymTabAST and constructing the definitions and * references. The SymTabAST is constructed in a DOMish fashion, i.e. * each node knows about its first child and its next sibling. The * DFS search is carried out by two functions -- walkTree, which * deals with a single SymTabAST node, and walkSibilngs, which deals with * all the siblings of an SymTabAST node. */ public class TableMaker { private SymbolTable symbolTable; private SymTabAST _tree; private File currentFile; private Vector imports = new Vector(); /** * Constructor for the TableMaker class * * @param tree is theSymTabAST from which to * build the TableMaker. It is the tree which wil be walked * in order to build definitions and references. */ public TableMaker(SymTabAST tree) { _tree = tree; } /** * returns the SymTabAST which is the * SymTabAST generated from the parsed Java Source files. * * @return SymTabAST */ public SymTabAST getTree() { return _tree; } /** * returns the SymbolTable that has been constructed by * this TableMaker * * @return SymbolTable * @throws SymbolTableException */ public SymbolTable getTable() throws SymbolTableException { if (symbolTable == null) { symbolTable = new SymbolTable( _tree ); createDefinitions(); resolveReferences(); } return symbolTable; } /** * walks the tree and finishes creating definitions. * * @return void * @throws SymbolTableException * @see #walkTree() * @see #finishCreatingDefinitions() */ private void createDefinitions() throws SymbolTableException { walkTree(); finishCreatingDefinitions(); } /** * finishes up creating definitions process * starts at the base of the Table * * @return void * @throws SymbolTableException * @see net.sourceforge.transmogrify.symtab.SymbolTable * @see #finishCreatingDefinition(Definition) */ private void finishCreatingDefinitions() throws SymbolTableException { finishCreatingDefinition(symbolTable.getBaseScope()); } /** * begins at the base of the Table and starts finishing definition creation. * * @param def Definition needs to be completed * @return void * @throws SymbolTableException * @see ClassFinisher * @see VariableFinisher * @see MethodFinisher * @see CatchFinisher */ private void finishCreatingDefinition(Definition def) throws SymbolTableException { if (def instanceof AnonymousInnerClass) { AnonymousInnerClass innerClass = (AnonymousInnerClass)def; innerClass.finishMakingDefinition(); } else if (def instanceof ClassDef) { new ClassFinisher(def).finish(); } else if ( def instanceof VariableDef ) { new VariableFinisher( def ).finish(); } else if (def instanceof DefaultConstructor) {} else if ( def instanceof MethodDef ) { new MethodFinisher( def ).finish(); } else if (def instanceof BlockDef) { SymTabAST firstChild = (SymTabAST)def.getTreeNode().getFirstChild(); //handle Checkstyle grammar if (firstChild.getType() == TokenTypes.LPAREN) { firstChild = (SymTabAST) firstChild.getNextSibling(); } if (firstChild.getType() == TokenTypes.PARAMETER_DEF) { // this is a catch block new CatchFinisher((BlockDef)def).finish(); } } if ( def instanceof Scope ) { finishCreatingChildren((Scope)def); } } /** * iterates through all the definitions in the Scope * finishes creating each Scope. * * @param scope Scope where defininitions will be finished. * @return void * @throws SymbolTableException * @see net.sourceforge.transmogrify.symtab.Scope * @see #finishCreatingDefinition(Definition) */ private void finishCreatingChildren( Scope scope ) throws SymbolTableException { Enumeration definitions = scope.getDefinitions(); while ( definitions.hasMoreElements() ) { Definition child = (Definition)(definitions.nextElement()); finishCreatingDefinition(child); } } /** * resolves SymbolTable using Resolver * * @return void * @see net.sourceforge.transmogrify.symtab.Resolver * @see net.sourceforge.transmogrify.symtab.SymbolTable */ private void resolveReferences() { new Resolver( symbolTable ).resolve(); } /** * starts walking the SymTabAST * * @return void * @see #walkSiblings(SymTabAST,boolean) * @see net.sourceforge.transmogrify.symtab.antlr.SymTabAST */ public void walkTree() { walkSiblings((SymTabAST)_tree.getFirstChild(), false); } /** * processes a single SymTabAST node based on its type and passes of its * children for further processing where appropriate. * * @param tree the SymTabAST node to process * @param makeAnonymousScopes sets to false after walking Class, * Methods and Try otherwise sets to true * @return void * @see #walkSiblings(SymTabAST, boolean) * @see #processAnonymousInnerClass(SymTabAST, SymTabAST) * @see #processBlock(SymTabAST, boolean) * @see #processClass(SymTabAST) * @see #processConstructorDef(SymTabAST) * @see #processElse(SymTabAST) * @see #processFile(SymTabAST) * @see #processFinally(SymTabAST) * @see #processFor(SymTabAST) * @see #processImplicitPackage(SymTabAST) * @see #processImport(SymTabAST) * @see #processLabel(SymTabAST) * @see #processMethodDef(SymTabAST) * @see #processPackage(SymTabAST) * @see #processTry(SymTabAST) * @see net.sourceforge.transmogrify.symtab.antlr.SymTabAST * @see net.sourceforge.transmogrify.symtab.antlr.JavaTokenTypes */ public void walkTree(SymTabAST tree, boolean makeAnonymousScopes) { if (tree != null) { tree.setScope( symbolTable.getCurrentScope() ); switch(tree.getType()) { case 0: processFile(tree); if ( tree.getFirstChild().getType() != TokenTypes.PACKAGE_DEF ) { processImplicitPackage( tree.getFile() ); } walkSiblings((SymTabAST)tree.getFirstChild(), false); // pop package scope symbolTable.popScope(); clearImports(); break; case TokenTypes.LITERAL_NEW: SymTabAST symtabTree = tree; //walk parameters, in case of anonymous inner class walkTree(symtabTree.findFirstToken(TokenTypes.ELIST), makeAnonymousScopes); SymTabAST objblock = symtabTree.findFirstToken(TokenTypes.OBJBLOCK); if (objblock != null) { SymTabAST classExtended = symtabTree.findFirstToken(TokenTypes.IDENT); processAnonymousInnerClass(objblock, classExtended); } break; case TokenTypes.SLIST: if (makeAnonymousScopes) { processBlock(tree, true); } else { walkSiblings((SymTabAST)tree.getFirstChild(), true); } break; case TokenTypes.CTOR_DEF: processConstructorDef(tree); break; case TokenTypes.METHOD_DEF: processMethodDef(tree); break; case TokenTypes.LITERAL_FINALLY: processFinally(tree); break; case TokenTypes.LITERAL_TRY: processTry(tree); break; case TokenTypes.VARIABLE_DEF: processVariableDef(tree); break; case TokenTypes.PACKAGE_DEF: processPackage(tree); break; case TokenTypes.LABELED_STAT: processLabel(tree); break; case TokenTypes.IMPORT: processImport(tree); break; case TokenTypes.CLASS_DEF: case TokenTypes.INTERFACE_DEF: processClass(tree); break; case TokenTypes.LITERAL_FOR: processFor(tree); break; case TokenTypes.LITERAL_IF: processIf(tree); break; case TokenTypes.LITERAL_ASSERT: processAssert(tree); break; case TokenTypes.LITERAL_CATCH: case TokenTypes.LITERAL_WHILE: case TokenTypes.LITERAL_SWITCH: case TokenTypes.LITERAL_DO: case TokenTypes.LITERAL_SYNCHRONIZED: case TokenTypes.STATIC_INIT: case TokenTypes.INSTANCE_INIT: processBlock(tree, false); break; default: walkSiblings((SymTabAST)tree.getFirstChild(), false); } } } /** * @param tree */ public void processAssert(SymTabAST tree) { BlockDef block = makeBlock(tree); SymTabAST expr = tree.findFirstToken(TokenTypes.EXPR); SymTabAST message = (SymTabAST)expr.getNextSibling(); while ((message != null) && (message.getType() != TokenTypes.EXPR)) { message = (SymTabAST) message.getNextSibling(); } symbolTable.pushScope( block ); walkTree(expr, false); if (message != null) { walkTree(message, false); } symbolTable.popScope(); } /** * processes the given SymTabAST and each of its siblings * * @param tree SymTabAST node to process * @param makeAnonymousScopes * * @return void * @see #walkTree(SymTabAST, boolean) * @see net.sourceforge.transmogrify.symtab.antlr.SymTabAST */ public void walkSiblings(SymTabAST tree, boolean makeAnonymousScopes) { while(tree != null) { walkTree(tree, makeAnonymousScopes); tree = (SymTabAST)tree.getNextSibling(); } } /** * processes the given SymTabAST as a package defintion * * @param tree the SymTabAST to process * @return void * @see net.sourceforge.transmogrify.symtab.antlr.SymTabAST * @see net.sourceforge.transmogrify.symtab.PackageDef * @see net.sourceforge.transmogrify.symtab.SymbolTable */ public void processPackage(SymTabAST tree) { SymTabAST firstChild = (SymTabAST)tree.getFirstChild(); String name = ASTUtil.constructDottedName(firstChild); firstChild.ignoreChildren(); PackageDef pkg = symbolTable.getPackage(name); if (pkg == null) { pkg = createPackage( (SymTabAST)(tree.getFirstChild()) ); } symbolTable.pushScope(pkg); } /** * processes a java class that use default no package * * @param file File object of the java class * @return void * @see net.sourceforge.transmogrify.symtab.PackageDef * @see net.sourceforge.transmogrify.symtab.SymbolTable */ public void processImplicitPackage( File file ) { String name = file.getParent(); if (name == null) { name = ""; } PackageDef pkg = symbolTable.getPackage( name ); if ( pkg == null ) { pkg = new PackageDef( name, symbolTable.getBaseScope(), null ); symbolTable.definePackage( pkg, symbolTable.getBaseScope() ); } symbolTable.pushScope( pkg ); } /** * gets the package represented by the tree. The method * analyzes the tree, constructs an appropriate package name * and fetches it from the internal package list. If the package does not * exist it is created. * * @param tree SymTabAST to consider * * @return PackageDef the resulting package definition * @see #getPackage(Scope, SymTabAST) */ private PackageDef createPackage( SymTabAST tree ) { PackageDef result = null; if (tree.getType() == TokenTypes.DOT) { // find the package result of left child SymTabAST leftChild = (SymTabAST)tree.getFirstChild(); SymTabAST rightChild = (SymTabAST)leftChild.getNextSibling(); PackageDef context = createPackage(leftChild); result = getPackage( context, rightChild ); } else { result = getPackage(symbolTable.getBaseScope(), tree); } return result; } /** * gets the package determined by the tree and parent package def. * The method analyzes the tree and parent scope and retrieves the * appropriate package definition from the internal package list. * If the package does not exist it is created. * * @param tree SymTabAST to consider * @param parent the parent package definition * * @return PackageDef the resulting package definition * @see net.sourceforge.transmogrify.symtab.PackageDef * @see net.sourceforge.transmogrify.symtab.SymbolTable * @see net.sourceforge.transmogrify.symtab.antlr.SymTabAST */ private PackageDef getPackage(Scope parent, SymTabAST tree ) { String name = tree.getText(); PackageDef result = null; if (!(parent instanceof BaseScope)) { result = symbolTable.getPackage(parent.getQualifiedName() + "." + name); } else { result = symbolTable.getPackage(name); } if (result == null) { result = new PackageDef(tree.getText(), parent, tree); symbolTable.definePackage(result, parent); } return result; } /** * process the given SymTabAST as a file definition * * @param tree the SymTabAST to process * @return void * @see #setCurrentFile(String) */ public void processFile(SymTabAST tree) { setCurrentFile(tree.getText()); } /** * adds the given SymTabAST to imports member * * @param tree the SymTabAST to process * @return void */ public void processImport(SymTabAST tree) { imports.add( tree ); } /** * clears the imports member * @return void */ private void clearImports() { imports.clear(); } /** * process the given SymTabAST as a label definition * * @param tree the SymTabAST to process * @return void * @see com.trwx.symtab.antlr.SymTabAST * @see net.sourceforge.transmogrify.symtab.LabelDef * @see #walkTree(SymTabAST, boolean) */ public void processLabel(SymTabAST tree) { String name = tree.findFirstToken(TokenTypes.IDENT).getText(); LabelDef label = new LabelDef( name, symbolTable.getCurrentScope(), tree ); symbolTable.defineLabel( label ); walkTree((SymTabAST)tree.getFirstChild().getNextSibling(), false); } /** * process the given SymTabAST as a class definition * * @param tree the SymTabAST to process * @return void * @see #makeClass(String, SymTabAST) * @see #walkSiblings(SymTabAST, boolean) * @see net.sourceforge.transmogrify.symtab.antlr.SymTabAST */ public void processClass(SymTabAST tree) { String name = tree.findFirstToken(TokenTypes.IDENT).getText(); makeClass(name, tree); final SymTabAST objblock = tree.findFirstToken(TokenTypes.OBJBLOCK); SymTabAST start = (SymTabAST)objblock.getFirstChild(); if (start != null) { //skip LPAREN if (start.getType() == TokenTypes.LPAREN) { start = (SymTabAST)start.getNextSibling(); } walkSiblings(start, false); } symbolTable.popScope(); } /** * creates ClassDef for the current class node and add it to the * symbol table * @param name name of the class * @param tree current node to be processed * @return void * @see net.sourceforge.transmogrify.symtab.ClassDef * @see net.sourceforge.transmogrify.symtab.SymbolTable */ public void makeClass(String name, SymTabAST tree) { ClassDef def = new ClassDef(name, symbolTable.getCurrentScope(), tree); def.addUnprocessedImports(imports); symbolTable.defineClass(def); symbolTable.pushScope(def); } /** * processes anonymous inner class encountered in the tree * @param objblock the anonymous block * @param classExtended * @return void * @see net.sourceforge.transmogrify.symtab.AnonymousInnerClass * @see net.sourceforge.transmogrify.symtab.SymbolTable */ public void processAnonymousInnerClass(SymTabAST objblock, SymTabAST classExtended) { ClassDef def = new AnonymousInnerClass(objblock, classExtended, symbolTable.getCurrentScope()); symbolTable.defineClass(def); symbolTable.pushScope(def); walkSiblings((SymTabAST)objblock.getFirstChild(), false); symbolTable.popScope(); } /** * process the given SymTabAST as a variable definition * * @param tree the SymTabAST to process * @return void * @see net.sourceforge.transmogrify.symtab.VariableDef * @see net.sourceforge.transmogrify.symtab.SymbolTable * @see net.sourceforge.transmogrify.symtab.antlr.SymTabAST * @see #makeVariableDef(SymTabAST, Scope) * @see #walkTree(SymTabAST, boolean) */ private void processVariableDef(SymTabAST tree) { VariableDef def = makeVariableDef( tree, symbolTable.getCurrentScope() ); symbolTable.defineVariable(def); SymTabAST assignmentNode = tree.findFirstToken(TokenTypes.ASSIGN); if (assignmentNode != null) { walkTree((SymTabAST)assignmentNode.getFirstChild(), false); } } /** * creates VariableDef based on the current tree node and scope * @param tree the current tree node * @param scope the current scope * @return VariableDef * @see net.sourceforge.transmogrify.symtab.VariableDef */ public VariableDef makeVariableDef(SymTabAST tree, Scope scope) { String name = tree.findFirstToken(TokenTypes.IDENT).getText(); VariableDef result = new VariableDef(name, scope, tree); return result; } /** * process the given SymTabAST as a try block * * @param tree the SymTabAST to process * @return void * @see #makeBlock(SymTabAST) * @see net.sourceforge.transmogrify.symtab.antlr.SymTabAST * @see #walkTree(SymTabAST, boolean) * @see #walkSiblings(SymTabAST, boolean) */ public void processTry(SymTabAST tree){ BlockDef block = makeBlock(tree); SymTabAST slist = tree.findFirstToken(TokenTypes.SLIST); SymTabAST everythingElse = (SymTabAST)slist.getNextSibling(); symbolTable.pushScope( block ); walkTree( slist, false ); symbolTable.popScope(); walkSiblings( everythingElse, false ); } /** * process the given SymTabAST as a finally block * * @param tree the SymTabAST to process * @return void * @see #makeBlock(SymTabAST) * @see #walkTree(SymTabAST, boolean) */ public void processFinally(SymTabAST tree){ BlockDef block = makeBlock(tree); SymTabAST slist = tree.findFirstToken(TokenTypes.SLIST); SymTabAST tryBlock = tree.findFirstToken(TokenTypes.LITERAL_TRY); symbolTable.pushScope( block ); walkTree( slist, false ); symbolTable.popScope(); walkTree( tryBlock, false ); } /** * process the given SymTabAST as a method definition * * @param tree the SymTabAST to process * @return void * @see net.sourceforge.transmogrify.symtab.MethodDef * @see net.sourceforge.transmogrify.symtab.SymbolTable * @see #walkTree(SymTabAST, boolean) */ public void processMethodDef(SymTabAST tree) { String name = tree.findFirstToken(TokenTypes.IDENT).getText(); MethodDef method = new MethodDef(name, symbolTable.getCurrentScope(), tree); symbolTable.defineMethod( method ); symbolTable.pushScope( method ); walkTree(tree.findFirstToken(TokenTypes.SLIST), false); symbolTable.popScope(); } /** * process the given SymTabAST as a constructor definition * * @param tree the SymTabAST to process * @return void * @see net.sourceforge.transmogrify.symtab.MethodDef * @see net.sourceforge.transmogrify.symtab.SymbolTable * @see #walkTree(SymTabAST, boolean) */ public void processConstructorDef(SymTabAST tree) { processMethodDef(tree); } /** * process the given SymTabAST as a for block * * @param tree the SymTabAST to process * @return void * @see #makeBlock(SymTabAST) * @see #walkTree(SymTabAST, boolean) */ public void processFor(SymTabAST tree) { BlockDef block = makeBlock(tree); symbolTable.pushScope( block ); SymTabAST body; SymTabAST forEach = tree.findFirstToken(TokenTypes.FOR_EACH_CLAUSE); if (forEach != null) { walkTree(forEach, false); body = (SymTabAST)forEach.getNextSibling(); } else { walkTree(tree.findFirstToken(TokenTypes.FOR_INIT), false); walkTree(tree.findFirstToken(TokenTypes.FOR_CONDITION), false); SymTabAST forIter = tree.findFirstToken(TokenTypes.FOR_ITERATOR); walkTree(forIter, false); body = (SymTabAST)forIter.getNextSibling(); } //handle Checkstyle grammar if (body.getType() == TokenTypes.RPAREN) { body = (SymTabAST) body.getNextSibling(); } walkTree(body, false); symbolTable.popScope(); } /** * process the given SymTabAST as an if block * * @param tree the SymTabAST to process * @return void * @see #makeBlock(SymTabAST) * @see #walkTree(SymTabAST, boolean) * @see #processElse(SymTabAST) */ public void processIf(SymTabAST tree) { BlockDef block = makeBlock(tree); SymTabAST expr = tree.findFirstToken(TokenTypes.EXPR); SymTabAST ifBranch = (SymTabAST)expr.getNextSibling(); // handle Checkstyle grammar if (ifBranch.getType() == TokenTypes.RPAREN) { ifBranch = (SymTabAST) ifBranch.getNextSibling(); } SymTabAST elseBranch = (SymTabAST)ifBranch.getNextSibling(); // handle Checkstyle grammar if ((elseBranch != null) && (elseBranch.getType() == TokenTypes.SEMI)) { elseBranch = (SymTabAST) elseBranch.getNextSibling(); } if ((elseBranch != null) && (elseBranch.getType() == TokenTypes.LITERAL_ELSE)) { elseBranch = (SymTabAST) elseBranch.getFirstChild(); } symbolTable.pushScope( block ); walkTree(expr, false); walkTree(ifBranch, false); symbolTable.popScope(); processElse(elseBranch); } /** * process the given SymTabAST as an else block * * @param tree the SymTabAST to process * @return void * @see #processIf(SymTabAST) * @see #makeElseBlock(SymTabAST) */ public void processElse(SymTabAST tree) { if (tree != null) { if (tree.getType() == TokenTypes.LITERAL_IF) { processIf(tree); } else { makeElseBlock(tree); } } } /** * defines an anonymous block to enclose the scope of an else block * * @param tree the SymTabAST to process * @return void * @see #makeBlock(SymTabAST) * @see #walkTree(SymTabAST, boolean) */ public void makeElseBlock(SymTabAST tree) { if (tree.getType() == TokenTypes.SLIST) { BlockDef block = makeBlock(tree); symbolTable.pushScope( block ); walkTree(tree, false); symbolTable.popScope(); } else { walkTree(tree, false); } } /** * processes the current tree node as BlockDef * @param tree current tree node * @param makeAnonymousScopes * @return void */ public void processBlock(SymTabAST tree, boolean makeAnonymousScopes) { BlockDef block = makeBlock(tree); symbolTable.pushScope(block); //handle Checkstyle grammar SymTabAST child = (SymTabAST)tree.getFirstChild(); if ((child != null) && (child.getType() == TokenTypes.LPAREN)) { child = (SymTabAST) child.getNextSibling(); } walkSiblings(child, makeAnonymousScopes); symbolTable.popScope(); } /** * set the current file to the named file * * @param fileName the name of the file * @return void */ public void setCurrentFile(String fileName) { currentFile = new File(fileName); symbolTable.setCurrentFile(currentFile); } /** * creates a new BlockDef in the SymbolTable * * @param tree is a SymTabAST whose root begins the new block * @return BlockDef * @see net.sourceforge.transmogrify.symtab.BlockDef * @see net.sourceforge.transmogrify.symtab.SymbolTable */ private BlockDef makeBlock( SymTabAST tree ) { BlockDef block = new BlockDef( symbolTable.getCurrentScope(), tree ); symbolTable.defineBlock( block ); return block; } /** * returns the SymTabAST that contains the parameter classDef's * extends nodes * * @param classDef is a ClassDef whose extends nodes we want * @return SymTabAST */ public static SymTabAST getExtendsNode(ClassDef classDef) { SymTabAST result = null; SymTabAST extendsClause = null; SymTabAST classDefTreeNode = classDef.getTreeNode(); extendsClause = classDefTreeNode.findFirstToken(TokenTypes.EXTENDS_CLAUSE); if (extendsClause != null) { result = (SymTabAST)(extendsClause.getFirstChild()); } return result; } /** * Superclass for different kind of XXXFinisher subclass * @see CatchFinisher * @see ClassFinisher * @see DefinitionFinisher * @see MethodFinisher * @see VariableFinisher */ class DefinitionFinisher { protected SymTabAST _node = null; /** * Constructor. It finishes the definition passed to it * */ public DefinitionFinisher( Definition def ) { _node = def.getTreeNode(); } public void finish() throws SymbolTableException {} /** * gets the classDef that represents the type of the given definition * * * @param def the definition whose type to find * @param typeNode the TokenTypes.TYPE node associated with the def * * @return the resulting class definition */ protected IClass getType( Definition def, SymTabAST typeNode ) { IClass result = null; SymTabAST typeClassNode = null; boolean isArray = false; if ( typeNode.getFirstChild().getType() == TokenTypes.ARRAY_DECLARATOR ) { isArray = true; typeClassNode = (SymTabAST)typeNode.getFirstChild().getFirstChild(); } else { typeClassNode = (SymTabAST)typeNode.getFirstChild(); } Scope lookupScope = null; if (def instanceof Scope) { lookupScope = (Scope)def; } else { lookupScope = def.getParentScope(); } Resolver resolver = new Resolver(symbolTable); IClass typeClass = resolver.resolveClass(typeClassNode, lookupScope, null, false); if ( isArray ) { result = new ArrayDef( typeClass ); } else { result = typeClass; } return result; } } class ClassFinisher extends DefinitionFinisher { private ClassDef _def = null; /** * Constructor. Creates a ClassFinisher from a Definition * * @param def is a Definition */ public ClassFinisher( Definition def ) { super( def ); _def = (ClassDef)def; } /** * Completes all tasks required for finishing a ClassDef * Including adding imports, setting super classes and adding * interfaces. * @return void * @throws SymbolTableException * @see #addImports() * @see #setSuperclass() * @see #addInterfaces() */ public void finish() throws SymbolTableException { if ( _node != null ) { addImports(); setSuperclass(); addInterfaces(); } } /** * Adds all packages and classes that are imported by this class * to the class for later reference */ private void addImports() throws ClassImportException { IPackage java = new ExternalPackage("java", null); IPackage lang = new ExternalPackage("lang", java); java.addDefinition(lang); _def.importPackage(lang); Vector unprocessedImports = _def.getUnprocessedImports(); for ( int i = 0; i < unprocessedImports.size(); i++ ) { SymTabAST importNode = (SymTabAST)unprocessedImports.get(i); SymTabAST imported = (SymTabAST)importNode.getFirstChild(); SymTabAST lastPart = (SymTabAST)imported.getFirstChild().getNextSibling(); DotIterator it = new DotIterator(imported); SymTabAST current = null; String className = null; IClass importedClass = null; // attempt at each token to find the class // first in source // then on classpath // // if there are more tokens left // continue until you hit the last token // if it's a star // import all inner classes // else // import the explicitly named inner class // else import the class // // if no classes were found, import the package while(it.hasNext()) { current = it.nextNode(); if (className == null) { className = current.getText(); } else { if (!current.getText().equals("*")) { className += "." + current.getText(); } else { break; } } importedClass = findOrLoadClass(className, importedClass); if (importedClass != null) { break; } } if (it.hasNext()) { boolean isImported = false; while(it.hasNext()) { current = it.nextNode(); if (current.getText().equals("*")) { importInnerClasses(importedClass); isImported = true; } else { className += "$" + current.getText(); importedClass = findOrLoadClass(className, importedClass); } } if (!isImported) { _def.importClass(importedClass); } } else { if (importedClass != null) { _def.importClass(importedClass); } else { if (current != null && current.getText().equals("*")) { IPackage pkg = symbolTable.getPackage(className); if (pkg == null) { pkg = getPackage(className); } _def.importPackage(pkg); } else { //TODO: can we safely ignore this? //throw new ClassImportException(className); ; } } } // now set definitions where appropriate imported.ignoreChildren(); if ((lastPart.getType() == TokenTypes.IDENT) //TODO: guard added for class not loaded //This is OK for single file processing, but not //multiple files. && (importedClass != null) ) { lastPart.setDefinition(importedClass, null, true); lastPart.setMeaningfulness(true); } } } /** * creates ExternalPackage * @param packageName name of the package * @return ExternalPackage * @see net.sourceforge.transmogrify.symtab.ExternalPackage */ private ExternalPackage getPackage(String packageName) { return new ExternalPackage(packageName, null); } /** * stores the inner classes in the approriate ClassDef * @param outerClass * @return void */ private void importInnerClasses(IClass outerClass) { IClass[] innerClasses = outerClass.getInnerClasses(); for (int i = 0; i < innerClasses.length; i++) { _def.importClass(innerClasses[i]); } } /** * creates ExternalClass based on a java class * @param className class to be loaded * @return IClass * @see net.sourceforge.transmogrify.symtab.ExternalClass */ private IClass loadClass(String className) { IClass result = null; try { Class javaClass = ClassManager.getClassLoader().loadClass(className); result = new ExternalClass(javaClass); } catch (ClassNotFoundException ignoreMe) {} return result; } /** * find a class from BaseCode or its parent * @param className name of the class to be load or found * @param parentClass its parent class * @return IClass * @see net.sourceforge.transmogrify.symtab.SymbolTable * @see net.sourceforge.transmogrify.symtab.IClass * @see #loadClass(String) */ private IClass findOrLoadClass(String className, IClass parentClass) { IClass result = null; if (parentClass == null) { result = symbolTable.getBaseScope().getClassDefinition(className); } else { int index = className.lastIndexOf("$"); if (index < 0) { index = className.lastIndexOf("."); } result = parentClass.getClassDefinition(className.substring(index + 1)); } if (result == null) { result = loadClass(className); } return result; } /** * * If the class has a super class a reference to this super class * is added to this class. * @return void * @see net.sourceforge.transmogrify.symtab.ClassDef */ private void setSuperclass() { if (_def.getTreeNode().getType() == TokenTypes.CLASS_DEF) { SymTabAST extendsNode = getExtendsNode(_def); if ( extendsNode != null ) { String superclassName = ASTUtil.constructDottedName(extendsNode); IClass superclass = _def.getClassDefinition(superclassName); if ( superclass != null ) { _def.setSuperclass( superclass ); superclass.addSubclass( _def ); } } else { _def.setSuperclass(new ExternalClass(Object.class)); } } else { _def.setSuperclass(new ExternalClass(Object.class)); } } /** * * If the class implements an interface a reference to this interface * is added to this class. * @return void * @see net.sourceforge.transmogrify.symtab.ClassDef */ private void addInterfaces() { SymTabAST implementsClause = null; if (_def.getTreeNode().getType() == TokenTypes.CLASS_DEF) { implementsClause = _node.findFirstToken(TokenTypes.IMPLEMENTS_CLAUSE); } else { implementsClause = _node.findFirstToken(TokenTypes.EXTENDS_CLAUSE); } if ( implementsClause != null ) { SymTabAST interfaceNode = (SymTabAST)implementsClause.getFirstChild(); while ( interfaceNode != null ) { IClass implemented = _def.getClassDefinition(interfaceNode.getText()); if ( implemented != null ) { _def.addInterface( implemented ); implemented.addImplementor( _def ); } interfaceNode = (SymTabAST)(interfaceNode.getNextSibling()); } } } } /** * * Completes a Variable by setting all required references * */ class VariableFinisher extends DefinitionFinisher { VariableDef _def = null; /** * * Constructor. Creates a VariableFinishes from the Definition * @param def VariableDef to be finished * @see net.sourceforge.transmogrify.symtab.VariableDef */ public VariableFinisher( Definition def ) { super( def ); _def = (VariableDef)def; } /** * * Finishes the variable by setting the Type * @return void * @see #getType(Definition, SymTabAST) * @see net.sourceforge.transmogrify.symtab.VariableDef */ public void finish() { SymTabAST typeNode = _node.findFirstToken(TokenTypes.TYPE); SymTabAST typeTextNode = (SymTabAST)(typeNode.getFirstChild()); if ( typeTextNode.getType() == TokenTypes.ARRAY_DECLARATOR ) { typeTextNode = (SymTabAST)(typeTextNode.getFirstChild()); } typeTextNode.setLine(ASTUtil.getLine( _def.getTreeNode() )); IClass varType = getType(_def, typeNode); _def.setType( varType ); } } /** * * Completes a Variable by setting all required references * */ class MethodFinisher extends DefinitionFinisher { MethodDef _def = null; /** * * Creates a MethodFinisher from a Definition * @param def MethodDef to be finished * @see net.sourceforge.transmogrify.symtab.MethodDef */ public MethodFinisher( Definition def ) { super( def ); _def = (MethodDef)def; } /** * * Completes a method by setting all references to return types, * signatures and exceptions. * @return void * @see #setReturnType() * @see #setSignature() * @see #setExceptionsThrown() */ public void finish() { setReturnType(); setSignature(); setExceptionsThrown(); } /** * * setReturnType adds a reference to the methods return type * to the method definition * @return void * @see net.sourceforge.transmogrify.symtab.MethodDef * @see #getType(Definition, SymTabAST) * @see #getTypeNode() */ private void setReturnType() { IClass type = null; if ( isConstructor() ) { type = _def.getEnclosingClass(); } else { type = getType(_def, getTypeNode()); } _def.setType(type); } /** * * setSignature adds a reference to the methods paramaters * to the method definition * @return void * @see #makeVariableDef(SymTabAST, Definition) * @see VariableFinisher * @see net.sourceforge.transmogrify.symtab.MethodDef */ private void setSignature() { SymTabAST parametersNode = _node.findFirstToken(TokenTypes.PARAMETERS); SymTabAST parameterNode = (SymTabAST)(parametersNode.getFirstChild()); while ( parameterNode != null ) { if (parameterNode.getType() == TokenTypes.PARAMETER_DEF) { VariableDef parameter = makeVariableDef( parameterNode, _def ); new VariableFinisher( parameter ).finish(); _def.addParameter( parameter ); } parameterNode = (SymTabAST)(parameterNode.getNextSibling()); } } /** * * setExceptionsThrown adds a reference to the methods Exceptions * to the method definition * @return void * @see net.sourceforge.transmogrify.symtab.SymbolTable * @see net.sourceforge.transmogrify.symtab.PackageDef * @see net.sourceforge.transmogrify.symtab.MethodDef */ private void setExceptionsThrown() { IClass exception = null; SymTabAST throwsNode = _node.findFirstToken(TokenTypes.LITERAL_THROWS); if ( throwsNode != null ) { SymTabAST exceptionNode = (SymTabAST)(throwsNode.getFirstChild()); while (exceptionNode != null ) { if (exceptionNode.getType() == TokenTypes.DOT) { PackageDef pkg = symbolTable.getPackage(ASTUtil.constructPackage(exceptionNode)); if ( pkg != null ) { exception = pkg.getClassDefinition(ASTUtil.constructClass(exceptionNode)); } } else { exception = _def.getClassDefinition(exceptionNode.getText()); } _def.addException(exception); exceptionNode = (SymTabAST)(exceptionNode.getNextSibling()); } } } /** * * isConstructor sets the flag in the method definition to indicate * whether it is a constructor or not * @return boolean true if a node has no return type * false if a node has a return type * @see #getTypeNode() */ private boolean isConstructor() { boolean result = false; if ( getTypeNode() == null ) { result = true; } return result; } /** * * getTypeNode returnss the SymTabAST node that is the * return type of this method * * @return SymTabAST */ private SymTabAST getTypeNode() { return _node.findFirstToken(TokenTypes.TYPE); } } class CatchFinisher extends DefinitionFinisher { BlockDef _def = null; /** * constructor that takes a BlockDef * @param def BlockDef for the catch block */ public CatchFinisher(BlockDef def) { super(def); _def = def; } /** * finishes definition creation * @return void * @see #createExceptionVariable() */ public void finish() { createExceptionVariable(); } /** * creates VariableDef and finishes creation definition for * arguments in the catch clause * @return void * @see net.sourceforge.transmogrify.symtab.VariableDef * @see #makeVariableDef(SymTabAST, Definition) * @see VariableFinisher */ private void createExceptionVariable() { SymTabAST exceptionNode = _def.getTreeNode().findFirstToken(TokenTypes.PARAMETER_DEF); VariableDef exception = makeVariableDef(exceptionNode, _def); new VariableFinisher(exception).finish(); _def.addDefinition(exception); } } } ././@LongLink100644 0 0 161 12026055133 10246 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/Typed.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 3626 11451071612 31453 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; /** * classes that implement this interface have a notion * of "type" like int, String, GerblinkenLight, etc. */ public interface Typed extends IDefinition { /** * gets the type of this definition */ public IClass getType(); } ././@LongLink100644 0 0 170 12026055133 10246 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/UnknownClass.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 11417 11451071612 31470 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import java.util.Iterator; import java.util.List; import java.util.Vector; public class UnknownClass implements IClass { String _name; SymTabAST _node; public UnknownClass(String name, SymTabAST node) { _name = name; _node = node; //System.out.println("Creating unknown class [" + name + " : " + node + "]"); } /** * returns the ClassDef that for the superclass * * @return the ClassDef for the superclass */ public IClass getSuperclass() { return null; } public IClass[] getInterfaces() { return new IClass[0]; } /** * returns a collection of the direct subclasses of this class * * @return a collection of the direct subclasses of this class */ public List getSubclasses() { return new Vector(); } public IClass getClassDefinition(String name) { return null; } /** * gets the method associated with the given name and signature * * @param name the name of the method * @param signature the signature (formal parameter types) of the method * * @return MethodDef * * @see MethodSignature */ public IMethod getMethodDefinition(String name, ISignature signature) { return null; } /** * gets the VariableDef associated with the given name * * @param name the name of the variable * * @return VariableDef */ public IVariable getVariableDefinition(String name) { return null; } // end definitions interface /** * adds ClassDef to the collection of (direct?) subclasses of * this class * * @param subclass the class to add */ public void addSubclass(ClassDef subclass) {} /** * adds ClassDef to the collection of implemented interfaces * of this class * * @param implementor the interface to add */ public void addImplementor(ClassDef implementor) {} /** * gets the list of ClassDefs that implmement this interface * * @return Vector the list of implementors */ public List getImplementors() { return new Vector(); } public boolean isCompatibleWith(IClass type) { return false; } public void addReference(Reference reference) {} public Iterator getReferences() { return new Vector().iterator(); } public int getNumReferences() { return 0; } public boolean isPrimitive() { return false; } public boolean isSourced() { return false; } public IClass[] getInnerClasses() { return new IClass[0]; } public String getName() { return _name; } public String getQualifiedName() { return _name; } public boolean equals(Object o) { //TODO: handle Checkstyle condition for two unknown classes if (o instanceof UnknownClass) { final UnknownClass other = (UnknownClass) o; return other.getName().equals(getName()); } return false; } public String toString() { return UnknownClass.class + "[" + getName() + "]"; } } ././@LongLink100644 0 0 167 12026055133 10254 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/VariableDef.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrif100644 0 0 10712 11451071612 31465 0ustar 0 0 // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * VariableDef is a Definition that contains * information about the definition of a variable. * * @see Definition * @see TypedDef */ public class VariableDef extends Definition implements IVariable { public static final int PRIVATE_VISIBILITY = 0; public static final int PROTECTED_VISIBILITY = 1; public static final int PUBLIC_VISIBILITY = 2; public static final int DEFAULT_VISIBILITY = 3; private IClass _type = null; public VariableDef(String name, Scope parentScope, SymTabAST node) { super(name, parentScope, node); } /** * Returns the Type of the variable. * * @see TypedDef * * @return the Type of the variable */ public IClass getType() { return _type; } /** * Sets the type of the variable. * * @see TypedDef * * @param def the Type object that represents the type of the * variable. */ public void setType(IClass type) { _type = type; } public int getVisibility() { int result = DEFAULT_VISIBILITY; SymTabAST visibilityNode = getVisibilityNode(); if (visibilityNode != null) { if (visibilityNode.getType() == TokenTypes.LITERAL_PRIVATE) { result = PRIVATE_VISIBILITY; } else if ( visibilityNode.getType() == TokenTypes.LITERAL_PROTECTED) { result = PROTECTED_VISIBILITY; } else if (visibilityNode.getType() == TokenTypes.LITERAL_PUBLIC) { result = PUBLIC_VISIBILITY; } } return result; } private SymTabAST getVisibilityNode() { SymTabAST result = null; SymTabAST modifiersNode = getTreeNode().findFirstToken(TokenTypes.MODIFIERS); SymTabAST modifier = (SymTabAST) modifiersNode.getFirstChild(); while (modifier != null) { if (isVisibilityNode(modifier)) { result = modifier; break; } modifier = (SymTabAST) modifier.getNextSibling(); } return result; } private boolean isVisibilityNode(SymTabAST node) { return ( node.getType() == TokenTypes.LITERAL_PUBLIC || node.getType() == TokenTypes.LITERAL_PROTECTED || node.getType() == TokenTypes.LITERAL_PRIVATE); } public boolean isAssignedAtDeclaration() { boolean result = false; if (getTreeNode().findFirstToken(TokenTypes.ASSIGN) != null) { result = true; } return result; } } ././@LongLink100644 0 0 167 12026055133 10254 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/UnusedLocalVariableCheck.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/UnusedLocal100644 0 0 4112 11451071612 31325 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2005 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.usage; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

Checks that a local variable is read. *

*

* An example of how to configure the check is: *

*
 * <module name="usage.UnusedLocalVariable"/>
 * 
* * @author Rick Giles */ public class UnusedLocalVariableCheck extends AbstractUsageCheck { /** @see com.puppycrawl.tools.checkstyle.api.Check */ public int[] getDefaultTokens() { return new int[] { TokenTypes.VARIABLE_DEF, }; } /** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */ public String getErrorKey() { return "unused.local"; } /** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */ public boolean mustCheckReferenceCount(DetailAST aAST) { return ScopeUtils.isLocalVariableDef(aAST); } } ././@LongLink100644 0 0 163 12026055133 10250 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/UnusedParameterCheck.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/UnusedParam100644 0 0 10763 11451071612 31364 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2005 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.usage; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

Checks that a parameter is used. *

*

* An example of how to configure the check is: *

*
 * <module name="usage.UnusedParameter"/>
 * 
* * @author Rick Giles */ public class UnusedParameterCheck extends AbstractUsageCheck { /** controls checking of catch clause parameter */ private boolean mIgnoreCatch = true; /** controls checking of public/protected/package methods */ private boolean mIgnoreNonLocal; /** @see com.puppycrawl.tools.checkstyle.api.Check */ public int[] getDefaultTokens() { return new int[] { TokenTypes.PARAMETER_DEF, }; } /** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */ public String getErrorKey() { return "unused.parameter"; } /** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */ public boolean mustCheckReferenceCount(DetailAST aAST) { boolean result = false; final DetailAST parent = aAST.getParent(); if (parent != null) { if (parent.getType() == TokenTypes.PARAMETERS) { final DetailAST grandparent = parent.getParent(); if (grandparent != null) { result = hasBody(grandparent) && (!mIgnoreNonLocal || isLocal(grandparent)); } } else if (parent.getType() == TokenTypes.LITERAL_CATCH) { result = !mIgnoreCatch; } } return result; } /** * Determines whether an AST is a method definition with a body, or is * a constructor definition. * @param aAST the AST to check. * @return if AST has a body. */ private boolean hasBody(DetailAST aAST) { if (aAST.getType() == TokenTypes.METHOD_DEF) { return aAST.branchContains(TokenTypes.SLIST); } else if (aAST.getType() == TokenTypes.CTOR_DEF) { return true; } return false; } /** * Checks if a given method is local, i.e. either static or private. * @param aAST method def for check * @return true if a given method is iether static or private. */ private boolean isLocal(DetailAST aAST) { if (aAST.getType() == TokenTypes.METHOD_DEF) { final DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS); return (modifiers == null) || modifiers.branchContains(TokenTypes.LITERAL_STATIC) || modifiers.branchContains(TokenTypes.LITERAL_PRIVATE); } return true; } /** * Control whether unused catch clause parameters are flagged. * @param aIgnoreCatch whether unused catch clause parameters * should be flagged. */ public void setIgnoreCatch(boolean aIgnoreCatch) { mIgnoreCatch = aIgnoreCatch; } /** * Controls whether public/protected/paskage methods shouldn't be checked. * @param aIgnoreNonLocal whether we should check any other methods * except static and private should be checked. */ public void setIgnoreNonLocal(boolean aIgnoreNonLocal) { mIgnoreNonLocal = aIgnoreNonLocal; } } ././@LongLink100644 0 0 166 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/UnusedPrivateFieldCheck.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/UnusedPriva100644 0 0 4374 11451071612 31366 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2005 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.usage; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.Scope; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

Checks that a private field is used. *

*

* An example of how to configure the check is: *

*
 * <module name="usage.UnusedPrivateField"/>
 * 
* * @author Rick Giles */ public class UnusedPrivateFieldCheck extends AbstractUsageCheck { /** @see com.puppycrawl.tools.checkstyle.api.Check */ public int[] getDefaultTokens() { return new int[] { TokenTypes.VARIABLE_DEF, }; } /** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */ public String getErrorKey() { return "unused.field"; } /** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */ public boolean mustCheckReferenceCount(DetailAST aAST) { final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS); return ((mods != null) && (ScopeUtils.getScopeFromMods(mods) == Scope.PRIVATE)); } } ././@LongLink100644 0 0 167 12026055133 10254 Lustar 0 0 checkstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/UnusedPrivateMethodCheck.javacheckstyle-5.6/contrib/usage/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/UnusedPriva100644 0 0 21651 11451071612 31403 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2005 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.usage; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.Scope; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

Checks that a private method is used. *

*

* An example of how to configure the check is: *

*
 * <module name="usage.UnusedPrivateMethod"/>
 * 
* * @author Rick Giles */ public class UnusedPrivateMethodCheck extends AbstractUsageCheck { /** Controls if checks skips serialization methods.*/ private boolean mAllowSerializationMethods; /** @see com.puppycrawl.tools.checkstyle.api.Check */ public int[] getDefaultTokens() { return new int[] { TokenTypes.METHOD_DEF, }; } /** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */ public String getErrorKey() { return "unused.method"; } /** * Configure the check to allow (or not) serialization-related methods. * @param aFlag new value for allowSerializationMethods value. */ public void setAllowSerializationMethods(boolean aFlag) { mAllowSerializationMethods = aFlag; } /** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */ public boolean mustCheckReferenceCount(DetailAST aAST) { final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS); if ((mods == null) || (ScopeUtils.getScopeFromMods(mods) != Scope.PRIVATE)) { return false; } return !mAllowSerializationMethods || !(isWriteObject(aAST) || isReadObject(aAST) || isWriteReplaceOrReadResolve(aAST)); } /** * Checks if a given method is writeObject(). * @param aAST method def to check * @return true if this is a writeObject() definition */ private boolean isWriteObject(DetailAST aAST) { // name is writeObject... final DetailAST ident = aAST.findFirstToken(TokenTypes.IDENT); if (!"writeObject".equals(ident.getText())) { return false; } // returns void... final DetailAST typeAST = (DetailAST) aAST.findFirstToken(TokenTypes.TYPE).getFirstChild(); if (typeAST.getType() != TokenTypes.LITERAL_VOID) { return false; } // should have one parameter... final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS); if (params == null || params.getChildCount() != 1) { return false; } // and paramter's type should be java.io.ObjectOutputStream final DetailAST type = (DetailAST) ((DetailAST) params.getFirstChild()) .findFirstToken(TokenTypes.TYPE).getFirstChild(); final String typeName = FullIdent.createFullIdent(type).getText(); if (!"java.io.ObjectOutputStream".equals(typeName) && !"ObjectOutputStream".equals(typeName)) { return false; } // and, finally, it should throws java.io.IOException final DetailAST throwsAST = aAST.findFirstToken(TokenTypes.LITERAL_THROWS); if (throwsAST == null || throwsAST.getChildCount() != 1) { return false; } final DetailAST expt = (DetailAST) throwsAST.getFirstChild(); final String exceptionName = FullIdent.createFullIdent(expt).getText(); if (!"java.io.IOException".equals(exceptionName) && !"IOException".equals(exceptionName)) { return false; } return true; } /** * Checks if a given method is readObject(). * @param aAST method def to check * @return true if this is a readObject() definition */ private boolean isReadObject(DetailAST aAST) { // name is readObject... final DetailAST ident = aAST.findFirstToken(TokenTypes.IDENT); if (!"readObject".equals(ident.getText())) { return false; } // returns void... final DetailAST typeAST = (DetailAST) aAST.findFirstToken(TokenTypes.TYPE).getFirstChild(); if (typeAST.getType() != TokenTypes.LITERAL_VOID) { return false; } // should have one parameter... final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS); if (params == null || params.getChildCount() != 1) { return false; } // and paramter's type should be java.io.ObjectInputStream final DetailAST type = (DetailAST) ((DetailAST) params.getFirstChild()) .findFirstToken(TokenTypes.TYPE).getFirstChild(); final String typeName = FullIdent.createFullIdent(type).getText(); if (!"java.io.ObjectInputStream".equals(typeName) && !"ObjectInputStream".equals(typeName)) { return false; } // and, finally, it should throws java.io.IOException // and java.lang.ClassNotFoundException final DetailAST throwsAST = aAST.findFirstToken(TokenTypes.LITERAL_THROWS); if (throwsAST == null || throwsAST.getChildCount() != 3) { return false; } final DetailAST excpt1 = (DetailAST) throwsAST.getFirstChild(); final String exception1 = FullIdent.createFullIdent(excpt1).getText(); final String exception2 = FullIdent.createFullIdent(throwsAST.getLastChild()).getText(); if (!"java.io.IOException".equals(exception1) && !"IOException".equals(exception1) && !"java.io.IOException".equals(exception2) && !"IOException".equals(exception2) || !"java.lang.ClassNotFoundException".equals(exception1) && !"ClassNotFoundException".equals(exception1) && !"java.lang.ClassNotFoundException".equals(exception2) && !"ClassNotFoundException".equals(exception2)) { return false; } return true; } /** * Checks if a given method is writeReplace() or readResolve(). * @param aAST method def to check * @return true if this is a writeReplace() definition */ private boolean isWriteReplaceOrReadResolve(DetailAST aAST) { // name is writeReplace or readResolve... final DetailAST ident = aAST.findFirstToken(TokenTypes.IDENT); if (!"writeReplace".equals(ident.getText()) && !"readResolve".equals(ident.getText())) { return false; } // returns Object... final DetailAST typeAST = (DetailAST) aAST.findFirstToken(TokenTypes.TYPE).getFirstChild(); if (typeAST.getType() != TokenTypes.DOT && typeAST.getType() != TokenTypes.IDENT) { return false; } // should have no parameters... final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS); if (params != null && params.getChildCount() != 0) { return false; } // and, finally, it should throws java.io.ObjectStreamException final DetailAST throwsAST = aAST.findFirstToken(TokenTypes.LITERAL_THROWS); if (throwsAST == null || throwsAST.getChildCount() != 1) { return false; } final DetailAST excpt = (DetailAST) throwsAST.getFirstChild(); final String exception = FullIdent.createFullIdent(excpt).getText(); if (!"java.io.ObjectStreamException".equals(exception) && !"ObjectStreamException".equals(exception)) { return false; } return true; } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputEmptyFile.javacheckstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputEmptyFile.jav100644 0 0 66 11451071612 31374 0ustar 0 0 // this is an empty file // it's a test for 1165855 ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputInnerUsedMethod.javacheckstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputInnerUsedMeth100644 0 0 732 11451071612 31451 0ustar 0 0 package com.puppycrawl.tools.checkstyle.usage; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JButton; public final class InputInnerUsedMethod { public static void show() { JButton b = new JButton(new AbstractAction() { public void actionPerformed(ActionEvent e) { doSomething(); } }); } private static void doSomething() { } } ././@LongLink100644 0 0 162 12026055133 10247 Lustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputOneMethodPrivateField.javacheckstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputOneMethodPriv100644 0 0 4040 11451071612 31476 0ustar 0 0 package com.puppycrawl.tools.checkstyle.usage; /** Test input for one method private field check */ public class InputOneMethodPrivateField { private static int SFIELD0; private static int SFIELD1; private static int SFIELD2; private static int SFIELD3; private int mField0; private int mField1; private int mField2; private int mField3; private int mField4; private int mIgnore; public InputOneMethodPrivateField() { SFIELD0 = 0; mField0 = 0; mField3 = 0; } private void method() { SFIELD1 = 0; mField1 = 0; mField3++; mField4 = 0; } { SFIELD2 = 0; mField2 = 0; mField4 = 1; } static { SFIELD3 = 0; } } class Outer2 { private int mField0; private int mField1; private int mField2; private int mField3; private class Inner { public Inner() { int i = mField0; } public void method() { mField1 = 0; mField3++; } { mField2 = 0; } } private void method() { mField3 = 0; } } class Outer3 { private int mField0; private int mField1; private void method() { final class Inner { public int mInner = mField0; } } /** tests NPE with dotted class name (bug 842781) */ public void dotted() { java.lang.Thread th = new java.lang.Thread() { public void run() { ; } }; th.start(); } } /** Tests NPE with foreach statements (bug 1109222) */ class Outer4 { private int[] mField; private void method() { for (int someInt : mField) { someInt = someInt ^ 2; } } }././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputUnusedField.javacheckstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputUnusedField.j100644 0 0 3641 11451071612 31420 0ustar 0 0 package com.puppycrawl.tools.checkstyle.usage; import java.awt.Rectangle; /** Test input for unused field check */ public class InputUnusedField { private int mReadPrimitive; private int mPrimitive; private int mUnreadPrimitive; private String mReadString; private String mReadString2; private Rectangle mRectangle; private int[] mArray; private int[] mArray2; private int[] mUnreadArray; private int mThisPrimitive; private int mInitializer = 0; private int mUnused2 = mInitializer; private static final int SUNUSED = 0; private static int USED; static { USED = 0; } public InputUnusedField() { int i = mReadPrimitive; } private void method() { int i = mReadString.length(); "".equals(mReadString2); int j = mRectangle.x; i = mArray[0]; mArray2[0] = 0; this.mThisPrimitive = 1; } private void shadow() { int mUnreadPrimitive = 0; mUnreadPrimitive++; int[] mUnreadArray = {0}; int i = mUnreadArray[0]; } { mPrimitive = 0; } } class Outer { private int mUsed1; private int mUsed2; private int mUsed3; private int mUnused; private class Inner { public Inner() { int i = mUsed1; } public void method() { mUsed2 = 0; } { mUsed3 = 0; } } } class ParenthesizedExpression { private int mUsed1 = 1; private int mUsed2 = 1; private boolean mUsed3 = true; public void testParentheses() { int x = 0; int a = (x++) / mUsed1; int b = (a - 1) << mUsed2; boolean c = (a == b) || mUsed3; } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputUnusedLocal.javacheckstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputUnusedLocal.j100644 0 0 2460 11451071612 31425 0ustar 0 0 package com.puppycrawl.tools.checkstyle.usage; import java.awt.Rectangle; /** Test input for unused local variable check */ public class InputUnusedLocal { private int mUnreadPrimitive = 0; public InputUnusedLocal() { int readPrimitive = 0; int mUnreadPrimitive = 0; int i = readPrimitive; i++; this.mUnreadPrimitive++; } private void method() { String readObject = ""; Rectangle rectangle = null; Object unreadObject; int i = readObject.length(); int j = rectangle.x; i += j; } private void methodArrays() { int[] array = {}; int[] array2 = {}; int[] unreadArray; int i = array[0]; array2[0] = 0; i++; } /** tests that neither type nor typecast are considered to be a reference */ public void method2() { int java; java.io.File file = (java.io.File) null; if (file != null) { } } /** tests array index references */ public void testArrayIndex() { int [][][] a = new int[1][1][1]; int i = 0; int j = 0; int k = 0; a[i][j][k]++; } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputUnusedMethod.javacheckstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputUnusedMethod.100644 0 0 6744 11451071612 31452 0ustar 0 0 package com.puppycrawl.tools.checkstyle.usage; /** Test input for unread method check */ public class InputUnusedMethod { private void methodUnused0() { } private void methodUsed0() { } private void methodUsed1(int aParam) { } private void methodUsed1(double aParam) { } private void methodUsed1(String aParam) { } public static void main(String[] args) { InputUnusedMethod method = new InputUnusedMethod(); method.methodUsed0(); method.methodUsed1(0 + 4); method.methodUsed1(Math.sqrt(2.0)); method.methodUsed1("" + "a"); } } interface InterfaceMethod { public void method(int aParam); } abstract class AbstractClassMethod { public abstract void method(int aParam); } /** Test for bug 880954: false positive when parentheses around second term * of ternary operator. */ class Ternary { private int m() { return 1; } public void m1() { int i = 0; int j = (i == 0) ? (i) : m(); } } class SerializableTest implements java.io.Serializable { private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { // it's ok to have this method in serializable class } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { // it's ok to have this method in serializable class } private Object writeReplace() throws java.io.ObjectStreamException { // it's ok to have this method in serializable class return new SerializableTest(); } private Object readResolve() throws java.io.ObjectStreamException { // it's ok to have this method in serializable class return new SerializableTest(); } } class BadSerializableTest1 implements java.io.Serializable { private void writeObject(Object out) throws java.io.IOException { } private void writeObject(java.io.ObjectOutputStream out, int i) throws java.io.IOException { } private void writeObject(java.io.ObjectOutputStream out) { } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException { } private void readObject(Object in) throws java.io.IOException, ClassNotFoundException { } private int writeReplace() throws java.io.ObjectStreamException { return 1; } private Object writeReplace(int i) throws java.io.ObjectStreamException { return new SerializableTest(); } private int readResolve() throws java.io.ObjectStreamException { return 1; } private Object readResolve(int i) throws java.io.ObjectStreamException { return new SerializableTest(); } } class BadSerializableTest2 implements java.io.Serializable { private int writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { return 1; } private void readObject(java.io.ObjectInputStream in) throws ClassNotFoundException { } private Object readResolve() { return new SerializableTest(); } } class BadSerializableTest3 implements java.io.Serializable { private int readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { return 1; } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputUnusedParameter.javacheckstyle-5.6/contrib/usage/src/testinputs/com/puppycrawl/tools/checkstyle/usage/InputUnusedParamet100644 0 0 2041 11451071612 31527 0ustar 0 0 package com.puppycrawl.tools.checkstyle.usage; import java.awt.Rectangle; /** Test input for unread parameter check */ public class InputUnusedParameter { public InputUnusedParameter(int aReadPrimitive, int aUnreadPrimitive) { int i = aReadPrimitive; } public void method( String aReadObject, Rectangle aRectangle, Object aUnreadObject) { int i = aReadObject.length(); int j = aRectangle.x; try { i++; } catch (Exception unreadException) { } } private void methodArrays(int[] aArray, int[] aArray2, int[] aUnreadArray) { int i = aArray[0]; aArray2[0] = 0; } private int member = 1; private void methodSameLocalVariable(int member) { int x = member; // refers to the param, not the member } } interface Interface { public void method(int aParam); } abstract class AbstractClass { public abstract void method(int aParam); } checkstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/AllTests.java100644 0 0 1457 11451071612 30577 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.usage; import junit.framework.Test; import junit.framework.TestSuite; public class AllTests { public static void main(String[] args) { junit.textui.TestRunner.run(AllTests.suite()); } public static Test suite() { TestSuite suite = new TestSuite("Test for com.puppycrawl.tools.checkstyle.checks.usage"); suite.addTest(new TestSuite(OneMethodPrivateFieldCheckTest.class)); suite.addTest(new TestSuite(UnusedLocalVariableCheckTest.class)); suite.addTest(new TestSuite(UnusedParameterCheckTest.class)); suite.addTest(new TestSuite(UnusedPrivateFieldCheckTest.class)); suite.addTest(new TestSuite(UnusedPrivateMethodCheckTest.class)); return suite; } } ././@LongLink100644 0 0 170 12026055133 10246 Lustar 0 0 checkstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/OneMethodPrivateFieldCheckTest.javacheckstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/OneMethodPrivate100644 0 0 4367 11451071612 31344 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.usage; import com.puppycrawl.tools.checkstyle.BaseCheckTestCase; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class OneMethodPrivateFieldCheckTest extends BaseCheckTestCase { public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(OneMethodPrivateFieldCheck.class); final String[] expected = { "6:24: Field 'SFIELD0' is used in only one method.", "7:24: Field 'SFIELD1' is used in only one method.", "8:24: Field 'SFIELD2' is used in only one method.", "9:24: Field 'SFIELD3' is used in only one method.", "11:17: Field 'mField0' is used in only one method.", "12:17: Field 'mField1' is used in only one method.", "13:17: Field 'mField2' is used in only one method.", "47:17: Field 'mField0' is used in only one method.", "48:17: Field 'mField1' is used in only one method.", "49:17: Field 'mField2' is used in only one method.", "105:19: Field 'mField' is used in only one method.", }; verify(checkConfig, getPath("usage/InputOneMethodPrivateField.java"), expected); } public void testIgnoreFormat() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(OneMethodPrivateFieldCheck.class); checkConfig.addAttribute("ignoreFormat", "2$"); final String[] expected = { "6:24: Field 'SFIELD0' is used in only one method.", "7:24: Field 'SFIELD1' is used in only one method.", "9:24: Field 'SFIELD3' is used in only one method.", "11:17: Field 'mField0' is used in only one method.", "12:17: Field 'mField1' is used in only one method.", "47:17: Field 'mField0' is used in only one method.", "48:17: Field 'mField1' is used in only one method.", "105:19: Field 'mField' is used in only one method.", }; verify(checkConfig, getPath("usage/InputOneMethodPrivateField.java"), expected); } } ././@LongLink100644 0 0 166 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/UnusedLocalVariableCheckTest.javacheckstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/UnusedLocalVaria100644 0 0 2574 11451071612 31326 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.usage; import com.puppycrawl.tools.checkstyle.BaseCheckTestCase; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class UnusedLocalVariableCheckTest extends BaseCheckTestCase { public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedLocalVariableCheck.class); final String[] expected = { "13:13: Unused local variable 'mUnreadPrimitive'.", "24:16: Unused local variable 'unreadObject'.", "36:15: Unused local variable 'unreadArray'.", "45:13: Unused local variable 'java'.", }; verify(checkConfig, getPath("usage/InputUnusedLocal.java"), expected); } public void testIgnoreFormat() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedLocalVariableCheck.class); checkConfig.addAttribute("ignoreFormat", "Array$"); final String[] expected = { "13:13: Unused local variable 'mUnreadPrimitive'.", "24:16: Unused local variable 'unreadObject'.", "45:13: Unused local variable 'java'.", }; verify(checkConfig, getPath("usage/InputUnusedLocal.java"), expected); } } ././@LongLink100644 0 0 162 12026055133 10247 Lustar 0 0 checkstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/UnusedParameterCheckTest.javacheckstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/UnusedParameterC100644 0 0 4504 11451071612 31327 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.usage; import com.puppycrawl.tools.checkstyle.BaseCheckTestCase; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class UnusedParameterCheckTest extends BaseCheckTestCase { public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedParameterCheck.class); final String[] expected = { "8:57: Unused parameter 'aUnreadPrimitive'.", "16:16: Unused parameter 'aUnreadObject'.", "29:66: Unused parameter 'aUnreadArray'.", }; verify(checkConfig, getPath("usage/InputUnusedParameter.java"), expected); } public void testException() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedParameterCheck.class); checkConfig.addAttribute("ignoreCatch", Boolean.FALSE.toString()); final String[] expected = { "8:57: Unused parameter 'aUnreadPrimitive'.", "16:16: Unused parameter 'aUnreadObject'.", "25:26: Unused parameter 'unreadException'.", "29:66: Unused parameter 'aUnreadArray'.", }; verify(checkConfig, getPath("usage/InputUnusedParameter.java"), expected); } public void testIgnoreFormat() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedParameterCheck.class); checkConfig.addAttribute("ignoreFormat", "Array$"); final String[] expected = { "8:57: Unused parameter 'aUnreadPrimitive'.", "16:16: Unused parameter 'aUnreadObject'.", }; verify(checkConfig, getPath("usage/InputUnusedParameter.java"), expected); } public void testIgnoreNonLocal() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedParameterCheck.class); checkConfig.addAttribute("ignoreNonLocal", "true"); final String[] expected = { "8:57: Unused parameter 'aUnreadPrimitive'.", "29:66: Unused parameter 'aUnreadArray'.", }; verify(checkConfig, getPath("usage/InputUnusedParameter.java"), expected); } } ././@LongLink100644 0 0 165 12026055133 10252 Lustar 0 0 checkstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/UnusedPrivateFieldCheckTest.javacheckstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/UnusedPrivateFie100644 0 0 2756 11451071612 31351 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.usage; import com.puppycrawl.tools.checkstyle.BaseCheckTestCase; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class UnusedPrivateFieldCheckTest extends BaseCheckTestCase { public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedPrivateFieldCheck.class); final String[] expected = { "10:17: Unused private field 'mUnreadPrimitive'.", "16:19: Unused private field 'mUnreadArray'.", "20:17: Unused private field 'mUnused2'.", "22:30: Unused private field 'SUNUSED'.", "64:17: Unused private field 'mUnused'.", }; verify(checkConfig, getPath("usage/InputUnusedField.java"), expected); } public void testIgnoreFormat() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedPrivateFieldCheck.class); checkConfig.addAttribute("ignoreFormat", "Array$"); final String[] expected = { "10:17: Unused private field 'mUnreadPrimitive'.", "20:17: Unused private field 'mUnused2'.", "22:30: Unused private field 'SUNUSED'.", "64:17: Unused private field 'mUnused'.", }; verify(checkConfig, getPath("usage/InputUnusedField.java"), expected); } } ././@LongLink100644 0 0 166 12026055133 10253 Lustar 0 0 checkstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/UnusedPrivateMethodCheckTest.javacheckstyle-5.6/contrib/usage/src/tests/com/puppycrawl/tools/checkstyle/checks/usage/UnusedPrivateMet100644 0 0 6660 11451071612 31371 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.usage; import com.puppycrawl.tools.checkstyle.BaseCheckTestCase; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class UnusedPrivateMethodCheckTest extends BaseCheckTestCase { public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedPrivateMethodCheck.class); final String[] expected = { "7:18: Unused private method 'methodUnused0'.", "66:18: Unused private method 'writeObject'.", "71:18: Unused private method 'readObject'.", "76:20: Unused private method 'writeReplace'.", "82:20: Unused private method 'readResolve'.", "91:18: Unused private method 'writeObject'.", "95:18: Unused private method 'writeObject'.", "99:18: Unused private method 'writeObject'.", "103:18: Unused private method 'readObject'.", "107:18: Unused private method 'readObject'.", "111:17: Unused private method 'writeReplace'.", "116:20: Unused private method 'writeReplace'.", "121:17: Unused private method 'readResolve'.", "126:20: Unused private method 'readResolve'.", "134:17: Unused private method 'writeObject'.", "139:18: Unused private method 'readObject'.", "143:20: Unused private method 'readResolve'.", "151:17: Unused private method 'readObject'.", }; verify(checkConfig, getPath("usage/InputUnusedMethod.java"), expected); } public void testAllowSerializationMethods() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedPrivateMethodCheck.class); checkConfig.addAttribute("allowSerializationMethods", "true"); final String[] expected = { "7:18: Unused private method 'methodUnused0'.", "91:18: Unused private method 'writeObject'.", "95:18: Unused private method 'writeObject'.", "99:18: Unused private method 'writeObject'.", "103:18: Unused private method 'readObject'.", "107:18: Unused private method 'readObject'.", "111:17: Unused private method 'writeReplace'.", "116:20: Unused private method 'writeReplace'.", "121:17: Unused private method 'readResolve'.", "126:20: Unused private method 'readResolve'.", "134:17: Unused private method 'writeObject'.", "139:18: Unused private method 'readObject'.", "143:20: Unused private method 'readResolve'.", "151:17: Unused private method 'readObject'.", }; verify(checkConfig, getPath("usage/InputUnusedMethod.java"), expected); } public void testInner() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedPrivateMethodCheck.class); final String[] expected = { }; verify(checkConfig, getPath("usage/InputInnerUsedMethod.java"), expected); } public void testEmptyFile() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedPrivateMethodCheck.class); final String[] expected = { }; verify(checkConfig, getPath("usage/InputEmptyFile.java"), expected); } } checkstyle-5.6/contrib/usage/src/xdocs/config_usage.xml100644 0 0 25442 11451071612 20524 0ustar 0 0 Usage Checks Checkstyle Development Team

Checks that a private field is used in more than one method, constructor, or initializer.

Rationale: a private field used in only one method, constructor, or initializer should be replaced by a local variable.

name description type default value
ignoreFormat pattern for field names that should be ignored regular expression ^$ (empty)

To configure the check:

<module name="usage.OneMethodPrivateField"/>

To configure the check to ignore fields whose name ends in Temp:

<module name="usage.OneMethodPrivateField"> <property name="ignoreFormat" value="Temp$"/> </module>

com.puppycrawl.tools.checkstyle.checks.usage

TreeWalker

Checks that a local variable is used after its declaration.

name description type default value
ignoreFormat pattern for variable names that should be ignored regular expression ^$ (empty)

To configure the check:

<module name="usage.UnusedLocalVariable"/>

To configure the check to ignore variables whose name ends in Temp:

<module name="usage.UnusedLocalVariable"> <property name="ignoreFormat" value="Temp$"/> </module>

com.puppycrawl.tools.checkstyle.checks.usage

TreeWalker

Checks that a parameter is used.

name description type default value
ignoreFormat pattern for parameter names that should be ignored regular expression ^$ (empty)
ignoreCatch controls whether catch parameters should be ignored boolean true
ignoreNonLocal controls whether parameters of non local (public, protected or package) methods should be ignored boolean false

To configure the check:

<module name="usage.UnusedParameter"/>

To configure the check to ignore parameters whose name ends in Temp:

<module name="usage.UnusedParameter"> <property name="ignoreFormat" value="Temp$"/> </module>

To configure the check to report unused catch parameters:

<module name="usage.UnusedParameter"> <property name="ignoreCatch" value="false"/> </module>

com.puppycrawl.tools.checkstyle.checks.usage

TreeWalker

Checks that a private field is used.

name description type default value
ignoreFormat pattern for field names that should be ignored regular expression ^$ (empty)

To configure the check:

<module name="usage.UnusedPrivateField"/>

To configure the check to ignore fields whose name ends in Temp:

<module name="usage.UnusedPrivateField"> <property name="ignoreFormat" value="Temp$"/> </module>

com.puppycrawl.tools.checkstyle.checks.usage

TreeWalker

Checks that a private method is used.

name description type default value
ignoreFormat pattern for method names that should be ignored regular expression ^$ (empty)
allowSerializationMethods whether the check should allow serialization-related methods (readObject(), writeObject(), readResolve() and writeReplace() boolean false

To configure the check:

<module name="usage.UnusedPrivateMethod"/>

To configure the check to ignore methods whose name ends in Temp:

<module name="usage.UnusedPrivateMethod"> <property name="ignoreFormat" value="Temp$"/> </module>
  • The classpath may need to be configured to locate parameter type information. The classpath configuration is dependent on the mechanism used to invoke Checkstyle.

com.puppycrawl.tools.checkstyle.checks.usage

TreeWalker

checkstyle-5.6/import-control.xml100644 0 0 3751 11451071612 14367 0ustar 0 0 checkstyle-5.6/java.header100644 0 0 2007 12026050216 12735 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// checkstyle-5.6/LICENSE100644 0 0 64466 11451071611 11713 0ustar 0 0 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! checkstyle-5.6/LICENSE.apache20100644 0 0 26450 11451071611 13264 0ustar 0 0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. checkstyle-5.6/pom.xml100644 0 0 45125 12026054767 12226 0ustar 0 0 oss-parent org.sonatype.oss 5 4.0.0 com.puppycrawl.tools checkstyle 5.6 jar checkstyle http://checkstyle.sourceforge.net/ SourceForge http://sourceforge.net/tracker/?group_id=29721 hudson http://hudson.fazend.com:8081/hudson/job/Checkstyle 2001 Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard GNU Lesser General Public License http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt scm:hg:http://checkstyle.hg.sourceforge.net:8000/hgroot/checkstyle/checkstyle scm:hg:ssh://oburn@checkstyle.hg.sourceforge.net/hgroot/checkstyle/checkstyle http://checkstyle.hg.sourceforge.net/hgweb/checkstyle/ checkstyle-snapshot-site Snapshot Site scp://shell.sourceforge.net/home/groups/c/ch/checkstyle/htdocs/snapshot oburn Oliver Burn founder lkuehne Lars Kĵhne developer rickgiles Rick Giles developer o_sukhodolsky Oleg Sukhodolsky developer mstudman Michael Studman developer tschneeberger Travis Schneeberger developer checkstyle-announce https://sourceforge.net/mailarchive/forum.php?forum_name=checkstyle-announce https://lists.sourceforge.net/mailman/listinfo/checkstyle-announce https://lists.sourceforge.net/mailman/listinfo/checkstyle-announce checkstyle-commits https://sourceforge.net/mailarchive/forum.php?forum_name=checkstyle-commits https://lists.sourceforge.net/mailman/listinfo/checkstyle-commits https://lists.sourceforge.net/mailman/listinfo/checkstyle-commits checkstyle-devel https://sourceforge.net/mailarchive/forum.php?forum_name=checkstyle-devel https://lists.sourceforge.net/mailman/listinfo/checkstyle-devel https://lists.sourceforge.net/mailman/listinfo/checkstyle-devel checkstyle-user https://sourceforge.net/mailarchive/forum.php?forum_name=checkstyle-user https://lists.sourceforge.net/mailman/listinfo/checkstyle-user https://lists.sourceforge.net/mailman/listinfo/checkstyle-user iso-8859-1 ${basedir}/src/testinputs/com/puppycrawl/tools/checkstyle ${basedir}/src/tests/com/puppycrawl/tools/checkstyle ${project.version} 1.5.0 ${java.home}/../lib/tools.jar antlr antlr 2.7.7 commons-beanutils commons-beanutils-core 1.8.3 commons-cli commons-cli 1.2 com.google.collections google-collections 1.0 org.apache.ant ant 1.7.0 provided junit junit 4.10 test src/checkstyle ${basedir}/src/checkstyle **/*.dtd **/*.properties **/*.xml src/testinputs/resources src/tests org.apache.maven.plugins maven-compiler-plugin 2.3.2 1.5 1.5 org.apache.maven.plugins maven-site-plugin 3.0-beta-3 ${basedir}/src/xdocs true org.apache.maven.plugins maven-enforcer-plugin 1.0.1 enforce-versions enforce 1.5 org.codehaus.mojo antlr-maven-plugin 2.2 ${basedir}/src/checkstyle/com/puppycrawl/tools/checkstyle/grammars java.g generate org.apache.maven.plugins maven-antrun-plugin 1.7 ant-phase-compile compile run ant-phase-verify verify run org.apache.ant ant-nodeps 1.7.1 org.apache.maven.plugins maven-surefire-plugin 2.9 testinputs.dir ${testinputs.dir} testsrcs.dir ${testsrcs.dir} -Duser.language=en -Duser.country=US org.codehaus.mojo exec-maven-plugin 1.2 runner java com.puppycrawl.tools.checkstyle.gui.Main runtime org.apache.maven.plugins maven-jar-plugin 2.3.1 true true org.codehaus.mojo cobertura-maven-plugin 2.5.1 com/puppycrawl/tools/checkstyle/CheckStyleTask*.class com/puppycrawl/tools/checkstyle/doclets/*.class com/puppycrawl/tools/checkstyle/grammars/*.class com/puppycrawl/tools/checkstyle/gui/*.class org.apache.maven.plugins maven-linkcheck-plugin 1.1 org.apache.maven.plugins maven-eclipse-plugin 2.8 true true org.apache.maven.plugins maven-javadoc-plugin 2.8 1.5 default javadoc distro org.apache.maven.plugins maven-site-plugin 3.0-beta-3 gen-site prepare-package site org.apache.maven.plugins maven-shade-plugin 1.4 package shade true all com.puppycrawl.tools.checkstyle.Main maven-assembly-plugin 2.2.1 config/assembly-bin.xml config/assembly-src.xml make-bundle package single release checkstyle-site Default Site scp://shell.sourceforge.net/home/groups/c/ch/checkstyle/htdocs release-sign-artifacts performRelease true org.apache.maven.plugins maven-gpg-plugin 1.4 sign-artifacts verify sign tools.jar-sun java.vendor Sun Microsystems Inc. com.sun tools ${tools.jar.version} system ${tools.jar.path} default-tools.jar-oracle java.vendor Oracle Corporation com.sun tools ${tools.jar.version} system ${tools.jar.path} checkstyle-5.6/README100644 0 0 2524 11451071611 11531 0ustar 0 0 CHECKSTYLE ========== This directory contains the distribution for checkstyle. It is a tool for checking Java source code for adherence to a set of rules. The latest version can be found at http://checkstyle.sourceforge.net Documentation is available in HTML format, in the "site" directory. Licensing ========= This software is licensed under the terms in the file named "LICENSE" in this directory. The software uses the ANTLR package (http://www.antlr.org). Its license terms are in the file named "RIGHTS.antlr" in this directory. This product includes software developed by The Apache Software Foundation (http://www.apache.org/). The software uses the Cli, Logging and Beanutils packages from the Apache Commons project (http://commons.apache.org/). The license terms of these packages are in the file named "LICENSE.apache20" in this directory. The software uses the Google Collections Library (http://code.google.com/p/google-collections/). The license terms of these packages are in the file named "LICENSE.apache20" in this directory. Feedback ======== Please send any feedback to checkstyle-user@lists.sourceforge.net. Bugs should be reported to the checkstyle bugtracker at http://sourceforge.net/tracker/?atid=397078&group_id=29721&func=browse Thanks for trying out checkstyle! Oliver Burn checkstyle-5.6/README-Eclipse.txt100644 0 0 421 11451075477 13721 0ustar 0 0 To run the JUnit tests in the Eclipse, you need to set the following VM arguments: -Dtestinputs.dir=${project_loc}\src\testinputs\com\puppycrawl\tools\checkstyle -Dtestsrcs.dir=${project_loc}\src\tests\com\puppycrawl\tools\checkstyle -Dcheckstyle.root=${project_loc} checkstyle-5.6/RIGHTS.antlr100644 0 0 2355 11451071611 12715 0ustar 0 0 SOFTWARE RIGHTS $Id: RIGHTS.antlr,v 1.1 2001-06-22 13:11:01 oburn Exp $ ANTLR 1989-2000 Developed by jGuru.com (MageLang Institute), http://www.ANTLR.org and http://www.jGuru.com We reserve no legal rights to the ANTLR--it is fully in the public domain. An individual or company may do whatever they wish with source code distributed with ANTLR or the code generated by ANTLR, including the incorporation of ANTLR, or its output, into commerical software. We encourage users to develop software with ANTLR. However, we do ask that credit is given to us for developing ANTLR. By "credit", we mean that if you use ANTLR or incorporate any source code into one of your programs (commercial product, research project, or otherwise) that you acknowledge this fact somewhere in the documentation, research report, etc... If you like ANTLR and have developed a nice tool with the output, please mention that you developed it using ANTLR. In addition, we ask that the headers remain intact in our source code. As long as these guidelines are kept, we expect to continue enhancing this system and expect to make other tools available as they are completed. The primary ANTLR guy: Terence Parr http://www.jGuru.com parrt@jguru.com checkstyle-5.6/src/checkstyle/checkstyletask.properties100644 0 0 73 11451071612 20673 0ustar 0 0 checkstyle=com.puppycrawl.tools.checkstyle.CheckStyleTask checkstyle-5.6/src/checkstyle/checkstyle_packages.xml100644 0 0 1555 11451071612 20320 0ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/antlib.xml100644 0 0 246 11451071612 24033 0ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.java100644 0 0 15050 12026051074 27467 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.io.File; import java.util.List; import java.util.TreeSet; /** * Provides common functionality for many FileSetChecks. * * @author lkuehne * @author oliver */ public abstract class AbstractFileSetCheck extends AbstractViolationReporter implements FileSetCheck { /** The dispatcher errors are fired to. */ private MessageDispatcher mDispatcher; /** the file extensions that are accepted by this filter */ private String[] mFileExtensions = {}; /** collects the error messages */ private final LocalizedMessages mMessages = new LocalizedMessages(); /** * Called to process a file that matches the specified file extensions. * @param aFile the file to be processed * @param aLines an immutable list of the contents of the file. */ protected abstract void processFiltered(File aFile, List aLines); /** {@inheritDoc} */ public void init() { } /** {@inheritDoc} */ public void destroy() { } /** {@inheritDoc} */ public void beginProcessing(String aCharset) { } /** {@inheritDoc} */ public final TreeSet process(File aFile, List aLines) { getMessageCollector().reset(); // Process only what interested in if (fileExtensionMatches(aFile)) { processFiltered(aFile, aLines); } return getMessageCollector().getMessages(); } /** {@inheritDoc} */ public void finishProcessing() { } /** {@inheritDoc} */ public final void setMessageDispatcher(MessageDispatcher aDispatcher) { mDispatcher = aDispatcher; } /** * A message dispatcher is used to fire violation messages to * interested audit listeners. * * @return the current MessageDispatcher. */ protected final MessageDispatcher getMessageDispatcher() { return mDispatcher; } /** * Sets the file extensions that identify the files that pass the * filter of this FileSetCheck. * @param aExtensions the set of file extensions. A missing * initial '.' character of an extension is automatically added. */ public final void setFileExtensions(String[] aExtensions) { if (aExtensions == null) { mFileExtensions = null; return; } mFileExtensions = new String[aExtensions.length]; for (int i = 0; i < aExtensions.length; i++) { final String extension = aExtensions[i]; if (extension.startsWith(".")) { mFileExtensions[i] = extension; } else { mFileExtensions[i] = "." + extension; } } } /** * Returns the collector for violation messages. * Subclasses can use the collector to find out the violation * messages to fire via the message dispatcher. * * @return the collector for localized messages. */ protected final LocalizedMessages getMessageCollector() { return mMessages; } @Override public final void log(int aLine, String aKey, Object... aArgs) { log(aLine, 0, aKey, aArgs); } @Override public final void log(int aLineNo, int aColNo, String aKey, Object... aArgs) { getMessageCollector().add( new LocalizedMessage(aLineNo, aColNo, getMessageBundle(), aKey, aArgs, getSeverityLevel(), getId(), this.getClass(), this.getCustomMessages().get(aKey))); } /** * Notify all listeners about the errors in a file. * Calls MessageDispatcher.fireErrors() with * all logged errors and than clears errors' list. * @param aFileName the audited file */ protected final void fireErrors(String aFileName) { final TreeSet errors = getMessageCollector() .getMessages(); getMessageCollector().reset(); getMessageDispatcher().fireErrors(aFileName, errors); } /** * Returns whether the file extension matches what we are meant to * process. * @param aFile the file to be checked. * @return whether there is a match. */ private boolean fileExtensionMatches(File aFile) { if ((null == mFileExtensions) || (mFileExtensions.length == 0)) { return true; } // normalize extensions so all of them have a leading dot final String[] withDotExtensions = new String[mFileExtensions.length]; for (int i = 0; i < mFileExtensions.length; i++) { final String extension = mFileExtensions[i]; if (extension.startsWith(".")) { withDotExtensions[i] = extension; } else { withDotExtensions[i] = "." + extension; } } final String fileName = aFile.getName(); for (final String fileExtension : withDotExtensions) { if (fileName.endsWith(fileExtension)) { return true; } } return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/AbstractLoader.java100644 0 0 12252 12026051074 26405 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.google.common.collect.Maps; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; /** * Contains the common implementation of a loader, for loading a configuration * from an XML file. *

* The error handling policy can be described as being austere, dead set, * disciplinary, dour, draconian, exacting, firm, forbidding, grim, hard, hard- * boiled, harsh, harsh, in line, iron-fisted, no-nonsense, oppressive, * persnickety, picky, prudish, punctilious, puritanical, rigid, rigorous, * scrupulous, set, severe, square, stern, stickler, straight, strait-laced, * stringent, stuffy, stuffy, tough, unpermissive, unsparing and uptight. * * @author Oliver Burn */ public abstract class AbstractLoader extends DefaultHandler { /** maps public id to resolve to esource name for the DTD */ private final Map mPublicIdToResourceNameMap; /** parser to read XML files **/ private final XMLReader mParser; /** * Creates a new instance. * @param aPublicId the public ID for the DTD to resolve * @param aDtdResourceName the resource for the DTD * @throws SAXException if an error occurs * @throws ParserConfigurationException if an error occurs */ protected AbstractLoader(String aPublicId, String aDtdResourceName) throws SAXException, ParserConfigurationException { this(new HashMap(1)); mPublicIdToResourceNameMap.put(aPublicId, aDtdResourceName); } /** * Creates a new instance. * @param aPublicIdToResourceNameMap maps public IDs to DTD resource names * @throws SAXException if an error occurs * @throws ParserConfigurationException if an error occurs */ protected AbstractLoader(Map aPublicIdToResourceNameMap) throws SAXException, ParserConfigurationException { mPublicIdToResourceNameMap = Maps.newHashMap(aPublicIdToResourceNameMap); final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); factory.setNamespaceAware(true); mParser = factory.newSAXParser().getXMLReader(); mParser.setContentHandler(this); mParser.setEntityResolver(this); mParser.setErrorHandler(this); } /** * Parses the specified input source. * @param aInputSource the input source to parse. * @throws IOException if an error occurs * @throws SAXException in an error occurs */ public void parseInputSource(InputSource aInputSource) throws IOException, SAXException { mParser.parse(aInputSource); } @Override public InputSource resolveEntity(String aPublicId, String aSystemId) throws SAXException, IOException { if (mPublicIdToResourceNameMap.keySet().contains(aPublicId)) { final String dtdResourceName = mPublicIdToResourceNameMap.get(aPublicId); final ClassLoader loader = this.getClass().getClassLoader(); final InputStream dtdIS = loader.getResourceAsStream(dtdResourceName); if (dtdIS == null) { throw new SAXException( "Unable to load internal dtd " + dtdResourceName); } return new InputSource(dtdIS); } return super.resolveEntity(aPublicId, aSystemId); } @Override public void warning(SAXParseException aEx) throws SAXException { throw aEx; } @Override public void error(SAXParseException aEx) throws SAXException { throw aEx; } @Override public void fatalError(SAXParseException aEx) throws SAXException { throw aEx; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/AbstractViolationReporter.java100644 0 0 13313 12026051073 30664 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.util.Map; /** * Serves as an abstract base class for all modules that report inspection * findings. Such modules have a Severity level which is used for the * {@link LocalizedMessage localized messages} that are created by the module. * * @author lkuehne */ public abstract class AbstractViolationReporter extends AutomaticBean { /** the severity level of any violations found */ private SeverityLevel mSeverityLevel = SeverityLevel.ERROR; /** the identifier of the reporter */ private String mId; /** * Returns the severity level of the messages generated by this module. * @return the severity level * @see SeverityLevel * @see LocalizedMessage#getSeverityLevel */ public final SeverityLevel getSeverityLevel() { return mSeverityLevel; } /** * Sets the severity level. The string should be one of the names * defined in the SeverityLevel class. * * @param aSeverity The new severity level * @see SeverityLevel */ public final void setSeverity(String aSeverity) { mSeverityLevel = SeverityLevel.getInstance(aSeverity); } /** * Get the severity level's name. * * @return the check's severity level name. */ public final String getSeverity() { return mSeverityLevel.getName(); } /** * Returns the identifier of the reporter. Can be null. * @return the id */ public final String getId() { return mId; } /** * Sets the identifier of the reporter. Can be null. * @param aId the id */ public final void setId(final String aId) { mId = aId; } /** * Helper method to log a LocalizedMessage. * * @param aAST a node to get line and column numbers associated * with the message * @param aKey key to locale message format * @param aArgs arguments to format */ protected final void log(DetailAST aAST, String aKey, Object... aArgs) { log(aAST.getLineNo(), aAST.getColumnNo(), aKey, aArgs); } /** * Returns the message bundle name resourcebundle that contains the messages * used by this module. *

* The default implementation expects the resource files to be named * messages.properties, messages_de.properties, etc. The file must * be placed in the same package as the module implementation. *

*

* Example: If you write com/foo/MyCoolCheck, create resource files * com/foo/messages.properties, com/foo/messages_de.properties, etc. *

* * @return name of a resource bundle that contains the messages * used by this module. */ protected String getMessageBundle() { final String className = this.getClass().getName(); return getMessageBundle(className); } /** * Returns an unmodifiable map instance containing the custom messages * for this configuration. * @return unmodifiable map containing custom messages */ protected Map getCustomMessages() { return getConfiguration().getMessages(); } /** * for unit tests, especially with a class with no package name. * @param aClassName class name of the module. * @return name of a resource bundle that contains the messages * used by the module. */ String getMessageBundle(final String aClassName) { final int endIndex = aClassName.lastIndexOf('.'); final String messages = "messages"; if (endIndex < 0) { return messages; } final String packageName = aClassName.substring(0, endIndex); return packageName + "." + messages; } /** * Log a message that has no column information. * * @param aLine the line number where the error was found * @param aKey the message that describes the error * @param aArgs the details of the message * * @see java.text.MessageFormat */ public abstract void log(int aLine, String aKey, Object... aArgs); /** * Log a message that has column information. * * @param aLine the line number where the error was found * @param aCol the column number where the error was found * @param aKey the message that describes the error * @param aArgs the details of the message * * @see java.text.MessageFormat */ public abstract void log(int aLine, int aCol, String aKey, Object... aArgs); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/AnnotationUtility.java100644 0 0 16107 12026051073 27213 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** * Contains utility methods designed to work with annotations. * * @author Travis Schneeberger */ public final class AnnotationUtility { /** * private utility constructor. * @throws UnsupportedOperationException if called */ private AnnotationUtility() { throw new UnsupportedOperationException("do not instantiate."); } /** * Checks to see if the AST is annotated with * the passed in annotation. * *

* This method will not look for imports or package * statements to detect the passed in annotation. *

* *

* To check if an AST contains a passed in annotation * taking into account fully-qualified names * (ex: java.lang.Override, Override) * this method will need to be called twice. Once for each * name given. *

* * @param aAST the current node * @param aAnnotation the annotation name to check for * @return true if contains the annotation * @throws NullPointerException if the aAST or * aAnnotation is null */ public static boolean containsAnnotation(final DetailAST aAST, String aAnnotation) { return AnnotationUtility.getAnnotation(aAST, aAnnotation) != null; } /** * Checks to see if the AST is annotated with * any annotation. * * @param aAST the current node * @return true if contains an annotation * @throws NullPointerException if the aAST is null */ public static boolean containsAnnotation(final DetailAST aAST) { final DetailAST holder = AnnotationUtility.getAnnotationHolder(aAST); return holder != null && holder.branchContains(TokenTypes.ANNOTATION); } /** * Gets the AST that holds a series of annotations for the * potentially annotated AST. Returns null * the passed in AST is not have an Annotation Holder. * * @param aAST the current node * @return the Annotation Holder * @throws NullPointerException if the aAST is null */ public static DetailAST getAnnotationHolder(DetailAST aAST) { if (aAST == null) { throw new NullPointerException("the aAST is null"); } final DetailAST annotationHolder; if (aAST.getType() == TokenTypes.ENUM_CONSTANT_DEF || aAST.getType() == TokenTypes.PACKAGE_DEF) { annotationHolder = aAST.findFirstToken(TokenTypes.ANNOTATIONS); } else { annotationHolder = aAST.findFirstToken(TokenTypes.MODIFIERS); } return annotationHolder; } /** * Checks to see if the AST is annotated with * the passed in annotation and return the AST * representing that annotation. * *

* This method will not look for imports or package * statements to detect the passed in annotation. *

* *

* To check if an AST contains a passed in annotation * taking into account fully-qualified names * (ex: java.lang.Override, Override) * this method will need to be called twice. Once for each * name given. *

* * @param aAST the current node * @param aAnnotation the annotation name to check for * @return the AST representing that annotation * @throws NullPointerException if the aAST or * aAnnotation is null */ public static DetailAST getAnnotation(final DetailAST aAST, String aAnnotation) { if (aAST == null) { throw new NullPointerException("the aAST is null"); } if (aAnnotation == null) { throw new NullPointerException("the aAnnotation is null"); } if (aAnnotation.trim().length() == 0) { throw new IllegalArgumentException("the aAnnotation" + "is empty or spaces"); } final DetailAST holder = AnnotationUtility.getAnnotationHolder(aAST); for (DetailAST child = holder.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getType() == TokenTypes.ANNOTATION) { final DetailAST at = child.getFirstChild(); final String aName = FullIdent.createFullIdent(at.getNextSibling()).getText(); if (aAnnotation.equals(aName)) { return child; } } } return null; } /** * Checks to see what the passed in AST (representing * an annotation) is annotating. * * @param aAST the AST representing an annotation. * @return the AST the annotation is annotating. * @throws NullPointerException if the aAST is null * @throws IllegalArgumentException if the aAST is not * an {@link TokenTypes#ANNOTATION} */ public static DetailAST annotatingWhat(DetailAST aAST) { if (aAST == null) { throw new NullPointerException("the aAST is null"); } if (aAST.getType() != TokenTypes.ANNOTATION) { throw new IllegalArgumentException( "The aAST is not an annotation. AST: " + aAST); } return aAST.getParent().getParent(); } /** * Checks to see if the passed in AST (representing * an annotation) is annotating the passed in type. * @param aAST the AST representing an annotation * @param aTokenType the passed in type * @return true if the annotation is annotating a type * equal to the passed in type * @throws NullPointerException if the aAST is null * @throws IllegalArgumentException if the aAST is not * an {@link TokenTypes#ANNOTATION} */ public static boolean isAnnotatingType(DetailAST aAST, int aTokenType) { final DetailAST ast = AnnotationUtility.annotatingWhat(aAST); return ast.getType() == aTokenType; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/AuditEvent.java100644 0 0 10707 12026051073 25565 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.util.EventObject; /** * Raw event for audit. *

* * I'm not very satisfied about the design of this event since there are * optional methods that will return null in most of the case. This will * need some work to clean it up especially if we want to introduce * a more sequential reporting action rather than a packet error * reporting. This will allow for example to follow the process quickly * in an interface or a servlet (yep, that's cool to run a check via * a web interface in a source repository ;-) * * @author Stephane Bailliez * @see AuditListener */ public final class AuditEvent extends EventObject { /** Record a version. */ private static final long serialVersionUID = -3774725606973812736L; /** filename event associated with **/ private final String mFileName; /** message associated with the event **/ private final transient LocalizedMessage mMessage; /** * Creates a new instance. * @param aSource the object that created the event */ public AuditEvent(Object aSource) { this(aSource, null); } /** * Creates a new AuditEvent instance. * @param aSrc source of the event * @param aFileName file associated with the event */ public AuditEvent(Object aSrc, String aFileName) { this(aSrc, aFileName, null); } /** * Creates a new AuditEvent instance. * * @param aSrc source of the event * @param aFileName file associated with the event * @param aMessage the actual message */ public AuditEvent(Object aSrc, String aFileName, LocalizedMessage aMessage) { super(aSrc); mFileName = aFileName; mMessage = aMessage; } /** * @return the file name currently being audited or null if there is * no relation to a file. */ public String getFileName() { return mFileName; } /** * return the line number on the source file where the event occurred. * This may be 0 if there is no relation to a file content. * @return an integer representing the line number in the file source code. */ public int getLine() { return mMessage.getLineNo(); } /** * return the message associated to the event. * @return the event message */ public String getMessage() { return mMessage.getMessage(); } /** @return the column associated with the message **/ public int getColumn() { return mMessage.getColumnNo(); } /** @return the audit event severity level **/ public SeverityLevel getSeverityLevel() { return (mMessage == null) ? SeverityLevel.INFO : mMessage.getSeverityLevel(); } /** * @return the identifier of the module that generated the event. Can return * null. */ public String getModuleId() { return mMessage.getModuleId(); } /** @return the name of the source for the message **/ public String getSourceName() { return mMessage.getSourceName(); } /** @return the localized message **/ public LocalizedMessage getLocalizedMessage() { return mMessage; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/AuditListener.java100644 0 0 4674 12026051073 26257 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.util.EventListener; /** * Listener in charge of receiving events from the Checker. * Typical events sequence is: *

 * auditStarted
 *   (fileStarted
 *     (addError)*
 *   fileFinished )*
 * auditFinished
 * 
* @author Stephane Bailliez */ public interface AuditListener extends EventListener { /** * Notify that the audit is about to start. * @param aEvt the event details */ void auditStarted(AuditEvent aEvt); /** * Notify that the audit is finished. * @param aEvt the event details */ void auditFinished(AuditEvent aEvt); /** * Notify that audit is about to start on a specific file. * @param aEvt the event details */ void fileStarted(AuditEvent aEvt); /** * Notify that audit is finished on a specific file. * @param aEvt the event details */ void fileFinished(AuditEvent aEvt); /** * Notify that an audit error was discovered on a specific file. * @param aEvt the event details */ void addError(AuditEvent aEvt); /** * Notify that an exception happened while performing audit. * @param aEvt the event details * @param aThrowable details of the exception */ void addException(AuditEvent aEvt, Throwable aThrowable); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/AutomaticBean.java100644 0 0 30416 12026051073 26230 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.google.common.collect.Lists; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.List; import java.util.StringTokenizer; import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.ConvertUtilsBean; import org.apache.commons.beanutils.Converter; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.PropertyUtilsBean; import org.apache.commons.beanutils.converters.ArrayConverter; import org.apache.commons.beanutils.converters.BooleanConverter; import org.apache.commons.beanutils.converters.ByteConverter; import org.apache.commons.beanutils.converters.CharacterConverter; import org.apache.commons.beanutils.converters.DoubleConverter; import org.apache.commons.beanutils.converters.FloatConverter; import org.apache.commons.beanutils.converters.IntegerConverter; import org.apache.commons.beanutils.converters.LongConverter; import org.apache.commons.beanutils.converters.ShortConverter; /** * A Java Bean that implements the component lifecycle interfaces by * calling the bean's setters for all configuration attributes. * @author lkuehne */ public class AutomaticBean implements Configurable, Contextualizable { /** the configuration of this bean */ private Configuration mConfiguration; /** * Creates a BeanUtilsBean that is configured to use * type converters that throw a ConversionException * instead of using the default value when something * goes wrong. * * @return a configured BeanUtilsBean */ private static BeanUtilsBean createBeanUtilsBean() { final ConvertUtilsBean cub = new ConvertUtilsBean(); // TODO: is there a smarter way to tell beanutils not to use defaults? cub.register(new BooleanConverter(), Boolean.TYPE); cub.register(new BooleanConverter(), Boolean.class); cub.register(new ArrayConverter( boolean[].class, new BooleanConverter()), boolean[].class); cub.register(new ByteConverter(), Byte.TYPE); cub.register(new ByteConverter(), Byte.class); cub.register(new ArrayConverter(byte[].class, new ByteConverter()), byte[].class); cub.register(new CharacterConverter(), Character.TYPE); cub.register(new CharacterConverter(), Character.class); cub.register(new ArrayConverter(char[].class, new CharacterConverter()), char[].class); cub.register(new DoubleConverter(), Double.TYPE); cub.register(new DoubleConverter(), Double.class); cub.register(new ArrayConverter(double[].class, new DoubleConverter()), double[].class); cub.register(new FloatConverter(), Float.TYPE); cub.register(new FloatConverter(), Float.class); cub.register(new ArrayConverter(float[].class, new FloatConverter()), float[].class); cub.register(new IntegerConverter(), Integer.TYPE); cub.register(new IntegerConverter(), Integer.class); cub.register(new ArrayConverter(int[].class, new IntegerConverter()), int[].class); cub.register(new LongConverter(), Long.TYPE); cub.register(new LongConverter(), Long.class); cub.register(new ArrayConverter(long[].class, new LongConverter()), long[].class); cub.register(new ShortConverter(), Short.TYPE); cub.register(new ShortConverter(), Short.class); cub.register(new ArrayConverter(short[].class, new ShortConverter()), short[].class); cub.register(new RelaxedStringArrayConverter(), String[].class); // BigDecimal, BigInteger, Class, Date, String, Time, TimeStamp // do not use defaults in the default configuration of ConvertUtilsBean return new BeanUtilsBean(cub, new PropertyUtilsBean()); } /** * Implements the Configurable interface using bean introspection. * * Subclasses are allowed to add behaviour. After the bean * based setup has completed first the method * {@link #finishLocalSetup finishLocalSetup} * is called to allow completion of the bean's local setup, * after that the method {@link #setupChild setupChild} * is called for each {@link Configuration#getChildren child Configuration} * of aConfiguration. * * @param aConfiguration {@inheritDoc} * @throws CheckstyleException {@inheritDoc} * @see Configurable */ public final void configure(Configuration aConfiguration) throws CheckstyleException { mConfiguration = aConfiguration; final BeanUtilsBean beanUtils = createBeanUtilsBean(); // TODO: debug log messages final String[] attributes = aConfiguration.getAttributeNames(); for (final String key : attributes) { final String value = aConfiguration.getAttribute(key); try { // BeanUtilsBean.copyProperties silently ignores missing setters // for key, so we have to go through great lengths here to // figure out if the bean property really exists. final PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(this, key); if ((pd == null) || (pd.getWriteMethod() == null)) { throw new CheckstyleException( "Property '" + key + "' in module " + aConfiguration.getName() + " does not exist, please check the documentation"); } // finally we can set the bean property beanUtils.copyProperty(this, key, value); } catch (final InvocationTargetException e) { throw new CheckstyleException( "Cannot set property '" + key + "' in module " + aConfiguration.getName() + " to '" + value + "': " + e.getTargetException().getMessage(), e); } catch (final IllegalAccessException e) { throw new CheckstyleException( "cannot access " + key + " in " + this.getClass().getName(), e); } catch (final NoSuchMethodException e) { throw new CheckstyleException( "cannot access " + key + " in " + this.getClass().getName(), e); } catch (final IllegalArgumentException e) { throw new CheckstyleException( "illegal value '" + value + "' for property '" + key + "' of module " + aConfiguration.getName(), e); } catch (final ConversionException e) { throw new CheckstyleException( "illegal value '" + value + "' for property '" + key + "' of module " + aConfiguration.getName(), e); } } finishLocalSetup(); final Configuration[] childConfigs = aConfiguration.getChildren(); for (final Configuration childConfig : childConfigs) { setupChild(childConfig); } } /** * Implements the Contextualizable interface using bean introspection. * @param aContext {@inheritDoc} * @throws CheckstyleException {@inheritDoc} * @see Contextualizable */ public final void contextualize(Context aContext) throws CheckstyleException { final BeanUtilsBean beanUtils = createBeanUtilsBean(); // TODO: debug log messages final Collection attributes = aContext.getAttributeNames(); for (final String key : attributes) { final Object value = aContext.get(key); try { beanUtils.copyProperty(this, key, value); } catch (final InvocationTargetException e) { // TODO: log.debug("The bean " + this.getClass() // + " is not interested in " + value) throw new CheckstyleException("cannot set property " + key + " to value " + value + " in bean " + this.getClass().getName(), e); } catch (final IllegalAccessException e) { throw new CheckstyleException( "cannot access " + key + " in " + this.getClass().getName(), e); } catch (final IllegalArgumentException e) { throw new CheckstyleException( "illegal value '" + value + "' for property '" + key + "' of bean " + this.getClass().getName(), e); } catch (final ConversionException e) { throw new CheckstyleException( "illegal value '" + value + "' for property '" + key + "' of bean " + this.getClass().getName(), e); } } } /** * Returns the configuration that was used to configure this component. * @return the configuration that was used to configure this component. */ protected final Configuration getConfiguration() { return mConfiguration; } /** * Provides a hook to finish the part of this component's setup that * was not handled by the bean introspection. *

* The default implementation does nothing. *

* @throws CheckstyleException if there is a configuration error. */ protected void finishLocalSetup() throws CheckstyleException { } /** * Called by configure() for every child of this component's Configuration. *

* The default implementation does nothing. *

* @param aChildConf a child of this component's Configuration * @throws CheckstyleException if there is a configuration error. * @see Configuration#getChildren */ protected void setupChild(Configuration aChildConf) throws CheckstyleException { } /** * A converter that does not care whether the array elements contain String * characters like '*' or '_'. The normal ArrayConverter class has problems * with this characters. */ private static class RelaxedStringArrayConverter implements Converter { /** {@inheritDoc} */ public Object convert(@SuppressWarnings("rawtypes") Class aType, Object aValue) { if (null == aType) { throw new ConversionException("Cannot convert from null."); } // Convert to a String and trim it for the tokenizer. final StringTokenizer st = new StringTokenizer( aValue.toString().trim(), ","); final List result = Lists.newArrayList(); while (st.hasMoreTokens()) { final String token = st.nextToken(); result.add(token.trim()); } return result.toArray(new String[result.size()]); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/Check.java100644 0 0 16511 12026051072 24530 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.google.common.collect.Sets; import java.util.Set; /** * The base class for checks. * * @author Oliver Burn * @version 1.0 * @see Writing * your own checks */ public abstract class Check extends AbstractViolationReporter { /** default tab width for column reporting */ private static final int DEFAULT_TAB_WIDTH = 8; /** the current file contents */ private FileContents mFileContents; /** the tokens the check is interested in */ private final Set mTokens = Sets.newHashSet(); /** the object for collecting messages. */ private LocalizedMessages mMessages; /** the tab width for column reporting */ private int mTabWidth = DEFAULT_TAB_WIDTH; // meaningful default /** * The class loader to load external classes. Not initialised as this must * be set by my creator. */ private ClassLoader mLoader; /** * Returns the default token a check is interested in. Only used if the * configuration for a check does not define the tokens. * @return the default tokens * @see TokenTypes */ public abstract int[] getDefaultTokens(); /** * The configurable token set. * Used to protect Checks against malicious users who specify an * unacceptable token set in the configuration file. * The default implementation returns the check's default tokens. * @return the token set this check is designed for. * @see TokenTypes */ public int[] getAcceptableTokens() { final int[] defaultTokens = getDefaultTokens(); final int[] copy = new int[defaultTokens.length]; System.arraycopy(defaultTokens, 0, copy, 0, defaultTokens.length); return copy; } /** * The tokens that this check must be registered for. * @return the token set this must be registered for. * @see TokenTypes */ public int[] getRequiredTokens() { return new int[] {}; } /** * Adds a set of tokens the check is interested in. * @param aStrRep the string representation of the tokens interested in */ public final void setTokens(String[] aStrRep) { for (final String s : aStrRep) { mTokens.add(s); } } /** * Returns the tokens registered for the check. * @return the set of token names */ public final Set getTokenNames() { return mTokens; } /** * Set the global object used to collect messages. * @param aMessages the messages to log with */ public final void setMessages(LocalizedMessages aMessages) { mMessages = aMessages; } /** * Initialise the check. This is the time to verify that the check has * everything required to perform it job. */ public void init() { } /** * Destroy the check. It is being retired from service. */ public void destroy() { } /** * Called before the starting to process a tree. Ideal place to initialise * information that is to be collected whilst processing a tree. * @param aRootAST the root of the tree */ public void beginTree(DetailAST aRootAST) { } /** * Called after finished processing a tree. Ideal place to report on * information collected whilst processing a tree. * @param aRootAST the root of the tree */ public void finishTree(DetailAST aRootAST) { } /** * Called to process a token. * @param aAST the token to process */ public void visitToken(DetailAST aAST) { } /** * Called after all the child nodes have been process. * @param aAST the token leaving */ public void leaveToken(DetailAST aAST) { } /** * Returns the lines associated with the tree. * @return the file contents */ public final String[] getLines() { return getFileContents().getLines(); } /** * Set the file contents associated with the tree. * @param aContents the manager */ public final void setFileContents(FileContents aContents) { mFileContents = aContents; } /** * Returns the file contents associated with the tree. * @return the file contents */ public final FileContents getFileContents() { return mFileContents; } /** * Set the class loader associated with the tree. * @param aLoader the class loader */ public final void setClassLoader(ClassLoader aLoader) { mLoader = aLoader; } /** * Returns the class loader associated with the tree. * @return the class loader */ public final ClassLoader getClassLoader() { return mLoader; } /** @return the tab width to report errors with */ protected final int getTabWidth() { return mTabWidth; } /** * Set the tab width to report errors with. * @param aTabWidth an int value */ public final void setTabWidth(int aTabWidth) { mTabWidth = aTabWidth; } @Override public final void log(int aLine, String aKey, Object... aArgs) { mMessages.add( new LocalizedMessage( aLine, getMessageBundle(), aKey, aArgs, getSeverityLevel(), getId(), this.getClass(), this.getCustomMessages().get(aKey))); } @Override public final void log(int aLineNo, int aColNo, String aKey, Object... aArgs) { final int col = 1 + Utils.lengthExpandedTabs( getLines()[aLineNo - 1], aColNo, getTabWidth()); mMessages.add( new LocalizedMessage( aLineNo, col, getMessageBundle(), aKey, aArgs, getSeverityLevel(), getId(), this.getClass(), this.getCustomMessages().get(aKey))); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/CheckstyleException.java100644 0 0 3710 12026051072 27445 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** * Represents an error condition within Checkstyle. * * @author Oliver Burn * @version 1.0 */ public class CheckstyleException extends Exception { /** For Serialisation that will never happen. */ private static final long serialVersionUID = -3517342299748221108L; /** * Creates a new CheckstyleException instance. * * @param aMessage a String value */ public CheckstyleException(String aMessage) { super(aMessage); } /** * Creates a new CheckstyleException instance * that was caused by another exception. * * @param aMessage a message that explains this exception * @param aCause the Exception that is wrapped by this exception */ public CheckstyleException(String aMessage, Throwable aCause) { super(aMessage, aCause); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/Comment.java100644 0 0 7110 12026051072 25070 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** * Representation of the comment block. * * @author o_sukhodolsky */ public class Comment implements TextBlock { /** text of the comment. */ private final String[] mText; /** number of first line of the comment. */ private final int mFirstLine; /** number of last line of the comment. */ private final int mLastLine; /** number of first column of the comment. */ private final int mFirstCol; /** number of last column of the comment. */ private final int mLastCol; /** * Creates new instance. * @param aText the lines that make up the comment. * @param aFirstCol number of the first column of the comment. * @param aLastLine number of the last line of the comment. * @param aLastCol number of the last column of the comment. */ public Comment(final String[] aText, final int aFirstCol, final int aLastLine, final int aLastCol) { mText = new String[aText.length]; System.arraycopy(aText, 0, mText, 0, mText.length); mFirstLine = aLastLine - mText.length + 1; mLastLine = aLastLine; mFirstCol = aFirstCol; mLastCol = aLastCol; } /** {@inheritDoc} */ public final String[] getText() { return mText.clone(); } /** {@inheritDoc} */ public final int getStartLineNo() { return mFirstLine; } /** {@inheritDoc} */ public final int getEndLineNo() { return mLastLine; } /** {@inheritDoc} */ public int getStartColNo() { return mFirstCol; } /** {@inheritDoc} */ public int getEndColNo() { return mLastCol; } /** {@inheritDoc} */ public boolean intersects(int aStartLineNo, int aStartColNo, int aEndLineNo, int aEndColNo) { // compute a single number for start and end // to simpify conditional logic final long multiplier = Integer.MAX_VALUE; final long thisStart = mFirstLine * multiplier + mFirstCol; final long thisEnd = mLastLine * multiplier + mLastCol; final long inStart = aStartLineNo * multiplier + aStartColNo; final long inEnd = aEndLineNo * multiplier + aEndColNo; return !((thisEnd < inStart) || (inEnd < thisStart)); } @Override public String toString() { return "Comment[" + mFirstLine + ":" + mFirstCol + "-" + mLastLine + ":" + mLastCol + "]"; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/Configurable.java100644 0 0 3105 12026051072 26066 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** * A component that can be configured. The general idea of * Configuration/Configurable was taken from Jakarta's Avalon framework. * @author lkuehne */ public interface Configurable { /** * Configures this component. * @param aConfiguration the configuration to use. * @throws CheckstyleException if there is a configuration error. */ void configure(Configuration aConfiguration) throws CheckstyleException; } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/Configuration.java100644 0 0 4634 12026051071 26304 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.google.common.collect.ImmutableMap; import java.io.Serializable; /** * A Configuration is used to configure a Configurable component. The general * idea of Configuration/Configurable was taken from Jakarta's Avalon framework. * @author lkuehne */ public interface Configuration extends Serializable { /** * The set of attribute names. * @return The set of attribute names, never null. */ String[] getAttributeNames(); /** * The attribute value for an attribute name. * @param aName the attribute name * @return the value that is associated with aName * @throws CheckstyleException if aName is not a valid attribute name */ String getAttribute(String aName) throws CheckstyleException; /** * The set of child configurations. * @return The set of child configurations, never null. */ Configuration[] getChildren(); /** * The name of this configuration. * @return The name of this configuration. */ String getName(); /** * Returns an unmodifiable map instance containing the custom messages * for this configuration. * @return unmodifiable map containing custom messages */ ImmutableMap getMessages(); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/Context.java100644 0 0 3521 12026051071 25113 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.google.common.collect.ImmutableCollection; /** * A context to be used in subcomponents. The general idea of * Context/Contextualizable was taken from Jakarta's Avalon framework. * @author lkuehne * @see Contextualizable */ public interface Context { /** * Searches for the value with the specified attribute key in this context. * @param aKey the attribute key. * @return the value in this context with the specified attribute key value. */ Object get(String aKey); /** * Returns the names of all atttributes of this context. * @return the names of all atttributes of this context. */ ImmutableCollection getAttributeNames(); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/Contextualizable.java100644 0 0 3353 12026051071 27007 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** * A Component that needs context information from it's container to work. * The container will create a Context object and pass it to this * Contextualizable. Contextualization will occur before configuration. The * general idea of Context/Contextualizable was taken from Jakarta's Avalon framework. * @author lkuehne */ public interface Contextualizable { /** * Sets the context for this Component. * @param aContext the context. * @throws CheckstyleException if there is a contextualization error. */ void contextualize(Context aContext) throws CheckstyleException; } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/DetailAST.java100644 0 0 22135 12026051071 25263 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.util.BitSet; import antlr.CommonAST; import antlr.Token; import antlr.collections.AST; /** * An extension of the CommonAST that records the line and column * number. The idea was taken from Java Guru * FAQ: How can I include line numbers in automatically generated * ASTs?. * @author Oliver Burn * @author lkuehne * @version 1.0 * @see ANTLR Website */ public final class DetailAST extends CommonAST { /** For Serialisation that will never happen. */ private static final long serialVersionUID = -2580884815577559874L; /** constant to indicate if not calculated the child count */ private static final int NOT_INITIALIZED = Integer.MIN_VALUE; /** the line number **/ private int mLineNo = NOT_INITIALIZED; /** the column number **/ private int mColumnNo = NOT_INITIALIZED; /** number of children */ private int mChildCount = NOT_INITIALIZED; /** the parent token */ private DetailAST mParent; /** previous sibling */ private DetailAST mPreviousSibling; /** * All token types in this branch. * Token 'x' (where x is an int) is in this branch * if mBranchTokenTypes.get(x) is true. */ private BitSet mBranchTokenTypes; @Override public void initialize(Token aTok) { super.initialize(aTok); mLineNo = aTok.getLine(); mColumnNo = aTok.getColumn() - 1; // expect columns to start @ 0 } @Override public void initialize(AST aAST) { final DetailAST da = (DetailAST) aAST; setText(da.getText()); setType(da.getType()); mLineNo = da.getLineNo(); mColumnNo = da.getColumnNo(); } @Override public void setFirstChild(AST aAST) { mChildCount = NOT_INITIALIZED; super.setFirstChild(aAST); if (aAST != null) { ((DetailAST) aAST).setParent(this); } } @Override public void setNextSibling(AST aAST) { super.setNextSibling(aAST); if ((aAST != null) && (mParent != null)) { ((DetailAST) aAST).setParent(mParent); } if (aAST != null) { ((DetailAST) aAST).setPreviousSibling(this); } } /** * Sets previous sibling. * @param aAST a previous sibling */ void setPreviousSibling(DetailAST aAST) { mPreviousSibling = aAST; } @Override public void addChild(AST aAST) { super.addChild(aAST); if (aAST != null) { ((DetailAST) aAST).setParent(this); (getFirstChild()).setParent(this); } } /** * Returns the number of child nodes one level below this node. That is is * does not recurse down the tree. * @return the number of child nodes */ public int getChildCount() { // lazy init if (mChildCount == NOT_INITIALIZED) { mChildCount = 0; AST child = getFirstChild(); while (child != null) { mChildCount += 1; child = child.getNextSibling(); } } return mChildCount; } /** * Set the parent token. * @param aParent the parent token */ // TODO: should be private but that breaks the DetailASTTest // until we manage parent in DetailAST instead of externally void setParent(DetailAST aParent) { // TODO: Check visibility, could be private // if set in setFirstChild() and friends mParent = aParent; final DetailAST nextSibling = getNextSibling(); if (nextSibling != null) { nextSibling.setParent(aParent); nextSibling.setPreviousSibling(this); } } /** * Returns the parent token. * @return the parent token */ public DetailAST getParent() { return mParent; } /** @return the line number **/ public int getLineNo() { if (mLineNo == NOT_INITIALIZED) { // an inner AST that has been initialized // with initialize(String text) final DetailAST child = getFirstChild(); final DetailAST sibling = getNextSibling(); if (child != null) { return child.getLineNo(); } else if (sibling != null) { return sibling.getLineNo(); } } return mLineNo; } /** @return the column number **/ public int getColumnNo() { if (mColumnNo == NOT_INITIALIZED) { // an inner AST that has been initialized // with initialize(String text) final DetailAST child = getFirstChild(); final DetailAST sibling = getNextSibling(); if (child != null) { return child.getColumnNo(); } else if (sibling != null) { return sibling.getColumnNo(); } } return mColumnNo; } /** @return the last child node */ public DetailAST getLastChild() { DetailAST ast = getFirstChild(); while ((ast != null) && (ast.getNextSibling() != null)) { ast = ast.getNextSibling(); } return ast; } /** * @return the token types that occur in the branch as a sorted set. */ private BitSet getBranchTokenTypes() { // lazy init if (mBranchTokenTypes == null) { mBranchTokenTypes = new BitSet(); mBranchTokenTypes.set(getType()); // add union of all childs DetailAST child = getFirstChild(); while (child != null) { final BitSet childTypes = child.getBranchTokenTypes(); mBranchTokenTypes.or(childTypes); child = child.getNextSibling(); } } return mBranchTokenTypes; } /** * Checks if this branch of the parse tree contains a token * of the provided type. * @param aType a TokenType * @return true if and only if this branch (including this node) * contains a token of type aType. */ public boolean branchContains(int aType) { return getBranchTokenTypes().get(aType); } /** * Returns the number of direct child tokens that have the specified type. * @param aType the token type to match * @return the number of matching token */ public int getChildCount(int aType) { int count = 0; for (AST i = getFirstChild(); i != null; i = i.getNextSibling()) { if (i.getType() == aType) { count++; } } return count; } /** * Returns the previous sibling or null if no such sibling exists. * @return the previous sibling or null if no such sibling exists. */ public DetailAST getPreviousSibling() { return mPreviousSibling; } /** * Returns the first child token that makes a specified type. * @param aType the token type to match * @return the matching token, or null if no match */ public DetailAST findFirstToken(int aType) { DetailAST retVal = null; for (DetailAST i = getFirstChild(); i != null; i = i.getNextSibling()) { if (i.getType() == aType) { retVal = i; break; } } return retVal; } @Override public String toString() { return super.toString() + "[" + getLineNo() + "x" + getColumnNo() + "]"; } @Override public DetailAST getNextSibling() { return (DetailAST) super.getNextSibling(); } @Override public DetailAST getFirstChild() { return (DetailAST) super.getFirstChild(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/FastStack.java100644 0 0 10251 12026051071 25370 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.google.common.collect.Lists; import java.util.Iterator; import java.util.List; /** * Simple implementation of a LIFO Stack that can be used instead of * {@link java.util.Vector} which is synchronized. * @author oliverb * @param The type to hold. */ public class FastStack implements Iterable { /** Hold the entries in the stack. */ private final List mEntries = Lists.newArrayList(); /** * Pushes the supplied element onto the stack. * @param aElement the element to push onto the stack. */ public void push(E aElement) { mEntries.add(aElement); } /** * Returns whether the stack is empty. * @return whether the stack is empty. */ public boolean isEmpty() { return mEntries.isEmpty(); } /** * Returns the number of entries in the stack. * @return the number of entries in the stack. */ public int size() { return mEntries.size(); } /** * Returns the entry at the top of the stack without removing it. * @return the top entry * @throws IllegalStateException if the stack is empty. */ public E peek() { if (mEntries.isEmpty()) { throw new IllegalStateException("FastStack is empty"); } return mEntries.get(mEntries.size() - 1); } /** * Returns the entry at the top of the stack by removing it. * @return the top entry * @throws IllegalStateException if the stack is empty. */ public E pop() { if (mEntries.isEmpty()) { throw new IllegalStateException("FastStack is empty"); } return mEntries.remove(mEntries.size() - 1); } /** * Return the element at the specified index. It does not remove the * element from the stack. * @param aIndex the index to return * @return the element at the index * @throws IllegalArgumentException if index out of range */ public E peek(int aIndex) { if ((aIndex < 0) || (aIndex >= mEntries.size())) { throw new IllegalArgumentException("index out of range."); } return mEntries.get(aIndex); } /** * Returns if the stack contains the specified element. * @param aElement the element to find * @return whether the stack contains the entry */ public boolean contains(E aElement) { return mEntries.contains(aElement); } /** * Clears the stack. */ public void clear() { mEntries.clear(); } /** * Returns an iterator that goes from the oldest element to the newest. * @return an iterator */ public Iterator iterator() { return mEntries.iterator(); } /** * Factory method to create a new instance. * @param the type of elements to hold in the stack. * @return a new instance of {@link FastStack} */ public static FastStack newInstance() { return new FastStack(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/FileContents.java100644 0 0 26363 12026051071 26115 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.puppycrawl.tools.checkstyle.grammars.CommentListener; import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * Represents the contents of a file. * * @author Oliver Burn * @version 1.0 */ public final class FileContents implements CommentListener { /** * the pattern to match a single line comment containing only the comment * itself -- no code. */ private static final String MATCH_SINGLELINE_COMMENT_PAT = "^\\s*//.*$"; /** compiled regexp to match a single-line comment line */ private static final Pattern MATCH_SINGLELINE_COMMENT = Pattern .compile(MATCH_SINGLELINE_COMMENT_PAT); /** the file name */ private final String mFilename; /** the text */ private final FileText mText; /** map of the Javadoc comments indexed on the last line of the comment. * The hack is it assumes that there is only one Javadoc comment per line. */ private final Map mJavadocComments = Maps.newHashMap(); /** map of the C++ comments indexed on the first line of the comment. */ private final Map mCPlusPlusComments = Maps.newHashMap(); /** * map of the C comments indexed on the first line of the comment to a list * of comments on that line */ private final Map> mCComments = Maps.newHashMap(); /** * Creates a new FileContents instance. * * @param aFilename name of the file * @param aLines the contents of the file * @deprecated Use {@link #FileContents(FileText)} instead * in order to preserve the original line breaks where possible. */ @Deprecated public FileContents(String aFilename, String[] aLines) { mFilename = aFilename; mText = FileText.fromLines(new File(aFilename), Arrays.asList(aLines)); } /** * Creates a new FileContents instance. * * @param aText the contents of the file */ public FileContents(FileText aText) { mFilename = aText.getFile().toString(); mText = aText; } /** {@inheritDoc} */ public void reportSingleLineComment(String aType, int aStartLineNo, int aStartColNo) { reportCppComment(aStartLineNo, aStartColNo); } /** {@inheritDoc} */ public void reportBlockComment(String aType, int aStartLineNo, int aStartColNo, int aEndLineNo, int aEndColNo) { reportCComment(aStartLineNo, aStartColNo, aEndLineNo, aEndColNo); } /** * Report the location of a C++ style comment. * @param aStartLineNo the starting line number * @param aStartColNo the starting column number **/ public void reportCppComment(int aStartLineNo, int aStartColNo) { final String line = line(aStartLineNo - 1); final String[] txt = new String[] {line.substring(aStartColNo)}; final Comment comment = new Comment(txt, aStartColNo, aStartLineNo, line.length() - 1); mCPlusPlusComments.put(aStartLineNo, comment); } /** * Returns a map of all the C++ style comments. The key is a line number, * the value is the comment {@link TextBlock} at the line. * @return the Map of comments */ public ImmutableMap getCppComments() { return ImmutableMap.copyOf(mCPlusPlusComments); } /** * Report the location of a C-style comment. * @param aStartLineNo the starting line number * @param aStartColNo the starting column number * @param aEndLineNo the ending line number * @param aEndColNo the ending column number **/ public void reportCComment(int aStartLineNo, int aStartColNo, int aEndLineNo, int aEndColNo) { final String[] cc = extractCComment(aStartLineNo, aStartColNo, aEndLineNo, aEndColNo); final Comment comment = new Comment(cc, aStartColNo, aEndLineNo, aEndColNo); // save the comment if (mCComments.containsKey(aStartLineNo)) { final List entries = mCComments.get(aStartLineNo); entries.add(comment); } else { final List entries = Lists.newArrayList(); entries.add(comment); mCComments.put(aStartLineNo, entries); } // Remember if possible Javadoc comment if (line(aStartLineNo - 1).indexOf("/**", aStartColNo) != -1) { mJavadocComments.put(aEndLineNo - 1, comment); } } /** * Returns a map of all C style comments. The key is the line number, the * value is a {@link List} of C style comment {@link TextBlock}s * that start at that line. * @return the map of comments */ public ImmutableMap> getCComments() { return ImmutableMap.copyOf(mCComments); } /** * Returns the specified C comment as a String array. * @return C comment as a array * @param aStartLineNo the starting line number * @param aStartColNo the starting column number * @param aEndLineNo the ending line number * @param aEndColNo the ending column number **/ private String[] extractCComment(int aStartLineNo, int aStartColNo, int aEndLineNo, int aEndColNo) { String[] retVal; if (aStartLineNo == aEndLineNo) { retVal = new String[1]; retVal[0] = line(aStartLineNo - 1).substring(aStartColNo, aEndColNo + 1); } else { retVal = new String[aEndLineNo - aStartLineNo + 1]; retVal[0] = line(aStartLineNo - 1).substring(aStartColNo); for (int i = aStartLineNo; i < aEndLineNo; i++) { retVal[i - aStartLineNo + 1] = line(i); } retVal[retVal.length - 1] = line(aEndLineNo - 1).substring(0, aEndColNo + 1); } return retVal; } /** * Returns the Javadoc comment before the specified line. * A return value of null means there is no such comment. * @return the Javadoc comment, or null if none * @param aLineNo the line number to check before **/ public TextBlock getJavadocBefore(int aLineNo) { // Lines start at 1 to the callers perspective, so need to take off 2 int lineNo = aLineNo - 2; // skip blank lines while ((lineNo > 0) && (lineIsBlank(lineNo) || lineIsComment(lineNo))) { lineNo--; } return mJavadocComments.get(lineNo); } /** * Get a single line. * For internal use only, as getText().get(lineNo) is just as * suitable for external use and avoids method duplication. * @param aLineNo the number of the line to get * @return the corresponding line, without terminator * @throws IndexOutOfBoundsException if lineNo is invalid */ private String line(int aLineNo) { return mText.get(aLineNo); } /** * Get the full text of the file. * @return an object containing the full text of the file */ public FileText getText() { return mText; } /** @return the lines in the file */ public String[] getLines() { return mText.toLinesArray(); } /** @return the name of the file */ public String getFilename() { return mFilename; } /** * Checks if the specified line is blank. * @param aLineNo the line number to check * @return if the specified line consists only of tabs and spaces. **/ public boolean lineIsBlank(int aLineNo) { // possible improvement: avoid garbage creation in trim() return "".equals(line(aLineNo).trim()); } /** * Checks if the specified line is a single-line comment without code. * @param aLineNo the line number to check * @return if the specified line consists of only a single line comment * without code. **/ public boolean lineIsComment(int aLineNo) { return MATCH_SINGLELINE_COMMENT.matcher(line(aLineNo)).matches(); } /** * Checks if the specified position intersects with a comment. * @param aStartLineNo the starting line number * @param aStartColNo the starting column number * @param aEndLineNo the ending line number * @param aEndColNo the ending column number * @return true if the positions intersects with a comment. **/ public boolean hasIntersectionWithComment(int aStartLineNo, int aStartColNo, int aEndLineNo, int aEndColNo) { // Check C comments (all comments should be checked) final Collection> values = mCComments.values(); for (final List row : values) { for (final TextBlock comment : row) { if (comment.intersects(aStartLineNo, aStartColNo, aEndLineNo, aEndColNo)) { return true; } } } // Check CPP comments (line searching is possible) for (int lineNumber = aStartLineNo; lineNumber <= aEndLineNo; lineNumber++) { final TextBlock comment = mCPlusPlusComments.get(lineNumber); if ((comment != null) && comment.intersects(aStartLineNo, aStartColNo, aEndLineNo, aEndColNo)) { return true; } } return false; } /** * Checks if the current file is a package-info.java file. * @return true if the package file. */ public boolean inPackageInfo() { return this.getFilename().endsWith("package-info.java"); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/FileSetCheck.java100644 0 0 6027 12026051070 25763 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.io.File; import java.util.List; import java.util.TreeSet; /** * Interface for Checking a set of files for some criteria. * * @author lkuehne * @author oliver */ public interface FileSetCheck extends Configurable, Contextualizable { /** * Sets the MessageDispatcher that is used to dispatch error * messages to AuditListeners during processing. * @param aDispatcher the dispatcher */ void setMessageDispatcher(MessageDispatcher aDispatcher); /** * Initialise the instance. This is the time to verify that everything * required to perform it job. */ void init(); /** Cleans up the object. **/ void destroy(); /** * Called when about to be called to process a set of files. * @param aCharset the character set used to read the files. */ void beginProcessing(String aCharset); /** * Request to process a file. The implementation should use the supplied * contents and not read the contents again. This reduces the amount of * file I/O. *

* The file set to process might contain files that are not * interesting to the FileSetCheck. Such files should be ignored, * no error message should be fired for them. For example a FileSetCheck * that checks java files should ignore HTML or properties files. *

* The method should return the set of messages to be logged. * * @param aFile the file to be processed * @param aLines an immutable list of the contents of the file. * @return the list of messages to be logged. */ TreeSet process(File aFile, List aLines); /** * Called when all the files have been processed. This is the time to * perform any checks that need to be done across a set of files. In this * method, the implementation is responsible for the logging of messages. */ void finishProcessing(); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/FileText.java100644 0 0 27422 12026051070 25240 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.nio.charset.UnsupportedCharsetException; import java.util.AbstractList; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents the text contents of a file of arbitrary plain text type. *

* This class will be passed to instances of class FileSetCheck by * Checker. It implements a string list to ensure backwards * compatibility, but can be extended in the future to allow more * flexible, more powerful or more efficient handling of certain * situations. * * @author Martin von Gagern */ public final class FileText extends AbstractList { /** * The number of characters to read in one go. */ private static final int READ_BUFFER_SIZE = 1024; /** * Regular expression pattern matching all line terminators. */ private static final Pattern LINE_TERMINATOR = Utils.getPattern("\\n|\\r\\n?"); // For now, we always keep both full text and lines array. // In the long run, however, the one passed at initialization might be // enough, while the other could be lazily created when requested. // This would save memory but cost CPU cycles. /** * The name of the file. * null if no file name is available for whatever reason. */ private final File mFile; /** * The charset used to read the file. * null if the file was reconstructed from a list of lines. */ private final Charset mCharset; /** * The full text contents of the file. */ private final CharSequence mFullText; /** * The lines of the file, without terminators. */ private final String[] mLines; /** * The first position of each line within the full text. */ private int[] mLineBreaks; /** * Creates a new file text representation. * * The file will be read using the specified encoding, replacing * malformed input and unmappable characters with the default * replacement character. * * @param aFile the name of the file * @param aCharsetName the encoding to use when reading the file * @throws NullPointerException if the text is null * @throws IOException if the file could not be read */ public FileText(File aFile, String aCharsetName) throws IOException { mFile = aFile; // We use our own decoder, to be sure we have complete control // about replacements. final CharsetDecoder decoder; try { mCharset = Charset.forName(aCharsetName); decoder = mCharset.newDecoder(); decoder.onMalformedInput(CodingErrorAction.REPLACE); decoder.onUnmappableCharacter(CodingErrorAction.REPLACE); } catch (final UnsupportedCharsetException ex) { final String message = "Unsuppored charset: " + aCharsetName; final UnsupportedEncodingException ex2; ex2 = new UnsupportedEncodingException(message); ex2.initCause(ex); throw ex2; } final char[] chars = new char[READ_BUFFER_SIZE]; final StringBuilder buf = new StringBuilder(); final FileInputStream stream = new FileInputStream(aFile); final Reader reader = new InputStreamReader(stream, decoder); try { while (true) { final int len = reader.read(chars); if (len < 0) { break; } buf.append(chars, 0, len); } } finally { Utils.closeQuietly(reader); } // buf.trimToSize(); // could be used instead of toString(). mFullText = buf.toString(); final String[] lines = LINE_TERMINATOR.split(mFullText, -1); if (lines.length > 0 && lines[lines.length - 1].length() == 0) { // drop empty line after last newline mLines = new String[lines.length - 1]; System.arraycopy(lines, 0, mLines, 0, lines.length - 1); } else { // no newline at end, so we keep the last line as is mLines = lines; } } /** * Compatibility constructor. * * This constructor reconstructs the text of the file by joining * lines with linefeed characters. This process does not restore * the original line terminators and should therefore be avoided. * * @param aFile the name of the file * @param aLines the lines of the text, without terminators * @throws NullPointerException if the lines array is null */ private FileText(File aFile, List aLines) { final StringBuilder buf = new StringBuilder(); for (final String line : aLines) { buf.append(line).append('\n'); } buf.trimToSize(); mFile = aFile; mCharset = null; mFullText = buf; mLines = aLines.toArray(new String[aLines.size()]); } /** * Compatibility conversion. * * This method can be used to convert the arguments passed to * {@link FileSetCheck#process(File,List)} to a FileText * object. If the list of lines already is a FileText, it is * returned as is. Otherwise, a new FileText is constructed by * joining the lines using line feed characters. * * @param aFile the name of the file * @param aLines the lines of the text, without terminators * @return an object representing the denoted text file */ public static FileText fromLines(File aFile, List aLines) { return (aLines instanceof FileText) ? (FileText) aLines : new FileText(aFile, aLines); } /** * Get the name of the file. * @return an object containing the name of the file */ public File getFile() { return mFile; } /** * Get the character set which was used to read the file. * Will be null for a file reconstructed from its lines. * @return the charset used when the file was read */ public Charset getCharset() { return mCharset; } /** * Get the binary contents of the file. * The returned object must not be modified. * @return a buffer containing the bytes making up the file * @throws IOException if the bytes could not be read from the file */ public ByteBuffer getBytes() throws IOException { // We might decide to cache file bytes in the future. if (mFile == null) { return null; } if (mFile.length() > Integer.MAX_VALUE) { throw new IOException("File too large."); } byte[] bytes = new byte[(int) mFile.length() + 1]; final FileInputStream stream = new FileInputStream(mFile); try { int fill = 0; while (true) { if (fill >= bytes.length) { // shouldn't happen, but it might nevertheless final byte[] newBytes = new byte[bytes.length * 2 + 1]; System.arraycopy(bytes, 0, newBytes, 0, fill); bytes = newBytes; } final int len = stream.read(bytes, fill, bytes.length - fill); if (len == -1) { break; } fill += len; } return ByteBuffer.wrap(bytes, 0, fill).asReadOnlyBuffer(); } finally { Utils.closeQuietly(stream); } } /** * Retrieve the full text of the file. * @return the full text of the file */ public CharSequence getFullText() { return mFullText; } /** * Returns an array of all lines. * {@code text.toLinesArray()} is equivalent to * {@code text.toArray(new String[text.size()])}. * @return an array of all lines of the text */ public String[] toLinesArray() { return mLines.clone(); } /** * Find positions of line breaks in the full text. * @return an array giving the first positions of each line. */ private int[] lineBreaks() { if (mLineBreaks == null) { final int[] lineBreaks = new int[size() + 1]; lineBreaks[0] = 0; int lineNo = 1; final Matcher matcher = LINE_TERMINATOR.matcher(mFullText); while (matcher.find()) { lineBreaks[lineNo++] = matcher.end(); } if (lineNo < lineBreaks.length) { lineBreaks[lineNo++] = mFullText.length(); } if (lineNo != lineBreaks.length) { throw new ConcurrentModificationException("Text changed."); } mLineBreaks = lineBreaks; } return mLineBreaks; } /** * Determine line and column numbers in full text. * @param aPos the character position in the full text * @return the line and column numbers of this character */ public LineColumn lineColumn(int aPos) { final int[] lineBreaks = lineBreaks(); int lineNo = Arrays.binarySearch(lineBreaks, aPos); if (lineNo < 0) { // we have: lineNo = -(insertion point) - 1 // we want: lineNo = (insertion point) - 1 lineNo = -lineNo - 2; } final int startOfLine = lineBreaks[lineNo]; final int columnNo = aPos - startOfLine; // now we have lineNo and columnNo, both starting at zero. return new LineColumn(lineNo + 1, columnNo); } /** * Retrieves a line of the text by its number. * The returned line will not contain a trailing terminator. * @param aLineNo the number of the line to get, starting at zero * @return the line with the given number */ @Override public String get(final int aLineNo) { return mLines[aLineNo]; } /** * Counts the lines of the text. * @return the number of lines in the text */ @Override public int size() { return mLines.length; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/Filter.java100644 0 0 2604 12026051070 24714 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** * An interface for filtering AuditEvents. * @author Rick Giles */ public interface Filter { /** * Determines whether or not a filtered AuditEvent is accepted. * @param aEvent the AudtiEvent to filter. * @return true if the aEvent is accepted. */ boolean accept(AuditEvent aEvent); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/FilterSet.java100644 0 0 5460 12026051070 25373 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.google.common.collect.Sets; import java.util.Set; /** * A filter set applies filters to AuditEvents. * If a filter in the set rejects an AuditEvent, then the * AuditEvent is rejected. Otherwise, the AuditEvent is accepted. * @author Rick Giles */ public class FilterSet implements Filter { /** filter set */ private final Set mFilters = Sets.newHashSet(); /** * Adds a Filter to the set. * @param aFilter the Filter to add. */ public void addFilter(Filter aFilter) { mFilters.add(aFilter); } /** * Removes filter. * @param aFilter filter to remove. */ public void removeFilter(Filter aFilter) { mFilters.remove(aFilter); } /** * Returns the Filters of the filter set. * @return the Filters of the filter set. */ protected Set getFilters() { return mFilters; } @Override public String toString() { return mFilters.toString(); } @Override public int hashCode() { return mFilters.hashCode(); } @Override public boolean equals(Object aObject) { if (aObject instanceof FilterSet) { final FilterSet other = (FilterSet) aObject; return this.mFilters.equals(other.mFilters); } return false; } /** {@inheritDoc} */ public boolean accept(AuditEvent aEvent) { for (Filter filter : mFilters) { if (!filter.accept(aEvent)) { return false; } } return true; } /** Clears the FilterSet. */ public void clear() { mFilters.clear(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/FullIdent.java100644 0 0 10634 12026051070 25377 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** * Represents a full identifier, including dots, with associated * position information. * *

* Identifiers such as java.util.HashMap are spread across * multiple AST nodes in the syntax tree (three IDENT nodes, two DOT nodes). * A FullIdent represents the whole String (excluding any intermediate * whitespace), which is often easier to work with in Checks. *

* * @author Oliver Burn * @see TokenTypes#DOT * @see TokenTypes#IDENT **/ public final class FullIdent { /** the string **/ private final StringBuffer mBuffer = new StringBuffer(); /** the line number **/ private int mLineNo; /** the column number **/ private int mColNo; /** hide default constructor */ private FullIdent() { } /** @return the text **/ public String getText() { return mBuffer.toString(); } /** @return the line number **/ public int getLineNo() { return mLineNo; } /** @return the column number **/ public int getColumnNo() { return mColNo; } /** * Append the specified text. * @param aText the text to append */ private void append(String aText) { mBuffer.append(aText); } /** * Append the specified token and also recalibrate the first line and * column. * @param aAST the token to append */ private void append(DetailAST aAST) { mBuffer.append(aAST.getText()); if (mLineNo == 0) { mLineNo = aAST.getLineNo(); } else if (aAST.getLineNo() > 0) { mLineNo = Math.min(mLineNo, aAST.getLineNo()); } // TODO: make a function if (mColNo == 0) { mColNo = aAST.getColumnNo(); } else if (aAST.getColumnNo() > 0) { mColNo = Math.min(mColNo, aAST.getColumnNo()); } } /** * Creates a new FullIdent starting from the specified node. * @param aAST the node to start from * @return a FullIdent value */ public static FullIdent createFullIdent(DetailAST aAST) { final FullIdent fi = new FullIdent(); extractFullIdent(fi, aAST); return fi; } /** * Creates a new FullIdent starting from the child of the specified node. * @param aAST the parent node from where to start from * @return a FullIdent value */ public static FullIdent createFullIdentBelow(DetailAST aAST) { return createFullIdent(aAST.getFirstChild()); } /** * Recursively extract a FullIdent. * * @param aFull the FullIdent to add to * @param aAST the node to recurse from */ private static void extractFullIdent(FullIdent aFull, DetailAST aAST) { if (aAST == null) { return; } if (aAST.getType() == TokenTypes.DOT) { extractFullIdent(aFull, aAST.getFirstChild()); aFull.append("."); extractFullIdent( aFull, aAST.getFirstChild().getNextSibling()); } else { aFull.append(aAST); } } @Override public String toString() { return getText() + "[" + getLineNo() + "x" + getColumnNo() + "]"; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/JavadocTagInfo.java100644 0 0 50213 12026051067 26333 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.google.common.collect.ImmutableMap; import java.util.Map; /** * This enum defines the various Javadoc tags and there properties. * *

* This class was modeled after documentation located at * * javadoc * * and * * * how to write. *

* *

* Some of this documentation was a little incomplete (ex: valid placement of * code, value, and literal tags). *

* *

* Whenever an inconsistency was found the author's judgment was used. *

* *

* For now, the number of required/optional tag arguments are not included * because some Javadoc tags have very complex rules for determining this * (ex: {@code {@value}} tag). *

* *

* Also, the {@link #isValidOn(DetailAST) isValidOn} method does not consider * classes defined in a local code block (method, init block, etc.). * * * @author Travis Schneeberger */ public enum JavadocTagInfo { /** * {@code @author}. */ AUTHOR("@author", "author", Type.BLOCK, true, true) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.PACKAGE_DEF || type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.ANNOTATION_DEF; } }, /** * {@code {@code}}. */ CODE("{@code}", "code", Type.INLINE, true, true) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.PACKAGE_DEF || type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.ANNOTATION_DEF || type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF || (type == TokenTypes.VARIABLE_DEF && !ScopeUtils.isLocalVariableDef(aAst)); } }, /** * {@code {@docRoot}}. */ DOC_ROOT("{@docRoot}", "docRoot", Type.INLINE, true, true) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.PACKAGE_DEF || type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.ANNOTATION_DEF || type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF || (type == TokenTypes.VARIABLE_DEF && !ScopeUtils.isLocalVariableDef(aAst)); } }, /** * {@code @deprecated}. */ DEPRECATED("@deprecated", "deprecated", Type.BLOCK, false, false) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.ANNOTATION_DEF || type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF || type == TokenTypes.ENUM_CONSTANT_DEF || type == TokenTypes.ANNOTATION_FIELD_DEF || (type == TokenTypes.VARIABLE_DEF && !ScopeUtils.isLocalVariableDef(aAst)); } }, /** * {@code @exception}. */ EXCEPTION("@exception", "exception", Type.BLOCK, false, false) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF; } }, /** * {@code {@inheritDoc}}. */ INHERIT_DOC("{@inheritDoc}", "inheritDoc", Type.INLINE, false, false) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.METHOD_DEF && !aAst.branchContains(TokenTypes.LITERAL_STATIC) && ScopeUtils.getScopeFromMods(aAst .findFirstToken(TokenTypes.MODIFIERS)) != Scope.PRIVATE; } }, /** * {@code {@link}}. */ LINK("{@link}", "link", Type.INLINE, true, true) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.PACKAGE_DEF || type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.ANNOTATION_DEF || type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF || (type == TokenTypes.VARIABLE_DEF && !ScopeUtils.isLocalVariableDef(aAst)); } }, /** * {@code {@linkplain}}. */ LINKPLAIN("{@linkplain}", "linkplain", Type.INLINE, true, true) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.PACKAGE_DEF || type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.ANNOTATION_DEF || type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF || (type == TokenTypes.VARIABLE_DEF && !ScopeUtils.isLocalVariableDef(aAst)); } }, /** * {@code {@literal}}. */ LITERAL("{@literal}", "literal", Type.INLINE, true, true) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.PACKAGE_DEF || type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.ANNOTATION_DEF || type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF || (type == TokenTypes.VARIABLE_DEF && !ScopeUtils.isLocalVariableDef(aAst)); } }, /** * {@code @param}. */ PARAM("@param", "param", Type.BLOCK, false, false) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF; } }, /** * {@code @return}. */ RETURN("@return", "return", Type.BLOCK, false, false) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); final DetailAST returnType = aAst.findFirstToken(TokenTypes.TYPE); return type == TokenTypes.METHOD_DEF && returnType.getFirstChild().getType() != TokenTypes.LITERAL_VOID; } }, /** * {@code @see}. */ SEE("@see", "see", Type.BLOCK, true, true) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.PACKAGE_DEF || type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.ANNOTATION_DEF || type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF || (type == TokenTypes.VARIABLE_DEF && !ScopeUtils.isLocalVariableDef(aAst)); } }, /** * {@code @serial}. */ SERIAL("@serial", "serial", Type.BLOCK, true, false) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.VARIABLE_DEF && !ScopeUtils.isLocalVariableDef(aAst); } }, /** * {@code @serialData}. */ SERIAL_DATA("@serialData", "serialData", Type.BLOCK, false, false) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); final DetailAST methodNameAst = aAst .findFirstToken(TokenTypes.IDENT); final String methodName = methodNameAst.getText(); return type == TokenTypes.METHOD_DEF && ("writeObject".equals(methodName) || "readObject".equals(methodName) || "writeExternal".equals(methodName) || "readExternal".equals(methodName) || "writeReplace".equals(methodName) || "readResolve" .equals(methodName)); } }, /** * {@code @serialField}. */ SERIAL_FIELD("@serialField", "serialField", Type.BLOCK, false, false) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); final DetailAST varType = aAst.findFirstToken(TokenTypes.TYPE); return type == TokenTypes.VARIABLE_DEF && varType.getType() == TokenTypes.ARRAY_DECLARATOR && "ObjectStreamField" .equals(varType.getFirstChild().getText()); } }, /** * {@code @since}. */ SINCE("@since", "since", Type.BLOCK, true, true) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.PACKAGE_DEF || type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.ANNOTATION_DEF || type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF || (type == TokenTypes.VARIABLE_DEF && !ScopeUtils.isLocalVariableDef(aAst)); } }, /** * {@code @throws}. */ THROWS("@throws", "throws", Type.BLOCK, false, false) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF; } }, /** * {@code {@value}}. */ VALUE("{@value}", "value", Type.INLINE, true, true) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.PACKAGE_DEF || type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.ANNOTATION_DEF || type == TokenTypes.METHOD_DEF || type == TokenTypes.CTOR_DEF || (type == TokenTypes.VARIABLE_DEF && !ScopeUtils.isLocalVariableDef(aAst)); } }, /** * {@code @version}. */ VERSION("@version", "version", Type.BLOCK, true, true) { /** {@inheritDoc} */ @Override public boolean isValidOn(final DetailAST aAst) { final int type = aAst.getType(); return type == TokenTypes.PACKAGE_DEF || type == TokenTypes.CLASS_DEF || type == TokenTypes.INTERFACE_DEF || type == TokenTypes.ENUM_DEF || type == TokenTypes.ANNOTATION_DEF; } }; /** holds tag text to tag enum mappings **/ private static final Map TEXT_TO_TAG; /** holds tag name to tag enum mappings **/ private static final Map NAME_TO_TAG; static { final ImmutableMap.Builder textToTagBuilder = new ImmutableMap.Builder(); final ImmutableMap.Builder nameToTagBuilder = new ImmutableMap.Builder(); for (final JavadocTagInfo tag : JavadocTagInfo.values()) { textToTagBuilder.put(tag.getText(), tag); nameToTagBuilder.put(tag.getName(), tag); } TEXT_TO_TAG = textToTagBuilder.build(); NAME_TO_TAG = nameToTagBuilder.build(); } /** the tag text **/ private final String mText; /** the tag name **/ private final String mName; /** the tag type **/ private final Type mType; /** if tag is valid in package.html **/ private final boolean mValidInPackageHtml; /** if tag is valid in overview.html **/ private final boolean mValidInOverviewHtml; /** * Sets the various properties of a Javadoc tag. * * @param aText the tag text * @param aName the tag name * @param aType the type of tag * @param aValidInPackageHtml whether the tag is valid * in package.html file * @param aValidInOverviewHtml whether the tag is valid * in overview.html file */ private JavadocTagInfo(final String aText, final String aName, final Type aType, final boolean aValidInPackageHtml, final boolean aValidInOverviewHtml) { this.mText = aText; this.mName = aName; this.mType = aType; this.mValidInPackageHtml = aValidInPackageHtml; this.mValidInOverviewHtml = aValidInOverviewHtml; } /** * Checks if a particular Javadoc tag is valid within a Javadoc block of a * given AST. * *

* For example: Given a call to * JavadocTag.RETURN{@link #isValidOn(DetailAST)}. *

* *

* If passing in a DetailAST representing a non-void METHOD_DEF * true would be returned. If passing in a DetailAST * representing a CLASS_DEF false would be returned because * CLASS_DEF's cannot return a value. *

* * @param aAST the AST representing a type that can be Javadoc'd * @return true if tag is valid. */ public abstract boolean isValidOn(DetailAST aAST); /** * Checks if tag is valid in a package.html Javadoc file. * * @return true if tag is valid. */ public boolean isValidInPackageHtml() { return this.mValidInPackageHtml; } /** * Checks if tag is valid in a overview.html Javadoc file. * * @return true if tag is valid. */ public boolean isValidInOverviewHtml() { return this.mValidInOverviewHtml; } /** * Gets the tag text. * @return the tag text */ public String getText() { return this.mText; } /** * Gets the tag name. * @return the tag name */ public String getName() { return this.mName; } /** * Gets the Tag type defined by {@link JavadocTagInfo.Type Type}. * @return the Tag type */ public Type getType() { return this.mType; } /** * returns a JavadocTag from the tag text. * @param aText String representing the tag text * @return Returns a JavadocTag type from a String representing the tag * @throws NullPointerException if the text is null * @throws IllegalArgumentException if the text is not a valid tag */ public static JavadocTagInfo fromText(final String aText) { if (aText == null) { throw new NullPointerException("the text is null"); } final JavadocTagInfo tag = TEXT_TO_TAG.get(aText); if (tag == null) { throw new IllegalArgumentException("the text [" + aText + "] is not a valid Javadoc tag text"); } return tag; } /** * returns a JavadocTag from the tag name. * @param aName String name of the tag * @return Returns a JavadocTag type from a String representing the tag * @throws NullPointerException if the text is null * @throws IllegalArgumentException if the text is not a valid tag. The name * can be checked using {@link JavadocTagInfo#isValidName(String)} */ public static JavadocTagInfo fromName(final String aName) { if (aName == null) { throw new NullPointerException("the name is null"); } final JavadocTagInfo tag = NAME_TO_TAG.get(aName); if (tag == null) { throw new IllegalArgumentException("the name [" + aName + "] is not a valid Javadoc tag name"); } return tag; } /** * Returns whether the provided name is for a valid tag. * @param aName the tag name to check. * @return whether the provided name is for a valid tag. */ public static boolean isValidName(final String aName) { return NAME_TO_TAG.containsKey(aName); } /** * {@inheritDoc} */ @Override public String toString() { return "text [" + this.mText + "] name [" + this.mName + "] type [" + this.mType + "] validInPackageHtml [" + this.mValidInPackageHtml + "] validInOverviewHtml [" + this.mValidInOverviewHtml + "]"; } /** * The Javadoc Type. * * For example a {@code @param} tag is a block tag while a * {@code {@link}} tag is a inline tag. * * @author Travis Schneeberger */ public enum Type { /** block type. **/ BLOCK, /** inline type. **/ INLINE; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/LineColumn.java100644 0 0 4130 12026051067 25536 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** * Immutable line and column numbers. * * @author Martin von Gagern */ public class LineColumn implements Comparable { /** The one-based line number */ private final int mLine; /** The zero-based column number */ private final int mCol; /** * Constructs a new pair of line and column numbers. * @param aLine the one-based line number * @param aCol the zero-based column number */ public LineColumn(int aLine, int aCol) { mLine = aLine; mCol = aCol; } /** @return the one-based line number */ public int getLine() { return mLine; } /** @return the zero-based column number */ public int getColumn() { return mCol; } /** {@inheritDoc} */ public int compareTo(LineColumn aLineColumn) { return (this.getLine() != aLineColumn.getLine()) ? this.getLine() - aLineColumn.getLine() : this.getColumn() - aLineColumn.getColumn(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/LocalizedMessage.java100644 0 0 31234 12026051067 26731 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.io.Serializable; import java.text.MessageFormat; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * Represents a message that can be localised. The translations come from * message.properties files. The underlying implementation uses * java.text.MessageFormat. * * @author Oliver Burn * @author lkuehne * @version 1.0 */ public final class LocalizedMessage implements Comparable, Serializable { /** Required for serialization. */ private static final long serialVersionUID = 5675176836184862150L; /** hash function multiplicand */ private static final int HASH_MULT = 29; /** the locale to localise messages to **/ private static Locale sLocale = Locale.getDefault(); /** * A cache that maps bundle names to RessourceBundles. * Avoids repetitive calls to ResourceBundle.getBundle(). * TODO: The cache should be cleared at some point. */ private static final Map BUNDLE_CACHE = Collections.synchronizedMap(new HashMap()); /** the line number **/ private final int mLineNo; /** the column number **/ private final int mColNo; /** the severity level **/ private final SeverityLevel mSeverityLevel; /** the id of the module generating the message. */ private final String mModuleId; /** the default severity level if one is not specified */ private static final SeverityLevel DEFAULT_SEVERITY = SeverityLevel.ERROR; /** key for the message format **/ private final String mKey; /** arguments for MessageFormat **/ private final Object[] mArgs; /** name of the resource bundle to get messages from **/ private final String mBundle; /** class of the source for this LocalizedMessage */ private final Class mSourceClass; /** a custom message overriding the default message from the bundle. */ private final String mCustomMessage; @Override public boolean equals(Object aObject) { if (this == aObject) { return true; } if (!(aObject instanceof LocalizedMessage)) { return false; } final LocalizedMessage localizedMessage = (LocalizedMessage) aObject; if (mColNo != localizedMessage.mColNo) { return false; } if (mLineNo != localizedMessage.mLineNo) { return false; } if (!mKey.equals(localizedMessage.mKey)) { return false; } if (!Arrays.equals(mArgs, localizedMessage.mArgs)) { return false; } // ignoring mBundle for perf reasons. // we currently never load the same error from different bundles. return true; } @Override public int hashCode() { int result; result = mLineNo; result = HASH_MULT * result + mColNo; result = HASH_MULT * result + mKey.hashCode(); for (final Object element : mArgs) { result = HASH_MULT * result + element.hashCode(); } return result; } /** * Creates a new LocalizedMessage instance. * * @param aLineNo line number associated with the message * @param aColNo column number associated with the message * @param aBundle resource bundle name * @param aKey the key to locate the translation * @param aArgs arguments for the translation * @param aSeverityLevel severity level for the message * @param aModuleId the id of the module the message is associated with * @param aSourceClass the Class that is the source of the message * @param aCustomMessage optional custom message overriding the default */ public LocalizedMessage(int aLineNo, int aColNo, String aBundle, String aKey, Object[] aArgs, SeverityLevel aSeverityLevel, String aModuleId, Class aSourceClass, String aCustomMessage) { mLineNo = aLineNo; mColNo = aColNo; mKey = aKey; mArgs = (null == aArgs) ? null : aArgs.clone(); mBundle = aBundle; mSeverityLevel = aSeverityLevel; mModuleId = aModuleId; mSourceClass = aSourceClass; mCustomMessage = aCustomMessage; } /** * Creates a new LocalizedMessage instance. * * @param aLineNo line number associated with the message * @param aColNo column number associated with the message * @param aBundle resource bundle name * @param aKey the key to locate the translation * @param aArgs arguments for the translation * @param aModuleId the id of the module the message is associated with * @param aSourceClass the Class that is the source of the message * @param aCustomMessage optional custom message overriding the default */ public LocalizedMessage(int aLineNo, int aColNo, String aBundle, String aKey, Object[] aArgs, String aModuleId, Class aSourceClass, String aCustomMessage) { this(aLineNo, aColNo, aBundle, aKey, aArgs, DEFAULT_SEVERITY, aModuleId, aSourceClass, aCustomMessage); } /** * Creates a new LocalizedMessage instance. * * @param aLineNo line number associated with the message * @param aBundle resource bundle name * @param aKey the key to locate the translation * @param aArgs arguments for the translation * @param aSeverityLevel severity level for the message * @param aModuleId the id of the module the message is associated with * @param aSourceClass the source class for the message * @param aCustomMessage optional custom message overriding the default */ public LocalizedMessage(int aLineNo, String aBundle, String aKey, Object[] aArgs, SeverityLevel aSeverityLevel, String aModuleId, Class aSourceClass, String aCustomMessage) { this(aLineNo, 0, aBundle, aKey, aArgs, aSeverityLevel, aModuleId, aSourceClass, aCustomMessage); } /** * Creates a new LocalizedMessage instance. The column number * defaults to 0. * * @param aLineNo line number associated with the message * @param aBundle name of a resource bundle that contains error messages * @param aKey the key to locate the translation * @param aArgs arguments for the translation * @param aModuleId the id of the module the message is associated with * @param aSourceClass the name of the source for the message * @param aCustomMessage optional custom message overriding the default */ public LocalizedMessage( int aLineNo, String aBundle, String aKey, Object[] aArgs, String aModuleId, Class aSourceClass, String aCustomMessage) { this(aLineNo, 0, aBundle, aKey, aArgs, DEFAULT_SEVERITY, aModuleId, aSourceClass, aCustomMessage); } /** @return the translated message **/ public String getMessage() { final String customMessage = getCustomMessage(); if (customMessage != null) { return customMessage; } try { // Important to use the default class loader, and not the one in // the GlobalProperties object. This is because the class loader in // the GlobalProperties is specified by the user for resolving // custom classes. final ResourceBundle bundle = getBundle(mBundle); final String pattern = bundle.getString(mKey); return MessageFormat.format(pattern, mArgs); } catch (final MissingResourceException ex) { // If the Check author didn't provide i18n resource bundles // and logs error messages directly, this will return // the author's original message return MessageFormat.format(mKey, mArgs); } } /** * Returns the formatted custom message if one is configured. * @return the formatted custom message or null * if there is no custom message */ private String getCustomMessage() { if (mCustomMessage == null) { return null; } return MessageFormat.format(mCustomMessage, mArgs); } /** * Find a ResourceBundle for a given bundle name. Uses the classloader * of the class emitting this message, to be sure to get the correct * bundle. * @param aBundleName the bundle name * @return a ResourceBundle */ private ResourceBundle getBundle(String aBundleName) { synchronized (BUNDLE_CACHE) { ResourceBundle bundle = BUNDLE_CACHE .get(aBundleName); if (bundle == null) { bundle = ResourceBundle.getBundle(aBundleName, sLocale, mSourceClass.getClassLoader()); BUNDLE_CACHE.put(aBundleName, bundle); } return bundle; } } /** @return the line number **/ public int getLineNo() { return mLineNo; } /** @return the column number **/ public int getColumnNo() { return mColNo; } /** @return the severity level **/ public SeverityLevel getSeverityLevel() { return mSeverityLevel; } /** @return the module identifier. */ public String getModuleId() { return mModuleId; } /** * Returns the message key to locate the translation, can also be used * in IDE plugins to map error messages to corrective actions. * * @return the message key */ public String getKey() { return mKey; } /** @return the name of the source for this LocalizedMessage */ public String getSourceName() { return mSourceClass.getName(); } /** @param aLocale the locale to use for localization **/ public static void setLocale(Locale aLocale) { sLocale = aLocale; } //////////////////////////////////////////////////////////////////////////// // Interface Comparable methods //////////////////////////////////////////////////////////////////////////// /** {@inheritDoc} */ public int compareTo(LocalizedMessage aOther) { if (getLineNo() == aOther.getLineNo()) { if (getColumnNo() == aOther.getColumnNo()) { return getMessage().compareTo(aOther.getMessage()); } return (getColumnNo() < aOther.getColumnNo()) ? -1 : 1; } return (getLineNo() < aOther.getLineNo()) ? -1 : 1; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/LocalizedMessages.java100644 0 0 4117 12026051067 27074 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; // TODO: check that this class is in the right package // as soon as architecture has settled. At the time of writing // this class is not necessary as a part of the public api import com.google.common.collect.Sets; import java.util.TreeSet; /** * Collection of messages. * @author Oliver Burn * @version 1.0 */ public final class LocalizedMessages { /** contains the messages logged **/ private final TreeSet mMessages = Sets.newTreeSet(); /** @return the logged messages **/ public TreeSet getMessages() { return Sets.newTreeSet(mMessages); } /** Reset the object. **/ public void reset() { mMessages.clear(); } /** * Logs a message to be reported. * @param aMsg the message to log **/ public void add(LocalizedMessage aMsg) { mMessages.add(aMsg); } /** @return the number of messages */ public int size() { return mMessages.size(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/MessageDispatcher.java100644 0 0 3464 12026051067 27075 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import java.util.TreeSet; /** * Used by FileSetChecks to distribute AuditEvents to AuditListeners. * @author lkuehne */ public interface MessageDispatcher { /** * Notify all listeners about the beginning of a file audit. * @param aFileName the file to be audited */ void fireFileStarted(String aFileName); /** * Notify all listeners about the end of a file audit. * @param aFileName the audited file */ void fireFileFinished(String aFileName); /** * Notify all listeners about the errors in a file. * @param aFileName the audited file * @param aErrors the audit errors from the file */ void fireErrors(String aFileName, TreeSet aErrors); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/package-info.java100644 0 0 2321 12026051065 26013 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the core API to be used to implement checks. If you want to * implement your own check, you should be referring to this package. */ package com.puppycrawl.tools.checkstyle.api; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/Scope.java100644 0 0 4577 12026051067 24561 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** * Represents a Java visibility scope. * * @author Lars Kühne * @author Travis Schneeberger */ public enum Scope { /** nothing scope. */ NOTHING, /** protected scope. */ PUBLIC, /** protected scope. */ PROTECTED, /** package or default scope. */ PACKAGE, /** private scope. */ PRIVATE, /** anonymous inner scope. */ ANONINNER; @Override public String toString() { return getName(); } /** * @return the name of this severity level. */ public String getName() { return name().toLowerCase(); } /** * Checks if this scope is a subscope of another scope. * Example: PUBLIC is a subscope of PRIVATE. * * @param aScope a Scope value * @return if this is a subscope of aScope. */ public boolean isIn(Scope aScope) { return (compareTo(aScope) <= 0); } /** * Scope factory method. * * @param aScopeName scope name, such as "nothing", "public", etc. * @return the Scope associated with aScopeName */ public static Scope getInstance(String aScopeName) { return valueOf(Scope.class, aScopeName.trim().toUpperCase()); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/ScopeUtils.java100644 0 0 23645 12026051066 25616 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import antlr.collections.AST; /** * Contains utility methods for working on scope. * * @author Oliver Burn * @version 1.0 */ public final class ScopeUtils { ///CLOVER:OFF /** prevent instantiation */ private ScopeUtils() { } ///CLOVER:ON /** * Returns the Scope specified by the modifier set. * * @param aMods root node of a modifier set * @return a Scope value */ public static Scope getScopeFromMods(DetailAST aMods) { Scope retVal = Scope.PACKAGE; // default scope for (AST token = aMods.getFirstChild(); token != null; token = token.getNextSibling()) { if ("public".equals(token.getText())) { retVal = Scope.PUBLIC; break; } else if ("protected".equals(token.getText())) { retVal = Scope.PROTECTED; break; } else if ("private".equals(token.getText())) { retVal = Scope.PRIVATE; break; } } return retVal; } /** * Returns the scope of the surrounding "block". * @param aAST the node to return the scope for * @return the Scope of the surrounding block */ public static Scope getSurroundingScope(DetailAST aAST) { Scope retVal = null; for (DetailAST token = aAST.getParent(); token != null; token = token.getParent()) { final int type = token.getType(); if ((type == TokenTypes.CLASS_DEF) || (type == TokenTypes.INTERFACE_DEF) || (type == TokenTypes.ANNOTATION_DEF) || (type == TokenTypes.ENUM_DEF)) { final DetailAST mods = token.findFirstToken(TokenTypes.MODIFIERS); final Scope modScope = ScopeUtils.getScopeFromMods(mods); if ((retVal == null) || (retVal.isIn(modScope))) { retVal = modScope; } } else if (type == TokenTypes.LITERAL_NEW) { retVal = Scope.ANONINNER; break; //because Scope.ANONINNER is not in any other Scope } } return retVal; } /** * Returns whether a node is directly contained within an interface block. * * @param aAST the node to check if directly contained within an interface * block * @return a boolean value */ public static boolean inInterfaceBlock(DetailAST aAST) { boolean retVal = false; // Loop up looking for a containing interface block for (DetailAST token = aAST.getParent(); token != null; token = token.getParent()) { final int type = token.getType(); if ((type == TokenTypes.CLASS_DEF) || (type == TokenTypes.ENUM_DEF) || (type == TokenTypes.ANNOTATION_DEF)) { break; // in a class, enum or annotation } else if (type == TokenTypes.LITERAL_NEW) { break; // inner implementation } else if (type == TokenTypes.INTERFACE_DEF) { retVal = true; break; } } return retVal; } /** * Returns whether a node is directly contained within an annotation block. * * @param aAST the node to check if directly contained within an annotation * block * @return a boolean value */ public static boolean inAnnotationBlock(DetailAST aAST) { boolean retVal = false; // Loop up looking for a containing interface block for (DetailAST token = aAST.getParent(); token != null; token = token.getParent()) { final int type = token.getType(); if ((type == TokenTypes.CLASS_DEF) || (type == TokenTypes.ENUM_DEF) || (type == TokenTypes.INTERFACE_DEF)) { break; // in a class, enum or interface } else if (type == TokenTypes.LITERAL_NEW) { break; // inner implementation } else if (type == TokenTypes.ANNOTATION_DEF) { retVal = true; break; } } return retVal; } /** * Returns whether a node is directly contained within an interface or * annotation block. * * @param aAST the node to check if directly contained within an interface * or annotation block * @return a boolean value */ public static boolean inInterfaceOrAnnotationBlock(DetailAST aAST) { return inInterfaceBlock(aAST) || inAnnotationBlock(aAST); } /** * Returns whether a node is directly contained within an enum block. * * @param aAST the node to check if directly contained within an enum * block * @return a boolean value */ public static boolean inEnumBlock(DetailAST aAST) { boolean retVal = false; // Loop up looking for a containing interface block for (DetailAST token = aAST.getParent(); token != null; token = token.getParent()) { final int type = token.getType(); if ((type == TokenTypes.INTERFACE_DEF) || (type == TokenTypes.ANNOTATION_DEF) || (type == TokenTypes.CLASS_DEF)) { break; // in an interface, annotation or class } else if (type == TokenTypes.LITERAL_NEW) { break; // inner implementation, enums can't be inner classes } else if (type == TokenTypes.ENUM_DEF) { retVal = true; break; } } return retVal; } /** * Returns whether the scope of a node is restricted to a code block. * A code block is a method or constructor body, or a initialiser block. * * @param aAST the node to check * @return a boolean value */ public static boolean inCodeBlock(DetailAST aAST) { boolean retVal = false; // Loop up looking for a containing code block for (DetailAST token = aAST.getParent(); token != null; token = token.getParent()) { final int type = token.getType(); if ((type == TokenTypes.METHOD_DEF) || (type == TokenTypes.CTOR_DEF) || (type == TokenTypes.INSTANCE_INIT) || (type == TokenTypes.STATIC_INIT)) { retVal = true; break; } } return retVal; } /** * Returns whether a node is contained in the outer most type block. * * @param aAST the node to check * @return a boolean value */ public static boolean isOuterMostType(DetailAST aAST) { boolean retVal = true; for (DetailAST parent = aAST.getParent(); parent != null; parent = parent.getParent()) { if ((parent.getType() == TokenTypes.CLASS_DEF) || (parent.getType() == TokenTypes.INTERFACE_DEF) || (parent.getType() == TokenTypes.ANNOTATION_DEF) || (parent.getType() == TokenTypes.ENUM_DEF)) { retVal = false; break; } } return retVal; } /** * Determines whether a node is a local variable definition. * I.e. if it is declared in a code block, a for initializer, * or a catch parameter. * @param aAST the node to check. * @return whether aAST is a local variable definition. */ public static boolean isLocalVariableDef(DetailAST aAST) { // variable declaration? if (aAST.getType() == TokenTypes.VARIABLE_DEF) { final DetailAST parent = aAST.getParent(); if (parent != null) { final int type = parent.getType(); return (type == TokenTypes.SLIST) || (type == TokenTypes.FOR_INIT) || (type == TokenTypes.FOR_EACH_CLAUSE); } } // catch parameter? else if (aAST.getType() == TokenTypes.PARAMETER_DEF) { final DetailAST parent = aAST.getParent(); if (parent != null) { return (parent.getType() == TokenTypes.LITERAL_CATCH); } } return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/SeverityLevel.java100644 0 0 4253 12026051066 26300 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** *

* Severity level for a check violation. *

*

* Each violation of an audit check is assigned one of the severity levels * defined here. *

* * @author David Schneider * @author Travis Schneeberger */ public enum SeverityLevel { /** security level ignore. */ IGNORE, /** security level info. */ INFO, /** security level warning. */ WARNING, /** security level error. */ ERROR; @Override public String toString() { return getName(); } /** * @return the name of this severity level. */ public String getName() { return name().toLowerCase(); } /** * SeverityLevel factory method. * * @param aSecurityLevelName level name, such as "ignore", "info", etc. * @return the SeverityLevel * associated with aSecurityLevelName */ public static SeverityLevel getInstance(String aSecurityLevelName) { return valueOf(SeverityLevel.class, aSecurityLevelName.trim() .toUpperCase()); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/SeverityLevelCounter.java100644 0 0 5303 12026051066 27635 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** * An audit listener that counts how many {@link AuditEvent AuditEvents} * of a given severity have been generated. * * @author lkuehne */ public final class SeverityLevelCounter implements AuditListener { /** The severity level to watch out for. */ private SeverityLevel mLevel; /** Keeps track of the number of counted events. */ private int mCount; /** * Creates a new counter. * @param aLevel the severity level events need to have, must be non-null. */ public SeverityLevelCounter(SeverityLevel aLevel) { if (aLevel == null) { throw new IllegalArgumentException(); } mLevel = aLevel; } /** {@inheritDoc} */ public void addError(AuditEvent aEvt) { if (mLevel.equals(aEvt.getSeverityLevel())) { mCount++; } } /** {@inheritDoc} */ public void addException(AuditEvent aEvt, Throwable aThrowable) { if (SeverityLevel.ERROR.equals(mLevel)) { mCount++; } } /** {@inheritDoc} */ public void auditStarted(AuditEvent aEvt) { mCount = 0; } /** {@inheritDoc} */ public void fileStarted(AuditEvent aEvt) { } /** {@inheritDoc} */ public void auditFinished(AuditEvent aEvt) { } /** {@inheritDoc} */ public void fileFinished(AuditEvent aEvt) { } /** * Returns the number of counted events since audit started. * @return the number of counted events since audit started. */ public int getCount() { return mCount; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/TextBlock.java100644 0 0 5361 12026051066 25376 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; /** * A block of text from an inputfile that does not necessarily * have any grammatical structure. * * @author lkuehne */ public interface TextBlock { /** * The text content of the text block. * Each line is represented by one array entry. * The linebreak characters are not part of the text content. * * @return the text content of the text block. */ String[] getText(); /** * The line in the inputfile where the text block starts. * Counting starts from 1. * @return first line of the text block */ int getStartLineNo(); /** * The last line of the text block in the inputfile. * Counting starts from 1. * @return last line of the text block */ int getEndLineNo(); /** * The column in the inputfile where the text block starts. * Counting starts from 0. * @return first line of the text block */ int getStartColNo(); /** * The column in the inputfile where the text block ends. * Counting starts from 0. * @return last line of the text block */ int getEndColNo(); /** * Checks if this comment intersects with a specified * part of the file. * * @param aStartLineNo the starting line number in the file * @param aStartColNo the starting column number in the file * @param aEndLineNo the ending line number in the file * @param aEndColNo the ending column number in the file * @return true if the positions intersects with this comment. */ boolean intersects(int aStartLineNo, int aStartColNo, int aEndLineNo, int aEndColNo); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/TokenTypes.java100644 0 0 314360 12026051065 25645 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.google.common.collect.ImmutableMap; import com.puppycrawl.tools.checkstyle.grammars.GeneratedJavaTokenTypes; import java.lang.reflect.Field; import java.util.ResourceBundle; /** * Contains the constants for all the tokens contained in the Abstract * Syntax Tree. * *

Implementation detail: This class has been introduced to break * the circular dependency between packages.

* * @author Oliver Burn * @author Peter Dobratz * @version 1.0 */ public final class TokenTypes { ///CLOVER:OFF /** prevent instantiation */ private TokenTypes() { } ///CLOVER:ON // The following three types are never part of an AST, // left here as a reminder so nobody will read them accidentally /* * token representing a NULL_TREE_LOOKAHEAD */ // public static final int NULL_TREE_LOOKAHEAD = 3; /* * token representing a BLOCK */ // public static final int BLOCK = 4; /* * token representing a VOCAB */ // public static final int VOCAB = 149; // These are the types that can actually occur in an AST // it makes sense to register Checks for these types /** * The end of file token. This is the root node for the source * file. It's children are an optional package definition, zero * or more import statements, and one or more class or interface * definitions. * * @see #PACKAGE_DEF * @see #IMPORT * @see #CLASS_DEF * @see #INTERFACE_DEF **/ public static final int EOF = GeneratedJavaTokenTypes.EOF; /** * Modifiers for type, method, and field declarations. The * modifiers element is always present even though it may have no * children. * * @see Java * Language Specification, Chapter 8 * @see #LITERAL_PUBLIC * @see #LITERAL_PROTECTED * @see #LITERAL_PRIVATE * @see #ABSTRACT * @see #LITERAL_STATIC * @see #FINAL * @see #LITERAL_TRANSIENT * @see #LITERAL_VOLATILE * @see #LITERAL_SYNCHRONIZED * @see #LITERAL_NATIVE * @see #STRICTFP * @see #ANNOTATION **/ public static final int MODIFIERS = GeneratedJavaTokenTypes.MODIFIERS; /** * An object block. These are children of class, interface, enum, * annotation and enum constant declarations. * Also, object blocks are children of the new keyword when defining * anonymous inner types. * * @see #LCURLY * @see #INSTANCE_INIT * @see #STATIC_INIT * @see #CLASS_DEF * @see #CTOR_DEF * @see #METHOD_DEF * @see #VARIABLE_DEF * @see #RCURLY * @see #INTERFACE_DEF * @see #LITERAL_NEW * @see #ENUM_DEF * @see #ENUM_CONSTANT_DEF * @see #ANNOTATION_DEF **/ public static final int OBJBLOCK = GeneratedJavaTokenTypes.OBJBLOCK; /** * A list of statements. * * @see #RCURLY * @see #EXPR * @see #LABELED_STAT * @see #LITERAL_THROWS * @see #LITERAL_RETURN * @see #SEMI * @see #METHOD_DEF * @see #CTOR_DEF * @see #LITERAL_FOR * @see #LITERAL_WHILE * @see #LITERAL_IF * @see #LITERAL_ELSE * @see #CASE_GROUP **/ public static final int SLIST = GeneratedJavaTokenTypes.SLIST; /** * A constructor declaration. * *

For example:

*
     * public SpecialEntry(int value, String text)
     * {
     *   this.value = value;
     *   this.text = text;
     * }
     * 
*

parses as:

*
     * +--CTOR_DEF
     *     |
     *     +--MODIFIERS
     *         |
     *         +--LITERAL_PUBLIC (public)
     *     +--IDENT (SpecialEntry)
     *     +--LPAREN (()
     *     +--PARAMETERS
     *         |
     *         +--PARAMETER_DEF
     *             |
     *             +--MODIFIERS
     *             +--TYPE
     *                 |
     *                 +--LITERAL_INT (int)
     *             +--IDENT (value)
     *         +--COMMA (,)
     *         +--PARAMETER_DEF
     *             |
     *             +--MODIFIERS
     *             +--TYPE
     *                 |
     *                 +--IDENT (String)
     *             +--IDENT (text)
     *     +--RPAREN ())
     *     +--SLIST ({)
     *         |
     *         +--EXPR
     *             |
     *             +--ASSIGN (=)
     *                 |
     *                 +--DOT (.)
     *                     |
     *                     +--LITERAL_THIS (this)
     *                     +--IDENT (value)
     *                 +--IDENT (value)
     *         +--SEMI (;)
     *         +--EXPR
     *             |
     *             +--ASSIGN (=)
     *                 |
     *                 +--DOT (.)
     *                     |
     *                     +--LITERAL_THIS (this)
     *                     +--IDENT (text)
     *                 +--IDENT (text)
     *         +--SEMI (;)
     *         +--RCURLY (})
     * 
* * @see #OBJBLOCK * @see #CLASS_DEF **/ public static final int CTOR_DEF = GeneratedJavaTokenTypes.CTOR_DEF; /** * A method declaration. The children are modifiers, type parameters, * return type, method name, parameter list, an optional throws list, and * statement list. The statement list is omitted if the method * declaration appears in an interface declaration. Method * declarations may appear inside object blocks of class * declarations, interface declarations, enum declarations, * enum constant declarations or anonymous inner-class declarations. * *

For example:

* *
     *  public static int square(int x)
     *  {
     *    return x*x;
     *  }
     * 
* *

parses as:

* *
     * +--METHOD_DEF
     *     |
     *     +--MODIFIERS
     *         |
     *         +--LITERAL_PUBLIC (public)
     *         +--LITERAL_STATIC (static)
     *     +--TYPE
     *         |
     *         +--LITERAL_INT (int)
     *     +--IDENT (square)
     *     +--PARAMETERS
     *         |
     *         +--PARAMETER_DEF
     *             |
     *             +--MODIFIERS
     *             +--TYPE
     *                 |
     *                 +--LITERAL_INT (int)
     *             +--IDENT (x)
     *     +--SLIST ({)
     *         |
     *         +--LITERAL_RETURN (return)
     *             |
     *             +--EXPR
     *                 |
     *                 +--STAR (*)
     *                     |
     *                     +--IDENT (x)
     *                     +--IDENT (x)
     *             +--SEMI (;)
     *         +--RCURLY (})
     * 
* * @see #MODIFIERS * @see #TYPE_PARAMETERS * @see #TYPE * @see #IDENT * @see #PARAMETERS * @see #LITERAL_THROWS * @see #SLIST * @see #OBJBLOCK **/ public static final int METHOD_DEF = GeneratedJavaTokenTypes.METHOD_DEF; /** * A field or local variable declaration. The children are * modifiers, type, the identifier name, and an optional * assignment statement. * * @see #MODIFIERS * @see #TYPE * @see #IDENT * @see #ASSIGN **/ public static final int VARIABLE_DEF = GeneratedJavaTokenTypes.VARIABLE_DEF; /** * An instance initializer. Zero or more instance initializers * may appear in class and enum definitions. This token will be a child * of the object block of the declaring type. * * @see Java * Language Specification§8.6 * @see #SLIST * @see #OBJBLOCK **/ public static final int INSTANCE_INIT = GeneratedJavaTokenTypes.INSTANCE_INIT; /** * A static initialization block. Zero or more static * initializers may be children of the object block of a class * or enum declaration (interfaces cannot have static initializers). The * first and only child is a statement list. * * @see Java * Language Specification, §8.7 * @see #SLIST * @see #OBJBLOCK **/ public static final int STATIC_INIT = GeneratedJavaTokenTypes.STATIC_INIT; /** * A type. This is either a return type of a method or a type of * a variable or field. The first child of this element is the * actual type. This may be a primitive type, an identifier, a * dot which is the root of a fully qualified type, or an array of * any of these. The second child may be type arguments to the type. * * @see #VARIABLE_DEF * @see #METHOD_DEF * @see #PARAMETER_DEF * @see #IDENT * @see #DOT * @see #LITERAL_VOID * @see #LITERAL_BOOLEAN * @see #LITERAL_BYTE * @see #LITERAL_CHAR * @see #LITERAL_SHORT * @see #LITERAL_INT * @see #LITERAL_FLOAT * @see #LITERAL_LONG * @see #LITERAL_DOUBLE * @see #ARRAY_DECLARATOR * @see #TYPE_ARGUMENTS **/ public static final int TYPE = GeneratedJavaTokenTypes.TYPE; /** * A class declaration. * *

For example:

*
     * public class MyClass
     *   implements Serializable
     * {
     * }
     * 
*

parses as:

*
     * +--CLASS_DEF
     *     |
     *     +--MODIFIERS
     *         |
     *         +--LITERAL_PUBLIC (public)
     *     +--LITERAL_CLASS (class)
     *     +--IDENT (MyClass)
     *     +--EXTENDS_CLAUSE
     *     +--IMPLEMENTS_CLAUSE
     *         |
     *         +--IDENT (Serializable)
     *     +--OBJBLOCK
     *         |
     *         +--LCURLY ({)
     *         +--RCURLY (})
     * 
* * @see Java * Language Specification, Chapter 8 * @see #MODIFIERS * @see #IDENT * @see #EXTENDS_CLAUSE * @see #IMPLEMENTS_CLAUSE * @see #OBJBLOCK * @see #LITERAL_NEW **/ public static final int CLASS_DEF = GeneratedJavaTokenTypes.CLASS_DEF; /** * An interface declaration. * *

For example:

* *
     *   public interface MyInterface
     *   {
     *   }
     *
     * 
* *

parses as:

* *
     * +--INTERFACE_DEF
     *     |
     *     +--MODIFIERS
     *         |
     *         +--LITERAL_PUBLIC (public)
     *     +--LITERAL_INTERFACE (interface)
     *     +--IDENT (MyInterface)
     *     +--EXTENDS_CLAUSE
     *     +--OBJBLOCK
     *         |
     *         +--LCURLY ({)
     *         +--RCURLY (})
     * 
* * @see Java * Language Specification, Chapter 9 * @see #MODIFIERS * @see #IDENT * @see #EXTENDS_CLAUSE * @see #OBJBLOCK **/ public static final int INTERFACE_DEF = GeneratedJavaTokenTypes.INTERFACE_DEF; /** * The package declaration. This is optional, but if it is * included, then there is only one package declaration per source * file and it must be the first non-comment in the file. A package * declaration may be annotated in which case the annotations comes * before the rest of the declaration (and are the first children). * *

For example:

* *
     *   package com.puppycrawl.tools.checkstyle.api;
     * 
* *

parses as:

* *
     * +--PACKAGE_DEF (package)
     *     |
     *     +--ANNOTATIONS
     *     +--DOT (.)
     *         |
     *         +--DOT (.)
     *             |
     *             +--DOT (.)
     *                 |
     *                 +--DOT (.)
     *                     |
     *                     +--IDENT (com)
     *                     +--IDENT (puppycrawl)
     *                 +--IDENT (tools)
     *             +--IDENT (checkstyle)
     *         +--IDENT (api)
     *     +--SEMI (;)
     * 
* * @see Java * Language Specification §7.4 * @see #DOT * @see #IDENT * @see #SEMI * @see #ANNOTATIONS * @see FullIdent **/ public static final int PACKAGE_DEF = GeneratedJavaTokenTypes.PACKAGE_DEF; /** * An array declaration. * *

If the array declaration represents a type, then the type of * the array elements is the first child. Multidimensional arrays * may be regarded as arrays of arrays. In other words, the first * child of the array declaration is another array * declaration.

* *

For example:

*
     *   int[] x;
     * 
*

parses as:

*
     * +--VARIABLE_DEF
     *     |
     *     +--MODIFIERS
     *     +--TYPE
     *         |
     *         +--ARRAY_DECLARATOR ([)
     *             |
     *             +--LITERAL_INT (int)
     *     +--IDENT (x)
     * +--SEMI (;)
     * 
* *

The array declaration may also represent an inline array * definition. In this case, the first child will be either an * expression specifying the length of the array or an array * initialization block.

* * @see Java * Language Specification Chapter 10 * @see #TYPE * @see #ARRAY_INIT **/ public static final int ARRAY_DECLARATOR = GeneratedJavaTokenTypes.ARRAY_DECLARATOR; /** * An extends clause. This appear as part of class and interface * definitions. This element appears even if the * extends keyword is not explicitly used. The child * is an optional identifier. * *

For example:

*
     * 
*

parses as:

*
     * +--EXTENDS_CLAUSE
     *     |
     *     +--DOT (.)
     *         |
     *         +--DOT (.)
     *             |
     *             +--IDENT (java)
     *             +--IDENT (util)
     *         +--IDENT (LinkedList)
     * 
* * @see #IDENT * @see #DOT * @see #CLASS_DEF * @see #INTERFACE_DEF * @see FullIdent **/ public static final int EXTENDS_CLAUSE = GeneratedJavaTokenTypes.EXTENDS_CLAUSE; /** * An implements clause. This always appears in a class or enum * declaration, even if there are no implemented interfaces. The * children are a comma separated list of zero or more * identifiers. * *

For example:

*
     * implements Serializable, Comparable
     * 
*

parses as:

*
     * +--IMPLEMENTS_CLAUSE
     *     |
     *     +--IDENT (Serializable)
     *     +--COMMA (,)
     *     +--IDENT (Comparable)
     * 
* * @see #IDENT * @see #DOT * @see #COMMA * @see #CLASS_DEF * @see #ENUM_DEF **/ public static final int IMPLEMENTS_CLAUSE = GeneratedJavaTokenTypes.IMPLEMENTS_CLAUSE; /** * A list of parameters to a method or constructor. The children * are zero or more parameter declarations separated by commas. * *

For example

*
     * int start, int end
     * 
*

parses as:

*
     * +--PARAMETERS
     *     |
     *     +--PARAMETER_DEF
     *         |
     *         +--MODIFIERS
     *         +--TYPE
     *             |
     *             +--LITERAL_INT (int)
     *         +--IDENT (start)
     *     +--COMMA (,)
     *     +--PARAMETER_DEF
     *         |
     *         +--MODIFIERS
     *         +--TYPE
     *             |
     *             +--LITERAL_INT (int)
     *         +--IDENT (end)
     * 
* * @see #PARAMETER_DEF * @see #COMMA * @see #METHOD_DEF * @see #CTOR_DEF **/ public static final int PARAMETERS = GeneratedJavaTokenTypes.PARAMETERS; /** * A parameter declaration. The last parameter in a list of parameters may * be variable length (indicated by the ELLIPSIS child node immediately * after the TYPE child). * * @see #MODIFIERS * @see #TYPE * @see #IDENT * @see #PARAMETERS * @see #ELLIPSIS **/ public static final int PARAMETER_DEF = GeneratedJavaTokenTypes.PARAMETER_DEF; /** * A labeled statement. * *

For example:

*
     * outside: ;
     * 
*

parses as:

*
     * +--LABELED_STAT (:)
     *     |
     *     +--IDENT (outside)
     *     +--EMPTY_STAT (;)
     * 
* * @see Java * Language Specification, §14.7 * @see #SLIST **/ public static final int LABELED_STAT = GeneratedJavaTokenTypes.LABELED_STAT; /** * A type-cast. * *

For example:

*
     * (String)it.next()
     * 
*

parses as:

*
     * +--TYPECAST (()
     *     |
     *     +--TYPE
     *         |
     *         +--IDENT (String)
     *     +--RPAREN ())
     *     +--METHOD_CALL (()
     *         |
     *         +--DOT (.)
     *             |
     *             +--IDENT (it)
     *             +--IDENT (next)
     *         +--ELIST
     *         +--RPAREN ())
     * 
* @see Java * Language Specification, §15.16 * @see #EXPR * @see #TYPE * @see #TYPE_ARGUMENTS * @see #RPAREN **/ public static final int TYPECAST = GeneratedJavaTokenTypes.TYPECAST; /** * The array index operator. * *

For example:

*
     * ar[2] = 5;
     * 
*

parses as:

*
     * +--EXPR
     *     |
     *     +--ASSIGN (=)
     *         |
     *         +--INDEX_OP ([)
     *             |
     *             +--IDENT (ar)
     *             +--EXPR
     *                 |
     *                 +--NUM_INT (2)
     *         +--NUM_INT (5)
     * +--SEMI (;)
     * 
* * @see #EXPR **/ public static final int INDEX_OP = GeneratedJavaTokenTypes.INDEX_OP; /** * The ++ (postfix increment) operator. * * @see Java * Language Specification, §15.14.1 * @see #EXPR * @see #INC **/ public static final int POST_INC = GeneratedJavaTokenTypes.POST_INC; /** * The -- (postfix decrement) operator. * * @see Java * Language Specification, §15.14.2 * @see #EXPR * @see #DEC **/ public static final int POST_DEC = GeneratedJavaTokenTypes.POST_DEC; /** * A method call. A method call may have type arguments however these * are attached to the appropriate node in the qualified method name. * *

For example:

*
     * Math.random()
     * 
*

parses as: *

     * +--METHOD_CALL (()
     *     |
     *     +--DOT (.)
     *         |
     *         +--IDENT (Math)
     *         +--IDENT (random)
     *     +--ELIST
     *     +--RPAREN ())
     * 
* * @see #IDENT * @see #TYPE_ARGUMENTS * @see #DOT * @see #ELIST * @see #RPAREN * @see FullIdent **/ public static final int METHOD_CALL = GeneratedJavaTokenTypes.METHOD_CALL; /** * An expression. Operators with lower precedence appear at a * higher level in the tree than operators with higher precedence. * Parentheses are siblings to the operator they enclose. * *

For example:

*
     * x = 4 + 3 * 5 + (30 + 26) / 4 + 5 % 4 + (1<<3);
     * 
*

parses as:

*
     * +--EXPR
     *     |
     *     +--ASSIGN (=)
     *         |
     *         +--IDENT (x)
     *         +--PLUS (+)
     *             |
     *             +--PLUS (+)
     *                 |
     *                 +--PLUS (+)
     *                     |
     *                     +--PLUS (+)
     *                         |
     *                         +--NUM_INT (4)
     *                         +--STAR (*)
     *                             |
     *                             +--NUM_INT (3)
     *                             +--NUM_INT (5)
     *                     +--DIV (/)
     *                         |
     *                         +--LPAREN (()
     *                         +--PLUS (+)
     *                             |
     *                             +--NUM_INT (30)
     *                             +--NUM_INT (26)
     *                         +--RPAREN ())
     *                         +--NUM_INT (4)
     *                 +--MOD (%)
     *                     |
     *                     +--NUM_INT (5)
     *                     +--NUM_INT (4)
     *             +--LPAREN (()
     *             +--SL (<<)
     *                 |
     *                 +--NUM_INT (1)
     *                 +--NUM_INT (3)
     *             +--RPAREN ())
     * +--SEMI (;)
     * 
* * @see #ELIST * @see #ASSIGN * @see #LPAREN * @see #RPAREN **/ public static final int EXPR = GeneratedJavaTokenTypes.EXPR; /** * An array initialization. This may occur as part of an array * declaration or inline with new. * *

For example:

*
     *   int[] y =
     *     {
     *       1,
     *       2,
     *     };
     * 
*

parses as:

*
     * +--VARIABLE_DEF
     *     |
     *     +--MODIFIERS
     *     +--TYPE
     *         |
     *         +--ARRAY_DECLARATOR ([)
     *             |
     *             +--LITERAL_INT (int)
     *     +--IDENT (y)
     *     +--ASSIGN (=)
     *         |
     *         +--ARRAY_INIT ({)
     *             |
     *             +--EXPR
     *                 |
     *                 +--NUM_INT (1)
     *             +--COMMA (,)
     *             +--EXPR
     *                 |
     *                 +--NUM_INT (2)
     *             +--COMMA (,)
     *             +--RCURLY (})
     * +--SEMI (;)
     * 
* *

Also consider:

*
     *   int[] z = new int[]
     *     {
     *       1,
     *       2,
     *     };
     * 
*

which parses as:

*
     * +--VARIABLE_DEF
     *     |
     *     +--MODIFIERS
     *     +--TYPE
     *         |
     *         +--ARRAY_DECLARATOR ([)
     *             |
     *             +--LITERAL_INT (int)
     *     +--IDENT (z)
     *     +--ASSIGN (=)
     *         |
     *         +--EXPR
     *             |
     *             +--LITERAL_NEW (new)
     *                 |
     *                 +--LITERAL_INT (int)
     *                 +--ARRAY_DECLARATOR ([)
     *                 +--ARRAY_INIT ({)
     *                     |
     *                     +--EXPR
     *                         |
     *                         +--NUM_INT (1)
     *                     +--COMMA (,)
     *                     +--EXPR
     *                         |
     *                         +--NUM_INT (2)
     *                     +--COMMA (,)
     *                     +--RCURLY (})
     * 
* * @see #ARRAY_DECLARATOR * @see #TYPE * @see #LITERAL_NEW * @see #COMMA **/ public static final int ARRAY_INIT = GeneratedJavaTokenTypes.ARRAY_INIT; /** * An import declaration. Import declarations are option, but * must appear after the package declaration and before the first type * declaration. * *

For example:

* *
     *   import java.io.IOException;
     * 
* *

parses as:

* *
     * +--IMPORT (import)
     *     |
     *     +--DOT (.)
     *         |
     *         +--DOT (.)
     *             |
     *             +--IDENT (java)
     *             +--IDENT (io)
     *         +--IDENT (IOException)
     *     +--SEMI (;)
     * 
* * @see Java * Language Specification §7.5 * @see #DOT * @see #IDENT * @see #STAR * @see #SEMI * @see FullIdent **/ public static final int IMPORT = GeneratedJavaTokenTypes.IMPORT; /** * The - (unary minus) operator. * * @see Java * Language Specification, §15.15.4 * @see #EXPR **/ public static final int UNARY_MINUS = GeneratedJavaTokenTypes.UNARY_MINUS; /** * The + (unary plus) operator. * * @see Java * Language Specification, §15.15.3 * @see #EXPR **/ public static final int UNARY_PLUS = GeneratedJavaTokenTypes.UNARY_PLUS; /** * A group of case clauses. Case clauses with no associated * statements are grouped together into a case group. The last * child is a statement list containing the statements to execute * upon a match. * *

For example:

*
     * case 0:
     * case 1:
     * case 2:
     *   x = 3;
     *   break;
     * 
*

parses as:

*
     * +--CASE_GROUP
     *     |
     *     +--LITERAL_CASE (case)
     *         |
     *         +--EXPR
     *             |
     *             +--NUM_INT (0)
     *     +--LITERAL_CASE (case)
     *         |
     *         +--EXPR
     *             |
     *             +--NUM_INT (1)
     *     +--LITERAL_CASE (case)
     *         |
     *         +--EXPR
     *             |
     *             +--NUM_INT (2)
     *     +--SLIST
     *         |
     *         +--EXPR
     *             |
     *             +--ASSIGN (=)
     *                 |
     *                 +--IDENT (x)
     *                 +--NUM_INT (3)
     *         +--SEMI (;)
     *         +--LITERAL_BREAK (break)
     *             |
     *             +--SEMI (;)
     * 
* * @see #LITERAL_CASE * @see #LITERAL_DEFAULT * @see #LITERAL_SWITCH **/ public static final int CASE_GROUP = GeneratedJavaTokenTypes.CASE_GROUP; /** * An expression list. The children are a comma separated list of * expressions. * * @see #LITERAL_NEW * @see #FOR_INIT * @see #FOR_ITERATOR * @see #EXPR * @see #METHOD_CALL * @see #CTOR_CALL * @see #SUPER_CTOR_CALL **/ public static final int ELIST = GeneratedJavaTokenTypes.ELIST; /** * A for loop initializer. This is a child of * LITERAL_FOR. The children of this element may be * a comma separated list of variable declarations, an expression * list, or empty. * * @see #VARIABLE_DEF * @see #ELIST * @see #LITERAL_FOR **/ public static final int FOR_INIT = GeneratedJavaTokenTypes.FOR_INIT; /** * A for loop condition. This is a child of * LITERAL_FOR. The child of this element is an * optional expression. * * @see #EXPR * @see #LITERAL_FOR **/ public static final int FOR_CONDITION = GeneratedJavaTokenTypes.FOR_CONDITION; /** * A for loop iterator. This is a child of * LITERAL_FOR. The child of this element is an * optional expression list. * * @see #ELIST * @see #LITERAL_FOR **/ public static final int FOR_ITERATOR = GeneratedJavaTokenTypes.FOR_ITERATOR; /** * The empty statement. This goes in place of an * SLIST for a for or while * loop body. * * @see Java * Language Specification, §14.6 * @see #LITERAL_FOR * @see #LITERAL_WHILE **/ public static final int EMPTY_STAT = GeneratedJavaTokenTypes.EMPTY_STAT; /** * The final keyword. * * @see #MODIFIERS **/ public static final int FINAL = GeneratedJavaTokenTypes.FINAL; /** * The abstract keyword. * * @see #MODIFIERS **/ public static final int ABSTRACT = GeneratedJavaTokenTypes.ABSTRACT; /** * The strictfp keyword. * * @see #MODIFIERS **/ public static final int STRICTFP = GeneratedJavaTokenTypes.STRICTFP; /** * A super constructor call. * * @see #ELIST * @see #RPAREN * @see #SEMI * @see #CTOR_CALL **/ public static final int SUPER_CTOR_CALL = GeneratedJavaTokenTypes.SUPER_CTOR_CALL; /** * A constructor call. * *

For example:

*
     * this(1);
     * 
*

parses as:

*
     * +--CTOR_CALL (this)
     *     |
     *     +--LPAREN (()
     *     +--ELIST
     *         |
     *         +--EXPR
     *             |
     *             +--NUM_INT (1)
     *     +--RPAREN ())
     *     +--SEMI (;)
     * 
* * @see #ELIST * @see #RPAREN * @see #SEMI * @see #SUPER_CTOR_CALL **/ public static final int CTOR_CALL = GeneratedJavaTokenTypes.CTOR_CALL; /* * * This token does not appear in the tree. * * @see #PACKAGE_DEF **/ //public static final int LITERAL_PACKAGE = // GeneratedJavaTokenTypes.LITERAL_package; /** * The statement terminator (;). Depending on the * context, this make occur as a sibling, a child, or not at all. * * @see #PACKAGE_DEF * @see #IMPORT * @see #SLIST * @see #ARRAY_INIT * @see #LITERAL_FOR **/ public static final int SEMI = GeneratedJavaTokenTypes.SEMI; /* * * This token does not appear in the tree. * * @see #IMPORT **/ // public static final int LITERAL_IMPORT = // GeneratedJavaTokenTypes.LITERAL_import; /* * * This token does not appear in the tree. * * @see #INDEX_OP * @see #ARRAY_DECLARATOR **/ //public static final int LBRACK = GeneratedJavaTokenTypes.LBRACK; /** * The ] symbol. * * @see #INDEX_OP * @see #ARRAY_DECLARATOR **/ public static final int RBRACK = GeneratedJavaTokenTypes.RBRACK; /** * The void keyword. * * @see #TYPE **/ public static final int LITERAL_VOID = GeneratedJavaTokenTypes.LITERAL_void; /** * The boolean keyword. * * @see #TYPE **/ public static final int LITERAL_BOOLEAN = GeneratedJavaTokenTypes.LITERAL_boolean; /** * The byte keyword. * * @see #TYPE **/ public static final int LITERAL_BYTE = GeneratedJavaTokenTypes.LITERAL_byte; /** * The char keyword. * * @see #TYPE **/ public static final int LITERAL_CHAR = GeneratedJavaTokenTypes.LITERAL_char; /** * The short keyword. * * @see #TYPE **/ public static final int LITERAL_SHORT = GeneratedJavaTokenTypes.LITERAL_short; /** * The int keyword. * * @see #TYPE **/ public static final int LITERAL_INT = GeneratedJavaTokenTypes.LITERAL_int; /** * The float keyword. * * @see #TYPE **/ public static final int LITERAL_FLOAT = GeneratedJavaTokenTypes.LITERAL_float; /** * The long keyword. * * @see #TYPE **/ public static final int LITERAL_LONG = GeneratedJavaTokenTypes.LITERAL_long; /** * The double keyword. * * @see #TYPE **/ public static final int LITERAL_DOUBLE = GeneratedJavaTokenTypes.LITERAL_double; /** * An identifier. These can be names of types, subpackages, * fields, methods, parameters, and local variables. **/ public static final int IDENT = GeneratedJavaTokenTypes.IDENT; /** * The . (dot) operator. * * @see FullIdent **/ public static final int DOT = GeneratedJavaTokenTypes.DOT; /** * The * (multiplication or wildcard) operator. * * @see Java * Language Specification, §7.5.2 * @see Java * Language Specification, §15.17.1 * @see #EXPR * @see #IMPORT **/ public static final int STAR = GeneratedJavaTokenTypes.STAR; /** * The private keyword. * * @see #MODIFIERS **/ public static final int LITERAL_PRIVATE = GeneratedJavaTokenTypes.LITERAL_private; /** * The public keyword. * * @see #MODIFIERS **/ public static final int LITERAL_PUBLIC = GeneratedJavaTokenTypes.LITERAL_public; /** * The protected keyword. * * @see #MODIFIERS **/ public static final int LITERAL_PROTECTED = GeneratedJavaTokenTypes.LITERAL_protected; /** * The static keyword. * * @see #MODIFIERS **/ public static final int LITERAL_STATIC = GeneratedJavaTokenTypes.LITERAL_static; /** * The transient keyword. * * @see #MODIFIERS **/ public static final int LITERAL_TRANSIENT = GeneratedJavaTokenTypes.LITERAL_transient; /** * The native keyword. * * @see #MODIFIERS **/ public static final int LITERAL_NATIVE = GeneratedJavaTokenTypes.LITERAL_native; /** * The synchronized keyword. This may be used as a * modifier of a method or in the definition of a synchronized * block. * *

For example:

* *
     * synchronized(this)
     * {
     *   x++;
     * }
     * 
* *

parses as:

* *
     * +--LITERAL_SYNCHRONIZED (synchronized)
     *     |
     *     +--LPAREN (()
     *     +--EXPR
     *         |
     *         +--LITERAL_THIS (this)
     *     +--RPAREN ())
     *     +--SLIST ({)
     *         |
     *         +--EXPR
     *             |
     *             +--POST_INC (++)
     *                 |
     *                 +--IDENT (x)
     *         +--SEMI (;)
     *         +--RCURLY (})
     * +--RCURLY (})
     * 
* * @see #MODIFIERS * @see #LPAREN * @see #EXPR * @see #RPAREN * @see #SLIST * @see #RCURLY **/ public static final int LITERAL_SYNCHRONIZED = GeneratedJavaTokenTypes.LITERAL_synchronized; /** * The volatile keyword. * * @see #MODIFIERS **/ public static final int LITERAL_VOLATILE = GeneratedJavaTokenTypes.LITERAL_volatile; /** * The class keyword. This element appears both * as part of a class declaration, and inline to reference a * class object. * *

For example:

* *
     * int.class
     * 
*

parses as:

*
     * +--EXPR
     *     |
     *     +--DOT (.)
     *         |
     *         +--LITERAL_INT (int)
     *         +--LITERAL_CLASS (class)
     * 
* * @see #DOT * @see #IDENT * @see #CLASS_DEF * @see FullIdent **/ public static final int LITERAL_CLASS = GeneratedJavaTokenTypes.LITERAL_class; /* * * This token does not appear in the tree. * * @see #EXTENDS_CLAUSE **/ //public static final int LITERAL_EXTENDS = // GeneratedJavaTokenTypes.LITERAL_extends; /** * The interface keyword. This token appears in * interface definition. * * @see #INTERFACE_DEF **/ public static final int LITERAL_INTERFACE = GeneratedJavaTokenTypes.LITERAL_interface; /** * A left (curly) brace ({). * * @see #OBJBLOCK * @see #ARRAY_INIT * @see #SLIST **/ public static final int LCURLY = GeneratedJavaTokenTypes.LCURLY; /** * A right (curly) brace (}). * * @see #OBJBLOCK * @see #ARRAY_INIT * @see #SLIST **/ public static final int RCURLY = GeneratedJavaTokenTypes.RCURLY; /** * The , (comma) operator. * * @see #ARRAY_INIT * @see #FOR_INIT * @see #FOR_ITERATOR * @see #LITERAL_THROWS * @see #IMPLEMENTS_CLAUSE **/ public static final int COMMA = GeneratedJavaTokenTypes.COMMA; /* * * This token does not appear in the tree. * * @see #IMPLEMENTS_CLAUSE **/ // public static final int LITERAL_IMPLEMENTS = // GeneratedJavaTokenTypes.LITERAL_implements; /** * A left parenthesis ((). * * @see #LITERAL_FOR * @see #LITERAL_NEW * @see #EXPR * @see #LITERAL_SWITCH * @see #LITERAL_CATCH **/ public static final int LPAREN = GeneratedJavaTokenTypes.LPAREN; /** * A right parenthesis ()). * * @see #LITERAL_FOR * @see #LITERAL_NEW * @see #METHOD_CALL * @see #TYPECAST * @see #EXPR * @see #LITERAL_SWITCH * @see #LITERAL_CATCH **/ public static final int RPAREN = GeneratedJavaTokenTypes.RPAREN; /** * The this keyword. * * @see #EXPR * @see #CTOR_CALL **/ public static final int LITERAL_THIS = GeneratedJavaTokenTypes.LITERAL_this; /** * The super keyword. * * @see #EXPR * @see #SUPER_CTOR_CALL **/ public static final int LITERAL_SUPER = GeneratedJavaTokenTypes.LITERAL_super; /** * The = (assignment) operator. * * @see Java * Language Specification, §15.26.1 * @see #EXPR **/ public static final int ASSIGN = GeneratedJavaTokenTypes.ASSIGN; /** * The throws keyword. The children are a number of * one or more identifiers separated by commas. * * @see Java * Language Specification, §8.4.4 * @see #IDENT * @see #DOT * @see #COMMA * @see #METHOD_DEF * @see #CTOR_DEF * @see FullIdent **/ public static final int LITERAL_THROWS = GeneratedJavaTokenTypes.LITERAL_throws; /** * The : (colon) operator. This will appear as part * of the conditional operator (? :). * * @see #QUESTION * @see #LABELED_STAT * @see #CASE_GROUP **/ public static final int COLON = GeneratedJavaTokenTypes.COLON; /** * The if keyword. * *

For example:

*
     * if(optimistic)
     * {
     *   message = "half full";
     * }
     * else
     * {
     *   message = "half empty";
     * }
     * 
*

parses as:

*
     * +--LITERAL_IF (if)
     *     |
     *     +--LPAREN (()
     *     +--EXPR
     *         |
     *         +--IDENT (optimistic)
     *     +--RPAREN ())
     *     +--SLIST ({)
     *         |
     *         +--EXPR
     *             |
     *             +--ASSIGN (=)
     *                 |
     *                 +--IDENT (message)
     *                 +--STRING_LITERAL ("half full")
     *         +--SEMI (;)
     *         +--RCURLY (})
     *     +--LITERAL_ELSE (else)
     *         |
     *         +--SLIST ({)
     *             |
     *             +--EXPR
     *                 |
     *                 +--ASSIGN (=)
     *                     |
     *                     +--IDENT (message)
     *                     +--STRING_LITERAL ("half empty")
     *             +--SEMI (;)
     *             +--RCURLY (})
     * 
* * @see #LPAREN * @see #EXPR * @see #RPAREN * @see #SLIST * @see #EMPTY_STAT * @see #LITERAL_ELSE **/ public static final int LITERAL_IF = GeneratedJavaTokenTypes.LITERAL_if; /** * The for keyword. The children are (, * an initializer, a condition, an iterator, a ) and * either a statement list, a single expression, or an empty * statement. * *

For example:

*
     * for(int i = 0, n = myArray.length; i < n; i++)
     * {
     * }
     * 
* *

parses as:

*
     * +--LITERAL_FOR (for)
     *     |
     *     +--LPAREN (()
     *     +--FOR_INIT
     *         |
     *         +--VARIABLE_DEF
     *             |
     *             +--MODIFIERS
     *             +--TYPE
     *                 |
     *                 +--LITERAL_INT (int)
     *             +--IDENT (i)
     *             +--ASSIGN (=)
     *                 |
     *                 +--EXPR
     *                     |
     *                     +--NUM_INT (0)
     *         +--COMMA (,)
     *         +--VARIABLE_DEF
     *             |
     *             +--MODIFIERS
     *             +--TYPE
     *                 |
     *                 +--LITERAL_INT (int)
     *             +--IDENT (n)
     *             +--ASSIGN (=)
     *                 |
     *                 +--EXPR
     *                     |
     *                     +--DOT (.)
     *                         |
     *                         +--IDENT (myArray)
     *                         +--IDENT (length)
     *     +--SEMI (;)
     *     +--FOR_CONDITION
     *         |
     *         +--EXPR
     *             |
     *             +--LT (<)
     *                 |
     *                 +--IDENT (i)
     *                 +--IDENT (n)
     *     +--SEMI (;)
     *     +--FOR_ITERATOR
     *         |
     *         +--ELIST
     *             |
     *             +--EXPR
     *                 |
     *                 +--POST_INC (++)
     *                     |
     *                     +--IDENT (i)
     *     +--RPAREN ())
     *     +--SLIST ({)
     *         |
     *         +--RCURLY (})
     * 
* * @see #LPAREN * @see #FOR_INIT * @see #SEMI * @see #FOR_CONDITION * @see #FOR_ITERATOR * @see #RPAREN * @see #SLIST * @see #EMPTY_STAT * @see #EXPR **/ public static final int LITERAL_FOR = GeneratedJavaTokenTypes.LITERAL_for; /** * The while keyword. * *

For example:

*
     * while(line != null)
     * {
     *   process(line);
     *   line = in.readLine();
     * }
     * 
*

parses as:

*
     * +--LITERAL_WHILE (while)
     *     |
     *     +--LPAREN (()
     *     +--EXPR
     *         |
     *         +--NOT_EQUAL (!=)
     *             |
     *             +--IDENT (line)
     *             +--LITERAL_NULL (null)
     *     +--RPAREN ())
     *     +--SLIST ({)
     *         |
     *         +--EXPR
     *             |
     *             +--METHOD_CALL (()
     *                 |
     *                 +--IDENT (process)
     *                 +--ELIST
     *                     |
     *                     +--EXPR
     *                         |
     *                         +--IDENT (line)
     *                 +--RPAREN ())
     *         +--SEMI (;)
     *         +--EXPR
     *             |
     *             +--ASSIGN (=)
     *                 |
     *                 +--IDENT (line)
     *                 +--METHOD_CALL (()
     *                     |
     *                     +--DOT (.)
     *                         |
     *                         +--IDENT (in)
     *                         +--IDENT (readLine)
     *                     +--ELIST
     *                     +--RPAREN ())
     *         +--SEMI (;)
     *         +--RCURLY (})
     * 
**/ public static final int LITERAL_WHILE = GeneratedJavaTokenTypes.LITERAL_while; /** * The do keyword. Note the the while token does not * appear as part of the do-while construct. * *

For example:

*
     * do
     * {
     *   x = rand.nextInt(10);
     * }
     * while(x < 5);
     * 
*

parses as:

*
     * +--LITERAL_DO (do)
     *     |
     *     +--SLIST ({)
     *         |
     *         +--EXPR
     *             |
     *             +--ASSIGN (=)
     *                 |
     *                 +--IDENT (x)
     *                 +--METHOD_CALL (()
     *                     |
     *                     +--DOT (.)
     *                         |
     *                         +--IDENT (rand)
     *                         +--IDENT (nextInt)
     *                     +--ELIST
     *                         |
     *                         +--EXPR
     *                             |
     *                             +--NUM_INT (10)
     *                     +--RPAREN ())
     *         +--SEMI (;)
     *         +--RCURLY (})
     *     +--LPAREN (()
     *     +--EXPR
     *         |
     *         +--LT (<)
     *             |
     *             +--IDENT (x)
     *             +--NUM_INT (5)
     *     +--RPAREN ())
     *     +--SEMI (;)
     * 
* * @see #SLIST * @see #EXPR * @see #EMPTY_STAT * @see #LPAREN * @see #RPAREN * @see #SEMI **/ public static final int LITERAL_DO = GeneratedJavaTokenTypes.LITERAL_do; /** * Literal while in do-while loop. * @see #LITERAL_DO */ public static final int DO_WHILE = GeneratedJavaTokenTypes.DO_WHILE; /** * The break keyword. The first child is an optional * identifier and the last child is a semicolon. * * @see #IDENT * @see #SEMI * @see #SLIST **/ public static final int LITERAL_BREAK = GeneratedJavaTokenTypes.LITERAL_break; /** * The continue keyword. The first child is an * optional identifier and the last child is a semicolon. * * @see #IDENT * @see #SEMI * @see #SLIST **/ public static final int LITERAL_CONTINUE = GeneratedJavaTokenTypes.LITERAL_continue; /** * The return keyword. The first child is an * optional expression for the return value. The last child is a * semi colon. * * @see #EXPR * @see #SEMI * @see #SLIST **/ public static final int LITERAL_RETURN = GeneratedJavaTokenTypes.LITERAL_return; /** * The switch keyword. * *

For example:

*
     * switch(type)
     * {
     *   case 0:
     *     background = Color.blue;
     *     break;
     *   case 1:
     *     background = Color.red;
     *     break;
     *   default:
     *     background = Color.green;
     *     break;
     * }
     * 
*

parses as:

*
     * +--LITERAL_SWITCH (switch)
     *     |
     *     +--LPAREN (()
     *     +--EXPR
     *         |
     *         +--IDENT (type)
     *     +--RPAREN ())
     *     +--LCURLY ({)
     *     +--CASE_GROUP
     *         |
     *         +--LITERAL_CASE (case)
     *             |
     *             +--EXPR
     *                 |
     *                 +--NUM_INT (0)
     *         +--SLIST
     *             |
     *             +--EXPR
     *                 |
     *                 +--ASSIGN (=)
     *                     |
     *                     +--IDENT (background)
     *                     +--DOT (.)
     *                         |
     *                         +--IDENT (Color)
     *                         +--IDENT (blue)
     *             +--SEMI (;)
     *             +--LITERAL_BREAK (break)
     *                 |
     *                 +--SEMI (;)
     *     +--CASE_GROUP
     *         |
     *         +--LITERAL_CASE (case)
     *             |
     *             +--EXPR
     *                 |
     *                 +--NUM_INT (1)
     *         +--SLIST
     *             |
     *             +--EXPR
     *                 |
     *                 +--ASSIGN (=)
     *                     |
     *                     +--IDENT (background)
     *                     +--DOT (.)
     *                         |
     *                         +--IDENT (Color)
     *                         +--IDENT (red)
     *             +--SEMI (;)
     *             +--LITERAL_BREAK (break)
     *                 |
     *                 +--SEMI (;)
     *     +--CASE_GROUP
     *         |
     *         +--LITERAL_DEFAULT (default)
     *         +--SLIST
     *             |
     *             +--EXPR
     *                 |
     *                 +--ASSIGN (=)
     *                     |
     *                     +--IDENT (background)
     *                     +--DOT (.)
     *                         |
     *                         +--IDENT (Color)
     *                         +--IDENT (green)
     *             +--SEMI (;)
     *             +--LITERAL_BREAK (break)
     *                 |
     *                 +--SEMI (;)
     *     +--RCURLY (})
     * 
* * @see Java * Language Specification, §14.10 * @see #LPAREN * @see #EXPR * @see #RPAREN * @see #LCURLY * @see #CASE_GROUP * @see #RCURLY * @see #SLIST **/ public static final int LITERAL_SWITCH = GeneratedJavaTokenTypes.LITERAL_switch; /** * The throw keyword. The first child is an * expression that evaluates to a Throwable instance. * * @see Java * Language Specification, §14.17 * @see #SLIST * @see #EXPR **/ public static final int LITERAL_THROW = GeneratedJavaTokenTypes.LITERAL_throw; /** * The else keyword. This appears as a child of an * if statement. * * @see #SLIST * @see #EXPR * @see #EMPTY_STAT * @see #LITERAL_IF **/ public static final int LITERAL_ELSE = GeneratedJavaTokenTypes.LITERAL_else; /** * The case keyword. The first child is a constant * expression that evaluates to a integer. * * @see #CASE_GROUP * @see #EXPR **/ public static final int LITERAL_CASE = GeneratedJavaTokenTypes.LITERAL_case; /** * The default keyword. This element has no * children. * * @see #CASE_GROUP **/ public static final int LITERAL_DEFAULT = GeneratedJavaTokenTypes.LITERAL_default; /** * The try keyword. The children are a statement * list, zero or more catch blocks and then an optional finally * block. * *

For example:

*
     * try
     * {
     *   FileReader in = new FileReader("abc.txt");
     * }
     * catch(IOException ioe)
     * {
     * }
     * finally
     * {
     * }
     * 
*

parses as:

*
     * +--LITERAL_TRY (try)
     *     |
     *     +--SLIST ({)
     *         |
     *         +--VARIABLE_DEF
     *             |
     *             +--MODIFIERS
     *             +--TYPE
     *                 |
     *                 +--IDENT (FileReader)
     *             +--IDENT (in)
     *             +--ASSIGN (=)
     *                 |
     *                 +--EXPR
     *                     |
     *                     +--LITERAL_NEW (new)
     *                         |
     *                         +--IDENT (FileReader)
     *                         +--LPAREN (()
     *                         +--ELIST
     *                             |
     *                             +--EXPR
     *                                 |
     *                                 +--STRING_LITERAL ("abc.txt")
     *                         +--RPAREN ())
     *         +--SEMI (;)
     *         +--RCURLY (})
     *     +--LITERAL_CATCH (catch)
     *         |
     *         +--LPAREN (()
     *         +--PARAMETER_DEF
     *             |
     *             +--MODIFIERS
     *             +--TYPE
     *                 |
     *                 +--IDENT (IOException)
     *             +--IDENT (ioe)
     *         +--RPAREN ())
     *         +--SLIST ({)
     *             |
     *             +--RCURLY (})
     *     +--LITERAL_FINALLY (finally)
     *         |
     *         +--SLIST ({)
     *             |
     *             +--RCURLY (})
     * +--RCURLY (})
     * 
* * @see Java * Language Specification, §14.19 * @see #SLIST * @see #LITERAL_CATCH * @see #LITERAL_FINALLY **/ public static final int LITERAL_TRY = GeneratedJavaTokenTypes.LITERAL_try; /** * Java 7 try-with-resources construct. * *

For example:

*
     * try (Foo foo = new Foo(); Bar bar = new Bar()) { }
     * 
*

parses as:

*
     * +--LITERAL_TRY (try)
     *     |
     *     +--RESOURCE_SPECIFICATION
     *         |
     *         +--LPAREN (()
     *         +--RESOURCES
     *             |
     *             +--RESOURCE
     *                 |
     *                 +--MODIFIERS
     *                 +--TYPE
     *                     |
     *                     +--IDENT (Foo)
     *                 +--IDENT (foo)
     *                 +--ASSIGN (=)
     *                 +--EXPR
     *                    |
     *                    +--LITERAL_NEW (new)
     *                       |
     *                       +--IDENT (Foo)
     *                       +--LPAREN (()
     *                       +--ELIST
     *                       +--RPAREN ())
     *             +--SEMI (;)
     *             +--RESOURCE
     *                 |
     *                 +--MODIFIERS
     *                 +--TYPE
     *                     |
     *                     +--IDENT (Bar)
     *                 +--IDENT (bar)
     *                 +--ASSIGN (=)
     *                 +--EXPR
     *                    |
     *                    +--LITERAL_NEW (new)
     *                       |
     *                       +--IDENT (Bar)
     *                       +--LPAREN (()
     *                       +--ELIST
     *                       +--RPAREN ())
     *         +--RPAREN ())
     *     +--SLIST ({)
     *         +--RCURLY (})
     * 
* * @see #LPAREN * @see #RESOURCES * @see #RESOURCE * @see #SEMI * @see #RPAREN * @see #LITERAL_TRY **/ public static final int RESOURCE_SPECIFICATION = GeneratedJavaTokenTypes.RESOURCE_SPECIFICATION; /** * Java 7 try-with-resources construct. * * @see #RESOURCE_SPECIFICATION **/ public static final int RESOURCES = GeneratedJavaTokenTypes.RESOURCES; /** * Java 7 try-with-resources construct. * * @see #RESOURCE_SPECIFICATION **/ public static final int RESOURCE = GeneratedJavaTokenTypes.RESOURCE; /** * The catch keyword. * * @see #LPAREN * @see #PARAMETER_DEF * @see #RPAREN * @see #SLIST * @see #LITERAL_TRY **/ public static final int LITERAL_CATCH = GeneratedJavaTokenTypes.LITERAL_catch; /** * The finally keyword. * * @see #SLIST * @see #LITERAL_TRY **/ public static final int LITERAL_FINALLY = GeneratedJavaTokenTypes.LITERAL_finally; /** * The += (addition assignment) operator. * * @see Java * Language Specification, §15.26.2 * @see #EXPR **/ public static final int PLUS_ASSIGN = GeneratedJavaTokenTypes.PLUS_ASSIGN; /** * The -= (subtraction assignment) operator. * * @see Java * Language Specification, §15.26.2 * @see #EXPR **/ public static final int MINUS_ASSIGN = GeneratedJavaTokenTypes.MINUS_ASSIGN; /** * The *= (multiplication assignment) operator. * * @see Java * Language Specification, §15.26.2 * @see #EXPR **/ public static final int STAR_ASSIGN = GeneratedJavaTokenTypes.STAR_ASSIGN; /** * The /= (division assignment) operator. * * @see Java * Language Specification, §15.26.2 * @see #EXPR **/ public static final int DIV_ASSIGN = GeneratedJavaTokenTypes.DIV_ASSIGN; /** * The %= (remainder assignment) operator. * * @see Java * Language Specification, §15.26.2 * @see #EXPR **/ public static final int MOD_ASSIGN = GeneratedJavaTokenTypes.MOD_ASSIGN; /** * The >>= (signed right shift assignment) * operator. * * @see Java * Language Specification, §15.26.2 * @see #EXPR **/ public static final int SR_ASSIGN = GeneratedJavaTokenTypes.SR_ASSIGN; /** * The >>>= (unsigned right shift assignment) * operator. * * @see Java * Language Specification, §15.26.2 * @see #EXPR **/ public static final int BSR_ASSIGN = GeneratedJavaTokenTypes.BSR_ASSIGN; /** * The <<= (left shift assignment) operator. * * @see Java * Language Specification, §15.26.2 * @see #EXPR **/ public static final int SL_ASSIGN = GeneratedJavaTokenTypes.SL_ASSIGN; /** * The &= (bitwise AND assignment) operator. * * @see Java * Language Specification, §15.26.2 * @see #EXPR **/ public static final int BAND_ASSIGN = GeneratedJavaTokenTypes.BAND_ASSIGN; /** * The ^= (bitwise exclusive OR assignment) operator. * * @see Java * Language Specification, §15.26.2 * @see #EXPR **/ public static final int BXOR_ASSIGN = GeneratedJavaTokenTypes.BXOR_ASSIGN; /** * The |= (bitwise OR assignment) operator. * * @see Java * Language Specification, §15.26.2 * @see #EXPR **/ public static final int BOR_ASSIGN = GeneratedJavaTokenTypes.BOR_ASSIGN; /** * The ? (conditional) operator. Technically, * the colon is also part of this operator, but it appears as a * separate token. * *

For example:

*
     * (quantity == 1) ? "": "s"
     * 
*

*

parses as:

*

*
     * +--QUESTION (?)
     *     |
     *     +--LPAREN (()
     *     +--EQUAL (==)
     *         |
     *         +--IDENT (quantity)
     *         +--NUM_INT (1)
     *     +--RPAREN ())
     *     +--STRING_LITERAL ("")
     *     +--COLON (:)
     *     +--STRING_LITERAL ("s")
     * 
* * @see Java * Language Specification, §15.25 * @see #EXPR * @see #COLON **/ public static final int QUESTION = GeneratedJavaTokenTypes.QUESTION; /** * The || (conditional OR) operator. * * @see Java * Language Specification, §15.24 * @see #EXPR **/ public static final int LOR = GeneratedJavaTokenTypes.LOR; /** * The && (conditional AND) operator. * * @see Java * Language Specification, §15.23 * @see #EXPR **/ public static final int LAND = GeneratedJavaTokenTypes.LAND; /** * The | (bitwise OR) operator. * * @see Java * Language Specification, §15.22.1 * @see #EXPR **/ public static final int BOR = GeneratedJavaTokenTypes.BOR; /** * The ^ (bitwise exclusive OR) operator. * * @see Java * Language Specification, §15.22.1 * @see #EXPR **/ public static final int BXOR = GeneratedJavaTokenTypes.BXOR; /** * The & (bitwise AND) operator. * * @see Java * Language Specification, §15.22.1 * @see #EXPR **/ public static final int BAND = GeneratedJavaTokenTypes.BAND; /** * The != (not equal) operator. * * @see #EXPR **/ public static final int NOT_EQUAL = GeneratedJavaTokenTypes.NOT_EQUAL; /** * The == (equal) operator. * * @see #EXPR **/ public static final int EQUAL = GeneratedJavaTokenTypes.EQUAL; /** * The < (less than) operator. * * @see #EXPR **/ public static final int LT = GeneratedJavaTokenTypes.LT; /** * The > (greater than) operator. * * @see #EXPR **/ public static final int GT = GeneratedJavaTokenTypes.GT; /** * The <= (less than or equal) operator. * * @see #EXPR **/ public static final int LE = GeneratedJavaTokenTypes.LE; /** * The >= (greater than or equal) operator. * * @see #EXPR **/ public static final int GE = GeneratedJavaTokenTypes.GE; /** * The instanceof operator. The first child is an * object reference or something that evaluates to an object * reference. The second child is a reference type. * * @see Java * Language Specification, §15.20.2 * @see #EXPR * @see #METHOD_CALL * @see #IDENT * @see #DOT * @see #TYPE * @see FullIdent **/ public static final int LITERAL_INSTANCEOF = GeneratedJavaTokenTypes.LITERAL_instanceof; /** * The << (shift left) operator. * * @see Java * Language Specification, §15.19 * @see #EXPR **/ public static final int SL = GeneratedJavaTokenTypes.SL; /** * The >> (signed shift right) operator. * * @see Java * Language Specification, §15.19 * @see #EXPR **/ public static final int SR = GeneratedJavaTokenTypes.SR; /** * The >>> (unsigned shift right) operator. * * @see Java * Language Specification, §15.19 * @see #EXPR **/ public static final int BSR = GeneratedJavaTokenTypes.BSR; /** * The + (addition) operator. * * @see Java * Language Specification, §15.18 * @see #EXPR **/ public static final int PLUS = GeneratedJavaTokenTypes.PLUS; /** * The - (subtraction) operator. * * @see Java * Language Specification, §15.18 * @see #EXPR **/ public static final int MINUS = GeneratedJavaTokenTypes.MINUS; /** * The / (division) operator. * * @see Java * Language Specification, §15.17.2 * @see #EXPR **/ public static final int DIV = GeneratedJavaTokenTypes.DIV; /** * The % (remainder) operator. * * @see Java * Language Specification, §15.17.3 * @see #EXPR **/ public static final int MOD = GeneratedJavaTokenTypes.MOD; /** * The ++ (prefix increment) operator. * * @see Java * Language Specification, §15.15.1 * @see #EXPR * @see #POST_INC **/ public static final int INC = GeneratedJavaTokenTypes.INC; /** * The -- (prefix decrement) operator. * * @see Java * Language Specification, §15.15.2 * @see #EXPR * @see #POST_DEC **/ public static final int DEC = GeneratedJavaTokenTypes.DEC; /** * The ~ (bitwise complement) operator. * * @see Java * Language Specification, §15.15.5 * @see #EXPR **/ public static final int BNOT = GeneratedJavaTokenTypes.BNOT; /** * The ! (logical complement) operator. * * @see Java * Language Specification, §15.15.6 * @see #EXPR **/ public static final int LNOT = GeneratedJavaTokenTypes.LNOT; /** * The true keyword. * * @see Java * Language Specification, §3.10.3 * @see #EXPR * @see #LITERAL_FALSE **/ public static final int LITERAL_TRUE = GeneratedJavaTokenTypes.LITERAL_true; /** * The false keyword. * * @see Java * Language Specification, §3.10.3 * @see #EXPR * @see #LITERAL_TRUE **/ public static final int LITERAL_FALSE = GeneratedJavaTokenTypes.LITERAL_false; /** * The null keyword. * * @see Java * Language Specification, §3.10.7 * @see #EXPR **/ public static final int LITERAL_NULL = GeneratedJavaTokenTypes.LITERAL_null; /** * The new keyword. This element is used to define * new instances of objects, new arrays, and new anonymous inner * classes. * *

For example:

* *
     * new ArrayList(50)
     * 
* *

parses as:

*
     * +--LITERAL_NEW (new)
     *     |
     *     +--IDENT (ArrayList)
     *     +--LPAREN (()
     *     +--ELIST
     *         |
     *         +--EXPR
     *             |
     *             +--NUM_INT (50)
     *     +--RPAREN ())
     * 
* *

For example:

*
     * new float[]
     *   {
     *     3.0f,
     *     4.0f
     *   };
     * 
* *

parses as:

*
     * +--LITERAL_NEW (new)
     *     |
     *     +--LITERAL_FLOAT (float)
     *     +--ARRAY_DECLARATOR ([)
     *     +--ARRAY_INIT ({)
     *         |
     *         +--EXPR
     *             |
     *             +--NUM_FLOAT (3.0f)
     *         +--COMMA (,)
     *         +--EXPR
     *             |
     *             +--NUM_FLOAT (4.0f)
     *         +--RCURLY (})
     * 
* *

For example:

*
     * new FilenameFilter()
     * {
     *   public boolean accept(File dir, String name)
     *   {
     *     return name.endsWith(".java");
     *   }
     * }
     * 
* *

parses as:

*
     * +--LITERAL_NEW (new)
     *     |
     *     +--IDENT (FilenameFilter)
     *     +--LPAREN (()
     *     +--ELIST
     *     +--RPAREN ())
     *     +--OBJBLOCK
     *         |
     *         +--LCURLY ({)
     *         +--METHOD_DEF
     *             |
     *             +--MODIFIERS
     *                 |
     *                 +--LITERAL_PUBLIC (public)
     *             +--TYPE
     *                 |
     *                 +--LITERAL_BOOLEAN (boolean)
     *             +--IDENT (accept)
     *             +--PARAMETERS
     *                 |
     *                 +--PARAMETER_DEF
     *                     |
     *                     +--MODIFIERS
     *                     +--TYPE
     *                         |
     *                         +--IDENT (File)
     *                     +--IDENT (dir)
     *                 +--COMMA (,)
     *                 +--PARAMETER_DEF
     *                     |
     *                     +--MODIFIERS
     *                     +--TYPE
     *                         |
     *                         +--IDENT (String)
     *                     +--IDENT (name)
     *             +--SLIST ({)
     *                 |
     *                 +--LITERAL_RETURN (return)
     *                     |
     *                     +--EXPR
     *                         |
     *                         +--METHOD_CALL (()
     *                             |
     *                             +--DOT (.)
     *                                 |
     *                                 +--IDENT (name)
     *                                 +--IDENT (endsWith)
     *                             +--ELIST
     *                                 |
     *                                 +--EXPR
     *                                     |
     *                                     +--STRING_LITERAL (".java")
     *                             +--RPAREN ())
     *                     +--SEMI (;)
     *                 +--RCURLY (})
     *         +--RCURLY (})
     * 
* * @see #IDENT * @see #DOT * @see #LPAREN * @see #ELIST * @see #RPAREN * @see #OBJBLOCK * @see #ARRAY_INIT * @see FullIdent **/ public static final int LITERAL_NEW = GeneratedJavaTokenTypes.LITERAL_new; /** * An integer literal. These may be specified in decimal, * hexadecimal, or octal form. * * @see Java * Language Specification, §3.10.1 * @see #EXPR * @see #NUM_LONG **/ public static final int NUM_INT = GeneratedJavaTokenTypes.NUM_INT; /** * A character literal. This is a (possibly escaped) character * enclosed in single quotes. * * @see Java * Language Specification, §3.10.4 * @see #EXPR **/ public static final int CHAR_LITERAL = GeneratedJavaTokenTypes.CHAR_LITERAL; /** * A string literal. This is a sequence of (possibly escaped) * characters enclosed in double quotes. * * @see Java * Language Specification, §3.10.5 * @see #EXPR **/ public static final int STRING_LITERAL = GeneratedJavaTokenTypes.STRING_LITERAL; /** * A single precision floating point literal. This is a floating * point number with an F or f suffix. * * @see Java * Language Specification, §3.10.2 * @see #EXPR * @see #NUM_DOUBLE **/ public static final int NUM_FLOAT = GeneratedJavaTokenTypes.NUM_FLOAT; /** * A long integer literal. These are almost the same as integer * literals, but they have an L or l * (ell) suffix. * * @see Java * Language Specification, §3.10.1 * @see #EXPR * @see #NUM_INT **/ public static final int NUM_LONG = GeneratedJavaTokenTypes.NUM_LONG; /** * A double precision floating point literal. This is a floating * point number with an optional D or d * suffix. * * @see Java * Language Specification, §3.10.2 * @see #EXPR * @see #NUM_FLOAT **/ public static final int NUM_DOUBLE = GeneratedJavaTokenTypes.NUM_DOUBLE; /* * * This token does not appear in the tree. * * @see Java * Language Specification, §3.6 * @see FileContents **/ //public static final int WS = GeneratedJavaTokenTypes.WS; /* * * This token does not appear in the tree. * * @see Java * Language Specification, §3.7 * @see FileContents **/ //public static final int SL_COMMENT = GeneratedJavaTokenTypes.SL_COMMENT; /* * * This token does not appear in the tree. * * @see Java * Language Specification, §3.7 * @see FileContents **/ //public static final int ML_COMMENT = GeneratedJavaTokenTypes.ML_COMMENT; /* * * This token does not appear in the tree. * * @see Java * Language Specification, §3.10.6 * @see #CHAR_LITERAL * @see #STRING_LITERAL **/ //public static final int ESC = GeneratedJavaTokenTypes.ESC; /* * * This token does not appear in the tree. * * @see #NUM_INT * @see #NUM_LONG **/ //public static final int HEX_DIGIT = GeneratedJavaTokenTypes.HEX_DIGIT; /* * * This token does not appear in the tree. * * @see #NUM_FLOAT * @see #NUM_DOUBLE **/ //public static final int EXPONENT = GeneratedJavaTokenTypes.EXPONENT; /* * * This token does not appear in the tree. * * @see #NUM_FLOAT * @see #NUM_DOUBLE **/ // public static final int FLOAT_SUFFIX = // GeneratedJavaTokenTypes.FLOAT_SUFFIX; /** * The assert keyword. This is only for Java 1.4 and * later. * *

For example:

*
     * assert(x==4);
     * 
*

parses as:

*
     * +--LITERAL_ASSERT (assert)
     *     |
     *     +--EXPR
     *         |
     *         +--LPAREN (()
     *         +--EQUAL (==)
     *             |
     *             +--IDENT (x)
     *             +--NUM_INT (4)
     *         +--RPAREN ())
     *     +--SEMI (;)
     * 
**/ public static final int LITERAL_ASSERT = GeneratedJavaTokenTypes.ASSERT; /** * A static import declaration. Static import declarations are optional, * but must appear after the package declaration and before the type * declaration. * *

For example:

* *
     *   import static java.io.IOException;
     * 
* *

parses as:

* *
     * +--STATIC_IMPORT (import)
     *     |
     *     +--LITERAL_STATIC
     *     +--DOT (.)
     *         |
     *         +--DOT (.)
     *             |
     *             +--IDENT (java)
     *             +--IDENT (io)
     *         +--IDENT (IOException)
     *     +--SEMI (;)
     * 
* * @see * JSR201 * @see #LITERAL_STATIC * @see #DOT * @see #IDENT * @see #STAR * @see #SEMI * @see FullIdent **/ public static final int STATIC_IMPORT = GeneratedJavaTokenTypes.STATIC_IMPORT; /** * An enum declaration. Its notable children are * enum constant declarations followed by * any construct that may be expected in a class body. * *

For example:

*
     * public enum MyEnum
     *   implements Serializable
     * {
     *     FIRST_CONSTANT,
     *     SECOND_CONSTANT;
     *
     *     public void someMethod()
     *     {
     *     }
     * }
     * 
*

parses as:

*
     * +--ENUM_DEF
     *     |
     *     +--MODIFIERS
     *         |
     *         +--LITERAL_PUBLIC (public)
     *     +--ENUM (enum)
     *     +--IDENT (MyEnum)
     *     +--EXTENDS_CLAUSE
     *     +--IMPLEMENTS_CLAUSE
     *         |
     *         +--IDENT (Serializable)
     *     +--OBJBLOCK
     *         |
     *         +--LCURLY ({)
     *         +--ENUM_CONSTANT_DEF
     *             |
     *             +--IDENT (FIRST_CONSTANT)
     *         +--COMMA (,)
     *         +--ENUM_CONSTANT_DEF
     *             |
     *             +--IDENT (SECOND_CONSTANT)
     *         +--SEMI (;)
     *         +--METHOD_DEF
     *             |
     *             +--MODIFIERS
     *                 |
     *                 +--LITERAL_PUBLIC (public)
     *             +--TYPE
     *                 |
     *                 +--LITERAL_void (void)
     *             +--IDENT (someMethod)
     *             +--LPAREN (()
     *             +--PARAMETERS
     *             +--RPAREN ())
     *             +--SLIST ({)
     *                 |
     *                 +--RCURLY (})
     *         +--RCURLY (})
     * 
* * @see * JSR201 * @see #MODIFIERS * @see #ENUM * @see #IDENT * @see #EXTENDS_CLAUSE * @see #IMPLEMENTS_CLAUSE * @see #OBJBLOCK * @see #LITERAL_NEW * @see #ENUM_CONSTANT_DEF **/ public static final int ENUM_DEF = GeneratedJavaTokenTypes.ENUM_DEF; /** * The enum keyword. This element appears * as part of an enum declaration. **/ public static final int ENUM = GeneratedJavaTokenTypes.ENUM; /** * An enum constant declaration. Its notable children are annotations, * arguments and object block akin to an annonymous * inner class' body. * *

For example:

*
     * SOME_CONSTANT(1)
     * {
     *     public void someMethodOverridenFromMainBody()
     *     {
     *     }
     * }
     * 
*

parses as:

*
     * +--ENUM_CONSTANT_DEF
     *     |
     *     +--ANNOTATIONS
     *     +--IDENT (SOME_CONSTANT)
     *     +--LPAREN (()
     *     +--ELIST
     *         |
     *         +--EXPR
     *             |
     *             +--NUM_INT (1)
     *     +--RPAREN ())
     *     +--OBJBLOCK
     *         |
     *         +--LCURLY ({)
     *         |
     *         +--METHOD_DEF
     *             |
     *             +--MODIFIERS
     *                 |
     *                 +--LITERAL_PUBLIC (public)
     *             +--TYPE
     *                 |
     *                 +--LITERAL_void (void)
     *             +--IDENT (someMethodOverridenFromMainBody)
     *             +--LPAREN (()
     *             +--PARAMETERS
     *             +--RPAREN ())
     *             +--SLIST ({)
     *                 |
     *                 +--RCURLY (})
     *         +--RCURLY (})
     * 
* * @see * JSR201 * @see #ANNOTATIONS * @see #MODIFIERS * @see #IDENT * @see #ELIST * @see #OBJBLOCK **/ public static final int ENUM_CONSTANT_DEF = GeneratedJavaTokenTypes.ENUM_CONSTANT_DEF; /** * A for-each clause. This is a child of * LITERAL_FOR. The children of this element may be * a parameter definition, the colon literal and an expression. * * @see #VARIABLE_DEF * @see #ELIST * @see #LITERAL_FOR **/ public static final int FOR_EACH_CLAUSE = GeneratedJavaTokenTypes.FOR_EACH_CLAUSE; /** * An annotation declaration. The notable children are the name of the * annotation type, annotation field declarations and (constant) fields. * *

For example:

*
     * public @interface MyAnnotation
     * {
     *     int someValue();
     * }
     * 
*

parses as:

*
     * +--ANNOTATION_DEF
     *     |
     *     +--MODIFIERS
     *         |
     *         +--LITERAL_PUBLIC (public)
     *     +--AT (@)
     *     +--LITERAL_INTERFACE (interface)
     *     +--IDENT (MyAnnotation)
     *     +--OBJBLOCK
     *         |
     *         +--LCURLY ({)
     *         +--ANNOTATION_FIELD_DEF
     *             |
     *             +--MODIFIERS
     *             +--TYPE
     *                 |
     *                 +--LITERAL_INT (int)
     *             +--IDENT (someValue)
     *             +--LPAREN (()
     *             +--RPAREN ())
     *             +--SEMI (;)
     *         +--RCURLY (})
     * 
* * @see * JSR201 * @see #MODIFIERS * @see #LITERAL_INTERFACE * @see #IDENT * @see #OBJBLOCK * @see #ANNOTATION_FIELD_DEF **/ public static final int ANNOTATION_DEF = GeneratedJavaTokenTypes.ANNOTATION_DEF; /** * An annotation field declaration. The notable children are modifiers, * field type, field name and an optional default value (a conditional * compile-time constant expression). Default values may also by * annotations. * *

For example:

* *
     *     String someField() default "Hello world";
     * 
* *

parses as:

* *
     * +--ANNOTATION_FIELD_DEF
     *     |
     *     +--MODIFIERS
     *     +--TYPE
     *         |
     *         +--IDENT (String)
     *     +--IDENT (someField)
     *     +--LPAREN (()
     *     +--RPAREN ())
     *     +--LITERAL_DEFAULT (default)
     *     +--STRING_LITERAL ("Hello world")
     *     +--SEMI (;)
     * 
* * @see * JSR201 * @see #MODIFIERS * @see #TYPE * @see #LITERAL_DEFAULT */ public static final int ANNOTATION_FIELD_DEF = GeneratedJavaTokenTypes.ANNOTATION_FIELD_DEF; // note: @ is the html escape for '@', // used here to avoid confusing the javadoc tool /** * A collection of annotations on a package or enum constant. * A collections of annotations will only occur on these nodes * as all other nodes that may be qualified with an annotation can * be qualified with any other modifier and hence these annotations * would be contained in a {@link #MODIFIERS} node. * *

For example:

* *
     *     @MyAnnotation package blah;
     * 
* *

parses as:

* *
     * +--PACKAGE_DEF (package)
     *     |
     *     +--ANNOTATIONS
     *         |
     *         +--ANNOTATION
     *             |
     *             +--AT (@)
     *             +--IDENT (MyAnnotation)
     *     +--IDENT (blah)
     *     +--SEMI (;)
     * 
* * @see * JSR201 * @see #ANNOTATION * @see #AT * @see #IDENT */ public static final int ANNOTATIONS = GeneratedJavaTokenTypes.ANNOTATIONS; // note: @ is the html escape for '@', // used here to avoid confusing the javadoc tool /** * An annotation of a package, type, field, parameter or variable. * An annotation may occur anywhere modifiers occur (it is a * type of modifier) and may also occur prior to a package definition. * The notable children are: The annotation name and either a single * default annotation value or a sequence of name value pairs. * Annotation values may also be annotations themselves. * *

For example:

* *
     *     @MyAnnotation(someField1 = "Hello",
     *                    someField2 = @SomeOtherAnnotation)
     * 
* *

parses as:

* *
     * +--ANNOTATION
     *     |
     *     +--AT (@)
     *     +--IDENT (MyAnnotation)
     *     +--LPAREN (()
     *     +--ANNOTATION_MEMBER_VALUE_PAIR
     *         |
     *         +--IDENT (someField1)
     *         +--ASSIGN (=)
     *         +--ANNOTATION
     *             |
     *             +--AT (@)
     *             +--IDENT (SomeOtherAnnotation)
     *     +--ANNOTATION_MEMBER_VALUE_PAIR
     *         |
     *         +--IDENT (someField2)
     *         +--ASSIGN (=)
     *         +--STRING_LITERAL ("Hello")
     *     +--RPAREN ())
     * 
* * @see * JSR201 * @see #MODIFIERS * @see #IDENT * @see #ANNOTATION_MEMBER_VALUE_PAIR */ public static final int ANNOTATION = GeneratedJavaTokenTypes.ANNOTATION; /** * An initialisation of an annotation member with a value. * Its children are the name of the member, the assignment literal * and the (compile-time constant conditional expression) value. * * @see * JSR201 * @see #ANNOTATION * @see #IDENT */ public static final int ANNOTATION_MEMBER_VALUE_PAIR = GeneratedJavaTokenTypes.ANNOTATION_MEMBER_VALUE_PAIR; /** * An annotation array member initialisation. * Initializers can not be nested. * Am initializer may be present as a default to a annotation * member, as the single default value to an annotation * (e.g. @Annotation({1,2})) or as the value of an annotation * member value pair. * *

For example:

* *
     *     { 1, 2 }
     * 
* *

parses as:

* *
     * +--ANNOTATION_ARRAY_INIT ({)
     *     |
     *     +--NUM_INT (1)
     *     +--COMMA (,)
     *     +--NUM_INT (2)
     *     +--RCURLY (})
     * 
* * @see * JSR201 * @see #ANNOTATION * @see #IDENT * @see #ANNOTATION_MEMBER_VALUE_PAIR */ public static final int ANNOTATION_ARRAY_INIT = GeneratedJavaTokenTypes.ANNOTATION_ARRAY_INIT; /** * A list of type parameters to a class, interface or * method definition. Children are LT, at least one * TYPE_PARAMETER, zero or more of: a COMMAs followed by a single * TYPE_PARAMETER and a final GT. * *

For example:

* *
     *     public class Blah<A, B>
     *     {
     *     }
     * 
* *

parses as:

* *
     * +--CLASS_DEF ({)
     *     |
     *     +--MODIFIERS
     *         |
     *         +--LITERAL_PUBLIC (public)
     *     +--LITERAL_CLASS (class)
     *     +--IDENT (Blah)
     *     +--TYPE_PARAMETERS
     *         |
     *         +--GENERIC_START (<)
     *         +--TYPE_PARAMETER
     *             |
     *             +--IDENT (A)
     *         +--COMMA (,)
     *         +--TYPE_PARAMETER
     *             |
     *             +--IDENT (B)
     *         +--GENERIC_END (>)
     *     +--OBJBLOCK
     *         |
     *         +--LCURLY ({)
     *     +--NUM_INT (1)
     *     +--COMMA (,)
     *     +--NUM_INT (2)
     *     +--RCURLY (})
     * 
* * @see * JSR14 * @see #GENERIC_START * @see #GENERIC_END * @see #TYPE_PARAMETER * @see #COMMA */ public static final int TYPE_PARAMETERS = GeneratedJavaTokenTypes.TYPE_PARAMETERS; /** * A type parameter to a class, interface or method definition. * Children are the type name and an optional TYPE_UPPER_BOUNDS. * *

For example:

* *
     *     A extends Collection
     * 
* *

parses as:

* *
     * +--TYPE_PARAMETER
     *     |
     *     +--IDENT (A)
     *     +--TYPE_UPPER_BOUNDS
     *         |
     *         +--IDENT (Collection)
     * 
* * @see * JSR14 * @see #IDENT * @see #WILDCARD_TYPE * @see #TYPE_UPPER_BOUNDS */ public static final int TYPE_PARAMETER = GeneratedJavaTokenTypes.TYPE_PARAMETER; /** * A list of type arguments to a type reference or * a method/ctor invocation. Children are GENERIC_START, at least one * TYPE_ARGUMENT, zero or more of a COMMAs followed by a single * TYPE_ARGUMENT, and a final GENERIC_END. * *

For example:

* *
     *     public Collection a;
     * 
* *

parses as:

* *
     * +--VARIABLE_DEF
     *     |
     *     +--MODIFIERS
     *         |
     *         +--LITERAL_PUBLIC (public)
     *     +--TYPE
     *         |
     *         +--IDENT (Collection)
     *             |
     *             +--TYPE_ARGUMENTS
     *                 |
     *                 +--GENERIC_START (<)
     *                 +--TYPE_ARGUMENT
     *                     |
     *                     +--WILDCARD_TYPE (?)
     *                 +--GENERIC_END (>)
     *     +--IDENT (a)
     *     +--SEMI (;)
     * 
* * @see #GENERIC_START * @see #GENERIC_END * @see #TYPE_ARGUMENT * @see #COMMA */ public static final int TYPE_ARGUMENTS = GeneratedJavaTokenTypes.TYPE_ARGUMENTS; /** * A type arguments to a type reference or a method/ctor invocation. * Children are either: type name or wildcard type with possible type * upper or lower bounds. * *

For example:

* *
     *     ? super List
     * 
* *

parses as:

* *
     * +--TYPE_ARGUMENT
     *     |
     *     +--WILDCARD_TYPE (?)
     *     +--TYPE_LOWER_BOUNDS
     *         |
     *         +--IDENT (List)
     * 
* * @see * JSR14 * @see #WILDCARD_TYPE * @see #TYPE_UPPER_BOUNDS * @see #TYPE_LOWER_BOUNDS */ public static final int TYPE_ARGUMENT = GeneratedJavaTokenTypes.TYPE_ARGUMENT; /** * The type that refers to all types. This node has no children. * * @see * JSR14 * @see #TYPE_ARGUMENT * @see #TYPE_UPPER_BOUNDS * @see #TYPE_LOWER_BOUNDS */ public static final int WILDCARD_TYPE = GeneratedJavaTokenTypes.WILDCARD_TYPE; /** * An upper bounds on a wildcard type argument or type parameter. * This node has one child - the type that is being used for * the bounding. * * @see * JSR14 * @see #TYPE_PARAMETER * @see #TYPE_ARGUMENT * @see #WILDCARD_TYPE */ public static final int TYPE_UPPER_BOUNDS = GeneratedJavaTokenTypes.TYPE_UPPER_BOUNDS; /** * A lower bounds on a wildcard type argument. This node has one child * - the type that is being used for the bounding. * * @see * JSR14 * @see #TYPE_ARGUMENT * @see #WILDCARD_TYPE */ public static final int TYPE_LOWER_BOUNDS = GeneratedJavaTokenTypes.TYPE_LOWER_BOUNDS; /** * An 'at' symbol - signifying an annotation instance or the prefix * to the interface literal signifying the definition of an annotation * declaration. * * @see * JSR201 */ public static final int AT = GeneratedJavaTokenTypes.AT; /** * A triple dot for variable-length parameters. This token only ever occurs * in a parameter declaration immediately after the type of the parameter. * * @see * JSR201 */ public static final int ELLIPSIS = GeneratedJavaTokenTypes.ELLIPSIS; /** * '&' symbol when used in a generic upper or lower bounds constrain * e.g. Comparable. */ public static final int TYPE_EXTENSION_AND = GeneratedJavaTokenTypes.TYPE_EXTENSION_AND; /** * '<' symbol signifying the start of type arguments or type parameters. */ public static final int GENERIC_START = GeneratedJavaTokenTypes.GENERIC_START; /** * '>' symbol signifying the end of type arguments or type parameters. */ public static final int GENERIC_END = GeneratedJavaTokenTypes.GENERIC_END; //////////////////////////////////////////////////////////////////////// // The interesting code goes here //////////////////////////////////////////////////////////////////////// /** maps from a token name to value */ private static final ImmutableMap TOKEN_NAME_TO_VALUE; /** maps from a token value to name */ private static final String[] TOKEN_VALUE_TO_NAME; // initialise the constants static { final ImmutableMap.Builder builder = ImmutableMap.builder(); final Field[] fields = TokenTypes.class.getDeclaredFields(); String[] tempTokenValueToName = new String[0]; for (final Field f : fields) { // Only process the int declarations. if (f.getType() != Integer.TYPE) { continue; } final String name = f.getName(); try { final int tokenValue = f.getInt(name); builder.put(name, tokenValue); if (tokenValue > tempTokenValueToName.length - 1) { final String[] temp = new String[tokenValue + 1]; System.arraycopy(tempTokenValueToName, 0, temp, 0, tempTokenValueToName.length); tempTokenValueToName = temp; } tempTokenValueToName[tokenValue] = name; } catch (final IllegalArgumentException e) { e.printStackTrace(); System.exit(1); } catch (final IllegalAccessException e) { e.printStackTrace(); System.exit(1); } } TOKEN_NAME_TO_VALUE = builder.build(); TOKEN_VALUE_TO_NAME = tempTokenValueToName; } /** * Returns the name of a token for a given ID. * @param aID the ID of the token name to get * @return a token name */ public static String getTokenName(int aID) { if (aID > TOKEN_VALUE_TO_NAME.length - 1) { throw new IllegalArgumentException("given id " + aID); } final String name = TOKEN_VALUE_TO_NAME[aID]; if (name == null) { throw new IllegalArgumentException("given id " + aID); } return name; } /** * Returns the ID of a token for a given name. * @param aName the name of the token ID to get * @return a token ID */ public static int getTokenId(String aName) { final Integer id = TOKEN_NAME_TO_VALUE.get(aName); if (id == null) { throw new IllegalArgumentException("given name " + aName); } return id.intValue(); } /** * Returns the short description of a token for a given name. * @param aName the name of the token ID to get * @return a short description */ public static String getShortDescription(String aName) { if (!TOKEN_NAME_TO_VALUE.containsKey(aName)) { throw new IllegalArgumentException("given name " + aName); } final String tokentypes = "com.puppycrawl.tools.checkstyle.api.tokentypes"; final ResourceBundle bundle = ResourceBundle.getBundle(tokentypes); return bundle.getString(aName); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/api/Utils.java100644 0 0 24012 12026051065 24610 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Contains utility methods. * * @author Oliver Burn * @version 1.0 */ public final class Utils { /** Map of all created regular expressions **/ private static final Map CREATED_RES = Maps.newHashMap(); /** Shared instance of logger for exception logging. */ private static final Log EXCEPTION_LOG = LogFactory.getLog("com.puppycrawl.tools.checkstyle.ExceptionLog"); ///CLOVER:OFF /** stop instances being created **/ private Utils() { } ///CLOVER:ON /** * Accessor for shared instance of logger which should be * used to log all exceptions occurred during FileSetCheck * work (debug() should be used). * @return shared exception logger. */ public static Log getExceptionLogger() { return EXCEPTION_LOG; } /** * Returns whether the specified string contains only whitespace up to the * specified index. * * @param aIndex index to check up to * @param aLine the line to check * @return whether there is only whitespace */ public static boolean whitespaceBefore(int aIndex, String aLine) { for (int i = 0; i < aIndex; i++) { if (!Character.isWhitespace(aLine.charAt(i))) { return false; } } return true; } /** * Returns the length of a string ignoring all trailing whitespace. It is a * pity that there is not a trim() like method that only removed the * trailing whitespace. * @param aLine the string to process * @return the length of the string ignoring all trailing whitespace **/ public static int lengthMinusTrailingWhitespace(String aLine) { int len = aLine.length(); for (int i = len - 1; i >= 0; i--) { if (!Character.isWhitespace(aLine.charAt(i))) { break; } len--; } return len; } /** * Returns the length of a String prefix with tabs expanded. * Each tab is counted as the number of characters is takes to * jump to the next tab stop. * @param aString the input String * @param aToIdx index in aString (exclusive) where the calculation stops * @param aTabWidth the distance between tab stop position. * @return the length of aString.substring(0, aToIdx) with tabs expanded. */ public static int lengthExpandedTabs(String aString, int aToIdx, int aTabWidth) { int len = 0; final char[] chars = aString.toCharArray(); for (int idx = 0; idx < aToIdx; idx++) { if (chars[idx] == '\t') { len = (len / aTabWidth + 1) * aTabWidth; } else { len++; } } return len; } /** * This is a factory method to return an Pattern object for the specified * regular expression. It calls {@link #getPattern(String, int)} with the * compile flags defaults to 0. * @return an Pattern object for the supplied pattern * @param aPattern the regular expression pattern * @throws PatternSyntaxException an invalid pattern was supplied **/ public static Pattern getPattern(String aPattern) throws PatternSyntaxException { return getPattern(aPattern, 0); } /** * This is a factory method to return an Pattern object for the specified * regular expression and compile flags. *

* This method is not MT safe, but neither are the returned Pattern objects. * @return an Pattern object for the supplied pattern * @param aPattern the regular expression pattern * @param aCompileFlags the compilation flags * @throws PatternSyntaxException an invalid pattern was supplied **/ public static Pattern getPattern(String aPattern, int aCompileFlags) throws PatternSyntaxException { final String key = aPattern + ":flags-" + aCompileFlags; Pattern retVal = CREATED_RES.get(key); if (retVal == null) { retVal = Pattern.compile(aPattern, aCompileFlags); CREATED_RES.put(key, retVal); } return retVal; } /** * Loads the contents of a file in a String array. * @return the lines in the file * @param aFileName the name of the file to load * @throws IOException error occurred * @deprecated consider using {@link FileText} instead **/ @Deprecated public static String[] getLines(String aFileName) throws IOException { return getLines( aFileName, System.getProperty("file.encoding", "UTF-8")); } /** * Loads the contents of a file in a String array using * the named charset. * @return the lines in the file * @param aFileName the name of the file to load * @param aCharsetName the name of a supported charset * @throws IOException error occurred * @deprecated consider using {@link FileText} instead **/ @Deprecated public static String[] getLines(String aFileName, String aCharsetName) throws IOException { final List lines = Lists.newArrayList(); final FileInputStream fr = new FileInputStream(aFileName); LineNumberReader lnr = null; try { lnr = new LineNumberReader(new InputStreamReader(fr, aCharsetName)); } catch (final UnsupportedEncodingException ex) { final String message = "unsupported charset: " + ex.getMessage(); throw new UnsupportedEncodingException(message); } try { while (true) { final String l = lnr.readLine(); if (l == null) { break; } lines.add(l); } } finally { Utils.closeQuietly(lnr); } return lines.toArray(new String[lines.size()]); } /** * Helper method to create a regular expression. * @param aPattern the pattern to match * @return a created regexp object * @throws ConversionException if unable to create Pattern object. **/ public static Pattern createPattern(String aPattern) throws ConversionException { Pattern retVal = null; try { retVal = getPattern(aPattern); } catch (final PatternSyntaxException e) { throw new ConversionException( "Failed to initialise regexp expression " + aPattern, e); } return retVal; } /** * @return the base class name from a fully qualified name * @param aType the fully qualified name. Cannot be null */ public static String baseClassname(String aType) { final int i = aType.lastIndexOf("."); return (i == -1) ? aType : aType.substring(i + 1); } /** * Create a stripped down version of a filename. * @param aBasedir the prefix to strip off the original filename * @param aFileName the original filename * @return the filename where an initial prefix of basedir is stripped */ public static String getStrippedFileName( final String aBasedir, final String aFileName) { final String stripped; if ((aBasedir == null) || !aFileName.startsWith(aBasedir)) { stripped = aFileName; } else { // making the assumption that there is text after basedir final int skipSep = aBasedir.endsWith(File.separator) ? 0 : 1; stripped = aFileName.substring(aBasedir.length() + skipSep); } return stripped; } /** * Closes the supplied {@link Closeable} object ignoring an * {@link IOException} if it is thrown. Honestly, what are you going to * do if you cannot close a file. * @param aShutting the object to be closed. */ public static void closeQuietly(Closeable aShutting) { if (null != aShutting) { try { aShutting.close(); } catch (IOException e) { ; // ignore } } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/Checker.java100644 0 0 50721 12026051077 24314 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AuditListener; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.api.Context; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.FileSetCheck; import com.puppycrawl.tools.checkstyle.api.FileText; import com.puppycrawl.tools.checkstyle.api.Filter; import com.puppycrawl.tools.checkstyle.api.FilterSet; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.MessageDispatcher; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import com.puppycrawl.tools.checkstyle.api.SeverityLevelCounter; import com.puppycrawl.tools.checkstyle.api.Utils; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; /** * This class provides the functionality to check a set of files. * @author Oliver Burn * @author Stephane Bailliez * @author lkuehne */ public class Checker extends AutomaticBean implements MessageDispatcher { /** maintains error count */ private final SeverityLevelCounter mCounter = new SeverityLevelCounter( SeverityLevel.ERROR); /** vector of listeners */ private final List mListeners = Lists.newArrayList(); /** vector of fileset checks */ private final List mFileSetChecks = Lists.newArrayList(); /** class loader to resolve classes with. **/ private ClassLoader mLoader = Thread.currentThread() .getContextClassLoader(); /** the basedir to strip off in filenames */ private String mBasedir; /** locale country to report messages **/ private String mLocaleCountry = Locale.getDefault().getCountry(); /** locale language to report messages **/ private String mLocaleLanguage = Locale.getDefault().getLanguage(); /** The factory for instantiating submodules */ private ModuleFactory mModuleFactory; /** The classloader used for loading Checkstyle module classes. */ private ClassLoader mModuleClassLoader; /** the context of all child components */ private Context mChildContext; /** The audit event filters */ private final FilterSet mFilters = new FilterSet(); /** * The severity level of any violations found by submodules. * The value of this property is passed to submodules via * contextualize(). * * Note: Since the Checker is merely a container for modules * it does not make sense to implement logging functionality * here. Consequently Checker does not extend AbstractViolationReporter, * leading to a bit of duplicated code for severity level setting. */ private SeverityLevel mSeverityLevel = SeverityLevel.ERROR; /** Name of a charset */ private String mCharset = System.getProperty("file.encoding", "UTF-8"); /** * Creates a new Checker instance. * The instance needs to be contextualized and configured. * * @throws CheckstyleException if an error occurs */ public Checker() throws CheckstyleException { addListener(mCounter); } @Override public void finishLocalSetup() throws CheckstyleException { final Locale locale = new Locale(mLocaleLanguage, mLocaleCountry); LocalizedMessage.setLocale(locale); if (mModuleFactory == null) { if (mModuleClassLoader == null) { throw new CheckstyleException( "if no custom moduleFactory is set, " + "moduleClassLoader must be specified"); } final Set packageNames = PackageNamesLoader .getPackageNames(mModuleClassLoader); mModuleFactory = new PackageObjectFactory(packageNames, mModuleClassLoader); } final DefaultContext context = new DefaultContext(); context.add("charset", mCharset); context.add("classLoader", mLoader); context.add("moduleFactory", mModuleFactory); context.add("severity", mSeverityLevel.getName()); context.add("basedir", mBasedir); mChildContext = context; } @Override protected void setupChild(Configuration aChildConf) throws CheckstyleException { final String name = aChildConf.getName(); try { final Object child = mModuleFactory.createModule(name); if (child instanceof AutomaticBean) { final AutomaticBean bean = (AutomaticBean) child; bean.contextualize(mChildContext); bean.configure(aChildConf); } if (child instanceof FileSetCheck) { final FileSetCheck fsc = (FileSetCheck) child; addFileSetCheck(fsc); } else if (child instanceof Filter) { final Filter filter = (Filter) child; addFilter(filter); } else if (child instanceof AuditListener) { final AuditListener listener = (AuditListener) child; addListener(listener); } else { throw new CheckstyleException(name + " is not allowed as a child in Checker"); } } catch (final Exception ex) { // TODO i18n throw new CheckstyleException("cannot initialize module " + name + " - " + ex.getMessage(), ex); } } /** * Adds a FileSetCheck to the list of FileSetChecks * that is executed in process(). * @param aFileSetCheck the additional FileSetCheck */ public void addFileSetCheck(FileSetCheck aFileSetCheck) { aFileSetCheck.setMessageDispatcher(this); mFileSetChecks.add(aFileSetCheck); } /** * Adds a filter to the end of the audit event filter chain. * @param aFilter the additional filter */ public void addFilter(Filter aFilter) { mFilters.addFilter(aFilter); } /** * Removes filter. * @param aFilter filter to remove. */ public void removeFilter(Filter aFilter) { mFilters.removeFilter(aFilter); } /** Cleans up the object. **/ public void destroy() { mListeners.clear(); mFilters.clear(); } /** * Add the listener that will be used to receive events from the audit. * @param aListener the nosy thing */ public final void addListener(AuditListener aListener) { mListeners.add(aListener); } /** * Removes a given listener. * @param aListener a listener to remove */ public void removeListener(AuditListener aListener) { mListeners.remove(aListener); } /** * Processes a set of files with all FileSetChecks. * Once this is done, it is highly recommended to call for * the destroy method to close and remove the listeners. * @param aFiles the list of files to be audited. * @return the total number of errors found * @see #destroy() */ public int process(List aFiles) { // Prepare to start fireAuditStarted(); for (final FileSetCheck fsc : mFileSetChecks) { fsc.beginProcessing(mCharset); } // Process each file for (final File f : aFiles) { final String fileName = f.getAbsolutePath(); fireFileStarted(fileName); final TreeSet fileMessages = Sets.newTreeSet(); try { final FileText theText = new FileText(f.getAbsoluteFile(), mCharset); for (final FileSetCheck fsc : mFileSetChecks) { fileMessages.addAll(fsc.process(f, theText)); } } catch (final FileNotFoundException fnfe) { Utils.getExceptionLogger().debug( "FileNotFoundException occured.", fnfe); fileMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE, "general.fileNotFound", null, null, this.getClass(), null)); } catch (final IOException ioe) { Utils.getExceptionLogger().debug("IOException occured.", ioe); fileMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE, "general.exception", new String[] {ioe.getMessage()}, null, this.getClass(), null)); } fireErrors(fileName, fileMessages); fireFileFinished(fileName); } // Finish up for (final FileSetCheck fsc : mFileSetChecks) { // They may also log!!! fsc.finishProcessing(); fsc.destroy(); } final int errorCount = mCounter.getCount(); fireAuditFinished(); return errorCount; } /** * Create a stripped down version of a filename. * @param aFileName the original filename * @return the filename where an initial prefix of basedir is stripped */ private String getStrippedFileName(final String aFileName) { return Utils.getStrippedFileName(mBasedir, aFileName); } /** @param aBasedir the base directory to strip off in filenames */ public void setBasedir(String aBasedir) { // we use getAbsolutePath() instead of getCanonicalPath() // because normalize() removes all . and .. so path // will be canonical by default. mBasedir = normalize(aBasedir); } /** * "normalize" the given absolute path. * *

This includes: *

    *
  • Uppercase the drive letter if there is one.
  • *
  • Remove redundant slashes after the drive spec.
  • *
  • resolve all ./, .\, ../ and ..\ sequences.
  • *
  • DOS style paths that start with a drive letter will have * \ as the separator.
  • *
* * @param aPath a path for "normalizing" * @return "normalized" file name * @throws java.lang.NullPointerException if the file path is * equal to null. */ public String normalize(String aPath) { final String osName = System.getProperty("os.name").toLowerCase( Locale.US); final boolean onNetWare = (osName.indexOf("netware") > -1); String path = aPath.replace('/', File.separatorChar).replace('\\', File.separatorChar); // make sure we are dealing with an absolute path final int colon = path.indexOf(":"); if (!onNetWare) { if (!path.startsWith(File.separator) && !((path.length() >= 2) && Character.isLetter(path.charAt(0)) && (colon == 1))) { final String msg = path + " is not an absolute path"; throw new IllegalArgumentException(msg); } } else { if (!path.startsWith(File.separator) && (colon == -1)) { final String msg = path + " is not an absolute path"; throw new IllegalArgumentException(msg); } } boolean dosWithDrive = false; String root = null; // Eliminate consecutive slashes after the drive spec if ((!onNetWare && (path.length() >= 2) && Character.isLetter(path.charAt(0)) && (path.charAt(1) == ':')) || (onNetWare && (colon > -1))) { dosWithDrive = true; final char[] ca = path.replace('/', '\\').toCharArray(); final StringBuffer sbRoot = new StringBuffer(); for (int i = 0; i < colon; i++) { sbRoot.append(Character.toUpperCase(ca[i])); } sbRoot.append(':'); if (colon + 1 < path.length()) { sbRoot.append(File.separatorChar); } root = sbRoot.toString(); // Eliminate consecutive slashes after the drive spec final StringBuffer sbPath = new StringBuffer(); for (int i = colon + 1; i < ca.length; i++) { if ((ca[i] != '\\') || ((ca[i] == '\\') && (ca[i - 1] != '\\'))) { sbPath.append(ca[i]); } } path = sbPath.toString().replace('\\', File.separatorChar); } else { if (path.length() == 1) { root = File.separator; path = ""; } else if (path.charAt(1) == File.separatorChar) { // UNC drive root = File.separator + File.separator; path = path.substring(2); } else { root = File.separator; path = path.substring(1); } } final FastStack s = FastStack.newInstance(); s.push(root); final StringTokenizer tok = new StringTokenizer(path, File.separator); while (tok.hasMoreTokens()) { final String thisToken = tok.nextToken(); if (".".equals(thisToken)) { continue; } else if ("..".equals(thisToken)) { if (s.size() < 2) { throw new IllegalArgumentException("Cannot resolve path " + aPath); } s.pop(); } else { // plain component s.push(thisToken); } } final StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.size(); i++) { if (i > 1) { // not before the filesystem root and not after it, since root // already contains one sb.append(File.separatorChar); } sb.append(s.peek(i)); } path = sb.toString(); if (dosWithDrive) { path = path.replace('/', '\\'); } return path; } /** @return the base directory property used in unit-test. */ public final String getBasedir() { return mBasedir; } /** notify all listeners about the audit start */ protected void fireAuditStarted() { final AuditEvent evt = new AuditEvent(this); for (final AuditListener listener : mListeners) { listener.auditStarted(evt); } } /** notify all listeners about the audit end */ protected void fireAuditFinished() { final AuditEvent evt = new AuditEvent(this); for (final AuditListener listener : mListeners) { listener.auditFinished(evt); } } /** * Notify all listeners about the beginning of a file audit. * * @param aFileName * the file to be audited */ public void fireFileStarted(String aFileName) { final String stripped = getStrippedFileName(aFileName); final AuditEvent evt = new AuditEvent(this, stripped); for (final AuditListener listener : mListeners) { listener.fileStarted(evt); } } /** * Notify all listeners about the end of a file audit. * * @param aFileName * the audited file */ public void fireFileFinished(String aFileName) { final String stripped = getStrippedFileName(aFileName); final AuditEvent evt = new AuditEvent(this, stripped); for (final AuditListener listener : mListeners) { listener.fileFinished(evt); } } /** * notify all listeners about the errors in a file. * * @param aFileName the audited file * @param aErrors the audit errors from the file */ public void fireErrors(String aFileName, TreeSet aErrors) { final String stripped = getStrippedFileName(aFileName); for (final LocalizedMessage element : aErrors) { final AuditEvent evt = new AuditEvent(this, stripped, element); if (mFilters.accept(evt)) { for (final AuditListener listener : mListeners) { listener.addError(evt); } } } } /** * Sets the factory for creating submodules. * * @param aModuleFactory the factory for creating FileSetChecks */ public void setModuleFactory(ModuleFactory aModuleFactory) { mModuleFactory = aModuleFactory; } /** @param aLocaleCountry the country to report messages **/ public void setLocaleCountry(String aLocaleCountry) { mLocaleCountry = aLocaleCountry; } /** @param aLocaleLanguage the language to report messages **/ public void setLocaleLanguage(String aLocaleLanguage) { mLocaleLanguage = aLocaleLanguage; } /** * Sets the severity level. The string should be one of the names * defined in the SeverityLevel class. * * @param aSeverity The new severity level * @see SeverityLevel */ public final void setSeverity(String aSeverity) { mSeverityLevel = SeverityLevel.getInstance(aSeverity); } /** * Sets the classloader that is used to contextualize filesetchecks. * Some Check implementations will use that classloader to improve the * quality of their reports, e.g. to load a class and then analyze it via * reflection. * @param aLoader the new classloader */ public final void setClassloader(ClassLoader aLoader) { mLoader = aLoader; } /** * Sets the classloader used to load Checkstyle core and custom module * classes when the module tree is being built up. * If no custom ModuleFactory is being set for the Checker module then * this module classloader must be specified. * @param aModuleClassLoader the classloader used to load module classes */ public final void setModuleClassLoader(ClassLoader aModuleClassLoader) { mModuleClassLoader = aModuleClassLoader; } /** * Sets a named charset. * @param aCharset the name of a charset * @throws UnsupportedEncodingException if aCharset is unsupported. */ public void setCharset(String aCharset) throws UnsupportedEncodingException { if (!Charset.isSupported(aCharset)) { final String message = "unsupported charset: '" + aCharset + "'"; throw new UnsupportedEncodingException(message); } mCharset = aCharset; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/AbstractFormatCheck.java100644 0 0 10322 12026051065 30050 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; /** *

Abstract class for checks that verify strings using a * {@link java.util.regex.Pattern regular expression}. It * provides support for setting the regular * expression using the property name format.

* * @author Oliver Burn * @version 1.0 */ public abstract class AbstractFormatCheck extends Check { /** the flags to create the regular expression with */ private int mCompileFlags; /** the regexp to match against */ private Pattern mRegexp; /** the format string of the regexp */ private String mFormat; /** * Creates a new AbstractFormatCheck instance. Defaults the * compile flag to 0 (the default). * @param aDefaultFormat default format * @throws ConversionException unable to parse aDefaultFormat */ public AbstractFormatCheck(String aDefaultFormat) throws ConversionException { this(aDefaultFormat, 0); } /** * Creates a new AbstractFormatCheck instance. * @param aDefaultFormat default format * @param aCompileFlags the Pattern flags to compile the regexp with. * See {@link Pattern#compile(java.lang.String, int)} * @throws ConversionException unable to parse aDefaultFormat */ public AbstractFormatCheck(String aDefaultFormat, int aCompileFlags) throws ConversionException { updateRegexp(aDefaultFormat, aCompileFlags); } /** * Set the format to the specified regular expression. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public final void setFormat(String aFormat) throws ConversionException { updateRegexp(aFormat, mCompileFlags); } /** * Set the compile flags for the regular expression. * @param aCompileFlags the compile flags to use. */ public final void setCompileFlags(int aCompileFlags) { updateRegexp(mFormat, aCompileFlags); } /** @return the regexp to match against */ public final Pattern getRegexp() { return mRegexp; } /** @return the regexp format */ public final String getFormat() { return mFormat; } /** * Updates the regular expression using the supplied format and compiler * flags. Will also update the member variables. * @param aFormat the format of the regular expression. * @param aCompileFlags the compiler flags to use. */ private void updateRegexp(String aFormat, int aCompileFlags) { try { mRegexp = Utils.getPattern(aFormat, aCompileFlags); mFormat = aFormat; mCompileFlags |= aCompileFlags; } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/AbstractOptionCheck.java100644 0 0 5763 12026051065 30065 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import org.apache.commons.beanutils.ConversionException; import com.puppycrawl.tools.checkstyle.api.Check; /** * Abstract class for checks with a parameter named option, where the * option is identified by a {@link Enum}. The logic to convert from a string * representation to the {@link Enum} is to {@link String#trim()} the string * and convert using {@link String#toUpperCase()} and then look up using * {@link Enum#valueOf}. * @param the type of the option. * @author Oliver Burn * @author Rick Giles */ public abstract class AbstractOptionCheck> extends Check { /** Since I cannot get this by going T.class. */ private final Class mOptionClass; /** the policy to enforce */ private T mOption; /** * Creates a new AbstractOptionCheck instance. * @param aDefault the default option. * @param aOptionClass the class for the option. Required due to a quirk * in the Java language. */ public AbstractOptionCheck(T aDefault, Class aOptionClass) { mOption = aDefault; mOptionClass = aOptionClass; } /** * Set the option to enforce. * @param aOption string to decode option from * @throws ConversionException if unable to decode */ public void setOption(String aOption) throws ConversionException { try { mOption = Enum.valueOf(mOptionClass, aOption.trim().toUpperCase()); } catch (IllegalArgumentException iae) { throw new ConversionException("unable to parse " + aOption, iae); } } /** * @return the AbstractOption set */ public T getAbstractOption() { // WARNING!! Do not rename this method to getOption(). It breaks // BeanUtils, which will silently not call setOption. Very annoying! return mOption; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/AbstractTypeAwareCheck.java100644 0 0 46443 12026051064 30535 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.Map; import java.util.Set; /** * Abstract class that endeavours to maintain type information for the Java * file being checked. It provides helper methods for performing type * information functions. * * @author Oliver Burn * @version 1.0 */ public abstract class AbstractTypeAwareCheck extends Check { /** imports details **/ private final Set mImports = Sets.newHashSet(); /** full identifier for package of the method **/ private FullIdent mPackageFullIdent; /** Name of current class. */ private String mCurrentClass; /** ClassResolver instance for current tree. */ private ClassResolver mClassResolver; /** Stack of maps for type params. */ private final FastStack> mTypeParams = FastStack.newInstance(); /** * Whether to log class loading errors to the checkstyle report * instead of throwing a RTE. * * Logging errors will avoid stopping checkstyle completely * because of a typo in javadoc. However, with modern IDEs that * support automated refactoring and generate javadoc this will * occur rarely, so by default we assume a configuration problem * in the checkstyle classpath and throw an execption. * * This configuration option was triggered by bug 1422462. */ private boolean mLogLoadErrors = true; /** * Controls whether to log class loading errors to the checkstyle report * instead of throwing a RTE. * * @param aLogLoadErrors true if errors should be logged */ public final void setLogLoadErrors(boolean aLogLoadErrors) { mLogLoadErrors = aLogLoadErrors; } /** * Whether to show class loading errors in the checkstyle report. * Request ID 1491630 */ private boolean mSuppressLoadErrors; /** * Controls whether to show class loading errors in the checkstyle report. * * @param aSuppressLoadErrors true if errors shouldn't be shown */ public final void setSuppressLoadErrors(boolean aSuppressLoadErrors) { mSuppressLoadErrors = aSuppressLoadErrors; } /** * Called to process an AST when visiting it. * @param aAST the AST to process. Guaranteed to not be PACKAGE_DEF or * IMPORT tokens. */ protected abstract void processAST(DetailAST aAST); @Override public final int[] getRequiredTokens() { return new int[] { TokenTypes.PACKAGE_DEF, TokenTypes.IMPORT, TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF, }; } @Override public void beginTree(DetailAST aRootAST) { mPackageFullIdent = FullIdent.createFullIdent(null); mImports.clear(); // add java.lang.* since it's always imported mImports.add("java.lang.*"); mClassResolver = null; mCurrentClass = ""; mTypeParams.clear(); } @Override public final void visitToken(DetailAST aAST) { if (aAST.getType() == TokenTypes.PACKAGE_DEF) { processPackage(aAST); } else if (aAST.getType() == TokenTypes.IMPORT) { processImport(aAST); } else if ((aAST.getType() == TokenTypes.CLASS_DEF) || (aAST.getType() == TokenTypes.ENUM_DEF)) { processClass(aAST); } else { if (aAST.getType() == TokenTypes.METHOD_DEF) { processTypeParams(aAST); } processAST(aAST); } } @Override public final void leaveToken(DetailAST aAST) { if ((aAST.getType() == TokenTypes.CLASS_DEF) || (aAST.getType() == TokenTypes.ENUM_DEF)) { // perhaps it was inner class int dotIdx = mCurrentClass.lastIndexOf("$"); if (dotIdx == -1) { // perhaps just a class dotIdx = mCurrentClass.lastIndexOf("."); } if (dotIdx == -1) { // looks like a topmost class mCurrentClass = ""; } else { mCurrentClass = mCurrentClass.substring(0, dotIdx); } mTypeParams.pop(); } else if (aAST.getType() == TokenTypes.METHOD_DEF) { mTypeParams.pop(); } else if ((aAST.getType() != TokenTypes.PACKAGE_DEF) && (aAST.getType() != TokenTypes.IMPORT)) { leaveAST(aAST); } } /** * Called when exiting an AST. A no-op by default, extending classes * may choose to override this to augment their processing. * @param aAST the AST we are departing. Guaranteed to not be PACKAGE_DEF, * CLASS_DEF, or IMPORT */ protected void leaveAST(DetailAST aAST) { } /** * Is exception is unchecked (subclass of RuntimeException * or Error * * @param aException Class of exception to check * @return true if exception is unchecked * false if exception is checked */ protected boolean isUnchecked(Class aException) { return isSubclass(aException, RuntimeException.class) || isSubclass(aException, Error.class); } /** * Checks if one class is subclass of another * * @param aChild Class of class * which should be child * @param aParent Class of class * which should be parent * @return true if aChild is subclass of aParent * false otherwise */ protected boolean isSubclass(Class aChild, Class aParent) { return (aParent != null) && (aChild != null) && aParent.isAssignableFrom(aChild); } /** @return ClassResolver for current tree. */ private ClassResolver getClassResolver() { if (mClassResolver == null) { mClassResolver = new ClassResolver(getClassLoader(), mPackageFullIdent.getText(), mImports); } return mClassResolver; } /** * Attempts to resolve the Class for a specified name. * @param aClassName name of the class to resolve * @param aCurrentClass name of surrounding class. * @return the resolved class or null * if unable to resolve the class. */ protected final Class resolveClass(String aClassName, String aCurrentClass) { try { return getClassResolver().resolve(aClassName, aCurrentClass); } catch (final ClassNotFoundException e) { return null; } } /** * Tries to load class. Logs error if unable. * @param aIdent name of class which we try to load. * @param aCurrentClass name of surrounding class. * @return Class for a ident. */ protected final Class tryLoadClass(Token aIdent, String aCurrentClass) { final Class clazz = resolveClass(aIdent.getText(), aCurrentClass); if (clazz == null) { logLoadError(aIdent); } return clazz; } /** * Logs error if unable to load class information. * Abstract, should be overrided in subclasses. * @param aIdent class name for which we can no load class. */ protected abstract void logLoadError(Token aIdent); /** * Common implementation for logLoadError() method. * @param aLineNo line number of the problem. * @param aColumnNo column number of the problem. * @param aMsgKey message key to use. * @param aValues values to fill the message out. */ protected final void logLoadErrorImpl(int aLineNo, int aColumnNo, String aMsgKey, Object... aValues) { if (!mLogLoadErrors) { final LocalizedMessage msg = new LocalizedMessage(aLineNo, aColumnNo, getMessageBundle(), aMsgKey, aValues, getSeverityLevel(), getId(), this.getClass(), null); throw new RuntimeException(msg.getMessage()); } if (!mSuppressLoadErrors) { log(aLineNo, aColumnNo, aMsgKey, aValues); } } /** * Collects the details of a package. * @param aAST node containing the package details */ private void processPackage(DetailAST aAST) { final DetailAST nameAST = aAST.getLastChild().getPreviousSibling(); mPackageFullIdent = FullIdent.createFullIdent(nameAST); } /** * Collects the details of imports. * @param aAST node containing the import details */ private void processImport(DetailAST aAST) { final FullIdent name = FullIdent.createFullIdentBelow(aAST); if (name != null) { mImports.add(name.getText()); } } /** * Process type params (if any) for given class, enum or method. * @param aAST class, enum or method to process. */ private void processTypeParams(DetailAST aAST) { final DetailAST typeParams = aAST.findFirstToken(TokenTypes.TYPE_PARAMETERS); final Map paramsMap = Maps.newHashMap(); mTypeParams.push(paramsMap); if (typeParams == null) { return; } for (DetailAST child = typeParams.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getType() == TokenTypes.TYPE_PARAMETER) { final DetailAST param = child; final String alias = param.findFirstToken(TokenTypes.IDENT).getText(); final DetailAST bounds = param.findFirstToken(TokenTypes.TYPE_UPPER_BOUNDS); if (bounds != null) { final FullIdent name = FullIdent.createFullIdentBelow(bounds); final ClassInfo ci = createClassInfo(new Token(name), getCurrentClassName()); paramsMap.put(alias, ci); } } } } /** * Processes class definition. * @param aAST class definition to process. */ private void processClass(DetailAST aAST) { final DetailAST ident = aAST.findFirstToken(TokenTypes.IDENT); mCurrentClass += ("".equals(mCurrentClass) ? "" : "$") + ident.getText(); processTypeParams(aAST); } /** * Returns current class. * @return name of current class. */ protected final String getCurrentClassName() { return mCurrentClass; } /** * Creates class info for given name. * @param aName name of type. * @param aSurroundingClass name of surrounding class. * @return class infor for given name. */ protected final ClassInfo createClassInfo(final Token aName, final String aSurroundingClass) { final ClassInfo ci = findClassAlias(aName.getText()); if (ci != null) { return new ClassAlias(aName, ci); } return new RegularClass(aName, aSurroundingClass, this); } /** * Looking if a given name is alias. * @param aName given name * @return ClassInfo for alias if it exists, null otherwise */ protected final ClassInfo findClassAlias(final String aName) { ClassInfo ci = null; for (int i = mTypeParams.size() - 1; i >= 0; i--) { final Map paramMap = mTypeParams.peek(i); ci = paramMap.get(aName); if (ci != null) { break; } } return ci; } /** * Contains class's Token. */ protected abstract static class ClassInfo { /** FullIdent associated with this class. */ private final Token mName; /** @return class name */ public final Token getName() { return mName; } /** @return Class associated with an object. */ public abstract Class getClazz(); /** * Creates new instance of class inforamtion object. * @param aName token which represents class name. */ protected ClassInfo(final Token aName) { if (aName == null) { throw new NullPointerException( "ClassInfo's name should be non-null"); } mName = aName; } } /** Represents regular classes/enumes. */ private static final class RegularClass extends ClassInfo { /** name of surrounding class. */ private final String mSurroundingClass; /** is class loadable. */ private boolean mIsLoadable = true; /** Class object of this class if it's loadable. */ private Class mClass; /** the check we use to resolve classes. */ private final AbstractTypeAwareCheck mCheck; /** * Creates new instance of of class information object. * @param aName FullIdent associated with new object. * @param aSurroundingClass name of current surrounding class. * @param aCheck the check we use to load class. */ private RegularClass(final Token aName, final String aSurroundingClass, final AbstractTypeAwareCheck aCheck) { super(aName); mSurroundingClass = aSurroundingClass; mCheck = aCheck; } /** @return if class is loadable ot not. */ private boolean isLoadable() { return mIsLoadable; } @Override public Class getClazz() { if (isLoadable() && (mClass == null)) { setClazz(mCheck.tryLoadClass(getName(), mSurroundingClass)); } return mClass; } /** * Associates Class with an object. * @param aClass Class to associate with. */ private void setClazz(Class aClass) { mClass = aClass; mIsLoadable = (mClass != null); } @Override public String toString() { return "RegularClass[name=" + getName() + ", in class=" + mSurroundingClass + ", loadable=" + mIsLoadable + ", class=" + mClass + "]"; } } /** Represents type param which is "alias" for real type. */ private static class ClassAlias extends ClassInfo { /** Class information associated with the alias. */ private final ClassInfo mClassInfo; /** * Creates nnew instance of the class. * @param aName token which represents name of class alias. * @param aClassInfo class information associated with the alias. */ ClassAlias(final Token aName, ClassInfo aClassInfo) { super(aName); mClassInfo = aClassInfo; } @Override public final Class getClazz() { return mClassInfo.getClazz(); } @Override public String toString() { return "ClassAlias[alias " + getName() + " for " + mClassInfo + "]"; } } /** * Represents text element with location in the text. */ protected static class Token { /** token's column number. */ private final int mColumn; /** token's line number. */ private final int mLine; /** token's text. */ private final String mText; /** * Creates token. * @param aText token's text * @param aLine token's line number * @param aColumn token's column number */ public Token(String aText, int aLine, int aColumn) { mText = aText; mLine = aLine; mColumn = aColumn; } /** * Converts FullIdent to Token. * @param aFullIdent full ident to convert. */ public Token(FullIdent aFullIdent) { mText = aFullIdent.getText(); mLine = aFullIdent.getLineNo(); mColumn = aFullIdent.getColumnNo(); } /** @return line number of the token */ public int getLineNo() { return mLine; } /** @return column number of the token */ public int getColumnNo() { return mColumn; } /** @return text of the token */ public String getText() { return mText; } @Override public String toString() { return "Token[" + getText() + "(" + getLineNo() + "x" + getColumnNo() + ")]"; } } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationUseStyleCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationUseStyleCh100644 0 0 40205 12026051060 31511 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.annotation; import org.apache.commons.beanutils.ConversionException; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * This check controls the style with the usage of annotations. * *

* Annotations have three element styles starting with the least verbose. *

    *
  • {@link ElementStyle#COMPACT_NO_ARRAY COMPACT_NO_ARRAY}
  • *
  • {@link ElementStyle#COMPACT COMPACT}
  • *
  • {@link ElementStyle#EXPANDED EXPANDED}
  • *
* To not enforce an element style * a {@link ElementStyle#IGNORE IGNORE} type is provided. The desired style * can be set through the elementStyle property. *

* *

* Using the EXPANDED style is more verbose. The expanded version * is sometimes referred to as "named parameters" in other languages. *

* *

* Using the COMPACT style is less verbose. This style can only * be used when there is an element called 'value' which is either * the sole element or all other elements have default valuess. *

* *

* Using the COMPACT_NO_ARRAY style is less verbose. It is similar * to the COMPACT style but single value arrays are flagged. With * annotations a single value array does not need to be placed in an * array initializer. This style can only be used when there is an * element called 'value' which is either the sole element or all other * elements have default values. *

* *

* The ending parenthesis are optional when using annotations with no elements. * To always require ending parenthesis use the * {@link ClosingParens#ALWAYS ALWAYS} type. To never have ending parenthesis * use the {@link ClosingParens#NEVER NEVER} type. To not enforce a * closing parenthesis preference a {@link ClosingParens#IGNORE IGNORE} type is * provided. Set this through the closingParens property. *

* *

* Annotations also allow you to specify arrays of elements in a standard * format. As with normal arrays, a trailing comma is optional. To always * require a trailing comma use the {@link TrailingArrayComma#ALWAYS ALWAYS} * type. To never have a trailing comma use the * {@link TrailingArrayComma#NEVER NEVER} type. To not enforce a trailing * array comma preference a {@link TrailingArrayComma#IGNORE IGNORE} type * is provided. Set this through the trailingArrayComma property. *

* *

* By default the ElementStyle is set to EXPANDED, the TrailingArrayComma * is set to NEVER, and the ClosingParans is set to ALWAYS. *

* *

* According to the JLS, it is legal to include a trailing comma * in arrays used in annotations but Sun's Java 5 & 6 compilers will not * compile with this syntax. This may in be a bug in Sun's compilers * since eclipse 3.4's built-in compiler does allow this syntax as * defined in the JLS. Note: this was tested with compilers included with * JDK versions 1.5.0.17 and 1.6.0.11 and the compiler included with eclipse * 3.4.1. * * See * Java Language specification, sections 9.7. *

* *

* An example shown below is set to enforce an EXPANDED style, with a * trailing array comma set to NEVER and always including the closing * parenthesis. *

* *
 * <module name="AnnotationUseStyle">
 *    <property name="ElementStyle"
 *        value="EXPANDED"/>
 *    <property name="TrailingArrayComma"
 *        value="NEVER"/>
 *    <property name="ClosingParens"
 *        value="ALWAYS"/>
 * </module>
 * 
* * @author Travis Schneeberger */ public final class AnnotationUseStyleCheck extends Check { /** * the element name used to receive special linguistic support * for annotation use. */ private static final String ANNOTATION_ELEMENT_SINGLE_NAME = "value"; //not extending AbstractOptionCheck because check //has more than one option type. /** @see #setElementStyle(String) */ private ElementStyle mStyle = ElementStyle.COMPACT_NO_ARRAY; //defaulting to NEVER because of the strange compiler behavior /** @see #setTrailingArrayComma(String) */ private TrailingArrayComma mComma = TrailingArrayComma.NEVER; /** @see #setClosingParans(String) */ private ClosingParens mParens = ClosingParens.NEVER; /** * Sets the ElementStyle from a string. * * @param aStyle string representation * @throws ConversionException if cannot convert string. */ public void setElementStyle(final String aStyle) { this.mStyle = this.getOption(ElementStyle.class, aStyle); } /** * Sets the TrailingArrayComma from a string. * * @param aComma string representation * @throws ConversionException if cannot convert string. */ public void setTrailingArrayComma(final String aComma) { this.mComma = this.getOption(TrailingArrayComma.class, aComma); } /** * Sets the ClosingParens from a string. * * @param aParens string representation * @throws ConversionException if cannot convert string. */ public void setClosingParens(final String aParens) { this.mParens = this.getOption(ClosingParens.class, aParens); } /** * Retrieves an {@link Enum Enum} type from a @{link String String}. * @param the enum type * @param aEnumClass the enum class * @param aString the string representing the enum * @return the enum type */ private > T getOption(final Class aEnumClass, final String aString) { try { return Enum.valueOf(aEnumClass, aString.trim().toUpperCase()); } catch (final IllegalArgumentException iae) { throw new ConversionException("unable to parse " + aString, iae); } } /** {@inheritDoc} */ @Override public int[] getDefaultTokens() { return this.getRequiredTokens(); } /** {@inheritDoc} */ @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.ANNOTATION, }; } /** {@inheritDoc} */ @Override public int[] getAcceptableTokens() { return this.getRequiredTokens(); } /** {@inheritDoc} */ @Override public void visitToken(final DetailAST aAST) { this.checkStyleType(aAST); this.checkCheckClosingParens(aAST); this.checkTrailingComma(aAST); } /** * Checks to see if the * {@link ElementStyle AnnotationElementStyle} * is correct. * * @param aAnnotation the annotation token */ private void checkStyleType(final DetailAST aAnnotation) { if (ElementStyle.IGNORE.equals(this.mStyle) || this.mStyle == null) { return; } if (ElementStyle.COMPACT_NO_ARRAY.equals(this.mStyle)) { this.checkCompactNoArrayStyle(aAnnotation); } else if (ElementStyle.COMPACT.equals(this.mStyle)) { this.checkCompactStyle(aAnnotation); } else if (ElementStyle.EXPANDED.equals(this.mStyle)) { this.checkExpandedStyle(aAnnotation); } } /** * Checks for expanded style type violations. * * @param aAnnotation the annotation token */ private void checkExpandedStyle(final DetailAST aAnnotation) { final int valuePairCount = aAnnotation.getChildCount(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); if (valuePairCount == 0 && aAnnotation.branchContains(TokenTypes.EXPR)) { this.log(aAnnotation.getLineNo(), "annotation.incorrect.style", ElementStyle.EXPANDED); } } /** * Checks for compact style type violations. * * @param aAnnotation the annotation token */ private void checkCompactStyle(final DetailAST aAnnotation) { final int valuePairCount = aAnnotation.getChildCount( TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); final DetailAST valuePair = aAnnotation.findFirstToken( TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); if (valuePairCount == 1 && AnnotationUseStyleCheck.ANNOTATION_ELEMENT_SINGLE_NAME.equals( valuePair.getFirstChild().getText())) { this.log(aAnnotation.getLineNo(), "annotation.incorrect.style", ElementStyle.COMPACT); } } /** * Checks for compact no array style type violations. * * @param aAnnotation the annotation token */ private void checkCompactNoArrayStyle(final DetailAST aAnnotation) { final DetailAST arrayInit = aAnnotation.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT); final int valuePairCount = aAnnotation.getChildCount(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); final DetailAST valuePair = aAnnotation.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); //in compact style with one value if (arrayInit != null && arrayInit.getChildCount(TokenTypes.EXPR) == 1) { this.log(aAnnotation.getLineNo(), "annotation.incorrect.style", ElementStyle.COMPACT_NO_ARRAY); } //in expanded style with one value and the correct element name else if (valuePairCount == 1) { final DetailAST nestedArrayInit = valuePair.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT); if (nestedArrayInit != null && AnnotationUseStyleCheck. ANNOTATION_ELEMENT_SINGLE_NAME.equals( valuePair.getFirstChild().getText()) && nestedArrayInit.getChildCount(TokenTypes.EXPR) == 1) { this.log(aAnnotation.getLineNo(), "annotation.incorrect.style", ElementStyle.COMPACT_NO_ARRAY); } } } /** * Checks to see if the trailing comma is present if required or * prohibited. * * @param aAnnotation the annotation token */ private void checkTrailingComma(final DetailAST aAnnotation) { if (TrailingArrayComma.IGNORE.equals(this.mComma) || this.mComma == null) { return; } DetailAST child = aAnnotation.getFirstChild(); while (child != null) { DetailAST arrayInit = null; if (child.getType() == TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR) { arrayInit = child.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT); } else if (child.getType() == TokenTypes.ANNOTATION_ARRAY_INIT) { arrayInit = child; } if (arrayInit != null) { this.logCommaViolation(arrayInit); } child = child.getNextSibling(); } } /** * logs a trailing array comma violation if one exists. * * @param aAST the array init * {@link TokenTypes#ANNOTATION_ARRAY_INIT ANNOTATION_ARRAY_INIT}. */ private void logCommaViolation(final DetailAST aAST) { final DetailAST rCurly = aAST.findFirstToken(TokenTypes.RCURLY); //comma can be null if array is empty final DetailAST comma = rCurly.getPreviousSibling(); if (TrailingArrayComma.ALWAYS.equals(this.mComma) && (comma == null || comma.getType() != TokenTypes.COMMA)) { this.log(rCurly.getLineNo(), rCurly.getColumnNo(), "annotation.trailing.comma.missing"); } else if (TrailingArrayComma.NEVER.equals(this.mComma) && comma != null && comma.getType() == TokenTypes.COMMA) { this.log(comma.getLineNo(), comma.getColumnNo(), "annotation.trailing.comma.present"); } } /** * Checks to see if the closing parenthesis are present if required or * prohibited. * * @param aAST the annotation token */ private void checkCheckClosingParens(final DetailAST aAST) { if (ClosingParens.IGNORE.equals(this.mParens) || this.mParens == null) { return; } final DetailAST paren = aAST.getLastChild(); final boolean parenExists = paren.getType() == TokenTypes.RPAREN; if (ClosingParens.ALWAYS.equals(this.mParens) && !parenExists) { this.log(aAST.getLineNo(), "annotation.parens.missing"); } else if (ClosingParens.NEVER.equals(this.mParens) && !aAST.branchContains(TokenTypes.EXPR) && parenExists) { this.log(aAST.getLineNo(), "annotation.parens.present"); } } /** * Defines the styles for defining elements in an annotation. * @author Travis Schneeberger */ public static enum ElementStyle { /** * expanded example * *
@SuppressWarnings(value={"unchecked","unused",})
. */ EXPANDED, /** * compact example * *
@SuppressWarnings({"unchecked","unused",})
*
or
*
@SuppressWarnings("unchecked")
. */ COMPACT, /** * compact example.] * *
@SuppressWarnings("unchecked")
. */ COMPACT_NO_ARRAY, /** * mixed styles. */ IGNORE, } /** * Defines the two styles for defining * elements in an annotation. * * @author Travis Schneeberger */ public static enum TrailingArrayComma { /** * with comma example * *
@SuppressWarnings(value={"unchecked","unused",})
. */ ALWAYS, /** * without comma example * *
@SuppressWarnings(value={"unchecked","unused"})
. */ NEVER, /** * mixed styles. */ IGNORE, } /** * Defines the two styles for defining * elements in an annotation. * * @author Travis Schneeberger */ public static enum ClosingParens { /** * with parens example * *
@Deprecated()
. */ ALWAYS, /** * without parens example * *
@Deprecated
. */ NEVER, /** * mixed styles. */ IGNORE, } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/messages.properties100644 0 0 2012 11451071612 31410 0ustar 0 0 annotation.missing.deprecated=Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description. annotation.missing.override=Must include @java.lang.Override annotation when '{'@inheritDoc'}' Javadoc tag exists. annotation.not.valid.on=The annotation {0} is not valid at this location. annotation.incorrect.style=Annotation style must be ''{0}''. annotation.trailing.comma.missing=Annotation array values must contain trailing comma. annotation.trailing.comma.present=Annotation array values cannot contain trailing comma. annotation.parens.missing=Annotation must have closing parenthesis. annotation.parens.present=Annotation cannot have closing parenthesis. annotation.package.location=Package annotations must be in the package-info.java info. suppressed.warning.not.allowed=The warning ''{0}'' cannot be suppressed at this location. javadoc.duplicateTag=Duplicate {0} tag. javadoc.missing=Missing a Javadoc comment. tag.not.valid.on=The Javadoc {0} tag is not valid at this location. ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/messages_de.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/messages_de.properti100644 0 0 2 11451071612 31445 0ustar 0 0 ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/messages_es.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/messages_es.properti100644 0 0 4 11451071612 31466 0ustar 0 0 ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/messages_tr.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/messages_tr.properti100644 0 0 2645 11744664014 31612 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) annotation.incorrect.style = Anotasyon stili \u015Fu \u015Fekilde olmal\u0131: ''{0}''. annotation.missing.deprecated = @java.lang.Deprecated anotasyonu ve @deprecated Javadoc etiketi (a\u00E7\u0131klamas\u0131yla birlikte) birlikte kullan\u0131lmal\u0131. annotation.missing.override = @inheritDoc Javadoc etiketi kullan\u0131ld\u0131\u011F\u0131nda @java.lang.Override anotasyonu da kullan\u0131lmal\u0131. annotation.not.valid.on = {0} anotasyonu bu konumda ge\u00E7erli de\u011Fil. annotation.package.location = Paket anotasyonlar\u0131 package-info.java dosyas\u0131nda tan\u0131mlanmal\u0131. annotation.parens.missing = Anotasyonun kapatma parantezi ('')'') olmal\u0131. annotation.parens.present = Anotasyonun kapatma parantezi ('')'') olmamal\u0131. annotation.trailing.comma.missing = Anotasyonun dizi de\u011Ferlerini takip eden bir virg\u00FCl kullan\u0131lmal\u0131d\u0131r. annotation.trailing.comma.present = Anotasyonun dizi de\u011Ferlerini takip eden bir virg\u00FCl kullan\u0131lmamal\u0131d\u0131r. javadoc.duplicateTag = Tekrarlanm\u0131\u015F {0} etiketi. javadoc.missing = Javadoc a\u00E7\u0131klamas\u0131 eksik. suppressed.warning.not.allowed = ''{0}'' uyar\u0131s\u0131 bu konumda bast\u0131r\u0131lamaz. tag.not.valid.on = {0} Javadoc etiketi bu konumda ge\u00E7ersiz. ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/MissingDeprecatedCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/MissingDeprecatedChe100644 0 0 17771 12026051057 31462 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.annotation; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.puppycrawl.tools.checkstyle.api.AnnotationUtility; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.JavadocTagInfo; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; /** *

* This class is used to verify that both the * {@link java.lang.Deprecated Deprecated} annotation * and the deprecated javadoc tag are present when * either one is present. *

* *

* Both ways of flagging deprecation serve their own purpose. The * {@link java.lang.Deprecated Deprecated} annotation is used for * compilers and development tools. The deprecated javadoc tag is * used to document why something is deprecated and what, if any, * alternatives exist. *

* *

* In order to properly mark something as deprecated both forms of * deprecation should be present. *

* *

* Package deprecation is a exception to the rule of always using the * javadoc tag and annotation to deprecate. Only the package-info.java * file can contain a Deprecated annotation and it CANNOT contain * a deprecated javadoc tag. This is the case with * Sun's javadoc tool released with JDK 1.6.0_11. As a result, this check * does not deal with Deprecated packages in any way. No official * documentation was found confirming this behavior is correct * (of the javadoc tool). *

* *

* To configure this check do the following: *

* *
 * <module name="JavadocDeprecated"/>
 * 
* * @author Travis Schneeberger */ public final class MissingDeprecatedCheck extends Check { /** {@link Deprecated Deprecated} annotation name */ private static final String DEPRECATED = "Deprecated"; /** fully-qualified {@link Deprecated Deprecated} annotation name */ private static final String FQ_DEPRECATED = "java.lang." + DEPRECATED; /** compiled regexp to match Javadoc tag with no argument * */ private static final Pattern MATCH_DEPRECATED = Utils.createPattern("@(deprecated)\\s+\\S"); /** compiled regexp to match first part of multilineJavadoc tags * */ private static final Pattern MATCH_DEPRECATED_MULTILINE_START = Utils.createPattern("@(deprecated)\\s*$"); /** compiled regexp to look for a continuation of the comment * */ private static final Pattern MATCH_DEPRECATED_MULTILINE_CONT = Utils.createPattern("(\\*/|@|[^\\s\\*])"); /** Multiline finished at end of comment * */ private static final String END_JAVADOC = "*/"; /** Multiline finished at next Javadoc * */ private static final String NEXT_TAG = "@"; /** {@inheritDoc} */ @Override public int[] getDefaultTokens() { return this.getAcceptableTokens(); } /** {@inheritDoc} */ @Override public int[] getAcceptableTokens() { return new int[] { TokenTypes.INTERFACE_DEF, TokenTypes.CLASS_DEF, TokenTypes.ANNOTATION_DEF, TokenTypes.ENUM_DEF, TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, TokenTypes.VARIABLE_DEF, TokenTypes.ENUM_CONSTANT_DEF, TokenTypes.ANNOTATION_FIELD_DEF, }; } /** {@inheritDoc} */ @Override public void visitToken(final DetailAST aAST) { final TextBlock javadoc = this.getFileContents().getJavadocBefore(aAST.getLineNo()); final boolean containsAnnotation = AnnotationUtility.containsAnnotation(aAST, DEPRECATED) || AnnotationUtility.containsAnnotation(aAST, FQ_DEPRECATED); final boolean containsJavadocTag = this.containsJavadocTag(javadoc); if (containsAnnotation ^ containsJavadocTag) { this.log(aAST.getLineNo(), "annotation.missing.deprecated"); } } /** * Checks to see if the text block contains a deprecated tag. * * @param aJavadoc the javadoc of the AST * @return true if contains the tag */ private boolean containsJavadocTag(final TextBlock aJavadoc) { if (aJavadoc == null) { return false; } final String[] lines = aJavadoc.getText(); boolean found = false; int currentLine = aJavadoc.getStartLineNo() - 1; for (int i = 0; i < lines.length; i++) { currentLine++; final String line = lines[i]; final Matcher javadocNoargMatcher = MissingDeprecatedCheck.MATCH_DEPRECATED.matcher(line); final Matcher noargMultilineStart = MissingDeprecatedCheck. MATCH_DEPRECATED_MULTILINE_START.matcher(line); if (javadocNoargMatcher.find()) { if (found) { this.log(currentLine, "javadoc.duplicateTag", JavadocTagInfo.DEPRECATED.getText()); } found = true; } else if (noargMultilineStart.find()) { // Look for the rest of the comment if all we saw was // the tag and the name. Stop when we see '*/' (end of // Javadoc), '@' (start of next tag), or anything that's // not whitespace or '*' characters. for (int remIndex = i + 1; remIndex < lines.length; remIndex++) { final Matcher multilineCont = MissingDeprecatedCheck.MATCH_DEPRECATED_MULTILINE_CONT .matcher(lines[remIndex]); if (multilineCont.find()) { remIndex = lines.length; final String lFin = multilineCont.group(1); if (!lFin.equals(MissingDeprecatedCheck.NEXT_TAG) && !lFin.equals(MissingDeprecatedCheck.END_JAVADOC)) { if (found) { this.log(currentLine, "javadoc.duplicateTag", JavadocTagInfo.DEPRECATED.getText()); } found = true; } else { this.log(currentLine, "javadoc.missing"); if (found) { this.log(currentLine, "javadoc.duplicateTag", JavadocTagInfo.DEPRECATED.getText()); } found = true; } } } } } return found; } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/MissingOverrideCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/MissingOverrideCheck100644 0 0 15167 12026051057 31514 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.annotation; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.puppycrawl.tools.checkstyle.api.AnnotationUtility; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.JavadocTagInfo; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; /** *

* This class is used to verify that the {@link java.lang.Override Override} * annotation is present when the inheritDoc javadoc tag is present. *

* *

* Rationale: The {@link java.lang.Override Override} annotation helps * compiler tools ensure that an override is actually occurring. It is * quite easy to accidentally overload a method or hide a static method * and using the {@link java.lang.Override Override} annotation points * out these problems. *

* *

* This check will log a violation if using the inheritDoc tag on a method that * is not valid (ex: private, or static method). *

* *

* There is a slight difference between the Override annotation in Java 5 versus * Java 6 and above. In Java 5, any method overridden from an interface cannot * be annotated with Override. In Java 6 this behavior is allowed. *

* *

* As a result of the aforementioned difference between Java 5 and Java 6, a * property called javaFiveCompatibility is available. This * property will only check classes, interfaces, etc. that do not contain the * extends or implements keyword or are not anonymous classes. This means it * only checks methods overridden from java.lang.Object * * Java 5 Compatibility mode severely limits this check. It is recommended to * only use it on Java 5 source *

* *
 * <module name="MissingOverride">
 *    <property name="javaFiveCompatibility"
 *        value="true"/>
 * </module>
 * 
* * @author Travis Schneeberger */ public final class MissingOverrideCheck extends Check { /** {@link Override Override} annotation name */ private static final String OVERRIDE = "Override"; /** fully-qualified {@link Override Override} annotation name */ private static final String FQ_OVERRIDE = "java.lang." + OVERRIDE; /** compiled regexp to match Javadoc tags with no argument and {} * */ private static final Pattern MATCH_INHERITDOC = Utils.createPattern("\\{\\s*@(inheritDoc)\\s*\\}"); /** @see MissingDeprecatedCheck#setJavaFiveCompatibility(boolean) */ private boolean mJavaFiveCompatibility; /** * Sets Java 5 compatibility mode. * *

* In Java 5, this check could flag code that is not valid for the Override * annotation even though it is a proper override. See the class * documentation for more information. *

* *

* Set this to true to turn on Java 5 compatibility mode. Set this to * false to turn off Java 5 compatibility mode. *

* * @param aCompatibility compatibility or not */ public void setJavaFiveCompatibility(final boolean aCompatibility) { this.mJavaFiveCompatibility = aCompatibility; } /** {@inheritDoc} */ @Override public int[] getDefaultTokens() { return this.getRequiredTokens(); } /** {@inheritDoc} */ @Override public int[] getAcceptableTokens() { return this.getRequiredTokens(); } /** {@inheritDoc} */ @Override public int[] getRequiredTokens() { return new int[] {TokenTypes.METHOD_DEF, }; } /** {@inheritDoc} */ @Override public void visitToken(final DetailAST aAST) { final TextBlock javadoc = this.getFileContents().getJavadocBefore(aAST.getLineNo()); final boolean containsTag = this.containsJavadocTag(javadoc); if (containsTag && !JavadocTagInfo.INHERIT_DOC.isValidOn(aAST)) { this.log(aAST.getLineNo(), "tag.not.valid.on", JavadocTagInfo.INHERIT_DOC.getText()); return; } if (this.mJavaFiveCompatibility) { final DetailAST defOrNew = aAST.getParent().getParent(); if (defOrNew.branchContains(TokenTypes.EXTENDS_CLAUSE) || defOrNew.branchContains(TokenTypes.IMPLEMENTS_CLAUSE) || defOrNew.getType() == TokenTypes.LITERAL_NEW) { return; } } if (containsTag && (!AnnotationUtility.containsAnnotation(aAST, OVERRIDE) && !AnnotationUtility.containsAnnotation(aAST, FQ_OVERRIDE))) { this.log(aAST.getLineNo(), "annotation.missing.override"); } } /** * Checks to see if the text block contains a inheritDoc tag. * * @param aJavadoc the javadoc of the AST * @return true if contains the tag */ private boolean containsJavadocTag(final TextBlock aJavadoc) { if (aJavadoc == null) { return false; } final String[] lines = aJavadoc.getText(); for (final String line : lines) { final Matcher matchInheritDoc = MissingOverrideCheck.MATCH_INHERITDOC.matcher(line); if (matchInheritDoc.find()) { return true; } } return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/package-info.java100644 0 0 2307 12026051057 30661 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the Annotation checks that are * bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks.annotation; ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/PackageAnnotationCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/PackageAnnotationChe100644 0 0 5445 12026051057 31431 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.annotation; import com.puppycrawl.tools.checkstyle.api.AnnotationUtility; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * This check makes sure that all package annotations are in the * package-info.java file. * *

* According to the Java JLS 3rd ed. *

* *

* The JLS does not enforce the placement of package annotations. * This placement may vary based on implementation. The JLS * does highly recommend that all package annotations are * placed in the package-info.java file. * * See * Java Language specification, sections 7.4.1.1. *

* @author Travis Schneeberger */ public class PackageAnnotationCheck extends Check { /** {@inheritDoc} */ @Override public int[] getDefaultTokens() { return this.getRequiredTokens(); } /** {@inheritDoc} */ @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.PACKAGE_DEF, }; } /** {@inheritDoc} */ @Override public int[] getAcceptableTokens() { return this.getRequiredTokens(); } /** {@inheritDoc} */ @Override public void visitToken(final DetailAST aAST) { final boolean containsAnnotation = AnnotationUtility.containsAnnotation(aAST); final boolean inPackageInfo = this.getFileContents().inPackageInfo(); if (containsAnnotation && !inPackageInfo) { this.log(aAST.getLine(), "annotation.package.location"); } } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/SuppressWarningsCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/annotation/SuppressWarningsChec100644 0 0 25025 12026051057 31557 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.annotation; import java.util.regex.Matcher; import com.puppycrawl.tools.checkstyle.api.AnnotationUtility; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck; /** *

* This check allows you to specify what warnings that * {@link SuppressWarnings SuppressWarnings} is not * allowed to suppress. You can also specify a list * of TokenTypes that the configured warning(s) cannot * be suppressed on. *

* *

* The {@link AbstractFormatCheck#setFormat warnings} property is a * regex pattern. Any warning being suppressed matching * this pattern will be flagged. *

* *

* By default, any warning specified will be disallowed on * all legal TokenTypes unless otherwise specified via * the * {@link com.puppycrawl.tools.checkstyle.api.Check#setTokens(String[]) tokens} * property. * * Also, by default warnings that are empty strings or all * whitespace (regex: ^$|^\s+$) are flagged. By specifying, * the format property these defaults no longer apply. *

* *

* Limitations: This check does not consider conditionals * inside the SuppressWarnings annotation.
* For example: * {@code @SupressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused")} * According to the above example, the "unused" warning is being suppressed * not the "unchecked" or "foo" warnings. All of these warnings will be * considered and matched against regardless of what the conditional * evaluates to. *

* *

* This check can be configured so that the "unchecked" * and "unused" warnings cannot be suppressed on * anything but variable and parameter declarations. * See below of an example. *

* *
 * <module name="SuppressWarnings">
 *    <property name="format"
 *        value="^unchecked$|^unused$"/>
 *    <property name="tokens"
 *        value="
 *        CLASS_DEF,INTERFACE_DEF,ENUM_DEF,
 *        ANNOTATION_DEF,ANNOTATION_FIELD_DEF,
 *        ENUM_CONSTANT_DEF,METHOD_DEF,CTOR_DEF
 *        "/>
 * </module>
 * 
* @author Travis Schneeberger */ public class SuppressWarningsCheck extends AbstractFormatCheck { /** {@link SuppressWarnings SuppressWarnings} annotation name */ private static final String SUPPRESS_WARNINGS = "SuppressWarnings"; /** * fully-qualified {@link SuppressWarnings SuppressWarnings} * annotation name */ private static final String FQ_SUPPRESS_WARNINGS = "java.lang." + SUPPRESS_WARNINGS; /** * Ctor that specifies the default for the format property * as specified in the class javadocs. */ public SuppressWarningsCheck() { super("^$|^\\s+$"); } /** {@inheritDoc} */ @Override public final int[] getDefaultTokens() { return this.getAcceptableTokens(); } /** {@inheritDoc} */ @Override public final int[] getAcceptableTokens() { return new int[] { TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.ENUM_DEF, TokenTypes.ANNOTATION_DEF, TokenTypes.ANNOTATION_FIELD_DEF, TokenTypes.ENUM_CONSTANT_DEF, TokenTypes.PARAMETER_DEF, TokenTypes.VARIABLE_DEF, TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, }; } /** {@inheritDoc} */ @Override public void visitToken(final DetailAST aAST) { final DetailAST annotation = this.getSuppressWarnings(aAST); if (annotation == null) { return; } final DetailAST warningHolder = this.findWarningsHolder(annotation); DetailAST warning = warningHolder.findFirstToken(TokenTypes.EXPR); //rare case with empty array ex: @SuppressWarnings({}) if (warning == null) { //check to see if empty warnings are forbidden -- are by default this.logMatch(warningHolder.getLineNo(), warningHolder.getColumnNo(), ""); return; } while (warning != null) { if (warning.getType() == TokenTypes.EXPR) { final DetailAST fChild = warning.getFirstChild(); //typical case if (fChild.getType() == TokenTypes.STRING_LITERAL) { final String warningText = this.removeQuotes(warning.getFirstChild().getText()); this.logMatch(warning.getLineNo(), warning.getColumnNo(), warningText); //conditional case //ex: @SupressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused") } else if (fChild.getType() == TokenTypes.QUESTION) { this.walkConditional(fChild); } else { assert false : "Should never get here, type: " + fChild.getType() + " text: " + fChild.getText(); } } warning = warning.getNextSibling(); } } /** * Gets the {@link SuppressWarnings SuppressWarnings} annotation * that is annotating the AST. If the annotation does not exist * this method will return {@code null}. * * @param aAST the AST * @return the {@link SuppressWarnings SuppressWarnings} annotation */ private DetailAST getSuppressWarnings(DetailAST aAST) { final DetailAST annotation = AnnotationUtility.getAnnotation( aAST, SuppressWarningsCheck.SUPPRESS_WARNINGS); return (annotation != null) ? annotation : AnnotationUtility.getAnnotation( aAST, SuppressWarningsCheck.FQ_SUPPRESS_WARNINGS); } /** * This method looks for a warning that matches a configured expression. * If found it logs a violation at the given line and column number. * * @param aLineNo the line number * @param aColNum the column number * @param aWarningText the warning. */ private void logMatch(final int aLineNo, final int aColNum, final String aWarningText) { final Matcher matcher = this.getRegexp().matcher(aWarningText); if (matcher.matches()) { this.log(aLineNo, aColNum, "suppressed.warning.not.allowed", aWarningText); } } /** * Find the parent (holder) of the of the warnings (Expr). * * @param aAnnotation the annotation * @return a Token representing the expr. */ private DetailAST findWarningsHolder(final DetailAST aAnnotation) { final DetailAST annValuePair = aAnnotation.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); final DetailAST annArrayInit; if (annValuePair != null) { annArrayInit = annValuePair.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT); } else { annArrayInit = aAnnotation.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT); } if (annArrayInit != null) { return annArrayInit; } return aAnnotation; } /** * Strips a single double quote from the front and back of a string. * * For example: *
* Input String = "unchecked" *
* Output String = unchecked * * @param aWarning the warning string * @return the string without two quotes */ private String removeQuotes(final String aWarning) { assert aWarning != null : "the aWarning was null"; assert aWarning.charAt(0) == '"'; assert aWarning.charAt(aWarning.length() - 1) == '"'; return aWarning.substring(1, aWarning.length() - 1); } /** * Recursively walks a conditional expression checking the left * and right sides, checking for matches and * logging violations. * * @param aCond a Conditional type * {@link TokenTypes#QUESTION QUESTION} */ private void walkConditional(final DetailAST aCond) { if (aCond.getType() != TokenTypes.QUESTION) { final String warningText = this.removeQuotes(aCond.getText()); this.logMatch(aCond.getLineNo(), aCond.getColumnNo(), warningText); return; } this.walkConditional(this.getCondLeft(aCond)); this.walkConditional(this.getCondRight(aCond)); } /** * Retrieves the left side of a conditional. * * @param aCond aCond a conditional type * {@link TokenTypes#QUESTION QUESTION} * @return either the value * or another conditional */ private DetailAST getCondLeft(final DetailAST aCond) { final DetailAST colon = aCond.findFirstToken(TokenTypes.COLON); return colon.getPreviousSibling(); } /** * Retrieves the right side of a conditional. * * @param aCond a conditional type * {@link TokenTypes#QUESTION QUESTION} * @return either the value * or another conditional */ private DetailAST getCondRight(final DetailAST aCond) { final DetailAST colon = aCond.findFirstToken(TokenTypes.COLON); return colon.getNextSibling(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ArrayTypeStyleCheck.java100644 0 0 5536 12026051064 30067 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Checks the style of array type definitions. * Some like Java-style: public static void main(String[] args) * and some like C-style: public static void main(String args[]) * * By default the Check enforces Java style. * @author lkuehne */ public class ArrayTypeStyleCheck extends Check { /** controls whether to use Java or C style */ private boolean mJavaStyle = true; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.ARRAY_DECLARATOR}; } @Override public void visitToken(DetailAST aAST) { final DetailAST typeAST = aAST.getParent(); if (typeAST.getType() != TokenTypes.TYPE) { return; } final DetailAST declAST = typeAST.getParent(); if (declAST.getType() == TokenTypes.METHOD_DEF) { // Do not check method's return type. // We have no alternatives here. return; } final DetailAST variableAST = typeAST.getNextSibling(); if (variableAST != null) { final boolean isJavaStyle = (variableAST.getLineNo() > aAST.getLineNo()) || (variableAST.getColumnNo() > aAST.getColumnNo()); if (isJavaStyle != mJavaStyle) { log(aAST.getLineNo(), aAST.getColumnNo(), "array.type.style"); } } } /** * Controls whether to check for Java or C style. * @param aJavaStyle true if Java style should be used. */ public void setJavaStyle(boolean aJavaStyle) { mJavaStyle = aJavaStyle; } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/AvoidNestedBlocksCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/AvoidNestedBlocksCheck.j100644 0 0 7303 12026051056 31251 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Finds nested blocks. * *

* For example this Check flags confusing code like *

*
 * public void guessTheOutput()
 * {
 *     int whichIsWich = 0;
 *     {
 *         int whichIsWhich = 2;
 *     }
 *     System.out.println("value = " + whichIsWhich);
 * }
 * 
* * and debugging / refactoring leftovers such as * *
 * // if (someOldCondition)
 * {
 *     System.out.println("unconditional");
 * }
 * 
* *

* A case in a switch statement does not implicitly form a block. * Thus to be able to introduce local variables that have case scope * it is necessary to open a nested block. This is supported, set * the allowInSwitchCase property to true and include all statements * of the case in the block. *

* *
 * switch (a)
 * {
 *     case 0:
 *         // Never OK, break outside block
 *         {
 *             x = 1;
 *         }
 *         break;
 *     case 1:
 *         // Never OK, statement outside block
 *         System.out.println("Hello");
 *         {
 *             x = 2;
 *             break;
 *         }
 *     case 1:
 *         // OK if allowInSwitchCase is true
 *         {
 *             System.out.println("Hello");
 *             x = 2;
 *             break;
 *         }
 * }
 * 
* * @author lkuehne */ public class AvoidNestedBlocksCheck extends Check { /** * Whether nested blocks are allowed if they are the * only child of a switch case. */ private boolean mAllowInSwitchCase; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.SLIST}; } @Override public void visitToken(DetailAST aAST) { final DetailAST parent = aAST.getParent(); if (parent.getType() == TokenTypes.SLIST) { if (mAllowInSwitchCase && (parent.getParent().getType() == TokenTypes.CASE_GROUP) && (parent.getNumberOfChildren() == 1)) { return; } log(aAST.getLineNo(), aAST.getColumnNo(), "block.nested"); } } /** * Setter for allowInSwitchCase property. * @param aAllowInSwitchCase whether nested blocks are allowed * if they are the only child of a switch case. */ public void setAllowInSwitchCase(boolean aAllowInSwitchCase) { mAllowInSwitchCase = aAllowInSwitchCase; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/BlockOption.java100644 0 0 3301 12026051056 27655 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; /** * Represents the policy for checking block statements. * @see com.puppycrawl.tools.checkstyle.checks.blocks.EmptyBlockCheck * @author Rick Giles */ public enum BlockOption { /** * Represents the policy that there is some text in the block. For example: * *
     * catch (Exception ex) {
     *     // This is a bad coding practice
     * }
     * 
*/ TEXT, /** * Represents the policy that there is a statement in the block. For * example: * *
     * finally {
     *     lock.release();
     * }
     * 
*/ STMT; } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyBlockCheck.java100644 0 0 13547 12026051056 30476 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck; /** * Checks for empty blocks. The policy to verify is specified using the {@link * BlockOption} class and defaults to {@link BlockOption#STMT}. * *

By default the check will check the following blocks: * {@link TokenTypes#LITERAL_WHILE LITERAL_WHILE}, * {@link TokenTypes#LITERAL_TRY LITERAL_TRY}, * {@link TokenTypes#LITERAL_CATCH LITERAL_CATCH}, * {@link TokenTypes#LITERAL_FINALLY LITERAL_FINALLY}, * {@link TokenTypes#LITERAL_DO LITERAL_DO}, * {@link TokenTypes#LITERAL_IF LITERAL_IF}, * {@link TokenTypes#LITERAL_ELSE LITERAL_ELSE}, * {@link TokenTypes#LITERAL_FOR LITERAL_FOR}, * {@link TokenTypes#STATIC_INIT STATIC_INIT}. *

* *

An example of how to configure the check is: *

*
 * <module name="EmptyBlock"/>
 * 
* *

An example of how to configure the check for the {@link * BlockOption#TEXT} policy and only catch blocks is: *

* *
 * <module name="EmptyBlock">
 *    <property name="tokens" value="LITERAL_CATCH"/>
 *    <property name="option" value="text"/>
 * </module>
 * 
* * @author Lars Kühne */ public class EmptyBlockCheck extends AbstractOptionCheck { /** * Creates a new EmptyBlockCheck instance. */ public EmptyBlockCheck() { super(BlockOption.STMT, BlockOption.class); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.LITERAL_WHILE, TokenTypes.LITERAL_TRY, TokenTypes.LITERAL_CATCH, TokenTypes.LITERAL_FINALLY, TokenTypes.LITERAL_DO, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_ELSE, TokenTypes.LITERAL_FOR, TokenTypes.INSTANCE_INIT, TokenTypes.STATIC_INIT, // TODO: need to handle.... //TokenTypes.LITERAL_SWITCH, //TODO: does this handle TokenTypes.LITERAL_SYNCHRONIZED? }; } @Override public void visitToken(DetailAST aAST) { final DetailAST slistAST = aAST.findFirstToken(TokenTypes.SLIST); if (slistAST != null) { if (getAbstractOption() == BlockOption.STMT) { if (slistAST.getChildCount() <= 1) { log(slistAST.getLineNo(), slistAST.getColumnNo(), "block.noStmt", aAST.getText()); } } else if (getAbstractOption() == BlockOption.TEXT) { if (!hasText(slistAST)) { log(slistAST.getLineNo(), slistAST.getColumnNo(), "block.empty", aAST.getText()); } } } } /** * @param aSlistAST a DetailAST value * @return whether the SLIST token contains any text. */ protected boolean hasText(final DetailAST aSlistAST) { boolean retVal = false; final DetailAST rcurlyAST = aSlistAST.findFirstToken(TokenTypes.RCURLY); if (rcurlyAST != null) { final int slistLineNo = aSlistAST.getLineNo(); final int slistColNo = aSlistAST.getColumnNo(); final int rcurlyLineNo = rcurlyAST.getLineNo(); final int rcurlyColNo = rcurlyAST.getColumnNo(); final String[] lines = getLines(); if (slistLineNo == rcurlyLineNo) { // Handle braces on the same line final String txt = lines[slistLineNo - 1] .substring(slistColNo + 1, rcurlyColNo); if (txt.trim().length() != 0) { retVal = true; } } else { // check only whitespace of first & last lines if ((lines[slistLineNo - 1] .substring(slistColNo + 1).trim().length() != 0) || (lines[rcurlyLineNo - 1] .substring(0, rcurlyColNo).trim().length() != 0)) { retVal = true; } else { // check if all lines are also only whitespace for (int i = slistLineNo; i < (rcurlyLineNo - 1); i++) { if (lines[i].trim().length() > 0) { retVal = true; break; } } } } } return retVal; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java100644 0 0 25632 12026051056 30334 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck; /** *

* Checks the placement of left curly braces on types, methods and * other blocks: * {@link TokenTypes#LITERAL_CATCH LITERAL_CATCH}, {@link * TokenTypes#LITERAL_DO LITERAL_DO}, {@link TokenTypes#LITERAL_ELSE * LITERAL_ELSE}, {@link TokenTypes#LITERAL_FINALLY LITERAL_FINALLY}, {@link * TokenTypes#LITERAL_FOR LITERAL_FOR}, {@link TokenTypes#LITERAL_IF * LITERAL_IF}, {@link TokenTypes#LITERAL_SWITCH LITERAL_SWITCH}, {@link * TokenTypes#LITERAL_SYNCHRONIZED LITERAL_SYNCHRONIZED}, {@link * TokenTypes#LITERAL_TRY LITERAL_TRY}, {@link TokenTypes#LITERAL_WHILE * LITERAL_WHILE}. *

* *

* The policy to verify is specified using the {@link LeftCurlyOption} class and * defaults to {@link LeftCurlyOption#EOL}. Policies {@link LeftCurlyOption#EOL} * and {@link LeftCurlyOption#NLOW} take into account property maxLineLength. * The default value for maxLineLength is 80. *

*

* An example of how to configure the check is: *

*
 * <module name="LeftCurly"/>
 * 
*

* An example of how to configure the check with policy * {@link LeftCurlyOption#NLOW} and maxLineLength 120 is: *

*
 * <module name="LeftCurly">
 *      <property name="option"
 * value="nlow"/>     <property name="maxLineLength" value="120"/> <
 * /module>
 * 
* * @author Oliver Burn * @author lkuehne * @version 1.0 */ public class LeftCurlyCheck extends AbstractOptionCheck { /** default maximum line length */ private static final int DEFAULT_MAX_LINE_LENGTH = 80; /** TODO: replace this ugly hack **/ private int mMaxLineLength = DEFAULT_MAX_LINE_LENGTH; /** * Creates a default instance and sets the policy to EOL. */ public LeftCurlyCheck() { super(LeftCurlyOption.EOL, LeftCurlyOption.class); } /** * Sets the maximum line length used in calculating the placement of the * left curly brace. * @param aMaxLineLength the max allowed line length */ public void setMaxLineLength(int aMaxLineLength) { mMaxLineLength = aMaxLineLength; } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.INTERFACE_DEF, TokenTypes.CLASS_DEF, TokenTypes.ANNOTATION_DEF, TokenTypes.ENUM_DEF, TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.ENUM_CONSTANT_DEF, TokenTypes.LITERAL_WHILE, TokenTypes.LITERAL_TRY, TokenTypes.LITERAL_CATCH, TokenTypes.LITERAL_FINALLY, TokenTypes.LITERAL_SYNCHRONIZED, TokenTypes.LITERAL_SWITCH, TokenTypes.LITERAL_DO, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_ELSE, TokenTypes.LITERAL_FOR, // TODO: need to handle.... //TokenTypes.STATIC_INIT, }; } @Override public void visitToken(DetailAST aAST) { final DetailAST startToken; final DetailAST brace; switch (aAST.getType()) { case TokenTypes.CTOR_DEF : case TokenTypes.METHOD_DEF : startToken = skipAnnotationOnlyLines(aAST); brace = aAST.findFirstToken(TokenTypes.SLIST); break; case TokenTypes.INTERFACE_DEF : case TokenTypes.CLASS_DEF : case TokenTypes.ANNOTATION_DEF : case TokenTypes.ENUM_DEF : case TokenTypes.ENUM_CONSTANT_DEF : startToken = skipAnnotationOnlyLines(aAST); final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK); brace = (objBlock == null) ? null : (DetailAST) objBlock.getFirstChild(); break; case TokenTypes.LITERAL_WHILE: case TokenTypes.LITERAL_CATCH: case TokenTypes.LITERAL_SYNCHRONIZED: case TokenTypes.LITERAL_FOR: case TokenTypes.LITERAL_TRY: case TokenTypes.LITERAL_FINALLY: case TokenTypes.LITERAL_DO: case TokenTypes.LITERAL_IF : startToken = aAST; brace = aAST.findFirstToken(TokenTypes.SLIST); break; case TokenTypes.LITERAL_ELSE : startToken = aAST; final DetailAST candidate = aAST.getFirstChild(); brace = (candidate.getType() == TokenTypes.SLIST) ? candidate : null; // silently ignore break; case TokenTypes.LITERAL_SWITCH : startToken = aAST; brace = aAST.findFirstToken(TokenTypes.LCURLY); break; default : startToken = null; brace = null; } if ((brace != null) && (startToken != null)) { verifyBrace(brace, startToken); } } /** * Skip lines that only contain TokenTypes.ANNOTATIONs. * If the received DetailAST * has annotations within its modifiers then first token on the line * of the first token afer all annotations is return. This might be * an annotation. * Otherwise, the received DetailAST is returned. * @param aAST DetailAST. * @return DetailAST. */ private DetailAST skipAnnotationOnlyLines(DetailAST aAST) { final DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS); if (modifiers == null) { return aAST; } DetailAST lastAnnot = findLastAnnotation(modifiers); if (lastAnnot == null) { // There are no annotations. return aAST; } final DetailAST tokenAfterLast = lastAnnot.getNextSibling() != null ? lastAnnot.getNextSibling() : modifiers.getNextSibling(); if (tokenAfterLast.getLineNo() > lastAnnot.getLineNo()) { return tokenAfterLast; } final int lastAnnotLineNumber = lastAnnot.getLineNo(); while (lastAnnot.getPreviousSibling() != null && (lastAnnot.getPreviousSibling().getLineNo() == lastAnnotLineNumber)) { lastAnnot = lastAnnot.getPreviousSibling(); } return lastAnnot; } /** * Find the last token of type TokenTypes.ANNOTATION * under the given set of modifiers. * @param aModifiers DetailAST. * @return DetailAST or null if there are no annotations. */ private DetailAST findLastAnnotation(DetailAST aModifiers) { DetailAST aAnnot = aModifiers.findFirstToken(TokenTypes.ANNOTATION); while (aAnnot != null && aAnnot.getNextSibling() != null && aAnnot.getNextSibling().getType() == TokenTypes.ANNOTATION) { aAnnot = aAnnot.getNextSibling(); } return aAnnot; } /** * Verifies that a specified left curly brace is placed correctly * according to policy. * @param aBrace token for left curly brace * @param aStartToken token for start of expression */ private void verifyBrace(final DetailAST aBrace, final DetailAST aStartToken) { final String braceLine = getLines()[aBrace.getLineNo() - 1]; // calculate the previous line length without trailing whitespace. Need // to handle the case where there is no previous line, cause the line // being check is the first line in the file. final int prevLineLen = (aBrace.getLineNo() == 1) ? mMaxLineLength : Utils.lengthMinusTrailingWhitespace( getLines()[aBrace.getLineNo() - 2]); // Check for being told to ignore, or have '{}' which is a special case if ((braceLine.length() > (aBrace.getColumnNo() + 1)) && (braceLine.charAt(aBrace.getColumnNo() + 1) == '}')) { ; // ignore } else if (getAbstractOption() == LeftCurlyOption.NL) { if (!Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine)) { log(aBrace.getLineNo(), aBrace.getColumnNo(), "line.new", "{"); } } else if (getAbstractOption() == LeftCurlyOption.EOL) { if (Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine) && ((prevLineLen + 2) <= mMaxLineLength)) { log(aBrace.getLineNo(), aBrace.getColumnNo(), "line.previous", "{"); } } else if (getAbstractOption() == LeftCurlyOption.NLOW) { if (aStartToken.getLineNo() == aBrace.getLineNo()) { ; // all ok as on the same line } else if ((aStartToken.getLineNo() + 1) == aBrace.getLineNo()) { if (!Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine)) { log(aBrace.getLineNo(), aBrace.getColumnNo(), "line.new", "{"); } else if ((prevLineLen + 2) <= mMaxLineLength) { log(aBrace.getLineNo(), aBrace.getColumnNo(), "line.previous", "{"); } } else if (!Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine)) { log(aBrace.getLineNo(), aBrace.getColumnNo(), "line.new", "{"); } } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyOption.java100644 0 0 4450 12026051055 30541 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; /** * Represents the options for placing the left curly brace '{'. * * @author Oliver Burn * @version 1 */ public enum LeftCurlyOption { /** * Represents the policy for placing the brace at the end of line. For * example: *
     * if (condition) {
     *     ...
     * 
**/ EOL, /** * Represents the policy that if the brace will fit on the first line of * the statement, taking into account maximum line length, then apply * EOL rule. Otherwise apply the NL * rule. NLOW is a mnemonic for "new line on wrap". * *

For the example above Checkstyle will enforce: * *

     * if (condition) {
     *     ...
     * 
* * But for a statement spanning multiple lines, Checkstyle will enforce: * *
     * if (condition1 && condition2 &&
     *     condition3 && condition4)
     * {
     *     ...
     * 
**/ NLOW, /** * Represents the policy that the brace must always be on a new line. For * example: *
     * if (condition)
     * {
     *     ...
     * 
*/ NL; } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/messages.properties100644 0 0 551 11451071612 30501 0ustar 0 0 block.empty=Empty {0} block. block.nested=Avoid nested blocks. block.noStmt=Must have at least one statement. line.alone=''{0}'' should be alone on a line. line.new=''{0}'' should be on a new line. line.previous=''{0}'' should be on the previous line. line.same=''{0}'' should be on the same line. needBraces=''{0}'' construct must use '''{}'''s. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/messages_de.properties100644 0 0 667 11451071612 31161 0ustar 0 0 block.empty=Leerer {0}-Block. block.nested=Verschachtelte Blöcke sollten vermieden werden. block.noStmt=Muss mindestens ein Statement beinhalten. line.alone=''{0}'' sollte allein in der Zeile stehen. line.new=''{0}'' sollte in einer neuen Zeile stehen. line.previous=''{0}'' sollte in der vorhergehenden Zeile stehen. line.same=''{0}'' sollte in derselben Zeile stehen. needBraces=Das ''{0}''-Konstrukt muss '''{}''' benutzen. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/messages_es.properties100644 0 0 625 11451071612 31172 0ustar 0 0 block.empty=Bloque {0} vacío. block.nested=Evitar bloques anidados. block.noStmt=Debe tener al menos una sentencia. line.alone=''{0}'' debería estar solo en una línea. line.new=''{0}'' debería estar en una nueva línea. line.previous=''{0}'' debería estar en la línea anterior. line.same=''{0}'' debería estar en la misma línea. needBraces=La construcción ''{0}'' debe usar '''{}'' (llaves). checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/messages_fi.properties100644 0 0 607 11451071612 31161 0ustar 0 0 block.empty=Tyhj¤ {0}-rakenne. block.nested=Avoid nested blocks. block.noStmt=Pit¤¤ olla ainakin yksi lause. line.alone=''{0}'' pit¤¤ olla yksin¤¤n rivill¤. line.new=''{0}'' pit¤¤ olla uudella rivill¤. line.previous=''{0}'' pit¤¤ olla edellisell¤ rivill¤. line.same=''{0}'' pit¤¤ olla samalla rivill¤. needBraces=''{0}''-rakenteen pit¤¤ k¤ytt¤¤ '''{}'':a. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/messages_fr.properties100644 0 0 706 11451071612 31172 0ustar 0 0 block.empty=Bloc ''{0}'' vide. block.nested=Evitez d''imbriquer les blocs. block.noStmt=Le bloc devrait contenir au moins une instruction. line.alone=''{0}'' devrait être seul sur sa ligne. line.new=''{0}'' devrait être sur une nouvelle ligne. line.previous=''{0}'' devrait être sur la ligne précédente. line.same=''{0}'' devrait être sur la même ligne. needBraces=L''instruction ''{0}'' devrait utiliser des accolades ('''{''' et '''}'''). checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/messages_ja.properties100644 0 0 1471 11451071612 31175 0ustar 0 0 block.empty=\u7a7a\u306e {0} \u30d6\u30ed\u30c3\u30af\u3067\u3059\u3002 block.nested=\u30cd\u30b9\u30c8\u3057\u305f\u30d6\u30ed\u30c3\u30af\u306f\u907f\u3051\u3066\u304f\u3060\u3055\u3044\u3002 block.noStmt=\u5c11\u306a\u304f\u3068\u30821\u6587\u306f\u3042\u308b\u306f\u305a\u3067\u3059\u3002 line.alone=''{0}'' \u306f\u72ec\u7acb\u3057\u305f\u884c\u306b\u3042\u308b\u3079\u304d\u3067\u3059\u3002 line.new=''{0}'' \u306f\u65b0\u3057\u3044\u884c\u306b\u3042\u308b\u3079\u304d\u3067\u3059\u3002 line.previous=''{0}'' \u306f\u524d\u306e\u884c\u306b\u3042\u308b\u3079\u304d\u3067\u3059\u3002 line.same=''{0}'' \u306f\u540c\u4e00\u884c\u306b\u3042\u308b\u3079\u304d\u3067\u3059\u3002 needBraces=''{0}'' \u6587\u3067\u306f '''{}''' \u3092\u4f7f\u7528\u3057\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/messages_pt.properties100644 0 0 601 11451071612 31200 0ustar 0 0 block.empty=Block {0} vazio. block.nested=Avoid nested blocks. block.noStmt=Tem que ter pelo menos uma instruço. line.alone=''{0}'' deve estar sozinho numa linha. line.new=''{0}'' deve estar numa nova linha. line.previous=''{0}'' deve estar na linha anterior. line.same=''{0}'' deve estar na mesma linha. needBraces=A estrutura sintáctica ''{0}'' deve utilizar '''{}'''s. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/messages_tr.properties100644 0 0 1172 11744664014 31237 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) block.empty = Bo\u015F blok bulundu: {0} block.nested = \u0130\u00E7 i\u00E7e bloklar kullan\u0131lmamal\u0131d\u0131r. block.noStmt = Blok en az bir ifade i\u00E7ermeli. line.alone = ''{0}'' ifadesi sat\u0131rda tek ba\u015F\u0131na olmal\u0131. line.new = ''{0}'' ifadesi yeni sat\u0131rda olmal\u0131. line.previous = ''{0}'' ifadesi \u00F6nceki sat\u0131rda olmal\u0131. line.same = ''{0}'' ifadesi ayn\u0131 sat\u0131rda olmal\u0131. needBraces = ''{0}'' yap\u0131s\u0131 s\u00FCsl\u00FC parantezler ('''{}''') kullanmal\u0131. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/NeedBracesCheck.java100644 0 0 5536 12026051055 30376 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks for braces around code blocks. *

*

By default the check will check the following blocks: * {@link TokenTypes#LITERAL_DO LITERAL_DO}, * {@link TokenTypes#LITERAL_ELSE LITERAL_ELSE}, * {@link TokenTypes#LITERAL_FOR LITERAL_FOR}, * {@link TokenTypes#LITERAL_IF LITERAL_IF}, * {@link TokenTypes#LITERAL_WHILE LITERAL_WHILE}. *

*

* An example of how to configure the check is: *

*
 * <module name="NeedBraces"/>
 * 
*

An example of how to configure the check for if and * else blocks is: *

*
 * <module name="NeedBraces">
 *     <property name="tokens" value="LITERAL_IF, LITERAL_ELSE"/>
 * </module>
 * 
* * @author Rick Giles * @version 1.0 */ public class NeedBracesCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.LITERAL_DO, TokenTypes.LITERAL_ELSE, TokenTypes.LITERAL_FOR, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_WHILE, }; } @Override public void visitToken(DetailAST aAST) { final DetailAST slistAST = aAST.findFirstToken(TokenTypes.SLIST); boolean isElseIf = false; if ((aAST.getType() == TokenTypes.LITERAL_ELSE) && (aAST.findFirstToken(TokenTypes.LITERAL_IF) != null)) { isElseIf = true; } if ((slistAST == null) && !isElseIf) { log(aAST.getLineNo(), "needBraces", aAST.getText()); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/package-info.java100644 0 0 2276 12026051054 27766 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the Block checks that are * bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks.blocks; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java100644 0 0 15453 12026051055 30516 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; /** *

* Checks the placement of right curly braces. * The policy to verify is specified using the {@link RightCurlyOption} class * and defaults to {@link RightCurlyOption#SAME}. *

*

By default the check will check the following tokens: * {@link TokenTypes#LITERAL_TRY LITERAL_TRY}. * {@link TokenTypes#LITERAL_CATCH LITERAL_CATCH}, * {@link TokenTypes#LITERAL_FINALLY LITERAL_FINALLY}. * {@link TokenTypes#LITERAL_IF LITERAL_IF}, * {@link TokenTypes#LITERAL_ELSE LITERAL_ELSE}, *

*

* An example of how to configure the check is: *

*
 * <module name="RightCurly"/>
 * 
*

* An example of how to configure the check with policy * {@link RightCurlyOption#ALONE} for else tokens is: *

*
 * <module name="RightCurly">
 *     <property name="tokens" value="LITERAL_ELSE"/>
 *     <property name="option" value="alone"/>
 * </module>
 * 
* * @author Oliver Burn * @author lkuehne * @author o_sukhodolsky * @version 2.0 */ public class RightCurlyCheck extends AbstractOptionCheck { /** Do we need to check if rculry starts line. */ private boolean mShouldStartLine = true; /** * Sets the right curly option to same. */ public RightCurlyCheck() { super(RightCurlyOption.SAME, RightCurlyOption.class); } /** * Does the check need to check if rcurly starts line. * @param aFlag new value of this property. */ public void setShouldStartLine(boolean aFlag) { mShouldStartLine = aFlag; } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.LITERAL_TRY, TokenTypes.LITERAL_CATCH, TokenTypes.LITERAL_FINALLY, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_ELSE, }; } @Override public void visitToken(DetailAST aAST) { // Attempt to locate the tokens to do the check DetailAST rcurly; DetailAST lcurly; DetailAST nextToken; boolean shouldCheckLastRcurly = false; switch (aAST.getType()) { case TokenTypes.LITERAL_TRY: lcurly = aAST.getFirstChild(); nextToken = lcurly.getNextSibling(); rcurly = lcurly.getLastChild(); break; case TokenTypes.LITERAL_CATCH: nextToken = aAST.getNextSibling(); lcurly = aAST.getLastChild(); rcurly = lcurly.getLastChild(); if (nextToken == null) { shouldCheckLastRcurly = true; nextToken = getNextToken(aAST); } break; case TokenTypes.LITERAL_IF: nextToken = aAST.findFirstToken(TokenTypes.LITERAL_ELSE); if (nextToken != null) { lcurly = nextToken.getPreviousSibling(); rcurly = lcurly.getLastChild(); } else { shouldCheckLastRcurly = true; nextToken = getNextToken(aAST); lcurly = aAST.getLastChild(); rcurly = lcurly.getLastChild(); } break; case TokenTypes.LITERAL_ELSE: shouldCheckLastRcurly = true; nextToken = getNextToken(aAST); lcurly = aAST.getFirstChild(); rcurly = lcurly.getLastChild(); break; case TokenTypes.LITERAL_FINALLY: shouldCheckLastRcurly = true; nextToken = getNextToken(aAST); lcurly = aAST.getFirstChild(); rcurly = lcurly.getLastChild(); break; default: throw new RuntimeException("Unexpected token type (" + TokenTypes.getTokenName(aAST.getType()) + ")"); } if ((rcurly == null) || (rcurly.getType() != TokenTypes.RCURLY)) { // we need to have both tokens to perform the check return; } if (shouldCheckLastRcurly) { if (rcurly.getLineNo() == nextToken.getLineNo()) { log(rcurly, "line.alone", "}"); } } else if ((getAbstractOption() == RightCurlyOption.SAME) && (rcurly.getLineNo() != nextToken.getLineNo())) { log(rcurly, "line.same", "}"); } else if ((getAbstractOption() == RightCurlyOption.ALONE) && (rcurly.getLineNo() == nextToken.getLineNo())) { log(rcurly, "line.alone", "}"); } if (!mShouldStartLine) { return; } final boolean startsLine = Utils.whitespaceBefore(rcurly.getColumnNo(), getLines()[rcurly.getLineNo() - 1]); if (!startsLine && (lcurly.getLineNo() != rcurly.getLineNo())) { log(rcurly, "line.new", "}"); } } /** * Finds next token after the given one. * @param aAST the given node. * @return the token which represents next lexical item. */ private DetailAST getNextToken(DetailAST aAST) { DetailAST next = null; DetailAST parent = aAST; while ((parent != null) && (next == null)) { next = parent.getNextSibling(); parent = parent.getParent(); } return CheckUtils.getFirstNode(next); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyOption.java100644 0 0 3255 12026051055 30726 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; /** * Represents the options for placing the right curly brace '}'. * * @author Oliver Burn * @version 1 */ public enum RightCurlyOption { /** * Represents the policy that the brace must be alone on the line. For * example: * *
     * try {
     *     ...
     * }
     * finally {
     * 
**/ ALONE, /** * Represents the policy that the brace must be on the same line as the * next statement. For example: * *
     * try {
     *     ...
     * } finally {
     * 
**/ SAME; } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/CheckUtils.java100644 0 0 27346 12026051064 26251 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.List; /** * Contains utility methods for the checks. * * @author Oliver Burn * @author Simon Harris * @author o_sukhodolsky */ public final class CheckUtils { /** prevent instances */ private CheckUtils() { throw new UnsupportedOperationException(); } /** * Tests whether a method definition AST defines an equals covariant. * @param aAST the method definition AST to test. * Precondition: aAST is a TokenTypes.METHOD_DEF node. * @return true if aAST defines an equals covariant. */ public static boolean isEqualsMethod(DetailAST aAST) { if (aAST.getType() != TokenTypes.METHOD_DEF) { // A node must be method def return false; } // non-static, non-abstract? final DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS); if (modifiers.branchContains(TokenTypes.LITERAL_STATIC) || modifiers.branchContains(TokenTypes.ABSTRACT)) { return false; } // named "equals"? final DetailAST nameNode = aAST.findFirstToken(TokenTypes.IDENT); final String name = nameNode.getText(); if (!"equals".equals(name)) { return false; } // one parameter? final DetailAST paramsNode = aAST.findFirstToken(TokenTypes.PARAMETERS); return (paramsNode.getChildCount() == 1); } /** * Returns whether a token represents an ELSE as part of an ELSE / IF set. * @param aAST the token to check * @return whether it is */ public static boolean isElseIf(DetailAST aAST) { final DetailAST parentAST = aAST.getParent(); return (aAST.getType() == TokenTypes.LITERAL_IF) && (isElse(parentAST) || isElseWithCurlyBraces(parentAST)); } /** * Returns whether a token represents an ELSE. * @param aAST the token to check * @return whether the token represents an ELSE */ private static boolean isElse(DetailAST aAST) { return aAST.getType() == TokenTypes.LITERAL_ELSE; } /** * Returns whether a token represents an SLIST as part of an ELSE * statement. * @param aAST the token to check * @return whether the toke does represent an SLIST as part of an ELSE */ private static boolean isElseWithCurlyBraces(DetailAST aAST) { return (aAST.getType() == TokenTypes.SLIST) && (aAST.getChildCount() == 2) && isElse(aAST.getParent()); } /** * Creates FullIdent for given type node. * @param aTypeAST a type node. * @return FullIdent for given type. */ public static FullIdent createFullType(DetailAST aTypeAST) { final DetailAST arrayDeclAST = aTypeAST.findFirstToken(TokenTypes.ARRAY_DECLARATOR); return createFullTypeNoArrays(arrayDeclAST == null ? aTypeAST : arrayDeclAST); } /** * @param aTypeAST a type node (no array) * @return FullIdent for given type. */ private static FullIdent createFullTypeNoArrays(DetailAST aTypeAST) { return FullIdent.createFullIdent(aTypeAST.getFirstChild()); } // constants for parseDouble() /** octal radix */ private static final int BASE_8 = 8; /** decimal radix */ private static final int BASE_10 = 10; /** hex radix */ private static final int BASE_16 = 16; /** * Returns the value represented by the specified string of the specified * type. Returns 0 for types other than float, double, int, and long. * @param aText the string to be parsed. * @param aType the token type of the text. Should be a constant of * {@link com.puppycrawl.tools.checkstyle.api.TokenTypes}. * @return the double value represented by the string argument. */ public static double parseDouble(String aText, int aType) { String txt = aText; double result = 0; switch (aType) { case TokenTypes.NUM_FLOAT: case TokenTypes.NUM_DOUBLE: result = Double.parseDouble(txt); break; case TokenTypes.NUM_INT: case TokenTypes.NUM_LONG: int radix = BASE_10; if (txt.startsWith("0x") || txt.startsWith("0X")) { radix = BASE_16; txt = txt.substring(2); } else if (txt.charAt(0) == '0') { radix = BASE_8; txt = txt.substring(1); } if ((txt.endsWith("L")) || (txt.endsWith("l"))) { txt = txt.substring(0, txt.length() - 1); } if (txt.length() > 0) { if (aType == TokenTypes.NUM_INT) { result = parseInt(txt, radix); } else { result = parseLong(txt, radix); } } break; default: break; } return result; } /** * Parses the string argument as a signed integer in the radix specified by * the second argument. The characters in the string must all be digits of * the specified radix. Handles negative values, which method * java.lang.Integer.parseInt(String, int) does not. * @param aText the String containing the integer representation to be * parsed. Precondition: aText contains a parsable int. * @param aRadix the radix to be used while parsing aText. * @return the integer represented by the string argument in the specified * radix. */ public static int parseInt(String aText, int aRadix) { int result = 0; final int max = aText.length(); for (int i = 0; i < max; i++) { final int digit = Character.digit(aText.charAt(i), aRadix); result *= aRadix; result += digit; } return result; } /** * Parses the string argument as a signed long in the radix specified by * the second argument. The characters in the string must all be digits of * the specified radix. Handles negative values, which method * java.lang.Integer.parseInt(String, int) does not. * @param aText the String containing the integer representation to be * parsed. Precondition: aText contains a parsable int. * @param aRadix the radix to be used while parsing aText. * @return the long represented by the string argument in the specified * radix. */ public static long parseLong(String aText, int aRadix) { long result = 0; final int max = aText.length(); for (int i = 0; i < max; i++) { final int digit = Character.digit(aText.charAt(i), aRadix); result *= aRadix; result += digit; } return result; } /** * Returns the value represented by the specified string of the specified * type. Returns 0 for types other than float, double, int, and long. * @param aText the string to be parsed. * @param aType the token type of the text. Should be a constant of * {@link com.puppycrawl.tools.checkstyle.api.TokenTypes}. * @return the float value represented by the string argument. */ public static double parseFloat(String aText, int aType) { return (float) parseDouble(aText, aType); } /** * Finds sub-node for given node minimal (line, column) pair. * @param aNode the root of tree for search. * @return sub-node with minimal (line, column) pair. */ public static DetailAST getFirstNode(final DetailAST aNode) { DetailAST currentNode = aNode; DetailAST child = aNode.getFirstChild(); while (child != null) { final DetailAST newNode = getFirstNode(child); if ((newNode.getLineNo() < currentNode.getLineNo()) || ((newNode.getLineNo() == currentNode.getLineNo()) && (newNode.getColumnNo() < currentNode.getColumnNo()))) { currentNode = newNode; } child = child.getNextSibling(); } return currentNode; } /** * Retrieves the names of the type parameters to the node. * @param aNode the parameterised AST node * @return a list of type parameter names */ public static List getTypeParameterNames(final DetailAST aNode) { final DetailAST typeParameters = aNode.findFirstToken(TokenTypes.TYPE_PARAMETERS); final List typeParamNames = Lists.newArrayList(); if (typeParameters != null) { final DetailAST typeParam = typeParameters.findFirstToken(TokenTypes.TYPE_PARAMETER); typeParamNames.add( typeParam.findFirstToken(TokenTypes.IDENT).getText()); DetailAST sibling = typeParam.getNextSibling(); while (sibling != null) { if (sibling.getType() == TokenTypes.TYPE_PARAMETER) { typeParamNames.add( sibling.findFirstToken(TokenTypes.IDENT).getText()); } sibling = sibling.getNextSibling(); } } return typeParamNames; } /** * Retrieves the type parameters to the node. * @param aNode the parameterised AST node * @return a list of type parameter names */ public static List getTypeParameters(final DetailAST aNode) { final DetailAST typeParameters = aNode.findFirstToken(TokenTypes.TYPE_PARAMETERS); final List typeParams = Lists.newArrayList(); if (typeParameters != null) { final DetailAST typeParam = typeParameters.findFirstToken(TokenTypes.TYPE_PARAMETER); typeParams.add(typeParam); DetailAST sibling = typeParam.getNextSibling(); while (sibling != null) { if (sibling.getType() == TokenTypes.TYPE_PARAMETER) { typeParams.add(sibling); } sibling = sibling.getNextSibling(); } } return typeParams; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ClassResolver.java100644 0 0 14604 12026051064 26773 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import java.util.Set; /** * Utility class to resolve a class name to an actual class. Note that loaded * classes are not initialized. *

Limitations: this does not handle inner classes very well.

* * @author Oliver Burn * @version 1.0 */ public class ClassResolver { /** name of the package to check if the class belongs to **/ private final String mPkg; /** set of imports to check against **/ private final Set mImports; /** use to load classes **/ private final ClassLoader mLoader; /** * Creates a new ClassResolver instance. * * @param aLoader the ClassLoader to load classes with. * @param aPkg the name of the package the class may belong to * @param aImports set of imports to check if the class belongs to */ public ClassResolver(ClassLoader aLoader, String aPkg, Set aImports) { mLoader = aLoader; mPkg = aPkg; mImports = aImports; mImports.add("java.lang.*"); } /** * Attempts to resolve the Class for a specified name. The algorithm is * to check: * - fully qualified name * - explicit imports * - enclosing package * - star imports * @param aName name of the class to resolve * @param aCurrentClass name of current class (for inner classes). * @return the resolved class * @throws ClassNotFoundException if unable to resolve the class */ public Class resolve(String aName, String aCurrentClass) throws ClassNotFoundException { // See if the class is full qualified Class clazz = resolveQualifiedName(aName); if (clazz != null) { return clazz; } // try matching explicit imports for (String imp : mImports) { // Very important to add the "." in the check below. Otherwise you // when checking for "DataException", it will match on // "SecurityDataException". This has been the cause of a very // difficult bug to resolve! if (imp.endsWith("." + aName)) { clazz = resolveQualifiedName(imp); if (clazz != null) { return clazz; } } } // See if in the package if (!"".equals(mPkg)) { clazz = resolveQualifiedName(mPkg + "." + aName); if (clazz != null) { return clazz; } } //inner class of this class??? if (!"".equals(aCurrentClass)) { final String innerClass = (!"".equals(mPkg) ? (mPkg + ".") : "") + aCurrentClass + "$" + aName; if (isLoadable(innerClass)) { return safeLoad(innerClass); } } // try star imports for (String imp : mImports) { if (imp.endsWith(".*")) { final String fqn = imp.substring(0, imp.lastIndexOf('.') + 1) + aName; clazz = resolveQualifiedName(fqn); if (clazz != null) { return clazz; } } } // Giving up, the type is unknown, so load the class to generate an // exception return safeLoad(aName); } /** * @return whether a specified class is loadable with safeLoad(). * @param aName name of the class to check */ public boolean isLoadable(String aName) { try { safeLoad(aName); return true; } catch (final ClassNotFoundException e) { return false; } } /** * Will load a specified class is such a way that it will NOT be * initialised. * @param aName name of the class to load * @return the Class for the specified class * @throws ClassNotFoundException if an error occurs */ public Class safeLoad(String aName) throws ClassNotFoundException { // The next line will load the class using the specified class // loader. The magic is having the "false" parameter. This means the // class will not be initialised. Very, very important. return Class.forName(aName, false, mLoader); } /** * Tries to resolve a class for fully-specified name. * @param aName a given name of class. * @return Class object for the given name or null. */ private Class resolveQualifiedName(final String aName) { try { if (isLoadable(aName)) { return safeLoad(aName); } //Perhaps it's fully-qualified inner class final int dot = aName.lastIndexOf("."); if (dot != -1) { final String innerName = aName.substring(0, dot) + "$" + aName.substring(dot + 1); if (isLoadable(innerName)) { return safeLoad(innerName); } } } catch (final ClassNotFoundException ex) { // we shouldn't get this exception here, // so this is unexpected runtime exception throw new RuntimeException(ex); } return null; } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/AbstractIllegalCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/AbstractIllegalCheck.jav100644 0 0 5336 12026051054 31262 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import java.util.Set; /** * Support for checks that look for usage of illegal types. * @author Oliver Burn */ public abstract class AbstractIllegalCheck extends Check { /** Illegal class names */ private final Set mIllegalClassNames = Sets.newHashSet(); /** * Constructs an object. * @param aInitialNames the initial class names to treat as illegal */ protected AbstractIllegalCheck(final String[] aInitialNames) { assert aInitialNames != null; setIllegalClassNames(aInitialNames); } /** * Checks if given class is illegal. * * @param aIdent * ident to check. * @return true if given ident is illegal. */ protected final boolean isIllegalClassName(final String aIdent) { return mIllegalClassNames.contains(aIdent); } /** * Set the list of illegal classes. * * @param aClassNames * array of illegal exception classes */ public final void setIllegalClassNames(final String[] aClassNames) { assert aClassNames != null; mIllegalClassNames.clear(); for (final String name : aClassNames) { mIllegalClassNames.add(name); final int lastDot = name.lastIndexOf("."); if ((lastDot > 0) && (lastDot < (name.length() - 1))) { final String shortName = name .substring(name.lastIndexOf(".") + 1); mIllegalClassNames.add(shortName); } } } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/AbstractIllegalMethodCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/AbstractIllegalMethodChe100644 0 0 5055 12026051054 31324 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Provide support for checking for a method with a specified name and no * arguments. * @author Oliver Burn */ public abstract class AbstractIllegalMethodCheck extends Check { /** Name of method to disallow. */ private final String mMethodName; /** The error key to report with. */ private final String mErrorKey; /** * Creates an instance. * @param aMethodName name of the method to disallow. * @param aErrorKey the error key to report with. */ public AbstractIllegalMethodCheck(String aMethodName, String aErrorKey) { mMethodName = aMethodName; mErrorKey = aErrorKey; } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.METHOD_DEF}; } @Override public void visitToken(DetailAST aAST) { final DetailAST mid = aAST.findFirstToken(TokenTypes.IDENT); final String methodName = mid.getText(); if (mMethodName.equals(methodName)) { final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS); final boolean hasEmptyParamList = !params.branchContains(TokenTypes.PARAMETER_DEF); if (hasEmptyParamList) { log(aAST.getLineNo(), mErrorKey); } } } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/AbstractNestedDepthCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/AbstractNestedDepthCheck100644 0 0 5377 12026051054 31346 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Abstract class which provides helpers functionality for nestedchecks. * * @author Simon Harris */ public abstract class AbstractNestedDepthCheck extends Check { /** maximum allowed nesting depth */ private int mMax; /** curren nesting depth */ private int mDepth; /** * Creates new instance of checks. * @param aMax default allowed nesting depth. */ public AbstractNestedDepthCheck(int aMax) { setMax(aMax); } @Override public final int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void beginTree(DetailAST aRootAST) { mDepth = 0; } /** * Getter for maximum allowed nesting depth. * @return maximum allowed nesting depth. */ public final int getMax() { return mMax; } /** * Setter for maximum allowed nesting depth. * @param aMax maximum allowed nesting depth. */ public final void setMax(int aMax) { mMax = aMax; } /** * Increasing current nesting depth. * @param aAST note which increases nesting. * @param aMessageId message id for logging error. */ protected final void nestIn(DetailAST aAST, String aMessageId) { if (mDepth > mMax) { log(aAST, aMessageId, mDepth, mMax); } ++mDepth; } /** Decreasing current nesting depth */ protected final void nestOut() { --mDepth; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/AbstractSuperCheck.java100644 0 0 16120 12026051053 31160 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import antlr.collections.AST; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.LinkedList; /** *

* Abstract class for checking that an overriding method with no parameters * invokes the super method. *

* @author Rick Giles */ public abstract class AbstractSuperCheck extends Check { /** * Stack node for a method definition and a record of * whether the method has a call to the super method. * @author Rick Giles */ private static class MethodNode { /** method definition */ private final DetailAST mMethod; /** true if the overriding method calls the super method */ private boolean mCallsSuper; /** * Constructs a stack node for a method definition. * @param aAST AST for the method definition. */ public MethodNode(DetailAST aAST) { mMethod = aAST; mCallsSuper = false; } /** * Records that the overriding method has a call to the super method. */ public void setCallsSuper() { mCallsSuper = true; } /** * Determines whether the overriding method has a call to the super * method. * @return true if the overriding method has a call to the super * method. */ public boolean getCallsSuper() { return mCallsSuper; } /** * Returns the overriding method definition AST. * @return the overriding method definition AST. */ public DetailAST getMethod() { return mMethod; } } /** stack of methods */ private final LinkedList mMethodStack = Lists.newLinkedList(); @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.METHOD_DEF, TokenTypes.LITERAL_SUPER, }; } /** * Returns the name of the overriding method. * @return the name of the overriding method. */ protected abstract String getMethodName(); @Override public void beginTree(DetailAST aRootAST) { mMethodStack.clear(); } @Override public void visitToken(DetailAST aAST) { if (isOverridingMethod(aAST)) { mMethodStack.add(new MethodNode(aAST)); } else if (isSuperCall(aAST)) { final MethodNode methodNode = mMethodStack.getLast(); methodNode.setCallsSuper(); } } /** * Determines whether a 'super' literal is a call to the super method * for this check. * @param aAST the AST node of a 'super' literal. * @return true if aAST is a call to the super method * for this check. */ private boolean isSuperCall(DetailAST aAST) { if (aAST.getType() != TokenTypes.LITERAL_SUPER) { return false; } // dot operator? DetailAST parent = aAST.getParent(); if ((parent == null) || (parent.getType() != TokenTypes.DOT)) { return false; } // same name of method AST sibling = aAST.getNextSibling(); // ignore type parameters if ((sibling != null) && (sibling.getType() == TokenTypes.TYPE_ARGUMENTS)) { sibling = sibling.getNextSibling(); } if ((sibling == null) || (sibling.getType() != TokenTypes.IDENT)) { return false; } final String name = sibling.getText(); if (!getMethodName().equals(name)) { return false; } // 0 parameters? final DetailAST args = parent.getNextSibling(); if ((args == null) || (args.getType() != TokenTypes.ELIST)) { return false; } if (args.getChildCount() != 0) { return false; } // in an overriding method for this check? while (parent != null) { if (parent.getType() == TokenTypes.METHOD_DEF) { return isOverridingMethod(parent); } else if ((parent.getType() == TokenTypes.CTOR_DEF) || (parent.getType() == TokenTypes.INSTANCE_INIT)) { return false; } parent = parent.getParent(); } return false; } @Override public void leaveToken(DetailAST aAST) { if (isOverridingMethod(aAST)) { final MethodNode methodNode = mMethodStack.removeLast(); if (!methodNode.getCallsSuper()) { final DetailAST methodAST = methodNode.getMethod(); final DetailAST nameAST = methodAST.findFirstToken(TokenTypes.IDENT); log(nameAST.getLineNo(), nameAST.getColumnNo(), "missing.super.call", nameAST.getText()); } } } /** * Determines whether an AST is a method definition for this check, * with 0 parameters. * @param aAST the method definition AST. * @return true if the method of aAST is a method for this check. */ private boolean isOverridingMethod(DetailAST aAST) { if ((aAST.getType() != TokenTypes.METHOD_DEF) || ScopeUtils.inInterfaceOrAnnotationBlock(aAST)) { return false; } final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT); final String name = nameAST.getText(); if (!getMethodName().equals(name)) { return false; } final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS); return (params.getChildCount() == 0); } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/ArrayTrailingCommaCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/ArrayTrailingCommaCheck.100644 0 0 4564 12026051053 31252 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** *

* Checks if array initialization contains optional trailing comma. *

*

* Rationale: Putting this comma in make is easier to change the * order of the elements or add new elements on the end. *

*

* An example of how to configure the check is: *

*
 * <module name="ArrayTrailingComma"/>
 * 
* @author o_sukhodolsky */ public class ArrayTrailingCommaCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.ARRAY_INIT}; } @Override public void visitToken(DetailAST aArrayInit) { final DetailAST rcurly = aArrayInit.findFirstToken(TokenTypes.RCURLY); // if curlys are on the same line // or array is empty then check nothing if ((aArrayInit.getLineNo() == rcurly.getLineNo()) || (aArrayInit.getChildCount() == 1)) { return; } final DetailAST prev = rcurly.getPreviousSibling(); if (prev.getType() != TokenTypes.COMMA) { log(rcurly.getLineNo(), "array.trailing.comma"); } } } ././@LongLink100644 0 0 156 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/AvoidInlineConditionalsCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/AvoidInlineConditionalsC100644 0 0 4245 12026051053 31360 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Detects inline conditionals. * * An example inline conditional is this: *
 * String a = getParameter("a");
 * String b = (a==null || a.length<1) ? null : a.substring(1);
 * 
* * Rationale: Some developers find inline conditionals hard to read, * so their company's coding standards forbids them. * * @author lkuehne */ public class AvoidInlineConditionalsCheck extends Check { @Override public int[] getDefaultTokens() { return new int[]{TokenTypes.QUESTION}; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aAST) { // the only place a QUESTION token can occur is in inline conditionals // so no need to do any further tricks here - pretty trivial Check! log(aAST.getLineNo(), aAST.getColumnNo(), "inline.conditional.avoid"); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheck.jav100644 0 0 10742 12026051053 31342 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; import java.util.Set; /** *

Checks that if a class defines a covariant method equals, * then it defines method equals(java.lang.Object). * Inspired by findbugs, * http://www.cs.umd.edu/~pugh/java/bugs/docs/findbugsPaper.pdf *

*

* An example of how to configure the check is: *

*
 * <module name="CovariantEquals"/>
 * 
* @author Rick Giles * @version 1.0 */ public class CovariantEqualsCheck extends Check { /** Set of equals method definitions */ private final Set mEqualsMethods = Sets.newHashSet(); @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.CLASS_DEF, TokenTypes.LITERAL_NEW, }; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aAST) { mEqualsMethods.clear(); boolean hasEqualsObject = false; // examine method definitions for equals methods final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK); if (objBlock != null) { DetailAST child = objBlock.getFirstChild(); while (child != null) { if (child.getType() == TokenTypes.METHOD_DEF) { if (CheckUtils.isEqualsMethod(child)) { if (hasObjectParameter(child)) { hasEqualsObject = true; } else { mEqualsMethods.add(child); } } } child = child.getNextSibling(); } // report equals method definitions if (!hasEqualsObject) { for (DetailAST equalsAST : mEqualsMethods) { final DetailAST nameNode = equalsAST .findFirstToken(TokenTypes.IDENT); log(nameNode.getLineNo(), nameNode.getColumnNo(), "covariant.equals"); } } } } /** * Tests whether a method definition AST has exactly one * parameter of type Object. * @param aAST the method definition AST to test. * Precondition: aAST is a TokenTypes.METHOD_DEF node. * @return true if aAST has exactly one parameter of type Object. */ private boolean hasObjectParameter(DetailAST aAST) { // one parameter? final DetailAST paramsNode = aAST.findFirstToken(TokenTypes.PARAMETERS); if (paramsNode.getChildCount() != 1) { return false; } // parameter type "Object"? final DetailAST paramNode = paramsNode.findFirstToken(TokenTypes.PARAMETER_DEF); final DetailAST typeNode = paramNode.findFirstToken(TokenTypes.TYPE); final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode); final String name = fullIdent.getText(); return ("Object".equals(name) || "java.lang.Object".equals(name)); } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.ja100644 0 0 17004 12026051053 31272 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.Scope; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that the parts of a class or interface declaration * appear in the order suggested by the * Code Conventions for the Java Programming Language. *

*

*

    *
  1. Class (static) variables. First the public class variables, then * the protected, then package level (no access modifier), and then * the private.
  2. *
  3. Instance variables. First the public class variables, then * the protected, then package level (no access modifier), and then * the private.
  4. *
  5. Constructors
  6. *
  7. Methods
  8. *
*

*

* An example of how to configure the check is: *

*
 * <module name="DeclarationOrder"/>
 * 
* * @author r_auckenthaler */ public class DeclarationOrderCheck extends Check { /** State for the VARIABLE_DEF */ private static final int STATE_STATIC_VARIABLE_DEF = 1; /** State for the VARIABLE_DEF */ private static final int STATE_INSTANCE_VARIABLE_DEF = 2; /** State for the CTOR_DEF */ private static final int STATE_CTOR_DEF = 3; /** State for the METHOD_DEF */ private static final int STATE_METHOD_DEF = 4; /** * List of Declaration States. This is necessary due to * inner classes that have their own state */ private final FastStack mScopeStates = FastStack.newInstance(); /** * private class to encapsulate the state */ private static class ScopeState { /** The state the check is in */ private int mScopeState = STATE_STATIC_VARIABLE_DEF; /** The sub-state the check is in */ private Scope mDeclarationAccess = Scope.PUBLIC; } /** If true, ignores the check to constructors. */ private boolean mIgnoreConstructors; /** If true, ignore the check to methods. */ private boolean mIgnoreMethods; /** If true, ignore the check to modifiers (fields, ...). */ private boolean mIgnoreModifiers; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.MODIFIERS, TokenTypes.OBJBLOCK, }; } @Override public void visitToken(DetailAST aAST) { final int parentType = aAST.getParent().getType(); ScopeState state; switch(aAST.getType()) { case TokenTypes.OBJBLOCK: mScopeStates.push(new ScopeState()); break; case TokenTypes.CTOR_DEF: if (parentType != TokenTypes.OBJBLOCK) { return; } state = mScopeStates.peek(); if (state.mScopeState > STATE_CTOR_DEF) { if (!mIgnoreConstructors) { log(aAST, "declaration.order.constructor"); } } else { state.mScopeState = STATE_CTOR_DEF; } break; case TokenTypes.METHOD_DEF: state = mScopeStates.peek(); if (parentType != TokenTypes.OBJBLOCK) { return; } if (state.mScopeState > STATE_METHOD_DEF) { if (!mIgnoreMethods) { log(aAST, "declaration.order.method"); } } else { state.mScopeState = STATE_METHOD_DEF; } break; case TokenTypes.MODIFIERS: if ((parentType != TokenTypes.VARIABLE_DEF) || (aAST.getParent().getParent().getType() != TokenTypes.OBJBLOCK)) { return; } state = mScopeStates.peek(); if (aAST.findFirstToken(TokenTypes.LITERAL_STATIC) != null) { if (state.mScopeState > STATE_STATIC_VARIABLE_DEF) { if (!mIgnoreModifiers || state.mScopeState > STATE_INSTANCE_VARIABLE_DEF) { log(aAST, "declaration.order.static"); } } else { state.mScopeState = STATE_STATIC_VARIABLE_DEF; } } else { if (state.mScopeState > STATE_INSTANCE_VARIABLE_DEF) { log(aAST, "declaration.order.instance"); } else if (state.mScopeState == STATE_STATIC_VARIABLE_DEF) { state.mDeclarationAccess = Scope.PUBLIC; state.mScopeState = STATE_INSTANCE_VARIABLE_DEF; } } final Scope access = ScopeUtils.getScopeFromMods(aAST); if (state.mDeclarationAccess.compareTo(access) > 0) { if (!mIgnoreModifiers) { log(aAST, "declaration.order.access"); } } else { state.mDeclarationAccess = access; } break; default: } } @Override public void leaveToken(DetailAST aAST) { switch(aAST.getType()) { case TokenTypes.OBJBLOCK: mScopeStates.pop(); break; default: } } /** * Sets whether to ignore constructors. * @param aIgnoreConstructors whether to ignore constructors. */ public void setIgnoreConstructors(boolean aIgnoreConstructors) { mIgnoreConstructors = aIgnoreConstructors; } /** * Sets whether to ignore methods. * @param aIgnoreMethods whether to ignore methods. */ public void setIgnoreMethods(boolean aIgnoreMethods) { mIgnoreMethods = aIgnoreMethods; } /** * Sets whether to ignore modifiers. * @param aIgnoreModifiers whether to ignore modifiers. */ public void setIgnoreModifiers(boolean aIgnoreModifiers) { mIgnoreModifiers = aIgnoreModifiers; } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/DefaultComesLastCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/DefaultComesLastCheck.ja100644 0 0 5575 12026051052 31241 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Check that the default is after all the cases * in a switch statement. *

*

* Rationale: Java allows default anywhere within the * switch statement. But if it comes after the last * case then it is more readable. *

*

* An example of how to configure the check is: *

*
 * <module name="DefaultComesLast"/>
 * 
* @author o_sukhodolsky */ public class DefaultComesLastCheck extends Check { /** Creates new instance of the check. */ public DefaultComesLastCheck() { // do nothing } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.LITERAL_DEFAULT, }; } @Override public int[] getAcceptableTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aAST) { final DetailAST defaultGroupAST = aAST.getParent(); //default keywords used in annotations too - not what we're //interested in if (defaultGroupAST.getType() != TokenTypes.ANNOTATION_FIELD_DEF) { final DetailAST switchAST = defaultGroupAST.getParent(); final DetailAST lastGroupAST = switchAST.getLastChild().getPreviousSibling(); if ((defaultGroupAST.getLineNo() != lastGroupAST.getLineNo()) || (defaultGroupAST.getColumnNo() != lastGroupAST.getColumnNo())) { log(aAST, "default.comes.last"); } } } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/EmptyStatementCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/EmptyStatementCheck.java100644 0 0 3714 12026051052 31345 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** *

* Detects empty statements (standalone ';'). * Empty statements often introduce bugs * that are hard to spot, such as in *

*
 * if (someCondition);
 *   doConditionalStuff();
 * doUnconditionalStuff();
 * 
*

* An example of how to configure the check is: *

*
 * <module name="EmptyStatement"/>
 * 
* @author Rick Giles * @version 1.0 */ public class EmptyStatementCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.EMPTY_STAT}; } @Override public void visitToken(DetailAST aAST) { log(aAST.getLineNo(), aAST.getColumnNo(), "empty.statement"); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.jav100644 0 0 17732 12026051052 31316 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import antlr.collections.AST; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that any combination of String literals with optional * assignment is on the left side of an equals() comparison. *

* *

* Rationale: Calling the equals() method on String literals * will avoid a potential NullPointerException. Also, it is * pretty common to see null check right before equals comparisons * which is not necessary in the below example. * * For example: * *

 *  
 *    String nullString = null;
 *    nullString.equals("My_Sweet_String");
 *  
 * 
* should be refactored to * *
 *  
 *    String nullString = null;
 *    "My_Sweet_String".equals(nullString);
 *  
 * 
*

* *

* Limitations: If the equals method is overridden or * a covariant equals method is defined and the implementation * is incorrect (where s.equals(t) does not return the same result * as t.equals(s)) then rearranging the called on object and * parameter may have unexpected results * *
* * Java's Autoboxing feature has an affect * on how this check is implemented. Pre Java 5 all IDENT + IDENT * object concatenations would not cause a NullPointerException even * if null. Those situations could have been included in this check. * They would simply act as if they surrounded by String.valueof() * which would concatenate the String null. *

*

* The following example will cause a * NullPointerException as a result of what autoboxing does. *

 * Integer i = null, j = null;
 * String number = "5"
 * number.equals(i + j);
 * 
*

* * Since, it is difficult to determine what kind of Object is being * concatenated all ident concatenation is considered unsafe. * * @author Travis Schneeberger * version 1.0 */ public class EqualsAvoidNullCheck extends Check { /** Whether to process equalsIgnoreCase() invocations. */ private boolean mIgnoreEqualsIgnoreCase; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.METHOD_CALL}; } @Override public void visitToken(final DetailAST aMethodCall) { final DetailAST dot = aMethodCall.getFirstChild(); if (dot.getType() != TokenTypes.DOT) { return; } final DetailAST objCalledOn = dot.getFirstChild(); //checks for calling equals on String literal and //anon object which cannot be null //Also, checks if calling using strange inner class //syntax outter.inner.equals(otherObj) by looking //for the dot operator which cannot be improved if ((objCalledOn.getType() == TokenTypes.STRING_LITERAL) || (objCalledOn.getType() == TokenTypes.LITERAL_NEW) || (objCalledOn.getType() == TokenTypes.DOT)) { return; } final DetailAST method = objCalledOn.getNextSibling(); final DetailAST expr = dot.getNextSibling().getFirstChild(); if ("equals".equals(method.getText()) || (!mIgnoreEqualsIgnoreCase && "equalsIgnoreCase" .equals(method.getText()))) { if (containsOneArg(expr) && containsAllSafeTokens(expr)) { log(aMethodCall.getLineNo(), aMethodCall.getColumnNo(), "equals".equals(method.getText()) ? "equals.avoid.null" : "equalsIgnoreCase.avoid.null"); } } } /** * Checks if a method contains no arguments * starting at with the argument expression. * * @param aExpr the argument expression * @return true if the method contains no args, false if not */ private boolean containsNoArgs(final AST aExpr) { return (aExpr == null); } /** * Checks if a method contains multiple arguments * starting at with the argument expression. * * @param aExpr the argument expression * @return true if the method contains multiple args, false if not */ private boolean containsMultiArgs(final AST aExpr) { final AST comma = aExpr.getNextSibling(); return (comma != null) && (comma.getType() == TokenTypes.COMMA); } /** * Checks if a method contains a single argument * starting at with the argument expression. * * @param aExpr the argument expression * @return true if the method contains a single arg, false if not */ private boolean containsOneArg(final AST aExpr) { return !containsNoArgs(aExpr) && !containsMultiArgs(aExpr); } /** *

* Looks for all "safe" Token combinations in the argument * expression branch. *

* *

* See class documentation for details on autoboxing's affect * on this method implementation. *

* * @param aExpr the argument expression * @return - true if any child matches the set of tokens, false if not */ private boolean containsAllSafeTokens(final DetailAST aExpr) { DetailAST arg = aExpr.getFirstChild(); if (arg.branchContains(TokenTypes.METHOD_CALL)) { return false; } arg = skipVariableAssign(arg); //Plus assignment can have ill affects //do not want to recommend moving expression //See example: //String s = "SweetString"; //s.equals(s += "SweetString"); //false //s = "SweetString"; //(s += "SweetString").equals(s); //true //arg = skipVariablePlusAssign(arg); if ((arg).branchContains(TokenTypes.PLUS_ASSIGN) || (arg).branchContains(TokenTypes.IDENT)) { return false; } //must be just String literals if got here return true; } /** * Skips over an inner assign portion of an argument expression. * @param aCurrentAST current token in the argument expression * @return the next relevant token */ private DetailAST skipVariableAssign(final DetailAST aCurrentAST) { if ((aCurrentAST.getType() == TokenTypes.ASSIGN) && (aCurrentAST.getFirstChild().getType() == TokenTypes.IDENT)) { return aCurrentAST.getFirstChild().getNextSibling(); } return aCurrentAST; } /** * Whether to ignore checking {@code String.equalsIgnoreCase(String)}. * @param aNewValue whether to ignore checking * {@code String.equalsIgnoreCase(String)}. */ public void setIgnoreEqualsIgnoreCase(boolean aNewValue) { mIgnoreEqualsIgnoreCase = aNewValue; } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/EqualsHashCodeCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/EqualsHashCodeCheck.java100644 0 0 12155 12026051051 31231 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import antlr.collections.AST; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.Map; import java.util.Set; /** *

* Checks that classes that override equals() also override hashCode(). *

*

* Rationale: The contract of equals() and hashCode() requires that * equal objects have the same hashCode. Hence, whenever you override * equals() you must override hashCode() to ensure that your class can * be used in collections that are hash based. *

*

* An example of how to configure the check is: *

*
 * <module name="EqualsHashCode"/>
 * 
* @author lkuehne */ public class EqualsHashCodeCheck extends Check { // implementation note: we have to use the following members to // keep track of definitions in different inner classes /** maps OBJ_BLOCK to the method definition of equals() */ private final Map mObjBlockEquals = Maps.newHashMap(); /** the set of OBJ_BLOCKs that contain a definition of hashCode() */ private final Set mObjBlockWithHashCode = Sets.newHashSet(); @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.METHOD_DEF}; } @Override public void beginTree(DetailAST aRootAST) { mObjBlockEquals.clear(); mObjBlockWithHashCode.clear(); } @Override public void visitToken(DetailAST aAST) { final DetailAST modifiers = aAST.getFirstChild(); final AST type = aAST.findFirstToken(TokenTypes.TYPE); final AST methodName = aAST.findFirstToken(TokenTypes.IDENT); final DetailAST parameters = aAST.findFirstToken(TokenTypes.PARAMETERS); if ((type.getFirstChild().getType() == TokenTypes.LITERAL_BOOLEAN) && "equals".equals(methodName.getText()) && modifiers.branchContains(TokenTypes.LITERAL_PUBLIC) && (parameters.getChildCount() == 1) && isObjectParam(parameters.getFirstChild()) ) { mObjBlockEquals.put(aAST.getParent(), aAST); } else if ((type.getFirstChild().getType() == TokenTypes.LITERAL_INT) && "hashCode".equals(methodName.getText()) && modifiers.branchContains(TokenTypes.LITERAL_PUBLIC) && (parameters.getFirstChild() == null)) // no params { mObjBlockWithHashCode.add(aAST.getParent()); } } /** * Determines if an AST is a formal param of type Object (or subclass). * @param aFirstChild the AST to check * @return true iff aFirstChild is a parameter of an Object type. */ private boolean isObjectParam(AST aFirstChild) { final AST modifiers = aFirstChild.getFirstChild(); final AST type = modifiers.getNextSibling(); switch (type.getFirstChild().getType()) { case TokenTypes.LITERAL_BOOLEAN: case TokenTypes.LITERAL_BYTE: case TokenTypes.LITERAL_CHAR: case TokenTypes.LITERAL_DOUBLE: case TokenTypes.LITERAL_FLOAT: case TokenTypes.LITERAL_INT: case TokenTypes.LITERAL_LONG: case TokenTypes.LITERAL_SHORT: return false; default: return true; } } @Override public void finishTree(DetailAST aRootAST) { final Set equalsDefs = mObjBlockEquals.keySet(); for (DetailAST objBlock : equalsDefs) { if (!mObjBlockWithHashCode.contains(objBlock)) { final DetailAST equalsAST = mObjBlockEquals.get(objBlock); log(equalsAST.getLineNo(), equalsAST.getColumnNo(), "equals.noHashCode"); } } mObjBlockEquals.clear(); mObjBlockWithHashCode.clear(); } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCh100644 0 0 13615 12026051051 31470 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; /** *

* Checks if any class or object member explicitly initialized * to default for its type value (null for object * references, zero for numeric types and char * and false for boolean. *

*

* Rationale: each instance variable gets * initialized twice, to the same value. Java * initializes each instance variable to its default * value (0 or null) before performing any * initialization specified in the code. So in this case, * x gets initialized to 0 twice, and bar gets initialized * to null twice. So there is a minor inefficiency. This style of * coding is a hold-over from C/C++ style coding, * and it shows that the developer isn't really confident that * Java really initializes instance variables to default * values. *

* * @author o_sukhodolsky */ public class ExplicitInitializationCheck extends Check { @Override public final int[] getDefaultTokens() { return new int[] {TokenTypes.VARIABLE_DEF}; } @Override public final int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aAST) { // do not check local variables and // fields declared in interface/annotations if (ScopeUtils.isLocalVariableDef(aAST) || ScopeUtils.inInterfaceOrAnnotationBlock(aAST)) { return; } final DetailAST assign = aAST.findFirstToken(TokenTypes.ASSIGN); if (assign == null) { // no assign - no check return; } final DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS); if ((modifiers != null) && modifiers.branchContains(TokenTypes.FINAL)) { // do not check final variables return; } final DetailAST type = aAST.findFirstToken(TokenTypes.TYPE); final DetailAST ident = aAST.findFirstToken(TokenTypes.IDENT); final DetailAST exprStart = assign.getFirstChild().getFirstChild(); if (isObjectType(type) && (exprStart.getType() == TokenTypes.LITERAL_NULL)) { log(ident, "explicit.init", ident.getText(), "null"); } final int primitiveType = type.getFirstChild().getType(); if ((primitiveType == TokenTypes.LITERAL_BOOLEAN) && (exprStart.getType() == TokenTypes.LITERAL_FALSE)) { log(ident, "explicit.init", ident.getText(), "false"); } if (isNumericType(primitiveType) && isZero(exprStart)) { log(ident, "explicit.init", ident.getText(), "0"); } if ((primitiveType == TokenTypes.LITERAL_CHAR) && (isZero(exprStart) || ((exprStart.getType() == TokenTypes.CHAR_LITERAL) && "'\\0'".equals(exprStart.getText())))) { log(ident, "explicit.init", ident.getText(), "\\0"); } } /** * Determines if a giiven type is an object type. * @param aType type to check. * @return true if it is an object type. */ private boolean isObjectType(DetailAST aType) { final int type = aType.getFirstChild().getType(); return ((type == TokenTypes.IDENT) || (type == TokenTypes.DOT) || (type == TokenTypes.ARRAY_DECLARATOR)); } /** * Determine if a given type is a numeric type. * @param aType code of the type for check. * @return true if it's a numeric type. * @see TokenTypes */ private boolean isNumericType(int aType) { return ((aType == TokenTypes.LITERAL_BYTE) || (aType == TokenTypes.LITERAL_SHORT) || (aType == TokenTypes.LITERAL_INT) || (aType == TokenTypes.LITERAL_FLOAT) || (aType == TokenTypes.LITERAL_LONG) || (aType == TokenTypes.LITERAL_DOUBLE)); } /** * @param aExpr node to check. * @return true if given node contains numeric constant for zero. */ private boolean isZero(DetailAST aExpr) { final int type = aExpr.getType(); switch (type) { case TokenTypes.NUM_FLOAT: case TokenTypes.NUM_DOUBLE: case TokenTypes.NUM_INT: case TokenTypes.NUM_LONG: final String text = aExpr.getText(); return (0 == CheckUtils.parseFloat(text, type)); default: return false; } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.java100644 0 0 32354 12026051051 30622 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; /** * Checks for fall through in switch statements * Finds locations where a case contains Java code - * but lacks a break, return, throw or continue statement. * *

* The check honors special comments to suppress warnings about * the fall through. By default the comments "fallthru", * "fall through", "falls through" and "fallthrough" are recognized. *

*

* The following fragment of code will NOT trigger the check, * because of the comment "fallthru". *

*
 * case 3:
 *     x = 2;
 *     // fallthru
 * case 4:
 * 
*

* The recognized relief comment can be configured with the property * reliefPattern. Default value of this regular expression * is "fallthru|fall through|fallthrough|falls through". *

*

* An example of how to configure the check is: *

*
 * <module name="FallThrough">
 *     <property name="reliefPattern"
 *                  value="Fall Through"/>
 * </module>
 * 
* * @author o_sukhodolsky */ public class FallThroughCheck extends Check { /** Do we need to check last case group. */ private boolean mCheckLastGroup; /** Relief pattern to allow fall throught to the next case branch. */ private String mReliefPattern = "fallthru|falls? ?through"; /** Relief regexp. */ private Pattern mRegExp; /** Creates new instance of the check. */ public FallThroughCheck() { // do nothing } @Override public int[] getDefaultTokens() { return new int[]{TokenTypes.CASE_GROUP}; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } /** * Set the relief pattern. * * @param aPattern * The regular expression pattern. */ public void setReliefPattern(String aPattern) { mReliefPattern = aPattern; } /** * Configures whether we need to check last case group or not. * @param aValue new value of the property. */ public void setCheckLastCaseGroup(boolean aValue) { mCheckLastGroup = aValue; } @Override public void init() { super.init(); mRegExp = Utils.getPattern(mReliefPattern); } @Override public void visitToken(DetailAST aAST) { final DetailAST nextGroup = aAST.getNextSibling(); final boolean isLastGroup = ((nextGroup == null) || (nextGroup.getType() != TokenTypes.CASE_GROUP)); if (isLastGroup && !mCheckLastGroup) { // we do not need to check last group return; } final DetailAST slist = aAST.findFirstToken(TokenTypes.SLIST); if (!isTerminated(slist, true, true)) { if (!hasFallTruComment(aAST, nextGroup)) { if (!isLastGroup) { log(nextGroup, "fall.through"); } else { log(aAST, "fall.through.last"); } } } } /** * Checks if a given subtree terminated by return, throw or, * if allowed break, continue. * @param aAST root of given subtree * @param aUseBreak should we consider break as terminator. * @param aUseContinue should we consider continue as terminator. * @return true if the subtree is terminated. */ private boolean isTerminated(final DetailAST aAST, boolean aUseBreak, boolean aUseContinue) { switch (aAST.getType()) { case TokenTypes.LITERAL_RETURN: case TokenTypes.LITERAL_THROW: return true; case TokenTypes.LITERAL_BREAK: return aUseBreak; case TokenTypes.LITERAL_CONTINUE: return aUseContinue; case TokenTypes.SLIST: return checkSlist(aAST, aUseBreak, aUseContinue); case TokenTypes.LITERAL_IF: return checkIf(aAST, aUseBreak, aUseContinue); case TokenTypes.LITERAL_FOR: case TokenTypes.LITERAL_WHILE: case TokenTypes.LITERAL_DO: return checkLoop(aAST); case TokenTypes.LITERAL_TRY: return checkTry(aAST, aUseBreak, aUseContinue); case TokenTypes.LITERAL_SWITCH: return checkSwitch(aAST, aUseContinue); default: return false; } } /** * Checks if a given SLIST terminated by return, throw or, * if allowed break, continue. * @param aAST SLIST to check * @param aUseBreak should we consider break as terminator. * @param aUseContinue should we consider continue as terminator. * @return true if SLIST is terminated. */ private boolean checkSlist(final DetailAST aAST, boolean aUseBreak, boolean aUseContinue) { DetailAST lastStmt = aAST.getLastChild(); if (lastStmt == null) { // if last case in switch is empty then slist is empty // since this is a last case it is not a fall-through return true; } if (lastStmt.getType() == TokenTypes.RCURLY) { lastStmt = lastStmt.getPreviousSibling(); } return (lastStmt != null) && isTerminated(lastStmt, aUseBreak, aUseContinue); } /** * Checks if a given IF terminated by return, throw or, * if allowed break, continue. * @param aAST IF to check * @param aUseBreak should we consider break as terminator. * @param aUseContinue should we consider continue as terminator. * @return true if IF is terminated. */ private boolean checkIf(final DetailAST aAST, boolean aUseBreak, boolean aUseContinue) { final DetailAST thenStmt = aAST.findFirstToken(TokenTypes.RPAREN) .getNextSibling(); final DetailAST elseStmt = thenStmt.getNextSibling(); boolean isTerminated = isTerminated(thenStmt, aUseBreak, aUseContinue); if (isTerminated && (elseStmt != null)) { isTerminated = isTerminated(elseStmt.getFirstChild(), aUseBreak, aUseContinue); } return isTerminated; } /** * Checks if a given loop terminated by return, throw or, * if allowed break, continue. * @param aAST loop to check * @return true if loop is terminated. */ private boolean checkLoop(final DetailAST aAST) { DetailAST loopBody = null; if (aAST.getType() == TokenTypes.LITERAL_DO) { final DetailAST lparen = aAST.findFirstToken(TokenTypes.DO_WHILE); loopBody = lparen.getPreviousSibling(); } else { final DetailAST rparen = aAST.findFirstToken(TokenTypes.RPAREN); loopBody = rparen.getNextSibling(); } return isTerminated(loopBody, false, false); } /** * Checks if a given try/catch/finally block terminated by return, throw or, * if allowed break, continue. * @param aAST loop to check * @param aUseBreak should we consider break as terminator. * @param aUseContinue should we consider continue as terminator. * @return true if try/cath/finally block is terminated. */ private boolean checkTry(final DetailAST aAST, boolean aUseBreak, boolean aUseContinue) { final DetailAST finalStmt = aAST.getLastChild(); if (finalStmt.getType() == TokenTypes.LITERAL_FINALLY) { return isTerminated(finalStmt.findFirstToken(TokenTypes.SLIST), aUseBreak, aUseContinue); } boolean isTerminated = isTerminated(aAST.getFirstChild(), aUseBreak, aUseContinue); DetailAST catchStmt = aAST.findFirstToken(TokenTypes.LITERAL_CATCH); while ((catchStmt != null) && isTerminated) { final DetailAST catchBody = catchStmt.findFirstToken(TokenTypes.SLIST); isTerminated &= isTerminated(catchBody, aUseBreak, aUseContinue); catchStmt = catchStmt.getNextSibling(); } return isTerminated; } /** * Checks if a given switch terminated by return, throw or, * if allowed break, continue. * @param aAST loop to check * @param aUseContinue should we consider continue as terminator. * @return true if switch is terminated. */ private boolean checkSwitch(final DetailAST aAST, boolean aUseContinue) { DetailAST caseGroup = aAST.findFirstToken(TokenTypes.CASE_GROUP); boolean isTerminated = (caseGroup != null); while (isTerminated && (caseGroup != null) && (caseGroup.getType() != TokenTypes.RCURLY)) { final DetailAST caseBody = caseGroup.findFirstToken(TokenTypes.SLIST); isTerminated &= isTerminated(caseBody, false, aUseContinue); caseGroup = caseGroup.getNextSibling(); } return isTerminated; } /** * Determines if the fall through case between aCurrentCase and * aNextCase is reliefed by a appropriate comment. * * @param aCurrentCase AST of the case that falls through to the next case. * @param aNextCase AST of the next case. * @return True if a relief comment was found */ private boolean hasFallTruComment(DetailAST aCurrentCase, DetailAST aNextCase) { final int startLineNo = aCurrentCase.getLineNo(); final int endLineNo = aNextCase.getLineNo(); final int endColNo = aNextCase.getColumnNo(); /* * Remember: The lines number returned from the AST is 1-based, but * the lines number in this array are 0-based. So you will often * see a "lineNo-1" etc. */ final String[] lines = getLines(); /* * Handle: * case 1: * /+ FALLTHRU +/ case 2: * .... * and * switch(i) { * default: * /+ FALLTHRU +/} */ final String linepart = lines[endLineNo - 1].substring(0, endColNo); if (commentMatch(mRegExp, linepart, endLineNo)) { return true; } /* * Handle: * case 1: * ..... * // FALLTHRU * case 2: * .... * and * switch(i) { * default: * // FALLTHRU * } */ for (int i = endLineNo - 2; i > startLineNo - 1; i--) { if (lines[i].trim().length() != 0) { return commentMatch(mRegExp, lines[i], i + 1); } } // Well -- no relief comment found. return false; } /** * Does a regular expression match on the given line and checks that a * possible match is within a comment. * @param aPattern The regular expression pattern to use. * @param aLine The line of test to do the match on. * @param aLineNo The line number in the file. * @return True if a match was found inside a comment. */ private boolean commentMatch(Pattern aPattern, String aLine, int aLineNo ) { final Matcher matcher = aPattern.matcher(aLine); final boolean hit = matcher.find(); if (hit) { final int startMatch = matcher.start(); // -1 because it returns the char position beyond the match final int endMatch = matcher.end() - 1; return getFileContents().hasIntersectionWithComment(aLineNo, startMatch, aLineNo, endMatch); } return false; } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.100644 0 0 16550 12026051051 31213 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.HashMap; import java.util.Map; /** *

* Ensures that local variables that never get their values changed, * must be declared final. *

*

* An example of how to configure the check is: *

*
 * <module name="FinalLocalVariable">
 *     <property name="token" value="VARIABLE_DEF"/>
 * </module>
 * 
* @author k_gibbs, r_auckenthaler */ public class FinalLocalVariableCheck extends Check { /** Scope Stack */ private final FastStack> mScopeStack = FastStack.newInstance(); @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.IDENT, TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.VARIABLE_DEF, TokenTypes.INSTANCE_INIT, TokenTypes.STATIC_INIT, TokenTypes.LITERAL_FOR, TokenTypes.SLIST, TokenTypes.OBJBLOCK, }; } @Override public int[] getAcceptableTokens() { return new int[] { TokenTypes.VARIABLE_DEF, TokenTypes.PARAMETER_DEF, }; } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.IDENT, TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.INSTANCE_INIT, TokenTypes.STATIC_INIT, TokenTypes.LITERAL_FOR, TokenTypes.SLIST, TokenTypes.OBJBLOCK, }; } @Override public void visitToken(DetailAST aAST) { switch(aAST.getType()) { case TokenTypes.OBJBLOCK: case TokenTypes.SLIST: case TokenTypes.LITERAL_FOR: case TokenTypes.METHOD_DEF: case TokenTypes.CTOR_DEF: case TokenTypes.STATIC_INIT: case TokenTypes.INSTANCE_INIT: mScopeStack.push(new HashMap()); break; case TokenTypes.PARAMETER_DEF: if (ScopeUtils.inInterfaceBlock(aAST) || inAbstractMethod(aAST)) { break; } case TokenTypes.VARIABLE_DEF: if ((aAST.getParent().getType() != TokenTypes.OBJBLOCK) && (aAST.getParent().getType() != TokenTypes.FOR_EACH_CLAUSE)) { insertVariable(aAST); } break; case TokenTypes.IDENT: final int parentType = aAST.getParent().getType(); if ((TokenTypes.POST_DEC == parentType) || (TokenTypes.DEC == parentType) || (TokenTypes.POST_INC == parentType) || (TokenTypes.INC == parentType) || (TokenTypes.ASSIGN == parentType) || (TokenTypes.PLUS_ASSIGN == parentType) || (TokenTypes.MINUS_ASSIGN == parentType) || (TokenTypes.DIV_ASSIGN == parentType) || (TokenTypes.STAR_ASSIGN == parentType) || (TokenTypes.MOD_ASSIGN == parentType) || (TokenTypes.SR_ASSIGN == parentType) || (TokenTypes.BSR_ASSIGN == parentType) || (TokenTypes.SL_ASSIGN == parentType) || (TokenTypes.BXOR_ASSIGN == parentType) || (TokenTypes.BOR_ASSIGN == parentType) || (TokenTypes.BAND_ASSIGN == parentType)) { // TODO: is there better way to check is aAST // in left part of assignment? if (aAST.getParent().getFirstChild() == aAST) { removeVariable(aAST); } } break; default: } } /** * Determines whether an AST is a descentant of an abstract method. * @param aAST the AST to check. * @return true if aAST is a descentant of an abstract method. */ private boolean inAbstractMethod(DetailAST aAST) { DetailAST parent = aAST.getParent(); while (parent != null) { if (parent.getType() == TokenTypes.METHOD_DEF) { final DetailAST modifiers = parent.findFirstToken(TokenTypes.MODIFIERS); return modifiers.branchContains(TokenTypes.ABSTRACT); } parent = parent.getParent(); } return false; } /** * Inserts a variable at the topmost scope stack * @param aAST the variable to insert */ private void insertVariable(DetailAST aAST) { if (!aAST.branchContains(TokenTypes.FINAL)) { final Map state = mScopeStack.peek(); final DetailAST ast = aAST.findFirstToken(TokenTypes.IDENT); state.put(ast.getText(), ast); } } /** * Removes the variable from the Stacks * @param aAST Variable to remove */ private void removeVariable(DetailAST aAST) { for (int i = mScopeStack.size() - 1; i >= 0; i--) { final Map state = mScopeStack.peek(i); final Object obj = state.remove(aAST.getText()); if (obj != null) { break; } } } @Override public void leaveToken(DetailAST aAST) { super.leaveToken(aAST); switch(aAST.getType()) { case TokenTypes.OBJBLOCK: case TokenTypes.SLIST: case TokenTypes.LITERAL_FOR: case TokenTypes.CTOR_DEF: case TokenTypes.STATIC_INIT: case TokenTypes.INSTANCE_INIT: case TokenTypes.METHOD_DEF: final Map state = mScopeStack.pop(); for (DetailAST var : state.values()) { log(var.getLineNo(), var.getColumnNo(), "final.variable", var .getText()); } break; default: } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java100644 0 0 40475 12026051050 30544 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; /** *

Checks that a local variable or a parameter does not shadow * a field that is defined in the same class. *

*

* An example of how to configure the check is: *

*
 * <module name="HiddenField"/>
 * 
*

* An example of how to configure the check so that it checks variables but not * parameters is: *

*
 * <module name="HiddenField">
 *    <property name="tokens" value="VARIABLE_DEF"/>
 * </module>
 * 
*

* An example of how to configure the check so that it ignores the parameter of * a setter method is: *

*
 * <module name="HiddenField">
 *    <property name="ignoreSetter" value="true"/>
 * </module>
 * 
*

* An example of how to configure the check so that it ignores constructor * parameters is: *

*
 * <module name="HiddenField">
 *    <property name="ignoreConstructorParameter" value="true"/>
 * </module>
 * 
* @author Rick Giles * @version 1.0 */ public class HiddenFieldCheck extends Check { /** stack of sets of field names, * one for each class of a set of nested classes. */ private FieldFrame mCurrentFrame; /** the regexp to match against */ private Pattern mRegexp; /** controls whether to check the parameter of a property setter method */ private boolean mIgnoreSetter; /** controls whether to check the parameter of a constructor */ private boolean mIgnoreConstructorParameter; /** controls whether to check the parameter of abstract methods. */ private boolean mIgnoreAbstractMethods; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.VARIABLE_DEF, TokenTypes.PARAMETER_DEF, TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF, TokenTypes.ENUM_CONSTANT_DEF, }; } @Override public int[] getAcceptableTokens() { return new int[] { TokenTypes.VARIABLE_DEF, TokenTypes.PARAMETER_DEF, }; } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF, TokenTypes.ENUM_CONSTANT_DEF, }; } @Override public void beginTree(DetailAST aRootAST) { mCurrentFrame = new FieldFrame(null, true); } @Override public void visitToken(DetailAST aAST) { if ((aAST.getType() == TokenTypes.VARIABLE_DEF) || (aAST.getType() == TokenTypes.PARAMETER_DEF)) { processVariable(aAST); return; } //A more thorough check of enum constant class bodies is //possible (checking for hidden fields against the enum //class body in addition to enum constant class bodies) //but not attempted as it seems out of the scope of this //check. final DetailAST typeMods = aAST.findFirstToken(TokenTypes.MODIFIERS); final boolean isStaticInnerType = (typeMods != null) && typeMods.branchContains(TokenTypes.LITERAL_STATIC); final FieldFrame frame = new FieldFrame(mCurrentFrame, isStaticInnerType); //add fields to container final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK); // enum constants may not have bodies if (objBlock != null) { DetailAST child = objBlock.getFirstChild(); while (child != null) { if (child.getType() == TokenTypes.VARIABLE_DEF) { final String name = child.findFirstToken(TokenTypes.IDENT).getText(); final DetailAST mods = child.findFirstToken(TokenTypes.MODIFIERS); if (mods.branchContains(TokenTypes.LITERAL_STATIC)) { frame.addStaticField(name); } else { frame.addInstanceField(name); } } child = child.getNextSibling(); } } // push container mCurrentFrame = frame; } @Override public void leaveToken(DetailAST aAST) { if ((aAST.getType() == TokenTypes.CLASS_DEF) || (aAST.getType() == TokenTypes.ENUM_DEF) || (aAST.getType() == TokenTypes.ENUM_CONSTANT_DEF)) { //pop mCurrentFrame = mCurrentFrame.getParent(); } } /** * Process a variable token. * Check whether a local variable or parameter shadows a field. * Store a field for later comparison with local variables and parameters. * @param aAST the variable token. */ private void processVariable(DetailAST aAST) { if (ScopeUtils.inInterfaceOrAnnotationBlock(aAST) || (!ScopeUtils.isLocalVariableDef(aAST) && (aAST.getType() != TokenTypes.PARAMETER_DEF))) { // do nothing return; } //local variable or parameter. Does it shadow a field? final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT); final String name = nameAST.getText(); if ((mCurrentFrame.containsStaticField(name) || (!inStatic(aAST) && mCurrentFrame.containsInstanceField(name))) && ((mRegexp == null) || (!getRegexp().matcher(name).find())) && !isIgnoredSetterParam(aAST, name) && !isIgnoredConstructorParam(aAST) && !isIgnoredParamOfAbstractMethod(aAST)) { log(nameAST, "hidden.field", name); } } /** * Determines whether an AST node is in a static method or static * initializer. * @param aAST the node to check. * @return true if aAST is in a static method or a static block; */ private static boolean inStatic(DetailAST aAST) { DetailAST parent = aAST.getParent(); while (parent != null) { switch (parent.getType()) { case TokenTypes.STATIC_INIT: return true; case TokenTypes.METHOD_DEF: final DetailAST mods = parent.findFirstToken(TokenTypes.MODIFIERS); return mods.branchContains(TokenTypes.LITERAL_STATIC); default: parent = parent.getParent(); } } return false; } /** * Decides whether to ignore an AST node that is the parameter of a * setter method, where the property setter method for field 'xyz' has * name 'setXyz', one parameter named 'xyz', and return type void. * @param aAST the AST to check. * @param aName the name of aAST. * @return true if aAST should be ignored because check property * ignoreSetter is true and aAST is the parameter of a setter method. */ private boolean isIgnoredSetterParam(DetailAST aAST, String aName) { if (aAST.getType() != TokenTypes.PARAMETER_DEF || !mIgnoreSetter) { return false; } //single parameter? final DetailAST parametersAST = aAST.getParent(); if (parametersAST.getChildCount() != 1) { return false; } //method parameter, not constructor parameter? final DetailAST methodAST = parametersAST.getParent(); if (methodAST.getType() != TokenTypes.METHOD_DEF) { return false; } //void? final DetailAST typeAST = methodAST.findFirstToken(TokenTypes.TYPE); if (!typeAST.branchContains(TokenTypes.LITERAL_VOID)) { return false; } //property setter name? final String methodName = methodAST.findFirstToken(TokenTypes.IDENT).getText(); final String expectedName = "set" + capitalize(aName); return methodName.equals(expectedName); } /** * Capitalizes a given property name the way we expect to see it in * a setter name. * @param aName a property name * @return capitalized property name */ private static String capitalize(final String aName) { if (aName == null || aName.length() == 0) { return aName; } // we should not capitalize the first character if the second // one is a capital one, since according to JavaBeans spec // setXYzz() is a setter for XYzz property, not for xYzz one. if (aName.length() > 1 && Character.isUpperCase(aName.charAt(1))) { return aName; } return aName.substring(0, 1).toUpperCase() + aName.substring(1); } /** * Decides whether to ignore an AST node that is the parameter of a * constructor. * @param aAST the AST to check. * @return true if aAST should be ignored because check property * ignoreConstructorParameter is true and aAST is a constructor parameter. */ private boolean isIgnoredConstructorParam(DetailAST aAST) { if ((aAST.getType() != TokenTypes.PARAMETER_DEF) || !mIgnoreConstructorParameter) { return false; } final DetailAST parametersAST = aAST.getParent(); final DetailAST constructorAST = parametersAST.getParent(); return (constructorAST.getType() == TokenTypes.CTOR_DEF); } /** * Decides whether to ignore an AST node that is the parameter of an * abstract method. * @param aAST the AST to check. * @return true if aAST should be ignored because check property * ignoreAbstactMethods is true and aAST is a parameter of abstract * methods. */ private boolean isIgnoredParamOfAbstractMethod(DetailAST aAST) { if ((aAST.getType() != TokenTypes.PARAMETER_DEF) || !mIgnoreAbstractMethods) { return false; } final DetailAST method = aAST.getParent().getParent(); if (method.getType() != TokenTypes.METHOD_DEF) { return false; } final DetailAST mods = method.findFirstToken(TokenTypes.MODIFIERS); return ((mods != null) && mods.branchContains(TokenTypes.ABSTRACT)); } /** * Set the ignore format to the specified regular expression. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setIgnoreFormat(String aFormat) throws ConversionException { try { mRegexp = Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } /** * Set whether to ignore the parameter of a property setter method. * @param aIgnoreSetter decide whether to ignore the parameter of * a property setter method. */ public void setIgnoreSetter(boolean aIgnoreSetter) { mIgnoreSetter = aIgnoreSetter; } /** * Set whether to ignore constructor parameters. * @param aIgnoreConstructorParameter decide whether to ignore * constructor parameters. */ public void setIgnoreConstructorParameter( boolean aIgnoreConstructorParameter) { mIgnoreConstructorParameter = aIgnoreConstructorParameter; } /** * Set whether to ignore parameters of abstract methods. * @param aIgnoreAbstractMethods decide whether to ignore * parameters of abstract methods. */ public void setIgnoreAbstractMethods( boolean aIgnoreAbstractMethods) { mIgnoreAbstractMethods = aIgnoreAbstractMethods; } /** @return the regexp to match against */ public Pattern getRegexp() { return mRegexp; } /** * Holds the names of static and instance fields of a type. * @author Rick Giles * Describe class FieldFrame * @author Rick Giles * @version Oct 26, 2003 */ private static class FieldFrame { /** is this a static inner type */ private final boolean mStaticType; /** parent frame. */ private final FieldFrame mParent; /** set of instance field names */ private final Set mInstanceFields = Sets.newHashSet(); /** set of static field names */ private final Set mStaticFields = Sets.newHashSet(); /** Creates new frame. * @param aStaticType is this a static inner type (class or enum). * @param aParent parent frame. */ public FieldFrame(FieldFrame aParent, boolean aStaticType) { mParent = aParent; mStaticType = aStaticType; } /** Is this frame for static inner type. * @return is this field frame for static inner type. */ boolean isStaticType() { return mStaticType; } /** * Adds an instance field to this FieldFrame. * @param aField the name of the instance field. */ public void addInstanceField(String aField) { mInstanceFields.add(aField); } /** * Adds a static field to this FieldFrame. * @param aField the name of the instance field. */ public void addStaticField(String aField) { mStaticFields.add(aField); } /** * Determines whether this FieldFrame contains an instance field. * @param aField the field to check. * @return true if this FieldFrame contains instance field aField. */ public boolean containsInstanceField(String aField) { return mInstanceFields.contains(aField) || !isStaticType() && (mParent != null) && mParent.containsInstanceField(aField); } /** * Determines whether this FieldFrame contains a static field. * @param aField the field to check. * @return true if this FieldFrame contains static field aField. */ public boolean containsStaticField(String aField) { return mStaticFields.contains(aField) || (mParent != null) && mParent.containsStaticField(aField); } /** * Getter for parent frame. * @return parent frame. */ public FieldFrame getParent() { return mParent; } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/IllegalCatchCheck.java100644 0 0 5217 12026051050 30674 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; /** * Catching java.lang.Exception, java.lang.Error or java.lang.RuntimeException * is almost never acceptable. * @author Simon Harris */ public final class IllegalCatchCheck extends AbstractIllegalCheck { /** Creates new instance of the check. */ public IllegalCatchCheck() { super(new String[] {"Exception", "Error", "RuntimeException", "Throwable", "java.lang.Error", "java.lang.Exception", "java.lang.RuntimeException", "java.lang.Throwable", }); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.LITERAL_CATCH}; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aDetailAST) { final DetailAST paramDef = aDetailAST.findFirstToken(TokenTypes.PARAMETER_DEF); final DetailAST excType = paramDef.findFirstToken(TokenTypes.TYPE); final FullIdent ident = CheckUtils.createFullType(excType); if (isIllegalClassName(ident.getText())) { log(aDetailAST, "illegal.catch", ident.getText()); } } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationChec100644 0 0 26151 12026051050 31423 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import antlr.collections.AST; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.Set; import java.util.StringTokenizer; // TODO: Clean up potential duplicate code here and in UnusedImportsCheck /** *

* Checks for illegal instantiations where a factory method is preferred. *

*

* Rationale: Depending on the project, for some classes it might be * preferable to create instances through factory methods rather than * calling the constructor. *

*

* A simple example is the java.lang.Boolean class, to save memory and CPU * cycles it is preferable to use the predeifined constants TRUE and FALSE. * Constructor invocations should be replaced by calls to Boolean.valueOf(). *

*

* Some extremely performance sensitive projects may require the use of factory * methods for other classes as well, to enforce the usage of number caches or * object pools. *

*

* Limitations: It is currently not possible to specify array classes. *

*

* An example of how to configure the check is: *

*
 * <module name="IllegalInstantiation"/>
 * 
* @author lkuehne */ public class IllegalInstantiationCheck extends Check { /** Set of fully qualified classnames. E.g. "java.lang.Boolean" */ private final Set mIllegalClasses = Sets.newHashSet(); /** name of the package */ private String mPkgName; /** the imports for the file */ private final Set mImports = Sets.newHashSet(); /** the class names defined in the file */ private final Set mClassNames = Sets.newHashSet(); /** the instantiations in the file */ private final Set mInstantiations = Sets.newHashSet(); @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.IMPORT, TokenTypes.LITERAL_NEW, TokenTypes.PACKAGE_DEF, TokenTypes.CLASS_DEF, }; } @Override public int[] getAcceptableTokens() { // Return an empty array to not allow user to change configuration. return new int[] {}; } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.IMPORT, TokenTypes.LITERAL_NEW, TokenTypes.PACKAGE_DEF, }; } @Override public void beginTree(DetailAST aRootAST) { super.beginTree(aRootAST); mPkgName = null; mImports.clear(); mInstantiations.clear(); mClassNames.clear(); } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.LITERAL_NEW: processLiteralNew(aAST); break; case TokenTypes.PACKAGE_DEF: processPackageDef(aAST); break; case TokenTypes.IMPORT: processImport(aAST); break; case TokenTypes.CLASS_DEF: processClassDef(aAST); break; default: throw new IllegalArgumentException("Unknown type " + aAST); } } @Override public void finishTree(DetailAST aRootAST) { for (DetailAST literalNewAST : mInstantiations) { postprocessLiteralNew(literalNewAST); } } /** * Collects classes defined in the source file. Required * to avoid false alarms for local vs. java.lang classes. * * @param aAST the classdef token. */ private void processClassDef(DetailAST aAST) { final DetailAST identToken = aAST.findFirstToken(TokenTypes.IDENT); final String className = identToken.getText(); mClassNames.add(className); } /** * Perform processing for an import token * @param aAST the import token */ private void processImport(DetailAST aAST) { final FullIdent name = FullIdent.createFullIdentBelow(aAST); if (name != null) { // Note: different from UnusedImportsCheck.processImport(), // '.*' imports are also added here mImports.add(name); } } /** * Perform processing for an package token * @param aAST the package token */ private void processPackageDef(DetailAST aAST) { final DetailAST packageNameAST = aAST.getLastChild() .getPreviousSibling(); final FullIdent packageIdent = FullIdent.createFullIdent(packageNameAST); mPkgName = packageIdent.getText(); } /** * Collects a "new" token. * @param aAST the "new" token */ private void processLiteralNew(DetailAST aAST) { mInstantiations.add(aAST); } /** * Processes one of the collected "new" tokens when treewalking * has finished. * @param aAST the "new" token. */ private void postprocessLiteralNew(DetailAST aAST) { final DetailAST typeNameAST = aAST.getFirstChild(); final AST nameSibling = typeNameAST.getNextSibling(); if ((nameSibling != null) && (nameSibling.getType() == TokenTypes.ARRAY_DECLARATOR)) { // aAST == "new Boolean[]" return; } final FullIdent typeIdent = FullIdent.createFullIdent(typeNameAST); final String typeName = typeIdent.getText(); final int lineNo = aAST.getLineNo(); final int colNo = aAST.getColumnNo(); final String fqClassName = getIllegalInstantiation(typeName); if (fqClassName != null) { log(lineNo, colNo, "instantiation.avoid", fqClassName); } } /** * Checks illegal instantiations. * @param aClassName instantiated class, may or may not be qualified * @return the fully qualified class name of aClassName * or null if instantiation of aClassName is OK */ private String getIllegalInstantiation(String aClassName) { final String javaLang = "java.lang."; if (mIllegalClasses.contains(aClassName)) { return aClassName; } final int clsNameLen = aClassName.length(); final int pkgNameLen = (mPkgName == null) ? 0 : mPkgName.length(); for (String illegal : mIllegalClasses) { final int illegalLen = illegal.length(); // class from java.lang if (((illegalLen - javaLang.length()) == clsNameLen) && illegal.endsWith(aClassName) && illegal.startsWith(javaLang)) { // java.lang needs no import, but a class without import might // also come from the same file or be in the same package. // E.g. if a class defines an inner class "Boolean", // the expression "new Boolean()" refers to that class, // not to java.lang.Boolean final boolean isSameFile = mClassNames.contains(aClassName); boolean isSamePackage = false; try { final ClassLoader classLoader = getClassLoader(); if (classLoader != null) { final String fqName = mPkgName + "." + aClassName; classLoader.loadClass(fqName); // no ClassNotFoundException, fqName is a known class isSamePackage = true; } } catch (final ClassNotFoundException ex) { // not a class from the same package isSamePackage = false; } if (!(isSameFile || isSamePackage)) { return illegal; } } // class from same package // the toplevel package (mPkgName == null) is covered by the // "illegalInsts.contains(aClassName)" check above // the test is the "no garbage" version of // illegal.equals(mPkgName + "." + aClassName) if ((mPkgName != null) && (clsNameLen == illegalLen - pkgNameLen - 1) && (illegal.charAt(pkgNameLen) == '.') && illegal.endsWith(aClassName) && illegal.startsWith(mPkgName)) { return illegal; } // import statements for (FullIdent importLineText : mImports) { final String importArg = importLineText.getText(); if (importArg.endsWith(".*")) { final String fqClass = importArg.substring(0, importArg.length() - 1) + aClassName; // assume that illegalInsts only contain existing classes // or else we might create a false alarm here if (mIllegalClasses.contains(fqClass)) { return fqClass; } } else { if (Utils.baseClassname(importArg).equals(aClassName) && mIllegalClasses.contains(importArg)) { return importArg; } } } } return null; } /** * Sets the classes that are illegal to instantiate. * @param aClassNames a comma seperate list of class names */ public void setClasses(String aClassNames) { mIllegalClasses.clear(); final StringTokenizer tok = new StringTokenizer(aClassNames, ","); while (tok.hasMoreTokens()) { mIllegalClasses.add(tok.nextToken()); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/IllegalThrowsCheck.java100644 0 0 7460 12026051050 31142 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.Set; /** * Throwing java.lang.Error or java.lang.RuntimeException * is almost never acceptable. * @author Oliver Burn */ public final class IllegalThrowsCheck extends AbstractIllegalCheck { /** Default ignored method names. */ private static final String[] DEFAULT_IGNORED_METHOD_NAMES = { "finalize", }; /** methods which should be ignored. */ private final Set mIgnoredMethodNames = Sets.newHashSet(); /** Creates new instance of the check. */ public IllegalThrowsCheck() { super(new String[] {"Error", "RuntimeException", "Throwable", "java.lang.Error", "java.lang.RuntimeException", "java.lang.Throwable", }); setIgnoredMethodNames(DEFAULT_IGNORED_METHOD_NAMES); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.LITERAL_THROWS}; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aDetailAST) { DetailAST token = aDetailAST.getFirstChild(); // Check if the method with the given name should be ignored. if (!(shouldIgnoreMethod(aDetailAST.getParent().findFirstToken( TokenTypes.IDENT).getText()))) { while (token != null) { if (token.getType() != TokenTypes.COMMA) { final FullIdent ident = FullIdent.createFullIdent(token); if (isIllegalClassName(ident.getText())) { log(token, "illegal.throw", ident.getText()); } } token = token.getNextSibling(); } } } /** * Check if the method is specified in the ignore method list * @param aName the name to check * @return whether the method with the passed name should be ignored */ private boolean shouldIgnoreMethod(String aName) { return mIgnoredMethodNames.contains(aName); } /** * Set the list of ignore method names. * @param aMethodNames array of ignored method names */ public void setIgnoredMethodNames(String[] aMethodNames) { mIgnoredMethodNames.clear(); for (String element : aMethodNames) { mIgnoredMethodNames.add(element); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenCheck.java100644 0 0 6256 12026051050 30736 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.Set; /** *

* Checks for illegal tokens. *

*

* Rational: Certain language features are often lead to hard to * maintain code or are non-obvious to novice developers. Others * may be discouraged in certain frameworks, such as not having * native methods in EJB components. *

*

* An example of how to configure the check is: *

*
 * <module name="IllegalToken"/>
 * 
*

An example of how to configure the check to forbid * a {@link TokenTypes#LITERAL_NATIVE LITERAL_NATIVE} token is: *

*
 * <module name="IllegalToken">
 *     <property name="tokens" value="LITERAL_NATIVE"/>
 * </module>
 * 
* @author Simon Harris * @author Rick Giles */ public class IllegalTokenCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.LITERAL_SWITCH, TokenTypes.POST_INC, TokenTypes.POST_DEC, }; } @Override public int[] getAcceptableTokens() { // Any tokens set by property 'tokens' are acceptable int[] tokensToCopy = getDefaultTokens(); final Set tokenNames = getTokenNames(); if (!tokenNames.isEmpty()) { tokensToCopy = new int[tokenNames.size()]; int i = 0; for (String name : tokenNames) { tokensToCopy[i] = TokenTypes.getTokenId(name); i++; } } final int[] copy = new int[tokensToCopy.length]; System.arraycopy(tokensToCopy, 0, copy, 0, tokensToCopy.length); return copy; } @Override public void visitToken(DetailAST aAST) { log( aAST.getLineNo(), aAST.getColumnNo(), "illegal.token", aAST.getText()); } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheck.ja100644 0 0 10461 12026051050 31265 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck; import java.util.Set; import java.util.regex.Pattern; /** *

* Checks for illegal token text. *

*

An example of how to configure the check to forbid String literals * containing "a href" is: *

*
 * <module name="IllegalTokenText">
 *     <property name="tokens" value="STRING_LITERAL"/>
 *     <property name="format" value="a href"/>
 * </module>
 * 
*

An example of how to configure the check to forbid leading zeros in an * integer literal, other than zero and a hex literal is: *

*
 * <module name="IllegalTokenText">
 *     <property name="tokens" value="NUM_INT,NUM_LONG"/>
 *     <property name="format" value="^0[^lx]"/>
 *     <property name="ignoreCase" value="true"/>
 * </module>
 * 
* @author Rick Giles */ public class IllegalTokenTextCheck extends AbstractFormatCheck { /** * Custom message for report if illegal regexp found * ignored if empty. */ private String mMessage = ""; /** * Instantiates a new instance. */ public IllegalTokenTextCheck() { super("$^"); // the empty language } @Override public void beginTree(DetailAST aRootAST) { } @Override public int[] getDefaultTokens() { return new int[0]; } @Override public int[] getAcceptableTokens() { // Any tokens set by property 'tokens' are acceptable final Set tokenNames = getTokenNames(); final int[] result = new int[tokenNames.size()]; int i = 0; for (final String name : tokenNames) { result[i] = TokenTypes.getTokenId(name); i++; } return result; } @Override public void visitToken(DetailAST aAST) { final String text = aAST.getText(); if (getRegexp().matcher(text).find()) { String message = getMessage(); if ("".equals(message)) { message = "illegal.token.text"; } log( aAST.getLineNo(), aAST.getColumnNo(), message, getFormat()); } } /** * Setter for message property. * @param aMessage custom message which should be used * to report about violations. */ public void setMessage(String aMessage) { mMessage = (null == aMessage) ? "" : aMessage; } /** * Getter for message property. * @return custom message which should be used * to report about violations. */ public String getMessage() { return mMessage; } /** * Set whether or not the match is case sensitive. * @param aCaseInsensitive true if the match is case insensitive. */ public void setIgnoreCase(boolean aCaseInsensitive) { if (aCaseInsensitive) { setCompileFlags(Pattern.CASE_INSENSITIVE); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheck.java100644 0 0 21224 12026051047 30615 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; import java.util.Set; /** *

* Checks that particular class are never used as types in variable * declarations, return values or parameters. Includes * a pattern check that by default disallows abstract classes. *

*

* Rationale: * Helps reduce coupling on concrete classes. In addition abstract * classes should be thought of a convenience base class * implementations of interfaces and as such are not types themsleves. *

* @author Simon Harris */ public final class IllegalTypeCheck extends AbstractFormatCheck { /** Default value of pattern for illegal class name. */ private static final String DEFAULT_FORMAT = "^(.*[\\.])?Abstract.*$"; /** Abstract classes legal by default. */ private static final String[] DEFAULT_LEGAL_ABSTRACT_NAMES = {}; /** Types illegal by default. */ private static final String[] DEFAULT_ILLEGAL_TYPES = { "GregorianCalendar", "Hashtable", "HashSet", "HashMap", "ArrayList", "LinkedList", "LinkedHashMap", "LinkedHashSet", "TreeSet", "TreeMap", "Vector", "java.util.GregorianCalendar", "java.util.Hashtable", "java.util.HashSet", "java.util.HashMap", "java.util.ArrayList", "java.util.LinkedList", "java.util.LinkedHashMap", "java.util.LinkedHashSet", "java.util.TreeSet", "java.util.TreeMap", "java.util.Vector", }; /** Default ignored method names. */ private static final String[] DEFAULT_IGNORED_METHOD_NAMES = { "getInitialContext", "getEnvironment", }; /** illegal classes. */ private final Set mIllegalClassNames = Sets.newHashSet(); /** legal abstract classes. */ private final Set mLegalAbstractClassNames = Sets.newHashSet(); /** methods which should be ignored. */ private final Set mIgnoredMethodNames = Sets.newHashSet(); /** Creates new instance of the check. */ public IllegalTypeCheck() { super(DEFAULT_FORMAT); setIllegalClassNames(DEFAULT_ILLEGAL_TYPES); setLegalAbstractClassNames(DEFAULT_LEGAL_ABSTRACT_NAMES); setIgnoredMethodNames(DEFAULT_IGNORED_METHOD_NAMES); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.VARIABLE_DEF, TokenTypes.PARAMETER_DEF, TokenTypes.METHOD_DEF, }; } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.METHOD_DEF: visitMethodDef(aAST); break; case TokenTypes.VARIABLE_DEF: visitVariableDef(aAST); break; case TokenTypes.PARAMETER_DEF: visitParameterDef(aAST); break; default: throw new IllegalStateException(aAST.toString()); } } /** * Checks return type of a given method. * @param aAST method for check. */ private void visitMethodDef(DetailAST aAST) { if (isCheckedMethod(aAST)) { checkClassName(aAST); } } /** * Checks type of parameters. * @param aAST parameter list for check. */ private void visitParameterDef(DetailAST aAST) { final DetailAST grandParentAST = aAST.getParent().getParent(); if ((grandParentAST.getType() == TokenTypes.METHOD_DEF) && isCheckedMethod(grandParentAST)) { checkClassName(aAST); } } /** * Checks type of given variable. * @param aAST variable to check. */ private void visitVariableDef(DetailAST aAST) { checkClassName(aAST); } /** * Checks type of given method, parameter or variable. * @param aAST node to check. */ private void checkClassName(DetailAST aAST) { final DetailAST type = aAST.findFirstToken(TokenTypes.TYPE); final FullIdent ident = CheckUtils.createFullType(type); if (isMatchingClassName(ident.getText())) { log(ident.getLineNo(), ident.getColumnNo(), "illegal.type", ident.getText()); } } /** * @param aClassName class name to check. * @return true if given class name is one of illegal classes * or if it matches to abstract class names pattern. */ private boolean isMatchingClassName(String aClassName) { return mIllegalClassNames.contains(aClassName) || (!mLegalAbstractClassNames.contains(aClassName) && getRegexp().matcher(aClassName).find()); } /** * @param aAST method def to check. * @return true if we should check this method. */ private boolean isCheckedMethod(DetailAST aAST) { final String methodName = aAST.findFirstToken(TokenTypes.IDENT).getText(); return !mIgnoredMethodNames.contains(methodName); } /** * Set the list of illegal variable types. * @param aClassNames array of illegal variable types */ public void setIllegalClassNames(String[] aClassNames) { mIllegalClassNames.clear(); for (String name : aClassNames) { mIllegalClassNames.add(name); final int lastDot = name.lastIndexOf("."); if ((lastDot > 0) && (lastDot < (name.length() - 1))) { final String shortName = name.substring(name.lastIndexOf(".") + 1); mIllegalClassNames.add(shortName); } } } /** * Get the list of illegal variable types. * @return array of illegal variable types */ public String[] getIllegalClassNames() { return mIllegalClassNames.toArray( new String[mIllegalClassNames.size()]); } /** * Set the list of ignore method names. * @param aMethodNames array of ignored method names */ public void setIgnoredMethodNames(String[] aMethodNames) { mIgnoredMethodNames.clear(); for (String element : aMethodNames) { mIgnoredMethodNames.add(element); } } /** * Get the list of ignored method names. * @return array of ignored method names */ public String[] getIgnoredMethodNames() { return mIgnoredMethodNames.toArray( new String[mIgnoredMethodNames.size()]); } /** * Set the list of legal abstract class names. * @param aClassNames array of legal abstract class names */ public void setLegalAbstractClassNames(String[] aClassNames) { mLegalAbstractClassNames.clear(); for (String element : aClassNames) { mLegalAbstractClassNames.add(element); } } /** * Get the list of legal abstract class names. * @return array of legal abstract class names */ public String[] getLegalAbstractClassNames() { return mLegalAbstractClassNames.toArray( new String[mLegalAbstractClassNames.size()]); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/InnerAssignmentCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/InnerAssignmentCheck.jav100644 0 0 16566 12026051047 31362 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import java.util.Arrays; import antlr.collections.AST; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** *

* Checks for assignments in subexpressions, such as in * String s = Integer.toString(i = 2);. *

*

* Rationale: With the exception of for iterators, all assignments * should occur in their own toplevel statement to increase readability. * With inner assignments like the above it is difficult to see all places * where a variable is set. *

* * @author lkuehne */ public class InnerAssignmentCheck extends Check { /** * list of allowed AST types from an assignement AST node * towards the root. */ private static final int[][] ALLOWED_ASSIGMENT_CONTEXT = { {TokenTypes.EXPR, TokenTypes.SLIST}, {TokenTypes.VARIABLE_DEF}, {TokenTypes.EXPR, TokenTypes.ELIST, TokenTypes.FOR_INIT}, {TokenTypes.EXPR, TokenTypes.ELIST, TokenTypes.FOR_ITERATOR}, {TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR}, { TokenTypes.RESOURCE, TokenTypes.RESOURCES, TokenTypes.RESOURCE_SPECIFICATION, }, }; /** * list of allowed AST types from an assignement AST node * towards the root. */ private static final int[][] CONTROL_CONTEXT = { {TokenTypes.EXPR, TokenTypes.LITERAL_DO}, {TokenTypes.EXPR, TokenTypes.LITERAL_FOR}, {TokenTypes.EXPR, TokenTypes.LITERAL_WHILE}, {TokenTypes.EXPR, TokenTypes.LITERAL_IF}, {TokenTypes.EXPR, TokenTypes.LITERAL_ELSE}, }; /** * list of allowed AST types from a comparison node (above an assignement) * towards the root. */ private static final int[][] ALLOWED_ASSIGMENT_IN_COMPARISON_CONTEXT = { {TokenTypes.EXPR, TokenTypes.LITERAL_WHILE, }, }; /** * The token types that identify comparison operators. */ private static final int[] COMPARISON_TYPES = { TokenTypes.EQUAL, TokenTypes.GE, TokenTypes.GT, TokenTypes.LE, TokenTypes.LT, TokenTypes.NOT_EQUAL, }; static { Arrays.sort(COMPARISON_TYPES); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.ASSIGN, // '=' TokenTypes.DIV_ASSIGN, // "/=" TokenTypes.PLUS_ASSIGN, // "+=" TokenTypes.MINUS_ASSIGN, //"-=" TokenTypes.STAR_ASSIGN, // "*=" TokenTypes.MOD_ASSIGN, // "%=" TokenTypes.SR_ASSIGN, // ">>=" TokenTypes.BSR_ASSIGN, // ">>>=" TokenTypes.SL_ASSIGN, // "<<=" TokenTypes.BXOR_ASSIGN, // "^=" TokenTypes.BOR_ASSIGN, // "|=" TokenTypes.BAND_ASSIGN, // "&=" }; } @Override public void visitToken(DetailAST aAST) { if (isInContext(aAST, ALLOWED_ASSIGMENT_CONTEXT)) { return; } if (isInNoBraceControlStatement(aAST)) { return; } if (isInWhileIdiom(aAST)) { return; } log(aAST.getLineNo(), aAST.getColumnNo(), "assignment.inner.avoid"); } /** * Determines if aAST is in the body of a flow control statement without * braces. An example of such a statement would be *

*

     * if (y < 0)
     *     x = y;
     * 
*

* This leads to the following AST structure: *

*

     * LITERAL_IF
     *     LPAREN
     *     EXPR // test
     *     RPAREN
     *     EXPR // body
     *     SEMI
     * 
*

* We need to ensure that aAST is in the body and not in the test. * * @param aAST an assignment operator AST * @return whether aAST is in the body of a flow control statement */ private static boolean isInNoBraceControlStatement(DetailAST aAST) { if (!isInContext(aAST, CONTROL_CONTEXT)) { return false; } final DetailAST expr = aAST.getParent(); final AST exprNext = expr.getNextSibling(); return (exprNext != null) && (exprNext.getType() == TokenTypes.SEMI); } /** * Tests whether the given AST is used in the "assignment in while test" * idiom. *

*

     * while ((b = is.read()) != -1) {
     *   // work with b
     * }
     * 
     * @param aAST assignment AST
     * @return whether the context of the assignemt AST indicates the idiom
     */
    private boolean isInWhileIdiom(DetailAST aAST)
    {
        if (!isComparison(aAST.getParent())) {
            return false;
        }
        return isInContext(
                aAST.getParent(), ALLOWED_ASSIGMENT_IN_COMPARISON_CONTEXT);
    }

    /**
     * Checks if an AST is a comparison operator.
     * @param aAST the AST to check
     * @return true iff aAST is a comparison operator.
     */
    private static boolean isComparison(DetailAST aAST)
    {
        final int astType = aAST.getType();
        return (Arrays.binarySearch(COMPARISON_TYPES, astType) >= 0);
    }

    /**
     * Tests whether the provided AST is in
     * one of the given contexts.
     *
     * @param aAST the AST from which to start walking towards root
     * @param aContextSet the contexts to test against.
     *
     * @return whether the parents nodes of aAST match
     * one of the allowed type paths
     */
    private static boolean isInContext(DetailAST aAST, int[][] aContextSet)
    {
        for (int[] element : aContextSet) {
            DetailAST current = aAST;
            final int len = element.length;
            for (int j = 0; j < len; j++) {
                current = current.getParent();
                final int expectedType = element[j];
                if ((current == null) || (current.getType() != expectedType)) {
                    break;
                }
                if (j == len - 1) {
                    return true;
                }
            }
        }
        return false;
    }
}
checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/JUnitTestCaseCheck.java100644      0      0       17574 12026051047  31104 0ustar     0      0 ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2012  Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;

import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;

import com.puppycrawl.tools.checkstyle.checks.CheckUtils;

/**
 * Ensures that the setUp(), tearDown()methods are named correctly,
 * have no arguments, return void and are either public or protected.
 * Also ensures that suite() is named correctly, have no arguments, return
 * junit.framewotk.Test, public and static.
 *
 * Rationale: often times developers will misname one or more of these
 * methods and not realise that the method is not being called.
 *
 * @author Simon Harris
 */
public final class JUnitTestCaseCheck extends Check
{
    /** setUp() method name. */
    private static final String SET_UP_METHOD_NAME = "setUp";
    /** tearDown() method name. */
    private static final String TEAR_DOWN_METHOD_NAME = "tearDown";
    /** suite() method name. */
    private static final String SUITE_METHOD_NAME = "suite";

    @Override
    public int[] getDefaultTokens()
    {
        return new int[] {TokenTypes.METHOD_DEF};
    }

    @Override
    public int[] getRequiredTokens()
    {
        return getDefaultTokens();
    }

    @Override
    public void visitToken(DetailAST aAST)
    {
        switch (aAST.getType()) {
        case TokenTypes.METHOD_DEF:
            visitMethodDef(aAST);
            break;
        default:
            throw new IllegalStateException(aAST.toString());
        }
    }

    /**
     * Checks given method definition.
     * @param aAST a method def node for check
     */
    private void visitMethodDef(DetailAST aAST)
    {
        final String name = aAST.findFirstToken(TokenTypes.IDENT).getText();

        if (name.equalsIgnoreCase(SET_UP_METHOD_NAME)) {
            checkSetUpTearDownMethod(aAST, name, SET_UP_METHOD_NAME);
        }
        else if (name.equalsIgnoreCase(TEAR_DOWN_METHOD_NAME)) {
            checkSetUpTearDownMethod(aAST, name, TEAR_DOWN_METHOD_NAME);
        }
        else if (name.equalsIgnoreCase(SUITE_METHOD_NAME)) {
            checkSuiteMethod(aAST, name);
        }
    }

    /**
     * Checks signature/name of suite().
     * @param aAST method definition node
     * @param aActualName method name
     */
    private void checkSuiteMethod(DetailAST aAST, String aActualName)
    {
        if (!aActualName.equals(SUITE_METHOD_NAME)) {
            log(aAST, "junit.method.name", SUITE_METHOD_NAME);
        }

        if (!isPublicAndStatic(aAST)) {
            log(aAST, "junit.method.public.and.static", SUITE_METHOD_NAME);
        }

        // let's check return type
        final DetailAST typeAST = aAST.findFirstToken(TokenTypes.TYPE);
        final boolean isArray =
            (typeAST.findFirstToken(TokenTypes.ARRAY_DECLARATOR) != null);
        final String type = CheckUtils.createFullType(typeAST).getText();
        if (isArray
            || (!"Test".equals(type)
            && !"junit.framework.Test".equals(type)))
        {
            log(aAST, "junit.method.return.type",
                SUITE_METHOD_NAME, "junit.framework.Test");
        }
        checkParameters(aAST, SUITE_METHOD_NAME);
    }

    /**
     * Checks signature/name of setUp()/tearDown.
     * @param aAST method definition node
     * @param aActualName actual method name
     * @param aExpectedName expected method name
     */
    private void checkSetUpTearDownMethod(DetailAST aAST, String aActualName,
                                          String aExpectedName)
    {
        if (!aActualName.equals(aExpectedName)) {
            log(aAST, "junit.method.name", aActualName, aExpectedName);
        }

        if (!isPublicOrProtected(aAST)) {
            log(aAST, "junit.method.protected.or.public", aExpectedName);
        }

        if (isStatic(aAST)) {
            log(aAST, "junit.method.static", aExpectedName);
        }

        checkReturnValue(aAST, aActualName);
        checkParameters(aAST, aActualName);
    }

    /**
     * Checks that given method returns void.
     * @param aAST method definition node
     * @param aName method name
     */
    private void checkReturnValue(DetailAST aAST, String aName)
    {
        final DetailAST returnValueAST = aAST.findFirstToken(TokenTypes.TYPE);

        if (returnValueAST.findFirstToken(TokenTypes.LITERAL_VOID) == null) {
            log(aAST, "junit.method.return.type", aName, "void");
        }
    }

    /**
     * Checks return value of given method.
     * @param aAST method definition node
     * @param aName method name
     */
    private void checkParameters(DetailAST aAST, String aName)
    {
        final DetailAST parametersAST =
            aAST.findFirstToken(TokenTypes.PARAMETERS);

        if (parametersAST.getChildCount() != 0) {
            log(aAST, "junit.method.parameters", aName);
        }
    }

    /**
     * Checks if given method declared as public or
     * protected and non-static.
     * @param aAST method definition node
     * @return true if given method is declared as public or protected
     */
    private boolean isPublicOrProtected(DetailAST aAST)
    {
        final DetailAST modifiersAST =
            aAST.findFirstToken(TokenTypes.MODIFIERS);
        final DetailAST publicAST =
            modifiersAST.findFirstToken(TokenTypes.LITERAL_PUBLIC);
        final DetailAST protectedAST =
            modifiersAST.findFirstToken(TokenTypes.LITERAL_PROTECTED);

        return (publicAST != null) || (protectedAST != null);
    }

    /**
     * Checks if given method declared as public and
     * static.
     * @param aAST method definition node
     * @return true if given method is declared as public and static
     */
    private boolean isPublicAndStatic(DetailAST aAST)
    {
        final DetailAST modifiersAST =
            aAST.findFirstToken(TokenTypes.MODIFIERS);
        final DetailAST publicAST =
            modifiersAST.findFirstToken(TokenTypes.LITERAL_PUBLIC);
        final DetailAST staticAST =
            modifiersAST.findFirstToken(TokenTypes.LITERAL_STATIC);

        return (publicAST != null) && (staticAST != null);
    }

    /**
     * Checks if given method declared as static.
     * @param aAST method definition node
     * @return true if given method is declared as static
     */
    private boolean isStatic(DetailAST aAST)
    {
        final DetailAST modifiersAST =
            aAST.findFirstToken(TokenTypes.MODIFIERS);
        final DetailAST staticAST =
            modifiersAST.findFirstToken(TokenTypes.LITERAL_STATIC);

        return (staticAST != null);
    }
}
checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/MagicNumberCheck.java100644      0      0       23265 12026051047  30602 0ustar     0      0 ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2012  Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;

import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.ScopeUtils;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.checks.CheckUtils;
import java.util.Arrays;

/**
 * 

* Checks for magic numbers. *

*

* An example of how to configure the check to ignore * numbers 0, 1, 1.5, 2: *

*
 * <module name="MagicNumber">
 *    <property name="ignoreNumbers" value="0, 1, 1.5, 2"/>
 *    <property name="ignoreHashCodeMethod" value="true"/>
 * </module>
 * 
* @author Rick Giles * @author Lars Kühne * @author Daniel Solano Gómez */ public class MagicNumberCheck extends Check { /** * The token types that are allowed in the AST path from the * number literal to the enclosing constant definition. */ private static final int[] ALLOWED_PATH_TOKENTYPES = { TokenTypes.ASSIGN, TokenTypes.ARRAY_INIT, TokenTypes.EXPR, TokenTypes.UNARY_PLUS, TokenTypes.UNARY_MINUS, TokenTypes.TYPECAST, TokenTypes.ELIST, TokenTypes.LITERAL_NEW, TokenTypes.METHOD_CALL, TokenTypes.STAR, }; static { Arrays.sort(ALLOWED_PATH_TOKENTYPES); } /** the numbers to ignore in the check, sorted */ private double[] mIgnoreNumbers = {-1, 0, 1, 2}; /** Whether to ignore magic numbers in a hash code method. */ private boolean mIgnoreHashCodeMethod; /** Whether to ignore magic numbers in annotation. */ private boolean mIgnoreAnnotation; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.NUM_DOUBLE, TokenTypes.NUM_FLOAT, TokenTypes.NUM_INT, TokenTypes.NUM_LONG, }; } @Override public void visitToken(DetailAST aAST) { if (mIgnoreAnnotation && isInAnnotation(aAST)) { return; } if (inIgnoreList(aAST) || (mIgnoreHashCodeMethod && isInHashCodeMethod(aAST))) { return; } final DetailAST constantDefAST = findContainingConstantDef(aAST); if (constantDefAST == null) { reportMagicNumber(aAST); } else { DetailAST ast = aAST.getParent(); while (ast != constantDefAST) { final int type = ast.getType(); if (Arrays.binarySearch(ALLOWED_PATH_TOKENTYPES, type) < 0) { reportMagicNumber(aAST); break; } ast = ast.getParent(); } } } /** * Finds the constant definition that contains aAST. * @param aAST the AST * @return the constant def or null if aAST is not * contained in a constant definition */ private DetailAST findContainingConstantDef(DetailAST aAST) { DetailAST varDefAST = aAST; while ((varDefAST != null) && (varDefAST.getType() != TokenTypes.VARIABLE_DEF) && (varDefAST.getType() != TokenTypes.ENUM_CONSTANT_DEF)) { varDefAST = varDefAST.getParent(); } // no containing variable definition? if (varDefAST == null) { return null; } // implicit constant? if (ScopeUtils.inInterfaceOrAnnotationBlock(varDefAST) || (varDefAST.getType() == TokenTypes.ENUM_CONSTANT_DEF)) { return varDefAST; } // explicit constant final DetailAST modifiersAST = varDefAST.findFirstToken(TokenTypes.MODIFIERS); if (modifiersAST.branchContains(TokenTypes.FINAL)) { return varDefAST; } return null; } /** * Reports aAST as a magic number, includes unary operators as needed. * @param aAST the AST node that contains the number to report */ private void reportMagicNumber(DetailAST aAST) { String text = aAST.getText(); final DetailAST parent = aAST.getParent(); DetailAST reportAST = aAST; if (parent.getType() == TokenTypes.UNARY_MINUS) { reportAST = parent; text = "-" + text; } else if (parent.getType() == TokenTypes.UNARY_PLUS) { reportAST = parent; text = "+" + text; } log(reportAST.getLineNo(), reportAST.getColumnNo(), "magic.number", text); } /** * Determines whether or not the given AST is in a valid hash code method. * A valid hash code method is considered to be a method of the signature * {@code public int hashCode()}. * * @param aAST the AST from which to search for an enclosing hash code * method definition * * @return {@code true} if {@code aAST} is in the scope of a valid hash * code method */ private boolean isInHashCodeMethod(DetailAST aAST) { // if not in a code block, can't be in hashCode() if (!ScopeUtils.inCodeBlock(aAST)) { return false; } // find the method definition AST DetailAST methodDefAST = aAST.getParent(); while ((null != methodDefAST) && (TokenTypes.METHOD_DEF != methodDefAST.getType())) { methodDefAST = methodDefAST.getParent(); } if (null == methodDefAST) { return false; } // Check for 'hashCode' name. final DetailAST identAST = methodDefAST.findFirstToken(TokenTypes.IDENT); if (!"hashCode".equals(identAST.getText())) { return false; } // Check for no arguments. final DetailAST paramAST = methodDefAST.findFirstToken(TokenTypes.PARAMETERS); if (0 != paramAST.getChildCount()) { return false; } // we are in a 'public int hashCode()' method! The compiler will ensure // the method returns an 'int' and is public. return true; } /** * Decides whether the number of an AST is in the ignore list of this * check. * @param aAST the AST to check * @return true if the number of aAST is in the ignore list of this * check. */ private boolean inIgnoreList(DetailAST aAST) { double value = CheckUtils.parseDouble(aAST.getText(), aAST.getType()); final DetailAST parent = aAST.getParent(); if (parent.getType() == TokenTypes.UNARY_MINUS) { value = -1 * value; } return (Arrays.binarySearch(mIgnoreNumbers, value) >= 0); } /** * Sets the numbers to ignore in the check. * BeanUtils converts numeric token list to double array automatically. * @param aList list of numbers to ignore. */ public void setIgnoreNumbers(double[] aList) { if ((aList == null) || (aList.length == 0)) { mIgnoreNumbers = new double[0]; } else { mIgnoreNumbers = new double[aList.length]; System.arraycopy(aList, 0, mIgnoreNumbers, 0, aList.length); Arrays.sort(mIgnoreNumbers); } } /** * Set whether to ignore hashCode methods. * @param aIgnoreHashCodeMethod decide whether to ignore * hash code methods */ public void setIgnoreHashCodeMethod(boolean aIgnoreHashCodeMethod) { mIgnoreHashCodeMethod = aIgnoreHashCodeMethod; } /** * Set whether to ignore Annotations. * @param aIgnoreAnnotation decide whether to ignore annotations */ public void setIgnoreAnnotation(boolean aIgnoreAnnotation) { mIgnoreAnnotation = aIgnoreAnnotation; } /** * Determines if the column displays a token type of annotation or * annotation member * * @param aAST the AST from which to search for annotations * * @return {@code true} if the token type for this node is a annotation */ private boolean isInAnnotation(DetailAST aAST) { if ((null == aAST.getParent()) || (null == aAST.getParent().getParent())) { return false; } return (TokenTypes.ANNOTATION == aAST.getParent().getParent().getType()) || (TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR == aAST.getParent().getParent().getType()); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/messages.properties100644 0 0 10737 11743005374 30544 0ustar 0 0 array.trailing.comma=Array should contain trailing comma. assignment.inner.avoid=Inner assignments should be avoided. avoid.finalizer.method=Avoid using finalizer method. avoid.clone.method=Avoid using clone method. covariant.equals=covariant equals without overriding equals(java.lang.Object). declaration.order.constructor=Constructor definition in wrong order. declaration.order.method=Method definition in wrong order. declaration.order.static=Static variable definition in wrong order. declaration.order.instance=Instance variable definition in wrong order. declaration.order.access=Variable access definition in wrong order. default.comes.last=Default should be last label in the switch. empty.statement=Empty statement. equals.avoid.null=String literal expressions should be on the left side of an equals comparison. equalsIgnoreCase.avoid.null=String literal expressions should be on the left side of an equalsIgnoreCase comparison. equals.noHashCode=Definition of ''equals()'' without corresponding definition of ''hashCode()''. explicit.init=Variable ''{0}'' explicitly initialized to ''{1}'' (default value for its type). fall.through=Fall through from previous branch of the switch statement. fall.through.last=Fall through from the last branch of the switch statement. final.variable=Variable ''{0}'' should be declared final. hidden.field=''{0}'' hides a field. illegal.catch=Catching ''{0}'' is not allowed. illegal.throw=Throwing ''{0}'' is not allowed. illegal.token=Using ''{0}'' is not allowed. illegal.token.text=Token text matches the illegal pattern ''{0}''. illegal.type=Declaring variables, return values or parameters of type ''{0}'' is not allowed. inline.conditional.avoid=Avoid inline conditionals. instantiation.avoid=Instantiation of {0} should be avoided. junit.method.name=The method ''{0}'' should be named ''{1}''. junit.method.return.type=The method ''{0}'' must be declared with a {1} return type. junit.method.parameters=The method ''{0}'' must be declared with no parameters. junit.method.public.and.static=The method ''{0}'' must be declared static. junit.method.protected.or.public=The method ''{0}'' must be public or protected. junit.method.static=The method ''{0}'' shouldn''t be static. magic.number=''{0}'' is a magic number. missing.ctor=Class should define a constructor. missing.package.declaration=Missing package declaration. missing.super.call=Method ''{0}'' should call ''super.{0}''. missing.switch.default=switch without \"default\" clause. modified.control.variable=Control variable ''{0}'' is modified. multiple.statements.line=Only one statement per line allowed. multiple.string.literal=The String {0} appears {1} times in the file. multiple.variable.declarations=Only one variable definition per line allowed. multiple.variable.declarations.comma=Each variable declaration must be in its own statement. nested.for.depth=Nested for depth is {0,number,integer} (max allowed is {1,number,integer}). nested.if.depth=Nested if-else depth is {0,number,integer} (max allowed is {1,number,integer}). nested.try.depth=Nested try depth is {0,number,integer} (max allowed is {1,number,integer}). parameter.assignment=Assignment of parameter ''{0}'' is not allowed. redundant.throws.classInfo=Unable to get class information for {0}. redundant.throws.duplicate=Redundant throws: ''{0}'' listed more then one time. redundant.throws.subclass=Redundant throws: ''{0}'' is subclass of ''{1}''. redundant.throws.unchecked=Redundant throws: ''{0}'' is unchecked exception. require.this.variable=Reference to instance variable ''{0}'' needs \"this.\". require.this.unfound.variable=Unable find where ''{0}'' is declared. require.this.method=Method call to ''{0}'' needs \"this.\". return.count=Return count is {0,number,integer} (max allowed is {1,number,integer}). simplify.boolreturn=Conditional logic can be removed. simplify.expression=Expression can be simplified. string.literal.equality=Literal Strings should be compared using equals(), not ''{0}''. unnecessary.paren.assign=Unnecessary parentheses around assignment right-hand side. unnecessary.paren.expr=Unnecessary parentheses around expression. unnecessary.paren.ident=Unnecessary parentheses around identifier ''{0}''. unnecessary.paren.literal=Unnecessary parentheses around literal ''{0}''. unnecessary.paren.return=Unnecessary parentheses around return value. unnecessary.paren.string=Unnecessary parentheses around string {0}. package.dir.mismatch=Package declaration does not match directory ''{0}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/messages_de.properties100644 0 0 10703 11743005374 31205 0ustar 0 0 array.trailing.comma=Array sollte mit einem Komma abheschlossen werden. assignment.inner.avoid=Innere Zuweisungen sollten vermieden werden. avoid.finalizer.method=Die Verwendung von finalizer Methoden sollte vermieden werden. covariant.equals=Kovariante Definition von equals() ohne equals(java.lang.Object) zu überschreiben. declaration.order.constructor=Konstruktordefinition in falscher Reihenfolge. declaration.order.method=Methodendefinition in falscher Reihenfolge. declaration.order.static=Statische Variablendefinition in falscher Reihenfolge. declaration.order.instance=Instanzvariablendefinition in falscher Reihenfolge. declaration.order.access=Fehlerhafte Deklarationsreihenfolge für diesen Scope. default.comes.last=Default sollte das letzte Label im switch sein. empty.statement=Leere Anweisung. equals.noHashCode=Definition von ''equals()'' ohne korrespondierende Definition von ''hashCode()''. explicit.init=Variable ''{0}'' wird explizit mit ''{1}'' initialisiert (Defaultwert für ihren Typ). fall.through=Fall through vom vorherigen Zweig der switch Anweisung. fall.through.last=Fall through von letzten Zweig der switch Anweisung. final.variable=Variable ''{0}'' sollte als final deklariert werden. hidden.field=''{0}'' verbirgt ein Feld. illegal.catch=Catch von ''{0}'' ist nicht erlaubt. illegal.throw=Werfen von ''{0}'' ist nicht erlaubt. illegal.token=Benutzung von ''{0}'' ist nicht erlaubt. illegal.token.text=Tokentext entspricht dem Muster ''{0}''. illegal.type=Deklaration von Variablen, Rückgabewerten oder Parametern des Typs ''{0}'' is nicht erlaubt. inline.conditional.avoid=Der Bedingungsoperator sollte vermieden werden. instantiation.avoid=Instantiierung von {0} sollte vermieden werden. junit.method.name=Die Methode ''{0}'' sollte zu ''{1}'' umbenannt werden. junit.method.return.type=Die Methode ''{0}'' muss den Rückgabetyp {1} haben. junit.method.parameters=Die Methode ''{0}'' muss parameterlos sein. junit.method.public.and.static=Die Methode ''{0}'' muss als static deklariert sein. junit.method.protected.or.public=Die Methode ''{0}'' muss public oder protected sein. junit.method.static=Die Methode ''{0}'' sollte nicht static sein. magic.number=''{0}'' sollte durch eine Konstante definiert sein. missing.ctor=Die Klasse sollte einen Konstruktor definieren. missing.package.declaration=Fehlende Package-Deklaration. missing.super.call=Die Methode ''{0}'' sollte ''super.{0}'' aufrufen. missing.switch.default=switch ohne \"default\". modified.control.variable=Die Kontrollvariable ''{0}'' wird modifiziert. multiple.string.literal=Der String {0} wird in dieser Datei {1} mal benutzt. multiple.variable.declarations=Nur eine Variablendefinition pro Zeile ist erlaubt. multiple.variable.declarations.comma=Jede Variablendeklaration muss in einer eigenen Anweisung erfolgen. nested.if.depth=Verschachtelungstiefe von if-else ist {0,number,integer} (Obergrenze ist {1,number,integer}). nested.try.depth=Verschachtelungstiefe von try Blöcken ist {0,number,integer} (Obergrenze ist {1,number,integer}). parameter.assignment=Zuweisung an den Parameter ''{0}'' is nicht erlaubt. redundant.throws.classInfo=Klassen-Information für {0} nicht verfügbar. redundant.throws.duplicate=Überflüssige throws-Deklaration: ''{0}'' ist mehrfach aufgeführt. redundant.throws.subclass=Überflüssige throws-Deklaration: ''{0}'' ist Unterklasse von ''{1}''. redundant.throws.unchecked=Überflüssige throws-Deklaration: ''{0}'' ist eine unchecked Exception (abgeleitet von RuntimeException). require.this.method=Methodenaufruf ''{0}'' muss über \"this.\" erfolgen. require.this.unfound.variable=Checkstyle kann Deklaration von ''{0}'' nicht finden. require.this.variable=Dereferenzierung der Instanzvariable ''{0}'' muss über \"this.\" erfolgen. return.count={0,number,integer} return-Anweisungen (Obergrenze ist {1,number,integer}). simplify.boolreturn=Die Verzweigung sollte entfernt werden. simplify.expression=Der Ausdruck kann vereinfacht werden. string.literal.equality=String-Literale sollten mit equals() verglichen werden, nicht mit ''{0}''. unnecessary.paren.assign=Überflüssige Klammern um die rechte Seite der Zuweisung. unnecessary.paren.expr=Überflüssige Klammern um Ausdruck. unnecessary.paren.ident=Überflüssige Klammern um den Bezeichner ''{0}''. unnecessary.paren.literal=Überflüssige Klammern um das Literal ''{0}''. unnecessary.paren.return=Überflüssige Klammern um den return-Wert. unnecessary.paren.string=Überflüssige Klammern um den String {0}. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/messages_es.properties100644 0 0 10370 11743005374 31224 0ustar 0 0 array.trailing.comma=El array debería llevar una coma al final. assignment.inner.avoid=Deben evitarse las asignaciones internas. covariant.equals=equals covariante sin sobrescribir equals(java.lang.Object). empty.statement=Sentencia vacía. equals.noHashCode=Definición de ''equals()'' sin la correspondiente definición de ''hashCode()''. final.variable=La variable ''{0}'' debe declararse final. hidden.field=''{0}'' oculta un campo. illegal.token=El uso de ''{0}'' no esta permitido. illegal.token.text=El texto del token coincide con el patrón ilegal ''{0}''. instantiation.avoid=Debería evitarse la instanciación de {0}. inline.conditional.avoid=Evitar los condicionales en línea. magic.number=''{0}'' es un número mágico. missing.super.call=El método ''{0}'' debería llamar a ''super.{0}''. missing.switch.default=switch sin etiqueta \"default\". multiple.string.literal=La cadena {0} aparece {1} veces en el fichero. redundant.throws.classInfo=No se puede obtener la información de clase de {0}. redundant.throws.duplicate=Sentencia throws redundante: ''{0}'' aparece más de una vez. redundant.throws.subclass=Sentencia throws redundante: ''{0}'' es una subclase de ''{1}''. redundant.throws.unchecked=Sentencia throws redundante: ''{0}'' es una excepción no comprobada. simplify.boolreturn=Se puede eliminar la lógica condicional. simplify.expression=Se puede simplificar la expresión. nested.if.depth=La profundidad de if-else anidados es {0,number,integer} (máximo permitido es {1,number,integer}). nested.try.depth=La profundidad de try anidados es {0,number,integer} (máximo permitido es {1,number,integer}). string.literal.equality=Las cadenas literales deben compararse usando equals(), no ''{0}''. illegal.catch=Capturar la excepción ''{0}'' no está permitido. missing.package.declaration=Falta la declaración de paquete. junit.method.name=El método ''{0}'' debería llamarse ''{1}''. junit.method.return.type=El método ''{0}'' debe declararse con tipo de retorno {1}. junit.method.parameters=El método ''{0}'' debe declararse sin parámetros. junit.method.public.and.static=El método ''{0}'' debe declararse static. junit.method.protected.or.public=El método ''{0}'' debe ser public o protected. junit.method.static=El método ''{0}'' no debería ser static. return.count=El número de sentencias return es {0,number,integer} (máximo permitido es {1,number,integer}). illegal.type=La declaración de variables, valores de retorno o parámetros de tipo ''{0}'' no está permitida. declaration.order.constructor=Definición de constructor en orden incorrecto. declaration.order.method=Definición de método en orden incorrecto. declaration.order.static=Definición de variable static en orden incorrecto. declaration.order.instance=Definición de variable de instancia en orden incorrecto. declaration.order.access=Definición de acceso a variable en orden incorrecto. parameter.assignment=No esta permitida la asignación del parámetro ''{0}''. modified.control.variable=Se modifica la variable de control ''{0}''. explicit.init=La variable ''{0}'' se inicializa explicitamente a ''{1}'' (valor por defecto para su tipo). default.comes.last=La etiqueta default debe ser la última etiqueta en el switch. missing.ctor=La clase debería definir un constructor. fall.through=Caída desde la etiqueta anterior en la sentencia switch. require.this.variable=La referencia a la variable de instancia ''{0}'' necesita \"this.\". require.this.unfound.variable=No se puede encontrar la declaración de ''{0}''. require.this.method=La llamada al método ''{0}'' necesita \"this.\". multiple.variable.declarations=Sólo se permite una definición de variable por línea. multiple.variable.declarations.comma=Cada declaración de variable debe estar en su línea. unnecessary.paren.assign=Paréntesis innecesarios alrededor de la parte derecha de una asignación. unnecessary.paren.expr=Paréntesis innecesarios alrededor de la expresión. unnecessary.paren.ident=Paréntesis innecesarios alrededor del identificador ''{0}''. unnecessary.paren.literal=Paréntesis innecesarios alrededor del literal ''{0}''. unnecessary.paren.return=Paréntesis innecesarios alrededor del valor de retorno. unnecessary.paren.string=Paréntesis innecesarios alrededor de la cadena {0}. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/messages_fi.properties100644 0 0 2251 11451071613 31165 0ustar 0 0 assignment.inner.avoid=„l¤ k¤yt¤ sis¤kk¤isi¤ sijoituksia. equals.noHashCode=''equals()'' m¤¤ritelty ilman vastaavaa ''hashCode()''-m¤¤rittely¤. final.variable=Muuttujan ''{0}'' pit¤isi olla final. hidden.field=''{0}'' piilottaa muuttujan. illegal.token=''{0}'':n k¤yttĥ ei ole sallittu. instantiation.avoid=„l¤ instantioi {0}:a. missing.super.call=Metodin ''{0}'' pit¤isi kutsua ''super.{0}'':aa. redundant.throws.duplicate=Ylim¤¤r¤inen throws: ''{0}'' mainittu useamman kuin yhden kerran. redundant.throws.subclass=Ylim¤¤r¤inen throws: ''{0}'' on ''{1}'':n aliluokka. redundant.throws.unchecked=Ylim¤¤r¤inen throws: ''{0}'' on tarkistamaton poikkeus. simplify.boolreturn=Konditionaalilogiikan voisi poistaa. simplify.expression=Ilmaisua voisi yksinkertaistaa. nested.if.depth=Sis¤kk¤isten if-else -lausekkeiden syvyys on {0,number,integer} (suurin sallittu on {1,number,integer}). nested.if.depth=Sis¤kk¤isten try -lausekkeiden syvyys on {0,number,integer} (suurin sallittu on {1,number,integer}). junit.method.name=Metodin ''{0}'' nimi pit¤isi olla ''{1}''. junit.method.static=Metodin ''{0}'' ei pit¤isi olla staattinen. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/messages_fr.properties100644 0 0 11455 11743005374 31231 0ustar 0 0 array.trailing.comma=La dernière valeur d''un tableau devrait être suivie d''une virgule. assignment.inner.avoid=Evitez d''affecter une valeur à une variable au sein d''une expression. covariant.equals=Votre méthode equals compare uniquement les objets de votre classe. N''oubliez pas de surcharger la méthode equals(java.lang.Object). empty.statement=Instruction vide. equals.noHashCode=La définition de la méthode ''equals()'' doit toujours être accompagnée de la définition de la méthode ''hashCode()''. final.variable=La variable ''{0}'' devrait être finale. hidden.field=''{0}'' masque un attribut. illegal.token=Il est interdit d''utiliser ''{0}''. illegal.token.text=Chaîne de caractères interdite ''{0}''. instantiation.avoid=L''instantiation de la classe {0} est prohibée. inline.conditional.avoid=L'utilisation de l'opérateur conditionel est prohibée. magic.number=''{0}'' devrait être défini comme une constante. missing.super.call=La méthode ''{0}'' devrait appeler ''super.{0}''. missing.switch.default=Il manque le cas \"default\" dans le bloc \"switch\". multiple.string.literal=La chaîne {0} apparait {1} fois dans le fichier. redundant.throws.classInfo=Impossible d''obtenir les informations relatives à {0}. redundant.throws.duplicate=Clause throws redondante : ''{0}'' est présent plus d''une fois. redundant.throws.subclass=Clause throws redondante : ''{0}'' est une sous-classe de ''{1}''. redundant.throws.unchecked=Clause throws redondante : ''{0}'' est une exception non vérifiée. simplify.boolreturn=Le test peut être supprimé et l''expression directement retournée. simplify.expression=L''expression peut être simplifiée. nested.if.depth=Le nombre de ''if'' imbriqué est de {0,number,integer}, alors que le maximum autorisé est de {1,number,integer}. nested.try.depth=Le nombre de ''try'' imbriqué est de {0,number,integer}, alors que le maximum autorisé est de {1,number,integer}. string.literal.equality=Les chaines de caractères littérales devraient être comparées avec la méthode equals() et pas avec ''{0}''. illegal.catch=Catcher l''exception ''{0}'' est prohibé. missing.package.declaration=Déclaration de package manquante. junit.method.name=La méthode ''{0}'' devrait être renommée ''{1}''. junit.method.return.type=La méthode ''{0}'' devrait être déclarée avec un type de retour {1}. junit.method.parameters=La méthode ''{0}'' devrait être déclarée sans paramètres. junit.method.public.and.static=La méthode ''{0}'' devrait être déclarée statique. junit.method.protected.or.public=La méthode ''{0}'' devrait être protégée ou publique. junit.method.static=La méthode ''{0}'' ne devrait pas être statique. return.count=Le nombre de return est de {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. illegal.type=Déclarer des variables, des valeurs de retour ou des paramètres de type ''{0}'' est interdit. declaration.order.constructor=La définition des constructeurs n''apparait pas dans le bon ordre. declaration.order.method=La définition des méthodes n''apparait pas dans le bon ordre. declaration.order.static=La définition des variables statiques n''apparait pas dans le bon ordre. declaration.order.instance=La définition des variables d''instance n''apparait pas dans le bon ordre. declaration.order.access=La définition des variables n''est pas triée suivant leur portée. parameter.assignment=Il est interdit d''affecter une valeur au paramètre ''{0}''. modified.control.variable=La variable de controle ''{0}'' est modifiée. explicit.init=L''initialisation explicite de la variable ''{0}'' à la valeur ''{1}'' est inutile, c''est la valeur par défaut pour ce type. default.comes.last=Le cas \"default\" devrait apparaitre en dernier dans le bloc \"switch\". missing.ctor=Il manque un constructeur à la classe. fall.through=Le cas précédent du \"switch\" ne contient pas de break, return, throw ou continue. require.this.variable=La référence à la variable d''instance ''{0}'' doit utiliser \"this.\". require.this.unfound.variable=Impossible de trouver où ''{0}'' est déclaré. require.this.method=L''appel à la méthode ''{0}'' nécessite l''utilisation de \"this.\". multiple.variable.declarations=Ne déclarez pas plus d''une variable par ligne. multiple.variable.declarations.comma=Chaque déclaration de variable doit faire l''objet d''une instruction à part. unnecessary.paren.assign=Parenthèses inutiles autour la partie droite de l''affectation. unnecessary.paren.expr=Parenthèses inutiles autour de l''expression. unnecessary.paren.ident=Parenthèses inutiles autour de l''identifiant ''{0}''. unnecessary.paren.literal=Parenthèses inutiles autour de la chaîne littérale ''{0}''. unnecessary.paren.return=Parenthèses inutiles autour de la valeur de retour. unnecessary.paren.string=Parenthèses inutiles autour de la chaîne {0}. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/messages_ja.properties100644 0 0 12766 11743005373 31221 0ustar 0 0 array.trailing.comma=\u914d\u5217\u3067\u306f\u30ab\u30f3\u30de\u304c\u884c\u672b\u306b\u6765\u308b\u3088\u3046\u306b\u3059\u3079\u304d\u3067\u3059\u3002 assignment.inner.avoid=\u5f0f\u5185\u90e8\u3067\u306e\u4ee3\u5165\u306f\u907f\u3051\u308b\u3079\u304d\u3067\u3059\u3002 covariant.equals=equals(java.lang.Object) \u3092\u30aa\u30fc\u30d0\u30fc\u30e9\u30a4\u30c9\u305b\u305a\u306b covariant \u306a equals \u3092\u5b9a\u7fa9\u3057\u3066\u3044\u307e\u3059\u3002 empty.statement=\u7a7a\u306e\u6587\u3067\u3059\u3002 equals.noHashCode=''equals()'' \u3092\u5b9a\u7fa9\u3057\u3066\u3044\u307e\u3059\u304c\u3001\u3053\u308c\u306b\u5bfe\u5fdc\u3059\u308b ''hashCode()'' \u306e\u5b9a\u7fa9\u304c\u3042\u308a\u307e\u305b\u3093\u3002 final.variable=\u5909\u6570 ''{0}'' \u306f final \u3068\u3057\u3066\u5ba3\u8a00\u3059\u3079\u304d\u3067\u3059\u3002 hidden.field=''{0}'' \u304c\u30d5\u30a3\u30fc\u30eb\u30c9\u3092\u96a0\u3057\u3066\u3044\u307e\u3059\u3002 illegal.token=''{0}'' \u306e\u4f7f\u7528\u306f\u8a31\u53ef\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002 illegal.token.text=\u30c8\u30fc\u30af\u30f3\u306e\u30c6\u30ad\u30b9\u30c8\u304c\u4e0d\u6b63\u306a\u30d1\u30bf\u30fc\u30f3 ''{0}'' \u306b\u4e00\u81f4\u3057\u3066\u3044\u307e\u3059\u3002 instantiation.avoid={0} \u306e\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u306f\u907f\u3051\u308b\u3079\u304d\u3067\u3059\u3002 magic.number=''{0}'' \u306f\u30de\u30b8\u30c3\u30af\u30ca\u30f3\u30d0\u30fc\u3067\u3059\u3002 missing.super.call=\u30e1\u30bd\u30c3\u30c9 ''{0}'' \u306f ''super.{0}'' \u3092\u547c\u3076\u3079\u304d\u3067\u3059\u3002 missing.switch.default=\"default\" \u7bc0\u306e\u7121\u3044 switch \u6587\u3067\u3059\u3002 redundant.throws.classInfo={0} \u306e\u30af\u30e9\u30b9\u60c5\u5831\u304c\u53d6\u5f97\u3067\u304d\u307e\u305b\u3093\u3002 redundant.throws.duplicate=\u5197\u9577\u306a throws: ''{0}'' \u304c\u91cd\u8907\u3057\u3066\u3044\u307e\u3059\u3002 redundant.throws.subclass=\u5197\u9577\u306a throws: ''{0}'' \u306f ''{1}'' \u306e\u30b5\u30d6\u30af\u30e9\u30b9\u3067\u3059\u3002 redundant.throws.unchecked=\u5197\u9577\u306a throws: ''{0}'' \u306f\u30c1\u30a7\u30c3\u30af\u3055\u308c\u306a\u3044\u4f8b\u5916\u3067\u3059\u3002 simplify.boolreturn=\u6761\u4ef6\u30ed\u30b8\u30c3\u30af\u306f\u306a\u304f\u305b\u307e\u3059\u3002 simplify.expression=\u8868\u73fe\u306f\u7c21\u6f54\u306b\u3067\u304d\u307e\u3059\u3002 nested.if.depth=\u30cd\u30b9\u30c8\u3057\u305f if-else \u306e\u6df1\u3055\u304c {0,number,integer} \uff08\u6700\u5927 {1,number,integer} \u307e\u3067\uff09\u3067\u3059\u3002 nested.try.depth=\u30cd\u30b9\u30c8\u3057\u305f try \u306e\u6df1\u3055\u304c {0,number,integer} \uff08\u6700\u5927 {1,number,integer} \u307e\u3067\uff09\u3067\u3059\u3002 string.literal.equality=\u30ea\u30c6\u30e9\u30eb\u306e\u6587\u5b57\u5217\u306f ''{0}'' \u3067\u306f\u306a\u304f\u3001 equals() \u3092\u4f7f\u7528\u3057\u3066\u6bd4\u8f03\u3059\u308b\u3079\u304d\u3067\u3059\u3002 illegal.catch=''{0}'' \u3092\u30ad\u30e3\u30c3\u30c1\u3059\u308b\u3053\u3068\u306f\u8a31\u53ef\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002 missing.package.declaration=package \u5ba3\u8a00\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093\u3002 junit.method.name=\u30e1\u30bd\u30c3\u30c9 ''{0}'' \u306f ''{1}'' \u3068\u547d\u540d\u3059\u3079\u304d\u3067\u3059\u3002 junit.method.return.type=\u30e1\u30bd\u30c3\u30c9 ''{0}'' \u306f\u623b\u308a\u5024\u306e\u578b\u3092 {1} \u3068\u3057\u3066\u5ba3\u8a00\u3059\u3079\u304d\u3067\u3059\u3002 junit.method.parameters=\u30e1\u30bd\u30c3\u30c9 ''{0}'' \u306f\u30d1\u30e9\u30e1\u30fc\u30bf\u306a\u3057\u3067\u5ba3\u8a00\u3059\u3079\u304d\u3067\u3059\u3002 junit.method.public.and.static=\u30e1\u30bd\u30c3\u30c9 ''{0}'' \u306f static \u3068\u3057\u3066\u5ba3\u8a00\u3059\u3079\u304d\u3067\u3059\u3002 junit.method.protected.or.public=\u30e1\u30bd\u30c3\u30c9 ''{0}'' \u306f public \u304b protected \u3067\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002 junit.method.static=\u30e1\u30bd\u30c3\u30c9 ''{0}'' \u306f static \u3067\u3042\u308b\u3079\u304d\u3067\u306f\u3042\u308a\u307e\u305b\u3093\u3002 return.count=return \u304c {0,number,integer} \u500b\u6240\u3042\u308a\u307e\u3059\uff08\u6700\u5927 {1,number,integer} \u307e\u3067\uff09\u3002 illegal.type=''{0}'' \u578b\u306e\u5909\u6570\u3001\u623b\u308a\u5024\u3001\u30d1\u30e9\u30e1\u30fc\u30bf\u3092\u5ba3\u8a00\u3059\u308b\u3053\u3068\u306f\u8a31\u53ef\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002 declaration.order.constructor=\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u306e\u5b9a\u7fa9\u9806\u5e8f\u304c\u9593\u9055\u3063\u3066\u3044\u307e\u3059\u3002 declaration.order.method=\u30e1\u30bd\u30c3\u30c9\u306e\u5b9a\u7fa9\u9806\u5e8f\u304c\u9593\u9055\u3063\u3066\u3044\u307e\u3059\u3002 declaration.order.static=static \u5909\u6570\u306e\u5b9a\u7fa9\u9806\u5e8f\u304c\u9593\u9055\u3063\u3066\u3044\u307e\u3059\u3002 declaration.order.instance=\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5909\u6570\u306e\u5b9a\u7fa9\u9806\u5e8f\u304c\u9593\u9055\u3063\u3066\u3044\u307e\u3059\u3002 declaration.order.access=\u5909\u6570\u30a2\u30af\u30bb\u30b9\u306e\u5b9a\u7fa9\u9806\u5e8f\u304c\u9593\u9055\u3063\u3066\u3044\u307e\u3059\u3002 parameter.assignment=\u30d1\u30e9\u30e1\u30fc\u30bf ''{0}'' \u3078\u306e\u4ee3\u5165\u306f\u8a31\u53ef\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002 explicit.init=\u5909\u6570 ''{0}'' \u304c\u660e\u793a\u7684\u306b ''{1}'' \uff08\u3053\u306e\u578b\u306e\u30c7\u30d5\u30a9\u30eb\u30c8\u5024\uff09\u306b\u521d\u671f\u5316\u3055\u308c\u3066\u3044\u307e\u3059\u3002 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/messages_pt.properties100644 0 0 5427 11743005373 31226 0ustar 0 0 array.trailing.comma=O vector deve ter uma virgula final. assignment.inner.avoid=As atribuiçġes internas devem ser evitadas. covariant.equals=\"equals\" covariante sem implementar equals(java.lang.Object). declaration.order.access=Definiço de acesso a variável em ordem errada. declaration.order.constructor=Definiço de construtor em ordem errada. declaration.order.instance=Definiço de variável de instância em ordem errada. declaration.order.method=Definiço de método em ordem errada. declaration.order.static=Definiço de variável estática em ordem errada. empty.statement=Declaraço vazia. equals.noHashCode=Definiço de ''equals()'' sem a definiço de ''hashCode()''. explicit.init=Variável ''{0}'' inicializada explicitamente para ''{1}'' (valor por omisso para o seu tipo). final.variable=Variável ''{0}'' deve ser declarada final. hidden.field=''{0}'' esconde um campo. illegal.catch=O tratamento de ''{0}'' no é permitido. illegal.token.text=Texto do elemento coincide com o padro ilegal ''{0}''. illegal.token=No é permitida a utilizaço de ''{0}''. illegal.type=A declaraço de variáveis, valores de retorno ou parâmetros do tipo ''{0}'' no é permitida. instantiation.avoid=A instanciaço de {0} deve ser evitada. junit.method.name=O método ''{0}'' deveria ser chamado ''{1}''. junit.method.parameters=O método ''{0}'' deve ser declarado sem parâmetros. junit.method.protected.or.public=O método ''{0}'' deve ser público ou protegido. junit.method.public.and.static=O método ''{0}'' deve ser declarado estático. junit.method.return.type=O método ''{0}'' deve ser declarado com o tipo de retorno {1}. junit.method.static=O método ''{0}'' no deve ser estático. magic.number=''{0}'' é um número mágico. missing.package.declaration=Falta a declaraço do pacote. missing.super.call=Method ''{0}'' deve chamar ''super.{0}''. missing.switch.default=switch sem o ramo \"default\". nested.if.depth=Profundidade de \"if-else\" é {0,number,integer} (máximo permitido é {1,number,integer}). nested.try.depth=Profundidade de \"try\" é {0,number,integer} (máximo permitido é {1,number,integer}). parameter.assignment=A atribuiço ao parâmetro ''{0}'' no é permitda. redundant.throws.classInfo=No foi possível obter os dados da classe {0}. redundant.throws.duplicate=throws redundante: ''{0}'' listado mais do que uma vez. redundant.throws.subclass=throws redundante: ''{0}'' é uma sub-classe de ''{1}''. redundant.throws.unchecked=throws redundante: ''{0}'' é um excepço no-verificada. return.count=O número de \"return\"s é {0,number,integer} (máximo permitido é {1,number,integer}). simplify.boolreturn=A lógica condicional pode ser removida. simplify.expression=Expresso pode ser simplicada. string.literal.equality=\"Strings\" literais devem ser comparadas com equals(), no ''{0}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/messages_tr.properties100644 0 0 16406 11744664214 31255 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) array.trailing.comma = Dizi, takip eden bir virg\u00FCl i\u00E7ermelidir. assignment.inner.avoid = Dahili atamalar kullan\u0131lmamal\u0131d\u0131r. avoid.clone.method = ''clone'' metodu kullan\u0131lmamal\u0131d\u0131r. avoid.finalizer.method = ''finalize'' metodu kullan\u0131lmamal\u0131d\u0131r. covariant.equals = java.lang.Object s\u0131n\u0131f\u0131n\u0131n ''equals'' metodundan ba\u015Fka bir ''equals'' metodu tan\u0131mlanm\u0131\u015F, java.lang.Object s\u0131n\u0131f\u0131ndan gelen ''equals'' metodu da ezilmelidir (override). declaration.order.access = De\u011Fi\u015Fken, eri\u015Fim seviyesine g\u00F6re yanl\u0131\u015F s\u0131rada tan\u0131mlanm\u0131\u015F. declaration.order.constructor = ''constructor'' tan\u0131m\u0131 yanl\u0131\u015F s\u0131rada yap\u0131lm\u0131\u015F. declaration.order.instance = De\u011Fi\u015Fken tan\u0131m\u0131 yanl\u0131\u015F s\u0131rada yap\u0131lm\u0131\u015F. declaration.order.method = Metot tan\u0131m\u0131 yanl\u0131\u015F s\u0131rada yap\u0131lm\u0131\u015F. declaration.order.static = ''static'' de\u011Fi\u015Fken tan\u0131m\u0131 yanl\u0131\u015F s\u0131rada yap\u0131lm\u0131\u015F. default.comes.last = ''switch'' i\u00E7erisindeki ''default'' ifadesi son durum olarak yer almal\u0131d\u0131r. doublechecked.locking.avoid = Double-Checked Locking (DCL - lock mekanizmas\u0131nda ikili kontrol) yap\u0131lmam\u0131\u015F. empty.statement = Bo\u015F ifade. equals.avoid.null = ''equals'' metodunda kullan\u0131lan harflerden olu\u015Fan ifadeler ''equals'' metodunun sol taraf\u0131nda yer almal\u0131d\u0131r. equals.noHashCode = ''equals'' metodu tan\u0131mlayan s\u0131n\u0131flar ''hashCode'' metodunu da tan\u0131mlamal\u0131d\u0131r. equalsIgnoreCase.avoid.null = ''equalsIgnoreCase'' metodunda kullan\u0131lan harflerden olu\u015Fan ifadeler ''equalsIgnoreCase'' metodunun sol taraf\u0131nda yer almal\u0131d\u0131r. explicit.init = ''{0}'' de\u011Fi\u015Fkeni (verilmese bile zaten ilklendirme de\u011Feri olan) ''{1}'' de\u011Feriyle ilklendirilmi\u015F. fall.through = ''switch'' ifadesinin bir \u00F6nceki durumundan a\u015Fa\u011F\u0131 d\u00FC\u015Fme mevcut (''break'' kullan\u0131lmam\u0131\u015F olabilir). fall.through.last = ''switch'' ifadesinin son durumundan a\u015Fa\u011F\u0131 d\u00FC\u015Fme mevcut (''break'' kullan\u0131lmam\u0131\u015F olabilir). final.variable = ''{0}'' de\u011Fi\u015Fkeni ''final'' olarak tan\u0131mlanmal\u0131d\u0131r. hidden.field = ''{0}'', ba\u015Fka bir alan\u0131 gizliyor. illegal.catch = ''{0}'' istisnas\u0131n\u0131/hatas\u0131n\u0131 yakalamaya izin verilmiyor. illegal.throw = ''{0}'' istisnas\u0131n\u0131/hatas\u0131n\u0131 f\u0131rlatmaya izin verilmiyor. illegal.token = ''{0}'' kullan\u0131m\u0131na izin verilmiyor. illegal.token.text = \u0130zin verilmeyen bir kal\u0131p kullan\u0131lm\u0131\u015F ''{0}''. illegal.type = ''{0}'' tipinde de\u011Fi\u015Fken, d\u00F6n\u00FC\u015F de\u011Feri ya da parametre tan\u0131mlanmamal\u0131d\u0131r. inline.conditional.avoid = Sat\u0131r i\u00E7i ko\u015Fullu ifadeler kullan\u0131lmamal\u0131d\u0131r. instantiation.avoid = {0} s\u0131n\u0131f\u0131n\u0131n yeni nesnesi \u00FCretilmemelidir. junit.method.name = ''{0}'' metodu ''{1}'' olarak adland\u0131r\u0131lmal\u0131d\u0131r. junit.method.parameters = ''{0}'' metodu parametresiz olarak tan\u0131mlanmal\u0131. junit.method.protected.or.public = ''{0}'' metodu ''public'' ya da ''protected'' olmal\u0131. junit.method.public.and.static = ''{0}'' metodu ''static'' olarak tan\u0131mlanmal\u0131. junit.method.return.type = ''{0}'' metodunun d\u00F6n\u00FC\u015F tipi ''{1}'' olmal\u0131. junit.method.static = ''{0}'' metodu ''static'' olarak tan\u0131mlanmamal\u0131. magic.number = ''{0}'' say\u0131s\u0131 ''magic number''d\u0131r. \u00D6nce tan\u0131mlanmal\u0131, sonra kullan\u0131lmal\u0131. missing.ctor = S\u0131n\u0131f, bir ''constructor'' tan\u0131mlamal\u0131. missing.package.declaration = Paket tan\u0131m\u0131 yap\u0131lmam\u0131\u015F. missing.super.call = ''{0}'' metodu ''super.{0}'' metodunu \u00E7a\u011F\u0131rmal\u0131. missing.switch.default = ''default'' olmadan ''switch'' kullan\u0131lm\u0131\u015F. modified.control.variable = Kontrol de\u011Fi\u015Fkeninin de\u011Feri de\u011Fi\u015Ftirilmi\u015F. multiple.statements.line = Her sat\u0131rda sadece bir ifade olmal\u0131d\u0131r. multiple.string.literal = ''{0}'' de\u011Feri dosyada {1} defa kullan\u0131lm\u0131\u015F. multiple.variable.declarations = Her sat\u0131rda sadece bir de\u011Fi\u015Fken tan\u0131mlanmal\u0131. multiple.variable.declarations.comma = Her de\u011Fi\u015Fken tan\u0131m\u0131 kendi ifadesinde yer almal\u0131. nested.for.depth = \u0130\u00E7 i\u00E7e kullan\u0131lan ''for'' say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). nested.if.depth = \u0130\u00E7 i\u00E7e kullan\u0131lan ''if-else'' say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). nested.try.depth = \u0130\u00E7 i\u00E7e kullan\u0131lan ''try'' say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). package.dir.mismatch = Paket tan\u0131m\u0131 ''{0}'' klas\u00F6r\u00FCyle e\u015Fle\u015Fmiyor. parameter.assignment = ''{0}'' parametresine atama yap\u0131lamaz. redundant.throws.classInfo = {0} i\u00E7in s\u0131n\u0131f bilgisi al\u0131nam\u0131yor. redundant.throws.duplicate = ''throws'' ifadesinde ''{0}'' tekrardan kullan\u0131lm\u0131\u015F. redundant.throws.subclass = ''{0}'', ''{1}'' s\u0131n\u0131f\u0131n\u0131n alt s\u0131n\u0131f\u0131d\u0131r, ''throws'' kullan\u0131m\u0131 gereksizdir. redundant.throws.unchecked = ''{0}'' ''unchecked'' bir istisnad\u0131r, ''throws'' kullan\u0131m\u0131 gereksizdir. require.this.method = ''{0}'' metoduna eri\u015Fim "this." kullan\u0131larak yap\u0131lmal\u0131d\u0131r. require.this.unfound.variable = ''{0}'' ifadesinin nerede tan\u0131mland\u0131\u011F\u0131 bilinmiyor. require.this.variable = ''{0}'' de\u011Fi\u015Fkenine eri\u015Fim "this." kullan\u0131larak yap\u0131lmal\u0131d\u0131r. return.count = Kullan\u0131lan ''return'' say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). simplify.boolreturn = Ko\u015Ful mant\u0131\u011F\u0131 kald\u0131r\u0131labilir. simplify.expression = \u0130fade sadele\u015Ftirilebilir. string.literal.equality = ''String'' ifadeleri ''{0}'' kullanarak de\u011Fil, equals() metodu kullanarak kar\u015F\u0131la\u015Ft\u0131r\u0131lmal\u0131. unnecessary.paren.assign = Atama ifadesinin sa\u011F taraf\u0131nda gereksiz parantez mevcut. unnecessary.paren.expr = \u0130fadenin etraf\u0131nda gereksiz parantez mevcut. unnecessary.paren.ident = ''{0}'' belirte\u00E7inin etraf\u0131nda gereksiz parantez mevcut. unnecessary.paren.literal = ''{0}'' etraf\u0131nda gereksiz parantez mevcut. unnecessary.paren.return = Geri d\u00F6n\u00FC\u015F de\u011Feri etraf\u0131nda gereksiz parantez mevcut. unnecessary.paren.string = ''{0}'' etraf\u0131nda gereksiz parantez mevcut. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/MissingCtorCheck.java100644 0 0 4752 12026051047 30632 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.DescendantTokenCheck; /** *

* Checks that classes (except abstract one) define a ctor and don't rely * on the default one. *

*

* An example of how to configure the check is: *

*
 * <module name="MissingCtor"/>
 * 
* * @author o_sukhodolsky */ public class MissingCtorCheck extends DescendantTokenCheck { /** Creates new instance of the check. */ public MissingCtorCheck() { setLimitedTokens(new String[] { TokenTypes.getTokenName(TokenTypes.CTOR_DEF), }); setMinimumNumber(1); setMaximumDepth(2); setMinimumMessage("missing.ctor"); } @Override public int[] getDefaultTokens() { return new int[]{TokenTypes.CLASS_DEF}; } @Override public int[] getAcceptableTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aAST) { final DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS); if ((modifiers != null) && modifiers.branchContains(TokenTypes.ABSTRACT)) { // should apply the check to abtract class return; } super.visitToken(aAST); } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/MissingSwitchDefaultCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/MissingSwitchDefaultChec100644 0 0 4710 12026051046 31367 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.DescendantTokenCheck; /** *

* Checks that switch statement has "default" clause. *

*

* Rationale: It's usually a good idea to introduce a * default case in every switch statement. Even if * the developer is sure that all currently possible * cases are covered, this should be expressed in the * default branch, e.g. by using an assertion. This way * the code is protected aginst later changes, e.g. * introduction of new types in an enumeration type. *

*

* An example of how to configure the check is: *

*
 * <module name="MissingSwitchDefault"/>
 * 
* @author o_sukhodolsky */ public class MissingSwitchDefaultCheck extends DescendantTokenCheck { /** Creates new instance of the check. */ public MissingSwitchDefaultCheck() { setLimitedTokens(new String[] { TokenTypes.getTokenName(TokenTypes.LITERAL_DEFAULT), }); setMinimumNumber(1); setMaximumDepth(2); setMinimumMessage("missing.switch.default"); } @Override public int[] getDefaultTokens() { return new int[]{TokenTypes.LITERAL_SWITCH}; } @Override public int[] getAcceptableTokens() { return getDefaultTokens(); } } ././@LongLink100644 0 0 156 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableC100644 0 0 17622 12026051046 31364 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Check for ensuring that for loop control variables are not modified * inside the for block. * * @author Daniel Grenner */ public final class ModifiedControlVariableCheck extends Check { /** Current set of parameters. */ private FastStack mCurrentVariables = FastStack.newInstance(); /** Stack of block parameters. */ private final FastStack> mVariableStack = FastStack.newInstance(); @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.OBJBLOCK, TokenTypes.LITERAL_FOR, TokenTypes.FOR_ITERATOR, TokenTypes.FOR_EACH_CLAUSE, TokenTypes.ASSIGN, TokenTypes.PLUS_ASSIGN, TokenTypes.MINUS_ASSIGN, TokenTypes.STAR_ASSIGN, TokenTypes.DIV_ASSIGN, TokenTypes.MOD_ASSIGN, TokenTypes.SR_ASSIGN, TokenTypes.BSR_ASSIGN, TokenTypes.SL_ASSIGN, TokenTypes.BAND_ASSIGN, TokenTypes.BXOR_ASSIGN, TokenTypes.BOR_ASSIGN, TokenTypes.INC, TokenTypes.POST_INC, TokenTypes.DEC, TokenTypes.POST_DEC, }; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void beginTree(DetailAST aRootAST) { // clear data mCurrentVariables.clear(); mVariableStack.clear(); } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.OBJBLOCK: enterBlock(); break; case TokenTypes.LITERAL_FOR: case TokenTypes.FOR_ITERATOR: case TokenTypes.FOR_EACH_CLAUSE: break; case TokenTypes.ASSIGN: case TokenTypes.PLUS_ASSIGN: case TokenTypes.MINUS_ASSIGN: case TokenTypes.STAR_ASSIGN: case TokenTypes.DIV_ASSIGN: case TokenTypes.MOD_ASSIGN: case TokenTypes.SR_ASSIGN: case TokenTypes.BSR_ASSIGN: case TokenTypes.SL_ASSIGN: case TokenTypes.BAND_ASSIGN: case TokenTypes.BXOR_ASSIGN: case TokenTypes.BOR_ASSIGN: case TokenTypes.INC: case TokenTypes.POST_INC: case TokenTypes.DEC: case TokenTypes.POST_DEC: checkIdent(aAST); break; default: throw new IllegalStateException(aAST.toString()); } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.FOR_ITERATOR: leaveForIter(aAST.getParent()); break; case TokenTypes.FOR_EACH_CLAUSE: leaveForEach(aAST); break; case TokenTypes.LITERAL_FOR: leaveForDef(aAST); break; case TokenTypes.OBJBLOCK: exitBlock(); break; case TokenTypes.ASSIGN: case TokenTypes.PLUS_ASSIGN: case TokenTypes.MINUS_ASSIGN: case TokenTypes.STAR_ASSIGN: case TokenTypes.DIV_ASSIGN: case TokenTypes.MOD_ASSIGN: case TokenTypes.SR_ASSIGN: case TokenTypes.BSR_ASSIGN: case TokenTypes.SL_ASSIGN: case TokenTypes.BAND_ASSIGN: case TokenTypes.BXOR_ASSIGN: case TokenTypes.BOR_ASSIGN: case TokenTypes.INC: case TokenTypes.POST_INC: case TokenTypes.DEC: case TokenTypes.POST_DEC: // Do nothing break; default: throw new IllegalStateException(aAST.toString()); } } /** * Enters an inner class, which requires a new variable set. */ private void enterBlock() { mVariableStack.push(mCurrentVariables); mCurrentVariables = FastStack.newInstance(); } /** * Leave an inner class, so restore variable set. */ private void exitBlock() { mCurrentVariables = mVariableStack.pop(); } /** * Check if ident is parameter. * @param aAST ident to check. */ private void checkIdent(DetailAST aAST) { if ((mCurrentVariables != null) && !mCurrentVariables.isEmpty()) { final DetailAST identAST = aAST.getFirstChild(); if ((identAST != null) && (identAST.getType() == TokenTypes.IDENT) && mCurrentVariables.contains(identAST.getText())) { log(aAST.getLineNo(), aAST.getColumnNo(), "modified.control.variable", identAST.getText()); } } } /** * Push current variables to the stack. * @param aAST a for definition. */ private void leaveForIter(DetailAST aAST) { final DetailAST forInitAST = aAST.findFirstToken(TokenTypes.FOR_INIT); DetailAST parameterDefAST = forInitAST.findFirstToken(TokenTypes.VARIABLE_DEF); for (; parameterDefAST != null; parameterDefAST = parameterDefAST.getNextSibling()) { if (parameterDefAST.getType() == TokenTypes.VARIABLE_DEF) { final DetailAST param = parameterDefAST.findFirstToken(TokenTypes.IDENT); mCurrentVariables.push(param.getText()); } } } /** * Push current variables to the stack. * @param aForEach a for-each clause */ private void leaveForEach(DetailAST aForEach) { final DetailAST paramDef = aForEach.findFirstToken(TokenTypes.VARIABLE_DEF); final DetailAST paramName = paramDef.findFirstToken(TokenTypes.IDENT); mCurrentVariables.push(paramName.getText()); } /** * Pops the variables from the stack. * @param aAST a for definition. */ private void leaveForDef(DetailAST aAST) { final DetailAST forInitAST = aAST.findFirstToken(TokenTypes.FOR_INIT); if (forInitAST != null) { DetailAST parameterDefAST = forInitAST.findFirstToken(TokenTypes.VARIABLE_DEF); for (; parameterDefAST != null; parameterDefAST = parameterDefAST.getNextSibling()) { if (parameterDefAST.getType() == TokenTypes.VARIABLE_DEF) { mCurrentVariables.pop(); } } } else { // this is for-each loop, just pop veriables mCurrentVariables.pop(); } } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/MultipleStringLiteralsCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/MultipleStringLiteralsCh100644 0 0 15563 12026051046 31471 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.BitSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /** * Checks for multiple occurrences of the same string literal within a * single file. * * @author Daniel Grenner */ public class MultipleStringLiteralsCheck extends Check { /** * The found strings and their positions. * , with the ArrayList containing StringInfo objects. */ private final Map> mStringMap = Maps.newHashMap(); /** * Marks the TokenTypes where duplicate strings should be ignored. */ private final BitSet mIgnoreOccurrenceContext = new BitSet(); /** * The allowed number of string duplicates in a file before an error is * generated. */ private int mAllowedDuplicates = 1; /** * Sets the maximum allowed duplicates of a string. * @param aAllowedDuplicates The maximum number of duplicates. */ public void setAllowedDuplicates(int aAllowedDuplicates) { mAllowedDuplicates = aAllowedDuplicates; } /** * Pattern for matching ignored strings. */ private Pattern mPattern; /** * Construct an instance with default values. */ public MultipleStringLiteralsCheck() { setIgnoreStringsRegexp("^\"\"$"); mIgnoreOccurrenceContext.set(TokenTypes.ANNOTATION); } /** * Sets regexp pattern for ignored strings. * @param aIgnoreStringsRegexp regexp pattern for ignored strings */ public void setIgnoreStringsRegexp(String aIgnoreStringsRegexp) { if ((aIgnoreStringsRegexp != null) && (aIgnoreStringsRegexp.length() > 0)) { mPattern = Utils.getPattern(aIgnoreStringsRegexp); } else { mPattern = null; } } /** * Adds a set of tokens the check is interested in. * @param aStrRep the string representation of the tokens interested in */ public final void setIgnoreOccurrenceContext(String[] aStrRep) { mIgnoreOccurrenceContext.clear(); for (final String s : aStrRep) { final int type = TokenTypes.getTokenId(s); mIgnoreOccurrenceContext.set(type); } } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.STRING_LITERAL}; } @Override public void visitToken(DetailAST aAST) { if (isInIgnoreOccurrenceContext(aAST)) { return; } final String currentString = aAST.getText(); if ((mPattern == null) || !mPattern.matcher(currentString).find()) { List hitList = mStringMap.get(currentString); if (hitList == null) { hitList = Lists.newArrayList(); mStringMap.put(currentString, hitList); } final int line = aAST.getLineNo(); final int col = aAST.getColumnNo(); hitList.add(new StringInfo(line, col)); } } /** * Analyses the path from the AST root to a given AST for occurrences * of the token types in {@link #mIgnoreOccurrenceContext}. * * @param aAST the node from where to start searching towards the root node * @return whether the path from the root node to aAST contains one of the * token type in {@link #mIgnoreOccurrenceContext}. */ private boolean isInIgnoreOccurrenceContext(DetailAST aAST) { for (DetailAST token = aAST; token.getParent() != null; token = token.getParent()) { final int type = token.getType(); if (mIgnoreOccurrenceContext.get(type)) { return true; } } return false; } @Override public void beginTree(DetailAST aRootAST) { super.beginTree(aRootAST); mStringMap.clear(); } @Override public void finishTree(DetailAST aRootAST) { final Set keys = mStringMap.keySet(); for (String key : keys) { final List hits = mStringMap.get(key); if (hits.size() > mAllowedDuplicates) { final StringInfo firstFinding = hits.get(0); final int line = firstFinding.getLine(); final int col = firstFinding.getCol(); log(line, col, "multiple.string.literal", key, hits.size()); } } } /** * This class contains information about where a string was found. */ private static final class StringInfo { /** * Line of finding */ private final int mLine; /** * Column of finding */ private final int mCol; /** * Creates information about a string position. * @param aLine int * @param aCol int */ private StringInfo(int aLine, int aCol) { mLine = aLine; mCol = aCol; } /** * The line where a string was found. * @return int Line of the string. */ private int getLine() { return mLine; } /** * The column where a string was found. * @return int Column of the string. */ private int getCol() { return mCol; } } } ././@LongLink100644 0 0 163 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarat100644 0 0 11015 12026051046 31421 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; /** *

* Checks that each variable declaration is in its own statement * and on its own line. *

*

* Rationale: * the SUN Code conventions chapter 6.1 recommends that * declarations should be one per line. *

*

* An example of how to configure the check is: *

*
 * <module name="MultipleVariableDeclarations"/>
 * 
* @author o_sukhodolsky */ public class MultipleVariableDeclarationsCheck extends Check { /** Creates new instance of the check. */ public MultipleVariableDeclarationsCheck() { } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.VARIABLE_DEF}; } @Override public void visitToken(DetailAST aAST) { DetailAST nextNode = aAST.getNextSibling(); final boolean isCommaSeparated = ((nextNode != null) && (nextNode.getType() == TokenTypes.COMMA)); if (nextNode == null) { // no next statement - no check return; } if ((nextNode.getType() == TokenTypes.COMMA) || (nextNode.getType() == TokenTypes.SEMI)) { nextNode = nextNode.getNextSibling(); } if ((nextNode != null) && (nextNode.getType() == TokenTypes.VARIABLE_DEF)) { final DetailAST firstNode = CheckUtils.getFirstNode(aAST); if (isCommaSeparated) { // Check if the multiple variable declarations are in a // for loop initializer. If they are, then no warning // should be displayed. Declaring multiple variables in // a for loop initializer is a good way to minimize // variable scope. Refer Feature Request Id - 2895985 // for more details if (aAST.getParent().getType() != TokenTypes.FOR_INIT) { log(firstNode, "multiple.variable.declarations.comma"); } return; } final DetailAST lastNode = getLastNode(aAST); final DetailAST firstNextNode = CheckUtils.getFirstNode(nextNode); if (firstNextNode.getLineNo() == lastNode.getLineNo()) { log(firstNode, "multiple.variable.declarations"); } } } /** * Finds sub-node for given node maximum (line, column) pair. * @param aNode the root of tree for search. * @return sub-node with maximum (line, column) pair. */ private static DetailAST getLastNode(final DetailAST aNode) { DetailAST currentNode = aNode; DetailAST child = aNode.getFirstChild(); while (child != null) { final DetailAST newNode = getLastNode(child); if ((newNode.getLineNo() > currentNode.getLineNo()) || ((newNode.getLineNo() == currentNode.getLineNo()) && (newNode.getColumnNo() > currentNode.getColumnNo()))) { currentNode = newNode; } child = child.getNextSibling(); } return currentNode; } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheck.java100644 0 0 5743 12026051046 31247 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Check the number of nested for -statements. The maximum * number of nested layers can be configured. The default value is 1. Most of * the logic is implemented in the parent class. The code for the class is * copied from the NestedIfDepthCheck-class. The only difference is the * intercepted token (for instead of if). Example: *
 *  <!-- Restricts nested for blocks to a specified depth (default = 1).
 *                                                                        -->
 *  <module name="com.puppycrawl.tools.checkstyle.checks.coding
 *                                            .CatchWithLostStackCheck">
 *    <property name="severity" value="info"/>
 *    <property name="max" value="1"/>
 *  </module>
 * 
* @author Alexander Jesse * @see com.puppycrawl.tools.checkstyle.checks.coding.AbstractNestedDepthCheck * @see com.puppycrawl.tools.checkstyle.checks.coding.NestedIfDepthCheck */ public final class NestedForDepthCheck extends AbstractNestedDepthCheck { /** default allowed nesting depth. */ private static final int DEFAULT_MAX = 1; /** Creates new check instance with default allowed nesting depth. */ public NestedForDepthCheck() { super(DEFAULT_MAX); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.LITERAL_FOR}; } @Override public void visitToken(DetailAST aAST) { if (TokenTypes.LITERAL_FOR == aAST.getType()) { nestIn(aAST, "nested.for.depth"); } } @Override public void leaveToken(DetailAST aAST) { if (TokenTypes.LITERAL_FOR == aAST.getType()) { nestOut(); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/NestedIfDepthCheck.java100644 0 0 5571 12026051045 31055 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; /** * Restricts nested if-else blocks to a specified depth (default = 1). * * @author Simon Harris */ public final class NestedIfDepthCheck extends AbstractNestedDepthCheck { /** default allowed nesting depth. */ private static final int DEFAULT_MAX = 1; /** Creates new check instance with default allowed nesting depth. */ public NestedIfDepthCheck() { super(DEFAULT_MAX); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.LITERAL_IF}; } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.LITERAL_IF: visitLiteralIf(aAST); break; default: throw new IllegalStateException(aAST.toString()); } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.LITERAL_IF: leaveLiteralIf(aAST); break; default: throw new IllegalStateException(aAST.toString()); } } /** * Increases current nesting depth. * @param aIf node for if. */ private void visitLiteralIf(DetailAST aIf) { if (!CheckUtils.isElseIf(aIf)) { nestIn(aIf, "nested.if.depth"); } } /** * Decreases current nesting depth. * @param aIf node for if. */ private void leaveLiteralIf(DetailAST aIf) { if (!CheckUtils.isElseIf(aIf)) { nestOut(); } } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/NestedTryDepthCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/NestedTryDepthCheck.java100644 0 0 5237 12026051045 31274 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Restricts nested try-catch-finally blocks to a specified depth (default = 1). * @author Simon Harris */ public final class NestedTryDepthCheck extends AbstractNestedDepthCheck { /** default allowed nesting depth */ private static final int DEFAULT_MAX = 1; /** Creates new check instance with default allowed nesting depth. */ public NestedTryDepthCheck() { super(DEFAULT_MAX); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.LITERAL_TRY}; } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.LITERAL_TRY: visitLiteralTry(aAST); break; default: throw new IllegalStateException(aAST.toString()); } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.LITERAL_TRY: leaveLiteralTry(); break; default: throw new IllegalStateException(aAST.toString()); } } /** * Increases current nesting depth. * @param aTry node for try. */ private void visitLiteralTry(DetailAST aTry) { nestIn(aTry, "nested.try.depth"); } /** Decreases current nesting depth */ private void leaveLiteralTry() { nestOut(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheck.java100644 0 0 11651 12026051045 27740 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; /** *

* Checks that the clone method is not overridden from the * Object class. *

* *

* Rationale: The clone method relies on strange/hard to follow rules that * do not work it all situations. Consequently, it is difficult to * override correctly. Below are some of the rules/reasons why the clone * method should be avoided. * *

    *
  • * Classes supporting the clone method should implement the Cloneable * interface but the Cloneable interface does not include the clone method. * As a result, it doesn't enforce the method override. *
  • *
  • * The Cloneable interface forces the Object's clone method to work * correctly. Without implementing it, the Object's clone method will * throw a CloneNotSupportedException. *
  • *
  • * Non-final classes must return the object returned from a call to * super.clone(). *
  • *
  • * Final classes can use a constructor to create a clone which is different * from non-final classes. *
  • *
  • * If a super class implements the clone method incorrectly all subclasses * calling super.clone() are doomed to failure. *
  • *
  • * If a class has references to mutable objects then those object * references must be replaced with copies in the clone method * after calling super.clone(). *
  • *
  • * The clone method does not work correctly with final mutable object * references because final references cannot be reassigned. *
  • *
  • * If a super class overrides the clone method then all subclasses must * provide a correct clone implementation. *
  • *
*

* *

* Two alternatives to the clone method, in some cases, is a copy constructor * or a static factory method to return copies of an object. Both of these * approaches are simpler and do not conflict with final fields. The do not * force the calling client to handle a CloneNotSuportException. They also * are typed therefore no casting is necessary. Finally, they are more * flexible since they can take interface types rather than concrete classes. *

* *

* Sometimes a copy constructor or static factory is not an acceptable * alternative to the clone method. The example below highlights the * limitation of a copy constructor (or static factory). Assume * Square is a subclass for Shape. * *

 * Shape s1 = new Square();
 * System.out.println(s1 instanceof Square); //true
 * 
* * ...assume at this point the code knows nothing of s1 being a Square * that's the beauty of polymorphism but the code wants to copy * the Square which is declared as a Shape, its super type... * *
 * Shape s2 = new Shape(s1); //using the copy constructor
 * System.out.println(s2 instanceof Square); //false
 * 
* * The working solution (without knowing about all subclasses and doing many * casts) is to do the following (assuming correct clone implementation). * *
 * Shape s2 = s1.clone();
 * System.out.println(s2 instanceof Square); //true
 * 
* * Just keep in mind if this type of polymorphic cloning is required * then a properly implemented clone method may be the best choice. *

* *

* Much of this information was taken from Effective Java: * Programming Language Guide First Edition by Joshua Bloch * pages 45-52. Give Bloch credit for writing an excellent book. *

* *

* This check is almost exactly the same as the {@link NoFinalizerCheck} *

* * @author Travis Schneeberger * @version 1.0 * @see java.lang.Object#clone() * @see java.lang.Cloneable * @see java.lang.CloneNotSupportedException */ public class NoCloneCheck extends AbstractIllegalMethodCheck { /** * Creates an instance. */ public NoCloneCheck() { super("clone", "avoid.clone.method"); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/NoFinalizerCheck.java100644 0 0 2764 12026051045 30610 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; /** * Checks that no method having zero parameters is defined * using the name finalize. * * @author fqian@google.com (Feng Qian) * @author smckay@google.com (Steve McKay) * @author lkuehne */ public class NoFinalizerCheck extends AbstractIllegalMethodCheck { /** * Creates an instance. */ public NoFinalizerCheck() { super("finalize", "avoid.finalizer.method"); } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheck100644 0 0 7414 12026051045 31332 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Restricts the number of statements per line to one. * @author Alexander Jesse * @author Oliver Burn */ public final class OneStatementPerLineCheck extends Check { /** hold the line-number where the last statement ended. */ private int mLastStatementEnd = -1; /** tracks the depth of EXPR tokens. */ private int mExprDepth; /** * The for-header usually has 3 statements on one line, but THIS IS OK. */ private boolean mInForHeader; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.EXPR, TokenTypes.SEMI, TokenTypes.FOR_INIT, TokenTypes.FOR_ITERATOR, }; } @Override public void beginTree(DetailAST aRootAST) { mExprDepth = 0; mInForHeader = false; mLastStatementEnd = -1; } @Override public void visitToken(DetailAST aAst) { switch (aAst.getType()) { case TokenTypes.EXPR: visitExpr(aAst); break; case TokenTypes.SEMI: visitSemi(aAst); break; case TokenTypes.FOR_INIT: mInForHeader = true; break; default: break; } } @Override public void leaveToken(DetailAST aAst) { switch (aAst.getType()) { case TokenTypes.FOR_ITERATOR: mInForHeader = false; break; case TokenTypes.EXPR: mExprDepth--; break; default: break; } } /** * Mark the state-change for the statement (entering) and remember the * first line of the last statement. If the first line of the new * statement is the same as the last line of the last statement and we are * not within a for-statement, then the rule is violated. * @param aAst token for the {@link TokenTypes#EXPR}. */ private void visitExpr(DetailAST aAst) { mExprDepth++; if (mExprDepth == 1) { if (!mInForHeader && (mLastStatementEnd == aAst.getLineNo())) { log(aAst, "multiple.statements.line"); } } } /** * Mark the state-change for the statement (leaving) and remember the last * line of the last statement. * @param aAst for the {@link TokenTypes#SEMI}. */ private void visitSemi(DetailAST aAst) { if (mExprDepth == 0) { mLastStatementEnd = aAst.getLineNo(); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/package-info.java100644 0 0 2277 12026051042 27752 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the Coding checks that are * bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks.coding; ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/PackageDeclarationCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/PackageDeclarationCheck.100644 0 0 7043 12026051044 31221 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.io.File; /** * Ensures there is a package declaration. * Rationale: Classes that live in the null package cannot be * imported. Many novice developers are not aware of this. * * @author Simon Harris * @author Oliver Burn */ public final class PackageDeclarationCheck extends Check { /** is package defined. */ private boolean mDefined; /** whether to ignore the directory name matches the package. */ private boolean mIgnoreDirectoryName; /** * Set whether to ignore checking the directory name. * @param aValue the new value. */ public void setIgnoreDirectoryName(boolean aValue) { mIgnoreDirectoryName = aValue; } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.PACKAGE_DEF}; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void beginTree(DetailAST aAST) { mDefined = false; } @Override public void finishTree(DetailAST aAST) { if (!mDefined) { log(aAST.getLineNo(), "missing.package.declaration"); } } @Override public void visitToken(DetailAST aAST) { mDefined = true; if (mIgnoreDirectoryName) { return; } // Calculate the directory name, but stripping off the last // part. final String fname = getFileContents().getFilename(); final int lastPos = fname.lastIndexOf(File.separatorChar); final String dirname = fname.substring(0, lastPos); // Convert the found package name into the expected directory name. final DetailAST nameAST = aAST.getLastChild().getPreviousSibling(); final FullIdent full = FullIdent.createFullIdent(nameAST); final String expected = full.getText().replace('.', File.separatorChar); // Finally see that the real directory ends with the expected directory if (!dirname.endsWith(expected)) { log(full.getLineNo(), full.getColumnNo(), "package.dir.mismatch", expected); } } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/ParameterAssignmentCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/ParameterAssignmentCheck100644 0 0 16130 12026051044 31430 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.Set; /** *

* Disallow assignment of parameters. *

*

* Rationale: * Parameter assignment is often considered poor * programming practice. Forcing developers to declare * parameters as final is often onerous. Having a check * ensure that parameters are never assigned would give * the best of both worlds. *

* @author Simon Harris */ public final class ParameterAssignmentCheck extends Check { /** Stack of methods' parameters. */ private final FastStack> mParameterNamesStack = FastStack.newInstance(); /** Current set of perameters. */ private Set mParameterNames; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.ASSIGN, TokenTypes.PLUS_ASSIGN, TokenTypes.MINUS_ASSIGN, TokenTypes.STAR_ASSIGN, TokenTypes.DIV_ASSIGN, TokenTypes.MOD_ASSIGN, TokenTypes.SR_ASSIGN, TokenTypes.BSR_ASSIGN, TokenTypes.SL_ASSIGN, TokenTypes.BAND_ASSIGN, TokenTypes.BXOR_ASSIGN, TokenTypes.BOR_ASSIGN, TokenTypes.INC, TokenTypes.POST_INC, TokenTypes.DEC, TokenTypes.POST_DEC, }; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void beginTree(DetailAST aRootAST) { // clear data mParameterNamesStack.clear(); mParameterNames = null; } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: visitMethodDef(aAST); break; case TokenTypes.ASSIGN: case TokenTypes.PLUS_ASSIGN: case TokenTypes.MINUS_ASSIGN: case TokenTypes.STAR_ASSIGN: case TokenTypes.DIV_ASSIGN: case TokenTypes.MOD_ASSIGN: case TokenTypes.SR_ASSIGN: case TokenTypes.BSR_ASSIGN: case TokenTypes.SL_ASSIGN: case TokenTypes.BAND_ASSIGN: case TokenTypes.BXOR_ASSIGN: case TokenTypes.BOR_ASSIGN: visitAssign(aAST); break; case TokenTypes.INC: case TokenTypes.POST_INC: case TokenTypes.DEC: case TokenTypes.POST_DEC: visitIncDec(aAST); break; default: throw new IllegalStateException(aAST.toString()); } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: leaveMethodDef(); break; case TokenTypes.ASSIGN: case TokenTypes.PLUS_ASSIGN: case TokenTypes.MINUS_ASSIGN: case TokenTypes.STAR_ASSIGN: case TokenTypes.DIV_ASSIGN: case TokenTypes.MOD_ASSIGN: case TokenTypes.SR_ASSIGN: case TokenTypes.BSR_ASSIGN: case TokenTypes.SL_ASSIGN: case TokenTypes.BAND_ASSIGN: case TokenTypes.BXOR_ASSIGN: case TokenTypes.BOR_ASSIGN: case TokenTypes.INC: case TokenTypes.POST_INC: case TokenTypes.DEC: case TokenTypes.POST_DEC: // Do nothing break; default: throw new IllegalStateException(aAST.toString()); } } /** * Ckecks if this is assignments of parameter. * @param aAST assignment to check. */ private void visitAssign(DetailAST aAST) { checkIdent(aAST); } /** * Checks if this is increment/decrement of parameter. * @param aAST dec/inc to check. */ private void visitIncDec(DetailAST aAST) { checkIdent(aAST); } /** * Check if ident is parameter. * @param aAST ident to check. */ private void checkIdent(DetailAST aAST) { if ((mParameterNames != null) && !mParameterNames.isEmpty()) { final DetailAST identAST = aAST.getFirstChild(); if ((identAST != null) && (identAST.getType() == TokenTypes.IDENT) && mParameterNames.contains(identAST.getText())) { log(aAST.getLineNo(), aAST.getColumnNo(), "parameter.assignment", identAST.getText()); } } } /** * Creates new set of parameters and store old one in stack. * @param aAST a method to process. */ private void visitMethodDef(DetailAST aAST) { mParameterNamesStack.push(mParameterNames); mParameterNames = Sets.newHashSet(); visitMethodParameters(aAST.findFirstToken(TokenTypes.PARAMETERS)); } /** Restores old set of parameters. */ private void leaveMethodDef() { mParameterNames = mParameterNamesStack.pop(); } /** * Creates new parameter set for given method. * @param aAST a method for process. */ private void visitMethodParameters(DetailAST aAST) { DetailAST parameterDefAST = aAST.findFirstToken(TokenTypes.PARAMETER_DEF); for (; parameterDefAST != null; parameterDefAST = parameterDefAST.getNextSibling()) { if (parameterDefAST.getType() == TokenTypes.PARAMETER_DEF) { final DetailAST param = parameterDefAST.findFirstToken(TokenTypes.IDENT); mParameterNames.add(param.getText()); } } } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/RedundantThrowsCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/RedundantThrowsCheck.jav100644 0 0 14521 12026051044 31373 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck; import java.util.Iterator; import java.util.List; /** * Checks for redundant exceptions declared in throws clause * such as duplicates, unchecked exceptions or subclasses of * another declared exception. * *

* An example of how to configure the check is: *

*
 * <module name="RedundantThrows">
 *    <property name="allowUnchecked" value="true"/>
 *    <property name="allowSubclasses" value="true"/>
 * </module>
 * 
* @author o_sukhodolsky */ public class RedundantThrowsCheck extends AbstractTypeAwareCheck { /** * whether unchecked exceptions in throws * are allowed or not */ private boolean mAllowUnchecked; /** * whether subclass of another declared * exception is allowed in throws clause */ private boolean mAllowSubclasses; /** * Getter for allowUnchecked property. * @param aAllowUnchecked whether unchecked excpetions in throws * are allowed or not */ public void setAllowUnchecked(boolean aAllowUnchecked) { mAllowUnchecked = aAllowUnchecked; } /** * Getter for allowSubclasses property. * @param aAllowSubclasses whether subclass of another declared * exception is allowed in throws clause */ public void setAllowSubclasses(boolean aAllowSubclasses) { mAllowSubclasses = aAllowSubclasses; } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.PACKAGE_DEF, TokenTypes.IMPORT, TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF, TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, }; } @Override protected final void processAST(DetailAST aAST) { final List knownExcs = Lists.newLinkedList(); final DetailAST throwsAST = aAST.findFirstToken(TokenTypes.LITERAL_THROWS); if (throwsAST != null) { DetailAST child = throwsAST.getFirstChild(); while (child != null) { if ((child.getType() == TokenTypes.IDENT) || (child.getType() == TokenTypes.DOT)) { final FullIdent fi = FullIdent.createFullIdent(child); checkException(fi, knownExcs); } child = child.getNextSibling(); } } } @Override protected final void logLoadError(Token aIdent) { logLoadErrorImpl(aIdent.getLineNo(), aIdent.getColumnNo(), "redundant.throws.classInfo", aIdent.getText()); } /** * Checks if an exception is already know (list of known * exceptions contains it or its superclass) and it's not * a superclass for some known exception and it's not * an unchecked exception. * If it's unknown then it will be added to ist of known exception. * All subclasses of this exception will be deleted from known * and the exception will be added instead. * * @param aExc FullIdent of exception to check * @param aKnownExcs list of already known exception */ private void checkException(FullIdent aExc, List aKnownExcs) { // Let's try to load class. final ClassInfo newClassInfo = createClassInfo(new Token(aExc), getCurrentClassName()); if (!mAllowUnchecked) { if (isUnchecked(newClassInfo.getClazz())) { log(aExc.getLineNo(), aExc.getColumnNo(), "redundant.throws.unchecked", aExc.getText()); } } boolean shouldAdd = true; for (final Iterator known = aKnownExcs.iterator(); known .hasNext();) { final ClassInfo ci = known.next(); final Token fi = ci.getName(); if (ci.getClazz() == newClassInfo.getClazz()) { shouldAdd = false; log(aExc.getLineNo(), aExc.getColumnNo(), "redundant.throws.duplicate", aExc.getText()); } else if (!mAllowSubclasses) { if (isSubclass(ci.getClazz(), newClassInfo.getClazz())) { known.remove(); log(fi.getLineNo(), fi.getColumnNo(), "redundant.throws.subclass", fi.getText(), aExc.getText()); } else if (isSubclass(newClassInfo.getClazz(), ci.getClazz())) { shouldAdd = false; log(aExc.getLineNo(), aExc.getColumnNo(), "redundant.throws.subclass", aExc.getText(), fi.getText()); } } } if (shouldAdd) { aKnownExcs.add(newClassInfo); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java100644 0 0 15034 12026051044 30645 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.DeclarationCollector; /** *

Checks that code doesn't rely on the "this" default. * That is references to instance variables and methods of the present * object are explicitly of the form "this.varName" or * "this.methodName(args)". *

*

Examples of use: *

 * <module name="RequireThis"/>
 * 
* An example of how to configure to check this qualifier for * methods only: *
 * <module name="RequireThis">
 *   <property name="checkFields" value="false"/>
 *   <property name="checkMethods" value="true"/>
 * </module>
 * 
*

*

Limitations: I'm not currently doing anything about static variables * or catch-blocks. Static methods invoked on a class name seem to be OK; * both the class name and the method name have a DOT parent. * Non-static methods invoked on either this or a variable name seem to be * OK, likewise.

*

Much of the code for this check was cribbed from Rick Giles's * HiddenFieldCheck.

* * @author Stephen Bloch * @author o_sukhodolsky */ public class RequireThisCheck extends DeclarationCollector { /** whether we should check fields usage. */ private boolean mCheckFields = true; /** whether we should check methods usage. */ private boolean mCheckMethods = true; /** * Setter for checkFields property. * @param aCheckFields should we check fields usage or not. */ public void setCheckFields(boolean aCheckFields) { mCheckFields = aCheckFields; } /** * @return true if we should check fields usage false otherwise. */ public boolean getCheckFields() { return mCheckFields; } /** * Setter for checkMethods property. * @param aCheckMethods should we check methods usage or not. */ public void setCheckMethods(boolean aCheckMethods) { mCheckMethods = aCheckMethods; } /** * @return true if we should check methods usage false otherwise. */ public boolean getCheckMethods() { return mCheckMethods; } /** Creates new instance of the check. */ public RequireThisCheck() { } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CLASS_DEF, TokenTypes.CTOR_DEF, TokenTypes.ENUM_DEF, TokenTypes.IDENT, TokenTypes.INTERFACE_DEF, TokenTypes.METHOD_DEF, TokenTypes.PARAMETER_DEF, TokenTypes.SLIST, TokenTypes.VARIABLE_DEF, }; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aAST) { super.visitToken(aAST); if (aAST.getType() == TokenTypes.IDENT) { processIDENT(aAST); } } // end visitToken /** * Checks if a given IDENT is method call or field name which * require explicit this qualifier. * * @param aAST IDENT to check. */ private void processIDENT(DetailAST aAST) { final int parentType = aAST.getParent().getType(); if (parentType == TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR || parentType == TokenTypes.ANNOTATION || parentType == TokenTypes.ANNOTATION_FIELD_DEF) { //cannot refer to 'this' from annotations return; } // let's check method calls if (parentType == TokenTypes.METHOD_CALL) { if (mCheckMethods && isClassField(aAST.getText())) { log(aAST, "require.this.method", aAST.getText()); } return; } // let's check fields if (!mCheckFields) { // we shouldn't check fields return; } if (ScopeUtils.getSurroundingScope(aAST) == null) { // it is not a class or interface it's // either import or package // we shouldn't checks this return; } if ((parentType == TokenTypes.DOT) && (aAST.getPreviousSibling() != null)) { // it's the method name in a method call; no problem return; } if ((parentType == TokenTypes.TYPE) || (parentType == TokenTypes.LITERAL_NEW)) { // it's a type name; no problem return; } if ((parentType == TokenTypes.VARIABLE_DEF) || (parentType == TokenTypes.CTOR_DEF) || (parentType == TokenTypes.METHOD_DEF) || (parentType == TokenTypes.CLASS_DEF) || (parentType == TokenTypes.ENUM_DEF) || (parentType == TokenTypes.INTERFACE_DEF) || (parentType == TokenTypes.PARAMETER_DEF)) { // it's being declared; no problem return; } final String name = aAST.getText(); if (isClassField(name)) { log(aAST, "require.this.variable", name); } } } // end class RequireThis checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheck.java100644 0 0 13577 12026051044 30703 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck; /** *

* Restricts return statements to a specified count (default = 2). * Ignores specified methods (equals() by default). *

*

* Rationale: Too many return points can be indication that code is * attempting to do too much or may be difficult to understand. *

* * @author Simon Harris * TODO: Test for inside a static block */ public final class ReturnCountCheck extends AbstractFormatCheck { /** Default allowed number of return statements. */ private static final int DEFAULT_MAX = 2; /** Stack of method contexts. */ private final FastStack mContextStack = FastStack.newInstance(); /** Maximum allowed number of return stmts. */ private int mMax; /** Current method context. */ private Context mContext; /** Creates new instance of the checks. */ public ReturnCountCheck() { super("^equals$"); setMax(DEFAULT_MAX); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.LITERAL_RETURN, }; } @Override public int[] getRequiredTokens() { return new int[]{ TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, }; } /** * Getter for max property. * @return maximum allowed number of return statements. */ public int getMax() { return mMax; } /** * Setter for max property. * @param aMax maximum allowed number of return statements. */ public void setMax(int aMax) { mMax = aMax; } @Override public void beginTree(DetailAST aRootAST) { mContext = null; mContextStack.clear(); } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: visitMethodDef(aAST); break; case TokenTypes.LITERAL_RETURN: mContext.visitLiteralReturn(); break; default: throw new IllegalStateException(aAST.toString()); } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: leaveMethodDef(aAST); break; case TokenTypes.LITERAL_RETURN: // Do nothing break; default: throw new IllegalStateException(aAST.toString()); } } /** * Creates new method context and places old one on the stack. * @param aAST method definition for check. */ private void visitMethodDef(DetailAST aAST) { mContextStack.push(mContext); final DetailAST methodNameAST = aAST.findFirstToken(TokenTypes.IDENT); mContext = new Context(!getRegexp().matcher(methodNameAST.getText()).find()); } /** * Checks number of return statments and restore * previous method context. * @param aAST method def node. */ private void leaveMethodDef(DetailAST aAST) { mContext.checkCount(aAST); mContext = mContextStack.pop(); } /** * Class to encapsulate information about one method. * @author Simon Harris */ private class Context { /** Whether we should check this method or not. */ private final boolean mChecking; /** Counter for return statements. */ private int mCount; /** * Creates new method context. * @param aChecking should we check this method or not. */ public Context(boolean aChecking) { mChecking = aChecking; mCount = 0; } /** Increase number of return statements. */ public void visitLiteralReturn() { ++mCount; } /** * Checks if number of return statements in method more * than allowed. * @param aAST method def associated with this context. */ public void checkCount(DetailAST aAST) { if (mChecking && (mCount > getMax())) { log(aAST.getLineNo(), aAST.getColumnNo(), "return.count", mCount, getMax()); } } } } ././@LongLink100644 0 0 160 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/SimplifyBooleanExpressionCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/SimplifyBooleanExpressio100644 0 0 5313 12026051043 31477 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** *

* Checks for overly complicated boolean expressions. Currently finds code like * if (b == true), b || true, !false, * etc. *

*

* Rationale: Complex boolean logic makes code hard to understand and maintain. *

*

* An example of how to configure the check is: *

*
 * <module name="SimplifyBooleanExpression"/>
 * 
* @author lkuehne */ public class SimplifyBooleanExpressionCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.LITERAL_TRUE, TokenTypes.LITERAL_FALSE}; } @Override public int[] getAcceptableTokens() { // Return empty list to prevent user changing tokens in the // configuration. return new int[] {}; } @Override public int[] getRequiredTokens() { return new int[] {TokenTypes.LITERAL_TRUE, TokenTypes.LITERAL_FALSE}; } @Override public void visitToken(DetailAST aAST) { final DetailAST parent = aAST.getParent(); switch (parent.getType()) { case TokenTypes.NOT_EQUAL: case TokenTypes.EQUAL: case TokenTypes.LNOT: case TokenTypes.LOR: case TokenTypes.LAND: log(parent.getLineNo(), parent.getColumnNo(), "simplify.expression"); break; default: break; } } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/SimplifyBooleanReturnCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/SimplifyBooleanReturnChe100644 0 0 11414 12026051043 31434 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import antlr.collections.AST; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** *

* Checks for overly complicated boolean return statements. * Idea shamelessly stolen from the equivalent PMD rule (pmd.sourceforge.net). *

*

* An example of how to configure the check is: *

*
 * <module name="SimplifyBooleanReturn"/>
 * 
* @author Lars Kühne */ public class SimplifyBooleanReturnCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.LITERAL_IF}; } @Override public void visitToken(DetailAST aAST) { // LITERAL_IF has the following four or five children: // '(' // condition // ')' // thenStatement // [ LITERAL_ELSE (with the elseStatement as a child) ] // don't bother if this is not if then else final AST elseLiteral = aAST.findFirstToken(TokenTypes.LITERAL_ELSE); if (elseLiteral == null) { return; } final AST elseStatement = elseLiteral.getFirstChild(); // skip '(' and ')' // TODO: Introduce helpers in DetailAST final AST condition = aAST.getFirstChild().getNextSibling(); final AST thenStatement = condition.getNextSibling().getNextSibling(); if (returnsOnlyBooleanLiteral(thenStatement) && returnsOnlyBooleanLiteral(elseStatement)) { log(aAST.getLineNo(), aAST.getColumnNo(), "simplify.boolreturn"); } } /** * Returns if an AST is a return statment with a boolean literal * or a compound statement that contains only such a return statement. * * Returns true iff aAST represents *
*
     * return true/false;
     * 
     * or
     * 
*
     * {
     *   return true/false;
     * }
     * 
     *
     * @param aAST the sytax tree to check
     * @return if aAST is a return statment with a boolean literal.
     */
    private static boolean returnsOnlyBooleanLiteral(AST aAST)
    {
        if (isBooleanLiteralReturnStatement(aAST)) {
            return true;
        }

        final AST firstStmnt = aAST.getFirstChild();
        return isBooleanLiteralReturnStatement(firstStmnt);
    }

    /**
     * Returns if an AST is a return statment with a boolean literal.
     *
     * Returns true iff aAST represents
     * 
*
     * return true/false;
     * 
     *
     * @param aAST the sytax tree to check
     * @return if aAST is a return statment with a boolean literal.
     */
    private static boolean isBooleanLiteralReturnStatement(AST aAST)
    {
        if ((aAST == null) || (aAST.getType() != TokenTypes.LITERAL_RETURN)) {
            return false;
        }

        final AST expr = aAST.getFirstChild();

        if ((expr == null) || (expr.getType() == TokenTypes.SEMI)) {
            return false;
        }

        final AST value = expr.getFirstChild();
        return isBooleanLiteralType(value.getType());
    }

    /**
     * Checks if a token type is a literal true or false.
     * @param aTokenType the TokenType
     * @return true iff aTokenType is LITERAL_TRUE or LITERAL_FALSE
     */
    private static boolean isBooleanLiteralType(final int aTokenType)
    {
        final boolean isTrue = (aTokenType == TokenTypes.LITERAL_TRUE);
        final boolean isFalse = (aTokenType == TokenTypes.LITERAL_FALSE);
        return isTrue || isFalse;
    }
}
././@LongLink100644      0      0         154 12026055133  10250 Lustar     0      0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/StringLiteralEqualityCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/StringLiteralEqualityChe100644      0      0        4510 12026051043  31420 0ustar     0      0 ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2012  Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;

import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import antlr.collections.AST;

/**
 * 

Checks that string literals are not used with * == or !=. *

*

* Rationale: Novice Java programmers often use code like * if (x == "something") when they mean * if ("something".equals(x)). *

* * @author Lars Kühne */ public class StringLiteralEqualityCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.EQUAL, TokenTypes.NOT_EQUAL}; } @Override public void visitToken(DetailAST aAST) { // no need to check for nulls here, == and != always have two children final AST firstChild = aAST.getFirstChild(); final AST secondChild = firstChild.getNextSibling(); if ((firstChild.getType() == TokenTypes.STRING_LITERAL) || (secondChild.getType() == TokenTypes.STRING_LITERAL)) { log(aAST.getLineNo(), aAST.getColumnNo(), "string.literal.equality", aAST.getText()); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/SuperCloneCheck.java100644 0 0 3135 12026051043 30436 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; /** *

* Checks that an overriding clone() method invokes super.clone(). *

*

* Reference: * Object.clone. *

*

* An example of how to configure the check is: *

*
 * <module name="SuperClone"/>
 * 
* @author Rick Giles */ public class SuperCloneCheck extends AbstractSuperCheck { @Override protected String getMethodName() { return "clone"; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/SuperFinalizeCheck.java100644 0 0 3175 12026051042 31142 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; /** *

* Checks that an overriding finalize() method invokes super.finalize(). *

*

* Reference: * Cleaning up unused objects. *

*

* An example of how to configure the check is: *

*
 * <module name="SuperFinalize"/>
 * 
* @author Rick Giles */ public class SuperFinalizeCheck extends AbstractSuperCheck { @Override protected String getMethodName() { return "finalize"; } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCh100644 0 0 25035 12026051042 31477 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import antlr.collections.AST; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks if unnecessary parentheses are used in a statement or expression. * The check will flag the following with warnings: *

*
 *     return (x);          // parens around identifier
 *     return (x + 1);      // parens around return value
 *     int x = (y / 2 + 1); // parens around assignment rhs
 *     for (int i = (0); i < 10; i++) {  // parens around literal
 *     t -= (z + 1);        // parens around assignment rhs
*

* The check is not "type aware", that is to say, it can't tell if parentheses * are unnecessary based on the types in an expression. It also doesn't know * about operator precedence and associatvity; therefore it won't catch * something like *

*
 *     int x = (a + b) + c;
*

* In the above case, given that a, b, and c are * all int variables, the parentheses around a + b * are not needed. *

* * @author Eric Roe */ public class UnnecessaryParenthesesCheck extends Check { /** The minimum number of child nodes to consider for a match. */ private static final int MIN_CHILDREN_FOR_MATCH = 3; /** The maximum string length before we chop the string. */ private static final int MAX_QUOTED_LENGTH = 25; /** Token types for literals. */ private static final int [] LITERALS = { TokenTypes.NUM_DOUBLE, TokenTypes.NUM_FLOAT, TokenTypes.NUM_INT, TokenTypes.NUM_LONG, TokenTypes.STRING_LITERAL, TokenTypes.LITERAL_NULL, TokenTypes.LITERAL_FALSE, TokenTypes.LITERAL_TRUE, }; /** Token types for assignment operations. */ private static final int [] ASSIGNMENTS = { TokenTypes.ASSIGN, TokenTypes.BAND_ASSIGN, TokenTypes.BOR_ASSIGN, TokenTypes.BSR_ASSIGN, TokenTypes.BXOR_ASSIGN, TokenTypes.DIV_ASSIGN, TokenTypes.MINUS_ASSIGN, TokenTypes.MOD_ASSIGN, TokenTypes.PLUS_ASSIGN, TokenTypes.SL_ASSIGN, TokenTypes.SR_ASSIGN, TokenTypes.STAR_ASSIGN, }; /** * Used to test if logging a warning in a parent node may be skipped * because a warning was already logged on an immediate child node. */ private DetailAST mParentToSkip; /** Depth of nested assignments. Normally this will be 0 or 1. */ private int mAssignDepth; @Override public int[] getDefaultTokens() { return new int [] { TokenTypes.EXPR, TokenTypes.IDENT, TokenTypes.NUM_DOUBLE, TokenTypes.NUM_FLOAT, TokenTypes.NUM_INT, TokenTypes.NUM_LONG, TokenTypes.STRING_LITERAL, TokenTypes.LITERAL_NULL, TokenTypes.LITERAL_FALSE, TokenTypes.LITERAL_TRUE, TokenTypes.ASSIGN, TokenTypes.BAND_ASSIGN, TokenTypes.BOR_ASSIGN, TokenTypes.BSR_ASSIGN, TokenTypes.BXOR_ASSIGN, TokenTypes.DIV_ASSIGN, TokenTypes.MINUS_ASSIGN, TokenTypes.MOD_ASSIGN, TokenTypes.PLUS_ASSIGN, TokenTypes.SL_ASSIGN, TokenTypes.SR_ASSIGN, TokenTypes.STAR_ASSIGN, }; } @Override public void visitToken(DetailAST aAST) { final int type = aAST.getType(); final boolean surrounded = isSurrounded(aAST); final DetailAST parent = aAST.getParent(); if ((type == TokenTypes.ASSIGN) && (parent.getType() == TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR)) { // shouldn't process assign in annotation pairs return; } // An identifier surrounded by parentheses. if (surrounded && (type == TokenTypes.IDENT)) { mParentToSkip = aAST.getParent(); log(aAST, "unnecessary.paren.ident", aAST.getText()); return; } // A literal (numeric or string) surrounded by parentheses. if (surrounded && inTokenList(type, LITERALS)) { mParentToSkip = aAST.getParent(); if (type == TokenTypes.STRING_LITERAL) { log(aAST, "unnecessary.paren.string", chopString(aAST.getText())); } else { log(aAST, "unnecessary.paren.literal", aAST.getText()); } return; } // The rhs of an assignment surrounded by parentheses. if (inTokenList(type, ASSIGNMENTS)) { mAssignDepth++; final DetailAST last = aAST.getLastChild(); if (last.getType() == TokenTypes.RPAREN) { log(aAST, "unnecessary.paren.assign"); } } } @Override public void leaveToken(DetailAST aAST) { final int type = aAST.getType(); final DetailAST parent = aAST.getParent(); if ((type == TokenTypes.ASSIGN) && (parent.getType() == TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR)) { // shouldn't process assign in annotation pairs return; } // An expression is surrounded by parentheses. if (type == TokenTypes.EXPR) { // If 'mParentToSkip' == 'aAST', then we've already logged a // warning about an immediate child node in visitToken, so we don't // need to log another one here. if ((mParentToSkip != aAST) && exprSurrounded(aAST)) { if (mAssignDepth >= 1) { log(aAST, "unnecessary.paren.assign"); } else if (aAST.getParent().getType() == TokenTypes.LITERAL_RETURN) { log(aAST, "unnecessary.paren.return"); } else { log(aAST, "unnecessary.paren.expr"); } } mParentToSkip = null; } else if (inTokenList(type, ASSIGNMENTS)) { mAssignDepth--; } super.leaveToken(aAST); } /** * Tests if the given DetailAST is surrounded by parentheses. * In short, does aAST have a previous sibling whose type is * TokenTypes.LPAREN and a next sibling whose type is * TokenTypes.RPAREN. * @param aAST the DetailAST to check if it is surrounded by * parentheses. * @return true if aAST is surrounded by * parentheses. */ private boolean isSurrounded(DetailAST aAST) { final DetailAST prev = aAST.getPreviousSibling(); final DetailAST next = aAST.getNextSibling(); return (prev != null) && (prev.getType() == TokenTypes.LPAREN) && (next != null) && (next.getType() == TokenTypes.RPAREN); } /** * Tests if the given expression node is surrounded by parentheses. * @param aAST a DetailAST whose type is * TokenTypes.EXPR. * @return true if the expression is surrounded by * parentheses. * @throws IllegalArgumentException if aAST.getType() is not * equal to TokenTypes.EXPR. */ private boolean exprSurrounded(DetailAST aAST) { if (aAST.getType() != TokenTypes.EXPR) { throw new IllegalArgumentException("Not an expression node."); } boolean surrounded = false; if (aAST.getChildCount() >= MIN_CHILDREN_FOR_MATCH) { final AST n1 = aAST.getFirstChild(); final AST nn = aAST.getLastChild(); surrounded = (n1.getType() == TokenTypes.LPAREN) && (nn.getType() == TokenTypes.RPAREN); } return surrounded; } /** * Check if the given token type can be found in an array of token types. * @param aType the token type. * @param aTokens an array of token types to search. * @return true if aType was found in * aTokens. */ private boolean inTokenList(int aType, int [] aTokens) { // NOTE: Given the small size of the two arrays searched, I'm not sure // it's worth bothering with doing a binary search or using a // HashMap to do the searches. boolean found = false; for (int i = 0; (i < aTokens.length) && !found; i++) { found = aTokens[i] == aType; } return found; } /** * Returns the specified string chopped to MAX_QUOTED_LENGTH * plus an ellipsis (...) if the length of the string exceeds * MAX_QUOTED_LENGTH. * @param aString the string to potentially chop. * @return the chopped string if aString is longer than * MAX_QUOTED_LENGTH; otherwise aString. */ private String chopString(String aString) { if (aString.length() > MAX_QUOTED_LENGTH) { return aString.substring(0, MAX_QUOTED_LENGTH) + "...\""; } return aString; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/DeclarationCollector.java100644 0 0 23630 12026051063 30276 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.LinkedList; import java.util.Set; /** * Abstract class for checks which need to collect information about * declared members/parameters/variables. * * @author o_sukhodolsky */ public abstract class DeclarationCollector extends Check { /** Stack of variable declaration frames. */ private FrameStack mFrames; @Override public void beginTree(DetailAST aRootAST) { mFrames = new FrameStack(); } @Override public void visitToken(DetailAST aAST) { final LexicalFrame frame = this.mFrames.current(); switch (aAST.getType()) { case TokenTypes.VARIABLE_DEF : { final String name = aAST.findFirstToken(TokenTypes.IDENT).getText(); if (frame instanceof ClassFrame) { final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS); if (mods.branchContains(TokenTypes.LITERAL_STATIC)) { ((ClassFrame) frame).addStaticMember(name); } else { ((ClassFrame) frame).addInstanceMember(name); } } else { frame.addName(name); } break; } case TokenTypes.PARAMETER_DEF : { final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT); frame.addName(nameAST.getText()); break; } case TokenTypes.CLASS_DEF : case TokenTypes.INTERFACE_DEF : case TokenTypes.ENUM_DEF : case TokenTypes.ANNOTATION_DEF : { final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT); frame.addName(nameAST.getText()); this.mFrames.enter(new ClassFrame()); break; } case TokenTypes.SLIST : this.mFrames.enter(new BlockFrame()); break; case TokenTypes.METHOD_DEF : { final String name = aAST.findFirstToken(TokenTypes.IDENT).getText(); if (frame instanceof ClassFrame) { final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS); if (mods.branchContains(TokenTypes.LITERAL_STATIC)) { ((ClassFrame) frame).addStaticMember(name); } else { ((ClassFrame) frame).addInstanceMember(name); } } } case TokenTypes.CTOR_DEF : this.mFrames.enter(new MethodFrame()); break; default: // do nothing } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CLASS_DEF : case TokenTypes.INTERFACE_DEF : case TokenTypes.ENUM_DEF : case TokenTypes.ANNOTATION_DEF : case TokenTypes.SLIST : case TokenTypes.METHOD_DEF : case TokenTypes.CTOR_DEF : this.mFrames.leave(); break; default : // do nothing } } /** * Check if given name is a name for class field in current environment. * @param aName a name to check * @return true is the given name is name of method or member. */ protected final boolean isClassField(String aName) { final LexicalFrame frame = mFrames.findFrame(aName); return (frame instanceof ClassFrame) && ((ClassFrame) frame).hasInstanceMember(aName); } /** * A declaration frame. * @author Stephen Bloch * June 19, 2003 */ private abstract static class LexicalFrame { /** Set of name of variables declared in this frame. */ private final Set mVarNames; /** constructor -- invokable only via super() from subclasses */ protected LexicalFrame() { mVarNames = Sets.newHashSet(); } /** add a name to the frame. * @param aNameToAdd the name we're adding */ void addName(String aNameToAdd) { mVarNames.add(aNameToAdd); } /** check whether the frame contains a given name. * @param aNameToFind the name we're looking for * @return whether it was found */ boolean contains(String aNameToFind) { return mVarNames.contains(aNameToFind); } } /** * The global frame; should hold only class names. * @author Stephen Bloch */ private static class GlobalFrame extends LexicalFrame { } /** * A frame initiated at method definition; holds parameter names. * @author Stephen Bloch */ private static class MethodFrame extends LexicalFrame { } /** * A frame initiated at class definition; holds instance variable * names. For the present, I'm not worried about other class names, * method names, etc. * @author Stephen Bloch */ private static class ClassFrame extends LexicalFrame { /** Set of name of instance members declared in this frame. */ private final Set mInstanceMembers; /** Set of name of variables declared in this frame. */ private final Set mStaticMembers; /** * Creates new instance of ClassFrame */ public ClassFrame() { super(); mInstanceMembers = Sets.newHashSet(); mStaticMembers = Sets.newHashSet(); } /** * Adds static member's name. * @param aName a name of static member of the class */ public void addStaticMember(final String aName) { mStaticMembers.add(aName); } /** * Adds instance member's name. * @param aName a name of instance member of the class */ public void addInstanceMember(final String aName) { mInstanceMembers.add(aName); } /** * Checks if a given name is a known instance member of the class. * @param aName a name to check * @return true is the given name is a name of a known * instance member of the class */ public boolean hasInstanceMember(final String aName) { return mInstanceMembers.contains(aName); } @Override boolean contains(String aNameToFind) { return super.contains(aNameToFind) || mInstanceMembers.contains(aNameToFind) || mStaticMembers.contains(aNameToFind); } } /** * A frame initiated on entering a statement list; holds local variable * names. For the present, I'm not worried about other class names, * method names, etc. * @author Stephen Bloch */ private static class BlockFrame extends LexicalFrame { } /** * A stack of LexicalFrames. Standard issue.... * @author Stephen Bloch */ private static class FrameStack { /** List of lexical frames. */ private final LinkedList mFrameList; /** Creates an empty FrameStack. */ FrameStack() { mFrameList = Lists.newLinkedList(); this.enter(new GlobalFrame()); } /** * Enter a scope, i.e. push a frame on the stack. * @param aNewFrame the already-created frame to push */ void enter(LexicalFrame aNewFrame) { mFrameList.addFirst(aNewFrame); } /** Leave a scope, i.e. pop a frame from the stack. */ void leave() { mFrameList.removeFirst(); } /** * Get current scope, i.e. top frame on the stack. * @return the current frame */ LexicalFrame current() { return mFrameList.getFirst(); } /** * Search this and containing frames for a given name. * @param aNameToFind the name we're looking for * @return the frame in which it was found, or null if not found */ LexicalFrame findFrame(String aNameToFind) { for (LexicalFrame thisFrame : mFrameList) { if (thisFrame.contains(aNameToFind)) { return thisFrame; } } return null; } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/DescendantTokenCheck.java100644 0 0 34616 12026051063 30217 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import antlr.collections.AST; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.Arrays; import java.util.Set; /** *

* Checks for restricted tokens beneath other tokens. *

*

* Examples of how to configure the check: *

*
 * <!-- String literal equality check -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="EQUAL,NOT_EQUAL"/>
 *     <property name="limitedTokens" value="STRING_LITERAL"/>
 *     <property name="maximumNumber" value="0"/>
 *     <property name="maximumDepth" value="1"/>
 * </module>
 *
 * <!-- Switch with no default -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="LITERAL_SWITCH"/>
 *     <property name="maximumDepth" value="2"/>
 *     <property name="limitedTokens" value="LITERAL_DEFAULT"/>
 *     <property name="minimumNumber" value="1"/>
 * </module>
 *
 * <!-- Assert statement may have side effects -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="LITERAL_ASSERT"/>
 *     <property name="limitedTokens" value="ASSIGN,DEC,INC,POST_DEC,
 *     POST_INC,PLUS_ASSIGN,MINUS_ASSIGN,STAR_ASSIGN,DIV_ASSIGN,MOD_ASSIGN,
 *     BSR_ASSIGN,SR_ASSIGN,SL_ASSIGN,BAND_ASSIGN,BXOR_ASSIGN,BOR_ASSIGN,
 *     METHOD_CALL"/>
 *     <property name="maximumNumber" value="0"/>
 * </module>
 *
 * <!-- Initialiser in for performs no setup - use while instead? -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="FOR_INIT"/>
 *     <property name="limitedTokens" value="EXPR"/>
 *     <property name="minimumNumber" value="1"/>
 * </module>
 *
 * <!-- Condition in for performs no check -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="FOR_CONDITION"/>
 *     <property name="limitedTokens" value="EXPR"/>
 *     <property name="minimumNumber" value="1"/>
 * </module>
 *
 * <!-- Switch within switch -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="LITERAL_SWITCH"/>
 *     <property name="limitedTokens" value="LITERAL_SWITCH"/>
 *     <property name="maximumNumber" value="0"/>
 *     <property name="minimumDepth" value="1"/>
 * </module>
 *
 * <!-- Return from within a catch or finally block -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="LITERAL_FINALLY,LITERAL_CATCH"/>
 *     <property name="limitedTokens" value="LITERAL_RETURN"/>
 *     <property name="maximumNumber" value="0"/>
 * </module>
 *
 * <!-- Try within catch or finally block -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="LITERAL_CATCH,LITERAL_FINALLY"/>
 *     <property name="limitedTokens" value="LITERAL_TRY"/>
 *     <property name="maximumNumber" value="0"/>
 * </module>
 *
 * <!-- Too many cases within a switch -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="LITERAL_SWITCH"/>
 *     <property name="limitedTokens" value="LITERAL_CASE"/>
 *     <property name="maximumDepth" value="2"/>
 *     <property name="maximumNumber" value="10"/>
 * </module>
 *
 * <!-- Too many local variables within a method -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="METHOD_DEF"/>
 *     <property name="limitedTokens" value="VARIABLE_DEF"/>
 *     <property name="maximumDepth" value="2"/>
 *     <property name="maximumNumber" value="10"/>
 * </module>
 *
 * <!-- Too many returns from within a method -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="METHOD_DEF"/>
 *     <property name="limitedTokens" value="LITERAL_RETURN"/>
 *     <property name="maximumNumber" value="3"/>
 * </module>
 *
 * <!-- Too many fields within an interface -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="INTERFACE_DEF"/>
 *     <property name="limitedTokens" value="VARIABLE_DEF"/>
 *     <property name="maximumDepth" value="2"/>
 *     <property name="maximumNumber" value="0"/>
 * </module>
 *
 * <!-- Limit the number of exceptions a method can throw -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="LITERAL_THROWS"/>
 *     <property name="limitedTokens" value="IDENT"/>
 *     <property name="maximumNumber" value="1"/>
 * </module>
 *
 * <!-- Limit the number of expressions in a method -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="METHOD_DEF"/>
 *     <property name="limitedTokens" value="EXPR"/>
 *     <property name="maximumNumber" value="200"/>
 * </module>
 *
 * <!-- Disallow empty statements -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="EMPTY_STAT"/>
 *     <property name="limitedTokens" value="EMPTY_STAT"/>
 *     <property name="maximumNumber" value="0"/>
 *     <property name="maximumDepth" value="0"/>
 *     <property name="maximumMessage"
 *         value="Empty statement is not allowed."/>
 * </module>
 *
 * <!-- Too many fields within a class -->
 * <module name="DescendantToken">
 *     <property name="tokens" value="CLASS_DEF"/>
 *     <property name="limitedTokens" value="VARIABLE_DEF"/>
 *     <property name="maximumDepth" value="2"/>
 *     <property name="maximumNumber" value="10"/>
 * </module>
 * 
* * @author Tim Tyler <tim@tt1.org> * @author Rick Giles */ public class DescendantTokenCheck extends Check { /** minimum depth */ private int mMinimumDepth; /** maximum depth */ private int mMaximumDepth = Integer.MAX_VALUE; /** minimum number */ private int mMinimumNumber; /** maximum number */ private int mMaximumNumber = Integer.MAX_VALUE; /** Whether to sum the number of tokens found. */ private boolean mSumTokenCounts; /** limited tokens */ private int[] mLimitedTokens = new int[0]; /** error message when minimum count not reached */ private String mMinimumMessage; /** error message when maximum count exceeded */ private String mMaximumMessage; /** * Counts of descendant tokens. * Indexed by (token ID - 1) for performance. */ private int[] mCounts = new int[0]; @Override public int[] getDefaultTokens() { return new int[0]; } @Override public void visitToken(DetailAST aAST) { //reset counts Arrays.fill(mCounts, 0); countTokens(aAST, 0); // name of this token final String name = TokenTypes.getTokenName(aAST.getType()); if (mSumTokenCounts) { int total = 0; for (int element : mLimitedTokens) { total += mCounts[element - 1]; } if (total < mMinimumNumber) { log(aAST.getLineNo(), aAST.getColumnNo(), (null == mMinimumMessage) ? "descendant.token.sum.min" : mMinimumMessage, String.valueOf(total), String.valueOf(mMinimumNumber), name); } if (total > mMaximumNumber) { log(aAST.getLineNo(), aAST.getColumnNo(), (null == mMaximumMessage) ? "descendant.token.sum.max" : mMaximumMessage, String.valueOf(total), String.valueOf(mMaximumNumber), name); } } else { for (int element : mLimitedTokens) { final int tokenCount = mCounts[element - 1]; if (tokenCount < mMinimumNumber) { final String descendantName = TokenTypes .getTokenName(element); log(aAST.getLineNo(), aAST.getColumnNo(), (null == mMinimumMessage) ? "descendant.token.min" : mMinimumMessage, String.valueOf(tokenCount), String.valueOf(mMinimumNumber), name, descendantName); } if (tokenCount > mMaximumNumber) { final String descendantName = TokenTypes .getTokenName(element); log(aAST.getLineNo(), aAST.getColumnNo(), (null == mMaximumMessage) ? "descendant.token.max" : mMaximumMessage, String.valueOf(tokenCount), String.valueOf(mMaximumNumber), name, descendantName); } } } } /** * Counts the number of occurrences of descendant tokens. * @param aAST the root token for descendants. * @param aDepth the maximum depth of the counted descendants. */ private void countTokens(AST aAST, int aDepth) { if (aDepth <= mMaximumDepth) { //update count if (aDepth >= mMinimumDepth) { final int type = aAST.getType(); if (type <= mCounts.length) { mCounts[type - 1]++; } } AST child = aAST.getFirstChild(); final int nextDepth = aDepth + 1; while (child != null) { countTokens(child, nextDepth); child = child.getNextSibling(); } } } @Override public int[] getAcceptableTokens() { // Any tokens set by property 'tokens' are acceptable final Set tokenNames = getTokenNames(); final int[] result = new int[tokenNames.size()]; int i = 0; for (String name : tokenNames) { result[i++] = TokenTypes.getTokenId(name); } return result; } /** * Sets the tokens which occurance as descendant is limited. * @param aLimitedTokens - list of tokens to ignore. */ public void setLimitedTokens(String[] aLimitedTokens) { mLimitedTokens = new int[aLimitedTokens.length]; int maxToken = 0; for (int i = 0; i < aLimitedTokens.length; i++) { mLimitedTokens[i] = TokenTypes.getTokenId(aLimitedTokens[i]); if (mLimitedTokens[i] > maxToken) { maxToken = mLimitedTokens[i]; } } mCounts = new int[maxToken]; } /** * Sets the mimimum depth for descendant counts. * @param aMinimumDepth the mimimum depth for descendant counts. */ public void setMinimumDepth(int aMinimumDepth) { mMinimumDepth = aMinimumDepth; } /** * Sets the maximum depth for descendant counts. * @param aMaximumDepth the maximum depth for descendant counts. */ public void setMaximumDepth(int aMaximumDepth) { mMaximumDepth = aMaximumDepth; } /** * Sets a minimum count for descendants. * @param aMinimumNumber the minimum count for descendants. */ public void setMinimumNumber(int aMinimumNumber) { mMinimumNumber = aMinimumNumber; } /** * Sets a maximum count for descendants. * @param aMaximumNumber the maximum count for descendants. */ public void setMaximumNumber(int aMaximumNumber) { mMaximumNumber = aMaximumNumber; } /** * Sets the error message for minimum count not reached. * @param aMessage the error message for minimum count not reached. * Used as a MessageFormat pattern with arguments *
    *
  • {0} - token count
  • *
  • {1} - minimum number
  • *
  • {2} - name of token
  • *
  • {3} - name of limited token
  • *
*/ public void setMinimumMessage(String aMessage) { mMinimumMessage = aMessage; } /** * Sets the error message for maximum count exceeded. * @param aMessage the error message for maximum count exceeded. * Used as a MessageFormat pattern with arguments *
    *
  • {0} - token count
  • *
  • {1} - maximum number
  • *
  • {2} - name of token
  • *
  • {3} - name of limited token
  • *
*/ public void setMaximumMessage(String aMessage) { mMaximumMessage = aMessage; } /** * Sets whether to use the sum of the tokens found, rather than the * individual counts. * @param aSum whether to use the sum. */ public void setSumTokenCounts(boolean aSum) { mSumTokenCounts = aSum; } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.100644 0 0 13153 12026051042 31320 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.Scope; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Checks that classes are designed for inheritance. * *

* More specifically, it enforces a programming style * where superclasses provide empty "hooks" that can be * implemented by subclasses. *

* *

* The exact rule is that nonprivate, nonstatic methods in * nonfinal classes (or classes that do not * only have private constructors) must either be *

    *
  • abstract or
  • *
  • final or
  • *
  • have an empty implementation
  • *
*

* *

* This protects superclasses against beeing broken by * subclasses. The downside is that subclasses are limited * in their flexibility, in particular they cannot prevent * execution of code in the superclass, but that also * means that subclasses can't forget to call their super * method. *

* * @author lkuehne */ public class DesignForExtensionCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.METHOD_DEF}; } @Override public void visitToken(DetailAST aAST) { // nothing to do for Interfaces if (ScopeUtils.inInterfaceOrAnnotationBlock(aAST)) { return; } // method is ok if it is private or abstract or final final DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS); if (modifiers.branchContains(TokenTypes.LITERAL_PRIVATE) || modifiers.branchContains(TokenTypes.ABSTRACT) || modifiers.branchContains(TokenTypes.FINAL) || modifiers.branchContains(TokenTypes.LITERAL_STATIC)) { return; } // method is ok if containing class is not visible in API and // cannot be extended by 3rd parties (bug #884035) if (!ScopeUtils.getSurroundingScope(aAST).isIn(Scope.PROTECTED)) { return; } // method is ok if it is implementation can verified to be empty // Note: native methods don't have impl in java code, so // implementation can be null even if method not abstract final DetailAST implementation = aAST.findFirstToken(TokenTypes.SLIST); if ((implementation != null) && (implementation.getFirstChild().getType() == TokenTypes.RCURLY)) { return; } // check if the containing class can be subclassed final DetailAST classDef = findContainingClass(aAST); final DetailAST classMods = classDef.findFirstToken(TokenTypes.MODIFIERS); if ((classDef.getType() == TokenTypes.ENUM_DEF) || classMods.branchContains(TokenTypes.FINAL)) { return; } // check if subclassing is prevented by having only private ctors final DetailAST objBlock = classDef.findFirstToken(TokenTypes.OBJBLOCK); boolean hasDefaultConstructor = true; boolean hasExplNonPrivateCtor = false; DetailAST candidate = objBlock.getFirstChild(); while (candidate != null) { if (candidate.getType() == TokenTypes.CTOR_DEF) { hasDefaultConstructor = false; final DetailAST ctorMods = candidate.findFirstToken(TokenTypes.MODIFIERS); if (!ctorMods.branchContains(TokenTypes.LITERAL_PRIVATE)) { hasExplNonPrivateCtor = true; break; } } candidate = candidate.getNextSibling(); } if (hasDefaultConstructor || hasExplNonPrivateCtor) { final String name = aAST.findFirstToken(TokenTypes.IDENT).getText(); log(aAST.getLineNo(), aAST.getColumnNo(), "design.forExtension", name); } } /** * Searches the tree towards the root until it finds a CLASS_DEF node. * @param aAST the start node for searching * @return the CLASS_DEF node. */ private DetailAST findContainingClass(DetailAST aAST) { DetailAST searchAST = aAST; while ((searchAST.getType() != TokenTypes.CLASS_DEF) && (searchAST.getType() != TokenTypes.ENUM_DEF)) { searchAST = searchAST.getParent(); } return searchAST; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java100644 0 0 13535 12026051042 30430 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that class which has only private ctors * is declared as final. *

*

* An example of how to configure the check is: *

*
 * <module name="FinalClass"/>
 * 
* @author o_sukhodolsky */ public class FinalClassCheck extends Check { /** Keeps ClassDesc objects for stack of declared classes. */ private final FastStack mClasses = FastStack.newInstance(); @Override public int[] getDefaultTokens() { return new int[]{TokenTypes.CLASS_DEF, TokenTypes.CTOR_DEF}; } @Override public void visitToken(DetailAST aAST) { final DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS); if (aAST.getType() == TokenTypes.CLASS_DEF) { final boolean isFinal = (modifiers != null) && modifiers.branchContains(TokenTypes.FINAL); final boolean isAbstract = (modifiers != null) && modifiers.branchContains(TokenTypes.ABSTRACT); mClasses.push(new ClassDesc(isFinal, isAbstract)); } else if (!ScopeUtils.inEnumBlock(aAST)) { //ctors in enums don't matter final ClassDesc desc = mClasses.peek(); if ((modifiers != null) && modifiers.branchContains(TokenTypes.LITERAL_PRIVATE)) { desc.reportPrivateCtor(); } else { desc.reportNonPrivateCtor(); } } } @Override public void leaveToken(DetailAST aAST) { if (aAST.getType() != TokenTypes.CLASS_DEF) { return; } final ClassDesc desc = mClasses.pop(); if (!desc.isDeclaredAsFinal() && !desc.isDeclaredAsAbstract() && desc.hasPrivateCtor() && !desc.hasNonPrivateCtor()) { final String className = aAST.findFirstToken(TokenTypes.IDENT).getText(); log(aAST.getLineNo(), "final.class", className); } } /** maintains information about class' ctors */ private static final class ClassDesc { /** is class declared as final */ private final boolean mDeclaredAsFinal; /** is class declared as abstract */ private final boolean mDeclaredAsAbstract; /** does class have non-provate ctors */ private boolean mHasNonPrivateCtor; /** does class have private ctors */ private boolean mHasPrivateCtor; /** * create a new ClassDesc instance. * @param aDeclaredAsFinal indicates if the * class declared as final * @param aDeclaredAsAbstract indicates if the * class declared as abstract */ ClassDesc(boolean aDeclaredAsFinal, boolean aDeclaredAsAbstract) { mDeclaredAsFinal = aDeclaredAsFinal; mDeclaredAsAbstract = aDeclaredAsAbstract; } /** adds private ctor. */ void reportPrivateCtor() { mHasPrivateCtor = true; } /** adds non-private ctor. */ void reportNonPrivateCtor() { mHasNonPrivateCtor = true; } /** * does class have private ctors. * @return true if class has private ctors */ boolean hasPrivateCtor() { return mHasPrivateCtor; } /** * does class have non-private ctors. * @return true if class has non-private ctors */ boolean hasNonPrivateCtor() { return mHasNonPrivateCtor; } /** * is class declared as final. * @return true if class is declared as final */ boolean isDeclaredAsFinal() { return mDeclaredAsFinal; } /** * is class declared as abstract. * @return true if class is declared as final */ boolean isDeclaredAsAbstract() { return mDeclaredAsAbstract; } @Override public String toString() { return this.getClass().getName() + "[" + "final=" + mDeclaredAsFinal + " abstract=" + mDeclaredAsAbstract + " pctor=" + mHasPrivateCtor + " ctor=" + mHasNonPrivateCtor + "]"; } } } ././@LongLink100644 0 0 162 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/HideUtilityClassConstructorCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/HideUtilityClassConstruc100644 0 0 12162 12026051042 31472 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Make sure that utility classes (classes that contain only static methods) * do not have a public constructor. *

* Rationale: Instantiating utility classes does not make sense. * A common mistake is forgetting to hide the default constructor. *

* * @author lkuehne */ public class HideUtilityClassConstructorCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.CLASS_DEF}; } @Override public void visitToken(DetailAST aAST) { if (isAbstract(aAST)) { // abstract class could not have private constructor return; } final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK); DetailAST child = objBlock.getFirstChild(); final boolean hasStaticModifier = isStatic(aAST); boolean hasMethodOrField = false; boolean hasNonStaticMethodOrField = false; boolean hasNonPrivateStaticMethodOrField = false; boolean hasDefaultCtor = true; boolean hasPublicCtor = false; while (child != null) { final int type = child.getType(); if (type == TokenTypes.METHOD_DEF || type == TokenTypes.VARIABLE_DEF) { hasMethodOrField = true; final DetailAST modifiers = child.findFirstToken(TokenTypes.MODIFIERS); final boolean isStatic = modifiers.branchContains(TokenTypes.LITERAL_STATIC); final boolean isPrivate = modifiers.branchContains(TokenTypes.LITERAL_PRIVATE); if (!isStatic && !isPrivate) { hasNonStaticMethodOrField = true; } if (isStatic && !isPrivate) { hasNonPrivateStaticMethodOrField = true; } } if (type == TokenTypes.CTOR_DEF) { hasDefaultCtor = false; final DetailAST modifiers = child.findFirstToken(TokenTypes.MODIFIERS); if (!modifiers.branchContains(TokenTypes.LITERAL_PRIVATE) && !modifiers.branchContains(TokenTypes.LITERAL_PROTECTED)) { // treat package visible as public // for the purpose of this Check hasPublicCtor = true; } } child = child.getNextSibling(); } final boolean hasAccessibleCtor = (hasDefaultCtor || hasPublicCtor); // figure out if class extends java.lang.object directly // keep it simple for now and get a 99% solution // TODO: check for "extends java.lang.Object" and "extends Object" // consider "import org.omg.CORBA.*" final boolean extendsJLO = // J.Lo even made it into in our sources :-) aAST.findFirstToken(TokenTypes.EXTENDS_CLAUSE) == null; final boolean isUtilClass = extendsJLO && hasMethodOrField && !hasNonStaticMethodOrField && hasNonPrivateStaticMethodOrField; if (isUtilClass && (hasAccessibleCtor && !hasStaticModifier)) { log(aAST.getLineNo(), aAST.getColumnNo(), "hide.utility.class"); } } /** * @param aAST class definition for check. * @return true if a given class declared as abstract. */ private boolean isAbstract(DetailAST aAST) { return aAST.findFirstToken(TokenTypes.MODIFIERS) .branchContains(TokenTypes.ABSTRACT); } /** * @param aAST class definition for check. * @return true if a given class declared as static. */ private boolean isStatic(DetailAST aAST) { return aAST.findFirstToken(TokenTypes.MODIFIERS) .branchContains(TokenTypes.LITERAL_STATIC); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/InnerTypeLastCheck.java100644 0 0 5372 12026051041 31131 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Check nested (internal) classes/interfaces are declared at the bottom of the * class after all method and field declarations. *

* * @author Ruslan Dyachenko */ public class InnerTypeLastCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF}; } /** Meet a root class. */ private boolean mRootClass = true; @Override public void visitToken(DetailAST aAST) { /** First root class */ if (mRootClass) { mRootClass = false; } else { DetailAST nextSibling = aAST.getNextSibling(); while (null != nextSibling && ((nextSibling.getType() != TokenTypes.CLASS_DEF) || (nextSibling.getType() != TokenTypes.INTERFACE_DEF))) { if (nextSibling.getType() == TokenTypes.VARIABLE_DEF || nextSibling.getType() == TokenTypes.METHOD_DEF) { log(nextSibling.getLineNo(), nextSibling.getColumnNo(), "arrangement.members.before.inner"); } nextSibling = nextSibling.getNextSibling(); } } } @Override public void leaveToken(DetailAST aAST) { /** Is this a root class */ if (null == aAST.getParent()) { mRootClass = true; } } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/InterfaceIsTypeCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/InterfaceIsTypeCheck.jav100644 0 0 5740 12026051041 31264 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Implements Bloch, Effective Java, Item 17 - * Use Interfaces only to define types. * *

* An interface should describe a type, it is therefore * inappropriate to define an interface that does not contain any methods * but only constants. *

* *

* The check can be configured to also disallow marker interfaces like * java.io.Serializable, that do not contain methods or * constants at all. *

* * @author lkuehne */ public final class InterfaceIsTypeCheck extends Check { /** flag to control whether marker interfaces are allowed. */ private boolean mAllowMarkerInterfaces = true; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.INTERFACE_DEF}; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aAST) { final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK); final DetailAST methodDef = objBlock.findFirstToken(TokenTypes.METHOD_DEF); final DetailAST variableDef = objBlock.findFirstToken(TokenTypes.VARIABLE_DEF); final boolean methodRequired = !mAllowMarkerInterfaces || (variableDef != null); if ((methodDef == null) && methodRequired) { log(aAST.getLineNo(), "interface.type"); } } /** * Controls whether marker interfaces like Serializable are allowed. * @param aFlag whether to allow marker interfaces or not */ public void setAllowMarkerInterfaces(boolean aFlag) { mAllowMarkerInterfaces = aFlag; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/messages.properties100644 0 0 1166 11451071613 30521 0ustar 0 0 arrangement.members.before.inner=Fields and methods should be before inner classes. design.forExtension=Method ''{0}'' is not designed for extension - needs to be abstract, final or empty. final.class=Class {0} should be declared as final. interface.type=interfaces should describe a type and hence have methods. variable.notPrivate=Variable ''{0}'' must be private and have accessor methods. mutable.exception=The field ''{0}'' must be declared final. throws.count=Throws count is {0,number,integer} (max allowed is {1,number,integer}). hide.utility.class=Utility classes should not have a public or default constructor. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/messages_de.properties100644 0 0 1022 11451071613 31160 0ustar 0 0 design.forExtension=Die Methode ''{0}'' ist nicht für Vererbung entworfen - muss abstract, final oder leer sein. final.class=Die Klasse {0} sollte als final deklariert sein, da alle ihre Konstruktoren private sind. interface.type=Interfaces sollten einen Typ beschreiben und darum Methoden beinhalten. variable.notPrivate=Variable ''{0}'' muss private sein. mutable.exception=Das Feld ''{0}'' muss final deklariert sein. throws.count=Anzahl der throws-Anweisungen ist {0,number,integer} (Obergrenze ist {1,number,integer}). checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/messages_es.properties100644 0 0 755 11451071613 31173 0ustar 0 0 design.forExtension=El método ''{0}'' no está diseñado para ser extendido - necesita ser abstracto, final o vacío. final.class=La clase {0} debería declararse final. interface.type=Los interfaces deberían describir tipos y por tanto tener métodos. variable.notPrivate=La variable ''{0}'' debe ser privada y tener métodos de acceso. mutable.exception=El campo ''{0}'' debe declararse final. throws.count=El número de throws es {0,number,integer} (máximo permitido es {1,number,integer}). checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/messages_fi.properties100644 0 0 717 11451071613 31160 0ustar 0 0 design.forExtension=Metodia ''{0}'' ei ole suunniteltu laajennettavaksi - pit¤isi olla abstrakti, final tai tyhj¤. final.class=Luokan {0} pit¤isi olla final. interface.type=Rajapintojen pit¤isi kuvata tyyppi¤ ja siten sis¤lt¤¤ metodeja. variable.notPrivate=Muuttujan ''{0}'' pit¤¤ olla private ja sill¤ pit¤¤ olla accessorimetodit. throws.count=Heitettyjen poikkeusten lukum¤¤r¤ on {0,number,integer} (suurin sallittu on {1,number,integer}). checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/messages_fr.properties100644 0 0 1442 11451071613 31205 0ustar 0 0 design.forExtension=La méthode ''{0}'' n''est pas conçue pour être dérivée - il faut la déclarer abstraite, finale ou la laisser vide. final.class=La classe {0} devrait être déclarée finale. interface.type=Les interfaces devraient décrire des types et, à ce titre, comporter des méthodes. variable.notPrivate=La variable ''{0}'' devrait être privée et avoir des accesseurs. mutable.exception=L''attribut ''{0}'' devrait être déclarée final. throws.count=Le nombre de clause \"throws\" {0,number,integer}, alors que le maximum autorisé est de {1,number,integer}. throws.count=Le nombre de clause \"throws\" est de {0,number,integer}, alors que le maximum autorisé est de {1,number,integer}. hide.utility.class=Les classes utilitaires ne doivent pas avoir de constructeur par défaut ou public. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/messages_ja.properties100644 0 0 2031 11451071613 31163 0ustar 0 0 design.forExtension=\u30e1\u30bd\u30c3\u30c9 ''{0}'' \u306f\u62e1\u5f35\u3059\u308b\u3088\u3046\u306b\u8a2d\u8a08\u3055\u308c\u3066\u3044\u307e\u305b\u3093 - abstract \u304b final \u304b\u7a7a\u3067\u3042\u308b\u5fc5\u8981\u304c\u3042\u308a\u307e\u3059\u3002 final.class=\u30af\u30e9\u30b9 {0} \u306f final \u3068\u3057\u3066\u5ba3\u8a00\u3059\u3079\u304d\u3067\u3059\u3002 interface.type=\u30a4\u30f3\u30bf\u30d5\u30a7\u30fc\u30b9\u306f\u578b\u3092\u8a18\u8ff0\u3059\u308b\u3082\u306e\u3067\u3042\u308a\u3001\u30e1\u30bd\u30c3\u30c9\u3092\u6301\u3064\u3079\u304d\u3067\u3059\u3002 variable.notPrivate=\u5909\u6570 ''{0}'' \u306f private \u3068\u3057\u3001\u30a2\u30af\u30bb\u30c3\u30b5\u30e1\u30bd\u30c3\u30c9\u3092\u6301\u3064\u3079\u304d\u3067\u3059\u3002 mutable.exception=\u30d5\u30a3\u30fc\u30eb\u30c9 ''{0}'' \u306f final \u5ba3\u8a00\u3057\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002 throws.count=throws \u306e\u6570\u304c {0,number,integer} \uff08\u6700\u5927 {1,number,integer} \u307e\u3067\uff09\u3067\u3059\u3002 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/messages_pt.properties100644 0 0 755 11451071613 31207 0ustar 0 0 design.forExtension=O método ''{0}'' no foi concebido para extenso - precisa de ser abstracto, final ou vazio. final.class=A classe {0} deve ser declarada como final. interface.type=As interfaces devem descrever um tipo e portanto devem ter métodos. mutable.exception=O campo ''{0}'' deve ser declarado final. throws.count=O número de \"throws\" é {0,number,integer} (máx. permitido é {1,number,integer}). variable.notPrivate=Variável ''{0}'' deve ser privada e ter métodos acessores. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/messages_tr.properties100644 0 0 2206 11744664014 31232 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) arrangement.members.before.inner = Alanlar ve metotlar i\u00E7 s\u0131n\u0131flardan \u00F6nce olmal\u0131. design.forExtension = ''{0}'' metodu kendinden t\u00FCretmek i\u00E7in tasarlanmad\u0131 - ''abstract'' ya da ''final'' olarak tan\u0131mlanmal\u0131, veya i\u00E7i bo\u015F olmal\u0131. final.class = {0} s\u0131n\u0131f\u0131 ''final'' olarak tan\u0131mlanmal\u0131. hide.utility.class = Utility s\u0131n\u0131flar\u0131 (sadece ''static'' metotlar i\u00E7eren s\u0131n\u0131flar) ''public'' ya da varsay\u0131lan bir ''constructor'' i\u00E7ermemelidir. interface.type = Aray\u00FCzler bir t\u00FCr olarak tan\u0131mlanmal\u0131, dolay\u0131s\u0131yla metotlar\u0131 olmal\u0131. mutable.exception = ''{0}'' alan\u0131 ''final'' olarak tan\u0131mlanmal\u0131. throws.count = Kullan\u0131lan ''throws'' say\u0131s\u0131 {0,number,integer} (maksimum izin verilen say\u0131 {1,number,integer}). variable.notPrivate = ''{0}'' de\u011Fi\u015Fkeni ''private'' olarak tan\u0131mlanmal\u0131 ve eri\u015Fim metotlar\u0131na(getter/setter) sahip olmal\u0131. ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/MutableExceptionCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/MutableExceptionCheck.ja100644 0 0 11266 12026051041 31330 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck; /** *

Ensures that exceptions (defined as any class name conforming * to some regular expression) are immutable. That is, have only final * fields.

*

Rationale: Exception instances should represent an error * condition. Having non final fields not only allows the state to be * modified by accident and therefore mask the original condition but * also allows developers to accidentally forget to initialise state * thereby leading to code catching the exception to draw incorrect * conclusions based on the state.

* * @author Simon Harris */ public final class MutableExceptionCheck extends AbstractFormatCheck { /** Default value for format property. */ private static final String DEFAULT_FORMAT = "^.*Exception$|^.*Error$"; /** Stack of checking information for classes. */ private final FastStack mCheckingStack = FastStack.newInstance(); /** Should we check current class or not. */ private boolean mChecking; /** Creates new instance of the check. */ public MutableExceptionCheck() { super(DEFAULT_FORMAT); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.CLASS_DEF, TokenTypes.VARIABLE_DEF}; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CLASS_DEF: visitClassDef(aAST); break; case TokenTypes.VARIABLE_DEF: visitVariableDef(aAST); break; default: throw new IllegalStateException(aAST.toString()); } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CLASS_DEF: leaveClassDef(); break; default: // Do nothing } } /** * Called when we start processing class definition. * @param aAST class definition node */ private void visitClassDef(DetailAST aAST) { mCheckingStack.push(mChecking ? Boolean.TRUE : Boolean.FALSE); mChecking = isExceptionClass(aAST.findFirstToken(TokenTypes.IDENT).getText()); } /** Called when we leave class definition. */ private void leaveClassDef() { mChecking = (mCheckingStack.pop()).booleanValue(); } /** * Checks variable definition. * @param aAST variable def node for check. */ private void visitVariableDef(DetailAST aAST) { if (mChecking && (aAST.getParent().getType() == TokenTypes.OBJBLOCK)) { final DetailAST modifiersAST = aAST.findFirstToken(TokenTypes.MODIFIERS); if (!(modifiersAST.findFirstToken(TokenTypes.FINAL) != null)) { log(aAST.getLineNo(), aAST.getColumnNo(), "mutable.exception", aAST.findFirstToken(TokenTypes.IDENT).getText()); } } } /** * @param aClassName class name to check * @return true if a given class name confirms specified format */ private boolean isExceptionClass(String aClassName) { return getRegexp().matcher(aClassName).find(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/package-info.java100644 0 0 2305 12026051041 27747 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the Class Design checks that * are bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks.design; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheck.java100644 0 0 6776 12026051041 30700 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Restricts throws statements to a specified count (default = 1). *

*

* Rationale: * Exceptions form part of a methods interface. Declaring * a method to throw too many differently rooted * exceptions makes exception handling onerous and leads * to poor programming practices such as catch * (Exception). This check forces developers to put * exceptions into a heirachy such that in the simplest * case, only one type of exception need be checked for by * a caller but allows any sub-classes to be caught * specifically if necessary. *

* @author Simon Harris */ public final class ThrowsCountCheck extends Check { /** default value of max property */ private static final int DEFAULT_MAX = 1; /** maximum allowed throws statments */ private int mMax; /** Creates new instance of the check. */ public ThrowsCountCheck() { setMax(DEFAULT_MAX); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.LITERAL_THROWS, }; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } /** * Getter for max property. * @return maximum allowed throws statements. */ public int getMax() { return mMax; } /** * Setter for max property. * @param aMax maximum allowed throws statements. */ public void setMax(int aMax) { mMax = aMax; } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.LITERAL_THROWS: visitLiteralThrows(aAST); break; default: throw new IllegalStateException(aAST.toString()); } } /** * Checks number of throws statments. * @param aAST throws for check. */ private void visitLiteralThrows(DetailAST aAST) { // Account for all the commas! final int count = (aAST.getChildCount() + 1) / 2; if (count > getMax()) { log(aAST.getLineNo(), aAST.getColumnNo(), "throws.count", count, getMax()); } } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheck.100644 0 0 17122 12026051041 31350 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import antlr.collections.AST; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; /** * Checks visibility of class members. Only static final members may be public, * other class members must be private unless allowProtected/Package is set. *

* Public members are not flagged if the name matches the public * member regular expression (contains "^serialVersionUID$" by * default). *

* Rationale: Enforce encapsulation. * * @author lkuehne */ public class VisibilityModifierCheck extends Check { /** whether protected members are allowed */ private boolean mProtectedAllowed; /** whether package visible members are allowed */ private boolean mPackageAllowed; /** * pattern for public members that should be ignored. Note: * Earlier versions of checkstyle used ^f[A-Z][a-zA-Z0-9]*$ as the * default to allow CMP for EJB 1.1 with the default settings. * With EJB 2.0 it is not longer necessary to have public access * for persistent fields. */ private String mPublicMemberFormat = "^serialVersionUID$"; /** regexp for public members that should be ignored */ private Pattern mPublicMemberPattern; /** Create an instance. */ public VisibilityModifierCheck() { setPublicMemberPattern(mPublicMemberFormat); } /** @return whether protected members are allowed */ public boolean isProtectedAllowed() { return mProtectedAllowed; } /** * Set whether protected members are allowed. * @param aProtectedAllowed whether protected members are allowed */ public void setProtectedAllowed(boolean aProtectedAllowed) { mProtectedAllowed = aProtectedAllowed; } /** @return whether package visible members are allowed */ public boolean isPackageAllowed() { return mPackageAllowed; } /** * Set whether package visible members are allowed. * @param aPackageAllowed whether package visible members are allowed */ public void setPackageAllowed(boolean aPackageAllowed) { mPackageAllowed = aPackageAllowed; } /** * Set the pattern for public members to ignore. * @param aPattern pattern for public members to ignore. */ public void setPublicMemberPattern(String aPattern) { try { mPublicMemberPattern = Utils.getPattern(aPattern); mPublicMemberFormat = aPattern; } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aPattern, e); } } /** * @return the regexp for public members to ignore. */ private Pattern getPublicMemberRegexp() { return mPublicMemberPattern; } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.VARIABLE_DEF}; } @Override public void visitToken(DetailAST aAST) { if ((aAST.getType() != TokenTypes.VARIABLE_DEF) || (aAST.getParent().getType() != TokenTypes.OBJBLOCK)) { return; } final DetailAST varNameAST = getVarNameAST(aAST); final String varName = varNameAST.getText(); final boolean inInterfaceOrAnnotationBlock = ScopeUtils.inInterfaceOrAnnotationBlock(aAST); final Set mods = getModifiers(aAST); final String declaredScope = getVisibilityScope(mods); final String variableScope = inInterfaceOrAnnotationBlock ? "public" : declaredScope; if (!("private".equals(variableScope) || inInterfaceOrAnnotationBlock // implicitly static and final || (mods.contains("static") && mods.contains("final")) || ("package".equals(variableScope) && isPackageAllowed()) || ("protected".equals(variableScope) && isProtectedAllowed()) || ("public".equals(variableScope) && getPublicMemberRegexp().matcher(varName).find()))) { log(varNameAST.getLineNo(), varNameAST.getColumnNo(), "variable.notPrivate", varName); } } /** * Returns the variable name in a VARIABLE_DEF AST. * @param aVariableDefAST an AST where type == VARIABLE_DEF AST. * @return the variable name in aVariableDefAST */ private DetailAST getVarNameAST(DetailAST aVariableDefAST) { DetailAST ast = aVariableDefAST.getFirstChild(); while (ast != null) { final DetailAST nextSibling = ast.getNextSibling(); if (ast.getType() == TokenTypes.TYPE) { return nextSibling; } ast = nextSibling; } return null; } /** * Returns the set of modifier Strings for a VARIABLE_DEF AST. * @param aVariableDefAST AST for a vraiable definition * @return the set of modifier Strings for variableDefAST */ private Set getModifiers(DetailAST aVariableDefAST) { final AST modifiersAST = aVariableDefAST.getFirstChild(); if (modifiersAST.getType() != TokenTypes.MODIFIERS) { throw new IllegalStateException("Strange parse tree"); } final Set retVal = Sets.newHashSet(); AST modifier = modifiersAST.getFirstChild(); while (modifier != null) { retVal.add(modifier.getText()); modifier = modifier.getNextSibling(); } return retVal; } /** * Returns the visibility scope specified with a set of modifiers. * @param aModifiers the set of modifier Strings * @return one of "public", "private", "protected", "package" */ private String getVisibilityScope(Set aModifiers) { final String[] explicitModifiers = {"public", "private", "protected"}; for (final String candidate : explicitModifiers) { if (aModifiers.contains(candidate)) { return candidate; } } return "package"; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/ChecksumInfo.java100644 0 0 14034 12026051040 30706 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.duplicates; import java.util.Arrays; /** * Helper class for {@link StrictDuplicateCodeCheck}, * provides block checksum information for a single file. * * @author lkuehne */ final class ChecksumInfo { /** * Helper value to avoid object allocations in * {@link #hasChecksumOverlapsWith(ChecksumInfo)}. */ private static final int[] NO_LINES = new int[0]; /** * Holds the checksums from the constructor call, * except {@link StrictDuplicateCodeCheck#IGNORE}, sorted. */ private int[] mSortedChecksums; /** * Reverse mapping from {@link #mSortedChecksums} to the checksums * from the constructor call. * * mSortedRelevantChecksums[i] == checksums[mOrigIdx[i]] */ private int[] mOrigIdx; /** * Creates a new ChecksumInfo. * * @param aBlockChecksums the block checksums as caculated by * the {@link StrictDuplicateCodeCheck}.ChecksumGenerator */ ChecksumInfo(int[] aBlockChecksums) { final int csLen = aBlockChecksums.length; final int[] relevant = new int[csLen]; final int[] reverse = new int[csLen]; int count = 0; for (int j = 0; j < csLen; j++) { final int checksum = aBlockChecksums[j]; if (checksum != StrictDuplicateCodeCheck.IGNORE) { reverse[count] = j; relevant[count++] = checksum; } } mSortedChecksums = new int[count]; mOrigIdx = new int[count]; System.arraycopy(relevant, 0, mSortedChecksums, 0, count); System.arraycopy(reverse, 0, mOrigIdx, 0, count); sort(); } /** * Sorts the {@link #mSortedChecksums} field and simultaneously * maintains the {@link mOrigIdx} mapping. The maintainance of the * reverse mapping is the reason why we don't simply use Arrays.sort() here. */ private void sort() { // abbreviation for longish field name final int[] arr = mSortedChecksums; final int len = arr.length; // bubblesort will do for now. It's important that the algorithm // is stable, i.e. it doesn't swap equal values for (int i = 0; i < len; i++) { for (int j = i; j > 0 && arr[j] < arr[j - 1]; j--) { final int k = j - 1; // swap j and k and maintain mOrigIdx final int v = arr[j]; arr[j] = arr[k]; arr[k] = v; final int z = mOrigIdx[j]; mOrigIdx[j] = mOrigIdx[k]; mOrigIdx[k] = z; } } } /** * Returns whether the same checksum occurs both in this ChecksumInfo and * another one, * * @param aChecksumInfo the other ChecksumInfo * @return true iff the same checksum occurs in both ChecksumInfos */ boolean hasChecksumOverlapsWith(final ChecksumInfo aChecksumInfo) { final int[] jSortedrelevantChecksums = aChecksumInfo.mSortedChecksums; final int iLen = mSortedChecksums.length; final int jLen = jSortedrelevantChecksums.length; // Both arrays are sorted, so we walk them in parallel, // increasing the index that points to the smaller value. // If the values ever become the same we have found an overlap. int jdx = 0; int idx = 0; while (jdx < jLen && idx < iLen) { final long iSum = mSortedChecksums[idx]; final long jSum = jSortedrelevantChecksums[jdx]; if (iSum < jSum) { idx += 1; } else if (iSum > jSum) { jdx += 1; } else { // files i and j contain a block with the same checksum return true; } } return false; } /** * Returns the lines that start a block with a given checksum. * * @param aSum the checksum * @return sorted line indices */ int[] findLinesWithChecksum(final int aSum) { int idx = Arrays.binarySearch(mSortedChecksums, aSum); if (idx < 0) { return NO_LINES; } // binary search might have left us in the // middle of a sequence of identical checksums // rewind while (idx > 0 && mSortedChecksums[idx - 1] == aSum) { idx -= 1; } final int start = idx; // forward int end = start + 1; while (end < mSortedChecksums.length && mSortedChecksums[end] == mSortedChecksums[end - 1]) { end += 1; } // find original lines through reverse mapping final int[] ret = new int[end - start]; for (int i = 0; i < ret.length; i++) { ret[i] = mOrigIdx[start + i]; } Arrays.sort(ret); return ret; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/messages.properties100644 0 0 116 11451071613 31357 0ustar 0 0 duplicates.lines=Found duplicate of {0} lines in {1}, starting from line {2} ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/messages_de.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/messages_de.properti100644 0 0 105 11451071613 31475 0ustar 0 0 duplicates.lines={0} gleiche Zeilen in {1}, beginnend bei Zeile {2} ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/messages_es.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/messages_es.properti100644 0 0 132 11451071613 31514 0ustar 0 0 duplicates.lines=Se encontraron {0} líneas duplicadas en {1}, comenzando en la línea {2} ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/messages_fr.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/messages_fr.properti100644 0 0 121 11451071613 31512 0ustar 0 0 duplicates.lines=Copier-coller de {0} lignes dans {1}, à partir de la ligne {2} ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/messages_tr.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/messages_tr.properti100644 0 0 326 11744664317 31555 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) duplicates.lines = ''{1}'' dosyas\u0131nda {2} numaral\u0131 sat\u0131rdan itibaren {0} sat\u0131r tekrarlanm\u0131\u015F ifade bulundu. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/package-info.java100644 0 0 2165 12026051040 30636 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Duplicate code detection tools. */ package com.puppycrawl.tools.checkstyle.checks.duplicates; ././@LongLink100644 0 0 156 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/StrictDuplicateCodeCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/duplicates/StrictDuplicateCodeC100644 0 0 46355 12026051040 31424 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.duplicates; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.collect.Multimap; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import com.puppycrawl.tools.checkstyle.api.FileText; import com.puppycrawl.tools.checkstyle.api.MessageDispatcher; import com.puppycrawl.tools.checkstyle.api.Utils; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Performs a line-by-line comparison of all code lines and reports * duplicate code if a sequence of lines differs only in * indentation. All import statements in Java code are ignored, any * other line - including javadoc, whitespace lines between methods, * etc. - is considered (which is why the check is called * strict). * * @author Lars Kühne */ public final class StrictDuplicateCodeCheck extends AbstractFileSetCheck { /** * A prime that is used o calculate checksums of lines and blocks of lines. * Important that it's larger than the length of most lines to avoid hash * collisions. * * For a list of primes see * http://www.utm.edu/research/primes/lists/small/1000.txt */ private static final int BIG_PRIME = 317; /** * Converts each consecutive block of {@link #mMin} lines of the * original source lines to a checksum that is checked against * to find duplicates. */ private interface ChecksumGenerator { /** * Convert each block of the original source lines * to a checksum that is checked against to find duplicates * * @param aOriginalLines the original lines as they appear * in the source file * * @return an array of (aOriginalLines.length - mMin + 1) checksums */ int[] convertLines(String[] aOriginalLines); } /** * Calculates checksums for text files. */ private class TextfileChecksumGenerator implements ChecksumGenerator { /** {@inheritDoc} */ public int[] convertLines(String[] aOriginalLines) { final int lineCount = aOriginalLines.length; final long[] checkSums = new long[lineCount]; for (int i = 0; i < lineCount; i++) { final String line = aOriginalLines[i]; checkSums[i] = calcChecksum(line); } final int retLen = Math.max(0, lineCount - mMin + 1); final int[] ret = new int[retLen]; for (int i = 0; i < retLen; i++) { int blockChecksum = 0; boolean onlyEmptyLines = true; for (int j = 0; j < mMin; j++) { if (aOriginalLines[i + j].length() > 0) { onlyEmptyLines = false; } final long checksum = checkSums[i + j]; if (checksum == IGNORE) { blockChecksum = IGNORE; break; } blockChecksum += (j + 1) * BIG_PRIME * checksum; } ret[i] = onlyEmptyLines ? IGNORE : blockChecksum; } return ret; } /** * Computes a checksum for a a single line of text. * @param aLine the aLine * @return checksum */ protected int calcChecksum(String aLine) { final int hashCode = aLine.hashCode(); if (hashCode == IGNORE) { return Integer.MAX_VALUE / 2; } return hashCode; } } /** * A TextfileChecksumGenerator that also ignores imports. */ private class JavaChecksumGenerator extends TextfileChecksumGenerator { // TODO: return IGNORE for lines in the header comment? // That would require some simple parsing... // we could also parse the java code using the TreeWalker // and then ignore everything before the CLASS_DEF... @Override protected int calcChecksum(String aLine) { // to avoid false alarms it is important that different lines // result in different checksums. if (aLine.startsWith("import ")) { return IGNORE; } return super.calcChecksum(aLine); } } /** a jakarta commons log */ private static final Log LOG = LogFactory.getLog(StrictDuplicateCodeCheck.class); /** the checksum value to use for lines that should be ignored */ static final int IGNORE = Integer.MIN_VALUE; /** default value for mMin */ private static final int DEFAULT_MIN_DUPLICATE_LINES = 12; /** number of lines that have to be idential for reporting duplicates */ private int mMin = DEFAULT_MIN_DUPLICATE_LINES; /** the basedir to strip off in filenames */ private String mBasedir; /** * The checksums of all files that are currently checked. * Dimension one: file index * Dimension two: block start line */ private int[][] mLineBlockChecksums; /** * helper to speed up searching algorithm, holds the checksums from * {@link #mLineBlockChecksums} except {@link #IGNORE}, sorted. */ private ChecksumInfo[] mChecksumInfo; /** files that are currently checked */ private final List mFiles = Lists.newArrayList(); /** * A SoftReference cache for the trimmed lines of a file path. */ private final Map mTrimmedLineCache = new MapMaker().softValues().makeMap(); // fields required only for statistics /** total number of duplicates found */ private int mDuplicates; /** the charset used to load files. */ private String mCharset; /** Creates a new instance of this class. */ public StrictDuplicateCodeCheck() { } /** * Sets the minimum number of lines that must be equivalent * before the check complains. * * @param aMin the number of lines that must be equal before * triggering a 'duplicate code' message. */ public void setMin(int aMin) { if (aMin < 1) { throw new IllegalArgumentException("min must be 1 or higher"); } mMin = aMin; } /** @param aBasedir the base directory to strip off in filenames */ public void setBasedir(String aBasedir) { mBasedir = aBasedir; } @Override public void beginProcessing(String aCharset) { super.beginProcessing(aCharset); mCharset = aCharset; mFiles.clear(); } @Override protected void processFiltered(File aFile, List aLines) { mFiles.add(aFile); } @Override public void finishProcessing() { super.finishProcessing(); final long start = System.currentTimeMillis(); mDuplicates = 0; mLineBlockChecksums = new int[mFiles.size()][]; mChecksumInfo = new ChecksumInfo[mFiles.size()]; if (LOG.isDebugEnabled()) { LOG.debug("Reading " + mFiles.size() + " input files"); } for (int i = 0; i < mFiles.size(); i++) { final File file = mFiles.get(i); try { final String[] lines = getTrimmedLines(file); final ChecksumGenerator transformer = findChecksumGenerator(file); mLineBlockChecksums[i] = transformer.convertLines(lines); } catch (final IOException ex) { LOG.error("Cannot access " + file + " (" + ex.getMessage() + "), ignoring", ex); // TODO: better to throw an exception here? // it would be best to throw IOException from process(), // but interface definition doesn't allow that... mLineBlockChecksums = new int[0][0]; } } fillSortedRelevantChecksums(); final long endReading = System.currentTimeMillis(); findDuplicates(); final long endSearching = System.currentTimeMillis(); dumpStats(start, endReading, endSearching); mLineBlockChecksums = null; mChecksumInfo = null; } /** * Finds the Checksum generator for a given file. * * @param aFile the file to check for duplicates * @return a generator to use for aFile */ private ChecksumGenerator findChecksumGenerator(File aFile) { if (aFile.getName().endsWith(".java")) { return new JavaChecksumGenerator(); } // TODO: Not sure what to do with binary files such as gifs return new TextfileChecksumGenerator(); } /** * Dump out statistics data on stderr. * @param aStart start time * @param aEndReading end time of reading phsical files * @param aEndSearching end time duplicate analysis */ private void dumpStats(long aStart, long aEndReading, long aEndSearching) { if (LOG.isDebugEnabled()) { final long initTime = aEndReading - aStart; final long workTime = aEndSearching - aEndReading; LOG.debug("files = " + mFiles.size()); LOG.debug("duplicates = " + mDuplicates); LOG.debug("Runtime = " + initTime + " + " + workTime); } } /** * filters and sorts the relevant lines and stores the result * in sortedRelevantChecksums during the setup phase. * That data is later used in a binary search to find out * if it is worth investigating a file for duplicates of a block. * If the block's checksum does not occur in the other file * at all, we can skip that file quickly. */ private void fillSortedRelevantChecksums() { for (int i = 0; i < mLineBlockChecksums.length; i++) { final int[] checksums = mLineBlockChecksums[i]; mChecksumInfo[i] = new ChecksumInfo(checksums); } } /** * finds duplicate lines in mFiles, * using a textsearch algorithm to find reoccuring * patters in the lineChecksums. */ private void findDuplicates() { if (LOG.isDebugEnabled()) { LOG.debug("Analysis phase"); } // It's been a while since my CS degree, but I think this is // somewhere near O(LOC^2). // It may be possible to do this *much* smarter, // but I don't have the Knuth bible at hand right now :-) final int len = mFiles.size(); for (int i = 0; i < len; i++) { final String path = mFiles.get(i).getPath(); getMessageCollector().reset(); final MessageDispatcher dispatcher = getMessageDispatcher(); dispatcher.fireFileStarted(path); for (int j = 0; j <= i; j++) { findDuplicatesInFiles(i, j); } fireErrors(path); dispatcher.fireFileFinished(path); } } /** * Compare two files and search for duplicates. * @param aI mLineChecksums index of the first file to compare * @param aJ mLineChecksums index of the seconds file to compare */ private void findDuplicatesInFiles(int aI, int aJ) { final ChecksumInfo iChecksumInfo = mChecksumInfo[aI]; final ChecksumInfo jChecksumInfo = mChecksumInfo[aJ]; if (!iChecksumInfo.hasChecksumOverlapsWith(jChecksumInfo)) { return; } final int[] iLineBlockChecksums = mLineBlockChecksums[aI]; final int iBlockCount = iLineBlockChecksums.length; // blocks of duplicate code might be longer than 'min'. We need to // remember the line combinations where we must ignore identical blocks // because we have already reported them for an earlier blockIdx. final Multimap ignorePairs = ArrayListMultimap.create(); // go through all the blocks in iFile and // check if the following mMin lines occur in jFile for (int iLine = 0; iLine < iBlockCount; iLine++) { final int iSum = iLineBlockChecksums[iLine]; final int[] jLines = jChecksumInfo.findLinesWithChecksum(iSum); // detailed analysis only if the iLine block occurs in jFile at all if (jLines.length > 0) { findDuplicateFromLine(aI, aJ, iLine, jLines, ignorePairs); } } } /** * Find and report a duplicate of the code starting from line aILine * in file aI in the file aJ. The caller has already ensured that * there are at least mMax duplicate lines, this method mainly analyzes * how far the block of duplicates extends. * * @param aI index of file that contains the candidate code * @param aJ index of file that is searched for a dup of the candidate * @param aILine starting line of the candidate in aI * @param aJLines lines in file aJ that have the same checksum as aILine * @param aIgnore Bag from iLine to jLines, an entry indicates that * this line i/j-combination has already been reported as part of another * viloation */ private void findDuplicateFromLine( final int aI, final int aJ, final int aILine, final int[] aJLines, final Multimap aIgnore) { // Using something more advanced like Boyer-Moore might be a // good idea... final int[] iCheckSums = mLineBlockChecksums[aI]; final int[] jCheckSums = mLineBlockChecksums[aJ]; final long checkSum = iCheckSums[aILine]; for (int jLine : aJLines) { if (aI == aJ && aILine >= jLine) { continue; } if (jCheckSums[jLine] != checkSum) { continue; } final Collection ignoreEntries = aIgnore.get(aILine); // avoid Integer constructor whenever we can if (ignoreEntries != null) { if (ignoreEntries.contains(jLine)) { continue; } } final int duplicateLines = verifiyDuplicateLines(aI, aJ, aILine, jLine); if (duplicateLines >= mMin) { reportDuplicate(duplicateLines, aILine, mFiles.get(aJ), jLine); final int extend = duplicateLines - mMin; for (int i = 0; i < extend; i++) { final int offset = (i + 1); aIgnore.put(aILine + offset, jLine + offset); } } } } /** * Verifies the number of lines that are equal. * Note that block checksums might be equal for blocks that in fact * are different, so we must check the actual file content again. * * @param aI file index i * @param aJ file index j * @param aIStartLine start line of potential duplicate code in file i * @param aJStartLine start line of potential duplicate code in file j * @return the number of verified equal lines */ private int verifiyDuplicateLines( int aI, int aJ, int aIStartLine, int aJStartLine) { final File iFile = mFiles.get(aI); final File jFile = mFiles.get(aJ); try { final String[] iLines = getTrimmedLines(iFile); final String[] jLines = getTrimmedLines(jFile); int verified = 0; int i = aIStartLine; int j = aJStartLine; while (i < iLines.length && j < jLines.length && iLines[i++].equals(jLines[j++])) { verified += 1; } return verified; } catch (IOException ex) { LOG.error("Unable to verify potential duplicate for " + iFile + " and " + jFile, ex); return 0; } } /** * Returns the trimmed lines of a given file. * Caches the results, so when memory is available * we try to avoid reading the file repeatedly. * * @param aFile the file * @return the lines in aFile after applying {@link String#trim()} * @throws IOException if the file content cannot be read */ private String[] getTrimmedLines(File aFile) throws IOException { final String path = aFile.getPath(); final String[] cachedLines = mTrimmedLineCache.get(path); if (cachedLines != null) { return cachedLines; } final String charset = mCharset; final FileText text = new FileText(aFile, charset); final String[] lines = getTrimmed(text.toLinesArray()); mTrimmedLineCache.put(path, lines); return lines; } /** * Applies {@link String#trim()} on each String in a given array. * @param aLines the original Strings * @return the converted Strings after applying {@link String#trim()} */ private String[] getTrimmed(String[] aLines) { final String[] ret = new String[aLines.length]; for (int i = 0; i < ret.length; i++) { ret[i] = aLines[i].trim(); } return ret; } /** * Dumps out a duplicate report. * @param aEquivalent number of equivalent lines * @param aILine location of duplicate code * within file that is currently checked * @param aJFile the other file that contains the duplicate * @param aJLine location of duplicate code within aJFile */ private void reportDuplicate( int aEquivalent, int aILine, File aJFile, int aJLine) { final String fileName = Utils.getStrippedFileName(mBasedir, aJFile.getPath()); log(aILine + 1, "duplicates.lines", aEquivalent, fileName, aJLine + 1); mDuplicates += 1; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/FileContentsHolder.java100644 0 0 4507 12026051063 27717 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; /** * Holds the current file contents for global access when configured * as a TreeWalker sub-module. For example, * a filter can access the current file contents through this module. * @author Mike McMahon * @author Rick Giles */ public class FileContentsHolder extends Check { /** The current file contents. */ private static final ThreadLocal FILE_CONTENTS = new ThreadLocal(); /** @return the current file contents. */ public static FileContents getContents() { return FILE_CONTENTS.get(); } @Override public int[] getDefaultTokens() { return new int[0]; } @Override public void beginTree(DetailAST aRootAST) { FILE_CONTENTS.set(getFileContents()); } @Override public void destroy() { // This needs to be called in destroy, rather than finishTree() // as finishTree() is called before the messages are passed to the // filters. Without calling remove, there is a memory leak. FILE_CONTENTS.remove(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java100644 0 0 11273 12026051062 30214 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Check that method/constructor/catch/foreach parameters are final. * The user can set the token set to METHOD_DEF, CONSTRUCTOR_DEF, * LITERAL_CATCH, FOR_EACH_CLAUSE or any combination of these token * types, to control the scope of this check. * Default scope is both METHOD_DEF and CONSTRUCTOR_DEF. * * @author lkuehne * @author o_sukhodolsky * @author Michael Studman */ public class FinalParametersCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, }; } @Override public int[] getAcceptableTokens() { return new int[] { TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, TokenTypes.LITERAL_CATCH, TokenTypes.FOR_EACH_CLAUSE, }; } @Override public void visitToken(DetailAST aAST) { // don't flag interfaces final DetailAST container = aAST.getParent().getParent(); if (container.getType() == TokenTypes.INTERFACE_DEF) { return; } if (aAST.getType() == TokenTypes.LITERAL_CATCH) { visitCatch(aAST); } else if (aAST.getType() == TokenTypes.FOR_EACH_CLAUSE) { visitForEachClause(aAST); } else { visitMethod(aAST); } } /** * Checks parameters of the method or ctor. * @param aMethod method or ctor to check. */ private void visitMethod(final DetailAST aMethod) { // exit on fast lane if there is nothing to check here if (!aMethod.branchContains(TokenTypes.PARAMETER_DEF)) { return; } // ignore abstract method final DetailAST modifiers = aMethod.findFirstToken(TokenTypes.MODIFIERS); if (modifiers.branchContains(TokenTypes.ABSTRACT)) { return; } // we can now be sure that there is at least one parameter final DetailAST parameters = aMethod.findFirstToken(TokenTypes.PARAMETERS); DetailAST child = parameters.getFirstChild(); while (child != null) { // childs are PARAMETER_DEF and COMMA if (child.getType() == TokenTypes.PARAMETER_DEF) { checkParam(child); } child = child.getNextSibling(); } } /** * Checks parameter of the catch block. * @param aCatch catch block to check. */ private void visitCatch(final DetailAST aCatch) { checkParam(aCatch.findFirstToken(TokenTypes.PARAMETER_DEF)); } /** * Checks parameter of the for each clause. * @param aForEachClause for each clause to check. */ private void visitForEachClause(final DetailAST aForEachClause) { checkParam(aForEachClause.findFirstToken(TokenTypes.VARIABLE_DEF)); } /** * Checks if the given parameter is final. * @param aParam parameter to check. */ private void checkParam(final DetailAST aParam) { if (!aParam.branchContains(TokenTypes.FINAL)) { final DetailAST paramName = aParam.findFirstToken(TokenTypes.IDENT); final DetailAST firstNode = CheckUtils.getFirstNode(aParam); log(firstNode.getLineNo(), firstNode.getColumnNo(), "final.parameter", paramName.getText()); } } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/AbstractHeaderCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/AbstractHeaderCheck.java100644 0 0 15074 12026051040 31242 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.header; import com.google.common.collect.ImmutableList; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.List; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Utils; import org.apache.commons.beanutils.ConversionException; /** * Abstract super class for header checks. * Provides support for header and headerFile properties. * @author o_sukhosolsky */ public abstract class AbstractHeaderCheck extends AbstractFileSetCheck { /** The file that contains the header to check against. */ private String mFilename; /** Name of a charset to use for loading the header from a file. */ private String mCharset = System.getProperty("file.encoding", "UTF-8"); /** the lines of the header file. */ private final List mHeaderLines = Lists.newArrayList(); /** * Return the header lines to check against. * @return the header lines to check against. */ protected ImmutableList getHeaderLines() { return ImmutableList.copyOf(mHeaderLines); } /** * Set the charset to use for loading the header from a file. * @param aCharset the charset to use for loading the header from a file * @throws UnsupportedEncodingException if aCharset is unsupported */ public void setCharset(String aCharset) throws UnsupportedEncodingException { if (!Charset.isSupported(aCharset)) { final String message = "unsupported charset: '" + aCharset + "'"; throw new UnsupportedEncodingException(message); } mCharset = aCharset; } /** * Set the header file to check against. * @param aFileName the file that contains the header to check against. */ public void setHeaderFile(String aFileName) { // Handle empty param if ((aFileName == null) || (aFileName.trim().length() == 0)) { return; } mFilename = aFileName; } /** * Load the header from a file. * @throws CheckstyleException if the file cannot be loaded */ private void loadHeaderFile() throws CheckstyleException { checkHeaderNotInitialized(); Reader headerReader = null; try { headerReader = new InputStreamReader(new BufferedInputStream( new FileInputStream(mFilename)), mCharset); loadHeader(headerReader); } catch (final IOException ex) { throw new CheckstyleException( "unable to load header file " + mFilename, ex); } finally { Utils.closeQuietly(headerReader); } } /** * Called before initializing the header. * @throws ConversionException if header has already been set */ private void checkHeaderNotInitialized() { if (!mHeaderLines.isEmpty()) { throw new ConversionException( "header has already been set - " + "set either header or headerFile, not both"); } } /** * Set the header to check against. Individual lines in the header * must be separated by '\n' characters. * @param aHeader header content to check against. * @throws ConversionException if the header cannot be interpreted */ public void setHeader(String aHeader) { if ((aHeader == null) || (aHeader.trim().length() == 0)) { return; } checkHeaderNotInitialized(); final String headerExpandedNewLines = aHeader.replaceAll("\\\\n", "\n"); final Reader headerReader = new StringReader(headerExpandedNewLines); try { loadHeader(headerReader); } catch (final IOException ex) { throw new ConversionException("unable to load header", ex); } finally { Utils.closeQuietly(headerReader); } } /** * Load header to check against from a Reader into mHeaderLines. * @param aHeaderReader delivers the header to check against * @throws IOException if */ private void loadHeader(final Reader aHeaderReader) throws IOException { final LineNumberReader lnr = new LineNumberReader(aHeaderReader); mHeaderLines.clear(); while (true) { final String l = lnr.readLine(); if (l == null) { break; } mHeaderLines.add(l); } postprocessHeaderLines(); } /** * Hook method for post processing header lines. * This implementation does nothing. */ protected void postprocessHeaderLines() { } @Override protected final void finishLocalSetup() throws CheckstyleException { if (mFilename != null) { loadHeaderFile(); } if (mHeaderLines.isEmpty()) { throw new CheckstyleException( "property 'headerFile' is missing or invalid in module " + getConfiguration().getName()); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheck.java100644 0 0 6375 12026051037 27550 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.header; import java.io.File; import java.util.Arrays; import java.util.List; /** * Checks the header of the source against a fixed header file. * * @author Lars Kühne */ public class HeaderCheck extends AbstractHeaderCheck { /** empty array to avoid instantiations. */ private static final int[] EMPTY_INT_ARRAY = new int[0]; /** the header lines to ignore in the check, sorted. */ private int[] mIgnoreLines = EMPTY_INT_ARRAY; /** * @param aLineNo a line number * @return if aLineNo is one of the ignored header lines. */ private boolean isIgnoreLine(int aLineNo) { return (Arrays.binarySearch(mIgnoreLines, aLineNo) >= 0); } /** * Checks if a code line matches the required header line. * @param aLineNumber the line number to check against the header * @param aLine the line contents * @return true if and only if the line matches the required header line */ protected boolean isMatch(int aLineNumber, String aLine) { // skip lines we are meant to ignore return isIgnoreLine(aLineNumber + 1) || getHeaderLines().get(aLineNumber).equals(aLine); } /** * Set the lines numbers to ignore in the header check. * @param aList comma separated list of line numbers to ignore in header. */ public void setIgnoreLines(int[] aList) { if ((aList == null) || (aList.length == 0)) { mIgnoreLines = EMPTY_INT_ARRAY; return; } mIgnoreLines = new int[aList.length]; System.arraycopy(aList, 0, mIgnoreLines, 0, aList.length); Arrays.sort(mIgnoreLines); } @Override protected void processFiltered(File aFile, List aLines) { if (getHeaderLines().size() > aLines.size()) { log(1, "header.missing"); } else { for (int i = 0; i < getHeaderLines().size(); i++) { if (!isMatch(i, aLines.get(i))) { log(i + 1, "header.mismatch", getHeaderLines().get(i)); break; // stop checking } } } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/messages.properties100644 0 0 203 11451071613 30447 0ustar 0 0 header.missing=Missing a header - not enough lines in file. header.mismatch=Line does not match expected header line of ''{0}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/messages_de.properties100644 0 0 212 11451071613 31117 0ustar 0 0 header.missing=Header fehlt - Datei hat nicht genug Zeilen. header.mismatch=Zeile entspricht nicht der erwarteten Header-Zeile ''{0}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/messages_es.properties100644 0 0 237 11451071613 31145 0ustar 0 0 header.missing=Falta una cabecera - no hay líneas suficientes en el fichero. header.mismatch=La línea no coincide con la línea de cabecera esperada ''{0}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/messages_fi.properties100644 0 0 206 11451071613 31130 0ustar 0 0 header.missing=Headeri puuttuu - ei riittävästi rivejä tiedostossa. header.mismatch=Rivi ei ole odotetun ''{0}'' headerin mukainen. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/messages_fr.properties100644 0 0 244 11451071613 31143 0ustar 0 0 header.missing=En-tête manquante - Le fichier ne contient pas assez de lignes. header.mismatch=La ligne ne correspond pas à la ligne d''en-tête attendue ''{0}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/messages_ja.properties100644 0 0 467 11451071613 31135 0ustar 0 0 header.missing=\u30d8\u30c3\u30c0\u304c\u3042\u308a\u307e\u305b\u3093 - \u30d5\u30a1\u30a4\u30eb\u306e\u884c\u6570\u304c\u4e0d\u8db3\u3057\u3066\u3044\u307e\u3059\u3002 header.mismatch=\u884c\u304c\u671f\u5f85\u3055\u308c\u308b\u30d8\u30c3\u30c0\u884c ''{0}'' \u3068\u5408\u81f4\u3057\u307e\u305b\u3093\u3002 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/messages_pt.properties100644 0 0 232 11451071613 31154 0ustar 0 0 header.mismatch=A linha no condiz com a linha de cabeçalho esperada ''{0}''. header.missing=Falta o cabeçalho - o ficheiro no tem linhas suficientes. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/messages_tr.properties100644 0 0 411 11744664014 31165 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) header.mismatch = Sat\u0131r, beklenen ba\u015Fl\u0131k sat\u0131r\u0131 olan ''{0}'' ile e\u015Fle\u015Fmiyor. header.missing = Ba\u015Fl\u0131k eksik - dosyada yeterli sat\u0131r yok. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/package-info.java100644 0 0 2143 12026051037 27733 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * File Header checks. */ package com.puppycrawl.tools.checkstyle.checks.header; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/header/RegexpHeaderCheck.java100644 0 0 12562 12026051037 30736 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.header; import java.util.Arrays; import java.io.File; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.Utils; /** * Checks the header of the source against a header file that contains a * {@link java.util.regex.Pattern regular expression} * for each line of the source header. * * @author Lars Kühne * @author o_sukhodolsky */ public class RegexpHeaderCheck extends AbstractHeaderCheck { /** empty array to avoid instantiations. */ private static final int[] EMPTY_INT_ARRAY = new int[0]; /** the compiled regular expressions */ private final List mHeaderRegexps = Lists.newArrayList(); /** the header lines to repeat (0 or more) in the check, sorted. */ private int[] mMultiLines = EMPTY_INT_ARRAY; /** * Set the lines numbers to repeat in the header check. * @param aList comma separated list of line numbers to repeat in header. */ public void setMultiLines(int[] aList) { if ((aList == null) || (aList.length == 0)) { mMultiLines = EMPTY_INT_ARRAY; return; } mMultiLines = new int[aList.length]; System.arraycopy(aList, 0, mMultiLines, 0, aList.length); Arrays.sort(mMultiLines); } @Override protected void processFiltered(File aFile, List aLines) { final int headerSize = getHeaderLines().size(); final int fileSize = aLines.size(); if (headerSize - mMultiLines.length > fileSize) { log(1, "header.missing"); } else { int headerLineNo = 0; int i; for (i = 0; (headerLineNo < headerSize) && (i < fileSize); i++) { final String line = aLines.get(i); boolean isMatch = isMatch(line, headerLineNo); while (!isMatch && isMultiLine(headerLineNo)) { headerLineNo++; isMatch = (headerLineNo == headerSize) || isMatch(line, headerLineNo); } if (!isMatch) { log(i + 1, "header.mismatch", getHeaderLines().get( headerLineNo)); break; // stop checking } if (!isMultiLine(headerLineNo)) { headerLineNo++; } } if (i == fileSize) { // if file finished, but we have at least one non-multi-line // header isn't completed for (; headerLineNo < headerSize; headerLineNo++) { if (!isMultiLine(headerLineNo)) { log(1, "header.missing"); break; } } } } } /** * Checks if a code line matches the required header line. * @param aLine the code line * @param aHeaderLineNo the header line number. * @return true if and only if the line matches the required header line. */ private boolean isMatch(String aLine, int aHeaderLineNo) { return mHeaderRegexps.get(aHeaderLineNo).matcher(aLine).find(); } /** * @param aLineNo a line number * @return if aLineNo is one of the repeat header lines. */ private boolean isMultiLine(int aLineNo) { return (Arrays.binarySearch(mMultiLines, aLineNo + 1) >= 0); } @Override protected void postprocessHeaderLines() { final List headerLines = getHeaderLines(); mHeaderRegexps.clear(); for (String line : headerLines) { try { // TODO: Not sure if cache in Utils is still necessary mHeaderRegexps.add(Utils.getPattern(line)); } catch (final PatternSyntaxException ex) { throw new ConversionException("line " + (mHeaderRegexps.size() + 1) + " in header specification" + " is not a regular expression"); } } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/AccessResult.java100644 0 0 2552 12026051037 30260 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; /** * Represents the result of an access check. * * @author Oliver Burn */ enum AccessResult { /** Represents that access is allowed. */ ALLOWED, /** Represents that access is disallowed. */ DISALLOWED, /** Represents that access is unknown. */ UNKNOWN } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/AvoidStarImportCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/AvoidStarImportCheck.ja100644 0 0 13202 12026051036 31367 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import java.util.List; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Check that finds import statements that use the * notation. *

*

* Rationale: Importing all classes from a package or static * members from a class leads to tight coupling between packages * or classes and might lead to problems when a new version of a * library introduces name clashes. *

*

* An example of how to configure the check is: *

*
 * <module name="AvoidStarImport">
 *   <property name="excludes" value="java.io,java.net,java.lang.Math"/>
 *   <property name="allowClassImports" value="false"/>
 *   <property name="allowStaticMemberImports" value="false"/>
 * </module>
 * 
* * The optional "excludes" property allows for certain packages like * java.io or java.net to be exempted from the rule. It also is used to * allow certain classes like java.lang.Math or java.io.File to be * excluded in order to support static member imports. * * The optional "allowClassImports" when set to true, will allow starred * class imports but will not affect static member imports. * * The optional "allowStaticMemberImports" when set to true will allow * starred static member imports but will not affect class imports. * * @author Oliver Burn * @author Bill Schneider * @author Travis Schneeberger * @version 2.0 */ public class AvoidStarImportCheck extends Check { /** the packages/classes to exempt from this check. */ private final List mExcludes = Lists.newArrayList(); /** whether to allow all class imports */ private boolean mAllowClassImports; /** whether to allow all static member imports */ private boolean mAllowStaticMemberImports; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT}; } /** * Sets the list of packages or classes to be exempt from the check. * The excludes can contain a .* or not. * @param aExcludes a list of package names/fully-qualifies class names * where star imports are ok */ public void setExcludes(String[] aExcludes) { mExcludes.clear(); for (final String exclude : aExcludes) { mExcludes.add(exclude.endsWith(".*") ? exclude : exclude + ".*"); } } /** * Sets whether or not to allow all non-static class imports. * @param aAllow true to allow false to disallow */ public void setAllowClassImports(boolean aAllow) { mAllowClassImports = aAllow; } /** * Sets whether or not to allow all static member imports. * @param aAllow true to allow false to disallow */ public void setAllowStaticMemberImports(boolean aAllow) { mAllowStaticMemberImports = aAllow; } @Override public void visitToken(final DetailAST aAST) { if (!mAllowClassImports && (TokenTypes.IMPORT == aAST.getType())) { final DetailAST startingDot = aAST.getFirstChild(); logsStarredImportViolation(startingDot); } else if (!mAllowStaticMemberImports && (TokenTypes.STATIC_IMPORT == aAST.getType())) { // must navigate past the static keyword final DetailAST startingDot = aAST.getFirstChild().getNextSibling(); logsStarredImportViolation(startingDot); } } /** * Gets the full import identifier. If the import is a starred import and * it's not excluded then a violation is logged. * @param aStartingDot the starting dot for the import statement */ private void logsStarredImportViolation(DetailAST aStartingDot) { final FullIdent name = FullIdent.createFullIdent(aStartingDot); if (isStaredImport(name) && !mExcludes.contains(name.getText())) { log(aStartingDot.getLineNo(), "import.avoidStar", name.getText()); } } /** * Checks is an import is a stared import. * @param aImportIdent the full import identifier * @return true if a start import false if not */ private boolean isStaredImport(FullIdent aImportIdent) { return (null != aImportIdent) && aImportIdent.getText().endsWith(".*"); } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/AvoidStaticImportCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/AvoidStaticImportCheck.100644 0 0 11261 12026051036 31375 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Check that finds static imports. *

*

* Rationale: Importing static members can lead to naming conflicts * between class' members. It may lead to poor code readability since it * may no longer be clear what class a member resides (without looking * at the import statement). *

*

* An example of how to configure the check is: *

*
 * <module name="AvoidStaticImport">
 *   <property name="excludes"
 *       value="java.lang.System.out,java.lang.Math.*"/>
 * </module>
 * 
* * The optional "excludes" property allows for certain classes via a star * notation to be excluded such as java.lang.Math.* or specific * static members to be excluded like java.lang.System.out for a variable * or java.lang.Math.random for a method. * *

* If you exclude a starred import on a class this automatically * excludes each member individually. *

* *

* For example: * Excluding java.lang.Math.* will allow the import of * each static member in the Math class individually like * java.lang.Math.PI *

* @author Travis Schneeberger * @version 1.0 */ public class AvoidStaticImportCheck extends Check { /** the classes/static members to exempt from this check. */ private String[] mExcludes = new String[0]; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.STATIC_IMPORT}; } /** * Sets the list of classes or static members to be exempt from the check. * @param aExcludes a list of fully-qualified class names/specific * static members where static imports are ok */ public void setExcludes(String[] aExcludes) { mExcludes = aExcludes.clone(); } @Override public void visitToken(final DetailAST aAST) { final DetailAST startingDot = aAST.getFirstChild().getNextSibling(); final FullIdent name = FullIdent.createFullIdent(startingDot); if ((null != name) && !isExempt(name.getText())) { log(startingDot.getLineNo(), "import.avoidStatic", name.getText()); } } /** * Checks if a class or static member is exempt from known excludes. * * @param aClassOrStaticMember * the class or static member * @return true if except false if not */ private boolean isExempt(String aClassOrStaticMember) { for (String exclude : mExcludes) { if (aClassOrStaticMember.equals(exclude)) { return true; } else if (exclude.endsWith(".*")) { //this section allows explicit imports //to be exempt when configured using //a starred import final String excludeMinusDotStar = exclude.substring(0, exclude.length() - 2); if (aClassOrStaticMember.startsWith(excludeMinusDotStar)) { final String member = aClassOrStaticMember.substring( excludeMinusDotStar.length() + 1); //if it contains a dot then it is not a member but a package if (member.indexOf('.') == -1) { return true; } } } } return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/Guard.java100644 0 0 12335 12026051036 26741 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; /** * Represents whether a package is allowed to be used or not. * @author Oliver Burn */ class Guard { /** Indicates if allow access or not. */ private final boolean mAllowed; /** Package to control access to. */ private final String mPkgName; /** Package to control access to. */ private final String mClassName; /** * Indicates if must be an exact match. Only valid if guard using a * package. */ private final boolean mExactMatch; /** Indicates if the guard only applies to this package. */ private final boolean mLocalOnly; /** * Indicates if the package and the class names are to be interpreted * as regular expressions. */ private final boolean mRegExp; /** * Constructs an instance. * @param aAllow whether to allow access. * @param aLocalOnly whether guard is to be applied locally only * @param aPkgName the package to apply guard on. * @param aExactMatch whether the package must match exactly. * @param aRegExp whether the package is to be interpreted as regular * expression. */ Guard(final boolean aAllow, final boolean aLocalOnly, final String aPkgName, final boolean aExactMatch, final boolean aRegExp) { mAllowed = aAllow; mLocalOnly = aLocalOnly; mPkgName = aPkgName; mRegExp = aRegExp; mClassName = null; mExactMatch = aExactMatch; } /** * Constructs an instance. * @param aAllow whether to allow access. * @param aLocalOnly whether guard is to be applied locally only * @param aClassName the class to apply guard on. * @param aRegExp whether the class is to be interpreted as regular * expression. */ Guard(final boolean aAllow, final boolean aLocalOnly, final String aClassName, final boolean aRegExp) { mAllowed = aAllow; mLocalOnly = aLocalOnly; mRegExp = aRegExp; mPkgName = null; mClassName = aClassName; mExactMatch = true; // not used. } /** * Verifies whether a package name be used. * @param aForImport the package to check. * @return a result {@link AccessResult} indicating whether it can be used. */ AccessResult verifyImport(final String aForImport) { assert aForImport != null; if (mClassName != null) { final boolean classMatch = mRegExp ? aForImport.matches(mClassName) : aForImport.equals(mClassName); return calculateResult(classMatch); } // Must be checking a package. First check that we actually match // the package. Then check if matched and we must be an exact match. // In this case, the text after the first "." must not contain // another "." as this indicates that it is not an exact match. assert mPkgName != null; boolean pkgMatch; if (mRegExp) { pkgMatch = aForImport.matches(mPkgName + "\\..*"); if (pkgMatch && mExactMatch) { pkgMatch = !aForImport.matches(mPkgName + "\\..*\\..*"); } } else { pkgMatch = aForImport.startsWith(mPkgName + "."); if (pkgMatch && mExactMatch) { pkgMatch = (aForImport.indexOf('.', (mPkgName.length() + 1)) == -1); } } return calculateResult(pkgMatch); } /** * @return returns whether the guard is to only be applied locally. */ boolean isLocalOnly() { return mLocalOnly; } /** * Returns the appropriate {@link AccessResult} based on whether there * was a match and if the guard is to allow access. * @param aMatched indicates whether there was a match. * @return An appropriate {@link AccessResult}. */ private AccessResult calculateResult(final boolean aMatched) { if (aMatched) { return mAllowed ? AccessResult.ALLOWED : AccessResult.DISALLOWED; } return AccessResult.UNKNOWN; } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheck.java100644 0 0 7646 12026051036 31372 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks for imports from a set of illegal packages. * By default, the check rejects all sun.* packages * since programs that contain direct calls to the sun.* packages * are * not 100% Pure Java. *

*

* To reject other packages, set property illegalPkgs to a comma-separated * list of the illegal packages. *

*

* An example of how to configure the check is: *

*
 * <module name="IllegalImport"/>
 * 
*

* An example of how to configure the check so that it rejects packages * java.io.* and java.sql.* is *

*
 * <module name="IllegalImport">
 *    <property name="illegalPkgs" value="java.io, java.sql"/>
 * </module>
 *
 * Compatible with Java 1.5 source.
 *
 * 
* @author Oliver Burn * @author Lars Kühne * @version 1.0 */ public class IllegalImportCheck extends Check { /** list of illegal packages */ private String[] mIllegalPkgs; /** * Creates a new IllegalImportCheck instance. */ public IllegalImportCheck() { setIllegalPkgs(new String[] {"sun"}); } /** * Set the list of illegal packages. * @param aFrom array of illegal packages */ public void setIllegalPkgs(String[] aFrom) { mIllegalPkgs = aFrom.clone(); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT}; } @Override public void visitToken(DetailAST aAST) { final FullIdent imp; if (aAST.getType() == TokenTypes.IMPORT) { imp = FullIdent.createFullIdentBelow(aAST); } else { imp = FullIdent.createFullIdent( aAST.getFirstChild().getNextSibling()); } if (isIllegalImport(imp.getText())) { log(aAST.getLineNo(), aAST.getColumnNo(), "import.illegal", imp.getText()); } } /** * Checks if an import is from a package that must not be used. * @param aImportText the argument of the import keyword * @return if aImportText contains an illegal package prefix */ private boolean isIllegalImport(String aImportText) { for (String element : mIllegalPkgs) { if (aImportText.startsWith(element + ".")) { return true; } } return false; } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheck.java100644 0 0 12530 12026051036 31445 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import java.io.File; import java.net.URI; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import org.apache.commons.beanutils.ConversionException; /** * Check that controls what packages can be imported in each package. Useful * for ensuring that application layering is not violated. Ideas on how the * check can be improved include support for: *
    *
  • Change the default policy that if a package being checked does not * match any guards, then it is allowed. Currently defaults to disallowed. * *
* @author Oliver Burn */ public class ImportControlCheck extends Check { /** The root package controller. */ private PkgControl mRoot; /** The package doing the import. */ private String mInPkg; /** * The package controller for the current file. Used for performance * optimisation. */ private PkgControl mCurrentLeaf; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.PACKAGE_DEF, TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT, }; } @Override public void beginTree(final DetailAST aRootAST) { mCurrentLeaf = null; } @Override public void visitToken(final DetailAST aAST) { if (aAST.getType() == TokenTypes.PACKAGE_DEF) { final DetailAST nameAST = aAST.getLastChild().getPreviousSibling(); final FullIdent full = FullIdent.createFullIdent(nameAST); if (mRoot == null) { log(nameAST, "import.control.missing.file"); } else { mInPkg = full.getText(); mCurrentLeaf = mRoot.locateFinest(mInPkg); if (mCurrentLeaf == null) { log(nameAST, "import.control.unknown.pkg"); } } } else if (mCurrentLeaf != null) { final FullIdent imp; if (aAST.getType() == TokenTypes.IMPORT) { imp = FullIdent.createFullIdentBelow(aAST); } else { // know it is a static import imp = FullIdent.createFullIdent(aAST .getFirstChild().getNextSibling()); } final AccessResult access = mCurrentLeaf.checkAccess(imp.getText(), mInPkg); if (!AccessResult.ALLOWED.equals(access)) { log(aAST, "import.control.disallowed", imp.getText()); } } } /** * Set the parameter for the url containing the import control * configuration. It will cause the url to be loaded. * @param aUrl the url of the file to load. * @throws ConversionException on error loading the file. */ public void setUrl(final String aUrl) { // Handle empty param if ((aUrl == null) || (aUrl.trim().length() == 0)) { return; } final URI uri; try { uri = URI.create(aUrl); } catch (final IllegalArgumentException ex) { throw new ConversionException("syntax error in url " + aUrl, ex); } try { mRoot = ImportControlLoader.load(uri); } catch (final CheckstyleException ex) { throw new ConversionException("Unable to load " + aUrl, ex); } } /** * Set the parameter for the file containing the import control * configuration. It will cause the file to be loaded. * @param aName the name of the file to load. * @throws ConversionException on error loading the file. */ public void setFile(final String aName) { // Handle empty param if ((aName == null) || (aName.trim().length() == 0)) { return; } try { mRoot = ImportControlLoader.load(new File(aName).toURI()); } catch (final CheckstyleException ex) { throw new ConversionException("Unable to load " + aName, ex); } } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.jav100644 0 0 17521 12026051035 31501 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.api.AbstractLoader; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.FastStack; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Responsible for loading the contents of an import control configuration file. * @author Oliver Burn */ final class ImportControlLoader extends AbstractLoader { /** the public ID for the configuration dtd */ private static final String DTD_PUBLIC_ID_1_0 = "-//Puppy Crawl//DTD Import Control 1.0//EN"; /** the public ID for the configuration dtd */ private static final String DTD_PUBLIC_ID_1_1 = "-//Puppy Crawl//DTD Import Control 1.1//EN"; /** the resource for the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_0 = "com/puppycrawl/tools/checkstyle/checks/imports/import_control_1_0.dtd"; /** the resource for the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_1 = "com/puppycrawl/tools/checkstyle/checks/imports/import_control_1_1.dtd"; /** Used to hold the {@link PkgControl} objects. */ private final FastStack mStack = FastStack.newInstance(); /** the map to lookup the resource name by the id */ private static final Map DTD_RESOURCE_BY_ID = new HashMap(); /** Initialise the map */ static { DTD_RESOURCE_BY_ID.put(DTD_PUBLIC_ID_1_0, DTD_RESOURCE_NAME_1_0); DTD_RESOURCE_BY_ID.put(DTD_PUBLIC_ID_1_1, DTD_RESOURCE_NAME_1_1); } /** * Constructs an instance. * @throws ParserConfigurationException if an error occurs. * @throws SAXException if an error occurs. */ private ImportControlLoader() throws ParserConfigurationException, SAXException { super(DTD_RESOURCE_BY_ID); } @Override public void startElement(final String aNamespaceURI, final String aLocalName, final String aQName, final Attributes aAtts) throws SAXException { if ("import-control".equals(aQName)) { final String pkg = safeGet(aAtts, "pkg"); mStack.push(new PkgControl(pkg)); } else if ("subpackage".equals(aQName)) { assert mStack.size() > 0; final String name = safeGet(aAtts, "name"); mStack.push(new PkgControl(mStack.peek(), name)); } else if ("allow".equals(aQName) || "disallow".equals(aQName)) { assert mStack.size() > 0; // Need to handle either "pkg" or "class" attribute. // May have "exact-match" for "pkg" // May have "local-only" final boolean isAllow = "allow".equals(aQName); final boolean isLocalOnly = (aAtts.getValue("local-only") != null); final String pkg = aAtts.getValue("pkg"); final boolean regex = (aAtts.getValue("regex") != null); final Guard g; if (pkg != null) { final boolean exactMatch = (aAtts.getValue("exact-match") != null); g = new Guard(isAllow, isLocalOnly, pkg, exactMatch, regex); } else { // handle class names which can be normal class names or regular // expressions final String clazz = safeGet(aAtts, "class"); g = new Guard(isAllow, isLocalOnly, clazz, regex); } final PkgControl pc = mStack.peek(); pc.addGuard(g); } } @Override public void endElement(final String aNamespaceURI, final String aLocalName, final String aQName) { if ("subpackage".equals(aQName)) { assert mStack.size() > 1; mStack.pop(); } } /** * Loads the import control file from a file. * @param aUri the uri of the file to load. * @return the root {@link PkgControl} object. * @throws CheckstyleException if an error occurs. */ static PkgControl load(final URI aUri) throws CheckstyleException { InputStream is = null; try { is = aUri.toURL().openStream(); } catch (final MalformedURLException e) { throw new CheckstyleException("syntax error in url " + aUri, e); } catch (final IOException e) { throw new CheckstyleException("unable to find " + aUri, e); } final InputSource source = new InputSource(is); return load(source, aUri); } /** * Loads the import control file from a {@link InputSource}. * @param aSource the source to load from. * @param aUri uri of the source being loaded. * @return the root {@link PkgControl} object. * @throws CheckstyleException if an error occurs. */ private static PkgControl load(final InputSource aSource, final URI aUri) throws CheckstyleException { try { final ImportControlLoader loader = new ImportControlLoader(); loader.parseInputSource(aSource); return loader.getRoot(); } catch (final ParserConfigurationException e) { throw new CheckstyleException("unable to parse " + aUri, e); } catch (final SAXException e) { throw new CheckstyleException("unable to parse " + aUri + " - " + e.getMessage(), e); } catch (final IOException e) { throw new CheckstyleException("unable to read " + aUri, e); } } /** * @return the root {@link PkgControl} object loaded. */ private PkgControl getRoot() { assert mStack.size() == 1; return mStack.peek(); } /** * Utility to safely get an attribute. If it does not exist an exception * is thrown. * @param aAtts collect to get attribute from. * @param aName name of the attribute to get. * @return the value of the attribute. * @throws SAXException if the attribute does not exist. */ private String safeGet(final Attributes aAtts, final String aName) throws SAXException { final String retVal = aAtts.getValue(aName); if (retVal == null) { throw new SAXException("missing attibute " + aName); } return retVal; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.java100644 0 0 32637 12026051035 31111 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck; import java.util.regex.Matcher; import java.util.regex.Pattern; /** *
    *
  • groups imports: ensures that groups of imports come in a specific order * (e.g., java. comes first, javax. comes second, then everything else)
  • *
  • adds a separation between groups : ensures that a blank line sit between * each group
  • *
  • sorts imports inside each group: ensures that imports within each group * are in lexicographic order
  • *
  • sorts according to case: ensures that the comparison between import is * case sensitive
  • *
  • groups static imports: ensures that static imports are at the top (or the * bottom) of all the imports, or above (or under) each group, or are treated * like non static imports (@see {@link ImportOrderOption}
  • *
* *

* Example: *

* *
 *  <module name="ImportOrder">
 *    <property name="groups" value="java,javax"/>
 *    <property name="ordered" value="true"/>
 *    <property name="caseSensitive" value="false"/>
 *    <property name="option" value="above"/>
 *  </module>
 * 
* *

* Group descriptions enclosed in slashes are interpreted as regular * expressions. If multiple groups match, the one matching a longer * substring of the imported name will take precedence, with ties * broken first in favor of earlier matches and finally in favor of * the first matching group. *

* *

* There is always a wildcard group to which everything not in a named group * belongs. If an import does not match a named group, the group belongs to * this wildcard group. The wildcard group position can be specified using the * {@code *} character. *

* *

* Defaults: *

*
    *
  • import groups: none
  • *
  • separation: false
  • *
  • ordered: true
  • *
  • case sensitive: true
  • *
  • static import: under
  • *
* *

* Compatible with Java 1.5 source. *

* * @author Bill Schneider * @author o_sukhodolsky * @author David DIDIER * @author Steve McKay */ public class ImportOrderCheck extends AbstractOptionCheck { /** the special wildcard that catches all remaining groups. */ private static final String WILDCARD_GROUP_NAME = "*"; /** List of import groups specified by the user. */ private Pattern[] mGroups = new Pattern[0]; /** Require imports in group be separated. */ private boolean mSeparated; /** Require imports in group. */ private boolean mOrdered = true; /** Should comparison be case sensitive. */ private boolean mCaseSensitive = true; /** Last imported group. */ private int mLastGroup; /** Line number of last import. */ private int mLastImportLine; /** Name of last import. */ private String mLastImport; /** If last import was static. */ private boolean mLastImportStatic; /** Whether there was any imports. */ private boolean mBeforeFirstImport; /** * Groups static imports under each group. */ public ImportOrderCheck() { super(ImportOrderOption.UNDER, ImportOrderOption.class); } /** * Sets the list of package groups and the order they should occur in the * file. * * @param aGroups a comma-separated list of package names/prefixes. */ public void setGroups(String[] aGroups) { mGroups = new Pattern[aGroups.length]; for (int i = 0; i < aGroups.length; i++) { String pkg = aGroups[i]; Pattern grp; // if the pkg name is the wildcard, make it match zero chars // from any name, so it will always be used as last resort. if (WILDCARD_GROUP_NAME.equals(pkg)) { grp = Pattern.compile(""); // matches any package } else if (pkg.startsWith("/")) { if (!pkg.endsWith("/")) { throw new IllegalArgumentException("Invalid group"); } pkg = pkg.substring(1, pkg.length() - 1); grp = Pattern.compile(pkg); } else { if (!pkg.endsWith(".")) { pkg = pkg + "."; } grp = Pattern.compile("^" + Pattern.quote(pkg)); } mGroups[i] = grp; } } /** * Sets whether or not imports should be ordered within any one group of * imports. * * @param aOrdered * whether lexicographic ordering of imports within a group * required or not. */ public void setOrdered(boolean aOrdered) { mOrdered = aOrdered; } /** * Sets whether or not groups of imports must be separated from one another * by at least one blank line. * * @param aSeparated * whether groups should be separated by oen blank line. */ public void setSeparated(boolean aSeparated) { mSeparated = aSeparated; } /** * Sets whether string comparison should be case sensitive or not. * * @param aCaseSensitive * whether string comparison should be case sensitive. */ public void setCaseSensitive(boolean aCaseSensitive) { mCaseSensitive = aCaseSensitive; } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT}; } @Override public void beginTree(DetailAST aRootAST) { mLastGroup = Integer.MIN_VALUE; mLastImportLine = Integer.MIN_VALUE; mLastImport = ""; mLastImportStatic = false; mBeforeFirstImport = true; } @Override public void visitToken(DetailAST aAST) { final FullIdent ident; final boolean isStatic; if (aAST.getType() == TokenTypes.IMPORT) { ident = FullIdent.createFullIdentBelow(aAST); isStatic = false; } else { ident = FullIdent.createFullIdent(aAST.getFirstChild() .getNextSibling()); isStatic = true; } switch (getAbstractOption()) { case TOP: if (!isStatic && mLastImportStatic) { mLastGroup = Integer.MIN_VALUE; mLastImport = ""; } // no break; case ABOVE: // previous non-static but current is static doVisitToken(ident, isStatic, (!mLastImportStatic && isStatic)); break; case INFLOW: // previous argument is useless here doVisitToken(ident, isStatic, true); break; case BOTTOM: if (isStatic && !mLastImportStatic) { mLastGroup = Integer.MIN_VALUE; mLastImport = ""; } // no break; case UNDER: // previous static but current is non-static doVisitToken(ident, isStatic, (mLastImportStatic && !isStatic)); break; default: break; } mLastImportLine = aAST.findFirstToken(TokenTypes.SEMI).getLineNo(); mLastImportStatic = isStatic; mBeforeFirstImport = false; } /** * Shares processing... * * @param aIdent the import to process. * @param aIsStatic whether the token is static or not. * @param aPrevious previous non-static but current is static (above), or * previous static but current is non-static (under). */ private void doVisitToken(FullIdent aIdent, boolean aIsStatic, boolean aPrevious) { if (aIdent != null) { final String name = aIdent.getText(); final int groupIdx = getGroupNumber(name); final int line = aIdent.getLineNo(); if (groupIdx > mLastGroup) { if (!mBeforeFirstImport && mSeparated) { // This check should be made more robust to handle // comments and imports that span more than one line. if ((line - mLastImportLine) < 2) { log(line, "import.separation", name); } } } else if (groupIdx == mLastGroup) { doVisitTokenInSameGroup(aIdent, aIsStatic, aPrevious, name, line); } else { log(line, "import.ordering", name); } mLastGroup = groupIdx; mLastImport = name; } } /** * Shares processing... * * @param aIdent the import to process. * @param aIsStatic whether the token is static or not. * @param aPrevious previous non-static but current is static (above), or * previous static but current is non-static (under). * @param aName the name of the current import. * @param aLine the line of the current import. */ private void doVisitTokenInSameGroup(FullIdent aIdent, boolean aIsStatic, boolean aPrevious, String aName, int aLine) { if (!mOrdered) { return; } if (getAbstractOption().equals(ImportOrderOption.INFLOW)) { // out of lexicographic order if (compare(mLastImport, aName, mCaseSensitive) > 0) { log(aLine, "import.ordering", aName); } } else { final boolean shouldFireError = // current and previous static or current and // previous non-static (!(mLastImportStatic ^ aIsStatic) && // and out of lexicographic order (compare(mLastImport, aName, mCaseSensitive) > 0)) || // previous non-static but current is static (above) // or // previous static but current is non-static (under) aPrevious; if (shouldFireError) { log(aLine, "import.ordering", aName); } } } /** * Finds out what group the specified import belongs to. * * @param aName the import name to find. * @return group number for given import name. */ private int getGroupNumber(String aName) { int bestIndex = mGroups.length; int bestLength = -1; int bestPos = 0; // find out what group this belongs in // loop over mGroups and get index for (int i = 0; i < mGroups.length; i++) { final Matcher matcher = mGroups[i].matcher(aName); while (matcher.find()) { final int length = matcher.end() - matcher.start(); if ((length > bestLength) || ((length == bestLength) && (matcher.start() < bestPos))) { bestIndex = i; bestLength = length; bestPos = matcher.start(); } } } return bestIndex; } /** * Compares two strings. * * @param aString1 * the first string. * @param aString2 * the second string. * @param aCaseSensitive * whether the comparison is case sensitive. * @return the value 0 if string1 is equal to string2; a value * less than 0 if string1 is lexicographically less * than the string2; and a value greater than 0 if * string1 is lexicographically greater than string2. */ private int compare(String aString1, String aString2, boolean aCaseSensitive) { if (aCaseSensitive) { return aString1.compareTo(aString2); } return aString1.compareToIgnoreCase(aString2); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderOption.java100644 0 0 6503 12026051035 31315 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; /** * Represents the policy for checking import order statements. * @see com.puppycrawl.tools.checkstyle.checks.imports.ImportOrderCheck * @author David DIDIER */ public enum ImportOrderOption { /** * Represents the policy that static imports are all at the top. * For example: * *
        import static java.awt.Button.ABORT;
        import static java.io.File.createTempFile;
        import static javax.swing.WindowConstants.*;

        import java.awt.Button;
        import java.awt.event.ActionEvent;
     * 
*/ TOP, /** * Represents the policy that static imports are above the local group. * For example: * *
        import static java.awt.Button.A;
        import static javax.swing.WindowConstants.*;
        import java.awt.Dialog;
        import javax.swing.JComponent;

        import static java.io.File.createTempFile;
        import java.io.File;
        import java.io.IOException;
     * 
*/ ABOVE, /** * Represents the policy that static imports are processed like non static * imports. For example: * *
        import java.awt.Button;
        import static java.awt.Button.ABORT;
        import java.awt.Dialog;

        import static javax.swing.WindowConstants.HIDE_ON_CLOSE;
        import javax.swing.JComponent;
     * 
*/ INFLOW, /** * Represents the policy that static imports are under the local group. * For example: * *
        import java.awt.Dialog;
        import javax.swing.JComponent;
        import static java.awt.Button.A;
        import static javax.swing.WindowConstants.*;

        import java.io.File;
        import java.io.IOException;
        import static java.io.File.createTempFile;
     * 
*/ UNDER, /** * Represents the policy that static imports are all at the bottom. * For example: * *
        import java.awt.Button;
        import java.awt.event.ActionEvent;

        import static java.awt.Button.ABORT;
        import static java.io.File.createTempFile;
        import static javax.swing.WindowConstants.*;
     * 
*/ BOTTOM; } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/import_control_1_0.dtd100644 0 0 3720 11451071613 31224 0ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/import_control_1_1.dtd100644 0 0 4111 11451071613 31220 0ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/messages.properties100644 0 0 1342 11451071613 30741 0ustar 0 0 import.avoidStar=Using the ''.*'' form of import should be avoided - {0}. import.avoidStatic=Using a static member import should be avoided - {0}. import.duplicate=Duplicate import to line {0,number,integer} - {1}. import.illegal=Import from illegal package - {0}. import.lang=Redundant import from the java.lang package - {0}. import.same=Redundant import from the same package - {0}. import.unused=Unused import - {0}. import.ordering=Wrong order for ''{0}'' import. import.separation=''{0}'' should be separated from previous imports. import.control.missing.file=Missing an import control file. import.control.disallowed=Disallowed import - {0}. import.control.unknown.pkg=Import control file does not handle this package. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/messages_de.properties100644 0 0 1015 11451071613 31406 0ustar 0 0 import.avoidStar=Die Form ''.*'' für import-Anweisungen sollte vermieden werden - {0}. import.duplicate=Gleiches import wie Zeile line {0,number,integer} - {1}. import.illegal=Import aus verbotenem Package - {0}. import.lang=Überflüssiges import aus dem Package java.lang - {0}. import.same=Überflüssiges import aus demselben Package - {0}. import.ordering=Falsche Reihenfolge für import von ''{0}''. import.unused=Nicht benutztes import - {0}. import.separation=''{0}'' sollte von vorherigen imports abgesetzt sein. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/messages_es.properties100644 0 0 754 11451071613 31416 0ustar 0 0 import.avoidStar=Usar la importación con ''.*'' debería evitarse - {0}. import.duplicate=import duplicado en la línea {0,number,integer} - {1}. import.illegal=Importación de un paquete ilegal - {0}. import.lang=Importación redundante del paquete java.lang - {0}. import.same=Importación redundante del mismo paquete - {0}. import.unused=import no usado - {0}. import.ordering=Orden incorrecto para el import ''{0}''. import.separation=''{0}'' debería separarse de los import previos. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/messages_fi.properties100644 0 0 545 11451071613 31403 0ustar 0 0 import.avoidStar=„l¤ k¤yt¤ import-muotoa ''.*'' - {0}. import.duplicate=Duplikaatti-import rivin {0,number,integer} kanssa - {1}. import.illegal=Import s¤¤ntĥjenvastaisesta paketista - {0}. import.lang=Tarpeeton import java.lang-paketista - {0}. import.same=Tarpeeton import samasta paketista - {0}. import.unused=K¤ytt¤m¤tĥn import - {0}. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/messages_fr.properties100644 0 0 1052 11451071613 31426 0ustar 0 0 import.avoidStar=L''utilisation des import.* est prohibé - {0}. import.duplicate=Import dupliqué à la ligne {0,number,integer} - {1}. import.illegal=Import d''un package illégal - {0}. import.lang=Import redondant car la classe importée est située dans le package java.lang - {0}. import.same=Import redondant car la classe importée est située dans le même package - {0}. import.unused=Import inutilisé - {0}. import.ordering=L''ordre d''import n''est pas respecté : ''{0}''. import.separation=''{0}'' devrait être séparé des imports précédents. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/messages_ja.properties100644 0 0 2115 11451071613 31412 0ustar 0 0 import.avoidStar=''.*'' \u5f62\u5f0f\u306e\u30a4\u30f3\u30dd\u30fc\u30c8\u306e\u4f7f\u7528\u306f\u907f\u3051\u308b\u3079\u304d\u3067\u3059 - {0}\u3002 import.duplicate={0,number,integer} \u884c\u76ee\u3068\u91cd\u8907\u3059\u308b\u30a4\u30f3\u30dd\u30fc\u30c8\u3067\u3059 - {1}\u3002 import.illegal=\u4e0d\u6b63\u306a\u30d1\u30c3\u30b1\u30fc\u30b8\u304b\u3089\u306e\u30a4\u30f3\u30dd\u30fc\u30c8\u3067\u3059 - {0}\u3002 import.lang=java.lang \u30d1\u30c3\u30b1\u30fc\u30b8\u304b\u3089\u306e\u30a4\u30f3\u30dd\u30fc\u30c8\u306f\u5197\u9577\u3067\u3059 - {0}\u3002 import.same=\u540c\u4e00\u30d1\u30c3\u30b1\u30fc\u30b8\u304b\u3089\u306e\u30a4\u30f3\u30dd\u30fc\u30c8\u306f\u5197\u9577\u3067\u3059 - {0}\u3002 import.unused=\u4f7f\u7528\u3055\u308c\u306a\u3044\u30a4\u30f3\u30dd\u30fc\u30c8\u3067\u3059 - {0}\u3002 import.ordering=''{0}'' \u306e\u30a4\u30f3\u30dd\u30fc\u30c8\u9806\u5e8f\u304c\u9593\u9055\u3063\u3066\u3044\u307e\u3059\u3002 import.separation=''{0}'' \u306f\u4e0a\u306e\u30a4\u30f3\u30dd\u30fc\u30c8\u6587\u304b\u3089\uff11\u884c\u7a7a\u3051\u308b\u3079\u304d\u3067\u3059\u3002 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/messages_pt.properties100644 0 0 771 11451071613 31431 0ustar 0 0 import.avoidStar=A forma de importaço ''.*'' deve ser evitada - {0}. import.duplicate=Importaço duplicada na linha {0,number,integer}. - {1}. import.illegal=Importaço de um pacote ilegal - {0}. import.lang=Importaço redundande do pacote java.lang - {0}. import.same=Importaço redundante do mesmo pacote - {0}. import.unused=Importaço no utilizada - {0}. import.ordering=Ordenaço incorrecta para a importaço ''{0}''. import.separation=''{0}'' deve ser separado das importaçġes anteriores. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/messages_tr.properties100644 0 0 2314 11744664014 31456 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) import.avoidStar = Y\u0131ld\u0131zl\u0131 (''.*'' \u015Feklinde) import kullan\u0131lmamal\u0131d\u0131r - {0}. import.avoidStatic = ''static'' bir ifade ''import'' edilmemeli - {0}. import.control.disallowed = \u0130zin verilmeyen ''import'' kullan\u0131m\u0131 - {0} import.control.missing.file = ''import'' kontrol dosyas\u0131 eksik. import.control.unknown.pkg = ''import'' kontrol dosyas\u0131 bu paketi kapsam\u0131yor. import.duplicate = ''import'' ifadesi {0,number,integer} sat\u0131r\u0131nda tekrarlanm\u0131\u015F - {1}. import.illegal = Ge\u00E7ersiz paketten ''import'' yap\u0131lm\u0131\u015F - {0}. import.lang = ''java.lang'' paketinden gereksiz ''import'' yap\u0131lm\u0131\u015F - {0}. import.ordering = ''{0}'' ''import'' ifadesinin s\u0131ras\u0131 hatal\u0131. import.same = Ayn\u0131 paketten gereksiz ''import'' yap\u0131lm\u0131\u015F - ''{0}''. import.separation = ''{0}'' ifadesi kendinden \u00F6nceki ''import'' ifadelerinden ayr\u0131lmal\u0131. import.unused = Kullan\u0131lmayan import - {0}. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/package-info.java100644 0 0 2301 12026051034 30171 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the Imports checks that are * bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks.imports; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/PkgControl.java100644 0 0 12551 12026051035 27760 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.google.common.collect.Lists; import java.util.LinkedList; import java.util.List; /** * Represents the a tree of guards for controlling whether packages are allowed * to be used. Each instance must have a single parent or be the root node. * Each instance may have zero or more children. * * @author Oliver Burn */ class PkgControl { /** List of {@link Guard} objects to check. */ private final LinkedList mGuards = Lists.newLinkedList(); /** List of children {@link PkgControl} objects. */ private final List mChildren = Lists.newArrayList(); /** The parent. Null indicates we are the root node. */ private final PkgControl mParent; /** The full package name for the node. */ private final String mFullPackage; /** * Construct a root node. * @param aPkgName the name of the package. */ PkgControl(final String aPkgName) { assert aPkgName != null; mParent = null; mFullPackage = aPkgName; } /** * Construct a child node. * @param aParent the parent node. * @param aSubPkg the sub package name. */ PkgControl(final PkgControl aParent, final String aSubPkg) { assert aParent != null; assert aSubPkg != null; mParent = aParent; mFullPackage = aParent.getFullPackage() + "." + aSubPkg; mParent.mChildren.add(this); } /** * Adds a guard to the node. * @param aThug the guard to be added. */ void addGuard(final Guard aThug) { mGuards.addFirst(aThug); } /** * @return the full package name represented by the node. */ String getFullPackage() { return mFullPackage; } /** * Search down the tree to locate the finest match for a supplied package. * @param aForPkg the package to search for. * @return the finest match, or null if no match at all. */ PkgControl locateFinest(final String aForPkg) { // Check if we are a match. // This algormithm should be improved to check for a trailing "." // or nothing following. if (!aForPkg.startsWith(getFullPackage())) { return null; } // Check if any of the children match. for (PkgControl pc : mChildren) { final PkgControl match = pc.locateFinest(aForPkg); if (match != null) { return match; } } // No match so I am the best there is. return this; } /** * Returns whether a package is allowed to be used. The algorithm checks * with the current node for a result, and if none is found then calls * its parent looking for a match. This will recurse looking for match. * If there is no clear result then {@link AccessResult#UNKNOWN} is * returned. * @param aForImport the package to check on. * @param aInPkg the package doing the import. * @return an {@link AccessResult}. */ AccessResult checkAccess(final String aForImport, final String aInPkg) { final AccessResult retVal = localCheckAccess(aForImport, aInPkg); if (retVal != AccessResult.UNKNOWN) { return retVal; } else if (mParent == null) { // we are the top, so default to not allowed. return AccessResult.DISALLOWED; } return mParent.checkAccess(aForImport, aInPkg); } /** * Checks whether any of the guards for this node control access to * a specified package. * @param aForImport the package to check. * @param aInPkg the package doing the import. * @return an {@link AccessResult}. */ private AccessResult localCheckAccess(final String aForImport, final String aInPkg) { for (Guard g : mGuards) { // Check if a Guard is only meant to be applied locally. if (g.isLocalOnly() && !mFullPackage.equals(aInPkg)) { continue; } final AccessResult result = g.verifyImport(aForImport); if (result != AccessResult.UNKNOWN) { return result; } } return AccessResult.UNKNOWN; } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/RedundantImportCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/RedundantImportCheck.ja100644 0 0 12226 12026051035 31423 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.Set; /** *

* Checks for imports that are redundant. An import statement is * considered redundant if: *

*
    *
  • It is a duplicate of another import. This is, when a class is imported * more than once.
  • *
  • The class non-statically imported is from the java.lang * package. For example importing java.lang.String.
  • *
  • The class non-statically imported is from the same package as the * current package.
  • *
*

* An example of how to configure the check is: *

*
 * <module name="RedundantImport"/>
 * 
* * Compatible with Java 1.5 source. * * @author Oliver Burn * @version 1.0 */ public class RedundantImportCheck extends Check { /** name of package in file */ private String mPkgName; /** set of the imports */ private final Set mImports = Sets.newHashSet(); /** set of static imports */ private final Set mStaticImports = Sets.newHashSet(); @Override public void beginTree(DetailAST aRootAST) { mPkgName = null; mImports.clear(); mStaticImports.clear(); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT, TokenTypes.PACKAGE_DEF, }; } @Override public void visitToken(DetailAST aAST) { if (aAST.getType() == TokenTypes.PACKAGE_DEF) { mPkgName = FullIdent.createFullIdent( aAST.getLastChild().getPreviousSibling()).getText(); } else if (aAST.getType() == TokenTypes.IMPORT) { final FullIdent imp = FullIdent.createFullIdentBelow(aAST); if (fromPackage(imp.getText(), "java.lang")) { log(aAST.getLineNo(), aAST.getColumnNo(), "import.lang", imp.getText()); } else if (fromPackage(imp.getText(), mPkgName)) { log(aAST.getLineNo(), aAST.getColumnNo(), "import.same", imp.getText()); } // Check for a duplicate import for (FullIdent full : mImports) { if (imp.getText().equals(full.getText())) { log(aAST.getLineNo(), aAST.getColumnNo(), "import.duplicate", full.getLineNo(), imp.getText()); } } mImports.add(imp); } else { // Check for a duplicate static import final FullIdent imp = FullIdent.createFullIdent( aAST.getLastChild().getPreviousSibling()); for (FullIdent full : mStaticImports) { if (imp.getText().equals(full.getText())) { log(aAST.getLineNo(), aAST.getColumnNo(), "import.duplicate", full.getLineNo(), imp.getText()); } } mStaticImports.add(imp); } } /** * Determines if an import statement is for types from a specified package. * @param aImport the import name * @param aPkg the package name * @return whether from the package */ private static boolean fromPackage(String aImport, String aPkg) { boolean retVal = false; if (aPkg == null) { // If not package, then check for no package in the import. retVal = (aImport.indexOf('.') == -1); } else { final int index = aImport.lastIndexOf('.'); if (index != -1) { final String front = aImport.substring(0, index); retVal = front.equals(aPkg); } } return retVal; } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/UnusedImportsCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/imports/UnusedImportsCheck.java100644 0 0 15726 12026051034 31463 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTags; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTag; import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocUtils; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** *

* Checks for unused import statements. *

*

* An example of how to configure the check is: *

*
 * <module name="UnusedImports"/>
 * 
* * Compatible with Java 1.5 source. * * @author Oliver Burn */ public class UnusedImportsCheck extends Check { /** flag to indicate when time to start collecting references */ private boolean mCollect; /** flag whether to process Javadoc comments. */ private boolean mProcessJavadoc; /** set of the imports */ private final Set mImports = Sets.newHashSet(); /** set of references - possibly to imports or other things */ private final Set mReferenced = Sets.newHashSet(); /** Default constructor. */ public UnusedImportsCheck() { } public void setProcessJavadoc(boolean aValue) { mProcessJavadoc = aValue; } @Override public void beginTree(DetailAST aRootAST) { mCollect = false; mImports.clear(); mReferenced.clear(); } @Override public void finishTree(DetailAST aRootAST) { // loop over all the imports to see if referenced. for (final FullIdent imp : mImports) { if (!mReferenced.contains(Utils.baseClassname(imp.getText()))) { log(imp.getLineNo(), imp.getColumnNo(), "import.unused", imp.getText()); } } } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.IDENT, TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT, // Definitions that may contain Javadoc... TokenTypes.PACKAGE_DEF, TokenTypes.ANNOTATION_DEF, TokenTypes.ANNOTATION_FIELD_DEF, TokenTypes.ENUM_DEF, TokenTypes.ENUM_CONSTANT_DEF, TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, TokenTypes.VARIABLE_DEF, }; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aAST) { if (aAST.getType() == TokenTypes.IDENT) { if (mCollect) { processIdent(aAST); } } else if (aAST.getType() == TokenTypes.IMPORT) { processImport(aAST); } else if (aAST.getType() == TokenTypes.STATIC_IMPORT) { processStaticImport(aAST); } else { mCollect = true; if (mProcessJavadoc) { processJavadoc(aAST); } } } /** * Collects references made by IDENT. * @param aAST the IDENT node to process */ private void processIdent(DetailAST aAST) { final DetailAST parent = aAST.getParent(); final int parentType = parent.getType(); if (((parentType != TokenTypes.DOT) && (parentType != TokenTypes.METHOD_DEF)) || ((parentType == TokenTypes.DOT) && (aAST.getNextSibling() != null))) { mReferenced.add(aAST.getText()); } } /** * Collects the details of imports. * @param aAST node containing the import details */ private void processImport(DetailAST aAST) { final FullIdent name = FullIdent.createFullIdentBelow(aAST); if ((name != null) && !name.getText().endsWith(".*")) { mImports.add(name); } } /** * Collects the details of static imports. * @param aAST node containing the static import details */ private void processStaticImport(DetailAST aAST) { final FullIdent name = FullIdent.createFullIdent( aAST.getFirstChild().getNextSibling()); if ((name != null) && !name.getText().endsWith(".*")) { mImports.add(name); } } /** * Collects references made in JavaDoc comments. * @param aAST node to inspect for JavaDoc */ private void processJavadoc(DetailAST aAST) { final FileContents contents = getFileContents(); final int lineNo = aAST.getLineNo(); final TextBlock cmt = contents.getJavadocBefore(lineNo); if (cmt != null) { final JavadocTags tags = JavadocUtils.getJavadocTags(cmt, JavadocUtils.JavadocTagType.ALL); for (final JavadocTag tag : tags.getValidTags()) { if (tag.canReferenceImports()) { String identifier = tag.getArg1(); // Trim off method or link text final Pattern pattern = Utils.getPattern("(.+?)(?:\\s+|#|\\$).*"); final Matcher matcher = pattern.matcher(identifier); if (matcher.find()) { identifier = matcher.group(1); } mReferenced.add(identifier); } } } } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ArrayInitHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ArrayInitHandler.ja100644 0 0 11111 12026051034 31354 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for array initialization blocks. * * @author jrichard */ public class ArrayInitHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public ArrayInitHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "array initialization", aAst, aParent); } @Override protected IndentLevel getLevelImpl() { final DetailAST parentAST = getMainAst().getParent(); final int type = parentAST.getType(); if ((type == TokenTypes.LITERAL_NEW) || (type == TokenTypes.ASSIGN)) { // note: assumes new or assignment is line to align with return new IndentLevel(getLineStart(parentAST)); } else if (getParent() instanceof ArrayInitHandler) { return ((ArrayInitHandler) getParent()).getChildrenExpectedLevel(); } else { return getParent().getLevel(); } } @Override protected DetailAST getToplevelAST() { return null; } @Override protected DetailAST getLCurly() { return getMainAst(); } @Override protected DetailAST getRCurly() { return getMainAst().findFirstToken(TokenTypes.RCURLY); } @Override protected boolean rcurlyMustStart() { return false; } @Override protected boolean childrenMayNest() { return true; } @Override protected DetailAST getListChild() { return getMainAst(); } @Override protected IndentLevel getChildrenExpectedLevel() { // now we accept // new int[] {1, // 2}; // and // new int[] {1, 2, // 3}; final IndentLevel expectedIndent = super.getChildrenExpectedLevel(); final int firstLine = getFirstLine(Integer.MAX_VALUE, getListChild()); if (hasCurlys() && (firstLine == getLCurly().getLineNo())) { final int lcurlyPos = expandedTabsColumnNo(getLCurly()); final int firstChildPos = getNextFirstNonblankOnLineAfter(firstLine, lcurlyPos); if (firstChildPos >= 0) { expectedIndent.addAcceptedIndent(firstChildPos); } } return expectedIndent; } /** * @param aLineNo number of line on which we search * @param aColumnNo number of column after which we search * * @return column number of first non-blank char after * specified column on specified line or -1 if * such char doesn't exist. */ private int getNextFirstNonblankOnLineAfter(int aLineNo, int aColumnNo) { int columnNo = aColumnNo + 1; final String line = getIndentCheck().getLines()[aLineNo - 1]; final int lineLength = line.length(); while ((columnNo < lineLength) && Character.isWhitespace(line.charAt(columnNo))) { columnNo++; } return (columnNo == lineLength) ? -1 : columnNo; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/AssignHandler.java100644 0 0 6761 12026051034 31224 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for assignements. * * @author o_sukhodolsky */ public class AssignHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public AssignHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "assign", aAst, aParent); } @Override public void checkIndentation() { final IndentLevel expectedLevel = getChildrenExpectedLevel(); // check indentation of assign if it starts line final DetailAST assign = getMainAst(); if (startsLine(assign) && !expectedLevel.accept(expandedTabsColumnNo(assign))) { logError(assign, "" , expandedTabsColumnNo(assign), expectedLevel); } // check indentation of rvalue DetailAST child = assign.getFirstChild(); // if this is assign in expression then skip first child, // because it's lvalue. final DetailAST parent = assign.getParent(); if ((parent != null) && (parent.getType() == TokenTypes.EXPR)) { child = child.getNextSibling(); } if ((parent != null) && (parent.getType() == TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR)) { child = assign.getNextSibling(); } checkExpressionSubtree(child, expectedLevel, false, true); } @Override protected boolean shouldIncreaseIndent() { return false; } @Override public IndentLevel suggestedChildLevel(ExpressionHandler aChild) { final DetailAST assign = getMainAst(); final DetailAST child = aChild.getMainAst(); if (child == assign.getFirstChild()) { // left side of assignment should have the same // indentation as "assignment" return getLevel(); } if (startsLine(assign)) { return new IndentLevel(expandedTabsColumnNo(assign)); } return super.suggestedChildLevel(aChild); } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.100644 0 0 24054 12026051033 31354 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for parents of blocks ('if', 'else', 'while', etc). *

* The "block" handler classes use a common superclass BlockParentHandler, * employing the Template Method pattern. *

*

    *
  • template method to get the lcurly
  • *
  • template method to get the rcurly
  • *
  • if curlys aren't present, then template method to get expressions * is called
  • *
  • now all the repetitous code which checks for BOL, if curlys are on * same line, etc. can be collapsed into the superclass
  • *
* * @author jrichard */ public class BlockParentHandler extends ExpressionHandler { /** * Children checked by parent handlers. */ private static final int[] CHECKED_CHILDREN = new int[] { TokenTypes.VARIABLE_DEF, TokenTypes.EXPR, TokenTypes.OBJBLOCK, TokenTypes.LITERAL_BREAK, TokenTypes.LITERAL_RETURN, TokenTypes.LITERAL_THROW, TokenTypes.LITERAL_CONTINUE, }; /** * Returns array of token types which should be checked among childrens. * @return array of token types to check. */ protected int[] getCheckedChildren() { return CHECKED_CHILDREN; } /** * Construct an instance of this handler with the given indentation check, * name, abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aName the name of the handler * @param aAst the abstract syntax tree * @param aParent the parent handler */ public BlockParentHandler(IndentationCheck aIndentCheck, String aName, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, aName, aAst, aParent); } /** * Get the top level expression being managed by this handler. * * @return the top level expression */ protected DetailAST getToplevelAST() { return getMainAst(); } /** * Check the indent of the top level token. */ protected void checkToplevelToken() { final DetailAST toplevel = getToplevelAST(); if ((toplevel == null) || getLevel().accept(expandedTabsColumnNo(toplevel))) { return; } if (!toplevelMustStartLine() && !startsLine(toplevel)) { return; } logError(toplevel, "", expandedTabsColumnNo(toplevel)); } /** * Determines if the top level token must start the line. * * @return true */ protected boolean toplevelMustStartLine() { return true; } /** * Determines if this block expression has curly braces. * * @return true if curly braces are present, false otherwise */ protected boolean hasCurlys() { return (getLCurly() != null) && (getRCurly() != null); } /** * Get the left curly brace portion of the expression we are handling. * * @return the left curly brace expression */ protected DetailAST getLCurly() { return getMainAst().findFirstToken(TokenTypes.SLIST); } /** * Get the right curly brace portion of the expression we are handling. * * @return the right curly brace expression */ protected DetailAST getRCurly() { final DetailAST slist = getMainAst().findFirstToken(TokenTypes.SLIST); if (slist == null) { return null; } return slist.findFirstToken(TokenTypes.RCURLY); } /** * Check the indentation of the left curly brace. */ protected void checkLCurly() { // the lcurly can either be at the correct indentation, or nested // with a previous expression final DetailAST lcurly = getLCurly(); final int lcurlyPos = expandedTabsColumnNo(lcurly); if ((lcurly == null) || curlyLevel().accept(lcurlyPos) || !startsLine(lcurly)) { return; } logError(lcurly, "lcurly", lcurlyPos); } /** * Get the expected indentation level for the curly braces. * * @return the curly brace indentation level */ private IndentLevel curlyLevel() { return new IndentLevel(getLevel(), getBraceAdjustement()); } /** * Determines if the right curly brace must be at the start of the line. * * @return true */ protected boolean rcurlyMustStart() { return true; } /** * Determines if child elements within the expression may be nested. * * @return false */ protected boolean childrenMayNest() { return false; } /** * Check the indentation of the right curly brace. */ protected void checkRCurly() { // the rcurly can either be at the correct indentation, or // on the same line as the lcurly final DetailAST lcurly = getLCurly(); final DetailAST rcurly = getRCurly(); final int rcurlyPos = expandedTabsColumnNo(rcurly); if ((rcurly == null) || curlyLevel().accept(rcurlyPos) || (!rcurlyMustStart() && !startsLine(rcurly)) || areOnSameLine(rcurly, lcurly)) { return; } logError(rcurly, "rcurly", rcurlyPos, curlyLevel()); } /** * Get the child element that is not a list of statements. * * @return the non-list child element */ protected DetailAST getNonlistChild() { return getMainAst().findFirstToken( TokenTypes.RPAREN).getNextSibling(); } /** * Check the indentation level of a child that is not a list of statements. */ private void checkNonlistChild() { // TODO: look for SEMI and check for it here? final DetailAST nonlist = getNonlistChild(); if (nonlist == null) { return; } final IndentLevel expected = new IndentLevel(getLevel(), getBasicOffset()); checkExpressionSubtree(nonlist, expected, false, false); } /** * Get the child element representing the list of statements. * * @return the statement list child */ protected DetailAST getListChild() { return getMainAst().findFirstToken(TokenTypes.SLIST); } /** * Get the right parenthesis portion of the expression we are handling. * * @return the right parenthis expression */ protected DetailAST getRParen() { return getMainAst().findFirstToken(TokenTypes.RPAREN); } /** * Get the left parenthesis portion of the expression we are handling. * * @return the left parenthis expression */ protected DetailAST getLParen() { return getMainAst().findFirstToken(TokenTypes.LPAREN); } @Override public void checkIndentation() { checkToplevelToken(); // seperate to allow for eventual configuration checkLParen(getLParen()); checkRParen(getLParen(), getRParen()); if (hasCurlys()) { checkLCurly(); checkRCurly(); } final DetailAST listChild = getListChild(); if (listChild != null) { // NOTE: switch statements usually don't have curlys if (!hasCurlys() || !areOnSameLine(getLCurly(), getRCurly())) { checkChildren(listChild, getCheckedChildren(), getChildrenExpectedLevel(), true, childrenMayNest()); } } else { checkNonlistChild(); } } /** * @return indentation level expected for children */ protected IndentLevel getChildrenExpectedLevel() { // if we have multileveled expected level then we should // try to suggest single level to children using curlies' // levels. if (getLevel().isMultiLevel() && hasCurlys() && !areOnSameLine(getLCurly(), getRCurly())) { if (startsLine(getLCurly())) { return new IndentLevel(expandedTabsColumnNo(getLCurly()) + getBasicOffset()); } else if (startsLine(getRCurly())) { return new IndentLevel(expandedTabsColumnNo(getRCurly()) + getBasicOffset()); } } return new IndentLevel(getLevel(), getBasicOffset()); } @Override public IndentLevel suggestedChildLevel(ExpressionHandler aChild) { return getChildrenExpectedLevel(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/CaseHandler.java100644 0 0 5107 12026051033 30643 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for case statements. * * @author jrichard */ public class CaseHandler extends ExpressionHandler { /** * The child elements of a case expression. */ private final int[] mCaseChildren = new int[] { TokenTypes.LITERAL_CASE, TokenTypes.LITERAL_DEFAULT, }; /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aExpr the abstract syntax tree * @param aParent the parent handler */ public CaseHandler(IndentationCheck aIndentCheck, DetailAST aExpr, ExpressionHandler aParent) { super(aIndentCheck, "case", aExpr, aParent); } @Override protected IndentLevel getLevelImpl() { return new IndentLevel(getParent().getLevel(), getIndentCheck().getCaseIndent()); } /** * Check the indentation of the case statement. */ private void checkCase() { checkChildren(getMainAst(), mCaseChildren, getLevel(), true, false); } @Override public IndentLevel suggestedChildLevel(ExpressionHandler aChild) { return getLevel(); } @Override public void checkIndentation() { checkCase(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/CatchHandler.java100644 0 0 4476 12026051033 31022 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for catch blocks. * * @author jrichard */ public class CatchHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public CatchHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "catch", aAst, aParent); } @Override protected boolean toplevelMustStartLine() { return false; } /** * Check the indentation level of the conditional expression. */ private void checkCondExpr() { final DetailAST condAst = getMainAst().findFirstToken(TokenTypes.LPAREN) .getNextSibling(); checkExpressionSubtree(condAst, getLevel(), false, false); } @Override public void checkIndentation() { super.checkIndentation(); checkCondExpr(); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.jav100644 0 0 10407 12026051033 31332 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for class definitions. * * @author jrichard */ public class ClassDefHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public ClassDefHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, (aAst.getType() == TokenTypes.CLASS_DEF) ? "class def" : ((aAst.getType() == TokenTypes.ENUM_DEF) ? "enum def" : "interface def"), aAst, aParent); } @Override protected DetailAST getLCurly() { return getMainAst().findFirstToken(TokenTypes.OBJBLOCK) .findFirstToken(TokenTypes.LCURLY); } @Override protected DetailAST getRCurly() { return getMainAst().findFirstToken(TokenTypes.OBJBLOCK) .findFirstToken(TokenTypes.RCURLY); } @Override protected DetailAST getToplevelAST() { return null; // note: ident checked by hand in check indentation; } @Override protected DetailAST getListChild() { return getMainAst().findFirstToken(TokenTypes.OBJBLOCK); } @Override public void checkIndentation() { // TODO: still need to better deal with the modifiers and "class" checkModifiers(); final LineSet lines = new LineSet(); // checks that line with class name starts at correct indentation, // and following lines (in implements and extends clauses) are // indented at least one level final DetailAST ident = getMainAst().findFirstToken(TokenTypes.IDENT); final int lineStart = getLineStart(ident); if (!getLevel().accept(lineStart)) { logError(ident, "ident", lineStart); } lines.addLineAndCol(ident.getLineNo(), lineStart); final DetailAST impl = getMainAst().findFirstToken( TokenTypes.IMPLEMENTS_CLAUSE); if ((impl != null) && (impl.getFirstChild() != null)) { findSubtreeLines(lines, impl, false); } final DetailAST ext = getMainAst().findFirstToken(TokenTypes.EXTENDS_CLAUSE); if ((ext != null) && (ext.getFirstChild() != null)) { findSubtreeLines(lines, ext, false); } checkLinesIndent(ident.getLineNo(), lines.lastLine(), getLevel()); super.checkIndentation(); } @Override protected int[] getCheckedChildren() { return new int[] { TokenTypes.EXPR, TokenTypes.OBJBLOCK, TokenTypes.LITERAL_BREAK, TokenTypes.LITERAL_RETURN, TokenTypes.LITERAL_THROW, TokenTypes.LITERAL_CONTINUE, }; } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/DoWhileHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/DoWhileHandler.java100644 0 0 4464 12026051033 31330 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for do...while blocks. * * @author jrichard */ public class DoWhileHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public DoWhileHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "do..while", aAst, aParent); } /** * Check the indentation level of the conditional expression. */ private void checkCondExpr() { final DetailAST condAst = getMainAst() .findFirstToken(TokenTypes.LPAREN).getNextSibling(); checkExpressionSubtree(condAst, getLevel(), false, false); } @Override public void checkIndentation() { super.checkIndentation(); // TODO: checkWhile(); // while is not in the grammar, why not? checkCondExpr(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ElseHandler.java100644 0 0 5167 12026051032 30665 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for else blocks. * * @author jrichard */ public class ElseHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public ElseHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "else", aAst, aParent); } @Override protected void checkToplevelToken() { // check if else is nested with rcurly of if: // // } else ... final DetailAST ifAST = getMainAst().getParent(); if (ifAST != null) { final DetailAST slist = ifAST.findFirstToken(TokenTypes.SLIST); if (slist != null) { final DetailAST lcurly = slist.getLastChild(); if ((lcurly != null) && (lcurly.getLineNo() == getMainAst().getLineNo())) { // indentation checked as part of LITERAL IF check return; } } } super.checkToplevelToken(); } @Override protected DetailAST getNonlistChild() { return getMainAst().getFirstChild(); } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ExpressionHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ExpressionHandler.j100644 0 0 53401 12026051032 31456 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.Arrays; /** * Abstract base class for all handlers. * * @author jrichard */ public abstract class ExpressionHandler { /** * The instance of IndentationCheck using this handler. */ private final IndentationCheck mIndentCheck; /** the AST which is handled by this handler */ private final DetailAST mMainAst; /** name used during output to user */ private final String mTypeName; /** containing AST handler */ private final ExpressionHandler mParent; /** indentation amount for this handler */ private IndentLevel mLevel; /** * Construct an instance of this handler with the given indentation check, * name, abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aTypeName the name of the handler * @param aExpr the abstract syntax tree * @param aParent the parent handler */ public ExpressionHandler(IndentationCheck aIndentCheck, String aTypeName, DetailAST aExpr, ExpressionHandler aParent) { mIndentCheck = aIndentCheck; mTypeName = aTypeName; mMainAst = aExpr; mParent = aParent; } /** * Get the indentation amount for this handler. For performance reasons, * this value is cached. The first time this method is called, the * indentation amount is computed and stored. On further calls, the stored * value is returned. * * @return the expected indentation amount */ public final IndentLevel getLevel() { if (mLevel == null) { mLevel = getLevelImpl(); } return mLevel; } /** * Compute the indentation amount for this handler. * * @return the expected indentation amount */ protected IndentLevel getLevelImpl() { return mParent.suggestedChildLevel(this); } /** * Indentation level suggested for a child element. Children don't have * to respect this, but most do. * * @param aChild child AST (so suggestion level can differ based on child * type) * * @return suggested indentation for child */ public IndentLevel suggestedChildLevel(ExpressionHandler aChild) { return new IndentLevel(getLevel(), getBasicOffset()); } /** * Log an indentation error. * * @param aAst the expression that caused the error * @param aSubtypeName the type of the expression * @param aActualLevel the actual indent level of the expression */ protected final void logError(DetailAST aAst, String aSubtypeName, int aActualLevel) { logError(aAst, aSubtypeName, aActualLevel, getLevel()); } /** * Log an indentation error. * * @param aAst the expression that caused the error * @param aSubtypeName the type of the expression * @param aActualLevel the actual indent level of the expression * @param aExpectedLevel the expected indent level of the expression */ protected final void logError(DetailAST aAst, String aSubtypeName, int aActualLevel, IndentLevel aExpectedLevel) { final String typeStr = ("".equals(aSubtypeName) ? "" : (" " + aSubtypeName)); mIndentCheck.indentationLog(aAst.getLineNo(), "indentation.error", mTypeName + typeStr, aActualLevel, aExpectedLevel); } /** * Log child indentation error. * * @param aLine the expression that caused the error * @param aActualLevel the actual indent level of the expression * @param aExpectedLevel the expected indent level of the expression */ private void logChildError(int aLine, int aActualLevel, IndentLevel aExpectedLevel) { mIndentCheck.indentationLog(aLine, "indentation.child.error", mTypeName, aActualLevel, aExpectedLevel); } /** * Determines if the given expression is at the start of a line. * * @param aAst the expression to check * * @return true if it is, false otherwise */ protected final boolean startsLine(DetailAST aAst) { return getLineStart(aAst) == expandedTabsColumnNo(aAst); } /** * Determines if two expressions are on the same line. * * @param aAst1 the first expression * @param aAst2 the second expression * * @return true if they are, false otherwise */ static boolean areOnSameLine(DetailAST aAst1, DetailAST aAst2) { return (aAst1 != null) && (aAst2 != null) && (aAst1.getLineNo() == aAst2.getLineNo()); } /** * Searchs in given sub-tree (including given node) for the token * which represents first symbol for this sub-tree in file. * @param aAST a root of sub-tree in which the search shoul be performed. * @return a token which occurs first in the file. */ static DetailAST getFirstToken(DetailAST aAST) { DetailAST first = aAST; DetailAST child = aAST.getFirstChild(); while (child != null) { final DetailAST toTest = getFirstToken(child); if ((toTest.getLineNo() < first.getLineNo()) || ((toTest.getLineNo() == first.getLineNo()) && (toTest.getColumnNo() < first.getColumnNo()))) { first = toTest; } child = child.getNextSibling(); } return first; } /** * Get the start of the line for the given expression. * * @param aAst the expression to find the start of the line for * * @return the start of the line for the given expression */ protected final int getLineStart(DetailAST aAst) { final String line = mIndentCheck.getLines()[aAst.getLineNo() - 1]; return getLineStart(line); } // TODO: this whole checking of consecuitive/expression line indents is // smelling pretty bad... and is in serious need of pruning. But, I // want to finish the invalid tests before I start messing around with // it. /** * Check the indentation of consecutive lines for the expression we are * handling. * * @param aStartLine the first line to check * @param aEndLine the last line to check * @param aIndentLevel the required indent level */ protected final void checkLinesIndent(int aStartLine, int aEndLine, IndentLevel aIndentLevel) { // check first line checkSingleLine(aStartLine, aIndentLevel); // check following lines final IndentLevel offsetLevel = new IndentLevel(aIndentLevel, getBasicOffset()); for (int i = aStartLine + 1; i <= aEndLine; i++) { checkSingleLine(i, offsetLevel); } } /** * @return true if indentation should be increased after * fisrt line in checkLinesIndent() * false otherwise */ protected boolean shouldIncreaseIndent() { return true; } /** * Check the indentation for a set of lines. * * @param aLines the set of lines to check * @param aIndentLevel the indentation level * @param aFirstLineMatches whether or not the first line has to match * @param aFirstLine firstline of whole expression */ private void checkLinesIndent(LineSet aLines, IndentLevel aIndentLevel, boolean aFirstLineMatches, int aFirstLine) { if (aLines.isEmpty()) { return; } // check first line final int startLine = aLines.firstLine(); final int endLine = aLines.lastLine(); final int startCol = aLines.firstLineCol(); final int realStartCol = getLineStart(mIndentCheck.getLines()[startLine - 1]); if (realStartCol == startCol) { checkSingleLine(startLine, startCol, aIndentLevel, aFirstLineMatches); } // if first line starts the line, following lines are indented // one level; but if the first line of this expression is // nested with the previous expression (which is assumed if it // doesn't start the line) then don't indent more, the first // indentation is absorbed by the nesting // TODO: shouldIncreaseIndent() is a hack, should be removed // after complete rewriting of checkExpressionSubtree() IndentLevel theLevel = aIndentLevel; if (aFirstLineMatches || ((aFirstLine > mMainAst.getLineNo()) && shouldIncreaseIndent())) { theLevel = new IndentLevel(aIndentLevel, getBasicOffset()); } // check following lines for (int i = startLine + 1; i <= endLine; i++) { final Integer col = aLines.getStartColumn(i); // startCol could be null if this line didn't have an // expression that was required to be checked (it could be // checked by a child expression) if (col != null) { checkSingleLine(i, col.intValue(), theLevel, false); } } } /** * Check the indent level for a single line. * * @param aLineNum the line number to check * @param aIndentLevel the required indent level */ private void checkSingleLine(int aLineNum, IndentLevel aIndentLevel) { final String line = mIndentCheck.getLines()[aLineNum - 1]; final int start = getLineStart(line); if (aIndentLevel.gt(start)) { logChildError(aLineNum, start, aIndentLevel); } } /** * Check the indentation for a single line. * * @param aLineNum the number of the line to check * @param aColNum the column number we are starting at * @param aIndentLevel the indentation level * @param aMustMatch whether or not the indentation level must match */ private void checkSingleLine(int aLineNum, int aColNum, IndentLevel aIndentLevel, boolean aMustMatch) { final String line = mIndentCheck.getLines()[aLineNum - 1]; final int start = getLineStart(line); // if must match is set, it is an error if the line start is not // at the correct indention level; otherwise, it is an only an // error if this statement starts the line and it is less than // the correct indentation level if (aMustMatch ? !aIndentLevel.accept(start) : (aColNum == start) && aIndentLevel.gt(start)) { logChildError(aLineNum, start, aIndentLevel); } } /** * Get the start of the specified line. * * @param aLine the specified line number * * @return the start of the specified line */ protected final int getLineStart(String aLine) { for (int start = 0; start < aLine.length(); start++) { final char c = aLine.charAt(start); if (!Character.isWhitespace(c)) { return Utils.lengthExpandedTabs( aLine, start, mIndentCheck.getIndentationTabWidth()); } } return 0; } // TODO: allowNesting either shouldn't be allowed with // firstLineMatches, or I should change the firstLineMatches logic // so it doesn't match if the first line is nested /** * Check the indent level of the children of the specified parent * expression. * * @param aParent the parent whose children we are checking * @param aTokenTypes the token types to check * @param aStartLevel the starting indent level * @param aFirstLineMatches whether or not the first line needs to match * @param aAllowNesting whether or not nested children are allowed */ protected final void checkChildren(DetailAST aParent, int[] aTokenTypes, IndentLevel aStartLevel, boolean aFirstLineMatches, boolean aAllowNesting) { Arrays.sort(aTokenTypes); for (DetailAST child = aParent.getFirstChild(); child != null; child = child.getNextSibling()) { if (Arrays.binarySearch(aTokenTypes, child.getType()) >= 0) { checkExpressionSubtree(child, aStartLevel, aFirstLineMatches, aAllowNesting); } } } /** * Check the indentation level for an expression subtree. * * @param aTree the expression subtree to check * @param aLevel the indentation level * @param aFirstLineMatches whether or not the first line has to match * @param aAllowNesting whether or not subtree nesting is allowed */ protected final void checkExpressionSubtree( DetailAST aTree, IndentLevel aLevel, boolean aFirstLineMatches, boolean aAllowNesting ) { final LineSet subtreeLines = new LineSet(); final int firstLine = getFirstLine(Integer.MAX_VALUE, aTree); if (aFirstLineMatches && !aAllowNesting) { subtreeLines.addLineAndCol(firstLine, getLineStart(mIndentCheck.getLines()[firstLine - 1])); } findSubtreeLines(subtreeLines, aTree, aAllowNesting); checkLinesIndent(subtreeLines, aLevel, aFirstLineMatches, firstLine); } /** * Get the first line for a given expression. * * @param aStartLine the line we are starting from * @param aTree the expression to find the first line for * * @return the first line of the expression */ protected final int getFirstLine(int aStartLine, DetailAST aTree) { // find line for this node // TODO: getLineNo should probably not return < 0, but it is for // the interface methods... I should ask about this int realStart = aStartLine; final int currLine = aTree.getLineNo(); if (currLine < realStart) { realStart = currLine; } // check children for (DetailAST node = aTree.getFirstChild(); node != null; node = node.getNextSibling()) { realStart = getFirstLine(realStart, node); } return realStart; } /** * Get the column number for the start of a given expression, expanding * tabs out into spaces in the process. * * @param aAST the expression to find the start of * * @return the column number for the start of the expression */ protected final int expandedTabsColumnNo(DetailAST aAST) { final String line = mIndentCheck.getLines()[aAST.getLineNo() - 1]; return Utils.lengthExpandedTabs(line, aAST.getColumnNo(), mIndentCheck.getIndentationTabWidth()); } /** * Find the set of lines for a given subtree. * * @param aLines the set of lines to add to * @param aTree the subtree to examine * @param aAllowNesting whether or not to allow nested subtrees */ protected final void findSubtreeLines(LineSet aLines, DetailAST aTree, boolean aAllowNesting) { // find line for this node // TODO: getLineNo should probably not return < 0, but it is for // the interface methods... I should ask about this if (getIndentCheck().getHandlerFactory().isHandledType(aTree.getType()) || (aTree.getLineNo() < 0)) { return; } // TODO: the problem with this is that not all tree tokens actually // have the right column number -- I should get a list of these // and verify that checking nesting this way won't cause problems // if (aAllowNesting && aTree.getColumnNo() != getLineStart(aTree)) { // return; // } final int lineNum = aTree.getLineNo(); final Integer colNum = aLines.getStartColumn(lineNum); final int thisLineColumn = expandedTabsColumnNo(aTree); if ((colNum == null) || (thisLineColumn < colNum.intValue())) { aLines.addLineAndCol(lineNum, thisLineColumn); } // check children for (DetailAST node = aTree.getFirstChild(); node != null; node = node.getNextSibling()) { findSubtreeLines(aLines, node, aAllowNesting); } } /** * Check the indentation level of modifiers. */ protected final void checkModifiers() { final DetailAST modifiers = mMainAst.findFirstToken(TokenTypes.MODIFIERS); for (DetailAST modifier = modifiers.getFirstChild(); modifier != null; modifier = modifier.getNextSibling()) { /* if (!areOnSameLine(modifier, prevExpr)) { continue; } */ if (startsLine(modifier) && !getLevel().accept(expandedTabsColumnNo(modifier))) { logError(modifier, "modifier", expandedTabsColumnNo(modifier)); } } } /** * Check the indentation of the expression we are handling. */ public abstract void checkIndentation(); /** * Accessor for the IndentCheck attribute. * * @return the IndentCheck attribute */ protected final IndentationCheck getIndentCheck() { return mIndentCheck; } /** * Accessor for the MainAst attribute. * * @return the MainAst attribute */ protected final DetailAST getMainAst() { return mMainAst; } /** * Accessor for the Parent attribute. * * @return the Parent attribute */ protected final ExpressionHandler getParent() { return mParent; } /** * A shortcut for IndentationCheck property. * @return value of basicOffset property of IndentationCheck */ protected final int getBasicOffset() { return getIndentCheck().getBasicOffset(); } /** * A shortcut for IndentationCheck property. * @return value of braceAdjustment property * of IndentationCheck */ protected final int getBraceAdjustement() { return getIndentCheck().getBraceAdjustement(); } /** * Check the indentation of the right parenthesis. * @param aRparen parenthesis to check * @param aLparen left parenthesis associated with aRparen */ protected final void checkRParen(DetailAST aLparen, DetailAST aRparen) { // no paren - no check :) if (aRparen == null) { return; } // the rcurly can either be at the correct indentation, // or not first on the line ... final int rparenLevel = expandedTabsColumnNo(aRparen); if (getLevel().accept(rparenLevel) || !startsLine(aRparen)) { return; } // or has + 1 indentation final int lparenLevel = expandedTabsColumnNo(aLparen); if (rparenLevel == (lparenLevel + 1)) { return; } logError(aRparen, "rparen", rparenLevel); } /** * Check the indentation of the left parenthesis. * @param aLparen parenthesis to check */ protected final void checkLParen(final DetailAST aLparen) { // the rcurly can either be at the correct indentation, or on the // same line as the lcurly if ((aLparen == null) || getLevel().accept(expandedTabsColumnNo(aLparen)) || !startsLine(aLparen)) { return; } logError(aLparen, "lparen", expandedTabsColumnNo(aLparen)); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/FinallyHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/FinallyHandler.java100644 0 0 3521 12026051032 31363 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Handler for finally blocks. * * @author jrichard */ public class FinallyHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public FinallyHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "finally", aAst, aParent); } @Override protected boolean toplevelMustStartLine() { return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ForHandler.java100644 0 0 6166 12026051032 30523 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for for loops. * * @author jrichard */ public class ForHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public ForHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "for", aAst, aParent); } /** * Check the indentation of the parameters of the 'for' loop. */ private void checkForParams() { final IndentLevel expected = new IndentLevel(getLevel(), getBasicOffset()); final DetailAST init = getMainAst().findFirstToken(TokenTypes.FOR_INIT); if (init != null) { checkExpressionSubtree(init, expected, false, false); final DetailAST cond = getMainAst().findFirstToken(TokenTypes.FOR_CONDITION); checkExpressionSubtree(cond, expected, false, false); final DetailAST iter = getMainAst().findFirstToken(TokenTypes.FOR_ITERATOR); checkExpressionSubtree(iter, expected, false, false); } // for each else { final DetailAST forEach = getMainAst().findFirstToken(TokenTypes.FOR_EACH_CLAUSE); checkExpressionSubtree(forEach, expected, false, false); } } @Override public void checkIndentation() { checkForParams(); super.checkIndentation(); } @Override public IndentLevel suggestedChildLevel(ExpressionHandler aChild) { if (aChild instanceof ElseHandler) { return getLevel(); } return super.suggestedChildLevel(aChild); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java100644 0 0 22600 12026051031 31412 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.google.common.collect.Maps; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Factory for handlers. Looks up constructor via reflection. * * @author jrichard */ public class HandlerFactory { /** Logger for indentation check */ private static final Log LOG = LogFactory.getLog("com.puppycrawl.tools.checkstyle.checks.indentation"); /** * Registered handlers. */ private final Map> mTypeHandlers = Maps.newHashMap(); /** * registers a handler * * @param aType * type from TokenTypes * @param aHandlerClass * the handler to register */ private void register(int aType, Class aHandlerClass) { try { final Constructor ctor = aHandlerClass .getConstructor(new Class[] {IndentationCheck.class, DetailAST.class, // current AST ExpressionHandler.class, // parent }); mTypeHandlers.put(aType, ctor); } ///CLOVER:OFF catch (final NoSuchMethodException e) { throw new RuntimeException("couldn't find ctor for " + aHandlerClass); } catch (final SecurityException e) { LOG.debug("couldn't find ctor for " + aHandlerClass, e); throw new RuntimeException("couldn't find ctor for " + aHandlerClass); } ///CLOVER:ON } /** Creates a HandlerFactory. */ public HandlerFactory() { register(TokenTypes.CASE_GROUP, CaseHandler.class); register(TokenTypes.LITERAL_SWITCH, SwitchHandler.class); register(TokenTypes.SLIST, SlistHandler.class); register(TokenTypes.PACKAGE_DEF, PackageDefHandler.class); register(TokenTypes.LITERAL_ELSE, ElseHandler.class); register(TokenTypes.LITERAL_IF, IfHandler.class); register(TokenTypes.LITERAL_TRY, TryHandler.class); register(TokenTypes.LITERAL_CATCH, CatchHandler.class); register(TokenTypes.LITERAL_FINALLY, FinallyHandler.class); register(TokenTypes.LITERAL_DO, DoWhileHandler.class); register(TokenTypes.LITERAL_WHILE, WhileHandler.class); register(TokenTypes.LITERAL_FOR, ForHandler.class); register(TokenTypes.METHOD_DEF, MethodDefHandler.class); register(TokenTypes.CTOR_DEF, MethodDefHandler.class); register(TokenTypes.CLASS_DEF, ClassDefHandler.class); register(TokenTypes.ENUM_DEF, ClassDefHandler.class); register(TokenTypes.OBJBLOCK, ObjectBlockHandler.class); register(TokenTypes.INTERFACE_DEF, ClassDefHandler.class); register(TokenTypes.IMPORT, ImportHandler.class); register(TokenTypes.ARRAY_INIT, ArrayInitHandler.class); register(TokenTypes.METHOD_CALL, MethodCallHandler.class); register(TokenTypes.CTOR_CALL, MethodCallHandler.class); register(TokenTypes.LABELED_STAT, LabelHandler.class); register(TokenTypes.STATIC_INIT, StaticInitHandler.class); register(TokenTypes.INSTANCE_INIT, SlistHandler.class); register(TokenTypes.ASSIGN, AssignHandler.class); register(TokenTypes.PLUS_ASSIGN, AssignHandler.class); register(TokenTypes.MINUS_ASSIGN, AssignHandler.class); register(TokenTypes.STAR_ASSIGN, AssignHandler.class); register(TokenTypes.DIV_ASSIGN, AssignHandler.class); register(TokenTypes.MOD_ASSIGN, AssignHandler.class); register(TokenTypes.SR_ASSIGN, AssignHandler.class); register(TokenTypes.BSR_ASSIGN, AssignHandler.class); register(TokenTypes.SL_ASSIGN, AssignHandler.class); register(TokenTypes.BAND_ASSIGN, AssignHandler.class); register(TokenTypes.BXOR_ASSIGN, AssignHandler.class); register(TokenTypes.BOR_ASSIGN, AssignHandler.class); register(TokenTypes.VARIABLE_DEF, MemberDefHandler.class); register(TokenTypes.LITERAL_NEW, NewHandler.class); } /** * Returns true if this type (form TokenTypes) is handled. * * @param aType type from TokenTypes * @return true if handler is registered, false otherwise */ public boolean isHandledType(int aType) { final Set typeSet = mTypeHandlers.keySet(); return typeSet.contains(aType); } /** * Gets list of registered handler types. * * @return int[] of TokenType types */ public int[] getHandledTypes() { final Set typeSet = mTypeHandlers.keySet(); final int[] types = new int[typeSet.size()]; int index = 0; for (final Integer val : typeSet) { types[index++] = val; } return types; } /** * Get the handler for an AST. * * @param aIndentCheck the indentation check * @param aAst ast to handle * @param aParent the handler parent of this AST * * @return the ExpressionHandler for aAst */ public ExpressionHandler getHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { final ExpressionHandler handler = mCreatedHandlers.get(aAst); if (handler != null) { return handler; } if (aAst.getType() == TokenTypes.METHOD_CALL) { return createMethodCallHandler(aIndentCheck, aAst, aParent); } ExpressionHandler expHandler = null; try { final Constructor handlerCtor = mTypeHandlers.get(aAst.getType()); if (handlerCtor != null) { expHandler = (ExpressionHandler) handlerCtor.newInstance( aIndentCheck, aAst, aParent); } } ///CLOVER:OFF catch (final InstantiationException e) { LOG.debug("couldn't instantiate constructor for " + aAst, e); throw new RuntimeException("couldn't instantiate constructor for " + aAst); } catch (final IllegalAccessException e) { LOG.debug("couldn't access constructor for " + aAst, e); throw new RuntimeException("couldn't access constructor for " + aAst); } catch (final InvocationTargetException e) { LOG.debug("couldn't instantiate constructor for " + aAst, e); throw new RuntimeException("couldn't instantiate constructor for " + aAst); } if (expHandler == null) { throw new RuntimeException("no handler for type " + aAst.getType()); } ///CLOVER:ON return expHandler; } /** * Create new instance of handler for METHOD_CALL. * * @param aIndentCheck the indentation check * @param aAst ast to handle * @param aParent the handler parent of this AST * * @return new instance. */ ExpressionHandler createMethodCallHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { ExpressionHandler theParent = aParent; DetailAST ast = aAst.getFirstChild(); while ((ast != null) && (ast.getType() == TokenTypes.DOT)) { ast = ast.getFirstChild(); } if ((ast != null) && isHandledType(ast.getType())) { theParent = getHandler(aIndentCheck, ast, theParent); mCreatedHandlers.put(ast, theParent); } return new MethodCallHandler(aIndentCheck, aAst, theParent); } /** Clears cache of created handlers. */ void clearCreatedHandlers() { mCreatedHandlers.clear(); } /** cache for created method call handlers */ private final Map mCreatedHandlers = Maps.newHashMap(); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/IfHandler.java100644 0 0 6615 12026051031 30331 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for if statements. * * @author jrichard */ public class IfHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public IfHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "if", aAst, aParent); } @Override public IndentLevel suggestedChildLevel(ExpressionHandler aChild) { if (aChild instanceof ElseHandler) { return getLevel(); } return super.suggestedChildLevel(aChild); } @Override protected IndentLevel getLevelImpl() { if (isIfAfterElse()) { return getParent().getLevel(); } return super.getLevelImpl(); } /** * Determines if this 'if' statement is part of an 'else' clause * and on the same line. * * @return true if this 'if' is part of an 'else', false otherwise */ private boolean isIfAfterElse() { // check if there is an 'else' and an 'if' on the same line final DetailAST parent = getMainAst().getParent(); return (parent.getType() == TokenTypes.LITERAL_ELSE) && (parent.getLineNo() == getMainAst().getLineNo()); } @Override protected void checkToplevelToken() { if (isIfAfterElse()) { return; } super.checkToplevelToken(); } /** * Check the indentation of the conditional expression. */ private void checkCondExpr() { final DetailAST condAst = getMainAst().findFirstToken(TokenTypes.LPAREN) .getNextSibling(); final IndentLevel expected = new IndentLevel(getLevel(), getBasicOffset()); checkExpressionSubtree(condAst, expected, false, false); } @Override public void checkIndentation() { super.checkIndentation(); checkCondExpr(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ImportHandler.java100644 0 0 4234 12026051031 31240 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for import statements. * * @author jrichard */ public class ImportHandler extends ExpressionHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public ImportHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "import", aAst, aParent); } @Override public void checkIndentation() { final int lineStart = getMainAst().getLineNo(); final DetailAST semi = getMainAst().findFirstToken(TokenTypes.SEMI); final int lineEnd = semi.getLineNo(); if (getMainAst().getLineNo() != lineEnd) { checkLinesIndent(lineStart, lineEnd, getLevel()); } } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheck.ja100644 0 0 21012 12026051031 31364 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; // TODO: allow preset indentation styles (IE... GNU style, Sun style, etc...)? // TODO: optionally make imports (and other?) statements required to start // line? -- but maybe this should be a different check // TODO: optionally allow array children, throws clause, etc... // to be of any indentation > required, for emacs-style indentation // TODO: this is not illegal, but probably should be: // myfunc3(11, 11, Integer. // getInteger("mytest").intValue(), // this should be in 4 more // 11); // TODO: any dot-based indentation doesn't work (at least not yet...) the // problem is that we don't know which way an expression tree will be built // and with dot trees, they are built backwards. This means code like // // org.blah.mystuff // .myclass.getFactoryObject() // .objFunc().otherMethod(); // and // return ((MethodCallHandler) parent) // .findContainingMethodCall(this); // is all checked at the level of the first line. Simple dots are actually // checked but the method call handler will have to be changed drastically // to fix the above... /** * Checks correct indentation of Java Code. * *

* The basic idea behind this is that while * pretty printers are sometimes convienent for bulk reformats of * legacy code, they often either aren't configurable enough or * just can't anticipate how format should be done. Sometimes this is * personal preference, other times it is practical experience. In any * case, this check should just ensure that a minimal set of indentation * rules are followed. *

* *

* Implementation -- * Basically, this check requests visitation for all handled token * types (those tokens registered in the HandlerFactory). When visitToken * is called, a new ExpressionHandler is created for the AST and pushed * onto the mHandlers stack. The new handler then checks the indentation * for the currently visiting AST. When leaveToken is called, the * ExpressionHandler is popped from the stack. *

* *

* While on the stack the ExpressionHandler can be queried for the * indentation level it suggests for children as well as for other * values. *

* *

* While an ExpressionHandler checks the indentation level of its own * AST, it typically also checks surrounding ASTs. For instance, a * while loop handler checks the while loop as well as the braces * and immediate children. *

*
 *   - handler class -to-> ID mapping kept in Map
 *   - parent passed in during construction
 *   - suggest child indent level
 *   - allows for some tokens to be on same line (ie inner classes OBJBLOCK)
 *     and not increase indentation level
 *   - looked at using double dispatch for suggestedChildLevel(), but it
 *     doesn't seem worthwhile, at least now
 *   - both tabs and spaces are considered whitespace in front of the line...
 *     tabs are converted to spaces
 *   - block parents with parens -- for, while, if, etc... -- are checked that
 *     they match the level of the parent
 * 
* * @author jrichard * @author o_sukhodolsky */ public class IndentationCheck extends Check { /** Default indentation amount - based on Sun */ private static final int DEFAULT_INDENTATION = 4; /** how many tabs or spaces to use */ private int mBasicOffset = DEFAULT_INDENTATION; /** how much to indent a case label */ private int mCaseIndentationAmount = DEFAULT_INDENTATION; /** how far brace should be indented when on next line */ private int mBraceAdjustment; /** handlers currently in use */ private final FastStack mHandlers = FastStack.newInstance(); /** factory from which handlers are distributed */ private final HandlerFactory mHandlerFactory = new HandlerFactory(); /** Creates a new instance of IndentationCheck. */ public IndentationCheck() { } /** * Set the basic offset. * * @param aBasicOffset the number of tabs or spaces to indent */ public void setBasicOffset(int aBasicOffset) { mBasicOffset = aBasicOffset; } /** * Get the basic offset. * * @return the number of tabs or spaces to indent */ public int getBasicOffset() { return mBasicOffset; } /** * Adjusts brace indentation (positive offset). * * @param aAdjustmentAmount the brace offset */ public void setBraceAdjustment(int aAdjustmentAmount) { mBraceAdjustment = aAdjustmentAmount; } /** * Get the brace adjustment amount. * * @return the positive offset to adjust braces */ public int getBraceAdjustement() { return mBraceAdjustment; } /** * Set the case indentation level. * * @param aAmount the case indentation level */ public void setCaseIndent(int aAmount) { mCaseIndentationAmount = aAmount; } /** * Get the case indentation level. * * @return the case indentation level */ public int getCaseIndent() { return mCaseIndentationAmount; } /** * Log an error message. * * @param aLine the line number where the error was found * @param aKey the message that describes the error * @param aArgs the details of the message * * @see java.text.MessageFormat */ public void indentationLog(int aLine, String aKey, Object... aArgs) { super.log(aLine, aKey, aArgs); } /** * Get the width of a tab. * * @return the width of a tab */ public int getIndentationTabWidth() { return getTabWidth(); } @Override public int[] getDefaultTokens() { return mHandlerFactory.getHandledTypes(); } @Override public void beginTree(DetailAST aAst) { mHandlerFactory.clearCreatedHandlers(); mHandlers.clear(); mHandlers.push(new PrimordialHandler(this)); } @Override public void visitToken(DetailAST aAST) { if ((aAST.getType() == TokenTypes.VARIABLE_DEF) && ScopeUtils.isLocalVariableDef(aAST)) { // we have handler only for members return; } final ExpressionHandler handler = mHandlerFactory.getHandler(this, aAST, mHandlers.peek()); mHandlers.push(handler); try { handler.checkIndentation(); } catch (final NullPointerException npe) { npe.printStackTrace(); } } @Override public void leaveToken(DetailAST aAST) { if ((aAST.getType() == TokenTypes.VARIABLE_DEF) && ScopeUtils.isLocalVariableDef(aAST)) { // we have handler only for members return; } mHandlers.pop(); } /** * Accessor for the handler factory. * * @return the handler factory */ final HandlerFactory getHandlerFactory() { return mHandlerFactory; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/IndentLevel.java100644 0 0 6654 12026051031 30711 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.google.common.collect.Sets; import java.util.SortedSet; /** * Encapsulates representation of notion of expected indentation levels. * Provide a way to have multiple accaptable levels. * * @author o_sukhodolsky */ public class IndentLevel { /** set of acceptable indentation levels. */ private final SortedSet mLevels = Sets.newTreeSet(); /** * Creates new instance with one accaptable indentation level. * @param aIndent accaptable indentation level. */ public IndentLevel(int aIndent) { mLevels.add(aIndent); } /** * Creates new instance for nested structure. * @param aBase parent's level * @param aOffset offset from parent's level. */ public IndentLevel(IndentLevel aBase, int aOffset) { for (Integer base : aBase.mLevels) { mLevels.add(base + aOffset); } } /** * Checks wether we have more than one level. * @return wether we have more than one level. */ public final boolean isMultiLevel() { return mLevels.size() > 1; } /** * Checks if given indentation is accaptable. * @param aIndent indentation to check. * @return true if givent indentation is acceptable, * false otherwise. */ public boolean accept(int aIndent) { return (mLevels.contains(aIndent)); } /** * @param aIndent indentation to check. * @return true if aIndent less then minimal of * accaptable indentation levels, false otherwise. */ public boolean gt(int aIndent) { return ((mLevels.first()).intValue() > aIndent); } /** * Adds one more acceptable indentation level. * @param aIndent new acceptable indentation. */ public void addAcceptedIndent(int aIndent) { mLevels.add(aIndent); } /** * Adds one more acceptable indentation level. * @param aIndent new acceptable indentation. */ public void addAcceptedIndent(IndentLevel aIndent) { mLevels.addAll(aIndent.mLevels); } @Override public String toString() { if (mLevels.size() == 1) { return mLevels.first().toString(); } return mLevels.toString(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/LabelHandler.java100644 0 0 5240 12026051030 31002 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for labels. * * @author jrichard */ public class LabelHandler extends ExpressionHandler { /** * The types of expressions that are children of a label. */ private final int[] mLabelChildren = new int[] { TokenTypes.IDENT, }; /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aExpr the abstract syntax tree * @param aParent the parent handler */ public LabelHandler(IndentationCheck aIndentCheck, DetailAST aExpr, ExpressionHandler aParent) { super(aIndentCheck, "label", aExpr, aParent); } @Override protected IndentLevel getLevelImpl() { return new IndentLevel(super.getLevelImpl(), -getBasicOffset()); } /** * Check the indentation of the label. */ private void checkLabel() { checkChildren(getMainAst(), mLabelChildren, getLevel(), true, false); } @Override public void checkIndentation() { checkLabel(); // need to check children (like 'block' parents do) final DetailAST parent = getMainAst().getFirstChild().getNextSibling(); final IndentLevel expected = new IndentLevel(getLevel(), getBasicOffset()); checkExpressionSubtree(parent, expected, true, false); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/LineSet.java100644 0 0 5764 12026051030 30043 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.google.common.collect.Maps; import java.util.SortedMap; /** * Represents a set of lines. * * @author jrichard */ public class LineSet { /** * Maps line numbers to their start column. */ private final SortedMap mLines = Maps.newTreeMap(); /** * Get the starting column for a given line number. * * @param aLineNum the specified line number * * @return the starting column for the given line number */ public Integer getStartColumn(Integer aLineNum) { return mLines.get(aLineNum); } /** * Get the starting column for the first line. * * @return the starting column for the first line. */ public int firstLineCol() { final Object firstLineKey = mLines.firstKey(); return (mLines.get(firstLineKey)).intValue(); } /** * Get the line number of the first line. * * @return the line number of the first line */ public int firstLine() { return (mLines.firstKey()).intValue(); } /** * Get the line number of the last line. * * @return the line number of the last line */ public int lastLine() { return (mLines.lastKey()).intValue(); } /** * Add a line to this set of lines. * * @param aLineNum the line to add * @param aCol the starting column of the new line */ public void addLineAndCol(int aLineNum, int aCol) { mLines.put(aLineNum, aCol); } /** * Determines if this set of lines is empty. * * @return true if it is empty, false otherwise */ public boolean isEmpty() { return mLines.isEmpty(); } @Override public String toString() { return "LineSet[ start=" + firstLine() + ", last=" + lastLine() + "]"; } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/MemberDefHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/MemberDefHandler.ja100644 0 0 5566 12026051030 31275 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for member definitions. * * @author o_sukhodolsky */ public class MemberDefHandler extends ExpressionHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAST the abstract syntax tree * @param aParent the parent handler */ public MemberDefHandler(IndentationCheck aIndentCheck, DetailAST aAST, ExpressionHandler aParent) { super(aIndentCheck, "member def", aAST, aParent); } /** * Check the indentation of the method name. */ private void checkIdent() { final DetailAST ident = getMainAst().findFirstToken(TokenTypes.IDENT); final int columnNo = expandedTabsColumnNo(ident); if (startsLine(ident) && !getLevel().accept(columnNo)) { logError(ident, "", columnNo); } } /** * Check the indentation of the method type. */ private void checkType() { final DetailAST type = getMainAst().findFirstToken(TokenTypes.TYPE); final DetailAST ident = ExpressionHandler.getFirstToken(type); final int columnNo = expandedTabsColumnNo(ident); if (startsLine(ident) && !getLevel().accept(columnNo)) { logError(ident, "type", columnNo); } } @Override public void checkIndentation() { checkModifiers(); checkType(); checkIdent(); } @Override public IndentLevel suggestedChildLevel(ExpressionHandler aChild) { return getLevel(); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages.properties100644 0 0 254 11451071613 31541 0ustar 0 0 indentation.error={0} at indentation level {1} not at correct indentation, {2} indentation.child.error={0} child at indentation level {1} not at correct indentation, {2} ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_de.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_de.propert100644 0 0 261 11451071613 31506 0ustar 0 0 indentation.error={0} bei Einrücktiefe {1} nicht an korrekter Einrücktiefe {2} indentation.child.error=Kind von {0} bei Einrücktiefe {1} nicht an korrekter Einrücktiefe {2} ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_es.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_es.propert100644 0 0 272 11451071613 31527 0ustar 0 0 indentation.error={0} en el nivel de sangrado {1} no está al nivel correcto, {2} indentation.child.error={0} el descendiente en el nivel de sangrado {1} no está al nivel correcto, {2} ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_fi.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_fi.propert100644 0 0 120 11451071613 31506 0ustar 0 0 indentation.error={0} sisennyssyvyydell¤ {1} ei ole oikealla syvyydell¤ {2}. ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_fr.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_fr.propert100644 0 0 304 11451071613 31523 0ustar 0 0 indentation.error={0} au niveau d''indentation {1} n''est pas indenté correctement ({2}) indentation.child.error=Le fils de {0} au niveau d''identation {1} n''est pas indenté correctement ({2}) ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_ja.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_ja.propert100644 0 0 552 11451071613 31513 0ustar 0 0 indentation.error=\u30a4\u30f3\u30c7\u30f3\u30c8\u968e\u5c64 {1} \u306e {0} \u304c\u6b63\u3057\u3044\u30a4\u30f3\u30c7\u30f3\u30c8 {2} \u306b\u3042\u308a\u307e\u305b\u3093 indentation.child.error=\u30a4\u30f3\u30c7\u30f3\u30c8\u968e\u5c64 {1} \u306e\u5b50 {0} \u304c\u6b63\u3057\u3044\u30a4\u30f3\u30c7\u30f3\u30c8 {2} \u306b\u3042\u308a\u307e\u305b\u3093 ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_pt.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_pt.propert100644 0 0 275 11451071613 31546 0ustar 0 0 indentation.error={0} no nível de indentaço {1} no está na indentaço correcta, {2} indentation.child.error=Filho de {0} no nível de indentaço {1} no está na indentaço correcta, {2} ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_tr.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/messages_tr.propert100644 0 0 546 11744664014 31561 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) indentation.child.error = {0} ifadesi do\u011Fru hizalanmam\u0131\u015F. Bulundu\u011Fu s\u00FCtun {1}, olmas\u0131 gereken s\u00FCtun {2}. indentation.error = {0} ifadesi do\u011Fru hizalanmam\u0131\u015F. Bulundu\u011Fu s\u00FCtun {1}, olmas\u0131 gereken s\u00FCtun {2}. ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/MethodCallHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/MethodCallHandler.j100644 0 0 15303 12026051030 31330 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for method calls. * * @author jrichard */ public class MethodCallHandler extends ExpressionHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAST the abstract syntax tree * @param aParent the parent handler */ public MethodCallHandler(IndentationCheck aIndentCheck, DetailAST aAST, ExpressionHandler aParent) { super(aIndentCheck, aAST.getType() == TokenTypes.METHOD_CALL ? "method call" : "ctor call", aAST, aParent); } @Override protected IndentLevel getLevelImpl() { // if inside a method call's params, this could be part of // an expression, so get the previous line's start if (getParent() instanceof MethodCallHandler) { final MethodCallHandler container = ((MethodCallHandler) getParent()); if (container != null) { if (areOnSameLine(container.getMainAst(), getMainAst())) { return container.getLevel(); } // we should increase indentation only if this is the first // chained method call which was moved to the next line final DetailAST main = getMainAst(); final DetailAST dot = main.getFirstChild(); final DetailAST target = dot.getFirstChild(); if ((dot.getType() == TokenTypes.DOT) && (target.getType() == TokenTypes.METHOD_CALL)) { final DetailAST dot1 = target.getFirstChild(); final DetailAST target1 = dot1.getFirstChild(); if ((dot1.getType() == TokenTypes.DOT) && (target1.getType() == TokenTypes.METHOD_CALL)) { return container.getLevel(); } } return new IndentLevel(container.getLevel(), getBasicOffset()); } // if we get here, we are the child of the left hand side (name // side) of a method call with no "containing" call, use // the first non-method call parent ExpressionHandler p = getParent(); while (p instanceof MethodCallHandler) { p = p.getParent(); } return p.suggestedChildLevel(this); } // if our expression isn't first on the line, just use the start // of the line final LineSet lines = new LineSet(); findSubtreeLines(lines, getMainAst().getFirstChild(), true); final int firstCol = lines.firstLineCol(); final int lineStart = getLineStart(getFirstAst(getMainAst())); if (lineStart != firstCol) { return new IndentLevel(lineStart); } return super.getLevelImpl(); } /** * Get the first AST of the specified method call. * * @param aAst * the method call * * @return the first AST of the specified method call */ private DetailAST getFirstAst(DetailAST aAst) { // walk down the first child part of the dots that make up a method // call name DetailAST ast = aAst.getFirstChild(); while ((ast != null) && (ast.getType() == TokenTypes.DOT)) { ast = ast.getFirstChild(); } if (ast == null) { ast = aAst; } return ast; } @Override public IndentLevel suggestedChildLevel(ExpressionHandler aChild) { // for whatever reason a method that crosses lines, like asList // here: // System.out.println("methods are: " + Arrays.asList( // new String[] {"method"}).toString()); // will not have the right line num, so just get the child name final DetailAST first = getMainAst().getFirstChild(); int indentLevel = getLineStart(first); if (!areOnSameLine(aChild.getMainAst().getFirstChild(), getMainAst().getFirstChild())) { indentLevel += getBasicOffset(); } return new IndentLevel(indentLevel); } @Override public void checkIndentation() { final DetailAST methodName = getMainAst().getFirstChild(); checkExpressionSubtree(methodName, getLevel(), false, false); final DetailAST lparen = getMainAst(); final DetailAST rparen = getMainAst().findFirstToken(TokenTypes.RPAREN); checkLParen(lparen); if (rparen.getLineNo() == lparen.getLineNo()) { return; } // if this method name is on the same line as a containing // method, don't indent, this allows expressions like: // method("my str" + method2( // "my str2")); // as well as // method("my str" + // method2( // "my str2")); // checkExpressionSubtree( getMainAst().findFirstToken(TokenTypes.ELIST), new IndentLevel(getLevel(), getBasicOffset()), false, true); checkRParen(lparen, rparen); } @Override protected boolean shouldIncreaseIndent() { return false; } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/MethodDefHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/MethodDefHandler.ja100644 0 0 10214 12026051027 31316 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for method definitions. * * @author jrichard */ public class MethodDefHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public MethodDefHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, (aAst.getType() == TokenTypes.CTOR_DEF) ? "ctor def" : "method def", aAst, aParent); } @Override protected DetailAST getToplevelAST() { // we check this stuff ourselves below return null; } /** * Check the indentation of the method name. */ private void checkIdent() { final DetailAST ident = getMainAst().findFirstToken(TokenTypes.IDENT); final int columnNo = expandedTabsColumnNo(ident); if (startsLine(ident) && !getLevel().accept(columnNo)) { logError(ident, "", columnNo); } } /** * Check the indentation of the throws clause. */ private void checkThrows() { final DetailAST throwsAst = getMainAst().findFirstToken(TokenTypes.LITERAL_THROWS); if (throwsAst == null) { return; } final int columnNo = expandedTabsColumnNo(throwsAst); final IndentLevel expectedColumnNo = new IndentLevel(getLevel(), getBasicOffset()); if (startsLine(throwsAst) && !expectedColumnNo.accept(columnNo)) { logError(throwsAst, "throws", columnNo, expectedColumnNo); } } /** * Check the indentation of the method type. */ private void checkType() { final DetailAST type = getMainAst().findFirstToken(TokenTypes.TYPE); final DetailAST ident = ExpressionHandler.getFirstToken(type); final int columnNo = expandedTabsColumnNo(ident); if (startsLine(ident) && !getLevel().accept(columnNo)) { logError(ident, "return type", columnNo); } } /** * Check the indentation of the method parameters. */ private void checkParameters() { final DetailAST params = getMainAst().findFirstToken(TokenTypes.PARAMETERS); checkExpressionSubtree(params, getLevel(), false, false); } @Override public void checkIndentation() { checkModifiers(); checkIdent(); checkThrows(); if (getMainAst().getType() != TokenTypes.CTOR_DEF) { checkType(); } checkParameters(); if (getLCurly() == null) { // asbtract method def -- no body return; } super.checkIndentation(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/NewHandler.java100644 0 0 6545 12026051027 30533 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for operator new. * * @author o_sukhodolsky */ public class NewHandler extends ExpressionHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAST the abstract syntax tree * @param aParent the parent handler */ public NewHandler(IndentationCheck aIndentCheck, DetailAST aAST, ExpressionHandler aParent) { super(aIndentCheck, "operator new", aAST, aParent); } @Override public void checkIndentation() { final DetailAST type = getMainAst().getFirstChild(); checkExpressionSubtree(type, getLevel(), false, false); final DetailAST lparen = getMainAst().findFirstToken(TokenTypes.LPAREN); final DetailAST rparen = getMainAst().findFirstToken(TokenTypes.RPAREN); checkLParen(lparen); if ((rparen == null) || (lparen == null) || (rparen.getLineNo() == lparen.getLineNo())) { return; } // if this method name is on the same line as a containing // method, don't indent, this allows expressions like: // method("my str" + method2( // "my str2")); // as well as // method("my str" + // method2( // "my str2")); // checkExpressionSubtree( getMainAst().findFirstToken(TokenTypes.ELIST), new IndentLevel(getLevel(), getBasicOffset()), false, true); checkRParen(lparen, rparen); } @Override protected IndentLevel getLevelImpl() { // if our expression isn't first on the line, just use the start // of the line if (getLineStart(getMainAst()) != getMainAst().getColumnNo()) { return new IndentLevel(getLineStart(getMainAst())); } return super.getLevelImpl(); } @Override protected boolean shouldIncreaseIndent() { return false; } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ObjectBlockHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/ObjectBlockHandler.100644 0 0 6262 12026051027 31315 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for inner classes. * * @author jrichard */ public class ObjectBlockHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public ObjectBlockHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "object def", aAst, aParent); } @Override protected DetailAST getToplevelAST() { return null; } @Override protected DetailAST getLCurly() { return getMainAst().findFirstToken(TokenTypes.LCURLY); } @Override protected DetailAST getRCurly() { return getMainAst().findFirstToken(TokenTypes.RCURLY); } @Override protected DetailAST getListChild() { return getMainAst(); } @Override protected IndentLevel getLevelImpl() { final DetailAST parentAST = getMainAst().getParent(); IndentLevel indent = getParent().getLevel(); if (parentAST.getType() == TokenTypes.LITERAL_NEW) { indent.addAcceptedIndent(super.getLevelImpl()); } else if (parentAST.getType() == TokenTypes.ENUM_CONSTANT_DEF) { indent = super.getLevelImpl(); } return indent; } @Override public void checkIndentation() { // if we have a class or interface as a parent, don't do anything, // as this is checked by class def; so // only do this if we have a new for a parent (anonymous inner // class) final DetailAST parentAST = getMainAst().getParent(); if (parentAST.getType() != TokenTypes.LITERAL_NEW) { return; } super.checkIndentation(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/package-info.java100644 0 0 2265 12026051025 31021 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains all classes required for the * indentation check. */ package com.puppycrawl.tools.checkstyle.checks.indentation; ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/PackageDefHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/PackageDefHandler.j100644 0 0 4275 12026051027 31262 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for package definitions. * * @author jrichard */ public class PackageDefHandler extends ExpressionHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public PackageDefHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "package def", aAst, aParent); } @Override public void checkIndentation() { final int columnNo = expandedTabsColumnNo(getMainAst()); if (!getLevel().accept(columnNo)) { logError(getMainAst(), "", columnNo); } checkLinesIndent(getMainAst().getLineNo(), getMainAst().findFirstToken(TokenTypes.SEMI).getLineNo(), getLevel()); } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/PrimordialHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/PrimordialHandler.j100644 0 0 3465 12026051027 31412 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; /** * A default no-op handler. * * @author jrichard */ public class PrimordialHandler extends ExpressionHandler { /** * Construct an instance of this handler with the given indentation check. * * @param aIndentCheck the indentation check */ public PrimordialHandler(IndentationCheck aIndentCheck) { super(aIndentCheck, null, null, null); } @Override public void checkIndentation() { // nothing to check } @Override public IndentLevel suggestedChildLevel(ExpressionHandler aChild) { return new IndentLevel(0); } @Override protected IndentLevel getLevelImpl() { return new IndentLevel(0); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/SlistHandler.java100644 0 0 10663 12026051026 31113 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for a list of statements. * * @author jrichard */ public class SlistHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public SlistHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "block", aAst, aParent); } @Override public IndentLevel suggestedChildLevel(ExpressionHandler aChild) { // this is: // switch (var) { // case 3: { // break; // } // } // ... the case SLIST is followed by a user-created SLIST and // preceded by a switch // if our parent is a block handler we want to be transparent if (((getParent() instanceof BlockParentHandler) && !(getParent() instanceof SlistHandler)) || ((getParent() instanceof CaseHandler) && (aChild instanceof SlistHandler))) { return getParent().suggestedChildLevel(aChild); } return super.suggestedChildLevel(aChild); } @Override protected DetailAST getNonlistChild() { // blocks always have either block children or they are transparent // and aren't checking children at all. In the later case, the // superclass will want to check single children, so when it // does tell it we have none. return null; } @Override protected DetailAST getListChild() { return getMainAst(); } @Override protected DetailAST getLCurly() { return getMainAst(); } @Override protected DetailAST getRCurly() { return getMainAst().findFirstToken(TokenTypes.RCURLY); } @Override protected DetailAST getToplevelAST() { return null; } /** * Determine if the expression we are handling has a block parent. * * @return true if it does, false otherwise */ private boolean hasBlockParent() { final int parentType = getMainAst().getParent().getType(); return (parentType == TokenTypes.LITERAL_IF) || (parentType == TokenTypes.LITERAL_FOR) || (parentType == TokenTypes.LITERAL_WHILE) || (parentType == TokenTypes.LITERAL_DO) || (parentType == TokenTypes.LITERAL_ELSE) || (parentType == TokenTypes.LITERAL_TRY) || (parentType == TokenTypes.LITERAL_CATCH) || (parentType == TokenTypes.LITERAL_FINALLY) || (parentType == TokenTypes.CTOR_DEF) || (parentType == TokenTypes.METHOD_DEF) || (parentType == TokenTypes.STATIC_INIT); } @Override public void checkIndentation() { // only need to check this if parent is not // an if, else, while, do, ctor, method if (hasBlockParent()) { return; } super.checkIndentation(); } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/StaticInitHandler.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/StaticInitHandler.j100644 0 0 3566 12026051026 31364 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Handler for static initialization blocks. * * @author Jeff Weston */ public class StaticInitHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public StaticInitHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "static initialization", aAst, aParent); } @Override protected boolean toplevelMustStartLine() { return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/SwitchHandler.java100644 0 0 5671 12026051026 31241 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for switch statements. * * @author jrichard */ public class SwitchHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public SwitchHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "switch", aAst, aParent); } @Override protected DetailAST getLCurly() { return getMainAst().findFirstToken(TokenTypes.LCURLY); } @Override protected DetailAST getRCurly() { return getMainAst().findFirstToken(TokenTypes.RCURLY); } @Override protected DetailAST getListChild() { // all children should be taken care of by case handler (plus // there is no parent of just the cases, if checking is needed // here in the future, an additional way beyond checkChildren() // will have to be devised to get children) return null; } @Override protected DetailAST getNonlistChild() { return null; } /** * Check the indentation of the switch expression. */ private void checkSwitchExpr() { checkExpressionSubtree( getMainAst().findFirstToken(TokenTypes.LPAREN). getNextSibling(), getLevel(), false, false); } @Override public void checkIndentation() { checkSwitchExpr(); super.checkIndentation(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/TryHandler.java100644 0 0 4014 12026051026 30544 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * Handler for try blocks. * * @author jrichard */ public class TryHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public TryHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "try", aAst, aParent); } @Override public IndentLevel suggestedChildLevel(ExpressionHandler aChild) { if ((aChild instanceof CatchHandler) || (aChild instanceof FinallyHandler)) { return getLevel(); } return super.suggestedChildLevel(aChild); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/indentation/WhileHandler.java100644 0 0 4421 12026051025 31037 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Handler for while loops. * * @author jrichard */ public class WhileHandler extends BlockParentHandler { /** * Construct an instance of this handler with the given indentation check, * abstract syntax tree, and parent handler. * * @param aIndentCheck the indentation check * @param aAst the abstract syntax tree * @param aParent the parent handler */ public WhileHandler(IndentationCheck aIndentCheck, DetailAST aAst, ExpressionHandler aParent) { super(aIndentCheck, "while", aAst, aParent); } /** * Check the indentation of the conditional expression. */ private void checkCondExpr() { final DetailAST condAst = getMainAst().findFirstToken(TokenTypes.EXPR); final IndentLevel expected = new IndentLevel(getLevel(), getBasicOffset()); checkExpressionSubtree(condAst, expected, false, false); } @Override public void checkIndentation() { checkCondExpr(); super.checkIndentation(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/HtmlTag.java100644 0 0 10345 12026051025 27146 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; /** * Used to keep track of a tag and the text that follows it. * * @author Chris Stillwell */ class HtmlTag { /** The maximum length of text to display with this tag. */ private static final int MAX_TEXT_LEN = 60; /** The HTML tag name. */ private final String mId; /** The line number in the source file where this tag was found. */ private final int mLineNo; /** The position within the line where this tag was found. */ private final int mPosition; /** The comment line of text where this tag appears. */ private final String mText; /** if this tag is self-closed. */ private final boolean mClosedTag; /** if the tag is inomplete. */ private final boolean mIncomplete; /** * Construct the HtmlTag. * @param aId the HTML tag name. * @param aLineNo the source line number of this tag. * @param aPosition the position within the text of this tag. * @param aClosedTag if this tag is self-closed (XHTML style) * @param aIncomplete is the tag is incomplete. * @param aText the line of comment text for this tag. */ HtmlTag(String aId, int aLineNo, int aPosition, boolean aClosedTag, boolean aIncomplete, String aText) { mId = (!"".equals(aId) && (aId.charAt(0) == '/')) ? aId.substring(1) : aId; mLineNo = aLineNo; mPosition = aPosition; mText = aText; mClosedTag = aClosedTag; mIncomplete = aIncomplete; } /** * Returns the id (name) of this tag. * @return a String id. */ public String getId() { return mId; } /** * Indicates if this tag is a close (end) tag. * @return true is this is a close tag. */ public boolean isCloseTag() { if (mPosition == (mText.length() - 1)) { return false; } return (mText.charAt(mPosition + 1) == '/'); } /** * Indicates if this tag is a self-closed XHTML style. * @return true is this is a self-closed tag. */ public boolean isClosedTag() { return mClosedTag; } /** * Indicates if this tag is incomplete (has no close >). * @return true if the tag is incomplete. */ public boolean isIncompleteTag() { return mIncomplete; } /** * Returns the source line number where this tag was found. * Used for displaying a Checkstyle error. * @return an int line number. */ public int getLineno() { return mLineNo; } /** * Returns the position with in the comment line where this tag * was found. Used for displaying a Checkstyle error. * @return an int relative to zero. */ public int getPosition() { return mPosition; } @Override public String toString() { final int startOfText = mPosition; final int endOfText = Math.min(startOfText + HtmlTag.MAX_TEXT_LEN, mText.length()); return mText.substring(startOfText, endOfText); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/InvalidJavadocTag.java100644 0 0 3727 12026051025 31106 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; /** * Value object for storing data about an invalid Javadoc validTags. * @author Oliver Burn */ public final class InvalidJavadocTag { /** The line in which the invalid tag occurs. */ private final int mLine; /** The column in which the invalid tag occurs. */ private final int mCol; /** The name of the invalid tag. */ private final String mName; /** * Creates an instance. * @param aLine the line of the tag * @param aCol the column of the tag * @param aName the name of the invalid tag */ public InvalidJavadocTag(int aLine, int aCol, String aName) { mLine = aLine; mCol = aCol; mName = aName; } public int getLine() { return mLine; } public int getCol() { return mCol; } public String getName() { return mName; } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java100644 0 0 105164 12026051024 31277 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import antlr.collections.AST; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.JavadocTagInfo; import com.puppycrawl.tools.checkstyle.api.Scope; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Checks the Javadoc of a method or constructor. * * @author Oliver Burn * @author Rick Giles * @author o_sukhodoslky */ public class JavadocMethodCheck extends AbstractTypeAwareCheck { /** compiled regexp to match Javadoc tags that take an argument * */ private static final Pattern MATCH_JAVADOC_ARG = Utils.createPattern("@(throws|exception|param)\\s+(\\S+)\\s+\\S*"); /** compiled regexp to match first part of multilineJavadoc tags * */ private static final Pattern MATCH_JAVADOC_ARG_MULTILINE_START = Utils.createPattern("@(throws|exception|param)\\s+(\\S+)\\s*$"); /** compiled regexp to look for a continuation of the comment * */ private static final Pattern MATCH_JAVADOC_MULTILINE_CONT = Utils.createPattern("(\\*/|@|[^\\s\\*])"); /** Multiline finished at end of comment * */ private static final String END_JAVADOC = "*/"; /** Multiline finished at next Javadoc * */ private static final String NEXT_TAG = "@"; /** compiled regexp to match Javadoc tags with no argument * */ private static final Pattern MATCH_JAVADOC_NOARG = Utils.createPattern("@(return|see)\\s+\\S"); /** compiled regexp to match first part of multilineJavadoc tags * */ private static final Pattern MATCH_JAVADOC_NOARG_MULTILINE_START = Utils.createPattern("@(return|see)\\s*$"); /** compiled regexp to match Javadoc tags with no argument and {} * */ private static final Pattern MATCH_JAVADOC_NOARG_CURLY = Utils.createPattern("\\{\\s*@(inheritDoc)\\s*\\}"); /** Maximum children allowed * */ private static final int MAX_CHILDREN = 7; /** Maximum children allowed * */ private static final int BODY_SIZE = 3; /** the visibility scope where Javadoc comments are checked * */ private Scope mScope = Scope.PRIVATE; /** the visibility scope where Javadoc comments shouldn't be checked * */ private Scope mExcludeScope; /** * controls whether to allow documented exceptions that are not declared if * they are a subclass of java.lang.RuntimeException. */ private boolean mAllowUndeclaredRTE; /** * controls whether to allow documented exceptions that are subclass of one * of declared exception. Defaults to false (backward compatibility). */ private boolean mAllowThrowsTagsForSubclasses; /** * controls whether to ignore errors when a method has parameters but does * not have matching param tags in the javadoc. Defaults to false. */ private boolean mAllowMissingParamTags; /** * controls whether to ignore errors when a method declares that it throws * exceptions but does not have matching throws tags in the javadoc. * Defaults to false. */ private boolean mAllowMissingThrowsTags; /** * controls whether to ignore errors when a method returns non-void type * but does not have a return tag in the javadoc. Defaults to false. */ private boolean mAllowMissingReturnTag; /** * Controls whether to ignore errors when there is no javadoc. Defaults to * false. */ private boolean mAllowMissingJavadoc; /** * Controls whether to allow missing Javadoc on accessor methods for * properties (setters and getters). */ private boolean mAllowMissingPropertyJavadoc; /** * Set the scope. * * @param aFrom a String value */ public void setScope(String aFrom) { mScope = Scope.getInstance(aFrom); } /** * Set the excludeScope. * * @param aScope a String value */ public void setExcludeScope(String aScope) { mExcludeScope = Scope.getInstance(aScope); } /** * controls whether to allow documented exceptions that are not declared if * they are a subclass of java.lang.RuntimeException. * * @param aFlag a Boolean value */ public void setAllowUndeclaredRTE(boolean aFlag) { mAllowUndeclaredRTE = aFlag; } /** * controls whether to allow documented exception that are subclass of one * of declared exceptions. * * @param aFlag a Boolean value */ public void setAllowThrowsTagsForSubclasses(boolean aFlag) { mAllowThrowsTagsForSubclasses = aFlag; } /** * controls whether to allow a method which has parameters to omit matching * param tags in the javadoc. Defaults to false. * * @param aFlag a Boolean value */ public void setAllowMissingParamTags(boolean aFlag) { mAllowMissingParamTags = aFlag; } /** * controls whether to allow a method which declares that it throws * exceptions to omit matching throws tags in the javadoc. Defaults to * false. * * @param aFlag a Boolean value */ public void setAllowMissingThrowsTags(boolean aFlag) { mAllowMissingThrowsTags = aFlag; } /** * controls whether to allow a method which returns non-void type to omit * the return tag in the javadoc. Defaults to false. * * @param aFlag a Boolean value */ public void setAllowMissingReturnTag(boolean aFlag) { mAllowMissingReturnTag = aFlag; } /** * Controls whether to ignore errors when there is no javadoc. Defaults to * false. * * @param aFlag a Boolean value */ public void setAllowMissingJavadoc(boolean aFlag) { mAllowMissingJavadoc = aFlag; } /** * Controls whether to ignore errors when there is no javadoc for a * property accessor (setter/getter methods). Defaults to false. * * @param aFlag a Boolean value */ public void setAllowMissingPropertyJavadoc(final boolean aFlag) { mAllowMissingPropertyJavadoc = aFlag; } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.PACKAGE_DEF, TokenTypes.IMPORT, TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF, TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, TokenTypes.ANNOTATION_FIELD_DEF, }; } @Override public int[] getAcceptableTokens() { return new int[] {TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, TokenTypes.ANNOTATION_FIELD_DEF, }; } @Override protected final void processAST(DetailAST aAST) { final Scope theScope = calculateScope(aAST); if (shouldCheck(aAST, theScope)) { final FileContents contents = getFileContents(); final TextBlock cmt = contents.getJavadocBefore(aAST.getLineNo()); if (cmt == null) { if (!isMissingJavadocAllowed(aAST)) { log(aAST, "javadoc.missing"); } } else { checkComment(aAST, cmt, theScope); } } } @Override protected final void logLoadError(Token aIdent) { logLoadErrorImpl(aIdent.getLineNo(), aIdent.getColumnNo(), "javadoc.classInfo", JavadocTagInfo.THROWS.getText(), aIdent.getText()); } /** * The JavadocMethodCheck is about to report a missing Javadoc. * This hook can be used by derived classes to allow a missing javadoc * in some situations. The default implementation checks * allowMissingJavadoc and * allowMissingPropertyJavadoc properties, do not forget * to call super.isMissingJavadocAllowed(aAST) in case * you want to keep this logic. * @param aAST the tree node for the method or constructor. * @return True if this method or constructor doesn't need Javadoc. */ protected boolean isMissingJavadocAllowed(final DetailAST aAST) { return mAllowMissingJavadoc || isOverrideMethod(aAST) || (mAllowMissingPropertyJavadoc && (isSetterMethod(aAST) || isGetterMethod(aAST))); } /** * Whether we should check this node. * * @param aAST a given node. * @param aScope the scope of the node. * @return whether we should check a given node. */ private boolean shouldCheck(final DetailAST aAST, final Scope aScope) { final Scope surroundingScope = ScopeUtils.getSurroundingScope(aAST); return aScope.isIn(mScope) && surroundingScope.isIn(mScope) && ((mExcludeScope == null) || !aScope.isIn(mExcludeScope) || !surroundingScope.isIn(mExcludeScope)); } /** * Checks the Javadoc for a method. * * @param aAST the token for the method * @param aComment the Javadoc comment * @param aScope the scope of the method. */ private void checkComment(DetailAST aAST, TextBlock aComment, Scope aScope) { final List tags = getMethodTags(aComment); if (hasShortCircuitTag(aAST, tags, aScope)) { return; } Iterator it = tags.iterator(); if (aAST.getType() != TokenTypes.ANNOTATION_FIELD_DEF) { // Check for inheritDoc boolean hasInheritDocTag = false; while (it.hasNext() && !hasInheritDocTag) { hasInheritDocTag |= (it.next()).isInheritDocTag(); } checkParamTags(tags, aAST, !hasInheritDocTag); checkThrowsTags(tags, getThrows(aAST), !hasInheritDocTag); if (isFunction(aAST)) { checkReturnTag(tags, aAST.getLineNo(), !hasInheritDocTag); } } // Dump out all unused tags it = tags.iterator(); while (it.hasNext()) { final JavadocTag jt = it.next(); if (!jt.isSeeOrInheritDocTag()) { log(jt.getLineNo(), "javadoc.unusedTagGeneral"); } } } /** * Validates whether the Javadoc has a short circuit tag. Currently this is * the inheritTag. Any errors are logged. * * @param aAST the construct being checked * @param aTags the list of Javadoc tags associated with the construct * @param aScope the scope of the construct * @return true if the construct has a short circuit tag. */ private boolean hasShortCircuitTag(final DetailAST aAST, final List aTags, final Scope aScope) { // Check if it contains {@inheritDoc} tag if ((aTags.size() != 1) || !(aTags.get(0)).isInheritDocTag()) { return false; } // Invalid if private, a constructor, or a static method if (!JavadocTagInfo.INHERIT_DOC.isValidOn(aAST)) { log(aAST, "javadoc.invalidInheritDoc"); } return true; } /** * Returns the scope for the method/constructor at the specified AST. If * the method is in an interface or annotation block, the scope is assumed * to be public. * * @param aAST the token of the method/constructor * @return the scope of the method/constructor */ private Scope calculateScope(final DetailAST aAST) { final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS); final Scope declaredScope = ScopeUtils.getScopeFromMods(mods); return ScopeUtils.inInterfaceOrAnnotationBlock(aAST) ? Scope.PUBLIC : declaredScope; } /** * Returns the tags in a javadoc comment. Only finds throws, exception, * param, return and see tags. * * @return the tags found * @param aComment the Javadoc comment */ private List getMethodTags(TextBlock aComment) { final String[] lines = aComment.getText(); final List tags = Lists.newArrayList(); int currentLine = aComment.getStartLineNo() - 1; for (int i = 0; i < lines.length; i++) { currentLine++; final Matcher javadocArgMatcher = MATCH_JAVADOC_ARG.matcher(lines[i]); final Matcher javadocNoargMatcher = MATCH_JAVADOC_NOARG.matcher(lines[i]); final Matcher noargCurlyMatcher = MATCH_JAVADOC_NOARG_CURLY.matcher(lines[i]); final Matcher argMultilineStart = MATCH_JAVADOC_ARG_MULTILINE_START.matcher(lines[i]); final Matcher noargMultilineStart = MATCH_JAVADOC_NOARG_MULTILINE_START.matcher(lines[i]); if (javadocArgMatcher.find()) { int col = javadocArgMatcher.start(1) - 1; if (i == 0) { col += aComment.getStartColNo(); } tags.add(new JavadocTag(currentLine, col, javadocArgMatcher .group(1), javadocArgMatcher.group(2))); } else if (javadocNoargMatcher.find()) { int col = javadocNoargMatcher.start(1) - 1; if (i == 0) { col += aComment.getStartColNo(); } tags.add(new JavadocTag(currentLine, col, javadocNoargMatcher .group(1))); } else if (noargCurlyMatcher.find()) { int col = noargCurlyMatcher.start(1) - 1; if (i == 0) { col += aComment.getStartColNo(); } tags.add(new JavadocTag(currentLine, col, noargCurlyMatcher .group(1))); } else if (argMultilineStart.find()) { final String p1 = argMultilineStart.group(1); final String p2 = argMultilineStart.group(2); int col = argMultilineStart.start(1) - 1; if (i == 0) { col += aComment.getStartColNo(); } // Look for the rest of the comment if all we saw was // the tag and the name. Stop when we see '*/' (end of // Javadoc), '@' (start of next tag), or anything that's // not whitespace or '*' characters. int remIndex = i + 1; while (remIndex < lines.length) { final Matcher multilineCont = MATCH_JAVADOC_MULTILINE_CONT .matcher(lines[remIndex]); if (multilineCont.find()) { remIndex = lines.length; final String lFin = multilineCont.group(1); if (!lFin.equals(NEXT_TAG) && !lFin.equals(END_JAVADOC)) { tags.add(new JavadocTag(currentLine, col, p1, p2)); } } remIndex++; } } else if (noargMultilineStart.find()) { final String p1 = noargMultilineStart.group(1); int col = noargMultilineStart.start(1) - 1; if (i == 0) { col += aComment.getStartColNo(); } // Look for the rest of the comment if all we saw was // the tag and the name. Stop when we see '*/' (end of // Javadoc), '@' (start of next tag), or anything that's // not whitespace or '*' characters. int remIndex = i + 1; while (remIndex < lines.length) { final Matcher multilineCont = MATCH_JAVADOC_MULTILINE_CONT .matcher(lines[remIndex]); if (multilineCont.find()) { remIndex = lines.length; final String lFin = multilineCont.group(1); if (!lFin.equals(NEXT_TAG) && !lFin.equals(END_JAVADOC)) { tags.add(new JavadocTag(currentLine, col, p1)); } } remIndex++; } } } return tags; } /** * Computes the parameter nodes for a method. * * @param aAST the method node. * @return the list of parameter nodes for aAST. */ private List getParameters(DetailAST aAST) { final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS); final List retVal = Lists.newArrayList(); DetailAST child = params.getFirstChild(); while (child != null) { if (child.getType() == TokenTypes.PARAMETER_DEF) { final DetailAST ident = child.findFirstToken(TokenTypes.IDENT); retVal.add(ident); } child = child.getNextSibling(); } return retVal; } /** * Computes the exception nodes for a method. * * @param aAST the method node. * @return the list of exception nodes for aAST. */ private List getThrows(DetailAST aAST) { final List retVal = Lists.newArrayList(); final DetailAST throwsAST = aAST .findFirstToken(TokenTypes.LITERAL_THROWS); if (throwsAST != null) { DetailAST child = throwsAST.getFirstChild(); while (child != null) { if ((child.getType() == TokenTypes.IDENT) || (child.getType() == TokenTypes.DOT)) { final FullIdent fi = FullIdent.createFullIdent(child); final ExceptionInfo ei = new ExceptionInfo(new Token(fi), getCurrentClassName()); retVal.add(ei); } child = child.getNextSibling(); } } return retVal; } /** * Checks a set of tags for matching parameters. * * @param aTags the tags to check * @param aParent the node which takes the parameters * @param aReportExpectedTags whether we should report if do not find * expected tag */ private void checkParamTags(final List aTags, final DetailAST aParent, boolean aReportExpectedTags) { final List params = getParameters(aParent); final List typeParams = CheckUtils .getTypeParameters(aParent); // Loop over the tags, checking to see they exist in the params. final ListIterator tagIt = aTags.listIterator(); while (tagIt.hasNext()) { final JavadocTag tag = tagIt.next(); if (!tag.isParamTag()) { continue; } tagIt.remove(); boolean found = false; // Loop looking for matching param final Iterator paramIt = params.iterator(); while (paramIt.hasNext()) { final DetailAST param = paramIt.next(); if (param.getText().equals(tag.getArg1())) { found = true; paramIt.remove(); break; } } if (tag.getArg1().startsWith("<") && tag.getArg1().endsWith(">")) { // Loop looking for matching type param final Iterator typeParamsIt = typeParams.iterator(); while (typeParamsIt.hasNext()) { final DetailAST typeParam = typeParamsIt.next(); if (typeParam.findFirstToken(TokenTypes.IDENT).getText() .equals( tag.getArg1().substring(1, tag.getArg1().length() - 1))) { found = true; typeParamsIt.remove(); break; } } } // Handle extra JavadocTag if (!found) { log(tag.getLineNo(), tag.getColumnNo(), "javadoc.unusedTag", "@param", tag.getArg1()); } } // Now dump out all type parameters/parameters without tags :- unless // the user has chosen to suppress these problems if (!mAllowMissingParamTags && aReportExpectedTags) { for (DetailAST param : params) { log(param, "javadoc.expectedTag", JavadocTagInfo.PARAM.getText(), param.getText()); } for (DetailAST typeParam : typeParams) { log(typeParam, "javadoc.expectedTag", JavadocTagInfo.PARAM.getText(), "<" + typeParam.findFirstToken(TokenTypes.IDENT).getText() + ">"); } } } /** * Checks whether a method is a function. * * @param aAST the method node. * @return whether the method is a function. */ private boolean isFunction(DetailAST aAST) { boolean retVal = false; if (aAST.getType() == TokenTypes.METHOD_DEF) { final DetailAST typeAST = aAST.findFirstToken(TokenTypes.TYPE); if ((typeAST != null) && (typeAST.findFirstToken(TokenTypes.LITERAL_VOID) == null)) { retVal = true; } } return retVal; } /** * Checks for only one return tag. All return tags will be removed from the * supplied list. * * @param aTags the tags to check * @param aLineNo the line number of the expected tag * @param aReportExpectedTags whether we should report if do not find * expected tag */ private void checkReturnTag(List aTags, int aLineNo, boolean aReportExpectedTags) { // Loop over tags finding return tags. After the first one, report an // error. boolean found = false; final ListIterator it = aTags.listIterator(); while (it.hasNext()) { final JavadocTag jt = it.next(); if (jt.isReturnTag()) { if (found) { log(jt.getLineNo(), jt.getColumnNo(), "javadoc.duplicateTag", JavadocTagInfo.RETURN.getText()); } found = true; it.remove(); } } // Handle there being no @return tags :- unless // the user has chosen to suppress these problems if (!found && !mAllowMissingReturnTag && aReportExpectedTags) { log(aLineNo, "javadoc.return.expected"); } } /** * Checks a set of tags for matching throws. * * @param aTags the tags to check * @param aThrows the throws to check * @param aReportExpectedTags whether we should report if do not find * expected tag */ private void checkThrowsTags(List aTags, List aThrows, boolean aReportExpectedTags) { // Loop over the tags, checking to see they exist in the throws. // The foundThrows used for performance only final Set foundThrows = Sets.newHashSet(); final ListIterator tagIt = aTags.listIterator(); while (tagIt.hasNext()) { final JavadocTag tag = tagIt.next(); if (!tag.isThrowsTag()) { continue; } tagIt.remove(); // Loop looking for matching throw final String documentedEx = tag.getArg1(); final Token token = new Token(tag.getArg1(), tag.getLineNo(), tag .getColumnNo()); final ClassInfo documentedCI = createClassInfo(token, getCurrentClassName()); boolean found = foundThrows.contains(documentedEx); // First look for matches on the exception name ListIterator throwIt = aThrows.listIterator(); while (!found && throwIt.hasNext()) { final ExceptionInfo ei = throwIt.next(); if (ei.getName().getText().equals( documentedCI.getName().getText())) { found = true; ei.setFound(); foundThrows.add(documentedEx); } } // Now match on the exception type throwIt = aThrows.listIterator(); while (!found && throwIt.hasNext()) { final ExceptionInfo ei = throwIt.next(); if (documentedCI.getClazz() == ei.getClazz()) { found = true; ei.setFound(); foundThrows.add(documentedEx); } else if (mAllowThrowsTagsForSubclasses) { found = isSubclass(documentedCI.getClazz(), ei.getClazz()); } } // Handle extra JavadocTag. if (!found) { boolean reqd = true; if (mAllowUndeclaredRTE) { reqd = !isUnchecked(documentedCI.getClazz()); } if (reqd) { log(tag.getLineNo(), tag.getColumnNo(), "javadoc.unusedTag", JavadocTagInfo.THROWS.getText(), tag.getArg1()); } } } // Now dump out all throws without tags :- unless // the user has chosen to suppress these problems if (!mAllowMissingThrowsTags && aReportExpectedTags) { for (ExceptionInfo ei : aThrows) { if (!ei.isFound()) { final Token fi = ei.getName(); log(fi.getLineNo(), fi.getColumnNo(), "javadoc.expectedTag", JavadocTagInfo.THROWS.getText(), fi.getText()); } } } } /** * Returns whether an AST represents a setter method. * @param aAST the AST to check with * @return whether the AST represents a setter method */ private boolean isSetterMethod(final DetailAST aAST) { // Check have a method with exactly 7 children which are all that // is allowed in a proper setter method which does not throw any // exceptions. if ((aAST.getType() != TokenTypes.METHOD_DEF) || (aAST.getChildCount() != MAX_CHILDREN)) { return false; } // Should I handle only being in a class???? // Check the name matches format setX... final DetailAST type = aAST.findFirstToken(TokenTypes.TYPE); final String name = type.getNextSibling().getText(); if (!name.matches("^set[A-Z].*")) { // Depends on JDK 1.4 return false; } // Check the return type is void if (type.getChildCount(TokenTypes.LITERAL_VOID) == 0) { return false; } // Check that is had only one parameter final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS); if ((params == null) || (params.getChildCount(TokenTypes.PARAMETER_DEF) != 1)) { return false; } // Now verify that the body consists of: // SLIST -> EXPR -> ASSIGN // SEMI // RCURLY final DetailAST slist = aAST.findFirstToken(TokenTypes.SLIST); if ((slist == null) || (slist.getChildCount() != BODY_SIZE)) { return false; } final AST expr = slist.getFirstChild(); if ((expr.getType() != TokenTypes.EXPR) || (expr.getFirstChild().getType() != TokenTypes.ASSIGN)) { return false; } return true; } /** * Returns whether an AST represents a getter method. * @param aAST the AST to check with * @return whether the AST represents a getter method */ private boolean isGetterMethod(final DetailAST aAST) { // Check have a method with exactly 7 children which are all that // is allowed in a proper getter method which does not throw any // exceptions. if ((aAST.getType() != TokenTypes.METHOD_DEF) || (aAST.getChildCount() != MAX_CHILDREN)) { return false; } // Check the name matches format of getX or isX. Technically I should // check that the format isX is only used with a boolean type. final DetailAST type = aAST.findFirstToken(TokenTypes.TYPE); final String name = type.getNextSibling().getText(); if (!name.matches("^(is|get)[A-Z].*")) { // Depends on JDK 1.4 return false; } // Check the return type is void if (type.getChildCount(TokenTypes.LITERAL_VOID) > 0) { return false; } // Check that is had only one parameter final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS); if ((params == null) || (params.getChildCount(TokenTypes.PARAMETER_DEF) > 0)) { return false; } // Now verify that the body consists of: // SLIST -> RETURN // RCURLY final DetailAST slist = aAST.findFirstToken(TokenTypes.SLIST); if ((slist == null) || (slist.getChildCount() != 2)) { return false; } final AST expr = slist.getFirstChild(); if ((expr.getType() != TokenTypes.LITERAL_RETURN) || (expr.getFirstChild().getType() != TokenTypes.EXPR)) { return false; } return true; } /** * Returns is a method has the "@Override" annotation. * @param aAST the AST to check with * @return whether the AST represents a method that has the annotation. */ private boolean isOverrideMethod(DetailAST aAST) { // Need it to be a method, cannot have an override on anything else. // Must also have MODIFIERS token to hold the @Override if ((TokenTypes.METHOD_DEF != aAST.getType()) || (TokenTypes.MODIFIERS != aAST.getFirstChild().getType())) { return false; } // Now loop over all nodes while they are annotations looking for // an "@Override". DetailAST node = aAST.getFirstChild().getFirstChild(); while ((null != node) && (TokenTypes.ANNOTATION == node.getType())) { if ((node.getFirstChild().getType() == TokenTypes.AT) && (node.getFirstChild().getNextSibling().getType() == TokenTypes.IDENT) && ("Override".equals( node.getFirstChild().getNextSibling().getText()))) { return true; } node = node.getNextSibling(); } return false; } /** Stores useful information about declared exception. */ private class ExceptionInfo { /** does the exception have throws tag associated with. */ private boolean mFound; /** class information associated with this exception. */ private final ClassInfo mClassInfo; /** * Creates new instance for FullIdent. * * @param aIdent the exception * @param aCurrentClass name of current class. */ ExceptionInfo(Token aIdent, String aCurrentClass) { mClassInfo = createClassInfo(aIdent, aCurrentClass); } /** Mark that the exception has associated throws tag */ final void setFound() { mFound = true; } /** @return whether the exception has throws tag associated with */ final boolean isFound() { return mFound; } /** @return exception's name */ final Token getName() { return mClassInfo.getName(); } /** @return class for this exception */ final Class getClazz() { return mClassInfo.getClazz(); } } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheck.jav100644 0 0 6115 12026051024 31205 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import java.io.File; import java.util.List; import java.util.Set; /** * Checks that all packages have a package documentation. See the documentation * for more information. * @author Oliver Burn */ public class JavadocPackageCheck extends AbstractFileSetCheck { /** Indicates if allow legacy "package.html" file to be used. */ private boolean mAllowLegacy; /** The directories checked. */ private final Set mDirectoriesChecked = Sets.newHashSet(); /** * Creates a new instance. */ public JavadocPackageCheck() { // java, not html! // The rule is: Every JAVA file should have a package.html sibling setFileExtensions(new String[]{"java"}); } @Override public void beginProcessing(String aCharset) { super.beginProcessing(aCharset); mDirectoriesChecked.clear(); } @Override protected void processFiltered(File aFile, List aLines) { // Check if already processed directory final File dir = aFile.getParentFile(); if (mDirectoriesChecked.contains(dir)) { return; } mDirectoriesChecked.add(dir); // Check for the preferred file. final File packageInfo = new File(dir, "package-info.java"); final File packageHtml = new File(dir, "package.html"); if (packageInfo.exists()) { if (packageHtml.exists()) { log(0, "javadoc.legacyPackageHtml"); } } else if (!mAllowLegacy || !packageHtml.exists()) { log(0, "javadoc.packageInfo"); } } /** * Indicates whether to allow support for the legacy package.html * file. * @param aAllowLegacy whether to allow support. */ public void setAllowLegacy(boolean aAllowLegacy) { mAllowLegacy = aAllowLegacy; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java100644 0 0 46317 12026051024 31143 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.google.common.collect.ImmutableSortedSet; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.JavadocTagInfo; import com.puppycrawl.tools.checkstyle.api.Scope; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; import java.util.List; import java.util.Set; import java.util.regex.Pattern; /** * Custom Checkstyle Check to validate Javadoc. * * @author Chris Stillwell * @author Daniel Grenner * @author Travis Schneeberger * @version 1.2 */ public class JavadocStyleCheck extends Check { /** Message property key for the Unclosed HTML message. */ private static final String UNCLOSED_HTML = "javadoc.unclosedhtml"; /** Message property key for the Extra HTML message. */ private static final String EXTRA_HTML = "javadoc.extrahtml"; /** HTML tags that do not require a close tag. */ private static final Set SINGLE_TAGS = ImmutableSortedSet.of("p", "br", "li", "dt", "dd", "td", "hr", "img", "tr", "th", "td"); /** HTML tags that are allowed in java docs. * From http://www.w3schools.com/tags/default.asp * The froms and structure tags are not allowed */ private static final Set ALLOWED_TAGS = ImmutableSortedSet.of( "a", "abbr", "acronym", "address", "area", "b", "bdo", "big", "blockquote", "br", "caption", "cite", "code", "colgroup", "del", "div", "dfn", "dl", "em", "fieldset", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "i", "img", "ins", "kbd", "li", "ol", "p", "pre", "q", "samp", "small", "span", "strong", "style", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "tt", "ul"); /** The scope to check. */ private Scope mScope = Scope.PRIVATE; /** the visibility scope where Javadoc comments shouldn't be checked **/ private Scope mExcludeScope; /** Format for matching the end of a sentence. */ private String mEndOfSentenceFormat = "([.?!][ \t\n\r\f<])|([.?!]$)"; /** Regular expression for matching the end of a sentence. */ private Pattern mEndOfSentencePattern; /** * Indicates if the first sentence should be checked for proper end of * sentence punctuation. */ private boolean mCheckFirstSentence = true; /** * Indicates if the HTML within the comment should be checked. */ private boolean mCheckHtml = true; /** * Indicates if empty javadoc statements should be checked. */ private boolean mCheckEmptyJavadoc; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.INTERFACE_DEF, TokenTypes.CLASS_DEF, TokenTypes.ANNOTATION_DEF, TokenTypes.ENUM_DEF, TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, TokenTypes.VARIABLE_DEF, TokenTypes.ENUM_CONSTANT_DEF, TokenTypes.ANNOTATION_FIELD_DEF, TokenTypes.PACKAGE_DEF, }; } @Override public void visitToken(DetailAST aAST) { if (shouldCheck(aAST)) { final FileContents contents = getFileContents(); // Need to start searching for the comment before the annotations // that may exist. Even if annotations are not defined on the // package, the ANNOTATIONS AST is defined. final TextBlock cmt = contents.getJavadocBefore(aAST.getFirstChild().getLineNo()); checkComment(aAST, cmt); } } /** * Whether we should check this node. * @param aAST a given node. * @return whether we should check a given node. */ private boolean shouldCheck(final DetailAST aAST) { if (aAST.getType() == TokenTypes.PACKAGE_DEF) { return getFileContents().inPackageInfo(); } if (ScopeUtils.inCodeBlock(aAST)) { return false; } final Scope declaredScope; if (aAST.getType() == TokenTypes.ENUM_CONSTANT_DEF) { declaredScope = Scope.PUBLIC; } else { declaredScope = ScopeUtils.getScopeFromMods( aAST.findFirstToken(TokenTypes.MODIFIERS)); } final Scope scope = ScopeUtils.inInterfaceOrAnnotationBlock(aAST) ? Scope.PUBLIC : declaredScope; final Scope surroundingScope = ScopeUtils.getSurroundingScope(aAST); return scope.isIn(mScope) && ((surroundingScope == null) || surroundingScope.isIn(mScope)) && ((mExcludeScope == null) || !scope.isIn(mExcludeScope) || ((surroundingScope != null) && !surroundingScope.isIn(mExcludeScope))); } /** * Performs the various checks agains the Javadoc comment. * * @param aAST the AST of the element being documented * @param aComment the source lines that make up the Javadoc comment. * * @see #checkFirstSentence(TextBlock) * @see #checkHtml(DetailAST, TextBlock) */ private void checkComment(final DetailAST aAST, final TextBlock aComment) { if (aComment == null) { /*checking for missing docs in JavadocStyleCheck is not consistent with the rest of CheckStyle... Even though, I didn't think it made sense to make another csheck just to ensure that the package-info.java file actually contains package Javadocs.*/ if (getFileContents().inPackageInfo()) { log(aAST.getLineNo(), "javadoc.missing"); } return; } if (mCheckFirstSentence) { checkFirstSentence(aAST, aComment); } if (mCheckHtml) { checkHtml(aAST, aComment); } if (mCheckEmptyJavadoc) { checkEmptyJavadoc(aComment); } } /** * Checks that the first sentence ends with proper punctuation. This method * uses a regular expression that checks for the presence of a period, * question mark, or exclamation mark followed either by whitespace, an * HTML element, or the end of string. This method ignores {_AT_inheritDoc} * comments for TokenTypes that are valid for {_AT_inheritDoc}. * * @param aAST the current node * @param aComment the source lines that make up the Javadoc comment. */ private void checkFirstSentence(final DetailAST aAST, TextBlock aComment) { final String commentText = getCommentText(aComment.getText()); if ((commentText.length() != 0) && !getEndOfSentencePattern().matcher(commentText).find() && !("{@inheritDoc}".equals(commentText) && JavadocTagInfo.INHERIT_DOC.isValidOn(aAST))) { log(aComment.getStartLineNo(), "javadoc.noperiod"); } } /** * Checks that the Javadoc is not empty. * * @param aComment the source lines that make up the Javadoc comment. */ private void checkEmptyJavadoc(TextBlock aComment) { final String commentText = getCommentText(aComment.getText()); if (commentText.length() == 0) { log(aComment.getStartLineNo(), "javadoc.empty"); } } /** * Returns the comment text from the Javadoc. * @param aComments the lines of Javadoc. * @return a comment text String. */ private String getCommentText(String[] aComments) { final StringBuffer buffer = new StringBuffer(); for (final String line : aComments) { final int textStart = findTextStart(line); if (textStart != -1) { if (line.charAt(textStart) == '@') { //we have found the tag section break; } buffer.append(line.substring(textStart)); trimTail(buffer); buffer.append('\n'); } } return buffer.toString().trim(); } /** * Finds the index of the first non-whitespace character ignoring the * Javadoc comment start and end strings (/** and */) as well as any * leading asterisk. * @param aLine the Javadoc comment line of text to scan. * @return the int index relative to 0 for the start of text * or -1 if not found. */ private int findTextStart(String aLine) { int textStart = -1; for (int i = 0; i < aLine.length(); i++) { if (!Character.isWhitespace(aLine.charAt(i))) { if (aLine.regionMatches(i, "/**", 0, "/**".length())) { i += 2; } else if (aLine.regionMatches(i, "*/", 0, 2)) { i++; } else if (aLine.charAt(i) != '*') { textStart = i; break; } } } return textStart; } /** * Trims any trailing whitespace or the end of Javadoc comment string. * @param aBuffer the StringBuffer to trim. */ private void trimTail(StringBuffer aBuffer) { for (int i = aBuffer.length() - 1; i >= 0; i--) { if (Character.isWhitespace(aBuffer.charAt(i))) { aBuffer.deleteCharAt(i); } else if ((i > 0) && (aBuffer.charAt(i - 1) == '*') && (aBuffer.charAt(i) == '/')) { aBuffer.deleteCharAt(i); aBuffer.deleteCharAt(i - 1); i--; while (aBuffer.charAt(i - 1) == '*') { aBuffer.deleteCharAt(i - 1); i--; } } else { break; } } } /** * Checks the comment for HTML tags that do not have a corresponding close * tag or a close tag that has no previous open tag. This code was * primarily copied from the DocCheck checkHtml method. * * @param aAST the node with the Javadoc * @param aComment the TextBlock which represents * the Javadoc comment. */ private void checkHtml(final DetailAST aAST, final TextBlock aComment) { final int lineno = aComment.getStartLineNo(); final FastStack htmlStack = FastStack.newInstance(); final String[] text = aComment.getText(); final List typeParameters = CheckUtils.getTypeParameterNames(aAST); TagParser parser = null; parser = new TagParser(text, lineno); while (parser.hasNextTag()) { final HtmlTag tag = parser.nextTag(); if (tag.isIncompleteTag()) { log(tag.getLineno(), "javadoc.incompleteTag", text[tag.getLineno() - lineno]); return; } if (tag.isClosedTag()) { //do nothing continue; } if (!tag.isCloseTag()) { //We only push html tags that are allowed if (isAllowedTag(tag)) { htmlStack.push(tag); } } else { // We have found a close tag. if (isExtraHtml(tag.getId(), htmlStack)) { // No corresponding open tag was found on the stack. log(tag.getLineno(), tag.getPosition(), EXTRA_HTML, tag); } else { // See if there are any unclosed tags that were opened // after this one. checkUnclosedTags(htmlStack, tag.getId()); } } } // Identify any tags left on the stack. String lastFound = ""; // Skip multiples, like ... for (final HtmlTag htag : htmlStack) { if (!isSingleTag(htag) && !htag.getId().equals(lastFound) && !typeParameters.contains(htag.getId())) { log(htag.getLineno(), htag.getPosition(), UNCLOSED_HTML, htag); lastFound = htag.getId(); } } } /** * Checks to see if there are any unclosed tags on the stack. The token * represents a html tag that has been closed and has a corresponding open * tag on the stack. Any tags, except single tags, that were opened * (pushed on the stack) after the token are missing a close. * * @param aHtmlStack the stack of opened HTML tags. * @param aToken the current HTML tag name that has been closed. */ private void checkUnclosedTags(FastStack aHtmlStack, String aToken) { final FastStack unclosedTags = FastStack.newInstance(); HtmlTag lastOpenTag = aHtmlStack.pop(); while (!aToken.equalsIgnoreCase(lastOpenTag.getId())) { // Find unclosed elements. Put them on a stack so the // output order won't be back-to-front. if (isSingleTag(lastOpenTag)) { lastOpenTag = aHtmlStack.pop(); } else { unclosedTags.push(lastOpenTag); lastOpenTag = aHtmlStack.pop(); } } // Output the unterminated tags, if any String lastFound = ""; // Skip multiples, like .. for (final HtmlTag htag : unclosedTags) { lastOpenTag = htag; if (lastOpenTag.getId().equals(lastFound)) { continue; } lastFound = lastOpenTag.getId(); log(lastOpenTag.getLineno(), lastOpenTag.getPosition(), UNCLOSED_HTML, lastOpenTag); } } /** * Determines if the HtmlTag is one which does not require a close tag. * * @param aTag the HtmlTag to check. * @return true if the HtmlTag is a single tag. */ private boolean isSingleTag(HtmlTag aTag) { // If its a singleton tag (

,
, etc.), ignore it // Can't simply not put them on the stack, since singletons // like

and
(unhappily) may either be terminated // or not terminated. Both options are legal. return SINGLE_TAGS.contains(aTag.getId().toLowerCase()); } /** * Determines if the HtmlTag is one which is allowed in a javadoc. * * @param aTag the HtmlTag to check. * @return true if the HtmlTag is an allowed html tag. */ private boolean isAllowedTag(HtmlTag aTag) { return ALLOWED_TAGS.contains(aTag.getId().toLowerCase()); } /** * Determines if the given token is an extra HTML tag. This indicates that * a close tag was found that does not have a corresponding open tag. * * @param aToken an HTML tag id for which a close was found. * @param aHtmlStack a Stack of previous open HTML tags. * @return false if a previous open tag was found * for the token. */ private boolean isExtraHtml(String aToken, FastStack aHtmlStack) { boolean isExtra = true; for (final HtmlTag td : aHtmlStack) { // Loop, looking for tags that are closed. // The loop is needed in case there are unclosed // tags on the stack. In that case, the stack would // not be empty, but this tag would still be extra. if (aToken.equalsIgnoreCase(td.getId())) { isExtra = false; break; } } return isExtra; } /** * Sets the scope to check. * @param aFrom string to get the scope from */ public void setScope(String aFrom) { mScope = Scope.getInstance(aFrom); } /** * Set the excludeScope. * @param aScope a String value */ public void setExcludeScope(String aScope) { mExcludeScope = Scope.getInstance(aScope); } /** * Set the format for matching the end of a sentence. * @param aFormat format for matching the end of a sentence. */ public void setEndOfSentenceFormat(String aFormat) { mEndOfSentenceFormat = aFormat; } /** * Returns a regular expression for matching the end of a sentence. * * @return a regular expression for matching the end of a sentence. */ private Pattern getEndOfSentencePattern() { if (mEndOfSentencePattern == null) { mEndOfSentencePattern = Pattern.compile(mEndOfSentenceFormat); } return mEndOfSentencePattern; } /** * Sets the flag that determines if the first sentence is checked for * proper end of sentence punctuation. * @param aFlag true if the first sentence is to be checked */ public void setCheckFirstSentence(boolean aFlag) { mCheckFirstSentence = aFlag; } /** * Sets the flag that determines if HTML checking is to be performed. * @param aFlag true if HTML checking is to be performed. */ public void setCheckHtml(boolean aFlag) { mCheckHtml = aFlag; } /** * Sets the flag that determines if empty JavaDoc checking should be done. * @param aFlag true if empty JavaDoc checking should be done. */ public void setCheckEmptyJavadoc(boolean aFlag) { mCheckEmptyJavadoc = aFlag; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTag.java100644 0 0 10764 12026051024 27615 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.puppycrawl.tools.checkstyle.api.JavadocTagInfo; /** * Represents a Javadoc tag. Provides methods to query what type of tag it is. * @author Oliver Burn */ public class JavadocTag { /** the line number of the tag **/ private final int mLineNo; /** the column number of the tag **/ private int mColumnNo; /** an optional first argument. For example the parameter name. **/ private final String mArg1; /** the JavadocTagInfo representing this tag **/ private final JavadocTagInfo mTagInfo; /** * Constructs the object. * @param aLine the line number of the tag * @param aColumn the column number of the tag * @param aTag the tag string * @param aArg1 the tag argument **/ public JavadocTag(int aLine, int aColumn, String aTag, String aArg1) { mLineNo = aLine; mColumnNo = aColumn; mArg1 = aArg1; mTagInfo = JavadocTagInfo.fromName(aTag); } /** * Constructs the object. * @param aLine the line number of the tag * @param aColumn the column number of the tag * @param aTag the tag string **/ public JavadocTag(int aLine, int aColumn, String aTag) { this(aLine, aColumn, aTag, null); } /** @return the tag string **/ public String getTagName() { return mTagInfo.getName(); } /** @return the first argument. null if not set. **/ public String getArg1() { return mArg1; } /** @return the line number **/ public int getLineNo() { return mLineNo; } /** @return the column number */ public int getColumnNo() { return mColumnNo; } @Override public String toString() { return "{Tag = '" + getTagName() + "', lineNo = " + getLineNo() + ", columnNo=" + mColumnNo + ", Arg1 = '" + getArg1() + "'}"; } /** @return whether the tag is an 'author' tag **/ public boolean isAuthorTag() { return JavadocTagInfo.AUTHOR.equals(mTagInfo); } /** @return whether the tag is an 'return' tag **/ public boolean isReturnTag() { return JavadocTagInfo.RETURN.equals(mTagInfo); } /** @return whether the tag is an 'param' tag **/ public boolean isParamTag() { return JavadocTagInfo.PARAM.equals(mTagInfo); } /** @return whether the tag is an 'throws' or 'exception' tag **/ public boolean isThrowsTag() { return (JavadocTagInfo.THROWS.equals(mTagInfo) || JavadocTagInfo.EXCEPTION.equals(mTagInfo)); } /** @return whether the tag is a 'see' or 'inheritDoc' tag **/ public boolean isSeeOrInheritDocTag() { return (JavadocTagInfo.SEE.equals(mTagInfo) || isInheritDocTag()); } /** @return whether the tag is a 'inheritDoc' tag **/ public boolean isInheritDocTag() { return JavadocTagInfo.INHERIT_DOC.equals(mTagInfo); } /** @return whether the tag can contain references to imported classes **/ public boolean canReferenceImports() { return (JavadocTagInfo.SEE.equals(mTagInfo) || JavadocTagInfo.LINK.equals(mTagInfo) || JavadocTagInfo.LINKPLAIN.equals(mTagInfo) || JavadocTagInfo.THROWS.equals(mTagInfo) || JavadocTagInfo.EXCEPTION.equals(mTagInfo)); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTags.java100644 0 0 3734 12026051023 27756 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import java.util.List; /** * Value object for combining the list of valid validTags with information * about invalid validTags encountered in a certain Javadoc comment. * @author Oliver Burn */ public final class JavadocTags { /** Valid validTags. */ private final List mValidTags; /** Invalid validTags. */ private final List mInvalidTags; /** * Creates an instance. * @param aTags the list of valid tags * @param aInvalidTags the list of invalid tags */ public JavadocTags(List aTags, List aInvalidTags) { mValidTags = aTags; mInvalidTags = aInvalidTags; } public List getValidTags() { return mValidTags; } public List getInvalidTags() { return mInvalidTags; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheck.java100644 0 0 27111 12026051023 30752 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.JavadocTagInfo; import com.puppycrawl.tools.checkstyle.api.Scope; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; /** * Checks the Javadoc of a type. * * @author Oliver Burn * @author Michael Tamm */ public class JavadocTypeCheck extends Check { /** the scope to check for */ private Scope mScope = Scope.PRIVATE; /** the visibility scope where Javadoc comments shouldn't be checked **/ private Scope mExcludeScope; /** compiled regexp to match author tag content **/ private Pattern mAuthorFormatPattern; /** compiled regexp to match version tag content **/ private Pattern mVersionFormatPattern; /** regexp to match author tag content */ private String mAuthorFormat; /** regexp to match version tag content */ private String mVersionFormat; /** * controls whether to ignore errors when a method has type parameters but * does not have matching param tags in the javadoc. Defaults to false. */ private boolean mAllowMissingParamTags; /** controls whether to flag errors for unknown tags. Defaults to false. */ private boolean mAllowUnknownTags; /** * Sets the scope to check. * @param aFrom string to set scope from */ public void setScope(String aFrom) { mScope = Scope.getInstance(aFrom); } /** * Set the excludeScope. * @param aScope a String value */ public void setExcludeScope(String aScope) { mExcludeScope = Scope.getInstance(aScope); } /** * Set the author tag pattern. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setAuthorFormat(String aFormat) throws ConversionException { try { mAuthorFormat = aFormat; mAuthorFormatPattern = Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } /** * Set the version format pattern. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setVersionFormat(String aFormat) throws ConversionException { try { mVersionFormat = aFormat; mVersionFormatPattern = Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } /** * Controls whether to allow a type which has type parameters to * omit matching param tags in the javadoc. Defaults to false. * * @param aFlag a Boolean value */ public void setAllowMissingParamTags(boolean aFlag) { mAllowMissingParamTags = aFlag; } /** * Controls whether to flag errors for unknown tags. Defaults to false. * @param aFlag a Boolean value */ public void setAllowUnknownTags(boolean aFlag) { mAllowUnknownTags = aFlag; } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.INTERFACE_DEF, TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF, TokenTypes.ANNOTATION_DEF, }; } @Override public void visitToken(DetailAST aAST) { if (shouldCheck(aAST)) { final FileContents contents = getFileContents(); final int lineNo = aAST.getLineNo(); final TextBlock cmt = contents.getJavadocBefore(lineNo); if (cmt == null) { log(lineNo, "javadoc.missing"); } else if (ScopeUtils.isOuterMostType(aAST)) { // don't check author/version for inner classes final List tags = getJavadocTags(cmt); checkTag(lineNo, tags, JavadocTagInfo.AUTHOR.getName(), mAuthorFormatPattern, mAuthorFormat); checkTag(lineNo, tags, JavadocTagInfo.VERSION.getName(), mVersionFormatPattern, mVersionFormat); final List typeParamNames = CheckUtils.getTypeParameterNames(aAST); if (!mAllowMissingParamTags) { //Check type parameters that should exist, do for (final String string : typeParamNames) { checkTypeParamTag( lineNo, tags, string); } } checkUnusedTypeParamTags(tags, typeParamNames); } } } /** * Whether we should check this node. * @param aAST a given node. * @return whether we should check a given node. */ private boolean shouldCheck(final DetailAST aAST) { final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS); final Scope declaredScope = ScopeUtils.getScopeFromMods(mods); final Scope scope = ScopeUtils.inInterfaceOrAnnotationBlock(aAST) ? Scope.PUBLIC : declaredScope; final Scope surroundingScope = ScopeUtils.getSurroundingScope(aAST); return scope.isIn(mScope) && ((surroundingScope == null) || surroundingScope.isIn(mScope)) && ((mExcludeScope == null) || !scope.isIn(mExcludeScope) || ((surroundingScope != null) && !surroundingScope.isIn(mExcludeScope))); } /** * Gets all standalone tags from a given javadoc. * @param aCmt the Javadoc comment to process. * @return all standalone tags from the given javadoc. */ private List getJavadocTags(TextBlock aCmt) { final JavadocTags tags = JavadocUtils.getJavadocTags(aCmt, JavadocUtils.JavadocTagType.BLOCK); if (!mAllowUnknownTags) { for (final InvalidJavadocTag tag : tags.getInvalidTags()) { log(tag.getLine(), tag.getCol(), "javadoc.unknownTag", tag.getName()); } } return tags.getValidTags(); } /** * Verifies that a type definition has a required tag. * @param aLineNo the line number for the type definition. * @param aTags tags from the Javadoc comment for the type definition. * @param aTag the required tag name. * @param aFormatPattern regexp for the tag value. * @param aFormat pattern for the tag value. */ private void checkTag(int aLineNo, List aTags, String aTag, Pattern aFormatPattern, String aFormat) { if (aFormatPattern == null) { return; } int tagCount = 0; for (int i = aTags.size() - 1; i >= 0; i--) { final JavadocTag tag = aTags.get(i); if (tag.getTagName().equals(aTag)) { tagCount++; if (!aFormatPattern.matcher(tag.getArg1()).find()) { log(aLineNo, "type.tagFormat", "@" + aTag, aFormat); } } } if (tagCount == 0) { log(aLineNo, "type.missingTag", "@" + aTag); } } /** * Verifies that a type definition has the specified param tag for * the specified type parameter name. * @param aLineNo the line number for the type definition. * @param aTags tags from the Javadoc comment for the type definition. * @param aTypeParamName the name of the type parameter */ private void checkTypeParamTag(final int aLineNo, final List aTags, final String aTypeParamName) { boolean found = false; for (int i = aTags.size() - 1; i >= 0; i--) { final JavadocTag tag = aTags.get(i); if (tag.isParamTag() && (tag.getArg1() != null) && (tag.getArg1().indexOf("<" + aTypeParamName + ">") == 0)) { found = true; } } if (!found) { log(aLineNo, "type.missingTag", JavadocTagInfo.PARAM.getText() + " <" + aTypeParamName + ">"); } } /** * Checks for unused param tags for type parameters. * @param aTags tags from the Javadoc comment for the type definition. * @param aTypeParamNames names of type parameters */ private void checkUnusedTypeParamTags( final List aTags, final List aTypeParamNames) { final Pattern pattern = Utils.getPattern("\\s*<([^>]+)>.*"); for (int i = aTags.size() - 1; i >= 0; i--) { final JavadocTag tag = aTags.get(i); if (tag.isParamTag()) { if (tag.getArg1() != null) { final Matcher matcher = pattern.matcher(tag.getArg1()); String typeParamName = null; if (matcher.matches()) { typeParamName = matcher.group(1).trim(); if (!aTypeParamNames.contains(typeParamName)) { log(tag.getLineNo(), tag.getColumnNo(), "javadoc.unusedTag", JavadocTagInfo.PARAM.getText(), "<" + typeParamName + ">"); } } else { log(tag.getLineNo(), tag.getColumnNo(), "javadoc.unusedTagGeneral"); } } else { log(tag.getLineNo(), tag.getColumnNo(), "javadoc.unusedTagGeneral"); } } } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocUtils.java100644 0 0 13725 12026051023 30201 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.JavadocTagInfo; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Contains utility methods for working with Javadoc. * @author Lyle Hanson */ public final class JavadocUtils { ///CLOVER:OFF /** prevent instantiation */ private JavadocUtils() { } ///CLOVER:ON /** * Gets validTags from a given piece of Javadoc. * @param aCmt the Javadoc comment to process. * @param aTagType the type of validTags we're interested in * @return all standalone validTags from the given javadoc. */ public static JavadocTags getJavadocTags(TextBlock aCmt, JavadocTagType aTagType) { final String[] text = aCmt.getText(); final List tags = Lists.newArrayList(); final List invalidTags = Lists.newArrayList(); Pattern blockTagPattern = Utils.getPattern("/\\*{2,}\\s*@(\\p{Alpha}+)\\s"); for (int i = 0; i < text.length; i++) { final String s = text[i]; final Matcher blockTagMatcher = blockTagPattern.matcher(s); if ((aTagType.equals(JavadocTagType.ALL) || aTagType .equals(JavadocTagType.BLOCK)) && blockTagMatcher.find()) { final String tagName = blockTagMatcher.group(1); String content = s.substring(blockTagMatcher.end(1)); if (content.endsWith("*/")) { content = content.substring(0, content.length() - 2); } final int line = aCmt.getStartLineNo() + i; int col = blockTagMatcher.start(1) - 1; if (i == 0) { col += aCmt.getStartColNo(); } if (JavadocTagInfo.isValidName(tagName)) { tags.add( new JavadocTag(line, col, tagName, content.trim())); } else { invalidTags.add(new InvalidJavadocTag(line, col, tagName)); } } // No block tag, so look for inline validTags else if (aTagType.equals(JavadocTagType.ALL) || aTagType.equals(JavadocTagType.INLINE)) { // Match JavaDoc text after comment characters final Pattern commentPattern = Utils.getPattern("^\\s*(?:/\\*{2,}|\\*+)\\s*(.*)"); final Matcher commentMatcher = commentPattern.matcher(s); final String commentContents; final int commentOffset; // offset including comment characters if (!commentMatcher.find()) { commentContents = s; // No leading asterisks, still valid commentOffset = 0; } else { commentContents = commentMatcher.group(1); commentOffset = commentMatcher.start(1) - 1; } final Pattern tagPattern = Utils.getPattern(".*?\\{@(\\p{Alpha}+)\\s+(.*?)\\}"); final Matcher tagMatcher = tagPattern.matcher(commentContents); while (tagMatcher.find()) { if (tagMatcher.groupCount() == 2) { final String tagName = tagMatcher.group(1); final String tagValue = tagMatcher.group(2).trim(); final int line = aCmt.getStartLineNo() + i; int col = commentOffset + (tagMatcher.start(1) - 1); if (i == 0) { col += aCmt.getStartColNo(); } if (JavadocTagInfo.isValidName(tagName)) { tags.add(new JavadocTag(line, col, tagName, tagValue)); } else { invalidTags.add(new InvalidJavadocTag(line, col, tagName)); } } // else Error: Unexpected match count for inline JavaDoc // tag! } } blockTagPattern = Utils.getPattern("^\\s*\\**\\s*@(\\p{Alpha}+)\\s"); } return new JavadocTags(tags, invalidTags); } /** * The type of Javadoc tag we want returned. */ public enum JavadocTagType { /** block type. */ BLOCK, /** inline type. */ INLINE, /** all validTags. */ ALL; } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocVariableCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocVariableCheck.ja100644 0 0 7433 12026051023 31214 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.Scope; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Checks that a variable has Javadoc comment. * * @author Oliver Burn * @version 1.0 */ public class JavadocVariableCheck extends Check { /** the scope to check */ private Scope mScope = Scope.PRIVATE; /** the visibility scope where Javadoc comments shouldn't be checked **/ private Scope mExcludeScope; /** * Sets the scope to check. * @param aFrom string to get the scope from */ public void setScope(String aFrom) { mScope = Scope.getInstance(aFrom); } /** * Set the excludeScope. * @param aScope a String value */ public void setExcludeScope(String aScope) { mExcludeScope = Scope.getInstance(aScope); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.VARIABLE_DEF, TokenTypes.ENUM_CONSTANT_DEF, }; } @Override public void visitToken(DetailAST aAST) { if (shouldCheck(aAST)) { final FileContents contents = getFileContents(); final TextBlock cmt = contents.getJavadocBefore(aAST.getLineNo()); if (cmt == null) { log(aAST, "javadoc.missing"); } } } /** * Whether we should check this node. * @param aAST a given node. * @return whether we should check a given node. */ private boolean shouldCheck(final DetailAST aAST) { if (ScopeUtils.inCodeBlock(aAST)) { return false; } final Scope scope; if (aAST.getType() == TokenTypes.ENUM_CONSTANT_DEF) { scope = Scope.PUBLIC; } else { final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS); final Scope declaredScope = ScopeUtils.getScopeFromMods(mods); scope = ScopeUtils.inInterfaceOrAnnotationBlock(aAST) ? Scope.PUBLIC : declaredScope; } final Scope surroundingScope = ScopeUtils.getSurroundingScope(aAST); return scope.isIn(mScope) && surroundingScope.isIn(mScope) && ((mExcludeScope == null) || !scope.isIn(mExcludeScope) || !surroundingScope.isIn(mExcludeScope)); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/messages.properties100644 0 0 2043 11451071613 30652 0ustar 0 0 javadoc.classInfo=Unable to get class information for {0} tag ''{1}''. javadoc.expectedTag=Expected {0} tag for ''{1}''. javadoc.extrahtml=Extra HTML tag found: {0} javadoc.incompleteTag=Incomplete HTML tag found: {0} javadoc.missing=Missing a Javadoc comment. javadoc.noperiod=First sentence should end with a period. javadoc.packageHtml=Missing package documentation file. javadoc.duplicateTag=Duplicate {0} tag. javadoc.return.expected=Expected an @return tag. javadoc.unclosedhtml=Unclosed HTML tag found: {0} javadoc.unusedTag=Unused {0} tag for ''{1}''. javadoc.unusedTagGeneral=Unused Javadoc tag. javadoc.empty=Javadoc has empty description section. javadoc.writeTag={0}={1} javadoc.invalidInheritDoc=Invalid use of the '{'@inheritDoc'}' tag. javadoc.legacyPackageHtml=Legacy package.html file should be removed. javadoc.packageInfo=Missing package-info.java file. javadoc.unknownTag=Unknown tag ''{0}''. type.missingTag=Type Javadoc comment is missing an {0} tag. type.tagFormat=Type Javadoc tag {0} must match pattern ''{1}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/messages_de.properties100644 0 0 1531 11451071613 31323 0ustar 0 0 javadoc.classInfo=Kann zum Tag ''{1}'' keine Klasseninformation zu {0} laden. javadoc.expectedTag=Erwartete Tag {0} für ''{1}''. javadoc.extrahtml=Unerwarteter schließender HTML-Tag: {0} javadoc.incompleteTag=Unvollständiger HTML-Tag: {0} javadoc.missing=Javadoc-Kommentar fehlt. javadoc.noperiod=Der erste Satz sollte mit einem Punkt abschließen. javadoc.packageHtml=Fehlende Package-Dokumentation. javadoc.duplicateTag=Doppelter {0}-Tag. javadoc.return.expected=Fehlender @return-Tag. javadoc.unclosedhtml=HTML-Tag {0} wird nicht geschlossen. javadoc.unusedTag=Nicht benutztes {0}-Tag für ''{1}''. javadoc.unusedTagGeneral=Nicht benutzter Javadoc-Tag. javadoc.empty=Javadoc enthält keine Beschreibung. type.missingTag=In der Klassen-Dokumentation fehlt ein {0}-Tag. type.tagFormat=Der Javadoc-Tag {0} entspricht nicht dem Muster ''{1}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/messages_es.properties100644 0 0 1674 11451071613 31352 0ustar 0 0 javadoc.classInfo=No se puede obtener la información de clase para {0} etiqueta ''{1}''. javadoc.expectedTag=Se esperaba la etiqueta {0} para ''{1}''. javadoc.extrahtml=Se encontró una etiqueta HTML extra: {0} javadoc.incompleteTag=Se encontró una etiqueta HTML incompleta: {0} javadoc.missing=Falta el comentario Javadoc. javadoc.noperiod=La primera frase debería finalizar con un punto. javadoc.packageHtml=Falta el fichero de documentación del paquete. javadoc.duplicateTag=Etiqueta {0} duplicada. javadoc.return.expected=Se esperaba la etiqueta @return. javadoc.unclosedhtml=Se encontró una etiqueta HTML sin cerrar: {0} javadoc.unusedTag=Etiqueta {0} no usada en ''{1}''. javadoc.unusedTagGeneral=Etiqueta Javadoc no usada. javadoc.empty=Hay una sección de descripción vacía en el Javadoc. type.missingTag=Al comentario Javadoc le falta una etiqueta {0}. type.tagFormat=El comentario Javadoc {0} debe coincidir con el patrón ''{1}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/messages_fi.properties100644 0 0 1051 11451071613 31326 0ustar 0 0 javadoc.missing=Javadoc-kommentti puuttuu. javadoc.unusedTagGeneral=Tuntematon Javadoc-tagi. javadoc.unusedTag=Tuntematon tagi ''{1}'':lle: {0}. javadoc.expectedTag=Javadoc-tagi puuttuu: {0} tagi ''{1}''. javadoc.duplicateTag=Duplikaatti {0}-tagi. javadoc.return.expected=@return-tagi puuttuu. javadoc.classInfo=Luokkatiedot ei saatavilla: {0} tagi ''{1}''. javadoc.packageHtml=Pakettidokumentaatiotiedosto puuttuu. type.missingTag=Javadoc-kommentista puuttuu {0}-tagi. type.tagFormat=Javadoc-tagin {0} pit¤¤ olla mallin ''{1}'' mukainen. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/messages_fr.properties100644 0 0 1705 11453016761 31352 0ustar 0 0 javadoc.classInfo=Impossible d''obtenir les informations relatives à la classe {1} pour la balise ''{0}''. javadoc.expectedTag=Balise javadoc {0} manquante pour ''{1}''. javadoc.extrahtml=Balise HTML en trop : {0} javadoc.incompleteTag=Balise HTML incomplète : {0} javadoc.missing=Commentaire javadoc manquant. javadoc.noperiod=La première ligne doit se terminer avec un point. javadoc.packageHtml=Fichier de documentation de package manquant. javadoc.duplicateTag=Balise javadoc {0} présente plus d''une fois. javadoc.return.expected=Balise javadoc @return manquante. javadoc.unclosedhtml=Balise HTML trouvée dans la javadoc : {0} javadoc.unusedTag=Balise javadoc {0} inutilisé pour ''{1}''. javadoc.unusedTagGeneral=Balise javadoc inutilisé. javadoc.empty=Le commentaire javadoc est vide. type.missingTag=Dans le commentaire javadoc de la classe, il manque une balise {0}. type.tagFormat=La balise javadoc {0} doit correspondre au motif ''{1}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/messages_ja.properties100644 0 0 3333 11451071613 31327 0ustar 0 0 javadoc.classInfo={0} \u30bf\u30b0\u306e ''{1}'' \u306e\u30af\u30e9\u30b9\u60c5\u5831\u304c\u53d6\u5f97\u3067\u304d\u307e\u305b\u3093\u3002 javadoc.expectedTag=''{1}'' \u306b\u306f {0} \u30bf\u30b0\u304c\u5fc5\u8981\u3067\u3059\u3002 javadoc.extrahtml=\u4e0d\u8981\u306a\u7d42\u4e86\u30bf\u30b0\u304c\u898b\u3064\u304b\u308a\u307e\u3057\u305f: {0} javadoc.incompleteTag=\u4e0d\u5b8c\u5168\u306aHTML\u30bf\u30b0\u304c\u898b\u3064\u304b\u308a\u307e\u3057\u305f: {0} javadoc.missing=Javadoc \u30b3\u30e1\u30f3\u30c8\u304c\u3042\u308a\u307e\u305b\u3093\u3002 javadoc.noperiod=\u6700\u521d\u306e\u4e00\u6587\u306f\u30d4\u30ea\u30aa\u30c9\u3067\u7d42\u308f\u3089\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002 javadoc.packageHtml=\u30d1\u30c3\u30b1\u30fc\u30b8\u30c9\u30ad\u30e5\u30e1\u30f3\u30c6\u30fc\u30b7\u30e7\u30f3\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093\u3002 javadoc.duplicateTag={0} \u30bf\u30b0\u304c\u91cd\u8907\u3057\u3066\u3044\u307e\u3059\u3002 javadoc.return.expected=@return \u30bf\u30b0\u304c\u5fc5\u8981\u3067\u3059\u3002 javadoc.unclosedhtml=\u9589\u3058\u3066\u3044\u306a\u3044 HTML \u30bf\u30b0\u304c\u898b\u3064\u304b\u308a\u307e\u3057\u305f: {0} javadoc.unusedTag=''{1}'' \u306b\u5bfe\u3059\u308b\u4f7f\u7528\u3055\u308c\u306a\u3044 {0} \u30bf\u30b0\u3067\u3059\u3002 javadoc.unusedTagGeneral=\u4f7f\u7528\u3055\u308c\u306a\u3044 Javadoc \u30bf\u30b0\u3067\u3059\u3002 type.missingTag=\u30af\u30e9\u30b9\u306e Javadoc \u30b3\u30e1\u30f3\u30c8\u306b {0} \u30bf\u30b0\u304c\u3042\u308a\u307e\u305b\u3093\u3002 type.tagFormat=\u30af\u30e9\u30b9\u306e Javadoc \u30bf\u30b0 {0} \u306f\u30d1\u30bf\u30fc\u30f3 ''{1}'' \u306b\u5408\u81f4\u3057\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/messages_pt.properties100644 0 0 1521 11451071613 31355 0ustar 0 0 javadoc.classInfo=No foi possível obter informaçġes de classe para {0} marca ''{1}''. javadoc.expectedTag=Esperada a marca {0} para ''{1}''. javadoc.extrahtml=Marca HTML extra encontrada: {0} javadoc.incompleteTag=Marca HTML incompleta encontrada: {0} javadoc.missing=Falta o comentário Javadoc. javadoc.noperiod=A primeira frase deve acabar num ponto final. javadoc.packageHtml=Falta o ficheiro de documentaço do pacote. javadoc.duplicateTag=Marca {0} duplicada. javadoc.return.expected=Esperava uma marca @return. javadoc.unclosedhtml=Marca HTML no fechada entrada: {0} javadoc.unusedTag=Marca {0} no utilizada por ''{1}''. javadoc.unusedTagGeneral=Marca Javadoc no utilizada. type.missingTag=Comentário Javadoc de tipo no está presente na marca {0}. type.tagFormat=Marca Javadoc {0} do tipo deve condizer com o padro ''{1}'' checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/messages_tr.properties100644 0 0 3140 11744664014 31366 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) javadoc.classInfo = {0} etiketi ''{1}'' i\u00E7in s\u0131n\u0131f bilgisi al\u0131nam\u0131yor. javadoc.duplicateTag = {0} etiketi tekrarlanm\u0131\u015F. javadoc.empty = Javadoc tan\u0131m alan\u0131 bo\u015F b\u0131rak\u0131lm\u0131\u015F. javadoc.expectedTag = ''{1}'' i\u00E7in {0} etiketi gerekli. javadoc.extrahtml = Fazladan HTML etiketi bulundu: {0} javadoc.incompleteTag = Tamamlanmam\u0131\u015F HTML etiketi bulundu: {0} javadoc.invalidInheritDoc = '{'@inheritDoc'}' etiketi kullan\u0131m\u0131 ge\u00E7ersiz. javadoc.legacyPackageHtml = Eskide kalan package.html dosyalar\u0131 kald\u0131r\u0131lmal\u0131. javadoc.missing = Javadoc a\u00E7\u0131klamas\u0131 eksik. javadoc.noperiod = \u0130lk c\u00FCmle nokta ile bitmeli. javadoc.packageHtml = Paket dok\u00FCmantasyon dosyas\u0131 eksik. javadoc.packageInfo = package-info.java dosyas\u0131 eksik. javadoc.return.expected = @return etiketi eksik. javadoc.unclosedhtml = Kapat\u0131lmam\u0131\u015F bir HTML etiketi bulundu: {0} javadoc.unknownTag = Bilinmeyen etiket: ''{0}''. javadoc.unusedTag = ''{1}'' i\u00E7in kullan\u0131lmayan {0} etiketi mevcut. javadoc.unusedTagGeneral = Kullan\u0131lmayan Javadoc etiketi. javadoc.writeTag = {0}={1} type.missingTag = T\u00FCr i\u00E7in yaz\u0131lan Javadoc a\u00E7\u0131klamas\u0131nda {0} etiketi eksik. type.tagFormat = T\u00FCr i\u00E7in yaz\u0131lan {0} Javadoc etiketi \u015Fu kal\u0131pta olmal\u0131: ''{1}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/package-info.java100644 0 0 2231 12026051022 30102 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the Javadoc checks that are bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks.javadoc; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java100644 0 0 25402 12026051022 27473 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.google.common.collect.Lists; import java.util.List; /** *

* Helper class used to parse HTML tags or generic type identifiers * from a single line of text. Just the beginning of the HTML tag * is located. No attempt is made to parse out the complete tag, * particularly since some of the tag parameters could be located * on the following line of text. The hasNextTag and * nextTag methods are used to iterate through the HTML * tags or generic type identifiers that were found on the line of text. *

* *

* This class isn't really specific to HTML tags. Currently the only HTML * tag that this class looks specifically for is the HTML comment tag. * This class helps figure out if a tag exists and if it is well-formed. * It does not know whether it is valid HTML. This class is also used for * generics types which looks like opening HTML tags ex: , , , * , etc. According to this class they are valid tags. *

* @author Chris Stillwell */ class TagParser { /** List of HtmlTags found on the input line of text. */ private final List mTags = Lists.newLinkedList(); /** * Constructs a TagParser and finds the first tag if any. * @param aText the line of text to parse. * @param aLineNo the source line number. */ public TagParser(String[] aText, int aLineNo) { parseTags(aText, aLineNo); } /** * Returns the next available HtmlTag. * @return a HtmlTag or null if none available. * @throws IndexOutOfBoundsException if there are no HtmlTags * left to return. */ public HtmlTag nextTag() { return mTags.remove(0); } /** * Indicates if there are any more HtmlTag to retrieve. * @return true if there are more tags. */ public boolean hasNextTag() { return (mTags.size() > 0); } /** * Performs lazy initialization on the internal tags List * and adds the tag. * @param aTag the HtmlTag to add. */ private void add(HtmlTag aTag) { mTags.add(aTag); } /** * Parses the text line for any HTML tags and adds them to the internal * List of tags. * @param aText the source line to parse. * @param aLineNo the source line number. */ private void parseTags(String[] aText, int aLineNo) { final int nLines = aText.length; Point position = new Point(0, 0); position = findChar(aText, '<', position); while (position.getLineNo() < nLines) { // if this is html comment then skip it if (isCommentTag(aText, position)) { position = skipHtmlComment(aText, position); } else if (!isTag(aText, position)) { position = getNextCharPos(aText, position); } else { // find end of tag final Point endTag = findChar(aText, '>', position); final boolean incompleteTag = (endTag.getLineNo() >= nLines); // get tag id (one word) final String tagId = (incompleteTag ? "" : getTagId(aText, position)); // is this closed tag final boolean closedTag = ((endTag.getLineNo() < nLines) && (endTag.getColumnNo() > 0) && (aText[endTag.getLineNo()] .charAt(endTag.getColumnNo() - 1) == '/')); // add new tag add(new HtmlTag(tagId, position.getLineNo() + aLineNo, position.getColumnNo(), closedTag, incompleteTag, aText[position.getLineNo()])); position = endTag; } position = findChar(aText, '<', position); } } /** * Checks if the given position is start one for HTML tag. * @param aText text of javadoc comments. * @param aPos position to check. * @return true some HTML tag starts from given position. */ private boolean isTag(String[] aText, Point aPos) { final int column = aPos.getColumnNo() + 1; final String text = aText[aPos.getLineNo()]; //Character.isJavaIdentifier... may not be a valid HTML //identifier but is valid for generics return ((column < text.length()) && (Character.isJavaIdentifierStart(text.charAt(column)) || Character.isJavaIdentifierPart(text.charAt(column)) || text.charAt(column) == '/') || (column >= text.length())); } /** * Parse tag id. * @param aText text of javadoc comments. * @param aTagStart start position of the tag * @return id for given tag */ private String getTagId(String[] aText, Point aTagStart) { int column = aTagStart.getColumnNo() + 1; String text = aText[aTagStart.getLineNo()]; if (column >= text.length()) { return ""; } if (text.charAt(column) == '/') { column++; } text = text.substring(column).trim(); column = 0; //Character.isJavaIdentifier... may not be a valid HTML //identifier but is valid for generics while (column < text.length() && (Character.isJavaIdentifierStart(text.charAt(column)) || Character.isJavaIdentifierPart(text.charAt(column)))) { column++; } return text.substring(0, column); } /** * If this is a HTML-comments. * @param aText text of javadoc comments * @param aPos position to check * @return true if HTML-comments * starts form given position. */ private boolean isCommentTag(String[] aText, Point aPos) { return aText[aPos.getLineNo()].startsWith("")) { to = findChar(aText, '>', getNextCharPos(aText, to)); } return to; } /** * Finds next occurrence of given character. * @param aText text to search * @param aChar character to search * @param aFrom position to start search * @return position of next occurrence of given character */ private Point findChar(String[] aText, char aChar, Point aFrom) { Point curr = new Point(aFrom.getLineNo(), aFrom.getColumnNo()); while ((curr.getLineNo() < aText.length) && (aText[curr.getLineNo()].charAt(curr.getColumnNo()) != aChar)) { curr = getNextCharPos(aText, curr); } return curr; } /** * Returns position of next comment character, skips * whitespaces and asterisks. * @param aText to search. * @param aFrom location to search from * @return location of the next character. */ private Point getNextCharPos(String[] aText, Point aFrom) { int line = aFrom.getLineNo(); int column = aFrom.getColumnNo() + 1; while ((line < aText.length) && (column >= aText[line].length())) { // go to the next line line++; column = 0; if (line < aText.length) { //skip beginning spaces and stars final String currentLine = aText[line]; while ((column < currentLine.length()) && (Character.isWhitespace(currentLine.charAt(column)) || (currentLine.charAt(column) == '*'))) { column++; if ((column < currentLine.length()) && (currentLine.charAt(column - 1) == '*') && (currentLine.charAt(column) == '/')) { // this is end of comment column = currentLine.length(); } } } } return new Point(line, column); } /** * Represents current position in the text. * @author o_sukholsky */ private static final class Point { /** line number. */ private final int mLine; /** column number.*/ private final int mColumn; /** * Creates new Point instance. * @param aLineNo line number * @param aColumnNo column number */ public Point(int aLineNo, int aColumnNo) { mLine = aLineNo; mColumn = aColumnNo; } /** * Getter for line number. * @return line number of the position. */ public int getLineNo() { return mLine; } /** * Getter for column number. * @return column number of the position. */ public int getColumnNo() { return mColumn; } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/WriteTagCheck.java100644 0 0 17633 12026051022 30276 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; /** *

* Outputs a JavaDoc tag as information. Can be used e.g. with the stylesheets * that sort the report by author name. * To define the format for a tag, set property tagFormat to a * regular expression. * This check uses two different severity levels. The normal one is used for * reporting when the tag is missing. The additional one (tagSeverity) is used * for the level of reporting when the tag exists. The default value for * tagSeverity is info. *

*

An example of how to configure the check for printing author name is: *

*
 * <module name="WriteTag">
 *    <property name="tag" value="@author"/>
 *    <property name="tagFormat" value="\S"/>
 * </module>
 * 
*

An example of how to configure the check to print warnings if an * "@incomplete" tag is found, and not print anything if it is not found: *

*
 * <module name="WriteTag">
 *    <property name="tag" value="@incomplete"/>
 *    <property name="tagFormat" value="\S"/>
 *    <property name="severity" value="ignore"/>
 *    <property name="tagSeverity" value="warning"/>
 * </module>
 * 
* * @author Daniel Grenner * @version 1.0 */ public class WriteTagCheck extends Check { /** compiled regexp to match tag **/ private Pattern mTagRE; /** compiled regexp to match tag content **/ private Pattern mTagFormatRE; /** regexp to match tag */ private String mTag; /** regexp to match tag content */ private String mTagFormat; /** the severity level of found tag reports */ private SeverityLevel mTagSeverityLevel = SeverityLevel.INFO; /** * Sets the tag to check. * @param aTag tag to check * @throws ConversionException If the tag is not a valid regular exception. */ public void setTag(String aTag) throws ConversionException { try { mTag = aTag; mTagRE = Utils.getPattern(aTag + "\\s*(.*$)"); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aTag, e); } } /** * Set the tag format. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setTagFormat(String aFormat) throws ConversionException { try { mTagFormat = aFormat; mTagFormatRE = Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } /** * Sets the tag severity level. The string should be one of the names * defined in the SeverityLevel class. * * @param aSeverity The new severity level * @see SeverityLevel */ public final void setTagSeverity(String aSeverity) { mTagSeverityLevel = SeverityLevel.getInstance(aSeverity); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.INTERFACE_DEF, TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF, TokenTypes.ANNOTATION_DEF, }; } @Override public int[] getAcceptableTokens() { return new int[] {TokenTypes.INTERFACE_DEF, TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF, TokenTypes.ANNOTATION_DEF, TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, TokenTypes.ENUM_CONSTANT_DEF, TokenTypes.ANNOTATION_FIELD_DEF, }; } @Override public void visitToken(DetailAST aAST) { final FileContents contents = getFileContents(); final int lineNo = aAST.getLineNo(); final TextBlock cmt = contents.getJavadocBefore(lineNo); if (cmt == null) { log(lineNo, "type.missingTag", mTag); } else { checkTag(lineNo, cmt.getText(), mTag, mTagRE, mTagFormatRE, mTagFormat); } } /** * Verifies that a type definition has a required tag. * @param aLineNo the line number for the type definition. * @param aComment the Javadoc comment for the type definition. * @param aTag the required tag name. * @param aTagRE regexp for the full tag. * @param aFormatRE regexp for the tag value. * @param aFormat pattern for the tag value. */ private void checkTag( int aLineNo, String[] aComment, String aTag, Pattern aTagRE, Pattern aFormatRE, String aFormat) { if (aTagRE == null) { return; } int tagCount = 0; for (int i = 0; i < aComment.length; i++) { final String s = aComment[i]; final Matcher matcher = aTagRE.matcher(s); if (matcher.find()) { tagCount += 1; final int contentStart = matcher.start(1); final String content = s.substring(contentStart); if ((aFormatRE != null) && !aFormatRE.matcher(content).find()) { log(aLineNo + i - aComment.length, "type.tagFormat", aTag, aFormat); } else { logTag(aLineNo + i - aComment.length, aTag, content); } } } if (tagCount == 0) { log(aLineNo, "type.missingTag", aTag); } } /** * Log a message. * * @param aLine the line number where the error was found * @param aTag the javdoc tag to be logged * @param aTagValue the contents of the tag * * @see java.text.MessageFormat */ protected final void logTag(int aLine, String aTag, String aTagValue) { final String originalSeverity = getSeverity(); setSeverity(mTagSeverityLevel.getName()); log(aLine, "javadoc.writeTag", aTag, aTagValue); setSeverity(originalSeverity); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/LineSeparatorOption.java100644 0 0 4433 12026051062 30122 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; /** * Represents the options for line separator settings. * * @author lkuehne * @see NewlineAtEndOfFileCheck */ public enum LineSeparatorOption { /** Windows-style line separators. **/ CRLF("\r\n"), /** Mac-style line separators. **/ CR("\r"), /** Unix-style line separators. **/ LF("\n"), /** System default line separators. **/ SYSTEM(System.getProperty("line.separator")); /** the line separator representation */ private final String mLineSeparator; /** * Creates a new LineSeparatorOption instance. * @param aSep the line separator, e.g. "\r\n" */ private LineSeparatorOption(String aSep) { mLineSeparator = aSep; } /** * @param aBytes a bytes array to check * @return if aBytes is equal to the byte representation * of this line separator */ public boolean matches(byte[] aBytes) { final String s = new String(aBytes); return s.equals(mLineSeparator); } /** * @return the length of the file separator, * e.g. 1 for CR, 2 for CRLF, ... */ public int length() { return mLineSeparator.length(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/messages.properties100644 0 0 2127 11451071613 27246 0ustar 0 0 noNewlineAtEOF=File does not end with a newline. unable.open=Unable to open ''{0}''. todo.match=Comment matches to-do format ''{0}''. upperEll=Should use uppercase ''L''. illegal.regexp=Line matches the illegal pattern ''{0}''. required.regexp=Required pattern ''{0}'' missing in file. duplicate.regexp=Found duplicate pattern ''{0}''. translation.missingKey=Key ''{0}'' missing. missing.switch.default=switch without \"default\" clause. uncommented.main=Uncommented main method found. descendant.token.min=Count of {0} for ''{2}'' descendant ''{3}'' is less than minimum count {1}. descendant.token.max=Count of {0} for ''{2}'' descendant ''{3}'' exceeds maximum count {1}. descendant.token.sum.min=Total count of {0} is less than minimum count {1} under ''{2}''. descendant.token.sum.max=Total count of {0} exceeds maximum count {1} under ''{2}''. final.parameter=Parameter {0} should be final. trailing.comments=Don''t use trailing comments. array.type.style=Array brackets at illegal position. type.file.mismatch=The name of the outer type and the file do not match. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/messages_de.properties100644 0 0 1504 11451071613 27714 0ustar 0 0 noNewlineAtEOF=Datei endet nicht mit einem Zeilenumbruch. todo.match=Kommentar entspricht to-do-Format ''{0}''. upperEll=Zur besseren Lesbarkeit sollte ein großes ''L'' verwendet werden. illegal.regexp=Die Zeile entspricht dem verbotenen Muster ''{0}''. required.regexp=Keine Zeile entspricht dem Muster ''{0}''. translation.missingKey=Übersetzung für Schlüssel ''{0}'' fehlt. missing.switch.default=switch ohne \"default\". uncommented.main=Unkommentierte main Methode. descendant.token.min=Anzahl von {2}-Unterknoten ''{3}'' ist {0}, muss mindestens {1} sein. descendant.token.max=Anzahl von {2}-Unterknoten ''{3}'' ist {0}, darf maximal {1} sein. final.parameter=Der Parameter {0} sollte als ''final'' deklariert sein. trailing.comments=Kommentare und Code sollten nicht in einer Zeile gemischt werden. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/messages_es.properties100644 0 0 1426 11451071613 27736 0ustar 0 0 noNewlineAtEOF=El fichero no termina con un retorno de carro. todo.match=El comentario coincide con el formato to-do ''{0}''. upperEll=Debería usar ''L'' mayúscula. illegal.regexp=La línea coincide con el patrón ilegal ''{0}''. required.regexp=El patron requerido ''{0}'' falta en el fichero. translation.missingKey=La clave ''{0}'' falta. missing.switch.default=switch sin etiqueta \"default\". uncommented.main=Se encotró un método main sin comentar. descendant.token.min=El recuento {0} para ''{2}'' descendientes ''{3}'' es menor que el mínimo {1}. descendant.token.max=El recuento {0} para ''{2}'' descendientes ''{3}'' excede el máximo {1}. final.parameter=El parámetro {0} debería ser final. trailing.comments=No usar comentarios de final de línea. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/messages_fi.properties100644 0 0 436 11451071613 27705 0ustar 0 0 noNewlineAtEOF=Tiedosto ei p¤¤ty rivinvaihtoon. todo.match=Kommentti on to-do formaatin ''{0}'' mukainen. upperEll=Pit¤¤ olla iso ''L''. illegal.regexp=Rivi on s¤¤ntĥjenvaistaisen mallin mukainen: ''{0}''. translation.missingKey=K¤¤nnĥsavain ''{0}'' puuttuu. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/messages_fr.properties100644 0 0 1766 11451071613 27745 0ustar 0 0 noNewlineAtEOF=Il manque un caractère NewLine à la fin du fichier todo.match=Le commentaire correspond au format TODO ''{0}''. upperEll=Utilisez un ''L'' majuscule pour une meilleure lisibilité. illegal.regexp=La ligne correspond au motif illégal ''{0}''. required.regexp=Le motif ''{0}'' attendu dans le fichier est manquant. translation.missingKey=La traduction du message ''{0}'' est manquante. missing.switch.default=Il manque le cas \"default\" dans le bloc \"switch\". uncommented.main=La méthode principale n'est pas commentée. descendant.token.min=Le nombre de lexèmes ''{3}'' descendant de ''{2}'' est {0}, il devrait être de {1} au minimum. descendant.token.max=Le nombre de lexèmes ''{3}'' descendant de ''{2}'' est {0}, il devrait être de {1} au maximum. final.parameter=Le paramètre {0} devrait être final. trailing.comments=Ne mélangez pas instructions Java et commentaires sur la même ligne. array.type.style=Les crochets du tableau ne sont pas placés au bon endroit. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/messages_ja.properties100644 0 0 2154 11451071613 27720 0ustar 0 0 noNewlineAtEOF=\u30d5\u30a1\u30a4\u30eb\u304c\u65b0\u3057\u3044\u884c\u3067\u7d42\u4e86\u3057\u3066\u3044\u307e\u305b\u3093\u3002 todo.match=\u30b3\u30e1\u30f3\u30c8\u304c to-do \u306e\u5f62\u5f0f ''{0}'' \u306b\u5408\u81f4\u3057\u3066\u3044\u307e\u3059\u3002 upperEll=\u5927\u6587\u5b57\u306e ''L'' \u3092\u4f7f\u7528\u3059\u3079\u304d\u3067\u3059\u3002 illegal.regexp=\u884c\u304c\u4e0d\u6b63\u306a\u30d1\u30bf\u30fc\u30f3 ''{0}'' \u306b\u5408\u81f4\u3057\u307e\u3059\u3002 translation.missingKey=\u30ad\u30fc ''{0}'' \u304c\u3042\u308a\u307e\u305b\u3093\u3002 missing.switch.default=\"default\" \u7bc0\u306e\u7121\u3044 switch \u6587\u3067\u3059\u3002 uncommented.main=\u30b3\u30e1\u30f3\u30c8\u3067\u306f\u306a\u3044 main \u30e1\u30bd\u30c3\u30c9\u304c\u898b\u3064\u304b\u308a\u307e\u3057\u305f\u3002 descendant.token.min=''{2}'' \u306e\u5b50\u5b6b ''{3}'' \u306e\u6570 {0} \u304c\u6700\u5c0f\u6570 {1} \u3092\u6e80\u305f\u3057\u307e\u305b\u3093\u3002 descendant.token.max=''{2}'' \u306e\u5b50\u5b6b ''{3}'' \u306e\u6570 {0} \u304c\u6700\u5927\u6570 {1} \u3092\u8d85\u3048\u3066\u3044\u307e\u3059\u3002 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/messages_pt.properties100644 0 0 1130 11451071613 27742 0ustar 0 0 descendant.token.max=Contagem de {0} para ''{2}'' descendente ''{3}'' é excede o número máximo {1}. descendant.token.min=Contagem de {0} para ''{2}'' descendente ''{3}'' é menos do que o número mínimo {1}. illegal.regexp=A linha condiz com o padro inválido ''{0}''. missing.switch.default=switch sem o ramo \"default\". noNewlineAtEOF=File does not end with a newline. todo.match=O comentário condiz com o padro de tarefa pendente ''{0}''. translation.missingKey=Falta a chave ''{0}''. uncommented.main=Método main no comentado encontrado. upperEll=Deve ser utilizado um ''L'' maiúsculo. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/messages_tr.properties100644 0 0 3355 11744664021 27765 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) array.type.style = Dizi parantezleri ge\u00E7ersiz konumda bulunuyor. descendant.token.max = ''{2}'' eleman\u0131ndan t\u00FCremi\u015F ''{3}'' i\u00E7in toplam {0} say\u0131s\u0131 maksimum {1} de\u011Ferinden daha y\u00FCksek. descendant.token.min = ''{2}'' eleman\u0131ndan t\u00FCremi\u015F ''{3}'' i\u00E7in toplam {0} say\u0131s\u0131 minimum {1} de\u011Ferinden daha d\u00FC\u015F\u00FCk. descendant.token.sum.max = ''{2}'' alt\u0131ndaki toplam {0} say\u0131s\u0131 maksimum {1} de\u011Ferinden daha y\u00FCksek. descendant.token.sum.min = ''{2}'' alt\u0131ndaki toplam {0} say\u0131s\u0131 minimum {1} de\u011Ferinden daha d\u00FC\u015F\u00FCk. duplicate.regexp = Tekrarlanm\u00FD\u00FEbir kal\u0131p bulundu: ''{0}''. final.parameter = {0} parametresi ''final'' olarak tan\u0131mlanmal\u0131. illegal.regexp = Sat\u0131rda ge\u00E7ersiz bir kal\u0131p var: ''{0}''. missing.switch.default = ''default'' durumu olmayan bir ''switch'' mevcut. noNewlineAtEOF = Dosyan\u0131n sonunda yeni sat\u0131r karakteri yok. required.regexp = Dosyada olmas\u0131 gereken ''{0}'' kal\u0131b\u0131 yok. todo.match = A\u00E7\u0131klamalar, ''to-do'' format\u0131 olan ''{0}'' ile \u00E7ak\u0131\u015F\u0131yor. trailing.comments = \u0130zleyen (trailing) a\u00E7\u0131klamalar kullan\u0131lmamal\u0131d\u0131r. translation.missingKey = ''{0}'' anahtar\u0131 eksik. type.file.mismatch = En d\u0131\u015Ftaki t\u00FCr\u00FCn ad\u0131 dosya ad\u0131yla ayn\u0131 de\u011Fil. unable.open = ''{0}'' a\u00E7\u0131lam\u0131yor. uncommented.main = ''main'' metoduna a\u00E7\u0131klama girilmeli. upperEll = B\u00FCy\u00FCk harf ''L'' kullan\u0131lmal\u0131. ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCh100644 0 0 24453 12026051022 31434 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; import java.util.Set; /** * Base class for coupling calculation. * * @author Simon Harris * @author o_sukhodolsky */ public abstract class AbstractClassCouplingCheck extends Check { /** Class names to ignore. */ private final Set mIgnoredClassNames = Sets.newHashSet(); /** Allowed complexity. */ private int mMax; /** package of the file we check. */ private String mPackageName; /** Stack of contexts. */ private final FastStack mContextStack = FastStack.newInstance(); /** Current context. */ private Context mContext; /** * Creates new instance of the check. * @param aDefaultMax default value for allowed complexity. */ protected AbstractClassCouplingCheck(int aDefaultMax) { setMax(aDefaultMax); mIgnoredClassNames.add("boolean"); mIgnoredClassNames.add("byte"); mIgnoredClassNames.add("char"); mIgnoredClassNames.add("double"); mIgnoredClassNames.add("float"); mIgnoredClassNames.add("int"); mIgnoredClassNames.add("long"); mIgnoredClassNames.add("short"); mIgnoredClassNames.add("void"); mIgnoredClassNames.add("Boolean"); mIgnoredClassNames.add("Byte"); mIgnoredClassNames.add("Character"); mIgnoredClassNames.add("Double"); mIgnoredClassNames.add("Float"); mIgnoredClassNames.add("Integer"); mIgnoredClassNames.add("Long"); mIgnoredClassNames.add("Object"); mIgnoredClassNames.add("Short"); mIgnoredClassNames.add("String"); mIgnoredClassNames.add("StringBuffer"); mIgnoredClassNames.add("Void"); mIgnoredClassNames.add("ArrayIndexOutOfBoundsException"); mIgnoredClassNames.add("Exception"); mIgnoredClassNames.add("RuntimeException"); mIgnoredClassNames.add("IllegalArgumentException"); mIgnoredClassNames.add("IllegalStateException"); mIgnoredClassNames.add("IndexOutOfBoundsException"); mIgnoredClassNames.add("NullPointerException"); mIgnoredClassNames.add("Throwable"); mIgnoredClassNames.add("SecurityException"); mIgnoredClassNames.add("UnsupportedOperationException"); } @Override public final int[] getDefaultTokens() { return getRequiredTokens(); } /** @return allowed complexity. */ public final int getMax() { return mMax; } /** * Sets maximul allowed complexity. * @param aMax allowed complexity. */ public final void setMax(int aMax) { mMax = aMax; } @Override public final void beginTree(DetailAST aAST) { mPackageName = ""; } /** @return message key we use for log violations. */ protected abstract String getLogMessageId(); @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.PACKAGE_DEF: visitPackageDef(aAST); break; case TokenTypes.CLASS_DEF: case TokenTypes.INTERFACE_DEF: case TokenTypes.ANNOTATION_DEF: case TokenTypes.ENUM_DEF: visitClassDef(aAST); break; case TokenTypes.TYPE: mContext.visitType(aAST); break; case TokenTypes.LITERAL_NEW: mContext.visitLiteralNew(aAST); break; case TokenTypes.LITERAL_THROWS: mContext.visitLiteralThrows(aAST); break; default: throw new IllegalStateException(aAST.toString()); } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CLASS_DEF: case TokenTypes.INTERFACE_DEF: case TokenTypes.ANNOTATION_DEF: case TokenTypes.ENUM_DEF: leaveClassDef(); break; default: // Do nothing } } /** * Stores package of current class we check. * @param aPkg package definition. */ private void visitPackageDef(DetailAST aPkg) { final FullIdent ident = FullIdent.createFullIdent(aPkg.getLastChild() .getPreviousSibling()); mPackageName = ident.getText(); } /** * Creates new context for a given class. * @param aClassDef class definition node. */ private void visitClassDef(DetailAST aClassDef) { mContextStack.push(mContext); final String className = aClassDef.findFirstToken(TokenTypes.IDENT).getText(); mContext = new Context(className, aClassDef.getLineNo(), aClassDef.getColumnNo()); } /** Restores previous context. */ private void leaveClassDef() { mContext.checkCoupling(); mContext = mContextStack.pop(); } /** * Incapsulates information about class coupling. * * @author Simon Harris * @author o_sukhodolsky */ private class Context { /** * Set of referenced classes. * Sorted by name for predictable error messages in unit tests. */ private final Set mReferencedClassNames = Sets.newTreeSet(); /** Own class name. */ private final String mClassName; /* Location of own class. (Used to log violations) */ /** Line number of class definition. */ private final int mLineNo; /** Column number of class definition. */ private final int mColumnNo; /** * Create new context associated with given class. * @param aClassName name of the given class. * @param aLineNo line of class definition. * @param aColumnNo column of class definition. */ public Context(String aClassName, int aLineNo, int aColumnNo) { mClassName = aClassName; mLineNo = aLineNo; mColumnNo = aColumnNo; } /** * Visits throws clause and collects all exceptions we throw. * @param aThrows throws to process. */ public void visitLiteralThrows(DetailAST aThrows) { for (DetailAST childAST = aThrows.getFirstChild(); childAST != null; childAST = childAST.getNextSibling()) { if (childAST.getType() != TokenTypes.COMMA) { addReferencedClassName(childAST); } } } /** * Visits type. * @param aAST type to process. */ public void visitType(DetailAST aAST) { final String className = CheckUtils.createFullType(aAST).getText(); mContext.addReferencedClassName(className); } /** * Visits NEW. * @param aAST NEW to process. */ public void visitLiteralNew(DetailAST aAST) { mContext.addReferencedClassName(aAST.getFirstChild()); } /** * Adds new referenced class. * @param aAST a node which represents referenced class. */ private void addReferencedClassName(DetailAST aAST) { final String className = FullIdent.createFullIdent(aAST).getText(); addReferencedClassName(className); } /** * Adds new referenced class. * @param aClassName class name of the referenced class. */ private void addReferencedClassName(String aClassName) { if (isSignificant(aClassName)) { mReferencedClassNames.add(aClassName); } } /** Checks if coupling less than allowed or not. */ public void checkCoupling() { mReferencedClassNames.remove(mClassName); mReferencedClassNames.remove(mPackageName + "." + mClassName); if (mReferencedClassNames.size() > mMax) { log(mLineNo, mColumnNo, getLogMessageId(), mReferencedClassNames.size(), getMax(), mReferencedClassNames.toString()); } } /** * Checks if given class shouldn't be ignored and not from java.lang. * @param aClassName class to check. * @return true if we should count this class. */ private boolean isSignificant(String aClassName) { return (aClassName.length() > 0) && !mIgnoredClassNames.contains(aClassName) && !aClassName.startsWith("java.lang."); } } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractComplexityCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractComplexityCheck100644 0 0 13026 12026051021 31477 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.math.BigInteger; /** * Base class for checks the calculate complexity based around methods. * * @author Simon Harris * @author Oliver Burn */ public abstract class AbstractComplexityCheck extends Check { /** the initial current value */ private static final BigInteger INITIAL_VALUE = BigInteger.ONE; /** stack of values - all but the current value */ private final FastStack mValueStack = FastStack.newInstance(); /** the current value */ private BigInteger mCurrentValue = BigInteger.ZERO; /** threshold to report error for */ private int mMax; /** * Creates an instance. * @param aMax the threshold of when to report an error */ public AbstractComplexityCheck(int aMax) { mMax = aMax; } /** * @return the message ID to log violations with */ protected abstract String getMessageID(); /** * Hook called when visiting a token. Will not be called the method * definition tokens. * * @param aAST the token being visited */ protected void visitTokenHook(DetailAST aAST) { } /** * Hook called when leaving a token. Will not be called the method * definition tokens. * * @param aAST the token being left */ protected void leaveTokenHook(DetailAST aAST) { } @Override public final int[] getRequiredTokens() { return new int[] { TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.INSTANCE_INIT, TokenTypes.STATIC_INIT, }; } /** @return the maximum threshold allowed */ public final int getMax() { return mMax; } /** * Set the maximum threshold allowed. * * @param aMax the maximum threshold */ public final void setMax(int aMax) { mMax = aMax; } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: case TokenTypes.INSTANCE_INIT: case TokenTypes.STATIC_INIT: visitMethodDef(); break; default: visitTokenHook(aAST); } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: case TokenTypes.INSTANCE_INIT: case TokenTypes.STATIC_INIT: leaveMethodDef(aAST); break; default: leaveTokenHook(aAST); } } /** * @return the current value */ protected final BigInteger getCurrentValue() { return mCurrentValue; } /** * Set the current value * @param aValue the new value */ protected final void setCurrentValue(BigInteger aValue) { mCurrentValue = aValue; } /** * Increments the current value by a specified amount. * * @param aBy the amount to increment by */ protected final void incrementCurrentValue(BigInteger aBy) { setCurrentValue(getCurrentValue().add(aBy)); } /** Push the current value on the stack */ protected final void pushValue() { mValueStack.push(mCurrentValue); mCurrentValue = INITIAL_VALUE; } /** * @return pop a value off the stack and make it the current value */ protected final BigInteger popValue() { mCurrentValue = mValueStack.pop(); return mCurrentValue; } /** Process the start of the method definition */ private void visitMethodDef() { pushValue(); } /** * Process the end of a method definition. * * @param aAST the token representing the method definition */ private void leaveMethodDef(DetailAST aAST) { final BigInteger max = BigInteger.valueOf(mMax); if (mCurrentValue.compareTo(max) > 0) { log(aAST, getMessageID(), mCurrentValue, max); } popValue(); } } ././@LongLink100644 0 0 163 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComple100644 0 0 14577 12026051021 31533 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.CheckUtils; /** * Restricts nested boolean operators (&&, ||, &, | and ^) to * a specified depth (default = 3). * * @author Simon Harris * @author o_sukhodolsky */ public final class BooleanExpressionComplexityCheck extends Check { /** Default allowed complexity. */ private static final int DEFAULT_MAX = 3; /** Stack of contexts. */ private final FastStack mContextStack = FastStack.newInstance(); /** Maximum allowed complexity. */ private int mMax; /** Current context. */ private Context mContext; /** Creates new instance of the check. */ public BooleanExpressionComplexityCheck() { setMax(DEFAULT_MAX); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.EXPR, TokenTypes.LAND, TokenTypes.BAND, TokenTypes.LOR, TokenTypes.BOR, TokenTypes.BXOR, }; } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.EXPR, }; } /** * Getter for maximum allowed complexity. * @return value of maximum allowed complexity. */ public int getMax() { return mMax; } /** * Setter for maximum allowed complexity. * @param aMax new maximum allowed complexity. */ public void setMax(int aMax) { mMax = aMax; } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: visitMethodDef(aAST); break; case TokenTypes.EXPR: visitExpr(); break; case TokenTypes.LAND: case TokenTypes.BAND: case TokenTypes.LOR: case TokenTypes.BOR: case TokenTypes.BXOR: mContext.visitBooleanOperator(); break; default: throw new IllegalStateException(aAST.toString()); } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: leaveMethodDef(); break; case TokenTypes.EXPR: leaveExpr(aAST); break; default: // Do nothing } } /** * Creates new context for a given method. * @param aAST a method we start to check. */ private void visitMethodDef(DetailAST aAST) { mContextStack.push(mContext); mContext = new Context(!CheckUtils.isEqualsMethod(aAST)); } /** Removes old context. */ private void leaveMethodDef() { mContext = mContextStack.pop(); } /** Creates and pushes new context. */ private void visitExpr() { mContextStack.push(mContext); mContext = new Context((mContext == null) || mContext.isChecking()); } /** * Restores previous context. * @param aAST expression we leave. */ private void leaveExpr(DetailAST aAST) { mContext.checkCount(aAST); mContext = mContextStack.pop(); } /** * Represents context (method/expression) in which we check complexity. * * @author Simon Harris * @author o_sukhodolsky */ private class Context { /** * Should we perform check in current context or not. * Usually false if we are inside equals() method. */ private final boolean mChecking; /** Count of boolean operators. */ private int mCount; /** * Creates new instance. * @param aChecking should we check in current context or not. */ public Context(boolean aChecking) { mChecking = aChecking; mCount = 0; } /** * Getter for checking property. * @return should we check in current context or not. */ public boolean isChecking() { return mChecking; } /** Increases operator counter. */ public void visitBooleanOperator() { ++mCount; } /** * Checks if we violates maximum allowed complexity. * @param aAST a node we check now. */ public void checkCount(DetailAST aAST) { if (mChecking && (mCount > getMax())) { final DetailAST parentAST = aAST.getParent(); log(parentAST.getLineNo(), parentAST.getColumnNo(), "booleanExpressionComplexity", mCount, getMax()); } } } } ././@LongLink100644 0 0 164 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCou100644 0 0 4147 12026051021 31404 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * This metric measures the number of instantiations of other classes * within the given class. * * @author Simon Harris * @author o_sukhodolsky */ public final class ClassDataAbstractionCouplingCheck extends AbstractClassCouplingCheck { /** Default allowed complexity. */ private static final int DEFAULT_MAX = 7; /** Creates bew instance of the check. */ public ClassDataAbstractionCouplingCheck() { super(DEFAULT_MAX); setTokens(new String[] {"LITERAL_NEW"}); } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.PACKAGE_DEF, TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.ENUM_DEF, TokenTypes.LITERAL_NEW, }; } @Override protected String getLogMessageId() { return "classDataAbstractionCoupling"; } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCh100644 0 0 4362 12026051021 31416 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * The number of other classes a given class relies on. Also the square * of this has been shown to indicate the amount of maintenence required * in functional programs (on a file basis) at least. * * @author Simon Harris * @author o_sukhodolsky */ public final class ClassFanOutComplexityCheck extends AbstractClassCouplingCheck { /** default value of max value. */ private static final int DEFAULT_MAX = 20; /** Creates new instance of this check. */ public ClassFanOutComplexityCheck() { super(DEFAULT_MAX); } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.PACKAGE_DEF, TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.ENUM_DEF, TokenTypes.TYPE, TokenTypes.LITERAL_NEW, TokenTypes.LITERAL_THROWS, TokenTypes.ANNOTATION_DEF, }; } @Override protected String getLogMessageId() { return "classFanOutComplexity"; } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/CyclomaticComplexityCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/CyclomaticComplexityChe100644 0 0 5563 12026051020 31473 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import java.math.BigInteger; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Checks cyclomatic complexity against a specified limit. The complexity is * measured by the number of "if", "while", "do", "for", "?:", "catch", * "switch", "case", "&&" and "||" statements (plus one) in the body of * the member. It is a measure of the minimum number of possible paths through * the source and therefore the number of required tests. Generally 1-4 is * considered good, 5-7 ok, 8-10 consider re-factoring, and 11+ re-factor now! * * @author Simon Harris * @author Oliver Burn */ public class CyclomaticComplexityCheck extends AbstractComplexityCheck { /** default allowed complexity */ private static final int DEFAULT_VALUE = 10; /** Create an instance. */ public CyclomaticComplexityCheck() { super(DEFAULT_VALUE); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.INSTANCE_INIT, TokenTypes.STATIC_INIT, TokenTypes.LITERAL_WHILE, TokenTypes.LITERAL_DO, TokenTypes.LITERAL_FOR, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_CASE, TokenTypes.LITERAL_CATCH, TokenTypes.QUESTION, TokenTypes.LAND, TokenTypes.LOR, }; } @Override protected final void visitTokenHook(DetailAST aAST) { incrementCurrentValue(BigInteger.ONE); } @Override protected final String getMessageID() { return "cyclomaticComplexity"; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/JavaNCSSCheck.java100644 0 0 26222 12026051020 30147 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * This check calculates the Non Commenting Source Statements (NCSS) metric for * java source files and methods. The check adheres to the JavaNCSS specification * and gives the same results as the JavaNCSS tool. * * The NCSS-metric tries to determine complexity of methods, classes and files * by counting the non commenting lines. Roughly said this is (nearly) * equivalent to counting the semicolons and opening curly braces. * * @author Lars Ködderitzsch */ public class JavaNCSSCheck extends Check { /** default constant for max file ncss */ private static final int FILE_MAX_NCSS = 2000; /** default constant for max file ncss */ private static final int CLASS_MAX_NCSS = 1500; /** default constant for max method ncss */ private static final int METHOD_MAX_NCSS = 50; /** maximum ncss for a complete source file */ private int mFileMax = FILE_MAX_NCSS; /** maximum ncss for a class */ private int mClassMax = CLASS_MAX_NCSS; /** maximum ncss for a method */ private int mMethodMax = METHOD_MAX_NCSS; /** list containing the stacked counters */ private FastStack mCounters; @Override public int[] getDefaultTokens() { return new int[]{ TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, TokenTypes.INSTANCE_INIT, TokenTypes.STATIC_INIT, TokenTypes.PACKAGE_DEF, TokenTypes.IMPORT, TokenTypes.VARIABLE_DEF, TokenTypes.CTOR_CALL, TokenTypes.SUPER_CTOR_CALL, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_ELSE, TokenTypes.LITERAL_WHILE, TokenTypes.LITERAL_DO, TokenTypes.LITERAL_FOR, TokenTypes.LITERAL_SWITCH, TokenTypes.LITERAL_BREAK, TokenTypes.LITERAL_CONTINUE, TokenTypes.LITERAL_RETURN, TokenTypes.LITERAL_THROW, TokenTypes.LITERAL_SYNCHRONIZED, TokenTypes.LITERAL_CATCH, TokenTypes.LITERAL_FINALLY, TokenTypes.EXPR, TokenTypes.LABELED_STAT, TokenTypes.LITERAL_CASE, TokenTypes.LITERAL_DEFAULT, }; } @Override public int[] getRequiredTokens() { return new int[]{ TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF, TokenTypes.INSTANCE_INIT, TokenTypes.STATIC_INIT, TokenTypes.PACKAGE_DEF, TokenTypes.IMPORT, TokenTypes.VARIABLE_DEF, TokenTypes.CTOR_CALL, TokenTypes.SUPER_CTOR_CALL, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_ELSE, TokenTypes.LITERAL_WHILE, TokenTypes.LITERAL_DO, TokenTypes.LITERAL_FOR, TokenTypes.LITERAL_SWITCH, TokenTypes.LITERAL_BREAK, TokenTypes.LITERAL_CONTINUE, TokenTypes.LITERAL_RETURN, TokenTypes.LITERAL_THROW, TokenTypes.LITERAL_SYNCHRONIZED, TokenTypes.LITERAL_CATCH, TokenTypes.LITERAL_FINALLY, TokenTypes.EXPR, TokenTypes.LABELED_STAT, TokenTypes.LITERAL_CASE, TokenTypes.LITERAL_DEFAULT, }; } @Override public void beginTree(DetailAST aRootAST) { mCounters = new FastStack(); //add a counter for the file mCounters.push(new Counter()); } @Override public void visitToken(DetailAST aAST) { final int tokenType = aAST.getType(); if ((TokenTypes.CLASS_DEF == tokenType) || (TokenTypes.METHOD_DEF == tokenType) || (TokenTypes.CTOR_DEF == tokenType) || (TokenTypes.STATIC_INIT == tokenType) || (TokenTypes.INSTANCE_INIT == tokenType)) { //add a counter for this class/method mCounters.push(new Counter()); } //check if token is countable if (isCountable(aAST)) { //increment the stacked counters for (final Counter c : mCounters) { c.increment(); } } } @Override public void leaveToken(DetailAST aAST) { final int tokenType = aAST.getType(); if ((TokenTypes.METHOD_DEF == tokenType) || (TokenTypes.CTOR_DEF == tokenType) || (TokenTypes.STATIC_INIT == tokenType) || (TokenTypes.INSTANCE_INIT == tokenType)) { //pop counter from the stack final Counter counter = mCounters.pop(); final int count = counter.getCount(); if (count > mMethodMax) { log(aAST.getLineNo(), aAST.getColumnNo(), "ncss.method", count, mMethodMax); } } else if (TokenTypes.CLASS_DEF == tokenType) { //pop counter from the stack final Counter counter = mCounters.pop(); final int count = counter.getCount(); if (count > mClassMax) { log(aAST.getLineNo(), aAST.getColumnNo(), "ncss.class", count, mClassMax); } } } @Override public void finishTree(DetailAST aRootAST) { //pop counter from the stack final Counter counter = mCounters.pop(); final int count = counter.getCount(); if (count > mFileMax) { log(aRootAST.getLineNo(), aRootAST.getColumnNo(), "ncss.file", count, mFileMax); } } /** * Sets the maximum ncss for a file. * * @param aFileMax * the maximum ncss */ public void setFileMaximum(int aFileMax) { mFileMax = aFileMax; } /** * Sets the maximum ncss for a class. * * @param aClassMax * the maximum ncss */ public void setClassMaximum(int aClassMax) { mClassMax = aClassMax; } /** * Sets the maximum ncss for a method. * * @param aMethodMax * the maximum ncss */ public void setMethodMaximum(int aMethodMax) { mMethodMax = aMethodMax; } /** * Checks if a token is countable for the ncss metric * * @param aAST * the AST * @return true if the token is countable */ private boolean isCountable(DetailAST aAST) { boolean countable = true; final int tokenType = aAST.getType(); //check if an expression is countable if (TokenTypes.EXPR == tokenType) { countable = isExpressionCountable(aAST); } //check if an variable definition is countable else if (TokenTypes.VARIABLE_DEF == tokenType) { countable = isVariableDefCountable(aAST); } return countable; } /** * Checks if a variable definition is countable. * * @param aAST the AST * @return true if the variable definition is countable, false otherwise */ private boolean isVariableDefCountable(DetailAST aAST) { boolean countable = false; //count variable defs only if they are direct child to a slist or // object block final int parentType = aAST.getParent().getType(); if ((TokenTypes.SLIST == parentType) || (TokenTypes.OBJBLOCK == parentType)) { final DetailAST prevSibling = aAST.getPreviousSibling(); //is countable if no previous sibling is found or //the sibling is no COMMA. //This is done because multiple assignment on one line are countes // as 1 countable = (prevSibling == null) || (TokenTypes.COMMA != prevSibling.getType()); } return countable; } /** * Checks if an expression is countable for the ncss metric. * * @param aAST the AST * @return true if the expression is countable, false otherwise */ private boolean isExpressionCountable(DetailAST aAST) { boolean countable = true; //count expressions only if they are direct child to a slist (method // body, for loop...) //or direct child of label,if,else,do,while,for final int parentType = aAST.getParent().getType(); switch (parentType) { case TokenTypes.SLIST : case TokenTypes.LABELED_STAT : case TokenTypes.LITERAL_FOR : case TokenTypes.LITERAL_DO : case TokenTypes.LITERAL_WHILE : case TokenTypes.LITERAL_IF : case TokenTypes.LITERAL_ELSE : //don't count if or loop conditions final DetailAST prevSibling = aAST.getPreviousSibling(); countable = (prevSibling == null) || (TokenTypes.LPAREN != prevSibling.getType()); break; default : countable = false; break; } return countable; } /** * @author Lars Ködderitzsch * * Class representing a counter, */ private static class Counter { /** the counters internal integer */ private int mIvCount; /** * Increments the counter. */ public void increment() { mIvCount++; } /** * Gets the counters value * * @return the counter */ public int getCount() { return mIvCount; } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/messages.properties100644 0 0 4430 11451330227 30712 0ustar 0 0 booleanExpressionComplexity=Boolean expression complexity is {0,number,integer} (max allowed is {1,number,integer}). classDataAbstractionCoupling=Class Data Abstraction Coupling is {0,number,integer} (max allowed is {1,number,integer}) classes {2}. classFanOutComplexity=Class Fan-Out Complexity is {0,number,integer} (max allowed is {1,number,integer}). cyclomaticComplexity=Cyclomatic Complexity is {0,number,integer} (max allowed is {1,number,integer}). duplicateLiteral=Duplicate instances of literal ''{0}'' are not allowed. finalField=The field ''{0}'' should be declared final. illegalAbstractClassName=Name ''{0}'' must match pattern ''{1}''. illegalCatch=Catching ''{0}'' is not allowed. illegalThrows=Throwing ''{0}'' is not allowed. illegalToken=Using ''{0}'' is not allowed. illegalType=Declaring variables, return values or parameters of type ''{0}'' is not allowed. junit.methodName=The method ''{0}'' should be named ''{1}'' junit.methodParameters=The method ''{0}'' must be declared with no parameters. junit.methodPublicAndStatic=The method ''{0}'' must be declared static. junit.methodPublicOrProtected=The method {0} must be declared public or protected junit.methodReturnType=The method ''{0}'' must de declared with a void return type. mutableException=The field ''{0}'' must be declared final. nestedIfDepth=Nested if-else depth is {0,number,integer} (max allowed is {1,number,integer}). nestedTryDepth=Nested try depth is {0,number,integer} (max allowed is {1,number,integer}). npathComplexity=NPath Complexity is {0,number,integer} (max allowed is {1,number,integer}). packageDeclaration=Missing package declaration. parameterAssignment=Assignment of parameter ''{0}'' is not allowed. returnCount=Return count is {0,number,integer} (max allowed is {1,number,integer}). returnFromCatch=Return from catch is not allowed. returnFromFinally=Return from finally is not allowed. throwsCount=Throws count is {0,number,integer} (max allowed is {1,number,integer}). unusedVariable=Variable ''{0}'' is never used. ncss.method=NCSS for this method is {0,number,integer} (max allowed is {1,number,integer}). ncss.class=NCSS for this class is {0,number,integer} (max allowed is {1,number,integer}). ncss.file=NCSS for this file is {0,number,integer} (max allowed is {1,number,integer}). checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/messages_es.properties100644 0 0 5017 11451071613 31404 0ustar 0 0 booleanExpressionComplexity=La complejidad de la expresión lógica es {0,number,integer} (máxima permitida es {1,number,integer}). classDataAbstractionCoupling=El acoplamiento abstracto de datos entre clases es {0,number,integer} (máximo permitida es {1,number,integer}) clases {2}. classFanOutComplexity=La complejidad Fan-Out de clase es {0,number,integer} (máxima permitida es {1,number,integer}). cyclomaticComplexity=La complejidad ciclomática es {0,number,integer} (máxima permitida es {1,number,integer}). duplicateLiteral=No estan permitidas instancias duplicadas del literal ''{0}''. finalField=El campo ''{0}'' debería declararse final. illegalAbstractClassName=El nombre ''{0}'' debe coincidir con el patrón ''{1}''. illegalCatch=No está permitido capturar la excepción ''{0}''. illegalThrows=No está permitido lanzar la excepción ''{0}''. illegalToken=No está permitido usar ''{0}''. illegalType=No está permitido declarar variables, valores de retorno o parámetros de tipo ''{0}''. junit.methodName=El método ''{0}'' debería llamarse ''{1}'' junit.methodParameters=El método ''{0}'' debería declararse sin parámetros. junit.methodPublicAndStatic=El método ''{0}'' debería declararse static. junit.methodPublicOrProtected=El método {0} debería declararse public o protected junit.methodReturnType=El método ''{0}'' debería declararse con tipo de retorno void. mutableException=El campo ''{0}'' debe declararse final. nestedIfDepth=La profundidad de if-else anidados es {0,number,integer} (máxima permitida es {1,number,integer}). nestedTryDepth=La profundidad de try anidados es {0,number,integer} (máxima permitida es {1,number,integer}). npathComplexity=La complejidad NPath es {0,number,integer} (máxima permitida es {1,number,integer}). packageDeclaration=Falta la declaración de paquete. parameterAssignment=No está permitido asignar al parámetro ''{0}''. returnCount=El número de sentencias return es {0,number,integer} (máximo permitido es {1,number,integer}). returnFromCatch=No esta permitido return desde un catch. returnFromFinally=No esta permitido return desde un finally. throwsCount=El número de throw es {0,number,integer} (máximo permitido es {1,number,integer}). unusedVariable=La variable ''{0}'' no se usa nunca. ncss.method=El NCSS para este método es {0,number,integer} (máximo permitido es {1,number,integer}). ncss.class=El NCSS para esta clase es {0,number,integer} (máximo permitido es {1,number,integer}). ncss.file=El NCSS para este fichero es {0,number,integer} (máximo permitido es {1,number,integer}). checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/messages_fr.properties100644 0 0 5614 11451071613 31407 0ustar 0 0 booleanExpressionComplexity=La complexité de l''expression booléenne est de {0,number,integer}, alors que le maximum autorisé est de {1,number,integer}. classDataAbstractionCoupling=Le DAC (Data Abstraction Coupling) de la classe est de {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. classFanOutComplexity=Le Fan-Out Complexity de la classe est de {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. cyclomaticComplexity=La complexité cyclomatique de la classe est de {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. duplicateLiteral=Utiliser plusieurs fois la même chaîne littérale ''{0}'' est interdit. finalField=L''attribut ''{0}'' devrait être déclaré final. illegalAbstractClassName=Le nom ''{0}'' devrait respecter l''expression ''{1}''. illegalCatch=Il est interdit de catcher l''exception ''{0}''. illegalThrows=Il est interdit de déclarer l''exception ''{0}''. illegalToken=Il est interdit d''utiliser ''{0}''. illegalType=Il est interdit de déclarer des variables, valeurs de retour ou paramètres de type ''{0}''. junit.methodName=La méthode ''{0}'' devrait être renommée ''{1}'' junit.methodParameters=La méthode ''{0}'' ne devrait pas comporter de paramètres. junit.methodPublicAndStatic=La méthode ''{0}'' devrait être statique. junit.methodPublicOrProtected=La méthode {0} devrait être protégée ou publique. junit.methodReturnType=La méthode ''{0}'' devrait avoir un type de retour \"void\". mutableException=L''attribut ''{0}'' devrait être déclaré final. nestedIfDepth=Le nombre de if imbriqués est de {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. nestedTryDepth=Le nombre de try imbriqués est de {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. npathComplexity=La complexité NPath est de {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. packageDeclaration=Déclaration de package manquante. parameterAssignment=L''affectation du paramètre ''{0}'' est interdit. returnCount=Le nombre d''instructions return est de {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. returnFromCatch=Il est interdit de placer une instruction \"return\" dans un bloc \"catch\". returnFromFinally=Il est interdit de placer une instruction \"return\" dans un bloc \"finally\". throwsCount=Le nombre d''exceptions déclaré est de {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. unusedVariable=La variable ''{0}'' n''est jamais utilisée. ncss.method=La métrique NCSS pour cette méthode vaut {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. ncss.class=La métrique NCSS pour cette classe vaut {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. ncss.file=La métrique NCSS pour ce fichier vaut {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/messages_tr.properties100644 0 0 10222 11744664265 31454 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) booleanExpressionComplexity = Mant\u0131ksal ifadenin karma\u015F\u0131kl\u0131\u011F\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). classDataAbstractionCoupling = Class Data Abstraction Coupling (CDAC) de\u011Feri {0,number,integer} {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). Nesnesi olu\u015Fturulan s\u0131n\u0131flar {2}. (CDAC: Bir s\u0131n\u0131f\u0131n, kendinden farkl\u0131 ka\u00E7 s\u0131n\u0131f\u0131n nesnesini olu\u015Fturdu\u011Fu.) classFanOutComplexity = Class Fan-Out Complexity (CFOC) de\u011Feri {0,number,integer} {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). (CFOC: Bir s\u0131n\u0131f\u0131n, kendinden ba\u015Fka ka\u00E7 farkl\u0131 s\u0131n\u0131f\u0131 kulland\u0131\u011F\u0131) cyclomaticComplexity = Cyclomatic Complexity de\u011Feri {0,number,integer} {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). (Cyclomatic Complexity: Bir metodun, constructorun ya da statik blo\u011Fun m\u00FCmk\u00FCn olan minimum ger\u00E7eklenme yolu say\u0131s\u0131) duplicateLiteral = ''{0}'' s\u00F6zc\u00FC\u011F\u00FC kod i\u00E7erisinde tekrarlanmamal\u0131, tan\u0131mlan\u0131p \u00F6yle kullan\u0131lmal\u0131. finalField = ''{0}'' alan\u0131 ''final'' olarak tan\u0131mlanmal\u0131. illegalAbstractClassName = ''{0}'' s\u0131n\u0131f\u0131n\u0131n ad\u0131 \u015Fu kal\u0131pta olmal\u0131: ''{1}''. illegalCatch = ''{0}'' istisnas\u0131n\u0131/hatas\u0131n\u0131 yakalamaya izin verilmiyor. illegalThrows = ''{0}'' istisnas\u0131n\u0131/hatas\u0131n\u0131 f\u0131rlatmaya izin verilmiyor. illegalToken = ''{0}'' kullanmaya izin verilmiyor. illegalType = ''{0}'' tipinde de\u011Fi\u015Fkenler, parametreler ya da geri d\u00F6n\u00FC\u015F de\u011Ferleri tan\u0131mlamaya, izin verilmiyor. junit.methodName = ''{0}'' metodunun ad\u0131 ''{1}'' olmal\u0131. junit.methodParameters = ''{0}'' metodu parametresiz olarak tan\u0131mlanmal\u0131. junit.methodPublicAndStatic = ''{0}'' metodu ''static'' olarak tan\u0131mlanmal\u0131. junit.methodPublicOrProtected = {0} metodu ''public'' ya da ''protected'' olarak tan\u0131mlanmal\u0131. junit.methodReturnType = ''{0}'' metodunun geri d\u00F6n\u00FC\u015F tipi ''void'' olmal\u0131. mutableException = ''{0}'' alan\u0131 ''final'' olarak tan\u0131mlanmal\u0131. ncss.class = Bu s\u0131n\u0131f\u0131n a\u00E7\u0131klama olmayan kaynak kod sat\u0131r\u0131 (NCSS) say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). ncss.file = Bu dosyan\u0131n a\u00E7\u0131klama olmayan kaynak kod sat\u0131r\u0131 (NCSS) say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). ncss.method = Bu metodun a\u00E7\u0131klama olmayan kaynak kod sat\u0131r\u0131 (NCSS) say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). nestedIfDepth = \u0130\u00E7 i\u00E7e kullan\u0131lan ''if-else'' say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). nestedTryDepth = \u0130\u00E7 i\u00E7e kullan\u0131lan ''try'' say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). npathComplexity = NPath Complexity de\u011Feri {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). (NPath Complexity: Bir metodun m\u00FCmk\u00FCn olan t\u00FCm ger\u00E7eklenme yollar\u0131n\u0131n say\u0131s\u0131) packageDeclaration = Paket tan\u0131m\u0131 eksik. parameterAssignment = ''{0}'' parametresine de\u011Fer atanamaz. returnCount = ''return'' say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). returnFromCatch = ''catch'' ifadesi i\u00E7inde ''return'' kullan\u0131lamaz. returnFromFinally = ''finally'' ifadesi i\u00E7inde ''return'' kullan\u0131lamaz. throwsCount = Kullan\u0131lan ''throws'' say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). unusedVariable = ''{0}'' de\u011Fi\u015Fkeni hi\u00E7 kullan\u0131lmam\u0131\u015F. ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.ja100644 0 0 11400 12026051020 31330 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import java.math.BigInteger; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Checks the npath complexity against a specified limit (default = 200). * The npath metric computes the number of possible execution paths * through a function. Similar to the cyclomatic complexity but also * takes into account the nesting of conditional statements and * multi-part boolean expressions. * * @author Simon Harris * @author o_sukhodolsky * TODO: For every or: _value += (_orCount * (nestedValue - 1)); * TODO: For every and: ??? */ public final class NPathComplexityCheck extends AbstractComplexityCheck { /** Default allowed complexity. */ private static final int DEFAULT_MAX = 200; /** Creates new instance of the check. */ public NPathComplexityCheck() { super(DEFAULT_MAX); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.STATIC_INIT, TokenTypes.INSTANCE_INIT, TokenTypes.LITERAL_WHILE, TokenTypes.LITERAL_DO, TokenTypes.LITERAL_FOR, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_ELSE, TokenTypes.LITERAL_SWITCH, TokenTypes.LITERAL_CASE, TokenTypes.LITERAL_TRY, TokenTypes.LITERAL_CATCH, TokenTypes.QUESTION, }; } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.LITERAL_WHILE: case TokenTypes.LITERAL_DO: case TokenTypes.LITERAL_FOR: case TokenTypes.LITERAL_IF: case TokenTypes.QUESTION: case TokenTypes.LITERAL_TRY: case TokenTypes.LITERAL_SWITCH: visitMultiplyingConditional(); break; case TokenTypes.LITERAL_ELSE: case TokenTypes.LITERAL_CATCH: case TokenTypes.LITERAL_CASE: visitAddingConditional(); break; default: super.visitToken(aAST); } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.LITERAL_WHILE: case TokenTypes.LITERAL_DO: case TokenTypes.LITERAL_FOR: case TokenTypes.LITERAL_IF: case TokenTypes.QUESTION: case TokenTypes.LITERAL_TRY: case TokenTypes.LITERAL_SWITCH: leaveMultiplyingConditional(); break; case TokenTypes.LITERAL_ELSE: case TokenTypes.LITERAL_CATCH: case TokenTypes.LITERAL_CASE: leaveAddingConditional(); break; default: super.leaveToken(aAST); } } @Override protected String getMessageID() { return "npathComplexity"; } /** Visits else, catch or case. */ private void visitAddingConditional() { pushValue(); } /** Leaves else, catch or case. */ private void leaveAddingConditional() { setCurrentValue( getCurrentValue().subtract(BigInteger.ONE).add(popValue())); } /** Visits while, do, for, if, try, ? (in ?::) or switch. */ private void visitMultiplyingConditional() { pushValue(); } /** Leaves while, do, for, if, try, ? (in ?::) or switch. */ private void leaveMultiplyingConditional() { setCurrentValue( getCurrentValue().add(BigInteger.ONE).multiply(popValue())); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/metrics/package-info.java100644 0 0 2301 12026051020 30135 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the Metrics checks that are * bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks.metrics; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages.properties100644 0 0 315 11451071613 31021 0ustar 0 0 redundantModifier=Redundant ''{0}'' modifier. annotation.order=''{0}'' annotation modifier does not preceed non-annotation modifiers. mod.order=''{0}'' modifier out of order with the JLS suggestions. ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_de.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_de.properties100644 0 0 370 11451071613 31472 0ustar 0 0 redundantModifier=Überflüssiger Modifier ''{0}''. annotation.order=''{0}'' Annotation-Modifier sollte vor den anderen Modifiern stehen. mod.order=Modifier ''{0}'' weicht von der empfohlenen Modifier-Reihenfolge aus der Java-Sprachdefinition ab. ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_es.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_es.properties100644 0 0 340 11451071613 31506 0ustar 0 0 redundantModifier=Modificador ''{0}'' redundante. annotation.order=El modificador de anotación ''{0}'' no precede a los modificadores normales. mod.order=Modificador ''{0}'' desordenado según las sugerencias de la JLS. ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_fi.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_fi.properties100644 0 0 200 11451071613 31470 0ustar 0 0 redundantModifier=Tarpeeton m¤¤rite: ''{0}'' mod.order=''{0}'' m¤¤rite rikkoo JLS:n suositusten mukaisesen j¤rjestyksen. ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_fr.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_fr.properties100644 0 0 350 11451071613 31507 0ustar 0 0 redundantModifier=Mot-clef ''{0}'' redondant. annotation.order=Le modificateur d''annotation ''{0}'' ne précède pas les autres modificateurs. mod.order=Le mot-clef ''{0}'' n''apparaît pas dans l''ordre préconisé par les JLS. ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_ja.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_ja.properties100644 0 0 320 11451071613 31467 0ustar 0 0 redundantModifier=\u5197\u9577\u306a ''{0}'' \u4fee\u98fe\u5b50\u3067\u3059\u3002 mod.order=''{0}'' \u4fee\u98fe\u5b50\u304c JLS \u63d0\u6848\u306e\u9806\u5e8f\u306b\u6cbf\u3044\u307e\u305b\u3093\u3002 ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_pt.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_pt.properties100644 0 0 172 11451071613 31525 0ustar 0 0 redundantModifier=Modificador ''{0}'' é redundante. mod.order=Modificador ''{0}'' fora da orderm sugerida pela JLS. ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_tr.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/messages_tr.properties100644 0 0 533 11744664014 31540 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) annotation.order = ''{0}'' anotasyon niteleyicisi, anotasyon olmayan niteleyicilerden \u00F6nce kullan\u0131lmal\u0131. mod.order = ''{0}'' niteleyicisi, Java taraf\u0131ndan \u00F6nerilen s\u0131rada de\u011Fil. redundantModifier = Gereksiz ''{0}'' niteleyicisi. ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/ModifierOrderCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/ModifierOrderCheck.jav100644 0 0 13211 12026051017 31320 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.modifier; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.Iterator; import java.util.List; /** *

* Checks that the order of modifiers conforms to the suggestions in the * * Java Language specification, sections 8.1.1, 8.3.1 and 8.4.3. * The correct order is:

  1. public
  2. protected
  3. private
  4. abstract
  5. static
  6. final
  7. transient
  8. volatile
  9. synchronized
  10. native
  11. strictfp
* In additional, modifiers are checked to ensure all annotations * are declared before all other modifiers. *

* Rationale: Code is easier to read if everybody follows * a standard. *

*

* An example of how to configure the check is: *

*
 * <module name="ModifierOrder"/>
 * 
* @author Lars Kühne */ public class ModifierOrderCheck extends Check { /** * The order of modifiers as suggested in sections 8.1.1, * 8.3.1 and 8.4.3 of the JLS. */ private static final String[] JLS_ORDER = { "public", "protected", "private", "abstract", "static", "final", "transient", "volatile", "synchronized", "native", "strictfp", }; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.MODIFIERS}; } @Override public void visitToken(DetailAST aAST) { final List mods = Lists.newArrayList(); DetailAST modifier = aAST.getFirstChild(); while (modifier != null) { mods.add(modifier); modifier = modifier.getNextSibling(); } if (!mods.isEmpty()) { final DetailAST error = checkOrderSuggestedByJLS(mods); if (error != null) { if (error.getType() == TokenTypes.ANNOTATION) { log(error.getLineNo(), error.getColumnNo(), "annotation.order", error.getFirstChild().getText() + error.getFirstChild().getNextSibling() .getText()); } else { log(error.getLineNo(), error.getColumnNo(), "mod.order", error.getText()); } } } } /** * Checks if the modifiers were added in the order suggested * in the Java language specification. * * @param aModifiers list of modifier AST tokens * @return null if the order is correct, otherwise returns the offending * * modifier AST. */ DetailAST checkOrderSuggestedByJLS(List aModifiers) { int i = 0; DetailAST modifier; final Iterator it = aModifiers.iterator(); //No modifiers, no problems if (!it.hasNext()) { return null; } //Speed past all initial annotations do { modifier = it.next(); } while (it.hasNext() && (modifier.getType() == TokenTypes.ANNOTATION)); //All modifiers are annotations, no problem if (modifier.getType() == TokenTypes.ANNOTATION) { return null; } while (i < JLS_ORDER.length) { if (modifier.getType() == TokenTypes.ANNOTATION) { //Annotation not at start of modifiers, bad return modifier; } while ((i < JLS_ORDER.length) && !JLS_ORDER[i].equals(modifier.getText())) { i++; } if (i == JLS_ORDER.length) { //Current modifier is out of JLS order return modifier; } else if (!it.hasNext()) { //Reached end of modifiers without problem return null; } else { modifier = it.next(); } } return modifier; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/package-info.java100644 0 0 2233 12026051017 30277 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the modifier checks that are bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks.modifier; ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck100644 0 0 11607 12026051017 31421 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.modifier; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Checks for redundant modifiers in interface and annotation definitions. * Also checks for redundant final modifiers on methods of final classes. * * @author lkuehne */ public class RedundantModifierCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.METHOD_DEF, TokenTypes.VARIABLE_DEF, TokenTypes.ANNOTATION_FIELD_DEF, TokenTypes.INTERFACE_DEF, }; } @Override public int[] getRequiredTokens() { return new int[] {}; } @Override public void visitToken(DetailAST aAST) { if (TokenTypes.INTERFACE_DEF == aAST.getType()) { final DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS); if (null != modifiers) { final DetailAST modifier = modifiers.findFirstToken(TokenTypes.LITERAL_STATIC); if (null != modifier) { log(modifier.getLineNo(), modifier.getColumnNo(), "redundantModifier", modifier.getText()); } } } else if (ScopeUtils.inInterfaceOrAnnotationBlock(aAST)) { final DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS); DetailAST modifier = modifiers.getFirstChild(); while (modifier != null) { // javac does not allow final or static in interface methods // order annotation fields hence no need to check that this // is not a method or annotation field final int type = modifier.getType(); if ((type == TokenTypes.LITERAL_PUBLIC) || (type == TokenTypes.ABSTRACT) || (type == TokenTypes.LITERAL_STATIC) || (type == TokenTypes.FINAL)) { log(modifier.getLineNo(), modifier.getColumnNo(), "redundantModifier", modifier.getText()); break; } modifier = modifier.getNextSibling(); } } else if (aAST.getType() == TokenTypes.METHOD_DEF) { final DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS); // private method? boolean checkFinal = modifiers.branchContains(TokenTypes.LITERAL_PRIVATE); // declared in a final class? DetailAST parent = aAST.getParent(); while (parent != null) { if (parent.getType() == TokenTypes.CLASS_DEF) { final DetailAST classModifiers = parent.findFirstToken(TokenTypes.MODIFIERS); checkFinal |= classModifiers.branchContains(TokenTypes.FINAL); break; } parent = parent.getParent(); } if (checkFinal) { DetailAST modifier = modifiers.getFirstChild(); while (modifier != null) { final int type = modifier.getType(); if (type == TokenTypes.FINAL) { log(modifier.getLineNo(), modifier.getColumnNo(), "redundantModifier", modifier.getText()); break; } modifier = modifier.getNextSibling(); } } } } } ././@LongLink100644 0 0 160 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/AbstractAccessControlNameCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/AbstractAccessControlNam100644 0 0 12667 12026051017 31424 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Abstract class for checking a class member (field/method)'s name conforms to * a format specified by the format property. * *

This class extends {@link AbstractNameCheck} with support for access level * restrictions. This allows the check to be configured to be applied to one of * the four Java access levels: {@code public}, {@code protected}, * {@code "package"}, and {@code private}. * *

Level is configured using the following properties: *

    *
  1. applyToPublic, default true; *
  2. applyToProtected, default true; *
  3. applyToPackage, default true; *
  4. applyToPrivate, default true; *
*

* * @author Rick Giles * @version 1.0 */ public abstract class AbstractAccessControlNameCheck extends AbstractNameCheck { /** If true, applies the check be public members. */ private boolean mApplyToPublic = true; /** If true, applies the check be protected members. */ private boolean mApplyToProtected = true; /** If true, applies the check be "package" members. */ private boolean mApplyToPackage = true; /** If true, applies the check be private members. */ private boolean mApplyToPrivate = true; /** * Creates a new {@code AbstractAccessControlNameCheck} instance. * * @param aFormat * format to check with */ public AbstractAccessControlNameCheck(String aFormat) { super(aFormat); } @Override protected boolean mustCheckName(DetailAST aAST) { return shouldCheckInScope(aAST); } /** * Should we check member with given modifiers. * * @param aModifiers * modifiers of member to check. * @return true if we should check such member. */ protected boolean shouldCheckInScope(DetailAST aModifiers) { if (aModifiers == null) { // if there are no modifiers it is a package-private return mApplyToPackage; } final boolean isPublic = aModifiers .branchContains(TokenTypes.LITERAL_PUBLIC); final boolean isProtected = aModifiers .branchContains(TokenTypes.LITERAL_PROTECTED); final boolean isPrivate = aModifiers .branchContains(TokenTypes.LITERAL_PRIVATE); final boolean isPackage = !(isPublic || isProtected || isPrivate); return (mApplyToPublic && isPublic) || (mApplyToProtected && isProtected) || (mApplyToPackage && isPackage) || (mApplyToPrivate && isPrivate); } /** * Sets whether we should apply the check to public members. * * @param aApplyTo new value of the property. */ public void setApplyToPublic(boolean aApplyTo) { mApplyToPublic = aApplyTo; } /** @return true if the check should be applied to public members. */ public boolean getApplyToPublic() { return mApplyToPublic; } /** * Sets whether we should apply the check to protected members. * * @param aApplyTo new value of the property. */ public void setApplyToProtected(boolean aApplyTo) { mApplyToProtected = aApplyTo; } /** @return true if the check should be applied to protected members. */ public boolean getApplyToProtected() { return mApplyToProtected; } /** * Sets whether we should apply the check to package-private members. * * @param aApplyTo new value of the property. */ public void setApplyToPackage(boolean aApplyTo) { mApplyToPackage = aApplyTo; } /** * @return true if the check should be applied to package-private members. */ public boolean getApplyToPackage() { return mApplyToPackage; } /** * Sets whether we should apply the check to private members. * * @param aApplyTo new value of the property. */ public void setApplyToPrivate(boolean aApplyTo) { mApplyToPrivate = aApplyTo; } /** @return true if the check should be applied to private members. */ public boolean getApplyToPrivate() { return mApplyToPrivate; } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheck.j100644 0 0 11010 12026051016 31236 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck; /** *

* Ensures that the names of abstract classes conforming to some * regular expression and check that abstract modifier exists. *

*

* Rationale: Abstract classes are convenience base class * implementations of interfaces, not types as such. As such * they should be named to indicate this. Also if names of classes * starts with 'Abstract' it's very convenient that they will * have abstract modifier. *

* * @author Simon Harris * @author Danil Lopatin */ public final class AbstractClassNameCheck extends AbstractFormatCheck { /** Default format for abstract class names */ private static final String DEFAULT_FORMAT = "^Abstract.*$|^.*Factory$"; /** whether to ignore checking the modifier */ private boolean mIgnoreModifier; /** whether to ignore checking the name */ private boolean mIgnoreName; /** Creates new instance of the check. */ public AbstractClassNameCheck() { super(DEFAULT_FORMAT); } /** * Whether to ignore checking for the abstract modifier. * @param aValue new value */ public void setIgnoreModifier(boolean aValue) { mIgnoreModifier = aValue; } /** * Whether to ignore checking the name. * @param aValue new value. */ public void setIgnoreName(boolean aValue) { mIgnoreName = aValue; } @Override public int[] getDefaultTokens() { return new int[]{TokenTypes.CLASS_DEF}; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void visitToken(DetailAST aAST) { if (TokenTypes.CLASS_DEF == aAST.getType()) { visitClassDef(aAST); } } /** * Checks class definition. * @param aAST class definition for check. */ private void visitClassDef(DetailAST aAST) { final String className = aAST.findFirstToken(TokenTypes.IDENT).getText(); if (isAbstract(aAST)) { // if class has abstract modifier if (!mIgnoreName && !isMatchingClassName(className)) { log(aAST.getLineNo(), aAST.getColumnNo(), "illegal.abstract.class.name", className, getFormat()); } } else if (!mIgnoreModifier && isMatchingClassName(className)) { log(aAST.getLineNo(), aAST.getColumnNo(), "no.abstract.class.modifier", className); } } /** * @param aAST class definition for check. * @return true if a given class declared as abstract. */ private boolean isAbstract(DetailAST aAST) { final DetailAST abstractAST = aAST.findFirstToken(TokenTypes.MODIFIERS) .findFirstToken(TokenTypes.ABSTRACT); return abstractAST != null; } /** * @param aClassName class name for check. * @return true if class name matches format of abstract class names. */ private boolean isMatchingClassName(String aClassName) { return getRegexp().matcher(aClassName).find(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/AbstractNameCheck.java100644 0 0 4733 12026051016 30736 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck; /** * Abstract class for checking that names conform to a specified format. * * @author Rick Giles * @version 1.0 */ public abstract class AbstractNameCheck extends AbstractFormatCheck { /** * Creates a new AbstractNameCheck instance. * @param aFormat format to check with */ public AbstractNameCheck(String aFormat) { super(aFormat); } /** * Decides whether the name of an AST should be checked against * the format regexp. * @param aAST the AST to check. * @return true if the IDENT subnode of aAST should be checked against * the format regexp. */ protected boolean mustCheckName(DetailAST aAST) { return true; } @Override public void visitToken(DetailAST aAST) { if (mustCheckName(aAST)) { final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT); if (!getRegexp().matcher(nameAST.getText()).find()) { log(nameAST.getLineNo(), nameAST.getColumnNo(), "name.invalidPattern", nameAST.getText(), getFormat()); } } } } ././@LongLink100644 0 0 160 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/AbstractTypeParameterNameCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/AbstractTypeParameterNam100644 0 0 5456 12026051016 31421 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Abstract class for checking if a class/method type parameter's name * conforms to a format specified by the format property. *

* *

This class extends {@link AbstractNameCheck}

* * @author Travis Schneeberger * @version 1.0 */ public abstract class AbstractTypeParameterNameCheck extends AbstractNameCheck { /** the location of the type parameter **/ private int mLocation; /** * Creates a new AbstractTypeParameterNameCheck instance. * @param aFormat format to check with */ public AbstractTypeParameterNameCheck(String aFormat) { super(aFormat); } @Override public final int[] getDefaultTokens() { return new int[] { TokenTypes.TYPE_PARAMETER, }; } @Override public final void init() { this.mLocation = getLocation(); assert (this.mLocation == TokenTypes.CLASS_DEF) || (this.mLocation == TokenTypes.METHOD_DEF); } @Override protected final boolean mustCheckName(DetailAST aAST) { DetailAST location = aAST.getParent().getParent(); if (location.getType() == TokenTypes.MODIFIERS) { location = location.getParent(); } return location.getType() == this.mLocation; } /** * This method must be overriden to specify the * location of the type parameter to check. * * @return TokenTypes.CLASS_DEF * or TokenTypes.METHOD_DEF */ protected abstract int getLocation(); } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/ClassTypeParameterNameCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/ClassTypeParameterNameCh100644 0 0 4230 12026051016 31330 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that class type parameter names conform to a format specified * by the format property. The format is a * {@link java.util.regex.Pattern regular expression} and defaults to * ^[A-Z]$. *

*

* An example of how to configure the check is: *

*
 * <module name="ClassTypeParameterName"/>
 * 
*

* An example of how to configure the check for names that are only a single * letter is *

*
 * <module name="ClassTypeParameterName">
 *    <property name="format" value="^[a-zA-Z]$"/>
 * </module>
 * 
* * @author Travis Schneeberger * @version 1.0 */ public class ClassTypeParameterNameCheck extends AbstractTypeParameterNameCheck { /** Creates a new ClassTypeParameterNameCheck instance. */ public ClassTypeParameterNameCheck() { super("^[A-Z]$"); } @Override protected final int getLocation() { return TokenTypes.CLASS_DEF; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/ConstantNameCheck.java100644 0 0 7077 12026051015 30767 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that constant names conform to a format specified * by the format property. * A constant is a static and final * field or an interface/annotation field, except * serialVersionUID and serialPersistentFields * . The format is a regular expression * and defaults to ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$. *

*

* An example of how to configure the check is: *

*
 * <module name="ConstantName"/>
 * 
* *

* An example of how to configure the check for names that are only upper case * letters and digits is: *

*
 * <module name="ConstantName">
 *    <property name="format" value="^[A-Z][A-Z0-9]*$"/>
 * </module>
 * 
* * * @author Rick Giles * @version 1.0 */ public class ConstantNameCheck extends AbstractAccessControlNameCheck { /** Creates a new ConstantNameCheck instance. */ public ConstantNameCheck() { super("^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.VARIABLE_DEF}; } @Override protected final boolean mustCheckName(DetailAST aAST) { boolean retVal = false; final DetailAST modifiersAST = aAST.findFirstToken(TokenTypes.MODIFIERS); final boolean isStatic = (modifiersAST != null) && modifiersAST.branchContains(TokenTypes.LITERAL_STATIC); final boolean isFinal = (modifiersAST != null) && modifiersAST.branchContains(TokenTypes.FINAL); if ((isStatic && isFinal && shouldCheckInScope(modifiersAST)) || ScopeUtils.inInterfaceOrAnnotationBlock(aAST)) { // Handle the serialVersionUID and serialPersistentFields constants // which are used for Serialization. Cannot enforce rules on it. :-) final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT); if ((nameAST != null) && !("serialVersionUID".equals(nameAST.getText())) && !("serialPersistentFields".equals(nameAST.getText()))) { retVal = true; } } return retVal; } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/LocalFinalVariableNameCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/LocalFinalVariableNameCh100644 0 0 5430 12026051015 31234 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that local final variable names conform to a format specified * by the format property. A catch parameter is considered to be * a local variable.The format is a * {@link java.util.regex.Pattern regular expression} and defaults to * ^[a-z][a-zA-Z0-9]*$. *

*

* An example of how to configure the check is: *

*
 * <module name="LocalFinalVariableName"/>
 * 
*

* An example of how to configure the check for names that are only upper case * letters and digits is: *

*
 * <module name="LocalFinalVariableName">
 *    <property name="format" value="^[A-Z][A-Z0-9]*$"/>
 * </module>
 * 
* * @author Rick Giles * @version 1.0 */ public class LocalFinalVariableNameCheck extends AbstractNameCheck { /** Creates a new LocalFinalVariableNameCheck instance. */ public LocalFinalVariableNameCheck() { super("^[a-z][a-zA-Z0-9]*$"); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.VARIABLE_DEF, TokenTypes.PARAMETER_DEF, }; } @Override protected final boolean mustCheckName(DetailAST aAST) { final DetailAST modifiersAST = aAST.findFirstToken(TokenTypes.MODIFIERS); final boolean isFinal = (modifiersAST != null) && modifiersAST.branchContains(TokenTypes.FINAL); return (isFinal && ScopeUtils.isLocalVariableDef(aAST)); } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/LocalVariableNameCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/LocalVariableNameCheck.j100644 0 0 5464 12026051015 31204 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that local, non-final variable names conform to a format specified * by the format property. A catch parameter is considered to be * a local variable. The format is a * {@link java.util.regex.Pattern regular expression} * and defaults to * ^[a-z][a-zA-Z0-9]*$. *

*

* An example of how to configure the check is: *

*
 * <module name="LocalVariableName"/>
 * 
*

* An example of how to configure the check for names that begin with a lower * case letter, followed by letters, digits, and underscores is: *

*
 * <module name="LocalVariableName">
 *    <property name="format" value="^[a-z](_?[a-zA-Z0-9]+)*$"/>
 * </module>
 * 
* @author Rick Giles * @version 1.0 */ public class LocalVariableNameCheck extends AbstractNameCheck { /** Creates a new LocalVariableNameCheck instance. */ public LocalVariableNameCheck() { super("^[a-z][a-zA-Z0-9]*$"); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.VARIABLE_DEF, TokenTypes.PARAMETER_DEF, }; } @Override protected final boolean mustCheckName(DetailAST aAST) { final DetailAST modifiersAST = aAST.findFirstToken(TokenTypes.MODIFIERS); final boolean isFinal = (modifiersAST != null) && modifiersAST.branchContains(TokenTypes.FINAL); return (!isFinal && ScopeUtils.isLocalVariableDef(aAST)); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/MemberNameCheck.java100644 0 0 5445 12026051015 30402 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that instance variable names conform to a format specified * by the format property. The format is a * {@link java.util.regex.Pattern regular expression} * and defaults to * ^[a-z][a-zA-Z0-9]*$. *

*

* An example of how to configure the check is: *

*
 * <module name="MemberName"/>
 * 
*

* An example of how to configure the check for names that begin with * "m", followed by an upper case letter, and then letters and * digits is: *

*
 * <module name="MemberName">
 *    <property name="format" value="^m[A-Z][a-zA-Z0-9]*$"/>
 * </module>
 * 
* @author Rick Giles * @version 1.0 */ public class MemberNameCheck extends AbstractAccessControlNameCheck { /** Creates a new MemberNameCheck instance. */ public MemberNameCheck() { super("^[a-z][a-zA-Z0-9]*$"); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.VARIABLE_DEF}; } @Override protected final boolean mustCheckName(DetailAST aAST) { final DetailAST modifiersAST = aAST.findFirstToken(TokenTypes.MODIFIERS); final boolean isStatic = (modifiersAST != null) && modifiersAST.branchContains(TokenTypes.LITERAL_STATIC); return (!isStatic && !ScopeUtils.inInterfaceOrAnnotationBlock(aAST) && !ScopeUtils.isLocalVariableDef(aAST)) && shouldCheckInScope(modifiersAST); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/messages.properties100644 0 0 454 11452563037 30507 0ustar 0 0 name.invalidPattern=Name ''{0}'' must match pattern ''{1}''. illegal.abstract.class.name=Name ''{0}'' must match pattern ''{1}''. method.name.equals.class.name=Method Name ''{0}'' must not equal the enclosing class name. no.abstract.class.modifier=Class ''{0}'' must be declared as ''abstract''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/messages_de.properties100644 0 0 230 11451071613 31140 0ustar 0 0 illegal.abstract.class.name=Klassenname ''{0}'' entspricht nicht dem Muster ''{1}''. name.invalidPattern=''{0}'' entspricht nicht dem Muster ''{1}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/messages_es.properties100644 0 0 242 11451071613 31162 0ustar 0 0 name.invalidPattern=El nombre ''{0}'' debe coincidir con el patrón ''{1}''. illegal.abstract.class.name=El nombre ''{0}'' debe coincidir con el patrón ''{1}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/messages_fi.properties100644 0 0 232 11451071613 31150 0ustar 0 0 name.invalidPattern=Nimen ''{0}'' pit¤¤ olla mallin ''{1}'' mukainen. illegal.abstract.class.name=Nimen ''{0}'' pit¤¤ olla mallin ''{1}'' mukainen. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/messages_fr.properties100644 0 0 301 11451071613 31156 0ustar 0 0 name.invalidPattern=Le nom ''{0}'' n''est pas conforme à l''expression ''{1}''. illegal.abstract.class.name=Le nom de la classe abstraite ''{0}'' n''est pas conforme à l''expression ''{1}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/messages_ja.properties100644 0 0 524 11451071613 31150 0ustar 0 0 name.invalidPattern=\u540d\u524d ''{0}'' \u306f\u30d1\u30bf\u30fc\u30f3 ''{1}'' \u306b\u4e00\u81f4\u3057\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002 illegal.abstract.class.name=\u540d\u524d ''{0}'' \u306f\u30d1\u30bf\u30fc\u30f3 ''{1}'' \u306b\u4e00\u81f4\u3057\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/messages_pt.properties100644 0 0 224 11451071613 31176 0ustar 0 0 illegal.abstract.class.name=Nome ''{0}'' deve condizer com o padro ''{1}''. name.invalidPattern=Nome ''{0}'' deve condizer com o padro ''{1}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/messages_tr.properties100644 0 0 725 11744664014 31216 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) illegal.abstract.class.name = ''{0}'' ismi, \u015Fu kal\u0131pta olmal\u0131: ''{1}''. method.name.equals.class.name = ''{0}'' metodunun ad\u0131 kendini kapsayan t\u00FCr ile ayn\u0131 olmamal\u0131. name.invalidPattern = ''{0}'' ismi, \u015Fu kal\u0131pta olmal\u0131: ''{1}''. no.abstract.class.modifier = ''{0}'' s\u0131n\u0131f\u0131 ''abstract'' olarak tan\u0131mlanmal\u0131. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheck.java100644 0 0 10776 12026051015 30436 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that method names conform to a format specified * by the format property. The format is a * {@link java.util.regex.Pattern regular expression} * and defaults to * ^[a-z][a-zA-Z0-9]*$. *

* *

* Also, checks if a method name has the same name as the residing class. * The default is false (it is not allowed). It is legal in Java to have * method with the same name as a class. As long as a return type is specified * it is a method and not a constructor which it could be easily confused as. *

* *

* An example of how to configure the check is: *

*
 * <module name="MethodName"/>
 * 
*

* An example of how to configure the check for names that begin with * a lower case letter, followed by letters, digits, and underscores is: *

*
 * <module name="MethodName">
 *    <property name="format" value="^[a-z](_?[a-zA-Z0-9]+)*$"/>
 * </module>
 * 
* *

* An example of how to configure the check to allow method names * to be equal to the residing class name is: *

*
 * <module name="MethodName">
 *    <property name="allowClassName" value="true"/>
 * </module>
 * 
* @author Oliver Burn * @author Travis Schneeberger * @version 1.1 */ public class MethodNameCheck extends AbstractAccessControlNameCheck { /** * for allowing method name to be the same as the class name. */ private boolean mAllowClassName; /** Creates a new MethodNameCheck instance. */ public MethodNameCheck() { super("^[a-z][a-zA-Z0-9]*$"); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.METHOD_DEF, }; } @Override public void visitToken(DetailAST aAst) { super.visitToken(aAst); // Will check the name against the format. if (!mAllowClassName) { final DetailAST method = aAst.findFirstToken(TokenTypes.IDENT); //in all cases this will be the classDef type except anon inner //with anon inner classes this will be the Literal_New keyword final DetailAST classDefOrNew = aAst.getParent().getParent(); final DetailAST classIdent = classDefOrNew.findFirstToken(TokenTypes.IDENT); // Following logic is to handle when a classIdent can not be // found. This is when you have a Literal_New keyword followed // a DOT, which is when you have: // new Outclass.InnerInterface(x) { ... } // Such a rare case, will not have the logic to handle parsing // down the tree looking for the first ident. if ((null != classIdent) && method.getText().equals(classIdent.getText())) { log(method.getLineNo(), method.getColumnNo(), "method.name.equals.class.name", method.getText()); } } } /** * Sets the property for allowing a method to be the same name as a class. * @param aAllowClassName true to allow false to disallow */ public void setAllowClassName(boolean aAllowClassName) { mAllowClassName = aAllowClassName; } } ././@LongLink100644 0 0 156 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/MethodTypeParameterNameCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/MethodTypeParameterNameC100644 0 0 4236 12026051014 31337 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that class type parameter names conform to a format specified * by the format property. The format is a * {@link java.util.regex.Pattern regular expression} and defaults to * ^[A-Z]$. *

*

* An example of how to configure the check is: *

*
 * <module name="MethodTypeParameterName"/>
 * 
*

* An example of how to configure the check for names that are only a single * letter is *

*
 * <module name="MethodTypeParameterName">
 *    <property name="format" value="^[a-zA-Z]$"/>
 * </module>
 * 
* * @author Travis Schneeberger * @version 1.0 */ public class MethodTypeParameterNameCheck extends AbstractTypeParameterNameCheck { /** Creates a new MethodTypeParameterNameCheck instance. */ public MethodTypeParameterNameCheck() { super("^[A-Z]$"); } @Override protected final int getLocation() { return TokenTypes.METHOD_DEF; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/package-info.java100644 0 0 2313 12026051013 27745 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the Naming conventions checks * that are bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks.naming; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/PackageNameCheck.java100644 0 0 6742 12026051014 30526 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck; /** *

* Checks that package names conform to a format specified * by the format property. The format is a * {@link java.util.regex.Pattern regular expression} * and defaults to * ^[a-z]+(\.[a-zA-Z_][a-zA-Z_0-9]*)*$. *

*

* The default format has been chosen to match the requirements in the * * Java Language specification and the Sun coding conventions. * However both underscores and uppercase letters are rather uncommon, * so most projects should probably use * ^[a-z]+(\.[a-z][a-z0-9]*)*$. *

*

* An example of how to configure the check is: *

*
 * <module name="PackageName"/>
 * 
*

* An example of how to configure the check for package names that begin with * com.puppycrawl.tools.checkstyle is: *

*
 * <module name="PackageName">
 *    <property name="format"
 *              value="^com\.puppycrawl\.tools\.checkstyle(\\.[a-zA-Z_][a-zA-Z_0-9]*)*$"/>
 * </module>
 * 
* * @author Oliver Burn * @version 1.0 */ public class PackageNameCheck extends AbstractFormatCheck { /** * Creates a new PackageNameCheck instance. */ public PackageNameCheck() { // Uppercase letters seem rather uncommon, but they're allowed in // http://java.sun.com/docs/books/jls/ // second_edition/html/packages.doc.html#40169 super("^[a-z]+(\\.[a-zA-Z_][a-zA-Z0-9_]*)*$"); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.PACKAGE_DEF}; } @Override public void visitToken(DetailAST aAST) { final DetailAST nameAST = aAST.getLastChild().getPreviousSibling(); final FullIdent full = FullIdent.createFullIdent(nameAST); if (!getRegexp().matcher(full.getText()).find()) { log(full.getLineNo(), full.getColumnNo(), "name.invalidPattern", full.getText(), getFormat()); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/ParameterNameCheck.java100644 0 0 4712 12026051014 31106 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that parameter names conform to a format specified * by the format property. The format is a * {@link java.util.regex.Pattern regular expression} * and defaults to * ^[a-z][a-zA-Z0-9]*$. *

*

* An example of how to configure the check is: *

*
 * <module name="ParameterName"/>
 * 
*

* An example of how to configure the check for names that begin with * a lower case letter, followed by letters, digits, and underscores is: *

*
 * <module name="ParameterName">
 *    <property name="format" value="^^[a-z](_?[a-zA-Z0-9]+)*$"/>
 * </module>
 * 
* * @author Oliver Burn */ public class ParameterNameCheck extends AbstractNameCheck { /** * Creates a new ParameterNameCheck instance. */ public ParameterNameCheck() { super("^[a-z][a-zA-Z0-9]*$"); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.PARAMETER_DEF}; } @Override protected boolean mustCheckName(DetailAST aAST) { return !( (aAST.getParent() != null) && (aAST.getParent().getType() == TokenTypes.LITERAL_CATCH)); } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/StaticVariableNameCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/StaticVariableNameCheck.100644 0 0 5670 12026051014 31225 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that static, non-final variable names conform to a format specified * by the format property. The format is a * {@link java.util.regex.Pattern regular expression} and defaults to * ^[a-z][a-zA-Z0-9]*$. *

*

* An example of how to configure the check is: *

*
 * <module name="StaticVariableName"/>
 * 
*

* An example of how to configure the check for names that begin with * a lower case letter, followed by letters, digits, and underscores is: *

*
 * <module name="StaticVariableName">
 *    <property name="format" value="^[a-z](_?[a-zA-Z0-9]+)*$"/>
 * </module>
 * 
* @author Rick Giles * @version 1.0 */ public class StaticVariableNameCheck extends AbstractAccessControlNameCheck { /** Creates a new StaticVariableNameCheck instance. */ public StaticVariableNameCheck() { super("^[a-z][a-zA-Z0-9]*$"); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.VARIABLE_DEF}; } @Override protected final boolean mustCheckName(DetailAST aAST) { final DetailAST modifiersAST = aAST.findFirstToken(TokenTypes.MODIFIERS); final boolean isStatic = (modifiersAST != null) && modifiersAST.branchContains(TokenTypes.LITERAL_STATIC); final boolean isFinal = (modifiersAST != null) && modifiersAST.branchContains(TokenTypes.FINAL); return (isStatic && !isFinal && shouldCheckInScope(modifiersAST) && !ScopeUtils.inInterfaceOrAnnotationBlock(aAST)); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/naming/TypeNameCheck.java100644 0 0 4352 12026051014 30107 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that type names conform to a format specified * by the format property. The format is a * {@link java.util.regex.Pattern regular expression} and defaults to * ^[A-Z][a-zA-Z0-9]*$. *

*

* An example of how to configure the check is: *

*
 * <module name="TypeName"/>
 * 
*

* An example of how to configure the check for names that begin with * a lower case letter, followed by letters, digits, and underscores is: *

*
 * <module name="TypeName">
 *    <property name="format" value="^[a-z](_?[a-zA-Z0-9]+)*$"/>
 * </module>
 * 
* @author Oliver Burn */ public class TypeNameCheck extends AbstractAccessControlNameCheck { /** * Creates a new TypeNameCheck instance. */ public TypeNameCheck() { super("^[A-Z][a-zA-Z0-9]*$"); } /** {@inheritDoc} */ @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, }; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheck.java100644 0 0 11146 12026051062 30540 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import com.puppycrawl.tools.checkstyle.api.Utils; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.List; import org.apache.commons.beanutils.ConversionException; /** *

* Checks that there is a newline at the end of each file. *

*

* An example of how to configure the check is: *

*
 * <module name="NewlineAtEndOfFile"/>
*

* This will check against the platform-specific default line separator. *

*

* It is also possible to enforce the use of a specific line-separator across * platforms, with the 'lineSeparator' property: *

*
 * <module name="NewlineAtEndOfFile">
 *   <property name="lineSeparator" value="lf"/>
 * </module>
*

* Valid values for the 'lineSeparator' property are 'system' (system default), * 'crlf' (windows), 'cr' (mac) and 'lf' (unix). *

* * @author Christopher Lenz * @author lkuehne * @version 1.0 */ public class NewlineAtEndOfFileCheck extends AbstractFileSetCheck { /** the line separator to check against. */ private LineSeparatorOption mLineSeparator = LineSeparatorOption.SYSTEM; @Override protected void processFiltered(File aFile, List aLines) { // Cannot use aLines as the line separators have been removed! RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(aFile, "r"); if (!endsWithNewline(randomAccessFile)) { log(0, "noNewlineAtEOF", aFile.getPath()); } } catch (final IOException e) { log(0, "unable.open", aFile.getPath()); } finally { Utils.closeQuietly(randomAccessFile); } } /** * Sets the line separator to one of 'crlf', 'lf' or 'cr'. * * @param aLineSeparator The line separator to set * @throws IllegalArgumentException If the specified line separator is not * one of 'crlf', 'lf' or 'cr' */ public void setLineSeparator(String aLineSeparator) { try { mLineSeparator = Enum.valueOf(LineSeparatorOption.class, aLineSeparator.trim() .toUpperCase()); } catch (IllegalArgumentException iae) { throw new ConversionException("unable to parse " + aLineSeparator, iae); } } /** * Checks whether the content provided by the Reader ends with the platform * specific line separator. * @param aRandomAccessFile The reader for the content to check * @return boolean Whether the content ends with a line separator * @throws IOException When an IO error occurred while reading from the * provided reader */ private boolean endsWithNewline(RandomAccessFile aRandomAccessFile) throws IOException { final int len = mLineSeparator.length(); if (aRandomAccessFile.length() < len) { return false; } aRandomAccessFile.seek(aRandomAccessFile.length() - len); final byte lastBytes[] = new byte[len]; final int readBytes = aRandomAccessFile.read(lastBytes); if (readBytes != len) { throw new IOException("Unable to read " + len + " bytes, got " + readBytes); } return mLineSeparator.matches(lastBytes); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/OuterTypeFilenameCheck.java100644 0 0 5160 12026051062 30516 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.io.File; /** * Checks that the outer type name and the file name match. * @author Oliver Burn */ public class OuterTypeFilenameCheck extends Check { /** indicates whether the first token has been seen in the file. */ private boolean mSeenFirstToken; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.ENUM_DEF, TokenTypes.ANNOTATION_DEF, }; } @Override public void beginTree(DetailAST aAST) { mSeenFirstToken = false; } @Override public void visitToken(DetailAST aAST) { // Only check first declaration if (mSeenFirstToken) { return; } mSeenFirstToken = true; final String outerTypeName = aAST.findFirstToken(TokenTypes.IDENT).getText(); // Calculate the file name without the leading path or // the trailing .java suffix. Will be lax and just remove whatever // is after the '.' character. String fname = getFileContents().getFilename(); fname = fname.substring(fname.lastIndexOf(File.separatorChar) + 1); fname = fname.replaceAll("\\.[^\\.]*$", ""); if (!(fname.equals(outerTypeName))) { log(aAST.getLineNo(), "type.file.mismatch"); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/package-info.java100644 0 0 2211 12026051013 26471 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the checks that are bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/CommentSuppressor.java100644 0 0 3730 12026051013 31156 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; import com.puppycrawl.tools.checkstyle.api.FileContents; /** * Implementation of a {@link MatchSuppressor} that suppresses based on * whether in a comment. * @author Oliver Burn */ class CommentSuppressor implements MatchSuppressor { /** File contents to check for comments. */ private FileContents mCurrentContents; /** {@inheritDoc} */ public boolean shouldSuppress(int aStartLineNo, int aStartColNo, int aEndLineNo, int aEndColNo) { return (null != mCurrentContents) && mCurrentContents.hasIntersectionWithComment(aStartLineNo, aStartColNo, aEndLineNo, aEndColNo); } /** * Set the current file contents. * @param aCurrentContents the new contents. */ public void setCurrentContents(FileContents aCurrentContents) { mCurrentContents = aCurrentContents; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/DetectorOptions.java100644 0 0 13470 12026051013 30615 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; import com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.regex.Pattern; /** * Options for a detector. * @author Oliver Burn */ class DetectorOptions { /** * Flags to compile a regular expression with. * See {@link Pattern#flags()}. */ private final int mCompileFlags; /** Used for reporting violations. */ private final AbstractViolationReporter mReporter; /** Format of the regular expression to check for. */ private String mFormat; /** The message to report on detection. If blank, then use the format. */ private String mMessage = ""; /** Minimum number of times regular expression should occur in a file. */ private int mMinimum; /** Maximum number of times regular expression should occur in a file. */ private int mMaximum; /** Whether to ignore case when matching. */ private boolean mIgnoreCase; /** Used to determine whether to suppress a detected match. */ private MatchSuppressor mSuppressor = NeverSuppress.INSTANCE; /** * Creates an instance. * @param aCompileFlags the flags to create the regular expression with. * @param aReporter used to report violations. */ public DetectorOptions(int aCompileFlags, AbstractViolationReporter aReporter) { mCompileFlags = aCompileFlags; mReporter = aReporter; } /** * The format to use when matching lines. * @param aFormat the format to use when matching lines. * @return current instance */ public DetectorOptions setFormat(String aFormat) { mFormat = aFormat; return this; } /** * Message to use when reporting a match. * @param aMessage message to use when reporting a match. * @return current instance. */ public DetectorOptions setMessage(String aMessage) { mMessage = aMessage; return this; } /** * Set the minimum allowed number of detections. * @param aMinimum the minimum allowed number of detections. * @return current instance */ public DetectorOptions setMinimum(int aMinimum) { mMinimum = aMinimum; return this; } /** * Set the maximum allowed number of detections. * @param aMaximum the maximum allowed number of detections. * @return current instance */ public DetectorOptions setMaximum(int aMaximum) { mMaximum = aMaximum; return this; } /** * Set the suppressor to use. * @param aSup the suppressor to use. * @return current instance */ public DetectorOptions setSuppressor(MatchSuppressor aSup) { mSuppressor = aSup; return this; } /** * Set whether to ignore case when matching. * @param aIgnore whether to ignore case when matching. * @return current instance */ public DetectorOptions setIgnoreCase(boolean aIgnore) { mIgnoreCase = aIgnore; return this; } /** * Format of the regular expression. * @return format of the regular expression. */ public String getFormat() { return mFormat; } /** * The violation reporter to use. * @return the violation reporter to use. */ public AbstractViolationReporter getReporter() { return mReporter; } /** * The message to report errors with. * @return the message to report errors with. */ public String getMessage() { return mMessage; } /** * The minimum number of allowed detections. * @return the minimum number of allowed detections. */ public int getMinimum() { return mMinimum; } /** * The maximum number of allowed detections. * @return the maximum number of allowed detections. */ public int getMaximum() { return mMaximum; } /** * The suppressor to use. * @return the suppressor to use. */ public MatchSuppressor getSuppressor() { return mSuppressor; } /** * Whether to ignore case when matching. * @return whether to ignore case when matching. */ public boolean isIgnoreCase() { return mIgnoreCase; } /** * The pattern to use when matching. * @return the pattern to use when matching. */ public Pattern getPattern() { final int options = (mIgnoreCase) ? mCompileFlags | Pattern.CASE_INSENSITIVE : mCompileFlags; return Utils.getPattern(mFormat, options); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/MatchSuppressor.java100644 0 0 3166 12026051012 30612 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; /** * Represents a suppressor for matches. * @author oliver */ interface MatchSuppressor { /** * Checks if the specified selection should be suppressed. * @param aStartLineNo the starting line number * @param aStartColNo the starting column number * @param aEndLineNo the ending line number * @param aEndColNo the ending column number * @return true if the positions intersects with a comment. **/ boolean shouldSuppress(int aStartLineNo, int aStartColNo, int aEndLineNo, int aEndColNo); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/messages.properties100644 0 0 213 11451071613 30512 0ustar 0 0 regexp.exceeded=Line matches the illegal pattern ''{0}''. regexp.minimum=File does not contain at least {0} matches for pattern ''{1}''. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/messages_tr.properties100644 0 0 423 11744664014 31232 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) regexp.exceeded = Sat\u0131r, ge\u00E7ersiz ''{0}'' kal\u0131b\u0131yla e\u015Fle\u015Fiyor. regexp.minimum = Dosya, ''{1}'' kal\u0131b\u0131 i\u00E7in en az {0} e\u015Fle\u015Fme i\u00E7ermiyor. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/MultilineDetector.java100644 0 0 7331 12026051012 31102 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; import java.util.regex.Matcher; import com.puppycrawl.tools.checkstyle.api.FileText; import com.puppycrawl.tools.checkstyle.api.LineColumn; /** * A detector that matches across multiple lines. * @author oliver */ class MultilineDetector { /** The detection options to use. */ private final DetectorOptions mOptions; /** Tracks the number of matches. */ private int mCurrentMatches; /** The mMatcher */ private Matcher mMatcher; /** The file text content */ private FileText mText; /** * Creates an instance. * @param aOptions the options to use. */ public MultilineDetector(DetectorOptions aOptions) { mOptions = aOptions; } /** * Processes an entire text file looking for matches. * @param aText the text to process */ public void processLines(FileText aText) { mText = aText; resetState(); mMatcher = mOptions.getPattern().matcher(mText.getFullText()); findMatch(); finish(); } /** recursive method that finds the matches. */ private void findMatch() { final boolean foundMatch = mMatcher.find(); if (!foundMatch) { return; } final LineColumn start = mText.lineColumn(mMatcher.start()); final LineColumn end = mText.lineColumn(mMatcher.end()); if (!mOptions.getSuppressor().shouldSuppress(start.getLine(), start.getColumn(), end.getLine(), end.getColumn())) { mCurrentMatches++; if (mCurrentMatches > mOptions.getMaximum()) { if ("".equals(mOptions.getMessage())) { mOptions.getReporter().log(start.getLine(), "regexp.exceeded", mMatcher.pattern().toString()); } else { mOptions.getReporter() .log(start.getLine(), mOptions.getMessage()); } } } findMatch(); } /** Perform processing at the end of a set of lines. */ private void finish() { if (mCurrentMatches < mOptions.getMinimum()) { if ("".equals(mOptions.getMessage())) { mOptions.getReporter().log(0, "regexp.minimum", mOptions.getMinimum(), mOptions.getFormat()); } else { mOptions.getReporter().log(0, mOptions.getMessage()); } } } /** * Reset the state of the detector. */ private void resetState() { mCurrentMatches = 0; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/NeverSuppress.java100644 0 0 3147 12026051012 30273 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; /** * An implementation of {@link MatchSuppressor} that never suppresses a * match. * @author oliver */ public final class NeverSuppress implements MatchSuppressor { /** The shared instance. */ public static final MatchSuppressor INSTANCE = new NeverSuppress(); /** Stop creation of instances. */ private NeverSuppress() { } /** {@inheritDoc} */ public boolean shouldSuppress(int aStartLineNo, int aStartColNo, int aEndLineNo, int aEndColNo) { return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/package-info.java100644 0 0 2247 12026051011 27772 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the regular expression checks that are bundled with the main * distribution. */ package com.puppycrawl.tools.checkstyle.checks.regexp; ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpMultilineCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpMultilineCheck.jav100644 0 0 6273 12026051012 31364 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; import java.util.regex.Pattern; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import com.puppycrawl.tools.checkstyle.api.FileText; import java.io.File; import java.util.List; /** * Implementation of a check that looks that matches across multiple lines in * any file type. * @author Oliver Burn */ public class RegexpMultilineCheck extends AbstractFileSetCheck { /** The detection options to use. */ private DetectorOptions mOptions = new DetectorOptions(Pattern.MULTILINE, this); /** The detector to use. */ private MultilineDetector mDetector; @Override public void beginProcessing(String aCharset) { super.beginProcessing(aCharset); mDetector = new MultilineDetector(mOptions); } @Override protected void processFiltered(File aFile, List aLines) { mDetector.processLines(FileText.fromLines(aFile, aLines)); } /** * Set the format of the regular expression to match. * @param aFormat the format of the regular expression to match. */ public void setFormat(String aFormat) { mOptions.setFormat(aFormat); } /** * Set the message to report for a match. * @param aMessage the message to report for a match. */ public void setMessage(String aMessage) { mOptions.setMessage(aMessage); } /** * Set the minimum number of matches required per file. * @param aMinimum the minimum number of matches required per file. */ public void setMinimum(int aMinimum) { mOptions.setMinimum(aMinimum); } /** * Set the maximum number of matches required per file. * @param aMaximum the maximum number of matches required per file. */ public void setMaximum(int aMaximum) { mOptions.setMaximum(aMaximum); } /** * Set whether to ignore case when matching. * @param aIgnore whether to ignore case when matching. */ public void setIgnoreCase(boolean aIgnore) { mOptions.setIgnoreCase(aIgnore); } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineCheck.ja100644 0 0 6030 12026051012 31314 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import java.io.File; import java.util.List; /** * Implementation of a check that looks for a single line in any file type. * @author Oliver Burn */ public class RegexpSinglelineCheck extends AbstractFileSetCheck { /** The detection options to use. */ private DetectorOptions mOptions = new DetectorOptions(0, this); /** The detector to use. */ private SinglelineDetector mDetector; @Override public void beginProcessing(String aCharset) { super.beginProcessing(aCharset); mDetector = new SinglelineDetector(mOptions); } @Override protected void processFiltered(File aFile, List aLines) { mDetector.processLines(aLines); } /** * Set the format of the regular expression to match. * @param aFormat the format of the regular expression to match. */ public void setFormat(String aFormat) { mOptions.setFormat(aFormat); } /** * Set the message to report for a match. * @param aMessage the message to report for a match. */ public void setMessage(String aMessage) { mOptions.setMessage(aMessage); } /** * Set the minimum number of matches required per file. * @param aMinimum the minimum number of matches required per file. */ public void setMinimum(int aMinimum) { mOptions.setMinimum(aMinimum); } /** * Set the maximum number of matches required per file. * @param aMaximum the maximum number of matches required per file. */ public void setMaximum(int aMaximum) { mOptions.setMaximum(aMaximum); } /** * Set whether to ignore case when matching. * @param aIgnore whether to ignore case when matching. */ public void setIgnoreCase(boolean aIgnore) { mOptions.setIgnoreCase(aIgnore); } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaChec100644 0 0 7237 12026051012 31364 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import java.util.Arrays; /** * Implementation of a check that looks for a single line in Java files. * Supports ignoring comments for matches. * @author Oliver Burn */ public class RegexpSinglelineJavaCheck extends Check { /** The detection options to use. */ private DetectorOptions mOptions = new DetectorOptions(0, this); /** The detector to use. */ private SinglelineDetector mDetector; /** The suppressor to use. */ private final CommentSuppressor mSuppressor = new CommentSuppressor(); @Override public int[] getDefaultTokens() { return new int[0]; } @Override public void init() { super.init(); mDetector = new SinglelineDetector(mOptions); } @Override public void beginTree(DetailAST aRootAST) { mSuppressor.setCurrentContents(getFileContents()); mDetector.processLines(Arrays.asList(getLines())); } /** * Set the format of the regular expression to match. * @param aFormat the format of the regular expression to match. */ public void setFormat(String aFormat) { mOptions.setFormat(aFormat); } /** * Set the message to report for a match. * @param aMessage the message to report for a match. */ public void setMessage(String aMessage) { mOptions.setMessage(aMessage); } /** * Set the minimum number of matches required per file. * @param aMinimum the minimum number of matches required per file. */ public void setMinimum(int aMinimum) { mOptions.setMinimum(aMinimum); } /** * Set the maximum number of matches required per file. * @param aMaximum the maximum number of matches required per file. */ public void setMaximum(int aMaximum) { mOptions.setMaximum(aMaximum); } /** * Set whether to ignore case when matching. * @param aIgnore whether to ignore case when matching. */ public void setIgnoreCase(boolean aIgnore) { mOptions.setIgnoreCase(aIgnore); } /** * Set whether to ignore comments when matching. * @param aIgnore whether to ignore comments when matching. */ public void setIgnoreComments(boolean aIgnore) { if (aIgnore) { mOptions.setSuppressor(mSuppressor); } else { mOptions.setSuppressor(NeverSuppress.INSTANCE); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/regexp/SinglelineDetector.java100644 0 0 10321 12026051011 31241 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; import java.util.List; import java.util.regex.Matcher; /** * A detector that matches individual lines. * @author oliver */ class SinglelineDetector { /** The detection options to use. */ private final DetectorOptions mOptions; /** Tracks the number of matches. */ private int mCurrentMatches; /** * Creates an instance. * @param aOptions the options to use. */ public SinglelineDetector(DetectorOptions aOptions) { mOptions = aOptions; } /** * Processes a set of lines looking for matches. * @param aLines the lines to process. */ public void processLines(List aLines) { resetState(); int lineno = 0; for (String line : aLines) { lineno++; checkLine(lineno, line, mOptions.getPattern().matcher(line), 0); } finish(); } /** Perform processing at the end of a set of lines. */ private void finish() { if (mCurrentMatches < mOptions.getMinimum()) { if ("".equals(mOptions.getMessage())) { mOptions.getReporter().log(0, "regexp.minimum", mOptions.getMinimum(), mOptions.getFormat()); } else { mOptions.getReporter().log(0, mOptions.getMessage()); } } } /** * Reset the state of the detector. */ private void resetState() { mCurrentMatches = 0; } /** * Check a line for matches. * @param aLineno the line number of the line to check * @param aLine the line to check * @param aMatcher the matcher to use * @param aStartPosition the position to start searching from. */ private void checkLine(int aLineno, String aLine, Matcher aMatcher, int aStartPosition) { final boolean foundMatch = aMatcher.find(aStartPosition); if (!foundMatch) { return; } // match is found, check for intersection with comment final int startCol = aMatcher.start(0); final int endCol = aMatcher.end(0); // Note that Matcher.end(int) returns the offset AFTER the // last matched character, but shouldSuppress() // needs column number of the last character. // So we need to use (endCol - 1) here. if (mOptions.getSuppressor() .shouldSuppress(aLineno, startCol, aLineno, endCol - 1)) { if (endCol < aLine.length()) { // check if the expression is on the rest of the line checkLine(aLineno, aLine, aMatcher, endCol); } return; // end processing here } mCurrentMatches++; if (mCurrentMatches > mOptions.getMaximum()) { if ("".equals(mOptions.getMessage())) { mOptions.getReporter().log(aLineno, "regexp.exceeded", aMatcher.pattern().toString()); } else { mOptions.getReporter().log(aLineno, mOptions.getMessage()); } } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/RegexpCheck.java100644 0 0 20313 12026051061 26363 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** *

* A check that makes sure that a specified pattern exists (or not) in the file. *

*

* An example of how to configure the check to make sure a copyright statement * is included in the file (but without requirements on where in the file * it should be): *

*
 * <module name="RequiredRegexp">
 *    <property name="format" value="This code is copyrighted"/>
 * </module>
 * 
*

* And to make sure the same statement appears at the beginning of the file. *

*
 * <module name="RequiredRegexp">
 *    <property name="format" value="\AThis code is copyrighted"/>
 * </module>
 * 
* @author Stan Quinn */ public class RegexpCheck extends AbstractFormatCheck { /** Default duplicate limit */ private static final int DEFAULT_DUPLICATE_LIMIT = -1; /** Default error report limit */ private static final int DEFAULT_ERROR_LIMIT = 100; /** Error count exceeded message */ private static final String ERROR_LIMIT_EXCEEDED_MESSAGE = "The error limit has been exceeded, " + "the check is aborting, there may be more unreported errors."; /** Custom message for report. */ private String mMessage = ""; /** Ignore matches within comments? **/ private boolean mIgnoreComments; /** Pattern illegal? */ private boolean mIllegalPattern; /** Error report limit */ private int mErrorLimit = DEFAULT_ERROR_LIMIT; /** Disallow more than x duplicates? */ private int mDuplicateLimit; /** Boolean to say if we should check for duplicates. */ private boolean mCheckForDuplicates; /** Tracks number of matches made */ private int mMatchCount; /** Tracks number of errors */ private int mErrorCount; /** Relates StringBuffer positions to line # and column */ private final List mCharacters = Lists.newArrayList(); /** The mMatcher */ private Matcher mMatcher; /** * Instantiates an new RegexpCheck. */ public RegexpCheck() { super("$^", Pattern.MULTILINE); // the empty language } /** * Setter for message property. * @param aMessage custom message which should be used in report. */ public void setMessage(String aMessage) { mMessage = (aMessage == null) ? "" : aMessage; } /** * Getter for message property. * I'm not sure if this gets used by anything outside, * I just included it because GenericIllegalRegexp had it, * it's being used in logMessage() so it's covered in EMMA. * @return custom message to be used in report. */ public String getMessage() { return mMessage; } /** * Sets if matches within comments should be ignored. * @param aIgnoreComments True if comments should be ignored. */ public void setIgnoreComments(boolean aIgnoreComments) { mIgnoreComments = aIgnoreComments; } /** * Sets if pattern is illegal, otherwise pattern is required. * @param aIllegalPattern True if pattern is not allowed. */ public void setIllegalPattern(boolean aIllegalPattern) { mIllegalPattern = aIllegalPattern; } /** * Sets the limit on the number of errors to report. * @param aErrorLimit the number of errors to report. */ public void setErrorLimit(int aErrorLimit) { mErrorLimit = aErrorLimit; } /** * Sets the maximum number of instances of required pattern allowed. * @param aDuplicateLimit negative values mean no duplicate checking, * any positive value is used as the limit. */ public void setDuplicateLimit(int aDuplicateLimit) { mDuplicateLimit = aDuplicateLimit; mCheckForDuplicates = (mDuplicateLimit > DEFAULT_DUPLICATE_LIMIT); } @Override public int[] getDefaultTokens() { return new int[0]; } @Override public void beginTree(DetailAST aRootAST) { mCharacters.clear(); final Pattern pattern = getRegexp(); final String[] lines = getLines(); final StringBuffer sb = new StringBuffer(); for (int i = 0; i < lines.length; i++) { sb.append(lines[i]); sb.append('\n'); for (int j = 0; j < (lines[i].length() + 1); j++) { mCharacters.add(new Integer[] {i + 1, j}); } } mMatcher = pattern.matcher(sb.toString()); mMatchCount = 0; mErrorCount = 0; findMatch(); } /** recursive method that finds the matches. */ private void findMatch() { int startLine; int startColumn; int endLine; int endColumn; boolean foundMatch; boolean ignore = false; foundMatch = mMatcher.find(); if (!foundMatch && !mIllegalPattern && (mMatchCount == 0)) { logMessage(0); } else if (foundMatch) { startLine = (mCharacters.get(mMatcher.start()))[0]. intValue(); startColumn = (mCharacters.get(mMatcher.start()))[1]. intValue(); endLine = (mCharacters.get(mMatcher.end() - 1))[0]. intValue(); endColumn = (mCharacters.get(mMatcher.end() - 1))[1]. intValue(); if (mIgnoreComments) { final FileContents theFileContents = getFileContents(); ignore = theFileContents.hasIntersectionWithComment(startLine, startColumn, endLine, endColumn); } if (!ignore) { mMatchCount++; if (mIllegalPattern || (mCheckForDuplicates && ((mMatchCount - 1) > mDuplicateLimit))) { mErrorCount++; logMessage(startLine); } } if ((mErrorCount < mErrorLimit) && (ignore || mIllegalPattern || mCheckForDuplicates)) { findMatch(); } } } /** * Displays the right message. * @param aLineNumber the line number the message relates to. */ private void logMessage(int aLineNumber) { String message = "".equals(getMessage()) ? getFormat() : mMessage; if (mErrorCount >= mErrorLimit) { message = ERROR_LIMIT_EXCEEDED_MESSAGE + message; } if (mIllegalPattern) { log(aLineNumber, "illegal.regexp", message); } else { if (aLineNumber > 0) { log(aLineNumber, "duplicate.regexp", message); } else { log(aLineNumber, "required.regexp", message); } } } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/AnonInnerLengthCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/AnonInnerLengthCheck.java100644 0 0 6344 12026051011 31302 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks for long anonymous inner classes. *

*

* Rationale: If an anonymous inner class becomes very long * it is hard to understand and to see the flow of the method * where the class is defined. Therefore long anonymous inner * classes should usually be refactored into a named inner class. * See also Bloch, Effective Java, p. 93. *

*

* The default maximum anonymous inner class length is 20 lines. * To change the maximum number of lines, set property max. *

*

* An example of how to configure the check is: *

*
 * <module name="AnonInnerLength"/>
 * 
*

* An example of how to configure the check so that it accepts anonymous * inner classes with up to 60 lines is: *

*
 * <module name="AnonInnerLength">
 *    <property name="max" value="60"/>
 * </module>
 * 
* * @author Rob Worth */ public class AnonInnerLengthCheck extends Check { /** default maximum number of lines */ private static final int DEFAULT_MAX = 20; /** maximum number of lines */ private int mMax = DEFAULT_MAX; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.LITERAL_NEW}; } @Override public void visitToken(DetailAST aAST) { final DetailAST openingBrace = aAST.findFirstToken(TokenTypes.OBJBLOCK); if (openingBrace != null) { final DetailAST closingBrace = openingBrace.findFirstToken(TokenTypes.RCURLY); final int length = closingBrace.getLineNo() - openingBrace.getLineNo() + 1; if (length > mMax) { log(aAST.getLineNo(), aAST.getColumnNo(), "maxLen.anonInner", length, mMax); } } } /** * @param aLength the maximum length of an anonymous inner class. */ public void setMax(int aLength) { mMax = aLength; } } ././@LongLink100644 0 0 156 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/ExecutableStatementCountCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/ExecutableStatementCountC100644 0 0 15000 12026051011 31462 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Restricts the number of executable statements to a specified limit * (default = 30). * @author Simon Harris */ public final class ExecutableStatementCountCheck extends Check { /** default threshold */ private static final int DEFAULT_MAX = 30; /** threshold to report error for */ private int mMax; /** Stack of method contexts. */ private final FastStack mContextStack = FastStack.newInstance(); /** Current method context. */ private Context mContext; /** Constructs a ExecutableStatementCountCheck. */ public ExecutableStatementCountCheck() { setMax(DEFAULT_MAX); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CTOR_DEF, TokenTypes.METHOD_DEF, TokenTypes.INSTANCE_INIT, TokenTypes.STATIC_INIT, TokenTypes.SLIST, }; } @Override public int[] getRequiredTokens() { return new int[] {TokenTypes.SLIST}; } /** * Gets the maximum threshold. * @return the maximum threshold. */ public int getMax() { return mMax; } /** * Sets the maximum threshold. * @param aMax the maximum threshold. */ public void setMax(int aMax) { mMax = aMax; } @Override public void beginTree(DetailAST aRootAST) { mContext = null; mContextStack.clear(); } @Override public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: case TokenTypes.INSTANCE_INIT: case TokenTypes.STATIC_INIT: visitMemberDef(aAST); break; case TokenTypes.SLIST: visitSlist(aAST); break; default: throw new IllegalStateException(aAST.toString()); } } @Override public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CTOR_DEF: case TokenTypes.METHOD_DEF: case TokenTypes.INSTANCE_INIT: case TokenTypes.STATIC_INIT: leaveMemberDef(aAST); break; case TokenTypes.SLIST: // Do nothing break; default: throw new IllegalStateException(aAST.toString()); } } /** * Process the start of the member definition. * @param aAST the token representing the member definition. */ private void visitMemberDef(DetailAST aAST) { mContextStack.push(mContext); mContext = new Context(aAST); } /** * Process the end of a member definition. * * @param aAST the token representing the member definition. */ private void leaveMemberDef(DetailAST aAST) { final int count = mContext.getCount(); if (count > getMax()) { log(aAST.getLineNo(), aAST.getColumnNo(), "executableStatementCount", count, getMax()); } mContext = mContextStack.pop(); } /** * Process the end of a statement list. * * @param aAST the token representing the statement list. */ private void visitSlist(DetailAST aAST) { if (mContext != null) { // find member AST for the statement list final DetailAST contextAST = mContext.getAST(); DetailAST parent = aAST.getParent(); while (parent != null) { final int type = parent.getType(); if ((type == TokenTypes.CTOR_DEF) || (type == TokenTypes.METHOD_DEF) || (type == TokenTypes.INSTANCE_INIT) || (type == TokenTypes.STATIC_INIT)) { if (parent == contextAST) { mContext.addCount(aAST.getChildCount() / 2); } break; } parent = parent.getParent(); } } } /** * Class to encapsulate counting information about one member. * @author Simon Harris */ private static class Context { /** Member AST node. */ private final DetailAST mAST; /** Counter for context elements. */ private int mCount; /** * Creates new member context. * @param aAST member AST node. */ public Context(DetailAST aAST) { mAST = aAST; mCount = 0; } /** * Increase count. * @param aCount the count increment. */ public void addCount(int aCount) { mCount += aCount; } /** * Gets the member AST node. * @return the member AST node. */ public DetailAST getAST() { return mAST; } /** * Gets the count. * @return the count. */ public int getCount() { return mCount; } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/FileLengthCheck.java100644 0 0 5143 12026051011 30266 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import java.io.File; import java.util.List; /** *

* Checks for long source files. *

*

* Rationale: If a source file becomes very long it is hard to understand. * Therefore long classes should usually be refactored into several * individual classes that focus on a specific task. *

*

* The default maximum file length is 2000 lines. To change the maximum * number of lines, set property max. *

*

* An example of how to configure the check is: *

*
 * <module name="FileLength"/>
 * 
*

* An example of how to configure the check so that it accepts files with at * most 1500 lines is: *

*
 * <module name="FileLength">
 *    <property name="max" value="1500"/>
 * </module>
 * 
* @author Lars Kühne */ public class FileLengthCheck extends AbstractFileSetCheck { /** default maximum number of lines */ private static final int DEFAULT_MAX_LINES = 2000; /** the maximum number of lines */ private int mMaxFileLength = DEFAULT_MAX_LINES; @Override protected void processFiltered(File aFile, List aLines) { if (aLines.size() > mMaxFileLength) { log(1, "maxLen.file", aLines.size(), mMaxFileLength); } } /** * @param aLength the maximum length of a Java source file */ public void setMax(int aLength) { mMaxFileLength = aLength; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/LineLengthCheck.java100644 0 0 11036 12026051010 30313 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; /** * Checks for long lines. * *

* Rationale: Long lines are hard to read in printouts or if developers * have limited screen space for the source code, e.g. if the IDE displays * additional information like project tree, class hierarchy, etc. *

* *

* Note: Support for the special handling of imports in CheckStyle Version 2 * has been dropped as it is a special case of regexp: The user can set * the ignorePattern to "^import" and achieve the same effect. *

*

* The default maximum allowable line length is 80 characters. To change the * maximum, set property max. *

*

* To ignore lines in the check, set property ignorePattern to a regular * expression for the lines to ignore. *

*

* An example of how to configure the check is: *

*
 * <module name="LineLength"/>
 * 
*

An example of how to configure the check to accept lines up to 120 * characters long is: *

*
 * <module name="LineLength">
 *    <property name="max" value="120"/>
 * </module>
 * 
*

An example of how to configure the check to ignore lines that begin with * " * ", followed by just one word, such as within a Javadoc comment, * is: *

*
 * <module name="LineLength">
 *    <property name="ignorePattern" value="^ *\* *[^ ]+$"/>
 * </module>
 * 
* * @author Lars Kühne */ public class LineLengthCheck extends Check { /** default maximum number of columns in a line */ private static final int DEFAULT_MAX_COLUMNS = 80; /** the maximum number of columns in a line */ private int mMax = DEFAULT_MAX_COLUMNS; /** the regexp when long lines are ignored */ private Pattern mIgnorePattern; /** * Creates a new LineLengthCheck instance. */ public LineLengthCheck() { setIgnorePattern("^$"); } @Override public int[] getDefaultTokens() { return new int[0]; } @Override public void beginTree(DetailAST aRootAST) { final String[] lines = getLines(); for (int i = 0; i < lines.length; i++) { final String line = lines[i]; final int realLength = Utils.lengthExpandedTabs( line, line.length(), getTabWidth()); if ((realLength > mMax) && !mIgnorePattern.matcher(line).find()) { log(i + 1, "maxLineLen", mMax, realLength); } } } /** * @param aLength the maximum length of a line */ public void setMax(int aLength) { mMax = aLength; } /** * Set the ignore pattern. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setIgnorePattern(String aFormat) throws ConversionException { try { mIgnorePattern = Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/messages.properties100644 0 0 2275 11744232233 30411 0ustar 0 0 executableStatementCount=Executable statement count is {0,number,integer} (max allowed is {1,number,integer}). maxLen.file=File length is {0,number,integer} lines (max allowed is {1,number,integer}). maxLen.method=Method length is {0,number,integer} lines (max allowed is {1,number,integer}). maxLen.anonInner=Anonymous inner class length is {0,number,integer} lines (max allowed is {1,number,integer}). maxLineLen=Line is longer than {0,number,integer} characters (found {1,number,integer}). maxOuterTypes=Outer types defined is {0,number,integer} (max allowed is {1,number,integer}). maxParam=More than {0,number,integer} parameters (found {1,number,integer}). too.many.privateMethods=Number of private methods is {0,number,integer} (max allowed is {1,number,integer}). too.many.packageMethods=Number of package methods is {0,number,integer} (max allowed is {1,number,integer}). too.many.protectedMethods=Number of protected methods is {0,number,integer} (max allowed is {1,number,integer}). too.many.publicMethods=Number of public methods is {0,number,integer} (max allowed is {1,number,integer}). too.many.methods=Total number of methods is {0,number,integer} (max allowed is {1,number,integer}). checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/messages_de.properties100644 0 0 1036 11451071613 31051 0ustar 0 0 executableStatementCount=Anzahl ausführbarer Statements ist {0,number,integer} (Obergrenze ist {1,number,integer}). maxLen.file=Datei ist {0,number,integer} Zeilen lang, erlaubt sind höchstens {1,number,integer}. maxLen.method=Methode ist {0,number,integer} Zeilen lang, erlaubt sind höchstens {1,number,integer}. maxLen.anonInner=Anonyme innere Klasse ist {0,number,integer} Zeilen lang, erlaubt sind höchstens ({1,number,integer}. maxLineLen=Zeile länger als {0,number,integer} Zeichen maxParam=Mehr als {0,number,integer} Parameter. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/messages_es.properties100644 0 0 1101 11451071613 31061 0ustar 0 0 executableStatementCount=El número de sentencias ejecutables es {0,number,integer} (máximo permitido es {1,number,integer}). maxLen.file=El tamaño del fichero es {0,number,integer} líneas (máximas permitidas {1,number,integer}). maxLen.method=El tamaño del método es {0,number,integer} líneas (máximas permitidas {1,number,integer}). maxLen.anonInner=El tamaño de la clase interna anónima es {0,number,integer} líneas (máximas permitidas {1,number,integer}). maxLineLen=La línea es mayor de {0,number,integer} caracteres. maxParam=Más de {0,number,integer} parámetros. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/messages_fi.properties100644 0 0 476 11451071613 31046 0ustar 0 0 maxLen.file=Tiedoston pituus on {0,number,integer} rivi¤ (suurin sallittu on {1,number,integer}). maxLen.method=Metodin pituus on {0,number,integer} rivi¤ (suurin sallittu on {1,number,integer}). maxLineLen=Rivi on pidempi kuin {0,number,integer} merkki¤. maxParam=Enemm¤n kuin {0,number,integer} parametri¤. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/messages_fr.properties100644 0 0 1207 11451071613 31070 0ustar 0 0 executableStatementCount=Le nombre d''instructions est de {0,number,integer} alors que le maximum autorisé est de {1,number,integer}. maxLen.file=Le fichier contient {0,number,integer} lignes alors que le maximum autorisé est de {1,number,integer}. maxLen.method=La méthode contient {0,number,integer} lignes alors que le maximum autorisé est de {1,number,integer}. maxLen.anonInner=La classe interne anonyme contient {0,number,integer} lignes alors que le maximum autorisé est de {1,number,integer}. maxLineLen=La ligne excède {0,number,integer} caractères. maxParam=La méthode ou le constructeur a plus de {0,number,integer} paramètres. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/messages_ja.properties100644 0 0 1640 11451071613 31054 0ustar 0 0 executableStatementCount=\u5b9f\u884c\u6587\u304c {0,number,integer} \u3042\u308a\u307e\u3059\uff08\u6700\u5927 {1,number,integer} \u307e\u3067\uff09\u3002 maxLen.file=\u30d5\u30a1\u30a4\u30eb\u304c {0,number,integer} \u884c\u3042\u308a\u307e\u3059\uff08\u6700\u5927 {1,number,integer} \u884c\u307e\u3067\uff09\u3002 maxLen.method=\u30e1\u30bd\u30c3\u30c9\u304c {0,number,integer} \u884c\u3042\u308a\u307e\u3059\uff08\u6700\u5927 {1,number,integer} \u884c\u307e\u3067\uff09\u3002 maxLen.anonInner=\u7121\u540d\u30a4\u30f3\u30ca\u30fc\u30af\u30e9\u30b9\u306e\u9577\u3055\u304c {0,number,integer} \u884c\u3042\u308a\u307e\u3059\uff08\u6700\u5927 {1,number,integer} \u884c\u307e\u3067\uff09\u3002 maxLineLen=\u884c\u304c {0,number,integer} \u6587\u5b57\u3092\u8d85\u3048\u3066\u3044\u307e\u3059\u3002 maxParam=\u30d1\u30e9\u30e1\u30fc\u30bf\u6570\u304c {0,number,integer} \u3092\u8d85\u3048\u3066\u3044\u307e\u3059\u3002 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/messages_pt.properties100644 0 0 1034 11451071613 31102 0ustar 0 0 executableStatementCount=Número de declaraçġes executáveis é {0,number,integer} (máx. permitido so {1,number,integer}). maxLen.anonInner=Classe interna anóima tem {0,number,integer} linhas (máx. permitido so {1,number,integer}). maxLen.file=Ficheiro tem {0,number,integer} linhas (máx. permitido so {1,number,integer}). maxLen.method=Método tem {0,number,integer} linhas (máx. permitido so {1,number,integer}). maxLineLen=Linha contém mais do que {0,number,integer} caracteres. maxParam=Mais do que {0,number,integer} parâmetros. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/messages_tr.properties100644 0 0 3206 11744664014 31117 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) executableStatementCount = Y\u00FCr\u00FCt\u00FClebilir ifade say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). maxLen.anonInner = \u0130simsiz i\u00E7 s\u0131n\u0131f uzunlu\u011Fu {0,number,integer} sat\u0131r (maksimum izin verilen de\u011Fer {1,number,integer}). maxLen.file = Dosya uzunlu\u011Fu {0,number,integer} sat\u0131r (maksimum izin verilen de\u011Fer {1,number,integer}). maxLen.method = Metot uzunlu\u011Fu {0,number,integer} sat\u0131r (maksimum izin verilen de\u011Fer {1,number,integer}). maxLineLen = Sat\u0131r {0,number,integer} de\u011Ferinden daha uzun. maxOuterTypes = Tan\u0131mlanan d\u0131\u015F t\u00FCr say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). maxParam = {0,number,integer} de\u011Ferinden daha fazla parametre mevcut. too.many.methods = Toplam metot say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). too.many.packageMethods = Toplam ''package'' eri\u015Fimli metot say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). too.many.privateMethods = Toplam ''private'' metot say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). too.many.protectedMethods = Toplam ''protected'' metot say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). too.many.publicMethods = Toplam ''public'' metot say\u0131s\u0131 {0,number,integer} (maksimum izin verilen de\u011Fer {1,number,integer}). checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.java100644 0 0 20222 12026051010 30510 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.Scope; import com.puppycrawl.tools.checkstyle.api.ScopeUtils; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.EnumMap; /** * Counts the methods of the type-definition and checks whether this * count is higher than the configured limit. * @author Alexander Jesse * @author Oliver Burn */ public final class MethodCountCheck extends Check { /** * Marker class used to collect data about the number of methods per * class. Objects of this class are used on the Stack to count the * methods for each class and layer. */ private static class MethodCounter { /** Maintains the counts. */ private final EnumMap mCounts = new EnumMap(Scope.class); /** indicated is an interface, in which case all methods are public */ private final boolean mInInterface; /** tracks the total. */ private int mTotal; /** * Creates an interface. * @param aInInterface indicated if counter for an interface. In which * case, add all counts as public methods. */ MethodCounter(boolean aInInterface) { mInInterface = aInInterface; } /** * Increments to counter by one for the supplied scope. * @param aScope the scope counter to increment. */ void increment(Scope aScope) { mTotal++; if (mInInterface) { mCounts.put(Scope.PUBLIC, 1 + value(Scope.PUBLIC)); } else { mCounts.put(aScope, 1 + value(aScope)); } } /** * @return the value of a scope counter * @param aScope the scope counter to get the value of */ int value(Scope aScope) { final Integer value = mCounts.get(aScope); return (null == value) ? 0 : value; } /** @return the total number of methods. */ int getTotal() { return mTotal; } }; /** default maximum number of methods */ private static final int DEFAULT_MAX_METHODS = 100; /** Maximum private methods. */ private int mMaxPrivate = DEFAULT_MAX_METHODS; /** Maximum package methods. */ private int mMaxPackage = DEFAULT_MAX_METHODS; /** Maximum protected methods. */ private int mMaxProtected = DEFAULT_MAX_METHODS; /** Maximum public methods. */ private int mMaxPublic = DEFAULT_MAX_METHODS; /** Maximum total number of methods. */ private int mMaxTotal = DEFAULT_MAX_METHODS; /** Maintains stack of counters, to support inner types. */ private final FastStack mCounters = new FastStack(); @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CLASS_DEF, TokenTypes.ENUM_CONSTANT_DEF, TokenTypes.ENUM_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.METHOD_DEF, }; } @Override public void visitToken(DetailAST aAST) { if ((TokenTypes.CLASS_DEF == aAST.getType()) || (TokenTypes.INTERFACE_DEF == aAST.getType()) || (TokenTypes.ENUM_CONSTANT_DEF == aAST.getType()) || (TokenTypes.ENUM_DEF == aAST.getType())) { mCounters.push(new MethodCounter( TokenTypes.INTERFACE_DEF == aAST.getType())); } else if (TokenTypes.METHOD_DEF == aAST.getType()) { raiseCounter(aAST); } } @Override public void leaveToken(DetailAST aAST) { if ((TokenTypes.CLASS_DEF == aAST.getType()) || (TokenTypes.INTERFACE_DEF == aAST.getType()) || (TokenTypes.ENUM_CONSTANT_DEF == aAST.getType()) || (TokenTypes.ENUM_DEF == aAST.getType())) { final MethodCounter counter = mCounters.pop(); checkCounters(counter, aAST); } } /** * Determine the visibility modifier and raise the corresponding counter. * @param aMethod * The method-subtree from the AbstractSyntaxTree. */ private void raiseCounter(DetailAST aMethod) { final MethodCounter actualCounter = mCounters.peek(); final DetailAST temp = aMethod.findFirstToken(TokenTypes.MODIFIERS); final Scope scope = ScopeUtils.getScopeFromMods(temp); actualCounter.increment(scope); } /** * Check the counters and report violations. * @param aCounter the method counters to check * @param aAst to report errors against. */ private void checkCounters(MethodCounter aCounter, DetailAST aAst) { checkMax(mMaxPrivate, aCounter.value(Scope.PRIVATE), "too.many.privateMethods", aAst); checkMax(mMaxPackage, aCounter.value(Scope.PACKAGE), "too.many.packageMethods", aAst); checkMax(mMaxProtected, aCounter.value(Scope.PROTECTED), "too.many.protectedMethods", aAst); checkMax(mMaxPublic, aCounter.value(Scope.PUBLIC), "too.many.publicMethods", aAst); checkMax(mMaxTotal, aCounter.getTotal(), "too.many.methods", aAst); } /** * Utility for reporting if a maximum has been exceeded. * @param aMax the maximum allowed value * @param aValue the actual value * @param aMsg the message to log. Takes two arguments of value and maximum. * @param aAst the AST to associate with the message. */ private void checkMax(int aMax, int aValue, String aMsg, DetailAST aAst) { if (aMax < aValue) { log(aAst.getLineNo(), aMsg, aValue, aMax); } } /** * Sets the maximum allowed private methods per type. * @param aValue the maximum allowed. */ public void setMaxPrivate(int aValue) { mMaxPrivate = aValue; } /** * Sets the maximum allowed package methods per type. * @param aValue the maximum allowed. */ public void setMaxPackage(int aValue) { mMaxPackage = aValue; } /** * Sets the maximum allowed protected methods per type. * @param aValue the maximum allowed. */ public void setMaxProtected(int aValue) { mMaxProtected = aValue; } /** * Sets the maximum allowed public methods per type. * @param aValue the maximum allowed. */ public void setMaxPublic(int aValue) { mMaxPublic = aValue; } /** * Sets the maximum total methods per type. * @param aValue the maximum allowed. */ public void setMaxTotal(int aValue) { mMaxTotal = aValue; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/MethodLengthCheck.java100644 0 0 7563 12026051010 30636 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks for long methods. *

*

* Rationale: If a method becomes very long it is hard to understand. * Therefore long methods should usually be refactored into several * individual methods that focus on a specific task. *

*

* The default maximum method length is 150 lines. To change the maximum * number of lines, set property max. *

*

* An example of how to configure the check is: *

*
 * <module name="MethodLength"/>
 * 
*

* An example of how to configure the check so that it accepts methods with at * most 60 lines is: *

*
 * <module name="MethodLength">
 *    <property name="max" value="60"/>
 * </module>
 * 
* @author Lars Kühne */ public class MethodLengthCheck extends Check { /** whether to ignore empty lines and single line comments */ private boolean mCountEmpty = true; /** default maximum number of lines */ private static final int DEFAULT_MAX_LINES = 150; /** the maximum number of lines */ private int mMax = DEFAULT_MAX_LINES; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF}; } @Override public void visitToken(DetailAST aAST) { final DetailAST openingBrace = aAST.findFirstToken(TokenTypes.SLIST); if (openingBrace != null) { final DetailAST closingBrace = openingBrace.findFirstToken(TokenTypes.RCURLY); int length = closingBrace.getLineNo() - openingBrace.getLineNo() + 1; if (!mCountEmpty) { final FileContents contents = getFileContents(); final int lastLine = closingBrace.getLineNo(); for (int i = openingBrace.getLineNo() - 1; i < lastLine; i++) { if (contents.lineIsBlank(i) || contents.lineIsComment(i)) { length--; } } } if (length > mMax) { log(aAST.getLineNo(), aAST.getColumnNo(), "maxLen.method", length, mMax); } } } /** * @param aLength the maximum length of a method. */ public void setMax(int aLength) { mMax = aLength; } /** * @param aCountEmpty whether to count empty and single line comments * of the form //. */ public void setCountEmpty(boolean aCountEmpty) { mCountEmpty = aCountEmpty; } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/OuterTypeNumberCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/OuterTypeNumberCheck.java100644 0 0 5056 12026051010 31360 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Check; /** * Checks for the number of defined types at the "outer" level. * @author oliverb */ public class OuterTypeNumberCheck extends Check { /** The maximum allowed number of outer types. */ private int mMax = 1; /** Tracks the current depth in types. */ private int mCurrentDepth; /** Tracks the number of outer types found. */ private int mOuterNum; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.ENUM_DEF, TokenTypes.ANNOTATION_DEF, }; } @Override public void beginTree(DetailAST aAst) { mCurrentDepth = 0; mOuterNum = 0; } @Override public void finishTree(DetailAST aAst) { if (mMax < mOuterNum) { log(aAst, "maxOuterTypes", mOuterNum, mMax); } } @Override public void visitToken(DetailAST aAst) { if (0 == mCurrentDepth) { mOuterNum++; } mCurrentDepth++; } @Override public void leaveToken(DetailAST aAst) { mCurrentDepth--; } /** * Sets the maximum allowed number of outer types. * @param aTo the new number. */ public void setMax(int aTo) { mMax = aTo; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/package-info.java100644 0 0 2307 12026051007 27637 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the Size Violations checks * that are bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks.sizes; ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/ParameterNumberCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/sizes/ParameterNumberCheck.java100644 0 0 5522 12026051010 31336 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks the number of parameters that a method or constructor has. * The default allowable number of parameters is 7. * To change the number of allowable parameters, set property max. *

*

* An example of how to configure the check is: *

*
 * <module name="ParameterNumber"/>
 * 
*

* An example of how to configure the check to allow 10 parameters is: *

*
 * <module name="ParameterNumber">
 *    <property name="max" value="10"/>
 * </module>
 * 
* @author Oliver Burn * @version 1.0 */ public class ParameterNumberCheck extends Check { /** default maximum number of allowed parameters */ private static final int DEFAULT_MAX_PARAMETERS = 7; /** the maximum number of allowed parameters */ private int mMax = DEFAULT_MAX_PARAMETERS; /** * Sets the maximum number of allowed parameters. * @param aMax the max allowed parameters */ public void setMax(int aMax) { mMax = aMax; } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF}; } @Override public void visitToken(DetailAST aAST) { final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS); final int count = params.getChildCount(TokenTypes.PARAMETER_DEF); if (count > mMax) { final DetailAST name = aAST.findFirstToken(TokenTypes.IDENT); log(name.getLineNo(), name.getColumnNo(), "maxParam", mMax, count); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/TodoCommentCheck.java100644 0 0 7467 12026051061 27360 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.TextBlock; import java.util.List; import java.util.Map; /** *

* A check for TODO comments. * Actually it is a generic {@link java.util.regex.Pattern regular expression} * matcher on Java comments. * To check for other patterns in Java comments, set property format. *

*

* An example of how to configure the check is: *

*
 * <module name="TodoComment"/>
 * 
*

* An example of how to configure the check for comments that contain * WARNING is: *

*
 * <module name="TodoComment">
 *    <property name="format" value="WARNING"/>
 * </module>
 * 
* @author Oliver Burn * @version 1.0 */ public class TodoCommentCheck extends AbstractFormatCheck { /** * Creates a new TodoCommentCheck instance. */ public TodoCommentCheck() { super("TODO:"); // the empty language } @Override public int[] getDefaultTokens() { return new int[0]; } @Override public void beginTree(DetailAST aRootAST) { final FileContents contents = getFileContents(); checkCppComments(contents); checkBadComments(contents); } /** * Checks the C++ comments for todo expressions. * @param aContents the FileContents */ private void checkCppComments(FileContents aContents) { final Map comments = aContents.getCppComments(); for (Map.Entry entry : comments.entrySet()) { final String cmt = entry.getValue().getText()[0]; if (getRegexp().matcher(cmt).find()) { log(entry.getKey().intValue(), "todo.match", getFormat()); } } } /** * Checks the C-style comments for todo expressions. * @param aContents the FileContents */ private void checkBadComments(FileContents aContents) { final Map> allComments = aContents .getCComments(); for (Map.Entry> entry : allComments.entrySet()) { for (TextBlock line : entry.getValue()) { final String[] cmt = line.getText(); for (int i = 0; i < cmt.length; i++) { if (getRegexp().matcher(cmt[i]).find()) { log(entry.getKey().intValue() + i, "todo.match", getFormat()); } } } } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheck.java100644 0 0 20025 12026051061 30225 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; /** *

* The check to ensure that requires that comments be the only thing on a line. * For the case of // comments that means that the only thing that should * precede it is whitespace. * It doesn't check comments if they do not end line, i.e. it accept * the following: * Thread.sleep( 10 <some comment here> ); * Format property is intended to deal with the "} // while" example. *

*

* Rationale: Steve McConnel in "Code Complete" suggests that endline * comments are a bad practice. An end line comment would * be one that is on the same line as actual code. For example: *

 *  a = b + c;      // Some insightful comment
 *  d = e / f;        // Another comment for this line
 * 
* Quoting "Code Complete" for the justfication: *
    *
  • * "The comments have to be aligned so that they do not * interfere with the visual structure of the code. If you don't * align them neatly, they'll make your listing look like it's been * through a washing machine." *
  • *
  • * "Endline comments tend to be hard to format...It takes time * to align them. Such time is not spent learning more about * the code; it's dedicated solely to the tedious task of * pressing the spacebar or tab key." *
  • *
  • * "Endline comments are also hard to maintain. If the code on * any line containing an endline comment grows, it bumps the * comment farther out, and all the other endline comments will * have to bumped out to match. Styles that are hard to * maintain aren't maintained...." *
  • *
  • * "Endline comments also tend to be cryptic. The right side of * the line doesn't offer much room and the desire to keep the * comment on one line means the comment must be short. * Work then goes into making the line as short as possible * instead of as clear as possible. The comment usually ends * up as cryptic as possible...." *
  • *
  • * "A systemic problem with endline comments is that it's hard * to write a meaningful comment for one line of code. Most * endline comments just repeat the line of code, which hurts * more than it helps." *
  • *
* His comments on being hard to maintain when the size of * the line changes are even more important in the age of * automated refactorings. *

*

* To configure the check so it enforces only comment on a line: *

 * <module name="TrailingComment">
 *    <property name="format" value="^\\s*$"/>
 * </module>
 * 
*

* @author o_sukhodolsky */ public class TrailingCommentCheck extends AbstractFormatCheck { /** default format for allowed blank line. */ private static final String DEFAULT_FORMAT = "^[\\s\\}\\);]*$"; /** pattern for legal trailing comment. */ private Pattern mLegalComment; /** * Sets patter for legal trailing comments. * @param aFormat format to set. * @throws ConversionException unable to parse a given format. */ public void setLegalComment(final String aFormat) throws ConversionException { try { mLegalComment = Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } /** * Creates new instance of the check. * @throws ConversionException unable to parse DEFAULT_FORMAT. */ public TrailingCommentCheck() throws ConversionException { super(DEFAULT_FORMAT); } @Override public int[] getDefaultTokens() { return new int[0]; } @Override public void visitToken(DetailAST aAST) { throw new IllegalStateException("visitToken() shouldn't be called."); } @Override public void beginTree(DetailAST aRootAST) { final Pattern blankLinePattern = getRegexp(); final Map cppComments = getFileContents() .getCppComments(); final Map> cComments = getFileContents() .getCComments(); final Set lines = Sets.newHashSet(); lines.addAll(cppComments.keySet()); lines.addAll(cComments.keySet()); for (Integer lineNo : lines) { final String line = getLines()[lineNo.intValue() - 1]; String lineBefore = ""; TextBlock comment = null; if (cppComments.containsKey(lineNo)) { comment = cppComments.get(lineNo); lineBefore = line.substring(0, comment.getStartColNo()); } else if (cComments.containsKey(lineNo)) { final List commentList = cComments.get(lineNo); comment = commentList.get(commentList.size() - 1); lineBefore = line.substring(0, comment.getStartColNo()); if (comment.getText().length == 1) { final String lineAfter = line.substring(comment.getEndColNo() + 1).trim(); if (!"".equals(lineAfter)) { // do not check comment which doesn't end line continue; } } } if ((comment != null) && !blankLinePattern.matcher(lineBefore).find() && !isLegalComment(comment)) { log(lineNo.intValue(), "trailing.comments"); } } } /** * Checks if given comment is legal (single-line and matches to the * pattern). * @param aComment comment to check. * @return true if the comment if legal. */ private boolean isLegalComment(final TextBlock aComment) { if (mLegalComment == null) { return false; } // multi-line comment can not be legal if (aComment.getStartLineNo() != aComment.getEndLineNo()) { return false; } String commentText = aComment.getText()[0]; // remove chars which start comment commentText = commentText.substring(2); // if this is a C-style comment we need to remove its end if (commentText.endsWith("*/")) { commentText = commentText.substring(0, commentText.length() - 2); } commentText = commentText.trim(); return mLegalComment.matcher(commentText).find(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java100644 0 0 22430 12026051061 27431 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.Defn; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.MessageDispatcher; import com.puppycrawl.tools.checkstyle.api.Utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.Map.Entry; /** *

* The TranslationCheck class helps to ensure the correct translation of code by * checking property files for consistency regarding their keys. * Two property files describing one and the same context are consistent if they * contain the same keys. *

*

* An example of how to configure the check is: *

*
 * <module name="Translation"/>
 * 
* @author Alexandra Bunge * @author lkuehne */ public class TranslationCheck extends AbstractFileSetCheck { /** The property files to process. */ private final List mPropertyFiles = Lists.newArrayList(); /** * Creates a new TranslationCheck instance. */ public TranslationCheck() { setFileExtensions(new String[]{"properties"}); } @Override public void beginProcessing(String aCharset) { super.beginProcessing(aCharset); mPropertyFiles.clear(); } @Override protected void processFiltered(File aFile, List aLines) { mPropertyFiles.add(aFile); } @Override public void finishProcessing() { super.finishProcessing(); final Map> propFilesMap = arrangePropertyFiles(mPropertyFiles); checkPropertyFileSets(propFilesMap); } /** * Gets the basename (the unique prefix) of a property file. For example * "xyz/messages" is the basename of "xyz/messages.properties", * "xyz/messages_de_AT.properties", "xyz/messages_en.properties", etc. * * @param aFile the file * @return the extracted basename */ private static String extractPropertyIdentifier(final File aFile) { final String filePath = aFile.getPath(); final int dirNameEnd = filePath.lastIndexOf(File.separatorChar); final int baseNameStart = dirNameEnd + 1; final int underscoreIdx = filePath.indexOf('_', baseNameStart); final int dotIdx = filePath.indexOf('.', baseNameStart); final int cutoffIdx = (underscoreIdx != -1) ? underscoreIdx : dotIdx; return filePath.substring(0, cutoffIdx); } /** * Arranges a set of property files by their prefix. * The method returns a Map object. The filename prefixes * work as keys each mapped to a set of files. * @param aPropFiles the set of property files * @return a Map object which holds the arranged property file sets */ private static Map> arrangePropertyFiles( List aPropFiles) { final Map> propFileMap = Maps.newHashMap(); for (final File f : aPropFiles) { final String identifier = extractPropertyIdentifier(f); Set fileSet = propFileMap.get(identifier); if (fileSet == null) { fileSet = Sets.newHashSet(); propFileMap.put(identifier, fileSet); } fileSet.add(f); } return propFileMap; } /** * Loads the keys of the specified property file into a set. * @param aFile the property file * @return a Set object which holds the loaded keys */ private Set loadKeys(File aFile) { final Set keys = Sets.newHashSet(); InputStream inStream = null; try { // Load file and properties. inStream = new FileInputStream(aFile); final Properties props = new Properties(); props.load(inStream); // Gather the keys and put them into a set final Enumeration e = props.propertyNames(); while (e.hasMoreElements()) { keys.add(e.nextElement()); } } catch (final IOException e) { logIOException(e, aFile); } finally { Utils.closeQuietly(inStream); } return keys; } /** * helper method to log an io exception. * @param aEx the exception that occured * @param aFile the file that could not be processed */ private void logIOException(IOException aEx, File aFile) { String[] args = null; String key = "general.fileNotFound"; if (!(aEx instanceof FileNotFoundException)) { args = new String[] {aEx.getMessage()}; key = "general.exception"; } final LocalizedMessage message = new LocalizedMessage( 0, Defn.CHECKSTYLE_BUNDLE, key, args, getId(), this.getClass(), null); final TreeSet messages = Sets.newTreeSet(); messages.add(message); getMessageDispatcher().fireErrors(aFile.getPath(), messages); Utils.getExceptionLogger().debug("IOException occured.", aEx); } /** * Compares the key sets of the given property files (arranged in a map) * with the specified key set. All missing keys are reported. * @param aKeys the set of keys to compare with * @param aFileMap a Map from property files to their key sets */ private void compareKeySets(Set aKeys, Map> aFileMap) { final Set>> fls = aFileMap.entrySet(); for (Entry> entry : fls) { final File currentFile = entry.getKey(); final MessageDispatcher dispatcher = getMessageDispatcher(); final String path = currentFile.getPath(); dispatcher.fireFileStarted(path); final Set currentKeys = entry.getValue(); // Clone the keys so that they are not lost final Set keysClone = Sets.newHashSet(aKeys); keysClone.removeAll(currentKeys); // Remaining elements in the key set are missing in the current file if (!keysClone.isEmpty()) { for (Object key : keysClone) { log(0, "translation.missingKey", key); } } fireErrors(path); dispatcher.fireFileFinished(path); } } /** * Tests whether the given property files (arranged by their prefixes * in a Map) contain the proper keys. * * Each group of files must have the same keys. If this is not the case * an error message is posted giving information which key misses in * which file. * * @param aPropFiles the property files organized as Map */ private void checkPropertyFileSets(Map> aPropFiles) { final Set>> entrySet = aPropFiles.entrySet(); for (Entry> entry : entrySet) { final Set files = entry.getValue(); if (files.size() >= 2) { // build a map from files to the keys they contain final Set keys = Sets.newHashSet(); final Map> fileMap = Maps.newHashMap(); for (File file : files) { final Set fileKeys = loadKeys(file); keys.addAll(fileKeys); fileMap.put(file, fileKeys); } // check the map for consistency compareKeySets(keys, fileMap); } } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheck.java100644 0 0 20057 12026051060 30220 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; /** * Detects uncommented main methods. Basically detects * any main method, since if it is detectable * that means it is uncommented. * *
 * <module name="UncommentedMain"/>
 * 
* * @author Michael Yui * @author o_sukhodolsky */ public class UncommentedMainCheck extends Check { /** the pattern to exclude classes from the check */ private String mExcludedClasses = "^$"; /** compiled regexp to exclude classes from check */ private Pattern mExcludedClassesPattern = Utils.createPattern(mExcludedClasses); /** current class name */ private String mCurrentClass; /** current package */ private FullIdent mPackage; /** class definition depth */ private int mClassDepth; /** * Set the excluded classes pattern. * @param aExcludedClasses a String value * @throws ConversionException unable to parse aExcludedClasses */ public void setExcludedClasses(String aExcludedClasses) throws ConversionException { try { mExcludedClasses = aExcludedClasses; mExcludedClassesPattern = Utils.getPattern(mExcludedClasses); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + mExcludedClasses, e); } } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.METHOD_DEF, TokenTypes.CLASS_DEF, TokenTypes.PACKAGE_DEF, }; } @Override public int[] getRequiredTokens() { return getDefaultTokens(); } @Override public void beginTree(DetailAST aRootAST) { mPackage = FullIdent.createFullIdent(null); mCurrentClass = null; mClassDepth = 0; } @Override public void leaveToken(DetailAST aAst) { if (aAst.getType() == TokenTypes.CLASS_DEF) { if (mClassDepth == 1) { mCurrentClass = null; } mClassDepth--; } } @Override public void visitToken(DetailAST aAst) { switch (aAst.getType()) { case TokenTypes.PACKAGE_DEF: visitPackageDef(aAst); break; case TokenTypes.CLASS_DEF: visitClassDef(aAst); break; case TokenTypes.METHOD_DEF: visitMethodDef(aAst); break; default: throw new IllegalStateException(aAst.toString()); } } /** * Sets current package. * @param aPackage node for package definition */ private void visitPackageDef(DetailAST aPackage) { mPackage = FullIdent.createFullIdent(aPackage.getLastChild() .getPreviousSibling()); } /** * If not inner class then change current class name. * @param aClass node for class definition */ private void visitClassDef(DetailAST aClass) { // we are not use inner classes because they can not // have static methods if (mClassDepth == 0) { final DetailAST ident = aClass.findFirstToken(TokenTypes.IDENT); mCurrentClass = mPackage.getText() + "." + ident.getText(); mClassDepth++; } } /** * Checks method definition if this is * public static void main(String[]). * @param aMethod method definition node */ private void visitMethodDef(DetailAST aMethod) { if (mClassDepth != 1) { // method in inner class or in interface definition return; } if (checkClassName() && checkName(aMethod) && checkModifiers(aMethod) && checkType(aMethod) && checkParams(aMethod)) { log(aMethod.getLineNo(), "uncommented.main"); } } /** * Checks that current class is not excluded * @return true if check passed, false otherwise */ private boolean checkClassName() { return !mExcludedClassesPattern.matcher(mCurrentClass).find(); } /** * Checks that method name is @quot;main@quot;. * @param aMethod the METHOD_DEF node * @return true if check passed, false otherwise */ private boolean checkName(DetailAST aMethod) { final DetailAST ident = aMethod.findFirstToken(TokenTypes.IDENT); return "main".equals(ident.getText()); } /** * Checks that method has final and static modifiers. * @param aMethod the METHOD_DEF node * @return true if check passed, false otherwise */ private boolean checkModifiers(DetailAST aMethod) { final DetailAST modifiers = aMethod.findFirstToken(TokenTypes.MODIFIERS); return modifiers.branchContains(TokenTypes.LITERAL_PUBLIC) && modifiers.branchContains(TokenTypes.LITERAL_STATIC); } /** * Checks that return type is void. * @param aMethod the METHOD_DEF node * @return true if check passed, false otherwise */ private boolean checkType(DetailAST aMethod) { final DetailAST type = aMethod.findFirstToken(TokenTypes.TYPE).getFirstChild(); return type.getType() == TokenTypes.LITERAL_VOID; } /** * Checks that method has only String[] param * @param aMethod the METHOD_DEF node * @return true if check passed, false otherwise */ private boolean checkParams(DetailAST aMethod) { final DetailAST params = aMethod.findFirstToken(TokenTypes.PARAMETERS); if (params.getChildCount() != 1) { return false; } final DetailAST paramType = (params.getFirstChild()) .findFirstToken(TokenTypes.TYPE); final DetailAST arrayDecl = paramType.findFirstToken(TokenTypes.ARRAY_DECLARATOR); if (arrayDecl == null) { return false; } final DetailAST arrayType = arrayDecl.getFirstChild(); if ((arrayType.getType() == TokenTypes.IDENT) || (arrayType.getType() == TokenTypes.DOT)) { final FullIdent type = FullIdent.createFullIdent(arrayType); return ("String".equals(type.getText()) || "java.lang.String".equals(type.getText())); } return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/UpperEllCheck.java100644 0 0 4467 12026051060 26654 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

Checks that long constants are defined with an upper ell. * That is 'L' and not * 'l'. This is in accordance to the Java Language * Specification, Section 3.10.1. *

*

* Rationale: The letter l looks a lot * like the number 1. *

*

Examples

*

* To configure the check: * *

*
 * <module name="UpperEll"/>
 * 
* * @author Oliver Burn * @version 1.0 */ public class UpperEllCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.NUM_LONG}; } @Override public void visitToken(DetailAST aAST) { if (aAST.getText().endsWith("l")) { log(aAST.getLineNo(), aAST.getColumnNo() + aAST.getText().length() - 1, "upperEll"); } } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/AbstractParenPadCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/AbstractParenPadChec100644 0 0 7011 12026051007 31330 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck; /** *

Abstract class for checking the padding of parentheses. That is whether a * space is required after a left parenthesis and before a right parenthesis, * or such spaces are forbidden. *

* @author Oliver Burn * @version 1.0 */ abstract class AbstractParenPadCheck extends AbstractOptionCheck { /** * Sets the paren pad otion to nospace. */ AbstractParenPadCheck() { super(PadOption.NOSPACE, PadOption.class); } /** * Process a token representing a left parentheses. * @param aAST the token representing a left parentheses */ protected void processLeft(DetailAST aAST) { final String line = getLines()[aAST.getLineNo() - 1]; final int after = aAST.getColumnNo() + 1; if (after < line.length()) { if ((PadOption.NOSPACE == getAbstractOption()) && (Character.isWhitespace(line.charAt(after)))) { log(aAST.getLineNo(), after, "ws.followed", "("); } else if ((PadOption.SPACE == getAbstractOption()) && !Character.isWhitespace(line.charAt(after)) && (line.charAt(after) != ')')) { log(aAST.getLineNo(), after, "ws.notFollowed", "("); } } } /** * Process a token representing a right parentheses. * @param aAST the token representing a right parentheses */ protected void processRight(DetailAST aAST) { final String line = getLines()[aAST.getLineNo() - 1]; final int before = aAST.getColumnNo() - 1; if (before >= 0) { if ((PadOption.NOSPACE == getAbstractOption()) && Character.isWhitespace(line.charAt(before)) && !Utils.whitespaceBefore(before, line)) { log(aAST.getLineNo(), before, "ws.preceded", ")"); } else if ((PadOption.SPACE == getAbstractOption()) && !Character.isWhitespace(line.charAt(before)) && (line.charAt(before) != '(')) { log(aAST.getLineNo(), aAST.getColumnNo(), "ws.notPreceded", ")"); } } } } ././@LongLink100644 0 0 161 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyForInitializerPadCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyForInitializerP100644 0 0 6547 12026051007 31475 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck; /** *

Checks the padding of an empty for initializer; that is whether a * space is required at an empty for initializer, or such spaces are * forbidden. No check occurs if there is a line wrap at the initializer, as in *

*
for (
      ; i < j; i++, j--)
   
*

* The policy to verify is specified using the {@link PadOption} class and * defaults to {@link PadOption#NOSPACE}. *

*

* An example of how to configure the check is: *

*
 * <module name="EmptyForInitializerPad"/>
 * 
* * @author lkuehne * @version 1.0 */ public class EmptyForInitializerPadCheck extends AbstractOptionCheck { /** * Sets the paren pad otion to nospace. */ public EmptyForInitializerPadCheck() { super(PadOption.NOSPACE, PadOption.class); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.FOR_INIT, }; } @Override public void visitToken(DetailAST aAST) { if (aAST.getChildCount() == 0) { //empty for initializer. test pad before semi. final DetailAST semi = aAST.getNextSibling(); final int semiLineIdx = semi.getLineNo() - 1; final String line = getLines()[semiLineIdx]; final int before = semi.getColumnNo() - 1; //don't check if semi at beginning of line if (!Utils.whitespaceBefore(before, line)) { final PadOption option = getAbstractOption(); if ((PadOption.NOSPACE == option) && (Character.isWhitespace(line.charAt(before)))) { log(semi.getLineNo(), before, "ws.preceded", ";"); } else if ((PadOption.SPACE == option) && !Character.isWhitespace(line.charAt(before))) { log(semi.getLineNo(), before, "ws.notPreceded", ";"); } } } } } ././@LongLink100644 0 0 156 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyForIteratorPadCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyForIteratorPadC100644 0 0 6334 12026051007 31405 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck; /** *

Checks the padding of an empty for iterator; that is whether a * space is required at an empty for iterator, or such spaces are * forbidden. No check occurs if there is a line wrap at the iterator, as in *

*
for (Iterator foo = very.long.line.iterator();
      foo.hasNext();
     )
   
*

* The policy to verify is specified using the {@link PadOption} class and * defaults to {@link PadOption#NOSPACE}. *

*

* An example of how to configure the check is: *

*
 * <module name="EmptyForIteratorPad"/>
 * 
* * @author Rick Giles * @version 1.0 */ public class EmptyForIteratorPadCheck extends AbstractOptionCheck { /** * Sets the paren pad otion to nospace. */ public EmptyForIteratorPadCheck() { super(PadOption.NOSPACE, PadOption.class); } @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.FOR_ITERATOR, }; } @Override public void visitToken(DetailAST aAST) { if (aAST.getChildCount() == 0) { //empty for iterator. test pad after semi. final DetailAST semi = aAST.getPreviousSibling(); final String line = getLines()[semi.getLineNo() - 1]; final int after = semi.getColumnNo() + 1; //don't check if at end of line if (after < line.length()) { if ((PadOption.NOSPACE == getAbstractOption()) && (Character.isWhitespace(line.charAt(after)))) { log(semi.getLineNo(), after, "ws.followed", ";"); } else if ((PadOption.SPACE == getAbstractOption()) && !Character.isWhitespace(line.charAt(after))) { log(semi.getLineNo(), after, "ws.notFollowed", ";"); } } } } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/FileTabCharacterCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/FileTabCharacterChec100644 0 0 4354 12026051006 31303 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import java.io.File; import java.util.List; /** * Checks to see if a file contains a tab character. * @author oliverb */ public class FileTabCharacterCheck extends AbstractFileSetCheck { /** Indicates whether to report once per file, or for each line. */ private boolean mEachLine; @Override protected void processFiltered(File aFile, List aLines) { int lineNum = 0; for (final String line : aLines) { lineNum++; final int tabPosition = line.indexOf('\t'); if (tabPosition != -1) { if (mEachLine) { log(lineNum, tabPosition + 1, "containsTab"); } else { log(lineNum, tabPosition + 1, "file.containsTab"); break; } } } } /** * Whether report on each line containing a tab. * @param aEachLine Whether report on each line containing a tab. */ public void setEachLine(boolean aEachLine) { mEachLine = aEachLine; } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceChe100644 0 0 14114 12026051006 31421 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; /** * Checks that the whitespace around the Generic tokens < and > are * correct to the typical convention. The convention is not configurable. * @author Oliver Burn */ public class GenericWhitespaceCheck extends Check { /** Used to count the depth of a Generic expression. */ private int mDepth; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.GENERIC_START, TokenTypes.GENERIC_END}; } @Override public void beginTree(DetailAST aRootAST) { // Reset for each tree, just incase there are errors in preceeding // trees. mDepth = 0; } @Override public void visitToken(DetailAST aAST) { if (aAST.getType() == TokenTypes.GENERIC_START) { processStart(aAST); mDepth++; } else if (aAST.getType() == TokenTypes.GENERIC_END) { processEnd(aAST); mDepth--; } } /** * Checks the token for the end of Generics. * @param aAST the token to check */ private void processEnd(DetailAST aAST) { final String line = getLines()[aAST.getLineNo() - 1]; final int before = aAST.getColumnNo() - 1; final int after = aAST.getColumnNo() + 1; if ((0 <= before) && Character.isWhitespace(line.charAt(before)) && !Utils.whitespaceBefore(before, line)) { log(aAST.getLineNo(), before, "ws.preceded", ">"); } if (after < line.length()) { // Check if the last Generic, in which case must be a whitespace // or a '(),[.'. if (1 == mDepth) { final char charAfter = line.charAt(after); // Need to handle a number of cases. First is: // Collections.emptySet(); // ^ // +--- whitespace not allowed if ((aAST.getParent().getType() == TokenTypes.TYPE_ARGUMENTS) && (aAST.getParent().getParent().getType() == TokenTypes.DOT) && (aAST.getParent().getParent().getParent().getType() == TokenTypes.METHOD_CALL)) { if (Character.isWhitespace(charAfter)) { log(aAST.getLineNo(), after, "ws.followed", ">"); } } else if (!Character.isWhitespace(charAfter) && ('(' != charAfter) && (')' != charAfter) && (',' != charAfter) && ('[' != charAfter) && ('.' != charAfter)) { log(aAST.getLineNo(), after, "ws.illegalFollow", ">"); } } else { // In a nested Generic type, so can only be a '>' or ',' if ((line.charAt(after) != '>') && (line.charAt(after) != ',')) { log(aAST.getLineNo(), after, "ws.followed", ">"); } } } } /** * Checks the token for the start of Generics. * @param aAST the token to check */ private void processStart(DetailAST aAST) { final String line = getLines()[aAST.getLineNo() - 1]; final int before = aAST.getColumnNo() - 1; final int after = aAST.getColumnNo() + 1; // Need to handle two cases as in: // // public static Callable callable(Runnable task, T result) // ^ ^ // ws reqd ---+ +--- whitespace NOT required // if (0 <= before) { // Detect if the first case final DetailAST parent = aAST.getParent(); final DetailAST grandparent = parent.getParent(); if ((TokenTypes.TYPE_PARAMETERS == parent.getType()) && ((TokenTypes.CTOR_DEF == grandparent.getType()) || (TokenTypes.METHOD_DEF == grandparent.getType()))) { // Require whitespace if (!Character.isWhitespace(line.charAt(before))) { log(aAST.getLineNo(), before, "ws.notPreceded", "<"); } } // Whitespace not required else if (Character.isWhitespace(line.charAt(before)) && !Utils.whitespaceBefore(before, line)) { log(aAST.getLineNo(), before, "ws.preceded", "<"); } } if ((after < line.length()) && Character.isWhitespace(line.charAt(after))) { log(aAST.getLineNo(), after, "ws.followed", "<"); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages.properties100644 0 0 1116 11451071613 31377 0ustar 0 0 containsTab=Line contains a tab character. file.containsTab=File contains tab characters (this is the first instance). line.alone=''{0}'' should be alone on a line. line.new=''{0}'' should be on a new line. line.previous=''{0}'' should be on the previous line. line.same=''{0}'' should be on the same line. ws.followed=''{0}'' is followed by whitespace. ws.notFollowed=''{0}'' is not followed by whitespace. ws.notPreceded=''{0}'' is not preceded with whitespace. ws.preceded=''{0}'' is preceded with whitespace. ws.illegalFollow=''{0}'' is followed by an illegal character. ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_de.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_de.properti100644 0 0 754 11451071613 31506 0ustar 0 0 containsTab=Zeile enthält ein TAB-Zeichen line.alone=''{0}'' sollte allein in der Zeile stehen. line.new=''{0}'' sollte in einer neuen Zeile stehen. line.previous=''{0}'' sollte in der vorangehenden Zeile stehen. line.same=''{0}'' sollte in derselben Zeile stehen. ws.followed=Nach ''{0}'' folgt ein Leerzeichen. ws.notFollowed=Nach ''{0}'' folgt kein Leerzeichen. ws.notPreceded=Vor ''{0}'' befindet sich kein Leerzeichen. ws.preceded=Vor ''{0}'' befindet sich ein Leerzeichen. ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_es.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_es.properti100644 0 0 1007 11451071613 31535 0ustar 0 0 containsTab=La línea contiene un carácter de tabulación. line.alone=''{0}'' debería estar solo en una línea. line.new=''{0}'' debería estar en una línea nueva. line.previous=''{0}'' debería estar en la línea anterior. line.same=''{0}'' debería estar en la misma línea. ws.followed=''{0}'' está seguido de espacios en blanco. ws.notFollowed=''{0}'' no está seguido de espacio en blanco. ws.notPreceded=''{0}'' no está precedido de espacio en blanco. ws.preceded=''{0}'' está precedido de espacio en blanco. ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_fi.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_fi.properti100644 0 0 711 11451071613 31505 0ustar 0 0 containsTab=Rivi sis¤lt¤¤ sarkainmerkin. line.alone=''{0}'' pit¤¤ olla yksin¤¤n rivill¤. line.new=''{0}'' pit¤¤ olla uudella rivill¤. line.previous=''{0}'' pit¤¤ olla edellisell¤ rivill¤. line.same=''{0}'' pit¤¤ olla samalla rivill¤. ws.followed=''{0}'':ta seuraa v¤lilyĥnti. ws.notFollowed=''{0}'':ta ei seuraa v¤lilyĥnti. ws.notPreceded=''{0}'':ta ei edell¤ v¤lilyĥnti. ws.preceded=''{0}'':ta edelt¤¤ v¤lilyĥnti. ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_fr.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_fr.properti100644 0 0 777 11451071613 31532 0ustar 0 0 containsTab=La ligne contient un caractère tabulation. line.alone=''{0}'' devrait être la seule instruction sur cette ligne. line.new=''{0}'' devrait être sur une nouvelle ligne. line.previous=''{0}'' devrait être sur la ligne précédente. line.same=''{0}'' devrait être sur la même ligne. ws.followed=Il y a une espace de trop après ''{0}''. ws.notFollowed=Il manque une espace après ''{0}''. ws.notPreceded=Il manque une espace avant ''{0}''. ws.preceded=Il y a une espace de trop avant ''{0}''. ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_ja.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_ja.properti100644 0 0 1764 11451071613 31532 0ustar 0 0 containsTab=\u884c\u306b\u30bf\u30d6\u6587\u5b57\u304c\u542b\u307e\u308c\u3066\u3044\u307e\u3059\u3002 line.alone=''{0}'' \u306f\u72ec\u7acb\u3057\u305f\u884c\u306b\u3042\u308b\u3079\u304d\u3067\u3059\u3002 line.new=''{0}'' \u306f\u65b0\u3057\u3044\u884c\u306b\u3042\u308b\u3079\u304d\u3067\u3059\u3002 line.previous=''{0}'' \u306f\u524d\u306e\u884c\u306b\u3042\u308b\u3079\u304d\u3067\u3059\u3002 line.same=''{0}'' \u306f\u540c\u4e00\u884c\u306b\u3042\u308b\u3079\u304d\u3067\u3059\u3002 ws.followed=''{0}'' \u306e\u5f8c\u306b\u30db\u30ef\u30a4\u30c8\u30b9\u30da\u30fc\u30b9\u304c\u3042\u308a\u307e\u3059\u3002 ws.notFollowed=''{0}'' \u306e\u5f8c\u306b\u30db\u30ef\u30a4\u30c8\u30b9\u30da\u30fc\u30b9\u304c\u3042\u308a\u307e\u305b\u3093\u3002 ws.notPreceded=''{0}'' \u306e\u524d\u306b\u30db\u30ef\u30a4\u30c8\u30b9\u30da\u30fc\u30b9\u304c\u3042\u308a\u307e\u305b\u3093\u3002 ws.preceded=''{0}'' \u306e\u524d\u306b\u30db\u30ef\u30a4\u30c8\u30b9\u30da\u30fc\u30b9\u304c\u3042\u308a\u307e\u3059\u3002 ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_pt.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_pt.properti100644 0 0 740 11451071613 31534 0ustar 0 0 containsTab=Linha contém um caracter de tabulaço. line.alone=''{0}'' deve estar sozinho numa linha. line.new=''{0}'' deve estar numa nova linha. line.previous=''{0}'' deve estar na linha anterior. line.same=''{0}'' deve estar na mesma linha. ws.followed=''{0}'' é seguido de espaço em branco. ws.notFollowed=''{0}'' no é seguido de espaço em branco. ws.notPreceded=''{0}'' no é precedido por espaço em branco. ws.preceded=''{0}'' é precedido por espaço em branco. ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_tr.propertiescheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/messages_tr.properti100644 0 0 1733 11744664014 31571 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) containsTab = Sat\u0131r, sekme karakteri i\u00E7ermekte. file.containsTab = Dosya, sekme karakterleri i\u00E7ermekte (sadece ilk bulunan g\u00F6steriliyor). line.alone = ''{0}'' ifadesi sat\u0131rda tek ba\u015F\u0131na olmal\u0131. line.new = ''{0}'' ifadesi yeni bir sat\u0131rda olmal\u0131. line.previous = ''{0}'' ifadesi \u00F6nceki sat\u0131rda olmal\u0131. line.same = ''{0}'' ifadesi ayn\u0131 sat\u0131rda olmal\u0131. ws.followed = ''{0}'' ifadesinden sonra bo\u015Fluk kullan\u0131lm\u0131\u015F. ws.illegalFollow = ''{0}'' ifadesinden sonra ge\u00E7ersiz bir karakter kullan\u0131lm\u0131\u015F. ws.notFollowed = ''{0}'' ifadesinden sonra bo\u015Fluk kullan\u0131lmam\u0131\u015F. ws.notPreceded = ''{0}'' ifadesinden \u00F6nce bo\u015Fluk kullan\u0131lmam\u0131\u015F. ws.preceded = ''{0}'' ifadesinden \u00F6nce bo\u015Fluk kullan\u0131lm\u0131\u015F. ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/MethodParamPadCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/MethodParamPadCheck.100644 0 0 11547 12026051006 31261 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck; /** *

* Checks the padding between the identifier of a method definition, * constructor definition, method call, or constructor invocation; * and the left parenthesis of the parameter list. * That is, if the identifier and left parenthesis are on the same line, * checks whether a space is required immediately after the identifier or * such a space is forbidden. * If they are not on the same line, reports an error, unless configured to * allow line breaks. *

*

By default the check will check the following tokens: * {@link TokenTypes#CTOR_DEF CTOR_DEF}, * {@link TokenTypes#LITERAL_NEW LITERAL_NEW}, * {@link TokenTypes#METHOD_CALL METHOD_CALL}, * {@link TokenTypes#METHOD_DEF METHOD_DEF}, * {@link TokenTypes#SUPER_CTOR_CALL SUPER_CTOR_CALL}. *

*

* An example of how to configure the check is: *

*
 * <module name="MethodParamPad"/>
 * 
*

An example of how to configure the check to require a space * after the identifier of a method definition, except if the left * parenthesis occurs on a new line, is: *

*
 * <module name="MethodParamPad">
 *     <property name="tokens" value="METHOD_DEF"/>
 *     <property name="option" value="space"/>
 *     <property name="allowLineBreaks" value="true"/>
 * </module>
 * 
* @author Rick Giles * @version 1.0 */ public class MethodParamPadCheck extends AbstractOptionCheck { /** * Sets the pad option to nospace. */ public MethodParamPadCheck() { super(PadOption.NOSPACE, PadOption.class); } /** Whether whitespace is allowed if the method identifier is at a * linebreak */ private boolean mAllowLineBreaks; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.CTOR_DEF, TokenTypes.LITERAL_NEW, TokenTypes.METHOD_CALL, TokenTypes.METHOD_DEF, TokenTypes.SUPER_CTOR_CALL, }; } @Override public void visitToken(DetailAST aAST) { final DetailAST parenAST; if ((aAST.getType() == TokenTypes.METHOD_CALL)) { parenAST = aAST; } else { parenAST = aAST.findFirstToken(TokenTypes.LPAREN); // array construction => parenAST == null if (parenAST == null) { return; } } final String line = getLines()[parenAST.getLineNo() - 1]; if (Utils.whitespaceBefore(parenAST.getColumnNo(), line)) { if (!mAllowLineBreaks) { log(parenAST, "line.previous", parenAST.getText()); } } else { final int before = parenAST.getColumnNo() - 1; if ((PadOption.NOSPACE == getAbstractOption()) && (Character.isWhitespace(line.charAt(before)))) { log(parenAST , "ws.preceded", parenAST.getText()); } else if ((PadOption.SPACE == getAbstractOption()) && !Character.isWhitespace(line.charAt(before))) { log(parenAST, "ws.notPreceded", parenAST.getText()); } } } /** * Control whether whitespace is flagged at linebreaks. * @param aAllowLineBreaks whether whitespace should be * flagged at linebreaks. */ public void setAllowLineBreaks(boolean aAllowLineBreaks) { mAllowLineBreaks = aAllowLineBreaks; } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterChe100644 0 0 11167 12026051006 31410 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that there is no whitespace after a token. * More specifically, it checks that it is not followed by whitespace, * or (if linebreaks are allowed) all characters on the line after are * whitespace. To forbid linebreaks afer a token, set property * allowLineBreaks to false. *

*

By default the check will check the following operators: * {@link TokenTypes#ARRAY_INIT ARRAY_INIT}, * {@link TokenTypes#BNOT BNOT}, * {@link TokenTypes#DEC DEC}, * {@link TokenTypes#DOT DOT}, * {@link TokenTypes#INC INC}, * {@link TokenTypes#LNOT LNOT}, * {@link TokenTypes#UNARY_MINUS UNARY_MINUS}, * {@link TokenTypes#UNARY_PLUS UNARY_PLUS}. It also supports the operator * {@link TokenTypes#TYPECAST TYPECAST}. *

*

* An example of how to configure the check is: *

*
 * <module name="NoWhitespaceAfter"/>
 * 
*

An example of how to configure the check to forbid linebreaks after * a {@link TokenTypes#DOT DOT} token is: *

*
 * <module name="NoWhitespaceAfter">
 *     <property name="tokens" value="DOT"/>
 *     <property name="allowLineBreaks" value="false"/>
 * </module>
 * 
* @author Rick Giles * @author lkuehne * @version 1.0 */ public class NoWhitespaceAfterCheck extends Check { /** Whether whitespace is allowed if the AST is at a linebreak */ private boolean mAllowLineBreaks = true; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.ARRAY_INIT, TokenTypes.INC, TokenTypes.DEC, TokenTypes.UNARY_MINUS, TokenTypes.UNARY_PLUS, TokenTypes.BNOT, TokenTypes.LNOT, TokenTypes.DOT, }; } @Override public int[] getAcceptableTokens() { return new int[] { TokenTypes.ARRAY_INIT, TokenTypes.INC, TokenTypes.DEC, TokenTypes.UNARY_MINUS, TokenTypes.UNARY_PLUS, TokenTypes.BNOT, TokenTypes.LNOT, TokenTypes.DOT, TokenTypes.TYPECAST, }; } @Override public void visitToken(DetailAST aAST) { DetailAST targetAST = aAST; if (targetAST.getType() == TokenTypes.TYPECAST) { targetAST = targetAST.findFirstToken(TokenTypes.RPAREN); } final String line = getLines()[aAST.getLineNo() - 1]; final int after = targetAST.getColumnNo() + targetAST.getText().length(); if ((after >= line.length()) || Character.isWhitespace(line.charAt(after))) { boolean flag = !mAllowLineBreaks; for (int i = after + 1; !flag && (i < line.length()); i++) { if (!Character.isWhitespace(line.charAt(i))) { flag = true; } } if (flag) { log(targetAST.getLineNo(), after, "ws.followed", targetAST.getText()); } } } /** * Control whether whitespace is flagged at linebreaks. * @param aAllowLineBreaks whether whitespace should be * flagged at linebreaks. */ public void setAllowLineBreaks(boolean aAllowLineBreaks) { mAllowLineBreaks = aAllowLineBreaks; } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceBeforeCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceBeforeCh100644 0 0 10565 12026051005 31404 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that there is no whitespace before a token. * More specifically, it checks that it is not preceded with whitespace, * or (if linebreaks are allowed) all characters on the line before are * whitespace. To allow linebreaks before a token, set property * allowLineBreaks to true. *

*

By default the check will check the following operators: * {@link TokenTypes#SEMI SEMI}, * {@link TokenTypes#POST_DEC POST_DEC}, * {@link TokenTypes#POST_INC POST_INC}. * {@link TokenTypes#DOT DOT} is also an acceptable token in a configuration * of this check. *

* *

* An example of how to configure the check is: *

*
 * <module name="NoWhitespaceBefore"/>
 * 
*

An example of how to configure the check to allow linebreaks before * a {@link TokenTypes#DOT DOT} token is: *

*
 * <module name="NoWhitespaceBefore">
 *     <property name="tokens" value="DOT"/>
 *     <property name="allowLineBreaks" value="true"/>
 * </module>
 * 
* @author Rick Giles * @author lkuehne * @version 1.0 */ public class NoWhitespaceBeforeCheck extends Check { /** Whether whitespace is allowed if the AST is at a linebreak */ private boolean mAllowLineBreaks; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.SEMI, TokenTypes.POST_INC, TokenTypes.POST_DEC, }; } @Override public int[] getAcceptableTokens() { return new int[] { TokenTypes.SEMI, TokenTypes.POST_INC, TokenTypes.POST_DEC, TokenTypes.DOT, }; } @Override public void visitToken(DetailAST aAST) { final String[] lines = getLines(); final String line = lines[aAST.getLineNo() - 1]; final int before = aAST.getColumnNo() - 1; if ((before < 0) || Character.isWhitespace(line.charAt(before))) { // empty FOR initializer? if (aAST.getType() == TokenTypes.SEMI) { final DetailAST sibling = aAST.getPreviousSibling(); if ((sibling != null) && (sibling.getType() == TokenTypes.FOR_INIT) && (sibling.getChildCount() == 0)) { return; } } boolean flag = !mAllowLineBreaks; // verify all characters before '.' are whitespace for (int i = 0; !flag && (i < before); i++) { if (!Character.isWhitespace(line.charAt(i))) { flag = true; } } if (flag) { log(aAST.getLineNo(), before, "ws.preceded", aAST.getText()); } } } /** * Control whether whitespace is flagged at linebreaks. * @param aAllowLineBreaks whether whitespace should be * flagged at linebreaks. */ public void setAllowLineBreaks(boolean aAllowLineBreaks) { mAllowLineBreaks = aAllowLineBreaks; } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapCheck.ja100644 0 0 20453 12026051005 31366 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck; /** *

* Checks line wrapping for operators. * The policy to verify is specified using the {@link OperatorWrapOption} class * and defaults to {@link OperatorWrapOption#NL}. *

*

By default the check will check the following operators: * {@link TokenTypes#BAND BAND}, * {@link TokenTypes#BOR BOR}, * {@link TokenTypes#BSR BSR}, * {@link TokenTypes#BXOR BXOR}, * {@link TokenTypes#COLON COLON}, * {@link TokenTypes#DIV DIV}, * {@link TokenTypes#EQUAL EQUAL}, * {@link TokenTypes#GE GE}, * {@link TokenTypes#GT GT}, * {@link TokenTypes#LAND LAND}, * {@link TokenTypes#LE LE}, * {@link TokenTypes#LITERAL_INSTANCEOF LITERAL_INSTANCEOF}, * {@link TokenTypes#LOR LOR}, * {@link TokenTypes#LT LT}, * {@link TokenTypes#MINUS MINUS}, * {@link TokenTypes#MOD MOD}, * {@link TokenTypes#NOT_EQUAL NOT_EQUAL}, * {@link TokenTypes#PLUS PLUS}, * {@link TokenTypes#QUESTION QUESTION}, * {@link TokenTypes#SL SL}, * {@link TokenTypes#SR SR}, * {@link TokenTypes#STAR STAR}. * Other acceptable tokens are * {@link TokenTypes#ASSIGN ASSIGN}, * {@link TokenTypes#BAND_ASSIGN BAND_ASSIGN}, * {@link TokenTypes#BOR_ASSIGN BOR_ASSIGN}, * {@link TokenTypes#BSR_ASSIGN BSR_ASSIGN}, * {@link TokenTypes#BXOR_ASSIGN BXOR_ASSIGN}, * {@link TokenTypes#DIV_ASSIGN DIV_ASSIGN}, * {@link TokenTypes#MINUS_ASSIGN MINUS_ASSIGN}, * {@link TokenTypes#MOD_ASSIGN MOD_ASSIGN}, * {@link TokenTypes#PLUS_ASSIGN PLUS_ASSIGN}, * {@link TokenTypes#SL_ASSIGN SL_ASSIGN}, * {@link TokenTypes#SR_ASSIGN SR_ASSIGN}, * {@link TokenTypes#STAR_ASSIGN STAR_ASSIGN}. *

*

* An example of how to configure the check is: *

*
 * <module name="OperatorWrap"/>
 * 
*

An example of how to configure the check for assignment operators at the * end of a line is: *

*
 * <module name="OperatorWrap">
 *     <property name="tokens"
 *               value="ASSIGN,DIV_ASSIGN,PLUS_ASSIGN,MINUS_ASSIGN,STAR_ASSIGN,MOD_ASSIGN,SR_ASSIGN,BSR_ASSIGN,SL_ASSIGN,BXOR_ASSIGN,BOR_ASSIGN,BAND_ASSIGN"/>
 *     <property name="option" value="eol"/>
  * </module>
 * 
* * @author Rick Giles * @version 1.0 */ public class OperatorWrapCheck extends AbstractOptionCheck { /** * Sets the operator wrap option to new line. */ public OperatorWrapCheck() { super(OperatorWrapOption.NL, OperatorWrapOption.class); } @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.QUESTION, // '?' TokenTypes.COLON, // ':' (not reported for a case) TokenTypes.EQUAL, // "==" TokenTypes.NOT_EQUAL, // "!=" TokenTypes.DIV, // '/' TokenTypes.PLUS, //' +' (unary plus is UNARY_PLUS) TokenTypes.MINUS, // '-' (unary minus is UNARY_MINUS) TokenTypes.STAR, // '*' TokenTypes.MOD, // '%' TokenTypes.SR, // ">>" TokenTypes.BSR, // ">>>" TokenTypes.GE, // ">=" TokenTypes.GT, // ">" TokenTypes.SL, // "<<" TokenTypes.LE, // "<=" TokenTypes.LT, // '<' TokenTypes.BXOR, // '^' TokenTypes.BOR, // '|' TokenTypes.LOR, // "||" TokenTypes.BAND, // '&' TokenTypes.LAND, // "&&" TokenTypes.LITERAL_INSTANCEOF, }; } @Override public int[] getAcceptableTokens() { return new int[] { TokenTypes.QUESTION, // '?' TokenTypes.COLON, // ':' (not reported for a case) TokenTypes.EQUAL, // "==" TokenTypes.NOT_EQUAL, // "!=" TokenTypes.DIV, // '/' TokenTypes.PLUS, //' +' (unary plus is UNARY_PLUS) TokenTypes.MINUS, // '-' (unary minus is UNARY_MINUS) TokenTypes.STAR, // '*' TokenTypes.MOD, // '%' TokenTypes.SR, // ">>" TokenTypes.BSR, // ">>>" TokenTypes.GE, // ">=" TokenTypes.GT, // ">" TokenTypes.SL, // "<<" TokenTypes.LE, // "<=" TokenTypes.LT, // '<' TokenTypes.BXOR, // '^' TokenTypes.BOR, // '|' TokenTypes.LOR, // "||" TokenTypes.BAND, // '&' TokenTypes.LAND, // "&&" TokenTypes.LITERAL_INSTANCEOF, TokenTypes.ASSIGN, // '=' TokenTypes.DIV_ASSIGN, // "/=" TokenTypes.PLUS_ASSIGN, // "+=" TokenTypes.MINUS_ASSIGN, //"-=" TokenTypes.STAR_ASSIGN, // "*=" TokenTypes.MOD_ASSIGN, // "%=" TokenTypes.SR_ASSIGN, // ">>=" TokenTypes.BSR_ASSIGN, // ">>>=" TokenTypes.SL_ASSIGN, // "<<=" TokenTypes.BXOR_ASSIGN, // "^=" TokenTypes.BOR_ASSIGN, // "|=" TokenTypes.BAND_ASSIGN, // "&=" }; } @Override public void visitToken(DetailAST aAST) { if (aAST.getType() == TokenTypes.COLON) { final DetailAST parent = aAST.getParent(); if ((parent.getType() == TokenTypes.LITERAL_DEFAULT) || (parent.getType() == TokenTypes.LITERAL_CASE)) { //we do not want to check colon for cases and defaults return; } } final OperatorWrapOption wOp = getAbstractOption(); final String text = aAST.getText(); final int colNo = aAST.getColumnNo(); final int lineNo = aAST.getLineNo(); final String currentLine = getLines()[lineNo - 1]; // TODO: Handle comments before and after operator // Check if rest of line is whitespace, and not just the operator // by itself. This last bit is to handle the operator on a line by // itself. if ((wOp == OperatorWrapOption.NL) && !text.equals(currentLine.trim()) && (currentLine.substring(colNo + text.length()) .trim().length() == 0)) { log(lineNo, colNo, "line.new", text); } else if ((wOp == OperatorWrapOption.EOL) && Utils.whitespaceBefore(colNo - 1, currentLine)) { log(lineNo, colNo, "line.previous", text); } } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapOption.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapOption.j100644 0 0 2545 12026051005 31442 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; /** * Represents the options for wrapping on an operator. * * @author Rick Giles * @version 1.0 */ public enum OperatorWrapOption { /** Require that the operator is on a new line. */ NL, /** Require that the operator is at the end of the line. */ EOL; } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/package-info.java100644 0 0 2307 12026051004 30633 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the Whitespace checks that * are bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.checks.whitespace; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/PadOption.java100644 0 0 3020 12026051005 30176 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; /** * Represents the options for whitespace around parentheses. * * @author Oliver Burn * @version 1 * @see EmptyForIteratorPadCheck * @see ParenPadCheck */ public enum PadOption { /** * Represents no spacing following a left parenthesis * or preceding a right one. */ NOSPACE, /** * Represents mandatory spacing following a left parenthesis * and preceeing a right one. */ SPACE; } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java100644 0 0 13174 12026051004 30763 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

Checks the padding of parentheses; that is whether a space is required * after a left parenthesis and before a right parenthesis, or such spaces are * forbidden, with the exception that it does * not check for padding of the right parenthesis at an empty for iterator. * Use Check {@link EmptyForIteratorPadCheck EmptyForIteratorPad} to validate * empty for iterators. *

*

* The policy to verify is specified using the {@link PadOption} class and * defaults to {@link PadOption#NOSPACE}. *

*

By default the check will check parentheses that occur with the following * tokens: * {@link TokenTypes#CTOR_CALL CTOR_CALL}, * {@link TokenTypes#LPAREN LPAREN}, * {@link TokenTypes#METHOD_CALL METHOD_CALL}, * {@link TokenTypes#RPAREN RPAREN}, * {@link TokenTypes#SUPER_CTOR_CALL SUPER_CTOR_CALL}, *

*

* An example of how to configure the check is: *

*
 * <module name="ParenPad"/>
 * 
*

* An example of how to configure the check to require spaces for the * parentheses of constructor, method, and super constructor invocations is: *

*
 * <module name="ParenPad">
 *     <property name="tokens"
 *               value="CTOR_CALL, METHOD_CALL, SUPER_CTOR_CALL"/>
 *     <property name="option" value="space"/>
 * </module>
 * 
* @author Oliver Burn * @version 1.0 */ public class ParenPadCheck extends AbstractParenPadCheck { @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.RPAREN, TokenTypes.LPAREN, TokenTypes.CTOR_CALL, TokenTypes.SUPER_CTOR_CALL, TokenTypes.METHOD_CALL, }; } @Override public void visitToken(DetailAST aAST) { DetailAST theAst = aAST; // Strange logic in this method to guard against checking RPAREN tokens // that are associated with a TYPECAST token. if (theAst.getType() != TokenTypes.RPAREN) { if ((theAst.getType() == TokenTypes.CTOR_CALL) || (theAst.getType() == TokenTypes.SUPER_CTOR_CALL)) { theAst = theAst.getFirstChild(); } if (!isPreceedsEmptyForInit(theAst)) { processLeft(theAst); } } else if ((theAst.getParent() == null) || (theAst.getParent().getType() != TokenTypes.TYPECAST) || (theAst.getParent().findFirstToken(TokenTypes.RPAREN) != theAst)) { if (!isFollowsEmptyForIterator(theAst)) { processRight(theAst); } } } /** * @param aAST the token to check * @return whether a token follows an empty for iterator */ private boolean isFollowsEmptyForIterator(DetailAST aAST) { boolean followsEmptyForIterator = false; final DetailAST parent = aAST.getParent(); //Only traditional for statements are examined, not for-each statements if ((parent != null) && (parent.getType() == TokenTypes.LITERAL_FOR) && (parent.findFirstToken(TokenTypes.FOR_EACH_CLAUSE) == null)) { final DetailAST forIterator = parent.findFirstToken(TokenTypes.FOR_ITERATOR); followsEmptyForIterator = (forIterator.getChildCount() == 0) && (aAST == forIterator.getNextSibling()); } return followsEmptyForIterator; } /** * @param aAST the token to check * @return whether a token preceeds an empty for initializer */ private boolean isPreceedsEmptyForInit(DetailAST aAST) { boolean preceedsEmptyForInintializer = false; final DetailAST parent = aAST.getParent(); //Only traditional for statements are examined, not for-each statements if ((parent != null) && (parent.getType() == TokenTypes.LITERAL_FOR) && (parent.findFirstToken(TokenTypes.FOR_EACH_CLAUSE) == null)) { final DetailAST forIterator = parent.findFirstToken(TokenTypes.FOR_INIT); preceedsEmptyForInintializer = (forIterator.getChildCount() == 0) && (aAST == forIterator.getPreviousSibling()); } return preceedsEmptyForInintializer; } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/TypecastParenPadCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/TypecastParenPadChec100644 0 0 5556 12026051004 31372 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

Checks the padding of parentheses for typecasts. That is whether a space * is required after a left parenthesis and before a right parenthesis, or such * spaces are forbidden. *

*

* The policy to verify is specified using the {@link PadOption} class and * defaults to {@link PadOption#NOSPACE}. *

*

* An example of how to configure the check is: *

*
 * <module name="TypecastParenPad"/>
 * 
*

* An example of how to configure the check to require spaces for the * parentheses of constructor, method, and super constructor invocations is: *

*
 * <module name="TypecastParenPad">
 *     <property name="option" value="space"/>
 * </module>
 * 
* @author Oliver Burn * @version 1.0 */ public class TypecastParenPadCheck extends AbstractParenPadCheck { @Override public int[] getRequiredTokens() { return new int[] {TokenTypes.RPAREN, TokenTypes.TYPECAST}; } @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public void visitToken(DetailAST aAST) { // Strange logic in this method to guard against checking RPAREN tokens // that are not associated with a TYPECAST token. if (aAST.getType() == TokenTypes.TYPECAST) { processLeft(aAST); } else if ((aAST.getParent() != null) && (aAST.getParent().getType() == TokenTypes.TYPECAST) && (aAST.getParent().findFirstToken(TokenTypes.RPAREN) == aAST)) { processRight(aAST); } } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheck100644 0 0 10053 12026051004 31420 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** *

* Checks that a token is followed by whitespace, with the exception that it * does not check for whitespace after the semicolon of an empty for iterator. * Use Check {@link EmptyForIteratorPadCheck EmptyForIteratorPad} to validate * empty for iterators. *

*

By default the check will check the following tokens: * {@link TokenTypes#COMMA COMMA}, * {@link TokenTypes#SEMI SEMI}, * {@link TokenTypes#TYPECAST TYPECAST}. *

*

* An example of how to configure the check is: *

*
 * <module name="WhitespaceAfter"/>
 * 
*

An example of how to configure the check for whitespace only after * {@link TokenTypes#COMMA COMMA} and {@link TokenTypes#SEMI SEMI} tokens is: *

*
 * <module name="WhitespaceAfter">
 *     <property name="tokens" value="COMMA, SEMI"/>
 * </module>
 * 
* @author Oliver Burn * @author Rick Giles * @version 1.0 */ public class WhitespaceAfterCheck extends Check { @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.COMMA, TokenTypes.SEMI, TokenTypes.TYPECAST, }; } @Override public void visitToken(DetailAST aAST) { final Object[] message; final DetailAST targetAST; if (aAST.getType() == TokenTypes.TYPECAST) { targetAST = aAST.findFirstToken(TokenTypes.RPAREN); // TODO: i18n message = new Object[]{"cast"}; } else { targetAST = aAST; message = new Object[]{aAST.getText()}; } final String line = getLines()[targetAST.getLineNo() - 1]; final int after = targetAST.getColumnNo() + targetAST.getText().length(); if (after < line.length()) { final char charAfter = line.charAt(after); if ((targetAST.getType() == TokenTypes.SEMI) && ((charAfter == ';') || (charAfter == ')'))) { return; } if (!Character.isWhitespace(charAfter)) { //empty FOR_ITERATOR? if (targetAST.getType() == TokenTypes.SEMI) { final DetailAST sibling = targetAST.getNextSibling(); if ((sibling != null) && (sibling.getType() == TokenTypes.FOR_ITERATOR) && (sibling.getChildCount() == 0)) { return; } } log(targetAST.getLineNo(), targetAST.getColumnNo() + targetAST.getText().length(), "ws.notFollowed", message); } } } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAroundCheck.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAroundChec100644 0 0 31226 12026051004 31441 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** *

* Checks that a token is surrounded by whitespace. *

*

By default the check will check the following operators: * {@link TokenTypes#LITERAL_ASSERT ASSERT}, * {@link TokenTypes#ASSIGN ASSIGN}, * {@link TokenTypes#BAND BAND}, * {@link TokenTypes#BAND_ASSIGN BAND_ASSIGN}, * {@link TokenTypes#BOR BOR}, * {@link TokenTypes#BOR_ASSIGN BOR_ASSIGN}, * {@link TokenTypes#BSR BSR}, * {@link TokenTypes#BSR_ASSIGN BSR_ASSIGN}, * {@link TokenTypes#BXOR BXOR}, * {@link TokenTypes#BXOR_ASSIGN BXOR_ASSIGN}, * {@link TokenTypes#COLON COLON}, * {@link TokenTypes#DIV DIV}, * {@link TokenTypes#DIV_ASSIGN DIV_ASSIGN}, * {@link TokenTypes#EQUAL EQUAL}, * {@link TokenTypes#GE GE}, * {@link TokenTypes#GT GT}, * {@link TokenTypes#LAND LAND}, * {@link TokenTypes#LCURLY LCURLY}, * {@link TokenTypes#LE LE}, * {@link TokenTypes#LITERAL_CATCH LITERAL_CATCH}, * {@link TokenTypes#LITERAL_DO LITERAL_DO}, * {@link TokenTypes#LITERAL_ELSE LITERAL_ELSE}, * {@link TokenTypes#LITERAL_FINALLY LITERAL_FINALLY}, * {@link TokenTypes#LITERAL_FOR LITERAL_FOR}, * {@link TokenTypes#LITERAL_IF LITERAL_IF}, * {@link TokenTypes#LITERAL_RETURN LITERAL_RETURN}, * {@link TokenTypes#LITERAL_SYNCHRONIZED LITERAL_SYNCHRONIZED}, * {@link TokenTypes#LITERAL_TRY LITERAL_TRY}, * {@link TokenTypes#LITERAL_WHILE LITERAL_WHILE}, * {@link TokenTypes#LOR LOR}, * {@link TokenTypes#LT LT}, * {@link TokenTypes#MINUS MINUS}, * {@link TokenTypes#MINUS_ASSIGN MINUS_ASSIGN}, * {@link TokenTypes#MOD MOD}, * {@link TokenTypes#MOD_ASSIGN MOD_ASSIGN}, * {@link TokenTypes#NOT_EQUAL NOT_EQUAL}, * {@link TokenTypes#PLUS PLUS}, * {@link TokenTypes#PLUS_ASSIGN PLUS_ASSIGN}, * {@link TokenTypes#QUESTION QUESTION}, * {@link TokenTypes#RCURLY RCURLY}, * {@link TokenTypes#SL SL}, * {@link TokenTypes#SLIST SLIST}, * {@link TokenTypes#SL_ASSIGN SL_ASSIGN}, * {@link TokenTypes#SR SR}, * {@link TokenTypes#SR_ASSIGN SR_ASSIGN}, * {@link TokenTypes#STAR STAR}, * {@link TokenTypes#STAR_ASSIGN STAR_ASSIGN}. * {@link TokenTypes#LITERAL_ASSERT LITERAL_ASSERT}. * {@link TokenTypes#TYPE_EXTENSION_AND TYPE_EXTENSION_AND}. *

*

* An example of how to configure the check is: *

*
 * <module name="WhitespaceAround"/>
 * 
*

An example of how to configure the check for whitespace only around * assignment operators is: *

*
 * <module name="WhitespaceAround">
 *     <property name="tokens"
 *               value="ASSIGN,DIV_ASSIGN,PLUS_ASSIGN,MINUS_ASSIGN,STAR_ASSIGN,MOD_ASSIGN,SR_ASSIGN,BSR_ASSIGN,SL_ASSIGN,BXOR_ASSIGN,BOR_ASSIGN,BAND_ASSIGN"/>
 * </module>
 * 
*

* In addition, this check can be configured to allow empty method and/or * constructor bodies. For example, a method with an empty body might look * like: *

*

*

    public void doSomething(int val) {}
*

*

* To configure the check to allow empty method blocks use *

*

*

   <property name="allowEmptyMethods" value="true" />
*

*

* To configure the check to allow empty constructor blocks use *

*

*

   <property name="allowEmptyConstructors" value="true" />
*

* *

* Also, this check can be configured to ignore the colon in an enhanced for * loop. The colon in an enhanced for loop is ignored by default *

*

* To configure the check to ignore the colon *

*

*

   <property name="ignoreEnhancedForColon" value="true" />
*

* * @author Oliver Burn * @version 1.0 */ public class WhitespaceAroundCheck extends Check { /** Whether or not empty constructor bodies are allowed. */ private boolean mAllowEmptyCtors; /** Whether or not empty method bodies are allowed. */ private boolean mAllowEmptyMethods; /** whether or not to ignore a colon in a enhanced for loop */ private boolean mIgnoreEnhancedForColon = true; @Override public int[] getDefaultTokens() { return new int[] { TokenTypes.ASSIGN, TokenTypes.BAND, TokenTypes.BAND_ASSIGN, TokenTypes.BOR, TokenTypes.BOR_ASSIGN, TokenTypes.BSR, TokenTypes.BSR_ASSIGN, TokenTypes.BXOR, TokenTypes.BXOR_ASSIGN, TokenTypes.COLON, TokenTypes.DIV, TokenTypes.DIV_ASSIGN, TokenTypes.EQUAL, TokenTypes.GE, TokenTypes.GT, TokenTypes.LAND, TokenTypes.LCURLY, TokenTypes.LE, TokenTypes.LITERAL_CATCH, TokenTypes.LITERAL_DO, TokenTypes.LITERAL_ELSE, TokenTypes.LITERAL_FINALLY, TokenTypes.LITERAL_FOR, TokenTypes.LITERAL_IF, TokenTypes.LITERAL_RETURN, TokenTypes.LITERAL_SYNCHRONIZED, TokenTypes.LITERAL_TRY, TokenTypes.LITERAL_WHILE, TokenTypes.LOR, TokenTypes.LT, TokenTypes.MINUS, TokenTypes.MINUS_ASSIGN, TokenTypes.MOD, TokenTypes.MOD_ASSIGN, TokenTypes.NOT_EQUAL, TokenTypes.PLUS, TokenTypes.PLUS_ASSIGN, TokenTypes.QUESTION, TokenTypes.RCURLY, TokenTypes.SL, TokenTypes.SLIST, TokenTypes.SL_ASSIGN, TokenTypes.SR, TokenTypes.SR_ASSIGN, TokenTypes.STAR, TokenTypes.STAR_ASSIGN, TokenTypes.LITERAL_ASSERT, TokenTypes.TYPE_EXTENSION_AND, }; } /** * Sets whether or not empty method bodies are allowed. * @param aAllow true to allow empty method bodies. */ public void setAllowEmptyMethods(boolean aAllow) { mAllowEmptyMethods = aAllow; } /** * Sets whether or not empty constructor bodies are allowed. * @param aAllow true to allow empty constructor bodies. */ public void setAllowEmptyConstructors(boolean aAllow) { mAllowEmptyCtors = aAllow; } /** * Sets whether or not to ignore the whitespace around the * colon in an enhanced for loop. * @param aIgnore true to ignore enhanced for colon. */ public void setIgnoreEnhancedForColon(boolean aIgnore) { mIgnoreEnhancedForColon = aIgnore; } @Override public void visitToken(DetailAST aAST) { final int type = aAST.getType(); final int parentType = aAST.getParent().getType(); // Check for CURLY in array initializer if (((type == TokenTypes.RCURLY) || (type == TokenTypes.LCURLY)) && (parentType == TokenTypes.ARRAY_INIT)) { return; } // Check for import pkg.name.*; if ((type == TokenTypes.STAR) && (parentType == TokenTypes.DOT)) { return; } // Check for an SLIST that has a parent CASE_GROUP. It is not a '{'. if ((type == TokenTypes.SLIST) && (parentType == TokenTypes.CASE_GROUP)) { return; } if ((type == TokenTypes.COLON)) { //we do not want to check colon for cases and defaults if (parentType == TokenTypes.LITERAL_DEFAULT || parentType == TokenTypes.LITERAL_CASE) { return; } else if (parentType == TokenTypes.FOR_EACH_CLAUSE && this.mIgnoreEnhancedForColon) { return; } } // Check for allowed empty method or ctor blocks. if (emptyMethodBlockCheck(aAST, parentType) || emptyCtorBlockCheck(aAST, parentType)) { return; } final String[] lines = getLines(); final String line = lines[aAST.getLineNo() - 1]; final int before = aAST.getColumnNo() - 1; final int after = aAST.getColumnNo() + aAST.getText().length(); if ((before >= 0) && !Character.isWhitespace(line.charAt(before))) { log(aAST.getLineNo(), aAST.getColumnNo(), "ws.notPreceded", aAST.getText()); } if (after >= line.length()) { return; } final char nextChar = line.charAt(after); if (!Character.isWhitespace(nextChar) // Check for "return;" && !((type == TokenTypes.LITERAL_RETURN) && (aAST.getFirstChild().getType() == TokenTypes.SEMI)) // Check for "})" or "};" or "},". Happens with anon-inners && !((type == TokenTypes.RCURLY) && ((nextChar == ')') || (nextChar == ';') || (nextChar == ',')))) { log(aAST.getLineNo(), aAST.getColumnNo() + aAST.getText().length(), "ws.notFollowed", aAST.getText()); } } /** * Test if the given DetailAST is part of an allowed empty * method block. * @param aAST the DetailAST to test. * @param aParentType the token type of aAST's parent. * @return true if aAST makes up part of an * allowed empty method block. */ private boolean emptyMethodBlockCheck(DetailAST aAST, int aParentType) { return mAllowEmptyMethods && emptyBlockCheck(aAST, aParentType, TokenTypes.METHOD_DEF); } /** * Test if the given DetailAST is part of an allowed empty * constructor (ctor) block. * @param aAST the DetailAST to test. * @param aParentType the token type of aAST's parent. * @return true if aAST makes up part of an * allowed empty constructor block. */ private boolean emptyCtorBlockCheck(DetailAST aAST, int aParentType) { return mAllowEmptyCtors && emptyBlockCheck(aAST, aParentType, TokenTypes.CTOR_DEF); } /** * Test if the given DetailAST is part of an empty block. * An example empty block might look like the following *

*

   public void myMethod(int val) {}
*

* In the above, the method body is an empty block ("{}"). * * @param aAST the DetailAST to test. * @param aParentType the token type of aAST's parent. * @param aMatch the parent token type we're looking to match. * @return true if aAST makes up part of an * empty block contained under a aMatch token type * node. */ private boolean emptyBlockCheck(DetailAST aAST, int aParentType, int aMatch) { final int type = aAST.getType(); if (type == TokenTypes.RCURLY) { final DetailAST grandParent = aAST.getParent().getParent(); return (aParentType == TokenTypes.SLIST) && (grandParent.getType() == aMatch); } return (type == TokenTypes.SLIST) && (aParentType == aMatch) && (aAST.getFirstChild().getType() == TokenTypes.RCURLY); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/CheckStyleTask.java100644 0 0 53040 12026051077 25626 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.Utils; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.AuditListener; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import com.puppycrawl.tools.checkstyle.api.SeverityLevelCounter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URL; import java.util.Hashtable; import java.util.List; import java.util.Properties; import java.util.ResourceBundle; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.LogOutputStream; import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; /** * An implementation of a ANT task for calling checkstyle. See the documentation * of the task for usage. * @author Oliver Burn */ public class CheckStyleTask extends Task { /** poor man's enum for an xml formatter */ private static final String E_XML = "xml"; /** poor man's enum for an plain formatter */ private static final String E_PLAIN = "plain"; /** class path to locate class files */ private Path mClasspath; /** name of file to check */ private String mFileName; /** config file containing configuration */ private String mConfigLocation; /** whether to fail build on violations */ private boolean mFailOnViolation = true; /** property to set on violations */ private String mFailureProperty; /** contains the filesets to process */ private final List mFileSets = Lists.newArrayList(); /** contains the formatters to log to */ private final List mFormatters = Lists.newArrayList(); /** contains the Properties to override */ private final List mOverrideProps = Lists.newArrayList(); /** the name of the properties file */ private File mPropertiesFile; /** the maximum number of errors that are tolerated. */ private int mMaxErrors; /** the maximum number of warnings that are tolerated. */ private int mMaxWarnings = Integer.MAX_VALUE; /** * whether to omit ignored modules - some modules may log above * their severity depending on their configuration (e.g. WriteTag) so * need to be included */ private boolean mOmitIgnoredModules = true; //////////////////////////////////////////////////////////////////////////// // Setters for ANT specific attributes //////////////////////////////////////////////////////////////////////////// /** * Tells this task to set the named property to "true" when there * is a violation. * @param aPropertyName the name of the property to set * in the event of an failure. */ public void setFailureProperty(String aPropertyName) { mFailureProperty = aPropertyName; } /** @param aFail whether to fail if a violation is found */ public void setFailOnViolation(boolean aFail) { mFailOnViolation = aFail; } /** * Sets the maximum number of errors allowed. Default is 0. * @param aMaxErrors the maximum number of errors allowed. */ public void setMaxErrors(int aMaxErrors) { mMaxErrors = aMaxErrors; } /** * Sets the maximum number of warings allowed. Default is * {@link Integer#MAX_VALUE}. * @param aMaxWarnings the maximum number of warnings allowed. */ public void setMaxWarnings(int aMaxWarnings) { mMaxWarnings = aMaxWarnings; } /** * Adds a set of files (nested fileset attribute). * @param aFS the file set to add */ public void addFileset(FileSet aFS) { mFileSets.add(aFS); } /** * Add a formatter. * @param aFormatter the formatter to add for logging. */ public void addFormatter(Formatter aFormatter) { mFormatters.add(aFormatter); } /** * Add an override property. * @param aProperty the property to add */ public void addProperty(Property aProperty) { mOverrideProps.add(aProperty); } /** * Set the class path. * @param aClasspath the path to locate classes */ public void setClasspath(Path aClasspath) { if (mClasspath == null) { mClasspath = aClasspath; } else { mClasspath.append(aClasspath); } } /** * Set the class path from a reference defined elsewhere. * @param aClasspathRef the reference to an instance defining the classpath */ public void setClasspathRef(Reference aClasspathRef) { createClasspath().setRefid(aClasspathRef); } /** @return a created path for locating classes */ public Path createClasspath() { if (mClasspath == null) { mClasspath = new Path(getProject()); } return mClasspath.createPath(); } /** @param aFile the file to be checked */ public void setFile(File aFile) { mFileName = aFile.getAbsolutePath(); } /** @param aFile the configuration file to use */ public void setConfig(File aFile) { setConfigLocation(aFile.getAbsolutePath()); } /** @param aURL the URL of the configuration to use */ public void setConfigURL(URL aURL) { setConfigLocation(aURL.toExternalForm()); } /** * Sets the location of the configuration. * @param aLocation the location, which is either a */ private void setConfigLocation(String aLocation) { if (mConfigLocation != null) { throw new BuildException("Attributes 'config' and 'configURL' " + "must not be set at the same time"); } mConfigLocation = aLocation; } /** @param aOmit whether to omit ignored modules */ public void setOmitIgnoredModules(boolean aOmit) { mOmitIgnoredModules = aOmit; } //////////////////////////////////////////////////////////////////////////// // Setters for Checker configuration attributes //////////////////////////////////////////////////////////////////////////// /** * Sets a properties file for use instead * of individually setting them. * @param aProps the properties File to use */ public void setProperties(File aProps) { mPropertiesFile = aProps; } //////////////////////////////////////////////////////////////////////////// // The doers //////////////////////////////////////////////////////////////////////////// @Override public void execute() throws BuildException { final long startTime = System.currentTimeMillis(); try { realExecute(); } finally { final long endTime = System.currentTimeMillis(); log("Total execution took " + (endTime - startTime) + " ms.", Project.MSG_VERBOSE); } } /** * Helper implementation to perform execution. */ private void realExecute() { // output version info in debug mode final ResourceBundle compilationProperties = ResourceBundle .getBundle("checkstylecompilation"); final String version = compilationProperties .getString("checkstyle.compile.version"); final String compileTimestamp = compilationProperties .getString("checkstyle.compile.timestamp"); log("checkstyle version " + version, Project.MSG_VERBOSE); log("compiled on " + compileTimestamp, Project.MSG_VERBOSE); // Check for no arguments if ((mFileName == null) && (mFileSets.size() == 0)) { throw new BuildException( "Must specify atleast one of 'file' or nested 'fileset'.", getLocation()); } if (mConfigLocation == null) { throw new BuildException("Must specify 'config'.", getLocation()); } // Create the checker Checker c = null; try { c = createChecker(); final SeverityLevelCounter warningCounter = new SeverityLevelCounter(SeverityLevel.WARNING); c.addListener(warningCounter); // Process the files long startTime = System.currentTimeMillis(); final List files = scanFileSets(); long endTime = System.currentTimeMillis(); log("To locate the files took " + (endTime - startTime) + " ms.", Project.MSG_VERBOSE); log("Running Checkstyle " + version + " on " + files.size() + " files", Project.MSG_INFO); log("Using configuration " + mConfigLocation, Project.MSG_VERBOSE); startTime = System.currentTimeMillis(); final int numErrs = c.process(files); endTime = System.currentTimeMillis(); log("To process the files took " + (endTime - startTime) + " ms.", Project.MSG_VERBOSE); final int numWarnings = warningCounter.getCount(); final boolean ok = (numErrs <= mMaxErrors) && (numWarnings <= mMaxWarnings); // Handle the return status if (!ok) { final String failureMsg = "Got " + numErrs + " errors and " + numWarnings + " warnings."; if (mFailureProperty != null) { getProject().setProperty(mFailureProperty, failureMsg); } if (mFailOnViolation) { throw new BuildException(failureMsg, getLocation()); } } } finally { if (c != null) { c.destroy(); } } } /** * Creates new instance of Checker. * @return new instance of Checker */ private Checker createChecker() { Checker c = null; try { final Properties props = createOverridingProperties(); final Configuration config = ConfigurationLoader.loadConfiguration( mConfigLocation, new PropertiesExpander(props), mOmitIgnoredModules); final DefaultContext context = new DefaultContext(); final ClassLoader loader = new AntClassLoader(getProject(), mClasspath); context.add("classloader", loader); final ClassLoader moduleClassLoader = Checker.class.getClassLoader(); context.add("moduleClassLoader", moduleClassLoader); c = new Checker(); c.contextualize(context); c.configure(config); // setup the listeners final AuditListener[] listeners = getListeners(); for (AuditListener element : listeners) { c.addListener(element); } } catch (final Exception e) { throw new BuildException("Unable to create a Checker: " + e.getMessage(), e); } return c; } /** * Create the Properties object based on the arguments specified * to the ANT task. * @return the properties for property expansion expansion * @throws BuildException if an error occurs */ private Properties createOverridingProperties() { final Properties retVal = new Properties(); // Load the properties file if specified if (mPropertiesFile != null) { FileInputStream inStream = null; try { inStream = new FileInputStream(mPropertiesFile); retVal.load(inStream); } catch (final FileNotFoundException e) { throw new BuildException("Could not find Properties file '" + mPropertiesFile + "'", e, getLocation()); } catch (final IOException e) { throw new BuildException("Error loading Properties file '" + mPropertiesFile + "'", e, getLocation()); } finally { Utils.closeQuietly(inStream); } } // override with Ant properties like ${basedir} final Hashtable antProps = this.getProject().getProperties(); for (Object name : antProps.keySet()) { final String key = (String) name; final String value = String.valueOf(antProps.get(key)); retVal.put(key, value); } // override with properties specified in subelements for (Property p : mOverrideProps) { retVal.put(p.getKey(), p.getValue()); } return retVal; } /** * Return the list of listeners set in this task. * @return the list of listeners. * @throws ClassNotFoundException if an error occurs * @throws InstantiationException if an error occurs * @throws IllegalAccessException if an error occurs * @throws IOException if an error occurs */ protected AuditListener[] getListeners() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException { final int formatterCount = Math.max(1, mFormatters.size()); final AuditListener[] listeners = new AuditListener[formatterCount]; // formatters if (mFormatters.size() == 0) { final OutputStream debug = new LogOutputStream(this, Project.MSG_DEBUG); final OutputStream err = new LogOutputStream(this, Project.MSG_ERR); listeners[0] = new DefaultLogger(debug, true, err, true); } else { for (int i = 0; i < formatterCount; i++) { final Formatter f = mFormatters.get(i); listeners[i] = f.createListener(this); } } return listeners; } /** * returns the list of files (full path name) to process. * @return the list of files included via the filesets. */ protected List scanFileSets() { final List list = Lists.newArrayList(); if (mFileName != null) { // oops we've got an additional one to process, don't // forget it. No sweat, it's fully resolved via the setter. log("Adding standalone file for audit", Project.MSG_VERBOSE); list.add(new File(mFileName)); } for (int i = 0; i < mFileSets.size(); i++) { final FileSet fs = mFileSets.get(i); final DirectoryScanner ds = fs.getDirectoryScanner(getProject()); ds.scan(); final String[] names = ds.getIncludedFiles(); log(i + ") Adding " + names.length + " files from directory " + ds.getBasedir(), Project.MSG_VERBOSE); for (String element : names) { final String pathname = ds.getBasedir() + File.separator + element; list.add(new File(pathname)); } } return list; } /** * Poor mans enumeration for the formatter types. * @author Oliver Burn */ public static class FormatterType extends EnumeratedAttribute { /** my possible values */ private static final String[] VALUES = {E_XML, E_PLAIN}; @Override public String[] getValues() { return VALUES.clone(); } } /** * Details about a formatter to be used. * @author Oliver Burn */ public static class Formatter { /** the formatter type */ private FormatterType mFormatterType; /** the file to output to */ private File mToFile; /** Whether or not the write to the named file. */ private boolean mUseFile = true; /** * Set the type of the formatter. * @param aType the type */ public void setType(FormatterType aType) { final String val = aType.getValue(); if (!E_XML.equals(val) && !E_PLAIN.equals(val)) { throw new BuildException("Invalid formatter type: " + val); } mFormatterType = aType; } /** * Set the file to output to. * @param aTo the file to output to */ public void setTofile(File aTo) { mToFile = aTo; } /** * Sets whether or not we write to a file if it is provided. * @param aUse whether not not to use provided file. */ public void setUseFile(boolean aUse) { mUseFile = aUse; } /** * Creates a listener for the formatter. * @param aTask the task running * @return a listener * @throws IOException if an error occurs */ public AuditListener createListener(Task aTask) throws IOException { if ((mFormatterType != null) && E_XML.equals(mFormatterType.getValue())) { return createXMLLogger(aTask); } return createDefaultLogger(aTask); } /** * @return a DefaultLogger instance * @param aTask the task to possibly log to * @throws IOException if an error occurs */ private AuditListener createDefaultLogger(Task aTask) throws IOException { if ((mToFile == null) || !mUseFile) { return new DefaultLogger( new LogOutputStream(aTask, Project.MSG_DEBUG), true, new LogOutputStream(aTask, Project.MSG_ERR), true); } return new DefaultLogger(new FileOutputStream(mToFile), true); } /** * @return an XMLLogger instance * @param aTask the task to possibly log to * @throws IOException if an error occurs */ private AuditListener createXMLLogger(Task aTask) throws IOException { if ((mToFile == null) || !mUseFile) { return new XMLLogger(new LogOutputStream(aTask, Project.MSG_INFO), true); } return new XMLLogger(new FileOutputStream(mToFile), true); } } /** * Represents a property that consists of a key and value. */ public static class Property { /** the property key */ private String mKey; /** the property value */ private String mValue; /** @return the property key */ public String getKey() { return mKey; } /** @param aKey sets the property key */ public void setKey(String aKey) { mKey = aKey; } /** @return the property value */ public String getValue() { return mValue; } /** @param aValue set the property value */ public void setValue(String aValue) { mValue = aValue; } /** @param aValue set the property value from a File */ public void setFile(File aValue) { setValue(aValue.getAbsolutePath()); } } /** Represents a custom listener. */ public static class Listener { /** classname of the listener class */ private String mClassname; /** @return the classname */ public String getClassname() { return mClassname; } /** @param aClassname set the classname */ public void setClassname(String aClassname) { mClassname = aClassname; } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java100644 0 0 55527 12026051077 26717 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.puppycrawl.tools.checkstyle.api.AbstractLoader; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.api.FastStack; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Loads a configuration from a standard configuration XML file. * * @author Oliver Burn * @version 1.0 */ public final class ConfigurationLoader { /** the public ID for version 1_0 of the configuration dtd */ private static final String DTD_PUBLIC_ID_1_0 = "-//Puppy Crawl//DTD Check Configuration 1.0//EN"; /** the resource for version 1_0 of the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_0 = "com/puppycrawl/tools/checkstyle/configuration_1_0.dtd"; /** the public ID for version 1_1 of the configuration dtd */ private static final String DTD_PUBLIC_ID_1_1 = "-//Puppy Crawl//DTD Check Configuration 1.1//EN"; /** the resource for version 1_1 of the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_1 = "com/puppycrawl/tools/checkstyle/configuration_1_1.dtd"; /** the public ID for version 1_2 of the configuration dtd */ private static final String DTD_PUBLIC_ID_1_2 = "-//Puppy Crawl//DTD Check Configuration 1.2//EN"; /** the resource for version 1_2 of the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_2 = "com/puppycrawl/tools/checkstyle/configuration_1_2.dtd"; /** the public ID for version 1_3 of the configuration dtd */ private static final String DTD_PUBLIC_ID_1_3 = "-//Puppy Crawl//DTD Check Configuration 1.3//EN"; /** the resource for version 1_3 of the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_3 = "com/puppycrawl/tools/checkstyle/configuration_1_3.dtd"; /** * Implements the SAX document handler interfaces, so they do not * appear in the public API of the ConfigurationLoader. */ private final class InternalLoader extends AbstractLoader { /** module elements */ private static final String MODULE = "module"; /** name attribute */ private static final String NAME = "name"; /** property element */ private static final String PROPERTY = "property"; /** value attribute */ private static final String VALUE = "value"; /** default attribute */ private static final String DEFAULT = "default"; /** name of the severity property */ private static final String SEVERITY = "severity"; /** name of the message element */ private static final String MESSAGE = "message"; /** name of the key attribute */ private static final String KEY = "key"; /** * Creates a new InternalLoader. * @throws SAXException if an error occurs * @throws ParserConfigurationException if an error occurs */ private InternalLoader() throws SAXException, ParserConfigurationException { // super(DTD_PUBLIC_ID_1_1, DTD_RESOURCE_NAME_1_1); super(createIdToResourceNameMap()); } @Override public void startElement(String aNamespaceURI, String aLocalName, String aQName, Attributes aAtts) throws SAXException { // TODO: debug logging for support purposes if (aQName.equals(MODULE)) { //create configuration final String name = aAtts.getValue(NAME); final DefaultConfiguration conf = new DefaultConfiguration(name); if (mConfiguration == null) { mConfiguration = conf; } //add configuration to it's parent if (!mConfigStack.isEmpty()) { final DefaultConfiguration top = mConfigStack.peek(); top.addChild(conf); } mConfigStack.push(conf); } else if (aQName.equals(PROPERTY)) { //extract name and value final String name = aAtts.getValue(NAME); final String value; try { value = replaceProperties(aAtts.getValue(VALUE), mOverridePropsResolver, aAtts.getValue(DEFAULT)); } catch (final CheckstyleException ex) { throw new SAXException(ex.getMessage()); } //add to attributes of configuration final DefaultConfiguration top = mConfigStack.peek(); top.addAttribute(name, value); } else if (aQName.equals(MESSAGE)) { //extract key and value final String key = aAtts.getValue(KEY); final String value = aAtts.getValue(VALUE); //add to messages of configuration final DefaultConfiguration top = mConfigStack.peek(); top.addMessage(key, value); } } @Override public void endElement(String aNamespaceURI, String aLocalName, String aQName) throws SAXException { if (aQName.equals(MODULE)) { final Configuration recentModule = mConfigStack.pop(); // remove modules with severity ignore if these modules should // be omitted SeverityLevel level = null; try { final String severity = recentModule.getAttribute(SEVERITY); level = SeverityLevel.getInstance(severity); } catch (final CheckstyleException e) { //severity not set -> ignore ; } // omit this module if these should be omitted and the module // has the severity 'ignore' final boolean omitModule = mOmitIgnoredModules && SeverityLevel.IGNORE.equals(level); if (omitModule && !mConfigStack.isEmpty()) { final DefaultConfiguration parentModule = mConfigStack.peek(); parentModule.removeChild(recentModule); } } } } /** the SAX document handler */ private final InternalLoader mSaxHandler; /** property resolver **/ private final PropertyResolver mOverridePropsResolver; /** the loaded configurations **/ private final FastStack mConfigStack = FastStack.newInstance(); /** the Configuration that is being built */ private Configuration mConfiguration; /** flags if modules with the severity 'ignore' should be omitted. */ private final boolean mOmitIgnoredModules; /** * Creates mapping between local resources and dtd ids. * @return map between local resources and dtd ids. */ private static Map createIdToResourceNameMap() { final Map map = Maps.newHashMap(); map.put(DTD_PUBLIC_ID_1_0, DTD_RESOURCE_NAME_1_0); map.put(DTD_PUBLIC_ID_1_1, DTD_RESOURCE_NAME_1_1); map.put(DTD_PUBLIC_ID_1_2, DTD_RESOURCE_NAME_1_2); map.put(DTD_PUBLIC_ID_1_3, DTD_RESOURCE_NAME_1_3); return map; } /** * Creates a new ConfigurationLoader instance. * @param aOverrideProps resolver for overriding properties * @param aOmitIgnoredModules true if ignored modules should be * omitted * @throws ParserConfigurationException if an error occurs * @throws SAXException if an error occurs */ private ConfigurationLoader(final PropertyResolver aOverrideProps, final boolean aOmitIgnoredModules) throws ParserConfigurationException, SAXException { mSaxHandler = new InternalLoader(); mOverridePropsResolver = aOverrideProps; mOmitIgnoredModules = aOmitIgnoredModules; } /** * Parses the specified input source loading the configuration information. * The stream wrapped inside the source, if any, is NOT * explicitely closed after parsing, it is the responsibility of * the caller to close the stream. * * @param aSource the source that contains the configuration data * @throws IOException if an error occurs * @throws SAXException if an error occurs */ private void parseInputSource(InputSource aSource) throws IOException, SAXException { mSaxHandler.parseInputSource(aSource); } /** * Returns the module configurations in a specified file. * @param aConfig location of config file, can be either a URL or a filename * @param aOverridePropsResolver overriding properties * @return the check configurations * @throws CheckstyleException if an error occurs */ public static Configuration loadConfiguration(String aConfig, PropertyResolver aOverridePropsResolver) throws CheckstyleException { return loadConfiguration(aConfig, aOverridePropsResolver, false); } /** * Returns the module configurations in a specified file. * * @param aConfig location of config file, can be either a URL or a filename * @param aOverridePropsResolver overriding properties * @param aOmitIgnoredModules true if modules with severity * 'ignore' should be omitted, false otherwise * @return the check configurations * @throws CheckstyleException if an error occurs */ public static Configuration loadConfiguration(String aConfig, PropertyResolver aOverridePropsResolver, boolean aOmitIgnoredModules) throws CheckstyleException { try { // figure out if this is a File or a URL URI uri; try { final URL url = new URL(aConfig); uri = url.toURI(); } catch (final MalformedURLException ex) { uri = null; } catch (final URISyntaxException ex) { // URL violating RFC 2396 uri = null; } if (uri == null) { final File file = new File(aConfig); if (file.exists()) { uri = file.toURI(); } else { // check to see if the file is in the classpath try { final URL configUrl = ConfigurationLoader.class .getResource(aConfig); if (configUrl == null) { throw new FileNotFoundException(aConfig); } uri = configUrl.toURI(); } catch (final URISyntaxException e) { throw new FileNotFoundException(aConfig); } } } final InputSource source = new InputSource(uri.toString()); return loadConfiguration(source, aOverridePropsResolver, aOmitIgnoredModules); } catch (final FileNotFoundException e) { throw new CheckstyleException("unable to find " + aConfig, e); } catch (final CheckstyleException e) { //wrap again to add file name info throw new CheckstyleException("unable to read " + aConfig + " - " + e.getMessage(), e); } } /** * Returns the module configurations from a specified input stream. * Note that clients are required to close the given stream by themselves * * @param aConfigStream the input stream to the Checkstyle configuration * @param aOverridePropsResolver overriding properties * @param aOmitIgnoredModules true if modules with severity * 'ignore' should be omitted, false otherwise * @return the check configurations * @throws CheckstyleException if an error occurs * * @deprecated As this method does not provide a valid system ID, * preventing resolution of external entities, a * {@link #loadConfiguration(InputSource,PropertyResolver,boolean) * version using an InputSource} * should be used instead */ @Deprecated public static Configuration loadConfiguration(InputStream aConfigStream, PropertyResolver aOverridePropsResolver, boolean aOmitIgnoredModules) throws CheckstyleException { return loadConfiguration(new InputSource(aConfigStream), aOverridePropsResolver, aOmitIgnoredModules); } /** * Returns the module configurations from a specified input source. * Note that if the source does wrap an open byte or character * stream, clients are required to close that stream by themselves * * @param aConfigSource the input stream to the Checkstyle configuration * @param aOverridePropsResolver overriding properties * @param aOmitIgnoredModules true if modules with severity * 'ignore' should be omitted, false otherwise * @return the check configurations * @throws CheckstyleException if an error occurs */ public static Configuration loadConfiguration(InputSource aConfigSource, PropertyResolver aOverridePropsResolver, boolean aOmitIgnoredModules) throws CheckstyleException { try { final ConfigurationLoader loader = new ConfigurationLoader(aOverridePropsResolver, aOmitIgnoredModules); loader.parseInputSource(aConfigSource); return loader.getConfiguration(); } catch (final ParserConfigurationException e) { throw new CheckstyleException( "unable to parse configuration stream", e); } catch (final SAXParseException e) { throw new CheckstyleException("unable to parse configuration stream" + " - " + e.getMessage() + ":" + e.getLineNumber() + ":" + e.getColumnNumber(), e); } catch (final SAXException e) { throw new CheckstyleException("unable to parse configuration stream" + " - " + e.getMessage(), e); } catch (final IOException e) { throw new CheckstyleException("unable to read from stream", e); } } /** * Returns the configuration in the last file parsed. * @return Configuration object */ private Configuration getConfiguration() { return mConfiguration; } /** * Replaces ${xxx} style constructions in the given value * with the string value of the corresponding data types. * * The method is package visible to facilitate testing. * * @param aValue The string to be scanned for property references. * May be null, in which case this * method returns immediately with no effect. * @param aProps Mapping (String to String) of property names to their * values. Must not be null. * @param aDefaultValue default to use if one of the properties in aValue * cannot be resolved from aProps. * * @throws CheckstyleException if the string contains an opening * ${ without a closing * } * @return the original string with the properties replaced, or * null if the original string is null. * * Code copied from ant - * http://cvs.apache.org/viewcvs/jakarta-ant/src/main/org/apache/tools/ant/ProjectHelper.java */ // Package visible for testing purposes static String replaceProperties( String aValue, PropertyResolver aProps, String aDefaultValue) throws CheckstyleException { if (aValue == null) { return null; } final List fragments = Lists.newArrayList(); final List propertyRefs = Lists.newArrayList(); parsePropertyString(aValue, fragments, propertyRefs); final StringBuffer sb = new StringBuffer(); final Iterator i = fragments.iterator(); final Iterator j = propertyRefs.iterator(); while (i.hasNext()) { String fragment = i.next(); if (fragment == null) { final String propertyName = j.next(); fragment = aProps.resolve(propertyName); if (fragment == null) { if (aDefaultValue != null) { return aDefaultValue; } throw new CheckstyleException( "Property ${" + propertyName + "} has not been set"); } } sb.append(fragment); } return sb.toString(); } /** * Parses a string containing ${xxx} style property * references into two lists. The first list is a collection * of text fragments, while the other is a set of string property names. * null entries in the first list indicate a property * reference from the second list. * * @param aValue Text to parse. Must not be null. * @param aFragments List to add text fragments to. * Must not be null. * @param aPropertyRefs List to add property names to. * Must not be null. * * @throws CheckstyleException if the string contains an opening * ${ without a closing * } * Code copied from ant - * http://cvs.apache.org/viewcvs/jakarta-ant/src/main/org/apache/tools/ant/ProjectHelper.java */ private static void parsePropertyString(String aValue, List aFragments, List aPropertyRefs) throws CheckstyleException { int prev = 0; int pos; //search for the next instance of $ from the 'prev' position while ((pos = aValue.indexOf("$", prev)) >= 0) { //if there was any text before this, add it as a fragment //TODO, this check could be modified to go if pos>prev; //seems like this current version could stick empty strings //into the list if (pos > 0) { aFragments.add(aValue.substring(prev, pos)); } //if we are at the end of the string, we tack on a $ //then move past it if (pos == (aValue.length() - 1)) { aFragments.add("$"); prev = pos + 1; } else if (aValue.charAt(pos + 1) != '{') { //peek ahead to see if the next char is a property or not //not a property: insert the char as a literal /* fragments.addElement(value.substring(pos + 1, pos + 2)); prev = pos + 2; */ if (aValue.charAt(pos + 1) == '$') { //backwards compatibility two $ map to one mode aFragments.add("$"); prev = pos + 2; } else { //new behaviour: $X maps to $X for all values of X!='$' aFragments.add(aValue.substring(pos, pos + 2)); prev = pos + 2; } } else { //property found, extract its name or bail on a typo final int endName = aValue.indexOf('}', pos); if (endName < 0) { throw new CheckstyleException("Syntax error in property: " + aValue); } final String propertyName = aValue.substring(pos + 2, endName); aFragments.add(null); aPropertyRefs.add(propertyName); prev = endName + 1; } } //no more $ signs found //if there is any tail to the file, append it if (prev < aValue.length()) { aFragments.add(aValue.substring(prev)); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/configuration_1_0.dtd100644 0 0 705 11451071613 26044 0ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/configuration_1_1.dtd100644 0 0 2030 11451071613 26056 0ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/configuration_1_2.dtd100644 0 0 2064 11451071613 26066 0ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/configuration_1_3.dtd100644 0 0 3205 11451071613 26065 0ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/DefaultConfiguration.java100644 0 0 11164 12026051076 27061 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import java.util.List; import java.util.Map; import java.util.Set; /** * Default implementation of the Configuration interface. * @author lkuehne */ public final class DefaultConfiguration implements Configuration { /** Required for serialization. */ private static final long serialVersionUID = 1157875385356127169L; /** The name of this configuration */ private final String mName; /** the list of child Configurations */ private final List mChildren = Lists.newArrayList(); /** the map from attribute names to attribute values */ private final Map mAttributeMap = Maps.newHashMap(); /** the map containing custom messages. */ private final Map mMessages = Maps.newHashMap(); /** * Instantiates a DefaultConfiguration. * @param aName the name for this DefaultConfiguration. */ public DefaultConfiguration(String aName) { mName = aName; } /** {@inheritDoc} */ public String[] getAttributeNames() { final Set keySet = mAttributeMap.keySet(); return keySet.toArray(new String[keySet.size()]); } /** {@inheritDoc} */ public String getAttribute(String aName) throws CheckstyleException { if (!mAttributeMap.containsKey(aName)) { // TODO: i18n throw new CheckstyleException( "missing key '" + aName + "' in " + getName()); } return mAttributeMap.get(aName); } /** {@inheritDoc} */ public Configuration[] getChildren() { return mChildren.toArray( new Configuration[mChildren.size()]); } /** {@inheritDoc} */ public String getName() { return mName; } /** * Makes a configuration a child of this configuration. * @param aConfiguration the child configuration. */ public void addChild(Configuration aConfiguration) { mChildren.add(aConfiguration); } /** * Removes a child of this configuration. * @param aConfiguration the child configuration to remove. */ public void removeChild(final Configuration aConfiguration) { mChildren.remove(aConfiguration); } /** * Adds an attribute to this configuration. * @param aName the name of the attribute. * @param aValue the value of the attribute. */ public void addAttribute(String aName, String aValue) { final String current = mAttributeMap.put(aName, aValue); if (null == current) { mAttributeMap.put(aName, aValue); } else { mAttributeMap.put(aName, current + "," + aValue); } } /** * Adds a custom message to this configuration. * @param aKey the message key * @param aValue the custom message pattern */ public void addMessage(String aKey, String aValue) { mMessages.put(aKey, aValue); } /** * Returns an unmodifiable map instance containing the custom messages * for this configuration. * @return unmodifiable map containing custom messages */ public ImmutableMap getMessages() { return ImmutableMap.copyOf(mMessages); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/DefaultContext.java100644 0 0 4006 12026051076 25653 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.Maps; import com.puppycrawl.tools.checkstyle.api.Context; import java.util.Map; /** * A default implementation of the Context interface. * @author lkuehne */ public final class DefaultContext implements Context { /** stores the context entries */ private final Map mEntries = Maps.newHashMap(); /** {@inheritDoc} */ public Object get(String aKey) { return mEntries.get(aKey); } /** {@inheritDoc} */ public ImmutableCollection getAttributeNames() { return ImmutableList.copyOf(mEntries.keySet()); } /** * Adds a context entry. * @param aKey the context key * @param aValue the value for aKey */ public void add(String aKey, Object aValue) { mEntries.put(aKey, aValue); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/DefaultLogger.java100644 0 0 13337 12026051076 25475 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.io.OutputStream; import java.io.PrintWriter; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AuditListener; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; /** * Simple plain logger for text output. * This is maybe not very suitable for a text output into a file since it * does not need all 'audit finished' and so on stuff, but it looks good on * stdout anyway. If there is really a problem this is what XMLLogger is for. * It gives structure. * * @author Stephane Bailliez * @see XMLLogger */ public class DefaultLogger extends AutomaticBean implements AuditListener { /** cushion for avoiding StringBuffer.expandCapacity */ private static final int BUFFER_CUSHION = 12; /** where to write info messages **/ private final PrintWriter mInfoWriter; /** close info stream after use */ private final boolean mCloseInfo; /** where to write error messages **/ private final PrintWriter mErrorWriter; /** close error stream after use */ private final boolean mCloseError; /** * Creates a new DefaultLogger instance. * @param aOS where to log infos and errors * @param aCloseStreamsAfterUse if aOS should be closed in auditFinished() */ public DefaultLogger(OutputStream aOS, boolean aCloseStreamsAfterUse) { // no need to close aOS twice this(aOS, aCloseStreamsAfterUse, aOS, false); } /** * Creates a new DefaultLogger instance. * * @param aInfoStream the OutputStream for info messages * @param aCloseInfoAfterUse auditFinished should close aInfoStream * @param aErrorStream the OutputStream for error messages * @param aCloseErrorAfterUse auditFinished should close aErrorStream */ public DefaultLogger(OutputStream aInfoStream, boolean aCloseInfoAfterUse, OutputStream aErrorStream, boolean aCloseErrorAfterUse) { mCloseInfo = aCloseInfoAfterUse; mCloseError = aCloseErrorAfterUse; mInfoWriter = new PrintWriter(aInfoStream); mErrorWriter = (aInfoStream == aErrorStream) ? mInfoWriter : new PrintWriter(aErrorStream); } /** * Print an Emacs compliant line on the error stream. * If the column number is non zero, then also display it. * @param aEvt {@inheritDoc} * @see AuditListener **/ public void addError(AuditEvent aEvt) { final SeverityLevel severityLevel = aEvt.getSeverityLevel(); if (!SeverityLevel.IGNORE.equals(severityLevel)) { final String fileName = aEvt.getFileName(); final String message = aEvt.getMessage(); // avoid StringBuffer.expandCapacity final int bufLen = fileName.length() + message.length() + BUFFER_CUSHION; final StringBuffer sb = new StringBuffer(bufLen); sb.append(fileName); sb.append(':').append(aEvt.getLine()); if (aEvt.getColumn() > 0) { sb.append(':').append(aEvt.getColumn()); } if (SeverityLevel.WARNING.equals(severityLevel)) { sb.append(": warning"); } sb.append(": ").append(message); mErrorWriter.println(sb.toString()); } } /** {@inheritDoc} */ public void addException(AuditEvent aEvt, Throwable aThrowable) { synchronized (mErrorWriter) { mErrorWriter.println("Error auditing " + aEvt.getFileName()); aThrowable.printStackTrace(mErrorWriter); } } /** {@inheritDoc} */ public void auditStarted(AuditEvent aEvt) { mInfoWriter.println("Starting audit..."); } /** {@inheritDoc} */ public void fileFinished(AuditEvent aEvt) { } /** {@inheritDoc} */ public void fileStarted(AuditEvent aEvt) { } /** {@inheritDoc} */ public void auditFinished(AuditEvent aEvt) { mInfoWriter.println("Audit done."); closeStreams(); } /** * Flushes the output streams and closes them if needed. */ protected void closeStreams() { mInfoWriter.flush(); if (mCloseInfo) { mInfoWriter.close(); } mErrorWriter.flush(); if (mCloseError) { mErrorWriter.close(); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/Defn.java100644 0 0 2752 12026051076 23604 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Contains constant definitions common to the package. * @author Oliver Burn **/ public final class Defn { ///CLOVER:OFF /** * Do no allow Defn instances to be created. **/ private Defn() { } ///CLOVER:ON /** Name of resource bundle for Checkstyle. */ public static final String CHECKSTYLE_BUNDLE = "com.puppycrawl.tools.checkstyle.messages"; } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/doclets/CheckDocsDoclet.java100644 0 0 21616 12026051004 27355 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.doclets; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import com.sun.javadoc.ClassDoc; import com.sun.javadoc.RootDoc; import com.sun.javadoc.Tag; /** * Doclet which is used to extract Anakia input files from the * Javadoc of Check implementations, so the Check's docs are * autogenerated. * * @author lkuehne */ public final class CheckDocsDoclet { /** javadoc command line option for dest dir. */ private static final String DEST_DIR_OPT = "-d"; /** Stop instances being created. */ private CheckDocsDoclet() { } /** * Comparator that compares the {@link ClassDoc ClassDocs} of two checks * by their check name. */ private static class ClassDocByCheckNameComparator implements Comparator { /** {@inheritDoc} */ public int compare(ClassDoc aObject1, ClassDoc aObject2) { final String checkName1 = getCheckName(aObject1); final String checkName2 = getCheckName(aObject2); return checkName1.compareTo(checkName2); } } /** * The first sentence of the check description. * * @param aClassDoc class doc of the check, e.g. EmptyStatement * @return The first sentence of the check description. */ private static String getDescription(final ClassDoc aClassDoc) { final Tag[] tags = aClassDoc.firstSentenceTags(); final StringBuffer buf = new StringBuffer(); if (tags.length > 0) { buf.append(tags[0].text()); } removeOpeningParagraphTag(buf); return buf.toString(); } /** * Removes an opening p tag from a StringBuffer. * @param aText the text to process */ private static void removeOpeningParagraphTag(final StringBuffer aText) { final String openTag = "

"; final int tagLen = openTag.length(); if ((aText.length() > tagLen) && aText.substring(0, tagLen).equals(openTag)) { aText.delete(0, tagLen); } } /** * Returns the official name of a check. * * @param aClassDoc the the check's documentation as extracted by javadoc * @return the check name, e.g. "IllegalImport" for * the "c.p.t.c.c.i.IllegalImportCheck" class. */ private static String getCheckName(final ClassDoc aClassDoc) { final String strippedClassName = aClassDoc.typeName(); final String checkName; if (strippedClassName.endsWith("Check")) { checkName = strippedClassName.substring( 0, strippedClassName.length() - "Check".length()); } else { checkName = strippedClassName; } return checkName; } /** * Writes the opening tags of an xdoc. * @param aPrintWriter you guessed it ... the target to print to :) * @param aTitle the title to use for the document. */ private static void writeXdocsHeader( final PrintWriter aPrintWriter, final String aTitle) { aPrintWriter.println(""); aPrintWriter.println(""); aPrintWriter.println(""); aPrintWriter.println("" + aTitle + ""); aPrintWriter.println("Checkstyle Development Team"); aPrintWriter.println(""); aPrintWriter.println(""); aPrintWriter.flush(); } /** * Writes the closing tags of an xdoc document. * @param aPrintWriter you guessed it ... the target to print to :) */ private static void writeXdocsFooter(final PrintWriter aPrintWriter) { aPrintWriter.println(""); aPrintWriter.println(""); aPrintWriter.flush(); } /** * Doclet entry point. * @param aRoot parsed javadoc of all java files passed to the javadoc task * @return true (TODO: semantics of the return value is not clear to me) * @throws IOException if there are problems writing output */ public static boolean start(RootDoc aRoot) throws IOException { final ClassDoc[] classDocs = aRoot.classes(); final File destDir = new File(getDestDir(aRoot.options())); final File checksIndexFile = new File(destDir, "availablechecks.xml"); final PrintWriter fileWriter = new PrintWriter( new FileWriter(checksIndexFile)); writeXdocsHeader(fileWriter, "Available Checks"); fileWriter.println("

Checkstyle provides many checks that you can" + " apply to your sourcecode. Below is an alphabetical" + " reference, the site navigation menu provides a reference" + " organized by functionality.

"); fileWriter.println(""); Arrays.sort(classDocs, new ClassDocByCheckNameComparator()); for (final ClassDoc classDoc : classDocs) { // TODO: introduce a "CheckstyleModule" interface // so we can do better in the next line... if (classDoc.typeName().endsWith("Check") && !classDoc.isAbstract()) { String pageName = getPageName(classDoc); // allow checks to override pageName when // java package hierarchy is not reflected in doc structure final Tag[] docPageTags = classDoc.tags("checkstyle-docpage"); if ((docPageTags != null) && (docPageTags.length > 0)) { pageName = docPageTags[0].text(); } final String descr = getDescription(classDoc); final String checkName = getCheckName(classDoc); fileWriter.println("" + ""); } } fileWriter.println("
" + checkName + "" + descr + "
"); writeXdocsFooter(fileWriter); fileWriter.close(); return true; } /** * Calculates the human readable page name for a doc page. * * @param aClassDoc the doc page. * @return the human readable page name for the doc page. */ private static String getPageName(ClassDoc aClassDoc) { final String packageName = aClassDoc.containingPackage().name(); final String pageName = packageName.substring(packageName.lastIndexOf('.') + 1); if ("checks".equals(pageName)) { return "misc"; } return pageName; } /** * Return the destination directory for this Javadoc run. * @param aOptions Javadoc commandline options * @return the dest dir specified on the command line (or ant task) */ public static String getDestDir(String[][] aOptions) { for (final String[] opt : aOptions) { if (DEST_DIR_OPT.equalsIgnoreCase(opt[0])) { return opt[1]; } } return null; // TODO: throw exception here ??? } /** * Returns option length (how many parts are in option). * @param aOption option name to process * @return option length (how many parts are in option). */ public static int optionLength(String aOption) { if (DEST_DIR_OPT.equals(aOption)) { return 2; } return 0; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/doclets/package-info.java100644 0 0 2323 12026051003 26671 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the doclets used during the build of Checktyle. REally *

* You should not be referring to this package. */ package com.puppycrawl.tools.checkstyle.doclets; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/doclets/TokenTypesDoclet.java100644 0 0 12374 12026051003 27634 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.doclets; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import com.sun.javadoc.ClassDoc; import com.sun.javadoc.DocErrorReporter; import com.sun.javadoc.FieldDoc; import com.sun.javadoc.RootDoc; /** * Doclet which is used to write property file with short descriptions * (first sentences) of TokenTypes' constants. * * @author o_sukhodolsky */ public final class TokenTypesDoclet { /** Command line option to specify file to write output of the doclet. */ private static final String DEST_FILE_OPT = "-destfile"; /** Stop instances being created. */ private TokenTypesDoclet() { } /** * The doclet's starter method. * @param aRoot RootDoc given to the doclet * @exception FileNotFoundException will be thrown if the doclet * will be unable to write to the specified file. * @return true if the given RootDoc is processed. */ public static boolean start(RootDoc aRoot) throws FileNotFoundException { final String fileName = getDestFileName(aRoot.options()); final FileOutputStream fos = new FileOutputStream(fileName); PrintStream ps = null; try { ps = new PrintStream(fos); final ClassDoc[] classes = aRoot.classes(); if ((classes.length != 1) || !"TokenTypes".equals(classes[0].name())) { final String message = "The doclet should be used for TokenTypes only"; throw new IllegalArgumentException(message); } final FieldDoc[] fields = classes[0].fields(); for (final FieldDoc field : fields) { if (field.isStatic() && field.isPublic() && field.isFinal() && "int".equals((field.type().qualifiedTypeName()))) { if (field.firstSentenceTags().length != 1) { final String message = "Should be only one tag."; throw new IllegalArgumentException(message); } ps.println(field.name() + "=" + field.firstSentenceTags()[0].text()); } } } finally { if (ps != null) { ps.close(); } } return true; } /** * Returns option length (how many parts are in option). * @param aOption option name to process * @return option length (how many parts are in option). */ public static int optionLength(String aOption) { if (DEST_FILE_OPT.equals(aOption)) { return 2; } return 0; } /** * Checks that only valid options was specified. * @param aOptions all parsed options * @param aReporter the reporter to report errors. * @return true if only valid options was specified */ public static boolean validOptions(String aOptions[][], DocErrorReporter aReporter) { boolean foundDestFileOption = false; for (final String[] opt : aOptions) { if (DEST_FILE_OPT.equals(opt[0])) { if (foundDestFileOption) { aReporter.printError("Only one -destfile option allowed."); return false; } foundDestFileOption = true; } } if (!foundDestFileOption) { final String message = "Usage: javadoc -destfile file -doclet TokenTypesDoclet ..."; aReporter.printError(message); } return foundDestFileOption; } /** * Reads destination file name. * @param aOptions all specified options. * @return destination file name */ private static String getDestFileName(String[][] aOptions) { String fileName = null; for (final String[] opt : aOptions) { if (DEST_FILE_OPT.equals(opt[0])) { fileName = opt[1]; } } return fileName; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/CSVFilter.java100644 0 0 7724 12026051003 26173 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import com.google.common.collect.Sets; import java.util.Set; import java.util.StringTokenizer; /** *

* This filter accepts an integer that matches a CSV value, where * each value is an integer or a range of integers. *

* @author Rick Giles * @author o_sukhodolsky */ class CSVFilter implements IntFilter { /** filter set */ private final Set mFilters = Sets.newHashSet(); /** * Adds a IntFilter to the set. * @param aFilter the IntFilter to add. */ public void addFilter(IntFilter aFilter) { mFilters.add(aFilter); } /** * Returns the IntFilters of the filter set. * @return the IntFilters of the filter set. */ protected Set getFilters() { return mFilters; } /** * Constructs a CSVFilter from a CSV, Comma-Separated Values, * string. Each value is an integer, or a range of integers. A range of * integers is of the form integer-integer, such as 1-10. * Note: integers must be non-negative. * @param aPattern the CSV string. * @throws NumberFormatException if a component substring does not * contain a parsable integer. */ public CSVFilter(String aPattern) throws NumberFormatException { final StringTokenizer tokenizer = new StringTokenizer(aPattern, ","); while (tokenizer.hasMoreTokens()) { final String token = tokenizer.nextToken().trim(); final int index = token.indexOf("-"); if (index == -1) { final int matchValue = Integer.parseInt(token); addFilter(new IntMatchFilter(matchValue)); } else { final int lowerBound = Integer.parseInt(token.substring(0, index)); final int upperBound = Integer.parseInt(token.substring(index + 1)); addFilter(new IntRangeFilter(lowerBound, upperBound)); } } } /** * Determines whether an Integer matches a CSV integer value. * @param aInt the Integer to check. * @return true if aInt is an Integer that matches a CSV value. */ public boolean accept(int aInt) { for (IntFilter filter : getFilters()) { if (filter.accept(aInt)) { return true; } } return false; } @Override public String toString() { return mFilters.toString(); } @Override public int hashCode() { return mFilters.hashCode(); } @Override public boolean equals(Object aObject) { if (aObject instanceof CSVFilter) { final CSVFilter other = (CSVFilter) aObject; return this.mFilters.equals(other.mFilters); } return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/IntFilter.java100644 0 0 2560 12026051003 26263 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; /** * An interface for filtering Integer. * @author o_sukhodolsky */ interface IntFilter { /** * Determines whether or not a filtered Integer is accepted. * @param aInt the Integer to filter. * @return true if the aInt is accepted. */ boolean accept(int aInt); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/IntMatchFilter.java100644 0 0 4102 12026051002 27231 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; /** * This filter accepts a matching Integer. * @author Rick Giles */ class IntMatchFilter implements IntFilter { /** the matching Integer */ private final int mMatchValue; /** * Constructs a MatchFilter for an int. * @param aMatchValue the matching int. */ public IntMatchFilter(int aMatchValue) { mMatchValue = aMatchValue; } /** {@inheritDoc} */ public boolean accept(int aInt) { return mMatchValue == aInt; } @Override public String toString() { return "IntMatchFilter[" + mMatchValue + "]"; } @Override public int hashCode() { return Integer.valueOf(mMatchValue).hashCode(); } @Override public boolean equals(Object aObject) { if (aObject instanceof IntMatchFilter) { final IntMatchFilter other = (IntMatchFilter) aObject; return this.mMatchValue == other.mMatchValue; } return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/IntRangeFilter.java100644 0 0 5142 12026051002 27236 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; /** * This filter accepts an Integer in a range. * @author Rick Giles */ class IntRangeFilter implements IntFilter { /** hash function multiplicand */ private static final int HASH_MULT = 29; /** lower bound of the range */ private final Integer mLowerBound; /** upper bound of the range */ private final Integer mUpperBound; /** * Constructs a IntRangeFilter with a * lower bound and an upper bound for the range. * @param aLowerBound the lower bound of the range. * @param aUpperBound the upper bound of the range. */ public IntRangeFilter(int aLowerBound, int aUpperBound) { mLowerBound = aLowerBound; mUpperBound = aUpperBound; } /** {@inheritDoc} */ public boolean accept(int aInt) { return ((mLowerBound.compareTo(aInt) <= 0) && (mUpperBound.compareTo(aInt) >= 0)); } @Override public int hashCode() { return HASH_MULT * mLowerBound.intValue() + mUpperBound.intValue(); } @Override public boolean equals(Object aObject) { if (aObject instanceof IntRangeFilter) { final IntRangeFilter other = (IntRangeFilter) aObject; return (this.mLowerBound.equals(other.mLowerBound) && this.mUpperBound.equals(other.mUpperBound)); } return false; } @Override public String toString() { return "IntRangeFilter[" + mLowerBound + "," + mUpperBound + "]"; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/package-info.java100644 0 0 2213 12026051001 26700 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the filters that are bundled with the main distribution. */ package com.puppycrawl.tools.checkstyle.filters; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilter.java100644 0 0 5302 12026051002 30314 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.Filter; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; /** * This is a very simple filter based on severity matching. * The filter admits option severity and accepts an AuditEvent * if its severity equals the filter's severity. * @author Rick Giles */ public class SeverityMatchFilter extends AutomaticBean implements Filter { /** the severity level to accept */ private SeverityLevel mSeverityLevel = SeverityLevel.ERROR; /** whether to accept or reject on severity matches */ private boolean mAcceptOnMatch = true; /** * Sets the severity level. The string should be one of the names * defined in the SeverityLevel class. * * @param aSeverity The new severity level * @see SeverityLevel */ public final void setSeverity(String aSeverity) { mSeverityLevel = SeverityLevel.getInstance(aSeverity); } /** * Sets whether to accept or reject on matching severity level. * @param aAcceptOnMatch if true, accept on matches; if * false, reject on matches. */ public final void setAcceptOnMatch(boolean aAcceptOnMatch) { mAcceptOnMatch = aAcceptOnMatch; } /** {@inheritDoc} */ public boolean accept(AuditEvent aEvent) { final boolean result = mSeverityLevel.equals(aEvent.getSeverityLevel()); if (mAcceptOnMatch) { return result; } return !result; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/SuppressElement.java100644 0 0 20041 12026051002 27532 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.Filter; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * This filter processes {@link com.puppycrawl.tools.checkstyle.api.AuditEvent} * objects based on the criteria of file, check, module id, line, and * column. It rejects an AuditEvent if the following match: *
    *
  • the event's file name; and *
  • the check name or the module identifier; and *
  • (optionally) the event's line is in the filter's line CSV; and *
  • (optionally) the check's columns is in the filter's column CSV. *
* * @author Rick Giles */ public class SuppressElement implements Filter { /** hash function multiplicand */ private static final int HASH_MULT = 29; /** the regexp to match file names against */ private final Pattern mFileRegexp; /** the pattern for file names*/ private final String mFilePattern; /** the regexp to match check names against */ private Pattern mCheckRegexp; /** the pattern for check class names*/ private String mCheckPattern; /** module id filter. */ private String mModuleId; /** line number filter */ private CSVFilter mLineFilter; /** CSV for line number filter */ private String mLinesCSV; /** column number filter */ private CSVFilter mColumnFilter; /** CSV for column number filter */ private String mColumnsCSV; /** * Constructs a SuppressElement for a * file name pattern. Must either call {@link #setColumns(String)} or * {@link #setModuleId(String)} before using this object. * @param aFiles regular expression for names of filtered files. * @throws PatternSyntaxException if there is an error. */ public SuppressElement(String aFiles) throws PatternSyntaxException { mFilePattern = aFiles; mFileRegexp = Utils.getPattern(aFiles); } /** * Set the check class pattern. * @param aChecks regular expression for filtered check classes. */ public void setChecks(final String aChecks) { mCheckPattern = aChecks; mCheckRegexp = Utils.getPattern(aChecks); } /** * Set the module id for filtering. Cannot be null. * @param aModuleId the id */ public void setModuleId(final String aModuleId) { mModuleId = aModuleId; } /** * Sets the CSV values and ranges for line number filtering. * E.g. "1,7-15,18". * @param aLines CSV values and ranges for line number filtering. */ public void setLines(String aLines) { mLinesCSV = aLines; if (aLines != null) { mLineFilter = new CSVFilter(aLines); } else { mLineFilter = null; } } /** * Sets the CSV values and ranges for column number filtering. * E.g. "1,7-15,18". * @param aColumns CSV values and ranges for column number filtering. */ public void setColumns(String aColumns) { mColumnsCSV = aColumns; if (aColumns != null) { mColumnFilter = new CSVFilter(aColumns); } else { mColumnFilter = null; } } /** {@inheritDoc} */ public boolean accept(AuditEvent aEvent) { // file and check match? if ((aEvent.getFileName() == null) || !mFileRegexp.matcher(aEvent.getFileName()).find() || (aEvent.getLocalizedMessage() == null) || ((mModuleId != null) && !mModuleId.equals(aEvent .getModuleId())) || ((mCheckRegexp != null) && !mCheckRegexp.matcher( aEvent.getSourceName()).find())) { return true; } // reject if no line/column matching if ((mLineFilter == null) && (mColumnFilter == null)) { return false; } // reject if line matches a line CSV value. if (mLineFilter != null) { if (mLineFilter.accept(aEvent.getLine())) { return false; } } // reject if column matches a column CSV value. if (mColumnFilter != null) { if (mColumnFilter.accept(aEvent.getColumn())) { return false; } } return true; } @Override public String toString() { return "SupressElement[files=" + mFilePattern + ",checks=" + mCheckPattern + ",lines=" + mLinesCSV + ",columns=" + mColumnsCSV + "]"; } @Override public int hashCode() { int result = HASH_MULT * mFilePattern.hashCode(); if (mCheckPattern != null) { result = HASH_MULT * result + mCheckPattern.hashCode(); } if (mModuleId != null) { result = HASH_MULT * result + mModuleId.hashCode(); } if (mLinesCSV != null) { result = HASH_MULT * result + mLinesCSV.hashCode(); } if (mColumnsCSV != null) { result = HASH_MULT * result + mColumnsCSV.hashCode(); } return result; } @Override public boolean equals(Object aObject) { if (aObject instanceof SuppressElement) { final SuppressElement other = (SuppressElement) aObject; // same file pattern? if (!this.mFilePattern.equals(other.mFilePattern)) { return false; } // same check pattern? if (mCheckPattern != null) { if (!mCheckPattern.equals(other.mCheckPattern)) { return false; } } else if (other.mCheckPattern != null) { return false; } // same module id? if (mModuleId != null) { if (!mModuleId.equals(other.mModuleId)) { return false; } } else if (other.mModuleId != null) { return false; } // same line number filter? if (mLineFilter != null) { if (!mLineFilter.equals(other.mLineFilter)) { return false; } } else if (other.mLineFilter != null) { return false; } // same column number filter? if (mColumnFilter != null) { if (!mColumnFilter.equals(other.mColumnFilter)) { return false; } } else if (other.mColumnFilter != null) { return false; } // everything is the same return true; } return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java100644 0 0 44031 12026051001 31423 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.Filter; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.FileContentsHolder; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; /** *

* A filter that uses comments to suppress audit events. *

*

* Rationale: * Sometimes there are legitimate reasons for violating a check. When * this is a matter of the code in question and not personal * preference, the best place to override the policy is in the code * itself. Semi-structured comments can be associated with the check. * This is sometimes superior to a separate suppressions file, which * must be kept up-to-date as the source file is edited. *

*

* Usage: * This check only works in conjunction with the FileContentsHolder module * since that module makes the suppression comments in the .java * files available sub rosa. *

* @see FileContentsHolder * @author Mike McMahon * @author Rick Giles */ public class SuppressionCommentFilter extends AutomaticBean implements Filter { /** * A Tag holds a suppression comment and its location, and determines * whether the supression turns checkstyle reporting on or off. * @author Rick Giles */ public class Tag implements Comparable { /** The text of the tag. */ private final String mText; /** The line number of the tag. */ private final int mLine; /** The column number of the tag. */ private final int mColumn; /** Determines whether the suppression turns checkstyle reporting on. */ private final boolean mOn; /** The parsed check regexp, expanded for the text of this tag. */ private Pattern mTagCheckRegexp; /** The parsed message regexp, expanded for the text of this tag. */ private Pattern mTagMessageRegexp; /** * Constructs a tag. * @param aLine the line number. * @param aColumn the column number. * @param aText the text of the suppression. * @param aOn true if the tag turns checkstyle reporting. * @throws ConversionException if unable to parse expanded aText. * on. */ public Tag(int aLine, int aColumn, String aText, boolean aOn) throws ConversionException { mLine = aLine; mColumn = aColumn; mText = aText; mOn = aOn; mTagCheckRegexp = mCheckRegexp; //Expand regexp for check and message //Does not intern Patterns with Utils.getPattern() String format = ""; try { if (aOn) { format = expandFromComment(aText, mCheckFormat, mOnRegexp); mTagCheckRegexp = Pattern.compile(format); if (mMessageFormat != null) { format = expandFromComment(aText, mMessageFormat, mOnRegexp); mTagMessageRegexp = Pattern.compile(format); } } else { format = expandFromComment(aText, mCheckFormat, mOffRegexp); mTagCheckRegexp = Pattern.compile(format); if (mMessageFormat != null) { format = expandFromComment( aText, mMessageFormat, mOffRegexp); mTagMessageRegexp = Pattern.compile(format); } } } catch (final PatternSyntaxException e) { throw new ConversionException( "unable to parse expanded comment " + format, e); } } /** @return the text of the tag. */ public String getText() { return mText; } /** @return the line number of the tag in the source file. */ public int getLine() { return mLine; } /** * Determines the column number of the tag in the source file. * Will be 0 for all lines of multiline comment, except the * first line. * @return the column number of the tag in the source file. */ public int getColumn() { return mColumn; } /** * Determines whether the suppression turns checkstyle reporting on or * off. * @return trueif the suppression turns reporting on. */ public boolean isOn() { return mOn; } /** * Compares the position of this tag in the file * with the position of another tag. * @param aObject the tag to compare with this one. * @return a negative number if this tag is before the other tag, * 0 if they are at the same position, and a positive number if this * tag is after the other tag. * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Tag aObject) { if (mLine == aObject.mLine) { return mColumn - aObject.mColumn; } return (mLine - aObject.mLine); } /** * Determines whether the source of an audit event * matches the text of this tag. * @param aEvent the AuditEvent to check. * @return true if the source of aEvent matches the text of this tag. */ public boolean isMatch(AuditEvent aEvent) { final Matcher tagMatcher = mTagCheckRegexp.matcher(aEvent.getSourceName()); if (tagMatcher.find()) { return true; } if (mTagMessageRegexp != null) { final Matcher messageMatcher = mTagMessageRegexp.matcher(aEvent.getMessage()); return messageMatcher.find(); } return false; } /** * Expand based on a matching comment. * @param aComment the comment. * @param aString the string to expand. * @param aRegexp the parsed expander. * @return the expanded string */ private String expandFromComment( String aComment, String aString, Pattern aRegexp) { final Matcher matcher = aRegexp.matcher(aComment); // Match primarily for effect. if (!matcher.find()) { ///CLOVER:OFF return aString; ///CLOVER:ON } String result = aString; for (int i = 0; i <= matcher.groupCount(); i++) { // $n expands comment match like in Pattern.subst(). result = result.replaceAll("\\$" + i, matcher.group(i)); } return result; } @Override public final String toString() { return "Tag[line=" + getLine() + "; col=" + getColumn() + "; on=" + isOn() + "; text='" + getText() + "']"; } } /** Turns checkstyle reporting off. */ private static final String DEFAULT_OFF_FORMAT = "CHECKSTYLE\\:OFF"; /** Turns checkstyle reporting on. */ private static final String DEFAULT_ON_FORMAT = "CHECKSTYLE\\:ON"; /** Control all checks */ private static final String DEFAULT_CHECK_FORMAT = ".*"; /** Whether to look in comments of the C type. */ private boolean mCheckC = true; /** Whether to look in comments of the C++ type. */ private boolean mCheckCPP = true; /** Parsed comment regexp that turns checkstyle reporting off. */ private Pattern mOffRegexp; /** Parsed comment regexp that turns checkstyle reporting on. */ private Pattern mOnRegexp; /** The check format to suppress. */ private String mCheckFormat; /** The parsed check regexp. */ private Pattern mCheckRegexp; /** The message format to suppress. */ private String mMessageFormat; //TODO: Investigate performance improvement with array /** Tagged comments */ private final List mTags = Lists.newArrayList(); /** * References the current FileContents for this filter. * Since this is a weak reference to the FileContents, the FileContents * can be reclaimed as soon as the strong references in TreeWalker * and FileContentsHolder are reassigned to the next FileContents, * at which time filtering for the current FileContents is finished. */ private WeakReference mFileContentsReference = new WeakReference(null); /** * Constructs a SuppressionCommentFilter. * Initializes comment on, comment off, and check formats * to defaults. */ public SuppressionCommentFilter() { setOnCommentFormat(DEFAULT_ON_FORMAT); setOffCommentFormat(DEFAULT_OFF_FORMAT); setCheckFormat(DEFAULT_CHECK_FORMAT); } /** * Set the format for a comment that turns off reporting. * @param aFormat a String value. * @throws ConversionException unable to parse aFormat. */ public void setOffCommentFormat(String aFormat) throws ConversionException { try { mOffRegexp = Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } /** * Set the format for a comment that turns on reporting. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setOnCommentFormat(String aFormat) throws ConversionException { try { mOnRegexp = Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } /** @return the FileContents for this filter. */ public FileContents getFileContents() { return mFileContentsReference.get(); } /** * Set the FileContents for this filter. * @param aFileContents the FileContents for this filter. */ public void setFileContents(FileContents aFileContents) { mFileContentsReference = new WeakReference(aFileContents); } /** * Set the format for a check. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setCheckFormat(String aFormat) throws ConversionException { try { mCheckRegexp = Utils.getPattern(aFormat); mCheckFormat = aFormat; } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } /** * Set the format for a message. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setMessageFormat(String aFormat) throws ConversionException { // check that aFormat parses try { Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } mMessageFormat = aFormat; } /** * Set whether to look in C++ comments. * @param aCheckCPP true if C++ comments are checked. */ public void setCheckCPP(boolean aCheckCPP) { mCheckCPP = aCheckCPP; } /** * Set whether to look in C comments. * @param aCheckC true if C comments are checked. */ public void setCheckC(boolean aCheckC) { mCheckC = aCheckC; } /** {@inheritDoc} */ public boolean accept(AuditEvent aEvent) { if (aEvent.getLocalizedMessage() == null) { return true; // A special event. } // Lazy update. If the first event for the current file, update file // contents and tag suppressions final FileContents currentContents = FileContentsHolder.getContents(); if (currentContents == null) { // we have no contents, so we can not filter. // TODO: perhaps we should notify user somehow? return true; } if (getFileContents() != currentContents) { setFileContents(currentContents); tagSuppressions(); } final Tag matchTag = findNearestMatch(aEvent); if ((matchTag != null) && !matchTag.isOn()) { return false; } return true; } /** * Finds the nearest comment text tag that matches an audit event. * The nearest tag is before the line and column of the event. * @param aEvent the AuditEvent to match. * @return The Tag nearest aEvent. */ private Tag findNearestMatch(AuditEvent aEvent) { Tag result = null; // TODO: try binary search if sequential search becomes a performance // problem. for (Tag tag : mTags) { if ((tag.getLine() > aEvent.getLine()) || ((tag.getLine() == aEvent.getLine()) && (tag.getColumn() > aEvent.getColumn()))) { break; } if (tag.isMatch(aEvent)) { result = tag; } }; return result; } /** * Collects all the suppression tags for all comments into a list and * sorts the list. */ private void tagSuppressions() { mTags.clear(); final FileContents contents = getFileContents(); if (mCheckCPP) { tagSuppressions(contents.getCppComments().values()); } if (mCheckC) { final Collection> cComments = contents .getCComments().values(); for (List element : cComments) { tagSuppressions(element); } } Collections.sort(mTags); } /** * Appends the suppressions in a collection of comments to the full * set of suppression tags. * @param aComments the set of comments. */ private void tagSuppressions(Collection aComments) { for (TextBlock comment : aComments) { final int startLineNo = comment.getStartLineNo(); final String[] text = comment.getText(); tagCommentLine(text[0], startLineNo, comment.getStartColNo()); for (int i = 1; i < text.length; i++) { tagCommentLine(text[i], startLineNo + i, 0); } } } /** * Tags a string if it matches the format for turning * checkstyle reporting on or the format for turning reporting off. * @param aText the string to tag. * @param aLine the line number of aText. * @param aColumn the column number of aText. */ private void tagCommentLine(String aText, int aLine, int aColumn) { final Matcher offMatcher = mOffRegexp.matcher(aText); if (offMatcher.find()) { addTag(offMatcher.group(0), aLine, aColumn, false); } else { final Matcher onMatcher = mOnRegexp.matcher(aText); if (onMatcher.find()) { addTag(onMatcher.group(0), aLine, aColumn, true); } } } /** * Adds a Tag to the list of all tags. * @param aText the text of the tag. * @param aLine the line number of the tag. * @param aColumn the column number of the tag. * @param aOn true if the tag turns checkstyle reporting on. */ private void addTag(String aText, int aLine, int aColumn, boolean aOn) { final Tag tag = new Tag(aLine, aColumn, aText, aOn); mTags.add(tag); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/SuppressionFilter.java100644 0 0 5163 12026051001 30063 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Filter; import com.puppycrawl.tools.checkstyle.api.FilterSet; /** *

* This filter accepts AuditEvents according to file, check, line, and * column, as specified in a suppression file. *

* @author Rick Giles */ public class SuppressionFilter extends AutomaticBean implements Filter { /** set of individual suppresses */ private FilterSet mFilters = new FilterSet(); /** * Loads the suppressions for a file. * @param aFileName name of the suppressions file. * @throws CheckstyleException if there is an error. */ public void setFile(String aFileName) throws CheckstyleException { mFilters = SuppressionsLoader.loadSuppressions(aFileName); } /** {@inheritDoc} */ public boolean accept(AuditEvent aEvent) { return mFilters.accept(aEvent); } @Override public String toString() { return mFilters.toString(); } @Override public int hashCode() { return mFilters.hashCode(); } @Override public boolean equals(Object aObject) { if (aObject instanceof SuppressionFilter) { final SuppressionFilter other = (SuppressionFilter) aObject; return this.mFilters.equals(other.mFilters); } return false; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoader.java100644 0 0 20250 12026051001 30241 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import com.google.common.collect.Maps; import com.puppycrawl.tools.checkstyle.api.AbstractLoader; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.FilterSet; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import java.util.regex.PatternSyntaxException; /** * Loads a filter chain of suppressions. * @author Rick Giles */ public final class SuppressionsLoader extends AbstractLoader { /** the public ID for the configuration dtd */ private static final String DTD_PUBLIC_ID_1_0 = "-//Puppy Crawl//DTD Suppressions 1.0//EN"; /** the resource for the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_0 = "com/puppycrawl/tools/checkstyle/suppressions_1_0.dtd"; /** the public ID for the configuration dtd */ private static final String DTD_PUBLIC_ID_1_1 = "-//Puppy Crawl//DTD Suppressions 1.1//EN"; /** the resource for the configuration dtd */ private static final String DTD_RESOURCE_NAME_1_1 = "com/puppycrawl/tools/checkstyle/suppressions_1_1.dtd"; /** * the filter chain to return in getAFilterChain(), * configured during parsing */ private final FilterSet mFilterChain = new FilterSet(); /** * Creates a new SuppressionsLoader instance. * @throws ParserConfigurationException if an error occurs * @throws SAXException if an error occurs */ private SuppressionsLoader() throws ParserConfigurationException, SAXException { super(createIdToResourceNameMap()); } /** * Returns the loaded filter chain. * @return the loaded filter chain. */ public FilterSet getFilterChain() { return mFilterChain; } @Override public void startElement(String aNamespaceURI, String aLocalName, String aQName, Attributes aAtts) throws SAXException { if ("suppress".equals(aQName)) { //add SuppressElement filter to the filter chain final String files = aAtts.getValue("files"); if (files == null) { throw new SAXException("missing files attribute"); } final String checks = aAtts.getValue("checks"); final String modId = aAtts.getValue("id"); if ((checks == null) && (modId == null)) { throw new SAXException("missing checks and id attribute"); } final SuppressElement suppress; try { suppress = new SuppressElement(files); if (modId != null) { suppress.setModuleId(modId); } if (checks != null) { suppress.setChecks(checks); } } catch (final PatternSyntaxException e) { throw new SAXException("invalid files or checks format"); } final String lines = aAtts.getValue("lines"); if (lines != null) { suppress.setLines(lines); } final String columns = aAtts.getValue("columns"); if (columns != null) { suppress.setColumns(columns); } mFilterChain.addFilter(suppress); } } /** * Returns the suppression filters in a specified file. * @param aFilename name of the suppresssions file. * @return the filter chain of suppression elements specified in the file. * @throws CheckstyleException if an error occurs. */ public static FilterSet loadSuppressions(String aFilename) throws CheckstyleException { InputStream fis; try { fis = new FileInputStream(aFilename); } catch (final FileNotFoundException e) { if (aFilename.matches("^https?://.+")) { // this is a URL, load it as such try { fis = new URL(aFilename).openStream(); } catch (MalformedURLException e1) { throw new CheckstyleException( "Invalid URL: " + aFilename, e1); } catch (IOException e1) { throw new CheckstyleException( "unable to read " + aFilename, e1); } } else { // check for the file in the classpath fis = SuppressionsLoader.class.getResourceAsStream(aFilename); } if (fis == null) { throw new CheckstyleException("unable to find " + aFilename, e); } } final InputSource source = new InputSource(fis); return loadSuppressions(source, aFilename); } /** * Returns the suppression filters in a specified source. * @param aSource the source for the suppressions. * @param aSourceName the name of the source. * @return the filter chain of suppression elements in aSource. * @throws CheckstyleException if an error occurs. */ private static FilterSet loadSuppressions( InputSource aSource, String aSourceName) throws CheckstyleException { try { final SuppressionsLoader suppressionsLoader = new SuppressionsLoader(); suppressionsLoader.parseInputSource(aSource); return suppressionsLoader.getFilterChain(); } catch (final FileNotFoundException e) { throw new CheckstyleException("unable to find " + aSourceName, e); } catch (final ParserConfigurationException e) { throw new CheckstyleException("unable to parse " + aSourceName, e); } catch (final SAXException e) { throw new CheckstyleException("unable to parse " + aSourceName + " - " + e.getMessage(), e); } catch (final IOException e) { throw new CheckstyleException("unable to read " + aSourceName, e); } catch (final NumberFormatException e) { throw new CheckstyleException("number format exception " + aSourceName + " - " + e.getMessage(), e); } } /** * Creates mapping between local resources and dtd ids. * @return map between local resources and dtd ids. */ private static Map createIdToResourceNameMap() { final Map map = Maps.newHashMap(); map.put(DTD_PUBLIC_ID_1_0, DTD_RESOURCE_NAME_1_0); map.put(DTD_PUBLIC_ID_1_1, DTD_RESOURCE_NAME_1_1); return map; } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.javacheckstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilte100644 0 0 43053 12026051002 31614 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.Filter; import com.puppycrawl.tools.checkstyle.api.TextBlock; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.checks.FileContentsHolder; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.apache.commons.beanutils.ConversionException; /** *

* A filter that uses nearby comments to suppress audit events. *

*

* This check is philosophically similar to {@link SuppressionCommentFilter}. * Unlike {@link SuppressionCommentFilter}, this filter does not require * pairs of comments. This check may be used to suppress warnings in the * current line: *

 *    offendingLine(for, whatever, reason); // SUPPRESS ParameterNumberCheck
 * 
* or it may be configured to span multiple lines, either forward: *
 *    // PERMIT MultipleVariableDeclarations NEXT 3 LINES
 *    double x1 = 1.0, y1 = 0.0, z1 = 0.0;
 *    double x2 = 0.0, y2 = 1.0, z2 = 0.0;
 *    double x3 = 0.0, y3 = 0.0, z3 = 1.0;
 * 
* or reverse: *
 *   try {
 *     thirdPartyLibrary.method();
 *   } catch (RuntimeException e) {
 *     // ALLOW ILLEGAL CATCH BECAUSE third party API wraps everything
 *     // in RuntimeExceptions.
 *     ...
 *   }
 * 
*

*

* See {@link SuppressionCommentFilter} for usage notes. *

* * @author Mick Killianey */ public class SuppressWithNearbyCommentFilter extends AutomaticBean implements Filter { /** * A Tag holds a suppression comment and its location. */ public class Tag implements Comparable { /** The text of the tag. */ private final String mText; /** The first line where warnings may be suppressed. */ private int mFirstLine; /** The last line where warnings may be suppressed. */ private int mLastLine; /** The parsed check regexp, expanded for the text of this tag. */ private Pattern mTagCheckRegexp; /** The parsed message regexp, expanded for the text of this tag. */ private Pattern mTagMessageRegexp; /** * Constructs a tag. * @param aText the text of the suppression. * @param aLine the line number. * @throws ConversionException if unable to parse expanded aText. * on. */ public Tag(String aText, int aLine) throws ConversionException { mText = aText; mTagCheckRegexp = mCheckRegexp; //Expand regexp for check and message //Does not intern Patterns with Utils.getPattern() String format = ""; try { format = expandFromComment(aText, mCheckFormat, mCommentRegexp); mTagCheckRegexp = Pattern.compile(format); if (mMessageFormat != null) { format = expandFromComment( aText, mMessageFormat, mCommentRegexp); mTagMessageRegexp = Pattern.compile(format); } int influence = 0; if (mInfluenceFormat != null) { format = expandFromComment( aText, mInfluenceFormat, mCommentRegexp); try { if (format.startsWith("+")) { format = format.substring(1); } influence = Integer.parseInt(format); } catch (final NumberFormatException e) { throw new ConversionException( "unable to parse influence from '" + aText + "' using " + mInfluenceFormat, e); } } if (influence >= 0) { mFirstLine = aLine; mLastLine = aLine + influence; } else { mFirstLine = aLine + influence; mLastLine = aLine; } } catch (final PatternSyntaxException e) { throw new ConversionException( "unable to parse expanded comment " + format, e); } } /** @return the text of the tag. */ public String getText() { return mText; } /** @return the line number of the first suppressed line. */ public int getFirstLine() { return mFirstLine; } /** @return the line number of the last suppressed line. */ public int getLastLine() { return mLastLine; } /** * Compares the position of this tag in the file * with the position of another tag. * @param aOther the tag to compare with this one. * @return a negative number if this tag is before the other tag, * 0 if they are at the same position, and a positive number if this * tag is after the other tag. * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Tag aOther) { if (mFirstLine == aOther.mFirstLine) { return mLastLine - aOther.mLastLine; } return (mFirstLine - aOther.mFirstLine); } /** * Determines whether the source of an audit event * matches the text of this tag. * @param aEvent the AuditEvent to check. * @return true if the source of aEvent matches the text of this tag. */ public boolean isMatch(AuditEvent aEvent) { final int line = aEvent.getLine(); if (line < mFirstLine) { return false; } if (line > mLastLine) { return false; } final Matcher tagMatcher = mTagCheckRegexp.matcher(aEvent.getSourceName()); if (tagMatcher.find()) { return true; } if (mTagMessageRegexp != null) { final Matcher messageMatcher = mTagMessageRegexp.matcher(aEvent.getMessage()); return messageMatcher.find(); } return false; } /** * Expand based on a matching comment. * @param aComment the comment. * @param aString the string to expand. * @param aRegexp the parsed expander. * @return the expanded string */ private String expandFromComment( String aComment, String aString, Pattern aRegexp) { final Matcher matcher = aRegexp.matcher(aComment); // Match primarily for effect. if (!matcher.find()) { ///CLOVER:OFF return aString; ///CLOVER:ON } String result = aString; for (int i = 0; i <= matcher.groupCount(); i++) { // $n expands comment match like in Pattern.subst(). result = result.replaceAll("\\$" + i, matcher.group(i)); } return result; } /** {@inheritDoc} */ @Override public final String toString() { return "Tag[lines=[" + getFirstLine() + " to " + getLastLine() + "]; text='" + getText() + "']"; } } /** Format to turns checkstyle reporting off. */ private static final String DEFAULT_COMMENT_FORMAT = "SUPPRESS CHECKSTYLE (\\w+)"; /** Default regex for checks that should be suppressed. */ private static final String DEFAULT_CHECK_FORMAT = ".*"; /** Default regex for messages that should be suppressed. */ private static final String DEFAULT_MESSAGE_FORMAT = null; /** Default regex for lines that should be suppressed. */ private static final String DEFAULT_INFLUENCE_FORMAT = "0"; /** Whether to look for trigger in C-style comments. */ private boolean mCheckC = true; /** Whether to look for trigger in C++-style comments. */ private boolean mCheckCPP = true; /** Parsed comment regexp that marks checkstyle suppression region. */ private Pattern mCommentRegexp; /** The comment pattern that triggers suppression. */ private String mCheckFormat; /** The parsed check regexp. */ private Pattern mCheckRegexp; /** The message format to suppress. */ private String mMessageFormat; /** The influence of the suppression comment. */ private String mInfluenceFormat; //TODO: Investigate performance improvement with array /** Tagged comments */ private final List mTags = Lists.newArrayList(); /** * References the current FileContents for this filter. * Since this is a weak reference to the FileContents, the FileContents * can be reclaimed as soon as the strong references in TreeWalker * and FileContentsHolder are reassigned to the next FileContents, * at which time filtering for the current FileContents is finished. */ private WeakReference mFileContentsReference = new WeakReference(null); /** * Constructs a SuppressionCommentFilter. * Initializes comment on, comment off, and check formats * to defaults. */ public SuppressWithNearbyCommentFilter() { if (DEFAULT_COMMENT_FORMAT != null) { setCommentFormat(DEFAULT_COMMENT_FORMAT); } if (DEFAULT_CHECK_FORMAT != null) { setCheckFormat(DEFAULT_CHECK_FORMAT); } if (DEFAULT_MESSAGE_FORMAT != null) { setMessageFormat(DEFAULT_MESSAGE_FORMAT); } if (DEFAULT_INFLUENCE_FORMAT != null) { setInfluenceFormat(DEFAULT_INFLUENCE_FORMAT); } } /** * Set the format for a comment that turns off reporting. * @param aFormat a String value. * @throws ConversionException unable to parse aFormat. */ public void setCommentFormat(String aFormat) throws ConversionException { try { mCommentRegexp = Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } /** @return the FileContents for this filter. */ public FileContents getFileContents() { return mFileContentsReference.get(); } /** * Set the FileContents for this filter. * @param aFileContents the FileContents for this filter. */ public void setFileContents(FileContents aFileContents) { mFileContentsReference = new WeakReference(aFileContents); } /** * Set the format for a check. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setCheckFormat(String aFormat) throws ConversionException { try { mCheckRegexp = Utils.getPattern(aFormat); mCheckFormat = aFormat; } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } } /** * Set the format for a message. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setMessageFormat(String aFormat) throws ConversionException { // check that aFormat parses try { Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } mMessageFormat = aFormat; } /** * Set the format for the influence of this check. * @param aFormat a String value * @throws ConversionException unable to parse aFormat */ public void setInfluenceFormat(String aFormat) throws ConversionException { // check that aFormat parses try { Utils.getPattern(aFormat); } catch (final PatternSyntaxException e) { throw new ConversionException("unable to parse " + aFormat, e); } mInfluenceFormat = aFormat; } /** * Set whether to look in C++ comments. * @param aCheckCPP true if C++ comments are checked. */ public void setCheckCPP(boolean aCheckCPP) { mCheckCPP = aCheckCPP; } /** * Set whether to look in C comments. * @param aCheckC true if C comments are checked. */ public void setCheckC(boolean aCheckC) { mCheckC = aCheckC; } /** {@inheritDoc} */ public boolean accept(AuditEvent aEvent) { if (aEvent.getLocalizedMessage() == null) { return true; // A special event. } // Lazy update. If the first event for the current file, update file // contents and tag suppressions final FileContents currentContents = FileContentsHolder.getContents(); if (currentContents == null) { // we have no contents, so we can not filter. // TODO: perhaps we should notify user somehow? return true; } if (getFileContents() != currentContents) { setFileContents(currentContents); tagSuppressions(); } for (final Iterator iter = mTags.iterator(); iter.hasNext();) { final Tag tag = iter.next(); if (tag.isMatch(aEvent)) { return false; } } return true; } /** * Collects all the suppression tags for all comments into a list and * sorts the list. */ private void tagSuppressions() { mTags.clear(); final FileContents contents = getFileContents(); if (mCheckCPP) { tagSuppressions(contents.getCppComments().values()); } if (mCheckC) { final Collection> cComments = contents.getCComments().values(); for (final List element : cComments) { tagSuppressions(element); } } Collections.sort(mTags); } /** * Appends the suppressions in a collection of comments to the full * set of suppression tags. * @param aComments the set of comments. */ private void tagSuppressions(Collection aComments) { for (final TextBlock comment : aComments) { final int startLineNo = comment.getStartLineNo(); final String[] text = comment.getText(); tagCommentLine(text[0], startLineNo, comment.getStartColNo()); for (int i = 1; i < text.length; i++) { tagCommentLine(text[i], startLineNo + i, 0); } } } /** * Tags a string if it matches the format for turning * checkstyle reporting on or the format for turning reporting off. * @param aText the string to tag. * @param aLine the line number of aText. * @param aColumn the column number of aText. */ private void tagCommentLine(String aText, int aLine, int aColumn) { final Matcher matcher = mCommentRegexp.matcher(aText); if (matcher.find()) { addTag(matcher.group(0), aLine); } } /** * Adds a comment suppression Tag to the list of all tags. * @param aText the text of the tag. * @param aLine the line number of the tag. */ private void addTag(String aText, int aLine) { final Tag tag = new Tag(aText, aLine); mTags.add(tag); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/grammars/CommentListener.java100644 0 0 5022 12026051001 27626 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.grammars; /** * This interface is used to be notified by parser about comments * in the parsed code. * * @author o_sukhodolsky */ public interface CommentListener { /** * Report the location of a single line comment that extends from the * given point to the end of the line. The type of comment is identified * by a String whose value depends on the language being parsed, but would * typically be the delimiter for the comment. * * @param aType an identifier for what type of comment it is. * @param aStartLineNo the starting line number * @param aStartColNo the starting column number */ void reportSingleLineComment(String aType, int aStartLineNo, int aStartColNo); /** * Report the location of a block comment that can span multiple lines. * The type of comment is identified by a String whose value depends on * the language being parsed, but would typically be the delimiter for the * comment. * * @param aType an identifier for what type of comment it is. * @param aStartLineNo the starting line number * @param aStartColNo the starting column number * @param aEndLineNo the ending line number * @param aEndColNo the ending column number */ void reportBlockComment(String aType, int aStartLineNo, int aStartColNo, int aEndLineNo, int aEndColNo); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/grammars/java.g100644 0 0 162472 12022116361 25030 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001 - 2007 Oliver Burn // // This program 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 2 // of the License, or (at your option) any later version. // // This program 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //////////////////////////////////////////////////////////////////////////////// header { package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.api.DetailAST; import java.text.MessageFormat; import antlr.CommonToken; } /** Java 1.5 Recognizer * * This grammar is in the PUBLIC DOMAIN */ class GeneratedJavaRecognizer extends Parser; options { k = 2; // two token lookahead exportVocab=GeneratedJava; // Call its vocabulary "GeneratedJava" codeGenMakeSwitchThreshold = 2; // Some optimizations codeGenBitsetTestThreshold = 3; defaultErrorHandler = false; // Don't generate parser error handlers buildAST = true; } tokens { //Pre-1.4 tokens BLOCK; MODIFIERS; OBJBLOCK; SLIST; CTOR_DEF; METHOD_DEF; VARIABLE_DEF; INSTANCE_INIT; STATIC_INIT; TYPE; CLASS_DEF; INTERFACE_DEF; PACKAGE_DEF; ARRAY_DECLARATOR; EXTENDS_CLAUSE; IMPLEMENTS_CLAUSE; PARAMETERS; PARAMETER_DEF; LABELED_STAT; TYPECAST; INDEX_OP; POST_INC; POST_DEC; METHOD_CALL; EXPR; ARRAY_INIT; IMPORT; UNARY_MINUS; UNARY_PLUS; CASE_GROUP; ELIST; FOR_INIT; FOR_CONDITION; FOR_ITERATOR; EMPTY_STAT; FINAL="final"; ABSTRACT="abstract"; STRICTFP="strictfp"; SUPER_CTOR_CALL; CTOR_CALL; //ANTLR-generated pre-1.4 tokens now listed here to preserve their numerical //order so as to make all future version of this grammar backwardly compatibile LITERAL_package="package";SEMI;LITERAL_import="import";LBRACK;RBRACK; LITERAL_void="void";LITERAL_boolean="boolean";LITERAL_byte="byte"; LITERAL_char="char";LITERAL_short="short";LITERAL_int="int"; LITERAL_float="float";LITERAL_long="long";LITERAL_double="double"; IDENT;DOT;STAR;LITERAL_private="private";LITERAL_public="public"; LITERAL_protected="protected";LITERAL_static="static"; LITERAL_transient="transient";LITERAL_native="native"; LITERAL_synchronized="synchronized";LITERAL_volatile="volatile"; LITERAL_class="class";LITERAL_extends="extends"; LITERAL_interface="interface";LCURLY;RCURLY;COMMA; LITERAL_implements="implements";LPAREN;RPAREN;LITERAL_this="this"; LITERAL_super="super";ASSIGN;LITERAL_throws="throws";COLON; LITERAL_if="if";LITERAL_while="while";LITERAL_do="do"; LITERAL_break="break";LITERAL_continue="continue";LITERAL_return="return"; LITERAL_switch="switch";LITERAL_throw="throw";LITERAL_for="for"; LITERAL_else="else";LITERAL_case="case";LITERAL_default="default"; LITERAL_try="try";LITERAL_catch="catch";LITERAL_finally="finally"; PLUS_ASSIGN;MINUS_ASSIGN;STAR_ASSIGN;DIV_ASSIGN;MOD_ASSIGN;SR_ASSIGN; BSR_ASSIGN;SL_ASSIGN;BAND_ASSIGN;BXOR_ASSIGN;BOR_ASSIGN;QUESTION; LOR;LAND;BOR;BXOR;BAND;NOT_EQUAL;EQUAL;LT;GT;LE;GE; LITERAL_instanceof="instanceof";SL;SR;BSR;PLUS;MINUS;DIV;MOD; INC;DEC;BNOT;LNOT;LITERAL_true="true";LITERAL_false="false"; LITERAL_null="null";LITERAL_new="new";NUM_INT;CHAR_LITERAL; STRING_LITERAL;NUM_FLOAT;NUM_LONG;NUM_DOUBLE;WS;SL_COMMENT; ML_COMMENT;ESC;HEX_DIGIT;VOCAB;EXPONENT;FLOAT_SUFFIX; //Token for Java 1.4 language enhancements ASSERT; //Tokens for Java 1.5 language enhancements STATIC_IMPORT; ENUM; ENUM_DEF; ENUM_CONSTANT_DEF; FOR_EACH_CLAUSE; ANNOTATION_DEF; ANNOTATIONS; ANNOTATION; ANNOTATION_MEMBER_VALUE_PAIR; ANNOTATION_FIELD_DEF; ANNOTATION_ARRAY_INIT; TYPE_ARGUMENTS; TYPE_ARGUMENT; TYPE_PARAMETERS; TYPE_PARAMETER; WILDCARD_TYPE; TYPE_UPPER_BOUNDS; TYPE_LOWER_BOUNDS; AT; ELLIPSIS; GENERIC_START; GENERIC_END; TYPE_EXTENSION_AND; // token which was not included to grammar initially // we need to put it to the end to maintain binary compatibility // with previous versions DO_WHILE; //Tokens for Java 1.7 language enhancements RESOURCE_SPECIFICATION; RESOURCES; RESOURCE; } { /** * Counts the number of LT seen in the typeArguments production. * It is used in semantic predicates to ensure we have seen * enough closing '>' characters; which actually may have been * either GT, SR or BSR tokens. */ private int ltCounter = 0; /** * Counts the number of '>' characters that have been seen but * have not yet been associated with the end of a typeParameters or * typeArguments production. This is necessary because SR and BSR * tokens have significance (the extra '>' characters) not only for the production * that sees them but also productions higher in the stack (possibly right up to an outer-most * typeParameters production). As the stack of the typeArguments/typeParameters productions unwind, * any '>' characters seen prematurely through SRs or BSRs are reconciled. */ private int gtToReconcile = 0; /** * The most recently seen gt sequence (GT, SR or BSR) * encountered in any type argument or type parameter production. * We retain this so we can keep manage the synthetic GT tokens/ * AST nodes we emit to have '<' & '>' balanced trees when encountering * SR and BSR tokens. */ private DetailAST currentGtSequence = null; /** * Consume a sequence of '>' characters (GT, SR or BSR) * and match these against the '<' characters seen. */ private void consumeCurrentGtSequence(DetailAST gtSequence) { currentGtSequence = gtSequence; gtToReconcile += currentGtSequence.getText().length(); ltCounter -= currentGtSequence.getText().length(); } /** * Emits a single GT AST node with the line and column correctly * set to its position in the source file. This must only * ever be called when a typeParameters or typeArguments production * is ending and there is at least one GT character to be emitted. * * @see #areThereGtsToEmit */ private DetailAST emitSingleGt() { gtToReconcile -= 1; CommonToken gtToken = new CommonToken(GENERIC_END, ">"); gtToken.setLine(currentGtSequence.getLineNo()); gtToken.setColumn(currentGtSequence.getColumnNo() + (currentGtSequence.getText().length() - gtToReconcile)); return (DetailAST)astFactory.create(gtToken); } /** * @return true if there is at least one '>' seen but * not reconciled with the end of a typeParameters or * typeArguments production; returns false otherwise */ private boolean areThereGtsToEmit() { return (gtToReconcile > 0); } /** * @return true if there is exactly one '>' seen but * not reconciled with the end of a typeParameters * production; returns false otherwise */ private boolean isThereASingleGtToEmit() { return (gtToReconcile == 1); } /** * @return true if the '<' and '>' are evenly matched * at the current typeParameters/typeArguments nested depth */ private boolean areLtsAndGtsBalanced(int currentLtLevel) { return ((currentLtLevel != 0) || ltCounter == currentLtLevel); } } // Compilation Unit: In Java, this is a single file. This is the start // rule for this parser compilationUnit : // A compilation unit starts with an optional package definition // semantic check because package definitions can be annotated // which causes possible non-determinism in Antrl ( (annotations "package")=> packageDefinition | /* nothing */ ) // Next we have a series of zero or more import statements ( importDefinition )* // Wrapping things up with any number of class or interface // definitions ( typeDefinition )* EOF! ; // Package statement: "package" followed by an identifier. packageDefinition options {defaultErrorHandler = true;} // let ANTLR handle errors : annotations p:"package"^ {#p.setType(PACKAGE_DEF);} identifier SEMI ; // Import statement: import followed by a package or class name importDefinition options {defaultErrorHandler = true;} : i:"import"^ {#i.setType(IMPORT);} ( "static" {#i.setType(STATIC_IMPORT);} )? identifierStar SEMI ; // A type definition in a file is either a class, interface, enum of annotation definition typeDefinition options {defaultErrorHandler = true;} : m:modifiers! typeDefinitionInternal[#m] | SEMI ; // Internal type definition for production reuse protected typeDefinitionInternal[AST modifiers] : classDefinition[#modifiers] | interfaceDefinition[#modifiers] | enumDefinition[#modifiers] | annotationDefinition[#modifiers] ; // A type specification is a type name with possible brackets afterwards // (which would make it an array type). typeSpec[boolean addImagNode] : classTypeSpec[addImagNode] | builtInTypeSpec[addImagNode] ; // A class type specification is a class type with either: // - possible brackets afterwards // (which would make it an array type). // - generic type arguments after classTypeSpec[boolean addImagNode] : classOrInterfaceType[addImagNode] (options{greedy=true;}: lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} RBRACK)* { if ( addImagNode ) { #classTypeSpec = #(#[TYPE,"TYPE"], #classTypeSpec); } } ; classOrInterfaceType[boolean addImagNode] : IDENT (typeArguments[addImagNode])? (options{greedy=true;}: // match as many as possible DOT^ IDENT (typeArguments[addImagNode])? )* ; // A generic type argument is a class type, a possibly bounded wildcard type or a built-in type array typeArgument[boolean addImagNode] : ( classTypeSpec[addImagNode] | builtInTypeArraySpec[addImagNode] | wildcardType[addImagNode] ) {#typeArgument = #(#[TYPE_ARGUMENT,"TYPE_ARGUMENT"], #typeArgument);} ; wildcardType[boolean addImagNode] : q:QUESTION {#q.setType(WILDCARD_TYPE);} (("extends" | "super")=> typeArgumentBounds[addImagNode])? ; typeArguments[boolean addImagNode] {int currentLtLevel = 0;} : {currentLtLevel = ltCounter;} lt:LT {#lt.setType(GENERIC_START); ;ltCounter++;} // (Dinesh Bolkensteyn) Added support for Java 7 diamond notation (disabled ambiguous warnings since generated code seems to work) (options{generateAmbigWarnings=false;}:typeArgument[addImagNode] (options{greedy=true;}: // match as many as possible // If there are any '>' to reconcile // (i.e. we've recently encountered a DT, SR or BSR // - the end of one or more type arguments and // possibly an enclosing type parameter) // then further type arguments are not possible {gtToReconcile == 0}? COMMA typeArgument[addImagNode] )*)? ( // turn warning off since Antlr generates the right code, // plus we have our semantic predicate below options{generateAmbigWarnings=false;}: typeArgumentsOrParametersEnd )? // As we are leaving a typeArguments production, the enclosing '>' // we've just read (and we've possibly seen more than one in the // case of SRs and BSRs) can now be marked as reconciled with a '<' // but we still leave unreconciled the count for any excess '>' // for other typeArguments or typeParameters productions higher in // the stack { if (areThereGtsToEmit()) { astFactory.addASTChild(currentAST, emitSingleGt()); } } // make sure we have gobbled up enough '>' characters // if we are at the "top level" of nested typeArgument productions {areLtsAndGtsBalanced(currentLtLevel)}? {#typeArguments = #(#[TYPE_ARGUMENTS, "TYPE_ARGUMENTS"], #typeArguments);} ; // this gobbles up *some* amount of '>' characters, and counts how many // it gobbled. protected typeArgumentsOrParametersEnd! : g:GT {consumeCurrentGtSequence((DetailAST)#g);} | sr:SR {consumeCurrentGtSequence((DetailAST)#sr);} | bsr:BSR {consumeCurrentGtSequence((DetailAST)#bsr);} ; typeArgumentBounds[boolean addImagNode] : ( e:"extends"^ {#e.setType(TYPE_UPPER_BOUNDS); } | s:"super"^ { #s.setType(TYPE_LOWER_BOUNDS); } ) ( classOrInterfaceType[addImagNode] | builtInType ) (options{greedy=true;}: lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} RBRACK)? ; // A builtin type array specification is a builtin type with brackets afterwards builtInTypeArraySpec[boolean addImagNode] : builtInType (options{greedy=true;}: lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} RBRACK)+ { if ( addImagNode ) { #builtInTypeArraySpec = #(#[TYPE,"TYPE"], #builtInTypeArraySpec); } } ; // A builtin type specification is a builtin type with possible brackets // afterwards (which would make it an array type). builtInTypeSpec[boolean addImagNode] : builtInType (lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} RBRACK)* { if ( addImagNode ) { #builtInTypeSpec = #(#[TYPE,"TYPE"], #builtInTypeSpec); } } ; // A type name. which is either a (possibly qualified and parameterized) // class name or a primitive (builtin) type type : classOrInterfaceType[false] | builtInType ; /** A declaration is the creation of a reference or primitive-type variable * Create a separate Type/Var tree for each var in the var list. */ declaration! : m:modifiers t:typeSpec[false] v:variableDefinitions[#m,#t] {#declaration = #v;} ; // The primitive types. builtInType : "void" | "boolean" | "byte" | "char" | "short" | "int" | "float" | "long" | "double" ; // A (possibly-qualified) java identifier. We start with the first IDENT // and expand its name by adding dots and following IDENTS identifier : IDENT ( DOT^ IDENT )* ; identifierStar : IDENT ( DOT^ IDENT )* ( DOT^ STAR )? ; // A list of zero or more modifiers. We could have used (modifier)* in // place of a call to modifiers, but I thought it was a good idea to keep // this rule separate so they can easily be collected in a Vector if // someone so desires modifiers : ( //hush warnings since the semantic check for "@interface" solves the non-determinism options{generateAmbigWarnings=false;}: modifier | //Semantic check that we aren't matching @interface as this is not an annotation //A nicer way to do this would be, um, nice {LA(1)==AT && !LT(2).getText().equals("interface")}? annotation )* {#modifiers = #([MODIFIERS, "MODIFIERS"], #modifiers);} ; // modifiers for Java classes, interfaces, class/instance vars and methods modifier : "private" | "public" | "protected" | "static" | "transient" | "final" | "abstract" | "native" | "synchronized" // | "const" // reserved word, but not valid | "volatile" | "strictfp" ; annotation! : AT i:identifier ( l:LPAREN ( args:annotationArguments )? r:RPAREN )? {#annotation = #(#[ANNOTATION,"ANNOTATION"], AT, i, l, args, r);} ; annotations : (annotation)* {#annotations = #(#[ANNOTATIONS,"ANNOTATIONS"], #annotations);} ; annotationArguments : annotationMemberValueInitializer | annotationMemberValuePairs ; annotationMemberValuePairs : annotationMemberValuePair ( COMMA annotationMemberValuePair )* ; annotationMemberValuePair! : i:IDENT a:ASSIGN v:annotationMemberValueInitializer {#annotationMemberValuePair = #(#[ANNOTATION_MEMBER_VALUE_PAIR,"ANNOTATION_MEMBER_VALUE_PAIR"], i, a, v);} ; annotationMemberValueInitializer : annotationExpression | annotation | annotationMemberArrayInitializer ; // This is an initializer used to set up an annotation member array. annotationMemberArrayInitializer : lc:LCURLY^ {#lc.setType(ANNOTATION_ARRAY_INIT);} ( annotationMemberArrayValueInitializer ( // CONFLICT: does a COMMA after an initializer start a new // initializer or start the option ',' at end? // ANTLR generates proper code by matching // the comma as soon as possible. options { warnWhenFollowAmbig = false; } : COMMA annotationMemberArrayValueInitializer )* (COMMA)? )? RCURLY ; // The two things that can initialize an annotation array element are a conditional expression // and an annotation (nested annotation array initialisers are not valid) annotationMemberArrayValueInitializer : annotationExpression | annotation ; annotationExpression : conditionalExpression {#annotationExpression = #(#[EXPR,"EXPR"],#annotationExpression);} ; // Definition of a Java class classDefinition![AST modifiers] : c:"class" IDENT // it _might_ have type paramaters (tp:typeParameters)? // it _might_ have a superclass... sc:superClassClause // it might implement some interfaces... ic:implementsClause // now parse the body of the class cb:classBlock {#classDefinition = #(#[CLASS_DEF,"CLASS_DEF"], modifiers, c, IDENT, tp, sc, ic, cb);} ; superClassClause : ( e:"extends"^ {#e.setType(EXTENDS_CLAUSE);} c:classOrInterfaceType[false] )? ; // Definition of a Java Interface interfaceDefinition![AST modifiers] : i:"interface" IDENT // it _might_ have type paramaters (tp:typeParameters)? // it might extend some other interfaces ie:interfaceExtends // now parse the body of the interface (looks like a class...) cb:classBlock {#interfaceDefinition = #(#[INTERFACE_DEF,"INTERFACE_DEF"], modifiers, i, IDENT,tp,ie,cb);} ; enumDefinition![AST modifiers] : e:ENUM IDENT // it might implement some interfaces... ic:implementsClause // now parse the body of the enum eb:enumBlock {#enumDefinition = #(#[ENUM_DEF,"ENUM_DEF"], modifiers, e, IDENT, ic, eb);} ; annotationDefinition![AST modifiers] : a:AT i:"interface" IDENT // now parse the body of the annotation ab:annotationBlock {#annotationDefinition = #(#[ANNOTATION_DEF,"ANNOTATION_DEF"], modifiers, a, i, IDENT, ab);} ; typeParameters {int currentLtLevel = 0;} : {currentLtLevel = ltCounter;} lt:LT {#lt.setType(GENERIC_START); ltCounter++;} typeParameter (COMMA typeParameter)* (typeArgumentsOrParametersEnd)? // There should be only one '>' to reconcile - the enclosing // '>' for the type parameter. Any other adjacent '>' seen should // have been reconciled with type arguments for the last type parameter // hence we can assert here that there is but one unaccounted '>'. { if (isThereASingleGtToEmit()) { astFactory.addASTChild(currentAST, emitSingleGt()); } } // make sure we have gobbled up enough '>' characters // if we are at the "top level" of nested typeArgument productions {areLtsAndGtsBalanced(currentLtLevel)}? {#typeParameters = #(#[TYPE_PARAMETERS, "TYPE_PARAMETERS"], #typeParameters);} ; typeParameter : // I'm pretty sure Antlr generates the right thing here: (id:IDENT) ( options{generateAmbigWarnings=false;}: typeParameterBounds )? {#typeParameter = #(#[TYPE_PARAMETER,"TYPE_PARAMETER"], #typeParameter);} ; typeParameterBounds : e:"extends"^ classOrInterfaceType[true] (b:BAND {#b.setType(TYPE_EXTENSION_AND);} classOrInterfaceType[true])* {#e.setType(TYPE_UPPER_BOUNDS);} ; // This is the body of an annotation. You can have annotation fields and extra semicolons, // That's about it (until you see what an annoation field is...) annotationBlock : LCURLY ( annotationField | SEMI )* RCURLY {#annotationBlock = #([OBJBLOCK, "OBJBLOCK"], #annotationBlock);} ; // An annotation field annotationField! : mods:modifiers ( td:typeDefinitionInternal[#mods] {#annotationField = #td;} | t:typeSpec[false] // annotation field ( i:IDENT // the name of the field LPAREN RPAREN rt:declaratorBrackets[#t] ( d:annotationDefault )? s:SEMI {#annotationField = #(#[ANNOTATION_FIELD_DEF,"ANNOTATION_FIELD_DEF"], mods, #(#[TYPE,"TYPE"],rt), i, LPAREN, RPAREN, d, s );} | v:variableDefinitions[#mods,#t] s6:SEMI { #annotationField = #v; #v.addChild(#s6); } ) ) ; annotationDefault : "default"^ annotationMemberValueInitializer ; // This is the body of an enum. You can have zero or more enum constants // followed by any number of fields like a regular class enumBlock : LCURLY ( enumConstant ( options{greedy=true;}: COMMA enumConstant )* ( COMMA )? )? ( SEMI ( field | SEMI )* )? RCURLY {#enumBlock = #([OBJBLOCK, "OBJBLOCK"], #enumBlock);} ; //An enum constant may have optional parameters and may have a //a body enumConstant! : an:annotations i:IDENT ( l:LPAREN args:argList r:RPAREN )? ( b:enumConstantBlock )? {#enumConstant = #([ENUM_CONSTANT_DEF, "ENUM_CONSTANT_DEF"], an, i, l, args, r, b);} ; //The class-like body of an enum constant enumConstantBlock : LCURLY ( enumConstantField | SEMI )* RCURLY {#enumConstantBlock = #([OBJBLOCK, "OBJBLOCK"], #enumConstantBlock);} ; //An enum constant field is just like a class field but without //the posibility of a constructor definition or a static initializer enumConstantField! : mods:modifiers ( td:typeDefinitionInternal[#mods] {#enumConstantField = #td;} | // A generic method has the typeParameters before the return type. // This is not allowed for variable definitions, but this production // allows it, a semantic check could be used if you wanted. (tp:typeParameters)? t:typeSpec[false] // method or variable declaration(s) ( IDENT // the name of the method // parse the formal parameter declarations. LPAREN param:parameterDeclarationList RPAREN rt:declaratorBrackets[#t] // get the list of exceptions that this method is // declared to throw (tc:throwsClause)? ( s2:compoundStatement | s3:SEMI ) {#enumConstantField = #(#[METHOD_DEF,"METHOD_DEF"], mods, tp, #(#[TYPE,"TYPE"],rt), IDENT, LPAREN, param, RPAREN, tc, s2, s3);} | v:variableDefinitions[#mods,#t] s6:SEMI { #enumConstantField = #v; #v.addChild(#s6); } ) ) // "{ ... }" instance initializer | s4:compoundStatement {#enumConstantField = #(#[INSTANCE_INIT,"INSTANCE_INIT"], s4);} ; // This is the body of a class. You can have fields and extra semicolons, // That's about it (until you see what a field is...) classBlock : LCURLY ( field | SEMI )* RCURLY {#classBlock = #([OBJBLOCK, "OBJBLOCK"], #classBlock);} ; // An interface can extend several other interfaces... interfaceExtends : ( e:"extends"^ {#e.setType(EXTENDS_CLAUSE);} classOrInterfaceType[false] ( COMMA classOrInterfaceType[false] )* )? ; // A class can implement several interfaces... implementsClause : ( i:"implements"^ {#i.setType(IMPLEMENTS_CLAUSE);} classOrInterfaceType[false] ( COMMA classOrInterfaceType[false] )* )? ; // Now the various things that can be defined inside a class or interface... // Note that not all of these are really valid in an interface (constructors, // for example), and if this grammar were used for a compiler there would // need to be some semantic checks to make sure we're doing the right thing... field! : // method, constructor, or variable declaration mods:modifiers ( td:typeDefinitionInternal[#mods] {#field = #td;} // A generic method/ctor has the typeParameters before the return type. // This is not allowed for variable definitions, but this production // allows it, a semantic check could be used if you wanted. | (tp:typeParameters)? ( h:ctorHead s:constructorBody // constructor {#field = #(#[CTOR_DEF,"CTOR_DEF"], mods, tp, h, s);} | t:typeSpec[false] // method or variable declaration(s) ( IDENT // the name of the method // parse the formal parameter declarations. LPAREN param:parameterDeclarationList RPAREN rt:declaratorBrackets[#t] // get the list of exceptions that this method is // declared to throw (tc:throwsClause)? ( s2:compoundStatement | s5:SEMI ) {#field = #(#[METHOD_DEF,"METHOD_DEF"], mods, tp, #(#[TYPE,"TYPE"],rt), IDENT, LPAREN, param, RPAREN, tc, s2, s5);} | v:variableDefinitions[#mods,#t] s6:SEMI { #field = #v; #v.addChild(#s6); } ) ) ) // "static { ... }" class initializer | si:"static" s3:compoundStatement {#si.setType(STATIC_INIT); #si.setText("STATIC_INIT"); #field = #(#si, s3);} // "{ ... }" instance initializer | s4:compoundStatement {#field = #(#[INSTANCE_INIT,"INSTANCE_INIT"], s4);} ; constructorBody : lc:LCURLY^ {#lc.setType(SLIST);} // Predicate might be slow but only checked once per constructor def // not for general methods. ( (explicitConstructorInvocation) => explicitConstructorInvocation | ) (statement)* RCURLY ; explicitConstructorInvocation : ( options { // this/super can begin a primaryExpression too; with finite // lookahead ANTLR will think the 3rd alternative conflicts // with 1, 2. I am shutting off warning since ANTLR resolves // the nondeterminism by correctly matching alts 1 or 2 when // it sees this( or super( generateAmbigWarnings=false; } : (typeArguments[false])? ( t:"this"^ LPAREN argList RPAREN SEMI {#t.setType(CTOR_CALL);} | s:"super"^ LPAREN argList RPAREN SEMI {#s.setType(SUPER_CTOR_CALL);} ) | // (new Outer()).super() (create enclosing instance) primaryExpression DOT (typeArguments[false])? s1:"super"^ LPAREN argList RPAREN SEMI {#s1.setType(SUPER_CTOR_CALL);} ) ; variableDefinitions[AST mods, AST t] : variableDeclarator[(AST) getASTFactory().dupTree(mods), (AST) getASTFactory().dupList(t)] //dupList as this also copies siblings (like TYPE_ARGUMENTS) ( COMMA variableDeclarator[(AST) getASTFactory().dupTree(mods), (AST) getASTFactory().dupList(t)] //dupList as this also copies siblings (like TYPE_ARGUMENTS) )* ; /** Declaration of a variable. This can be a class/instance variable, * or a local variable in a method * It can also include possible initialization. */ variableDeclarator![AST mods, AST t] : id:IDENT d:declaratorBrackets[t] v:varInitializer {#variableDeclarator = #(#[VARIABLE_DEF,"VARIABLE_DEF"], mods, #(#[TYPE,"TYPE"],d), id, v);} ; declaratorBrackets[AST typ] : {#declaratorBrackets=typ;} (lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} RBRACK)* ; varInitializer : ( ASSIGN^ initializer )? ; // This is an initializer used to set up an array. arrayInitializer : lc:LCURLY^ {#lc.setType(ARRAY_INIT);} ( initializer ( // CONFLICT: does a COMMA after an initializer start a new // initializer or start the option ',' at end? // ANTLR generates proper code by matching // the comma as soon as possible. options { warnWhenFollowAmbig = false; } : COMMA initializer )* )? (COMMA)? RCURLY ; // The two "things" that can initialize an array element are an expression // and another (nested) array initializer. initializer : expression | arrayInitializer ; // This is the header of a method. It includes the name and parameters // for the method. // This also watches for a list of exception classes in a "throws" clause. ctorHead : IDENT // the name of the method // parse the formal parameter declarations. LPAREN parameterDeclarationList RPAREN // get the list of exceptions that this method is declared to throw (throwsClause)? ; // This is a list of exception classes that the method is declared to throw throwsClause : "throws"^ identifier ( COMMA identifier )* ; // A list of formal parameters // Zero or more parameters // If a parameter is variable length (e.g. String... myArg) it is the right-most parameter parameterDeclarationList // The semantic check in ( .... )* block is flagged as superfluous, and seems superfluous but // is the only way I could make this work. If my understanding is correct this is a known bug in Antlr : ( ( parameterDeclaration )=> parameterDeclaration ( options {warnWhenFollowAmbig=false;} : ( COMMA parameterDeclaration ) => COMMA parameterDeclaration )* ( COMMA variableLengthParameterDeclaration )? | variableLengthParameterDeclaration )? {#parameterDeclarationList = #(#[PARAMETERS,"PARAMETERS"], #parameterDeclarationList);} ; variableLengthParameterDeclaration! : pm:parameterModifier t:typeSpec[false] td:ELLIPSIS IDENT pd:declaratorBrackets[#t] {#variableLengthParameterDeclaration = #(#[PARAMETER_DEF,"PARAMETER_DEF"], pm, #([TYPE,"TYPE"],pd), td, IDENT);} ; parameterModifier //final can appear amongst annotations in any order - greedily consume any preceding //annotations to shut nond-eterminism warnings off : (options{greedy=true;} : annotation)* (f:"final")? (annotation)* {#parameterModifier = #(#[MODIFIERS,"MODIFIERS"], #parameterModifier);} ; // A formal parameter. // (Dinesh Bolkensteyn) Extended to support Java7's "multi-catch", several types seperated by '|' parameterDeclaration! : pm:parameterModifier t:typeSpec[false] (mct:multiCatchTypes { #t.setNextSibling(#mct); })? id:IDENT pd:declaratorBrackets[#t] {#parameterDeclaration = #(#[PARAMETER_DEF,"PARAMETER_DEF"], pm, #([TYPE,"TYPE"],pd), id);} ; multiCatchTypes : (BOR! typeSpec[false])+; // Compound statement. This is used in many contexts: // Inside a class definition prefixed with "static": // it is a class initializer // Inside a class definition without "static": // it is an instance initializer // As the body of a method // As a completely indepdent braced block of code inside a method // it starts a new scope for variable definitions compoundStatement : lc:LCURLY^ {#lc.setType(SLIST);} // include the (possibly-empty) list of statements (statement)* RCURLY ; // overrides the statement production in java.g, adds assertStatement statement : traditionalStatement | assertStatement ; // assert statement, available since JDK 1.4 assertStatement : ASSERT^ expression ( COLON expression )? SEMI ; // a traditional (JDK < 1.4) java statement, assert keyword is not allowed traditionalStatement // A list of statements in curly braces -- start a new scope! : compoundStatement // declarations are ambiguous with "ID DOT" relative to expression // statements. Must backtrack to be sure. Could use a semantic // predicate to test symbol table to see what the type was coming // up, but that's pretty hard without a symbol table ;) | (declaration)=> declaration SEMI // An expression statement. This could be a method call, // assignment statement, or any other expression evaluated for // side-effects. | expression SEMI // class definition | m:modifiers! classDefinition[#m] // Attach a label to the front of a statement | IDENT c:COLON^ {#c.setType(LABELED_STAT);} statement // If-else statement | "if"^ LPAREN expression RPAREN statement ( // CONFLICT: the old "dangling-else" problem... // ANTLR generates proper code matching // as soon as possible. Hush warning. options { warnWhenFollowAmbig = false; } : elseStatement )? // For statement | forStatement // While statement | "while"^ LPAREN expression RPAREN statement // do-while statement | "do"^ statement w:"while" {#w.setType(DO_WHILE);} LPAREN expression RPAREN SEMI // get out of a loop (or switch) | "break"^ (IDENT)? SEMI // do next iteration of a loop | "continue"^ (IDENT)? SEMI // Return an expression | "return"^ (expression)? SEMI // switch/case statement | "switch"^ LPAREN expression RPAREN LCURLY ( casesGroup )* RCURLY // exception try-catch block | tryBlock // throw an exception | "throw"^ expression SEMI // synchronize a statement | "synchronized"^ LPAREN expression RPAREN compoundStatement // empty statement | s:SEMI {#s.setType(EMPTY_STAT);} ; forStatement : f:"for"^ LPAREN ( (forInit SEMI)=>traditionalForClause | forEachClause) RPAREN statement // statement to loop over ; traditionalForClause : forInit SEMI // initializer forCond SEMI // condition test forIter // updater ; forEachClause : forEachDeclarator COLON expression {#forEachClause = #(#[FOR_EACH_CLAUSE,"FOR_EACH_CLAUSE"], #forEachClause);} ; forEachDeclarator! : m:modifiers t:typeSpec[false] id:IDENT d:declaratorBrackets[#t] {#forEachDeclarator = #(#[VARIABLE_DEF,"VARIABLE_DEF"], m, #(#[TYPE,"TYPE"],d), id);} ; elseStatement : "else"^ statement ; casesGroup : ( // CONFLICT: to which case group do the statements bind? // ANTLR generates proper code: it groups the // many "case"/"default" labels together then // follows them with the statements options { warnWhenFollowAmbig = false; } : aCase )+ caseSList {#casesGroup = #([CASE_GROUP, "CASE_GROUP"], #casesGroup);} ; aCase : ("case"^ expression | "default"^) COLON ; caseSList : (statement)* {#caseSList = #(#[SLIST,"SLIST"],#caseSList);} ; // The initializer for a for loop forInit // if it looks like a declaration, it is : ( (declaration)=> declaration // otherwise it could be an expression list... | expressionList )? {#forInit = #(#[FOR_INIT,"FOR_INIT"],#forInit);} ; forCond : (expression)? {#forCond = #(#[FOR_CONDITION,"FOR_CONDITION"],#forCond);} ; forIter : (expressionList)? {#forIter = #(#[FOR_ITERATOR,"FOR_ITERATOR"],#forIter);} ; // an exception handler try/catch block // (Dinesh Bolkensteyn): Added support for Java 7 try-with-resources tryBlock : "try"^ // try-with-resources (resourceSpecification)? compoundStatement (handler)* ( finallyHandler )? ; resourceSpecification : LPAREN resources (SEMI)? RPAREN {#resourceSpecification = #([RESOURCE_SPECIFICATION, "RESOURCE_SPECIFICATION"], #resourceSpecification);} ; resources : resource (SEMI resource)* {#resources = #([RESOURCES, "RESOURCES"], #resources);} ; resource : modifiers typeSpec[true] IDENT resource_assign {#resource = #([RESOURCE, "RESOURCE"], #resource);} ; resource_assign : ASSIGN^ expression ; // an exception handler handler : "catch"^ LPAREN parameterDeclaration RPAREN compoundStatement ; finallyHandler : "finally"^ compoundStatement ; // expressions // Note that most of these expressions follow the pattern // thisLevelExpression : // nextHigherPrecedenceExpression // (OPERATOR nextHigherPrecedenceExpression)* // which is a standard recursive definition for a parsing an expression. // The operators in java have the following precedences: // lowest (13) = *= /= %= += -= <<= >>= >>>= &= ^= |= // (12) ?: // (11) || // (10) && // ( 9) | // ( 8) ^ // ( 7) & // ( 6) == != // ( 5) < <= > >= // ( 4) << >> // ( 3) +(binary) -(binary) // ( 2) * / % // ( 1) ++ -- +(unary) -(unary) ~ ! (type) // [] () (method call) . (dot -- identifier qualification) // new () (explicit parenthesis) // // the last two are not usually on a precedence chart; I put them in // to point out that new has a higher precedence than '.', so you // can validy use // new Frame().show() // // Note that the above precedence levels map to the rules below... // Once you have a precedence chart, writing the appropriate rules as below // is usually very straightfoward // the mother of all expressions expression : assignmentExpression {#expression = #(#[EXPR,"EXPR"],#expression);} ; // This is a list of expressions. expressionList : expression (COMMA expression)* {#expressionList = #(#[ELIST,"ELIST"], expressionList);} ; // assignment expression (level 13) assignmentExpression : conditionalExpression ( ( ASSIGN^ | PLUS_ASSIGN^ | MINUS_ASSIGN^ | STAR_ASSIGN^ | DIV_ASSIGN^ | MOD_ASSIGN^ | SR_ASSIGN^ | BSR_ASSIGN^ | SL_ASSIGN^ | BAND_ASSIGN^ | BXOR_ASSIGN^ | BOR_ASSIGN^ ) assignmentExpression )? ; // conditional test (level 12) conditionalExpression : logicalOrExpression ( QUESTION^ assignmentExpression COLON conditionalExpression )? ; // logical or (||) (level 11) logicalOrExpression : logicalAndExpression (LOR^ logicalAndExpression)* ; // logical and (&&) (level 10) logicalAndExpression : inclusiveOrExpression (LAND^ inclusiveOrExpression)* ; // bitwise or non-short-circuiting or (|) (level 9) inclusiveOrExpression : exclusiveOrExpression (BOR^ exclusiveOrExpression)* ; // exclusive or (^) (level 8) exclusiveOrExpression : andExpression (BXOR^ andExpression)* ; // bitwise or non-short-circuiting and (&) (level 7) andExpression : equalityExpression (BAND^ equalityExpression)* ; // equality/inequality (==/!=) (level 6) equalityExpression : relationalExpression ((NOT_EQUAL^ | EQUAL^) relationalExpression)* ; // boolean relational expressions (level 5) relationalExpression : shiftExpression ( ( ( LT^ | GT^ | LE^ | GE^ ) shiftExpression )* | "instanceof"^ typeSpec[true] ) ; // bit shift expressions (level 4) shiftExpression : additiveExpression ((SL^ | SR^ | BSR^) additiveExpression)* ; // binary addition/subtraction (level 3) additiveExpression : multiplicativeExpression ((PLUS^ | MINUS^) multiplicativeExpression)* ; // multiplication/division/modulo (level 2) multiplicativeExpression : unaryExpression ((STAR^ | DIV^ | MOD^ ) unaryExpression)* ; unaryExpression : INC^ unaryExpression | DEC^ unaryExpression | MINUS^ {#MINUS.setType(UNARY_MINUS);} unaryExpression | PLUS^ {#PLUS.setType(UNARY_PLUS);} unaryExpression | unaryExpressionNotPlusMinus ; unaryExpressionNotPlusMinus : BNOT^ unaryExpression | LNOT^ unaryExpression | ( // subrule allows option to shut off warnings options { // "(int" ambig with postfixExpr due to lack of sequence // info in linear approximate LL(k). It's ok. Shut up. generateAmbigWarnings=false; } : // If typecast is built in type, must be numeric operand // Also, no reason to backtrack if type keyword like int, float... lpb:LPAREN^ {#lpb.setType(TYPECAST);} builtInTypeSpec[true] RPAREN unaryExpression // Have to backtrack to see if operator follows. If no operator // follows, it's a typecast. No semantic checking needed to parse. // if it _looks_ like a cast, it _is_ a cast; else it's a "(expr)" | (LPAREN classTypeSpec[true] RPAREN unaryExpressionNotPlusMinus)=> lp:LPAREN^ {#lp.setType(TYPECAST);} classTypeSpec[true] RPAREN unaryExpressionNotPlusMinus | postfixExpression ) ; // TODO: handle type parameters more effectively - I think this production needs // a refactoring like the original Antlr Java grammar got // qualified names, array expressions, method invocation, post inc/dec postfixExpression : primaryExpression // start with a primary ( // qualified id (id.id.id.id...) -- build the name DOT^ ( (typeArguments[false])? ( IDENT | "this" | "super" // ClassName.super.field ) | "class" | newExpression ) // the above line needs a semantic check to make sure "class" // is the _last_ qualifier. // allow ClassName[].class | ( lbc:LBRACK^ {#lbc.setType(ARRAY_DECLARATOR);} RBRACK )+ DOT^ "class" // an array indexing operation | lb:LBRACK^ {#lb.setType(INDEX_OP);} expression RBRACK // method invocation // The next line is not strictly proper; it allows x(3)(4) or // x[2](4) which are not valid in Java. If this grammar were used // to validate a Java program a semantic check would be needed, or // this rule would get really ugly... // It also allows ctor invocation like super(3) which is now // handled by the explicit constructor rule, but it would // be hard to syntactically prevent ctor calls here | lp:LPAREN^ {#lp.setType(METHOD_CALL);} argList RPAREN )* // possibly add on a post-increment or post-decrement. // allows INC/DEC on too much, but semantics can check ( in:INC^ {#in.setType(POST_INC);} | de:DEC^ {#de.setType(POST_DEC);} | // nothing ) ; // the basic element of an expression primaryExpression : IDENT | constant | "true" | "false" | "this" | "null" | newExpression | LPAREN assignmentExpression RPAREN | "super" // look for int.class and int[].class | builtInType ( lbt:LBRACK^ {#lbt.setType(ARRAY_DECLARATOR);} RBRACK )* DOT^ "class" ; /** object instantiation. * Trees are built as illustrated by the following input/tree pairs: * * new T() * * new * | * T -- ELIST * | * arg1 -- arg2 -- .. -- argn * * new int[] * * new * | * int -- ARRAY_DECLARATOR * * new int[] {1,2} * * new * | * int -- ARRAY_DECLARATOR -- ARRAY_INIT * | * EXPR -- EXPR * | | * 1 2 * * new int[3] * new * | * int -- ARRAY_DECLARATOR * | * EXPR * | * 3 * * new int[1][2] * * new * | * int -- ARRAY_DECLARATOR * | * ARRAY_DECLARATOR -- EXPR * | | * EXPR 1 * | * 2 * */ newExpression : "new"^ (typeArguments[false])? type ( LPAREN argList RPAREN (classBlock)? //java 1.1 // Note: This will allow bad constructs like // new int[4][][3] {exp,exp}. // There needs to be a semantic check here... // to make sure: // a) [ expr ] and [ ] are not mixed // b) [ expr ] and an init are not used together | newArrayDeclarator (arrayInitializer)? ) ; argList : ( expressionList | /*nothing*/ {#argList = #[ELIST,"ELIST"];} ) ; newArrayDeclarator : ( // CONFLICT: // newExpression is a primaryExpression which can be // followed by an array index reference. This is ok, // as the generated code will stay in this loop as // long as it sees an LBRACK (proper behavior) options { warnWhenFollowAmbig = false; } : lb:LBRACK^ {#lb.setType(ARRAY_DECLARATOR);} (expression)? RBRACK )+ ; constant : NUM_INT | NUM_LONG | NUM_FLOAT | NUM_DOUBLE | CHAR_LITERAL | STRING_LITERAL ; //---------------------------------------------------------------------------- // The Java scanner //---------------------------------------------------------------------------- class GeneratedJavaLexer extends Lexer; options { exportVocab=GeneratedJava; // call the vocabulary "Java" testLiterals=false; // don't automatically test for literals k=4; // four characters of lookahead charVocabulary='\u0000'..'\uFFFE'; // without inlining some bitset tests, couldn't do unicode; // I need to make ANTLR generate smaller bitsets; see // bottom of JavaLexer.java codeGenBitsetTestThreshold=20; } // JavaLexer verbatim source code { // explicitly set tab width to 1 (default in ANTLR 2.7.1) // in ANTLR 2.7.2a2 the default has changed from 1 to 8 public void tab() { setColumn( getColumn() + 1 ); } private CommentListener mCommentListener = null; // TODO: Check visibility of this method one parsing is done in central // utility method public void setCommentListener(CommentListener aCommentListener) { mCommentListener = aCommentListener; } private boolean mTreatAssertAsKeyword = true; public void setTreatAssertAsKeyword(boolean aTreatAsKeyword) { mTreatAssertAsKeyword = aTreatAsKeyword; } private boolean mTreatEnumAsKeyword = true; public void setTreatEnumAsKeyword(boolean aTreatAsKeyword) { mTreatEnumAsKeyword = aTreatAsKeyword; } } // OPERATORS QUESTION : '?' ; LPAREN : '(' ; RPAREN : ')' ; LBRACK : '[' ; RBRACK : ']' ; LCURLY : '{' ; RCURLY : '}' ; COLON : ':' ; COMMA : ',' ; //DOT : '.' ; ASSIGN : '=' ; EQUAL : "==" ; LNOT : '!' ; BNOT : '~' ; NOT_EQUAL : "!=" ; DIV : '/' ; DIV_ASSIGN : "/=" ; PLUS : '+' ; PLUS_ASSIGN : "+=" ; INC : "++" ; MINUS : '-' ; MINUS_ASSIGN : "-=" ; DEC : "--" ; STAR : '*' ; STAR_ASSIGN : "*=" ; MOD : '%' ; MOD_ASSIGN : "%=" ; SR : ">>" ; SR_ASSIGN : ">>=" ; BSR : ">>>" ; BSR_ASSIGN : ">>>=" ; GE : ">=" ; GT : ">" ; SL : "<<" ; SL_ASSIGN : "<<=" ; LE : "<=" ; LT : '<' ; BXOR : '^' ; BXOR_ASSIGN : "^=" ; BOR : '|' ; BOR_ASSIGN : "|=" ; LOR : "||" ; BAND : '&' ; BAND_ASSIGN : "&=" ; LAND : "&&" ; SEMI : ';' ; //token signifying annotations and annotation declaration AT : '@' ; // Whitespace -- ignored WS : ( ' ' | '\t' | '\f' // handle newlines | ( options {generateAmbigWarnings=false;} : "\r\n" // Evil DOS | '\r' // Macintosh | '\n' // Unix (the right way) ) { newline(); } )+ { _ttype = Token.SKIP; } ; // Single-line comments SL_COMMENT : "//" { mCommentListener.reportSingleLineComment("//", getLine(), getColumn() - 3); } (~('\n'|'\r'))* ('\n'|'\r'('\n')?|) {$setType(Token.SKIP); newline();} ; // multiple-line comments ML_COMMENT { int startLine = -1; int startCol = -1; } : "/*" { startLine = getLine(); startCol = getColumn() - 3; } ( /* '\r' '\n' can be matched in one alternative or by matching '\r' in one iteration and '\n' in another. I am trying to handle any flavor of newline that comes in, but the language that allows both "\r\n" and "\r" and "\n" to all be valid newline is ambiguous. Consequently, the resulting grammar must be ambiguous. I'm shutting this warning off. */ options { generateAmbigWarnings=false; } : { LA(2)!='/' }? '*' | '\r' '\n' {newline();} | '\r' {newline();} | '\n' {newline();} | ~('*'|'\n'|'\r') )* "*/" { mCommentListener.reportBlockComment("/*", startLine, startCol, getLine(), getColumn() - 2); $setType(Token.SKIP); } ; // character literals CHAR_LITERAL : '\'' ( ESC | ~'\'' ) '\'' ; // string literals STRING_LITERAL : '"' ( ESC | ~'"' )* '"' ; // escape sequence -- note that this is protected; it can only be called // from another lexer rule -- it will not ever directly return a token to // the parser // There are various ambiguities hushed in this rule. The optional // '0'...'9' digit matches should be matched here rather than letting // them go back to STRING_LITERAL to be matched. ANTLR does the // right thing by matching immediately; hence, it's ok to shut off // the FOLLOW ambig warnings. protected ESC : '\\' ( ('u')+ (options { generateAmbigWarnings=false; } : '0' '0' '5' ('c'|'C') (options { generateAmbigWarnings=false; } : '\\' ('u')+ '0' '0' '5' ('c'|'C') | STD_ESC ) | HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ) | STD_ESC ) ; protected STD_ESC : 'n' | 'r' | 't' | 'b' | 'f' | '"' | '\'' | '\\' | ('0'..'3') ( options { warnWhenFollowAmbig = false; } : ('0'..'7') ( options { warnWhenFollowAmbig = false; } : '0'..'7' )? )? | ('4'..'7') ( options { warnWhenFollowAmbig = false; } : ('0'..'9') )? ; // hexadecimal digit (again, note it's protected!) protected HEX_DIGIT : ('0'..'9'|'A'..'F'|'a'..'f') ; // binary digit (again, note it's protected!) protected BINARY_DIGIT : ('0'|'1') ; // a dummy rule to force vocabulary to be all characters (except special // ones that ANTLR uses internally (0 to 2) protected VOCAB : '\3'..'\377' ; protected ID_START: '_' | '$' | ( {Character.isJavaIdentifierStart(LA(1))}? ~( '_' | '$' | '/' | '*' | '0'..'9' | '.' | '\'' | '\\' | '"' | '\t' | '\n' | '\r' | ' ' | '\f' | '(' | ')' | '{' | '}' | '[' | ']'| ';' | ',' | '=' | '+' | '~' | '&' | '<' | '>' | '-' | '!' | '^' | '%' | ':' | '?' | '|'| '@' ) ) ; exception catch[SemanticException ex] { throw new SemanticException( MessageFormat.format( "Unexpected character {0} in identifier", new Object[] {"0x" + Integer.toHexString(LA(1))}), getFilename(), getLine(), getColumn()); } protected ID_PART : '_' | '$' | ( {Character.isJavaIdentifierPart(LA(1))}? ~( '_' | '$' | '/' | '*' | '.' | '\'' | '\\' | '"' | '\t' | '\n' | '\r' | ' ' | '\f' | '(' | ')' | '{' | '}' | '[' | ']'| ';' | ',' | '=' | '+' | '~' | '&' | '<' | '>' | '-' | '!' | '^' | '%' | ':' | '?' | '|' | '@' ) ) ; exception catch[SemanticException ex] { throw new SemanticException( MessageFormat.format( "Unexpected character {0} in identifier", new Object[] {"0x" + Integer.toHexString(LA(1))}), getFilename(), getLine(), getColumn()); } // an identifier. Note that testLiterals is set to true! This means // that after we match the rule, we look in the literals table to see // if it's a literal or really an identifer. As enum and assert // are purposefully not part of the literal list, we do manual tests on // the ident to test whether this should be an ENUM or ASSERT token. // This behaviour is controlled by the treatAssertAsKeyword and // treatEnumAsKeyword boolean properties on the lexer IDENT options {testLiterals=true;} : ID_START (ID_PART)* { if (mTreatAssertAsKeyword && "assert".equals($getText)) { $setType(ASSERT); } if (mTreatEnumAsKeyword && "enum".equals($getText)) { $setType(ENUM); } } ; //overriden definition of this lexer rule to recognize the ... token - for //variable argument length NUM_INT : (ELLIPSIS)=>ELLIPSIS {$setType(ELLIPSIS);} | (DOT)=>DOT {$setType(DOT);} | (DOUBLE_LITERAL)=>DOUBLE_LITERAL {$setType(NUM_DOUBLE);} | (FLOAT_LITERAL)=>FLOAT_LITERAL {$setType(NUM_FLOAT);} | (HEX_DOUBLE_LITERAL)=>HEX_DOUBLE_LITERAL {$setType(NUM_DOUBLE);} | (HEX_FLOAT_LITERAL)=>HEX_FLOAT_LITERAL {$setType(NUM_FLOAT);} | (LONG_LITERAL)=>LONG_LITERAL {$setType(NUM_LONG);} | (INT_LITERAL)=>INT_LITERAL {$setType(NUM_INT);} ; protected INT_LITERAL : ( '0' ( ('x'|'X')(HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))? // Hexa | ('b'|'B')(BINARY_DIGIT)((BINARY_DIGIT|'_')*(BINARY_DIGIT))? // Binary | ((('0'..'7')|'_')*('0'..'7'))? // If empty 0, otherwise octal (which may start with an underscore) ) | ('1'..'9') (('0'..'9'|'_')*('0'..'9'))? // Non-zero decimal ) ; protected LONG_LITERAL : ( '0' ( ('x'|'X')(HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))? // Hexa | ('b'|'B')(BINARY_DIGIT)((BINARY_DIGIT|'_')*(BINARY_DIGIT))? // Binary | ((('0'..'7')|'_')*('0'..'7'))? // If empty 0, otherwise octal (which may start with an underscore) ) | ('1'..'9') (('0'..'9'|'_')*('0'..'9'))? // Non-zero decimal ) // long signifier ('l'|'L') ; protected FLOAT_LITERAL : ( ((('0'..'9')(('0'..'9'|'_')*('0'..'9'))?)? '.')=> ( (('0'..'9')(('0'..'9'|'_')*('0'..'9'))?) '.' (('0'..'9')(('0'..'9'|'_')*('0'..'9'))?)? | '.' (('0'..'9')(('0'..'9'|'_')*('0'..'9'))?) ) (EXPONENT)? ('f'|'F')? | (('0'..'9')(('0'..'9'|'_')*('0'..'9'))?) ((EXPONENT ('f'|'F')?) | ('f'|'F')) ) ; protected DOUBLE_LITERAL : ( ((('0'..'9')(('0'..'9'|'_')*('0'..'9'))?)? '.')=> ( (('0'..'9')(('0'..'9'|'_')*('0'..'9'))?) '.' (('0'..'9')(('0'..'9'|'_')*('0'..'9'))?)? | '.' (('0'..'9')(('0'..'9'|'_')*('0'..'9'))?) ) | (('0'..'9')(('0'..'9'|'_')*('0'..'9'))?) ) (EXPONENT)? ('d'|'D') ; protected HEX_FLOAT_LITERAL : '0' ('x'|'X') ( (((HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))?)? '.')=> ( ((HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))?) '.' ((HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))?)? | '.' ((HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))?) ) | ((HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))?) ) BINARY_EXPONENT ('f'|'F')? ; protected HEX_DOUBLE_LITERAL : '0' ('x'|'X') ( (((HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))?)? '.')=> ( ((HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))?) '.' ((HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))?)? | '.' ((HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))?) ) | ((HEX_DIGIT)((HEX_DIGIT|'_')*(HEX_DIGIT))?) ) BINARY_EXPONENT ('d'|'D') ; protected ELLIPSIS : "..." ; protected DOT : '.' ; // a couple protected methods to assist in matching floating point numbers protected EXPONENT : ('e'|'E') SIGNED_INTEGER ; protected SIGNED_INTEGER : ('+'|'-')? (('0'..'9')(('0'..'9'|'_')*('0'..'9'))?) ; protected FLOAT_SUFFIX : 'f'|'F'|'d'|'D' ; protected BINARY_EXPONENT : ('p'|'P') SIGNED_INTEGER ; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/grammars/package-info.java100644 0 0 2306 12026051000 27043 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the grammar used by the Checkstyle framework. *

You should not be referring to this package. */ package com.puppycrawl.tools.checkstyle.grammars; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/AbstractCellEditor.java100644 0 0 13360 11451071613 27243 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /* * %W% %E% * * Copyright 1997, 1998 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ package com.puppycrawl.tools.checkstyle.gui; import java.util.EventObject; import javax.swing.CellEditor; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.event.EventListenerList; /** * A base class for CellEditors, providing default implementations for all * methods in the CellEditor interface and support for managing a series * of listeners. * * Original Source Location * * @author Philip Milne */ public class AbstractCellEditor implements CellEditor { private final EventListenerList mListenerList = new EventListenerList(); /** @see CellEditor */ public Object getCellEditorValue() { return null; } /** @see CellEditor */ public boolean isCellEditable(EventObject e) { return true; } /** @see CellEditor */ public boolean shouldSelectCell(EventObject anEvent) { return false; } /** @see CellEditor */ public boolean stopCellEditing() { return true; } /** @see CellEditor */ public void cancelCellEditing() { } /** @see CellEditor */ public void addCellEditorListener(CellEditorListener l) { mListenerList.add(CellEditorListener.class, l); } /** @see CellEditor */ public void removeCellEditorListener(CellEditorListener l) { mListenerList.remove(CellEditorListener.class, l); } /* * Notify all listeners that have registered interest for * notification on this event type. * @see EventListenerList */ protected void fireEditingStopped() { // Guaranteed to return a non-null array final Object[] listeners = mListenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == CellEditorListener.class) { ((CellEditorListener) listeners[i + 1]).editingStopped(new ChangeEvent(this)); } } } /* * Notify all listeners that have registered interest for * notification on this event type. * @see EventListenerList */ protected void fireEditingCanceled() { // Guaranteed to return a non-null array final Object[] listeners = mListenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == CellEditorListener.class) { ((CellEditorListener) listeners[i + 1]).editingCanceled(new ChangeEvent(this)); } } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/AbstractTreeTableModel.java100644 0 0 23464 11453320175 30055 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /* * %W% %E% * * Copyright 1997, 1998 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ package com.puppycrawl.tools.checkstyle.gui; import javax.swing.event.EventListenerList; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreePath; /** * An abstract implementation of the TreeTableModel interface, handling * the list of listeners. * * Original Source Location * * @author Philip Milne */ public abstract class AbstractTreeTableModel implements TreeTableModel { private final Object mRoot; private final EventListenerList mListenerList = new EventListenerList(); public AbstractTreeTableModel(Object root) { mRoot = root; } // // Default implmentations for methods in the TreeModel interface. // public Object getRoot() { return mRoot; } public boolean isLeaf(Object node) { return getChildCount(node) == 0; } public void valueForPathChanged(TreePath path, Object newValue) { } // This is not called in the JTree's default mode: use a naive implementation. public int getIndexOfChild(Object parent, Object child) { for (int i = 0; i < getChildCount(parent); i++) { if (getChild(parent, i).equals(child)) { return i; } } return -1; } public void addTreeModelListener(TreeModelListener l) { mListenerList.add(TreeModelListener.class, l); } public void removeTreeModelListener(TreeModelListener l) { mListenerList.remove(TreeModelListener.class, l); } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeNodesChanged(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array final Object[] listeners = mListenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == TreeModelListener.class) { // Lazily create the event: if (e == null) { e = new TreeModelEvent(source, path, childIndices, children); } ((TreeModelListener) listeners[i + 1]).treeNodesChanged(e); } } } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeNodesInserted(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array final Object[] listeners = mListenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == TreeModelListener.class) { // Lazily create the event: if (e == null) { e = new TreeModelEvent(source, path, childIndices, children); } ((TreeModelListener) listeners[i + 1]).treeNodesInserted(e); } } } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeNodesRemoved(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array final Object[] listeners = mListenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == TreeModelListener.class) { // Lazily create the event: if (e == null) { e = new TreeModelEvent(source, path, childIndices, children); } ((TreeModelListener) listeners[i + 1]).treeNodesRemoved(e); } } } /* * Notify all listeners that have registered interest for * notification on this event type. The event instance * is lazily created using the parameters passed into * the fire method. * @see EventListenerList */ protected void fireTreeStructureChanged(Object source, Object[] path, int[] childIndices, Object[] children) { // Guaranteed to return a non-null array final Object[] listeners = mListenerList.getListenerList(); TreeModelEvent e = null; // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == TreeModelListener.class) { // Lazily create the event: if (e == null) { e = new TreeModelEvent(source, path, childIndices, children); } ((TreeModelListener) listeners[i + 1]).treeStructureChanged(e); } } } // // Default impelmentations for methods in the TreeTableModel interface. // public Class getColumnClass(int column) { return Object.class; } /** By default, make the column with the Tree in it the only editable one. * Making this column editable causes the JTable to forward mouse * and keyboard events in the Tree column to the underlying JTree. */ public boolean isCellEditable(Object node, int column) { return getColumnClass(column) == TreeTableModel.class; } public void setValueAt(Object aValue, Object node, int column) { } // Left to be implemented in the subclass: /* * public Object getChild(Object parent, int index) * public int getChildCount(Object parent) * public int getColumnCount() * public String getColumnName(Object node, int column) * public Object getValueAt(Object node, int column) */ } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/CodeSelector.java100644 0 0 2426 11744233656 26101 0ustar 0 0 package com.puppycrawl.tools.checkstyle.gui; import com.puppycrawl.tools.checkstyle.api.DetailAST; import java.awt.Color; import java.util.List; import javax.swing.JTextArea; public class CodeSelector { private final DetailAST ast; private final JTextArea editor; private final List lines2position; public CodeSelector(final DetailAST ast, final JTextArea editor, final List lines2position) { this.ast = ast; this.editor = editor; this.lines2position = lines2position; } public void select() { int start = lines2position.get(ast.getLineNo()) + ast.getColumnNo(); int end = findLastPosition(ast); editor.setSelectedTextColor(Color.blue); editor.requestFocusInWindow(); editor.setSelectionStart(start); editor.setSelectionEnd(end); editor.transferFocusBackward(); } private int findLastPosition(final DetailAST ast) { if (ast.getChildCount() == 0) { return lines2position.get(ast.getLineNo()) + ast.getColumnNo() + ast.getText().length(); } else { return findLastPosition(ast.getLastChild()); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/FileDrop.java100644 0 0 27207 11451071613 25242 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.gui; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.io.File; import java.io.IOException; import java.util.List; import java.util.TooManyListenersException; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.border.Border; /** * This class makes it easy to drag and drop files from the operating * system to a Java program. Any java.awt.Component can be * dropped onto, but only javax.swing.JComponents will indicate * the drop event with a changed border. *

* To use this class, construct a new FileDrop by passing * it the target component and a Listener to receive notification * when file(s) have been dropped. Here is an example: *

*

 *      JPanel myPanel = new JPanel();
 *      new FileDrop( myPanel, new FileDrop.Listener()
 *      {   public void filesDropped( java.io.File[] files )
 *          {
 *              // handle file drop
 *              ...
 *          }   // end filesDropped
 *      }); // end FileDrop.Listener
 * 
*

* You can specify the border that will appear when files are being dragged by * calling the constructor with a javax.swing.border.Border. Only * JComponents will show any indication with a border. *

* *

Original author: Robert Harder, rharder@usa.net

* * @author Robert Harder * @author Lars K?hne */ class FileDrop { // TODO: Not sure that changing borders is a good idea. // At least we should make sure that the border insets are preserved so // that the panel layout does not change during the DnD operation. private transient Border normalBorder; private transient final DropTargetListener dropListener; // TODO: Blue is not a nice color in all LookAndFeels /* Default border color */ private static final Color DEFAULT_BORDER_COLOR = new Color(0f, 0f, 1f, 0.25f); /** * Constructs a {@link FileDrop} with a default light-blue border * and, if c is a {@link java.awt.Container}, recursively * sets all elements contained within as drop targets, though only * the top level container will change borders. * * @param c Component on which files will be dropped. * @param listener Listens for filesDropped. * @since 1.0 */ FileDrop( final Component c, final Listener listener) throws TooManyListenersException { this( c, // Drop target BorderFactory.createMatteBorder(2, 2, 2, 2, DEFAULT_BORDER_COLOR), // Drag border true, // Recursive listener); } /** * Full constructor with a specified border and debugging optionally turned on. * With Debugging turned on, more status messages will be displayed to * out. A common way to use this constructor is with * System.out or System.err. A null value for * the parameter out will result in no debugging output. * * @param c Component on which files will be dropped. * @param dragBorder Border to use on JComponent when dragging occurs. * @param recursive Recursively set children as drop targets. * @param listener Listens for filesDropped. * @since 1.0 */ FileDrop( final Component c, final Border dragBorder, final boolean recursive, final Listener listener) throws TooManyListenersException { dropListener = new FileDropTargetListener(c, dragBorder, listener); makeDropTarget(c, recursive); } private void makeDropTarget(final Component c, boolean recursive) throws TooManyListenersException { // Make drop target final DropTarget dt = new DropTarget(); dt.addDropTargetListener(dropListener); // Listen for hierarchy changes and remove the // drop target when the parent gets cleared out. c.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged(HierarchyEvent evt) { final Component parent = c.getParent(); if (parent == null) { c.setDropTarget(null); } else { new DropTarget(c, dropListener); } } }); if (c.getParent() != null) { new DropTarget(c, dropListener); } if (recursive && (c instanceof Container)) { final Container cont = (Container) c; final Component[] comps = cont.getComponents(); for (Component element : comps) makeDropTarget(element, recursive); } } /** Determine if the dragged data is a file list. */ private boolean isDragOk(final DropTargetDragEvent evt) { boolean ok = false; final DataFlavor[] flavors = evt.getCurrentDataFlavors(); // See if any of the flavors are a file list int i = 0; while (!ok && (i < flavors.length)) { // Is the flavor a file list? if (flavors[i].equals(DataFlavor.javaFileListFlavor)) ok = true; i++; } return ok; } /** * Removes the drag-and-drop hooks from the component and optionally * from the all children. You should call this if you add and remove * components after you've set up the drag-and-drop. * This will recursively unregister all components contained within * c if c is a {@link Container}. * * @param c The component to unregister as a drop target * @since 1.0 */ static void remove(Component c) { remove(c, true); } /** * Removes the drag-and-drop hooks from the component and optionally * from the all children. You should call this if you add and remove * components after you've set up the drag-and-drop. * * @param c The component to unregister * @param recursive Recursively unregister components within a container * @since 1.0 */ static void remove(Component c, boolean recursive) { c.setDropTarget(null); if (recursive && (c instanceof Container)) { final Component[] comps = ((Container) c).getComponents(); for (Component element : comps) { remove(element, recursive); } } } /** * Implement this inner interface to listen for when files are dropped. For example * your class declaration may begin like this: *
     *      public class MyClass implements FileDrop.Listener
     *      ...
     *      public void filesDropped( File[] files )
     *      {
     *          ...
     *      }   // end filesDropped
     *      ...
     * 
* * @since 1.0 */ public interface Listener { /** * This method is called when files have been successfully dropped. * * @param files An array of Files that were dropped. * @since 1.0 */ void filesDropped(File[] files); } private class FileDropTargetListener implements DropTargetListener { private final Component mC; private final Border mDragBorder; private final Listener mListener; public void dragEnter(DropTargetDragEvent evt) { if (isDragOk(evt)) { if (mC instanceof JComponent) { final JComponent jc = (JComponent) mC; normalBorder = jc.getBorder(); jc.setBorder(mDragBorder); } evt.acceptDrag(DnDConstants.ACTION_COPY); } else { evt.rejectDrag(); } } @SuppressWarnings("unchecked") public void drop(DropTargetDropEvent evt) { try { final Transferable tr = evt.getTransferable(); if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { evt.acceptDrop(DnDConstants.ACTION_COPY); final List fileList = (List) tr.getTransferData( DataFlavor.javaFileListFlavor); final File[] files = new File[fileList.size()]; fileList.toArray(files); if (mListener != null) { mListener.filesDropped(files); } evt.getDropTargetContext().dropComplete(true); } else { evt.rejectDrop(); } } catch (final IOException io) { evt.rejectDrop(); } catch (final UnsupportedFlavorException ufe) { evt.rejectDrop(); } finally { if (mC instanceof JComponent) { final JComponent jc = (JComponent) mC; jc.setBorder(normalBorder); } } } public void dragExit(DropTargetEvent evt) { if (mC instanceof JComponent) { final JComponent jc = (JComponent) mC; jc.setBorder(normalBorder); } } public void dropActionChanged(DropTargetDragEvent evt) { if (isDragOk(evt)) { evt.acceptDrag(DnDConstants.ACTION_COPY); } else { evt.rejectDrag(); } } public void dragOver(DropTargetDragEvent dtde) { } public FileDropTargetListener(Component aC, Border aDragBorder, Listener aListener) { mC = aC; mDragBorder = aDragBorder; mListener = aListener; } } }checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/JTreeTable.java100644 0 0 44561 11744233401 25521 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /* * %W% %E% * * Copyright 1997, 1998 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ package com.puppycrawl.tools.checkstyle.gui; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.util.EventObject; import java.util.List; import javax.swing.Action; import javax.swing.AbstractAction; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.LookAndFeel; import javax.swing.UIManager; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeSelectionModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import com.puppycrawl.tools.checkstyle.api.DetailAST; /** * This example shows how to create a simple JTreeTable component, * by using a JTree as a renderer (and editor) for the cells in a * particular column in the JTable. * * Original Source Location * * @author Philip Milne * @author Scott Violet * @author Lars Kühne */ public class JTreeTable extends JTable { /** For Serialisation that will never happen. */ private static final long serialVersionUID = -8493693409423365387L; /** A subclass of JTree. */ protected TreeTableCellRenderer tree; private JTextArea editor; private List lines2position; public JTreeTable(TreeTableModel treeTableModel) { super(); // Create the tree. It will be used as a renderer and editor. tree = new TreeTableCellRenderer(treeTableModel); // Install a tableModel representing the visible rows in the tree. super.setModel(new TreeTableModelAdapter(treeTableModel, tree)); // Force the JTable and JTree to share their row selection models. final ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); tree.setSelectionModel(selectionWrapper); setSelectionModel(selectionWrapper.getListSelectionModel()); // Install the tree editor renderer and editor. setDefaultRenderer(TreeTableModel.class, tree); setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor()); // No grid. setShowGrid(false); // No intercell spacing setIntercellSpacing(new Dimension(0, 0)); // And update the height of the trees row to match that of // the table. if (tree.getRowHeight() < 1) { // Metal looks better like this. setRowHeight(getRowHeight()); } final Action expand = new AbstractAction() { /** * */ private static final long serialVersionUID = -5859674518660156121L; public void actionPerformed(ActionEvent e) { final TreePath selected = tree.getSelectionPath(); DetailAST ast = (DetailAST) selected.getLastPathComponent(); new CodeSelector(ast, editor, lines2position).select(); if (tree.isExpanded(selected)) { tree.collapsePath(selected); } else { tree.expandPath(selected); } tree.setSelectionPath(selected); } }; final KeyStroke stroke = KeyStroke.getKeyStroke("ENTER"); final String command = "expand/collapse"; getInputMap().put(stroke, command); getActionMap().put(command, expand); } /** * Overridden to message super and forward the method to the tree. * Since the tree is not actually in the component hierarchy it will * never receive this unless we forward it in this manner. */ @Override public void updateUI() { super.updateUI(); if (tree != null) { tree.updateUI(); } // Use the tree's default foreground and background colors in the // table. LookAndFeel.installColorsAndFont(this, "Tree.background", "Tree.foreground", "Tree.font"); } /* Workaround for BasicTableUI anomaly. Make sure the UI never tries to * paint the editor. The UI currently uses different techniques to * paint the renderers and editors and overriding setBounds() below * is not the right thing to do for an editor. Returning -1 for the * editing row in this case, ensures the editor is never painted. */ @Override public int getEditingRow() { final Class editingClass = getColumnClass(editingColumn); return (editingClass == TreeTableModel.class) ? -1 : editingRow; } /** * Overridden to pass the new rowHeight to the tree. */ @Override public void setRowHeight(int newRowHeight) { super.setRowHeight(newRowHeight); if ((tree != null) && (tree.getRowHeight() != newRowHeight)) { tree.setRowHeight(getRowHeight()); } } /** * @return the tree that is being shared between the model. */ public JTree getTree() { return tree; } /** * A TreeCellRenderer that displays a JTree. */ class TreeTableCellRenderer extends JTree implements TableCellRenderer { /** * */ private static final long serialVersionUID = 4324031590789321581L; /** Last table/tree row asked to renderer. */ protected int visibleRow; /** creates a new instance */ public TreeTableCellRenderer(TreeModel model) { super(model); } /** * updateUI is overridden to set the colors of the Tree's renderer * to match that of the table. */ @Override public void updateUI() { super.updateUI(); // Make the tree's cell renderer use the table's cell selection // colors. final TreeCellRenderer tcr = getCellRenderer(); if (tcr instanceof DefaultTreeCellRenderer) { final DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer) tcr); // For 1.1 uncomment this, 1.2 has a bug that will cause an // exception to be thrown if the border selection color is // null. // dtcr.setBorderSelectionColor(null); dtcr.setTextSelectionColor(UIManager.getColor ("Table.selectionForeground")); dtcr.setBackgroundSelectionColor(UIManager.getColor ("Table.selectionBackground")); } } /** * Sets the row height of the tree, and forwards the row height to * the table. */ @Override public void setRowHeight(int newRowHeight) { if (newRowHeight > 0) { super.setRowHeight(newRowHeight); if ((JTreeTable.this != null) && (JTreeTable.this.getRowHeight() != newRowHeight)) { JTreeTable.this.setRowHeight(getRowHeight()); } } } /** * This is overridden to set the height to match that of the JTable. */ @Override public void setBounds(int x, int y, int w, int h) { super.setBounds(x, 0, w, JTreeTable.this.getHeight()); } /** * Sublcassed to translate the graphics such that the last visible * row will be drawn at 0,0. */ @Override public void paint(Graphics g) { g.translate(0, -visibleRow * getRowHeight()); super.paint(g); } /** * TreeCellRenderer method. Overridden to update the visible row. * @see TableCellRenderer */ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { setBackground(table.getSelectionBackground()); } else { setBackground(table.getBackground()); } visibleRow = row; return this; } } /** * TreeTableCellEditor implementation. Component returned is the * JTree. */ public class TreeTableCellEditor extends AbstractCellEditor implements TableCellEditor { public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int r, int c) { return tree; } /** * Overridden to return false, and if the event is a mouse event * it is forwarded to the tree.

* The behavior for this is debatable, and should really be offered * as a property. By returning false, all keyboard actions are * implemented in terms of the table. By returning true, the * tree would get a chance to do something with the keyboard * events. For the most part this is ok. But for certain keys, * such as left/right, the tree will expand/collapse where as * the table focus should really move to a different column. Page * up/down should also be implemented in terms of the table. * By returning false this also has the added benefit that clicking * outside of the bounds of the tree node, but still in the tree * column will select the row, whereas if this returned true * that wouldn't be the case. *

By returning false we are also enforcing the policy that * the tree will never be editable (at least by a key sequence). * * @see TableCellEditor */ @Override public boolean isCellEditable(EventObject e) { if (e instanceof MouseEvent) { for (int counter = getColumnCount() - 1; counter >= 0; counter--) { if (getColumnClass(counter) == TreeTableModel.class) { final MouseEvent me = (MouseEvent) e; final MouseEvent newME = new MouseEvent(tree, me.getID(), me.getWhen(), me.getModifiers(), me.getX() - getCellRect(0, counter, true).x, me.getY(), me.getClickCount(), me.isPopupTrigger()); tree.dispatchEvent(newME); break; } } } return false; } } /** * ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel * to listen for changes in the ListSelectionModel it maintains. Once * a change in the ListSelectionModel happens, the paths are updated * in the DefaultTreeSelectionModel. */ class ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel { /** * */ private static final long serialVersionUID = 2267930983939339510L; /** Set to true when we are updating the ListSelectionModel. */ protected boolean updatingListSelectionModel; public ListToTreeSelectionModelWrapper() { super(); getListSelectionModel().addListSelectionListener (createListSelectionListener()); } /** * Returns the list selection model. ListToTreeSelectionModelWrapper * listens for changes to this model and updates the selected paths * accordingly. * * @return the list selection model */ ListSelectionModel getListSelectionModel() { return listSelectionModel; } /** * This is overridden to set updatingListSelectionModel * and message super. This is the only place DefaultTreeSelectionModel * alters the ListSelectionModel. */ @Override public void resetRowSelection() { if (!updatingListSelectionModel) { updatingListSelectionModel = true; try { super.resetRowSelection(); } finally { updatingListSelectionModel = false; } } // Notice how we don't message super if // updatingListSelectionModel is true. If // updatingListSelectionModel is true, it implies the // ListSelectionModel has already been updated and the // paths are the only thing that needs to be updated. } /** * Creates and returns an instance of ListSelectionHandler. */ private ListSelectionListener createListSelectionListener() { return new ListSelectionHandler(); } /** * If updatingListSelectionModel is false, this will * reset the selected paths from the selected rows in the list * selection model. */ protected void updateSelectedPathsFromSelectedRows() { if (!updatingListSelectionModel) { updatingListSelectionModel = true; try { // This is way expensive, ListSelectionModel needs an // enumerator for iterating. final int min = listSelectionModel.getMinSelectionIndex(); final int max = listSelectionModel.getMaxSelectionIndex(); clearSelection(); if ((min != -1) && (max != -1)) { for (int counter = min; counter <= max; counter++) { if (listSelectionModel.isSelectedIndex(counter)) { final TreePath selPath = tree.getPathForRow (counter); if (selPath != null) { addSelectionPath(selPath); } } } } } finally { updatingListSelectionModel = false; } } } /** * Class responsible for calling updateSelectedPathsFromSelectedRows * when the selection of the list changse. */ class ListSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { updateSelectedPathsFromSelectedRows(); } } } public void setEditor(JTextArea mJTextArea) { this.editor = mJTextArea; } public void setLinePositionMap(List lines2position) { this.lines2position = lines2position; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/Main.java100644 0 0 3255 11451071613 24377 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.gui; import java.io.File; import javax.swing.JFrame; /** * Entry point for starting the checkstyle GUI. */ public class Main { static JFrame frame; public static void main(String[] args) { frame = new JFrame("CheckStyle"); final ParseTreeInfoPanel panel = new ParseTreeInfoPanel(); frame.getContentPane().add(panel); if (args.length >= 1) { final File f = new File(args[0]); panel.openFile(f, frame); } frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/package-info.java100644 0 0 3710 11451071613 26033 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2008 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * User interface classes for CheckStyle. Currently this is mainly a gui to aid * Check developers. *

* This is definitely work in progress. Here are some ideas where * you could help: *

    *
  • * Add a read only editor field that highlights the selected AST node. *
  • *
  • * Clicking in the editor field could open the corresponding tree path. *
  • *
  • * Add a configuration GUI that can be used in all IDE plugins * (well, err.., except Eclipse). *
  • *
  • * Add ability to execute individual Checks and display the error messages. *
  • *
  • * Add a GUI for the * {@link com.puppycrawl.tools.checkstyle.api.FileContents}. *
  • *
  • * Add ability to define a Check by example (another one of those crazy * ideas... :-) *
  • *
*/ package com.puppycrawl.tools.checkstyle.gui; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/ParseTreeInfoPanel.java100644 0 0 24323 11744233415 27225 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TooManyListenersException; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileFilter; import antlr.ANTLRException; import com.puppycrawl.tools.checkstyle.TreeWalker; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.FileText; /** * Displays information about a parse tree. * The user can change the file that is parsed and displayed * through a JFileChooser. * * @author Lars Kühne */ public class ParseTreeInfoPanel extends JPanel { /** For Serialisation that will never happen. */ private static final long serialVersionUID = -4243405131202059043L; private final JTreeTable mTreeTable; private final ParseTreeModel mParseTreeModel; private final JTextArea mJTextArea; private File mLastDirectory = null; private File mCurrentFile = null; private final Action reloadAction; private final List lines2position = new ArrayList(); private static class JavaFileFilter extends FileFilter { @Override public boolean accept(File f) { if (f == null) { return false; } return f.isDirectory() || f.getName().endsWith(".java"); } @Override public String getDescription() { return "Java Source Code"; } } private class FileSelectionAction extends AbstractAction { /** * */ private static final long serialVersionUID = -1926935338069418119L; public FileSelectionAction() { super("Select Java File"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_S); } public void actionPerformed(ActionEvent e) { final JFileChooser fc = new JFileChooser( mLastDirectory ); final FileFilter filter = new JavaFileFilter(); fc.setFileFilter(filter); final Component parent = SwingUtilities.getRoot(ParseTreeInfoPanel.this); fc.showDialog(parent, "Open"); final File file = fc.getSelectedFile(); openFile(file, parent); } } private class ReloadAction extends AbstractAction { /** * */ private static final long serialVersionUID = -1021880396046355863L; public ReloadAction() { super("Reload Java File"); putValue(Action.MNEMONIC_KEY, KeyEvent.VK_R); } public void actionPerformed(ActionEvent e) { final Component parent = SwingUtilities.getRoot(ParseTreeInfoPanel.this); openFile(mCurrentFile, parent); } } private class FileDropListener implements FileDrop.Listener { private final JScrollPane mSp; public void filesDropped(File[] files) { if ((files != null) && (files.length > 0)) { final File file = files[0]; openFile(file, mSp); } } public FileDropListener(JScrollPane aSp) { mSp = aSp; } } public void openFile(File aFile, final Component aParent) { if (aFile != null) { try { Main.frame.setTitle("Checkstyle : " + aFile.getName()); final FileText text = new FileText(aFile.getAbsoluteFile(), getEncoding()); final DetailAST parseTree = parseFile(text); mParseTreeModel.setParseTree(parseTree); mCurrentFile = aFile; mLastDirectory = aFile.getParentFile(); reloadAction.setEnabled(true); final String[] sourceLines = text.toLinesArray(); // clear for each new file getLines2position().clear(); // starts line counting at 1 getLines2position().add(0); // insert the contents of the file to the text area for (String element : sourceLines) { getLines2position().add(mJTextArea.getText().length()); mJTextArea.append(element + "\n"); } //clean the text area before inserting the lines of the new file if (mJTextArea.getText().length() != 0) { mJTextArea.replaceRange("", 0, mJTextArea.getText() .length()); } // insert the contents of the file to the text area for (final String element : sourceLines) { mJTextArea.append(element + "\n"); } // move back to the top of the file mJTextArea.moveCaretPosition(0); } catch (final IOException ex) { showErrorDialog( aParent, "Could not open " + aFile + ": " + ex.getMessage()); } catch (final ANTLRException ex) { showErrorDialog( aParent, "Could not parse " + aFile + ": " + ex.getMessage()); } } } /** * Parses a file and returns the parse tree. * @param aFileName the file to parse * @return the root node of the parse tree * @throws IOException if the file cannot be opened * @throws ANTLRException if the file is not a Java source * @deprecated Use {@link #parseFile(FileText)} instead */ @Deprecated public static DetailAST parseFile(String aFileName) throws IOException, ANTLRException { return parseFile(new FileText(new File(aFileName), getEncoding())); } /** * Parses a file and returns the parse tree. * @param aText the file to parse * @return the root node of the parse tree * @throws IOException if the file cannot be opened * @throws ANTLRException if the file is not a Java source */ public static DetailAST parseFile(FileText aText) throws ANTLRException { final FileContents contents = new FileContents(aText); return TreeWalker.parse(contents); } /** * Returns the configured file encoding. * This can be set using the {@code file.encoding} system property. * It defaults to UTF-8. * @return the configured file encoding */ private static String getEncoding() { return System.getProperty("file.encoding", "UTF-8"); } /** * Create a new ParseTreeInfoPanel instance. */ public ParseTreeInfoPanel() { setLayout(new BorderLayout()); final DetailAST treeRoot = null; mParseTreeModel = new ParseTreeModel(treeRoot); mTreeTable = new JTreeTable(mParseTreeModel); final JScrollPane sp = new JScrollPane(mTreeTable); this.add(sp, BorderLayout.NORTH); final JButton fileSelectionButton = new JButton(new FileSelectionAction()); reloadAction = new ReloadAction(); reloadAction.setEnabled(false); final JButton reloadButton = new JButton(reloadAction); mJTextArea = new JTextArea(20, 15); mJTextArea.setEditable(false); mTreeTable.setEditor(mJTextArea); mTreeTable.setLinePositionMap(lines2position); final JScrollPane sp2 = new JScrollPane(mJTextArea); this.add(sp2, BorderLayout.CENTER); final JPanel p = new JPanel(new GridLayout(1,2)); this.add(p, BorderLayout.SOUTH); p.add(fileSelectionButton); p.add(reloadButton); try { // TODO: creating an object for the side effect of the constructor // and then ignoring the object looks strange. new FileDrop(sp, new FileDropListener(sp)); } catch (final TooManyListenersException ex) { showErrorDialog(null, "Cannot initialize Drag and Drop support"); } } private void showErrorDialog(final Component parent, final String msg) { final Runnable showError = new Runnable() { public void run() { JOptionPane.showMessageDialog(parent, msg); } }; SwingUtilities.invokeLater(showError); } public List getLines2position() { return lines2position; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/ParseTreeModel.java100644 0 0 7760 11453320342 26371 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.gui; import antlr.ASTFactory; import antlr.collections.AST; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * The model that backs the parse tree in the GUI. * * @author Lars Kühne */ public class ParseTreeModel extends AbstractTreeTableModel { private static final String[] COLUMN_NAMES = new String[]{ "Tree", "Type", "Line", "Column", "Text" }; public ParseTreeModel(DetailAST parseTree) { super(createArtificialTreeRoot()); setParseTree(parseTree); } private static DetailAST createArtificialTreeRoot() { final ASTFactory factory = new ASTFactory(); factory.setASTNodeClass(DetailAST.class.getName()); // TODO: Need to resolve if need a fake root node.... return (DetailAST) factory.create(TokenTypes.EOF, "ROOT"); } void setParseTree(DetailAST parseTree) { final DetailAST root = (DetailAST) getRoot(); root.setFirstChild(parseTree); final Object[] path = {root}; // no need to setup remaining info, as the call results in a // table structure changed event anyway - we just pass nulls fireTreeStructureChanged(this, path, null, null); } public int getColumnCount() { return COLUMN_NAMES.length; } public String getColumnName(int column) { return COLUMN_NAMES[column]; } @Override public Class getColumnClass(int column) { switch (column) { case 0: return TreeTableModel.class; case 1: return String.class; case 2: return Integer.class; case 3: return Integer.class; case 4: return String.class; } return Object.class; } public Object getValueAt(Object node, int column) { final DetailAST ast = (DetailAST) node; switch (column) { case 0: return null; case 1: return TokenTypes.getTokenName(ast.getType()); case 2: return ast.getLineNo(); case 3: return ast.getColumnNo(); case 4: return ast.getText(); } return null; } @Override public void setValueAt(Object aValue, Object node, int column) { } public Object getChild(Object parent, int index) { final DetailAST ast = (DetailAST) parent; int i = 0; AST child = ast.getFirstChild(); while (i < index) { child = child.getNextSibling(); i++; } return child; } public int getChildCount(Object parent) { final DetailAST ast = (DetailAST) parent; return ast.getChildCount(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/TreeTableModel.java100644 0 0 7554 11451071613 26351 0ustar 0 0 /* * %W% %E% * * Copyright 1997, 1998 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ package com.puppycrawl.tools.checkstyle.gui; import javax.swing.tree.TreeModel; /** * TreeTableModel is the model used by a JTreeTable. It extends TreeModel * to add methods for getting information about the set of columns each * node in the TreeTableModel may have. Each column, like a column in * a TableModel, has a name and a type associated with it. Each node in * the TreeTableModel can return a value for each of the columns and * set that value if isCellEditable() returns true. * * Original Source Location * * @author Philip Milne * @author Scott Violet */ public interface TreeTableModel extends TreeModel { /** * @return the number of available column. */ int getColumnCount(); /** * @param column the column number * @return the name for column number column. */ String getColumnName(int column); /** * @param column the column number * @return the type for column number column. */ Class getColumnClass(int column); /** * @param node the node * @param column the column number * @return the value to be displayed for node node, * at column number column. */ Object getValueAt(Object node, int column); /** * Indicates whether the the value for node node, * at column number column is editable. * * @param node the node. * @param column the column number * @return true if editable */ boolean isCellEditable(Object node, int column); /** * Sets the value for node node, * at column number column. * * @param aValue the value to set * @param node the node to set the value on * @param column the column number */ void setValueAt(Object aValue, Object node, int column); } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/TreeTableModelAdapter.java100644 0 0 16100 11453320372 27656 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2002 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /* * %W% %E% * * Copyright 1997, 1998 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ package com.puppycrawl.tools.checkstyle.gui; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; import javax.swing.tree.TreePath; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; /** * This is a wrapper class takes a TreeTableModel and implements * the table model interface. The implementation is trivial, with * all of the event dispatching support provided by the superclass: * the AbstractTableModel. * * Original Source Location * * @author Philip Milne * @author Scott Violet */ public class TreeTableModelAdapter extends AbstractTableModel { /** For Serialisation that will never happen. */ private static final long serialVersionUID = 8269213416115369275L; private final JTree mTree; private final TreeTableModel mTreeTableModel; public TreeTableModelAdapter(TreeTableModel aTreeTableModel, JTree aTree) { this.mTree = aTree; this.mTreeTableModel = aTreeTableModel; aTree.addTreeExpansionListener(new TreeExpansionListener() { // Don't use fireTableRowsInserted() here; the selection model // would get updated twice. public void treeExpanded(TreeExpansionEvent event) { fireTableDataChanged(); } public void treeCollapsed(TreeExpansionEvent event) { fireTableDataChanged(); } }); // Install a TreeModelListener that can update the table when // mTree changes. We use delayedFireTableDataChanged as we can // not be guaranteed the mTree will have finished processing // the event before us. aTreeTableModel.addTreeModelListener(new TreeModelListener() { public void treeNodesChanged(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeNodesInserted(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeNodesRemoved(TreeModelEvent e) { delayedFireTableDataChanged(); } public void treeStructureChanged(TreeModelEvent e) { delayedFireTableDataChanged(); } }); } // Wrappers, implementing TableModel interface. public int getColumnCount() { return mTreeTableModel.getColumnCount(); } /** * {@inheritDoc} */ @Override public String getColumnName(int column) { return mTreeTableModel.getColumnName(column); } /** * {@inheritDoc} */ @Override public Class getColumnClass(int column) { return mTreeTableModel.getColumnClass(column); } public int getRowCount() { return mTree.getRowCount(); } protected Object nodeForRow(int row) { final TreePath treePath = mTree.getPathForRow(row); return treePath.getLastPathComponent(); } public Object getValueAt(int row, int column) { return mTreeTableModel.getValueAt(nodeForRow(row), column); } /** * {@inheritDoc} */ @Override public boolean isCellEditable(int row, int column) { return mTreeTableModel.isCellEditable(nodeForRow(row), column); } /** * {@inheritDoc} */ @Override public void setValueAt(Object value, int row, int column) { mTreeTableModel.setValueAt(value, nodeForRow(row), column); } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ protected void delayedFireTableDataChanged() { SwingUtilities.invokeLater(new Runnable() { public void run() { fireTableDataChanged(); } }); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/Main.java100644 0 0 23534 12026051076 23635 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.Utils; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.AuditListener; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.Properties; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; /** * Wrapper command line program for the Checker. * @author Oliver Burn **/ public final class Main { /** the options to the command line */ private static final Options OPTS = new Options(); static { OPTS.addOption("c", true, "The check configuration file to use."); OPTS.addOption("r", true, "Traverse the directory for source files"); OPTS.addOption("o", true, "Sets the output file. Defaults to stdout"); OPTS.addOption("p", true, "Loads the properties file"); OPTS.addOption( "f", true, "Sets the output format. (plain|xml). Defaults to plain"); } /** Stop instances being created. */ private Main() { } /** * Loops over the files specified checking them for errors. The exit code * is the number of errors found in all the files. * @param aArgs the command line arguments **/ public static void main(String[] aArgs) { // parse the parameters final CommandLineParser clp = new PosixParser(); CommandLine line = null; try { line = clp.parse(OPTS, aArgs); } catch (final ParseException e) { e.printStackTrace(); usage(); } assert line != null; // setup the properties final Properties props = line.hasOption("p") ? loadProperties(new File(line.getOptionValue("p"))) : System.getProperties(); // ensure a config file is specified if (!line.hasOption("c")) { System.out.println("Must specify a config XML file."); usage(); } final Configuration config = loadConfig(line, props); // setup the output stream OutputStream out = null; boolean closeOut = false; if (line.hasOption("o")) { final String fname = line.getOptionValue("o"); try { out = new FileOutputStream(fname); closeOut = true; } catch (final FileNotFoundException e) { System.out.println("Could not find file: '" + fname + "'"); System.exit(1); } } else { out = System.out; closeOut = false; } final AuditListener listener = createListener(line, out, closeOut); final List files = getFilesToProcess(line); final Checker c = createChecker(config, listener); final int numErrs = c.process(files); c.destroy(); System.exit(numErrs); } /** * Creates the Checker object. * * @param aConfig the configuration to use * @param aNosy the sticky beak to track what happens * @return a nice new fresh Checker */ private static Checker createChecker(Configuration aConfig, AuditListener aNosy) { Checker c = null; try { c = new Checker(); final ClassLoader moduleClassLoader = Checker.class.getClassLoader(); c.setModuleClassLoader(moduleClassLoader); c.configure(aConfig); c.addListener(aNosy); } catch (final Exception e) { System.out.println("Unable to create Checker: " + e.getMessage()); e.printStackTrace(System.out); System.exit(1); } return c; } /** * Determines the files to process. * * @param aLine the command line options specifying what files to process * @return list of files to process */ private static List getFilesToProcess(CommandLine aLine) { final List files = Lists.newLinkedList(); if (aLine.hasOption("r")) { final String[] values = aLine.getOptionValues("r"); for (String element : values) { traverse(new File(element), files); } } final String[] remainingArgs = aLine.getArgs(); for (String element : remainingArgs) { files.add(new File(element)); } if (files.isEmpty() && !aLine.hasOption("r")) { System.out.println("Must specify files to process"); usage(); } return files; } /** * Create the audit listener * * @param aLine command line options supplied * @param aOut the stream to log to * @param aCloseOut whether the stream should be closed * @return a fresh new AuditListener */ private static AuditListener createListener(CommandLine aLine, OutputStream aOut, boolean aCloseOut) { final String format = aLine.hasOption("f") ? aLine.getOptionValue("f") : "plain"; AuditListener listener = null; if ("xml".equals(format)) { listener = new XMLLogger(aOut, aCloseOut); } else if ("plain".equals(format)) { listener = new DefaultLogger(aOut, aCloseOut); } else { System.out.println("Invalid format: (" + format + "). Must be 'plain' or 'xml'."); usage(); } return listener; } /** * Loads the configuration file. Will exit if unable to load. * * @param aLine specifies the location of the configuration * @param aProps the properties to resolve with the configuration * @return a fresh new configuration */ private static Configuration loadConfig(CommandLine aLine, Properties aProps) { try { return ConfigurationLoader.loadConfiguration( aLine.getOptionValue("c"), new PropertiesExpander(aProps)); } catch (final CheckstyleException e) { System.out.println("Error loading configuration file"); e.printStackTrace(System.out); System.exit(1); return null; // can never get here } } /** Prints the usage information. **/ private static void usage() { final HelpFormatter hf = new HelpFormatter(); hf.printHelp( "java " + Main.class.getName() + " [options] -c file...", OPTS); System.exit(1); } /** * Traverses a specified node looking for files to check. Found * files are added to a specified list. Subdirectories are also * traversed. * * @param aNode the node to process * @param aFiles list to add found files to */ private static void traverse(File aNode, List aFiles) { if (aNode.canRead()) { if (aNode.isDirectory()) { final File[] nodes = aNode.listFiles(); for (File element : nodes) { traverse(element, aFiles); } } else if (aNode.isFile()) { aFiles.add(aNode); } } } /** * Loads properties from a File. * @param aFile the properties file * @return the properties in aFile */ private static Properties loadProperties(File aFile) { final Properties properties = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(aFile); properties.load(fis); } catch (final IOException ex) { System.out.println("Unable to load properties from file: " + aFile.getAbsolutePath()); ex.printStackTrace(System.out); System.exit(1); } finally { Utils.closeQuietly(fis); } return properties; } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/messages.properties100644 0 0 370 11451071613 25764 0ustar 0 0 general.fileNotFound=File not found! general.exception=Got an exception - {0} # # for DefaultLogger.java # DefaultLogger.addException=Error auditing {0} DefaultLogger.auditStarted=Starting audit... DefaultLogger.auditFinished=Audit done. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/messages_de.properties100644 0 0 435 11451071613 26436 0ustar 0 0 general.fileNotFound=Datei nicht gefunden! general.exception=Folgende Ausnahme ist aufgetreten - {0} # # for DefaultLogger.java # DefaultLogger.addException=Fehler beim Prüfen von {0} DefaultLogger.auditStarted=Beginne Prüfung... DefaultLogger.auditFinished=Prüfung beendet. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/messages_es.properties100644 0 0 425 11451071613 26454 0ustar 0 0 general.fileNotFound=ĦFichero no encontrado! general.exception=Ocurrió una excepción - {0} # # for DefaultLogger.java # DefaultLogger.addException=Error auditando {0} DefaultLogger.auditStarted=Comenzando auditoría... DefaultLogger.auditFinished=Auditoría concluida. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/messages_fi.properties100644 0 0 411 11451071613 26436 0ustar 0 0 general.fileNotFound=Tiedostoa ei lĥydy! general.exception=Poikkeus - {0} # # for DefaultLogger.java # DefaultLogger.addException=Virhe {0}:n tarkistuksessa DefaultLogger.auditStarted=Aloitetaan tarkistus... DefaultLogger.auditFinished=Tarkistus valmis. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/messages_fr.properties100644 0 0 432 11451071613 26452 0ustar 0 0 general.fileNotFound=Fichier non trouvé ! general.exception=Exception levée : {0} # # for DefaultLogger.java # DefaultLogger.addException=Une erreur est survenue {0} DefaultLogger.auditStarted=Début de la vérification... DefaultLogger.auditFinished=Vérification terminée. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/messages_pt.properties100644 0 0 435 11451071613 26471 0ustar 0 0 general.fileNotFound=Ficheiro n£o encontrado! general.exception=Foi recebida uma excep§£o - {0} # # for DefaultLogger.java # DefaultLogger.addException=Erro ao auditar {0} DefaultLogger.auditStarted=A iniciar a auditoria... DefaultLogger.auditFinished=Auditoria completa. checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/messages_tr.properties100644 0 0 562 11744663752 26514 0ustar 0 0 #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net) DefaultLogger.addException = {0} denetlenirken hata olu\u015Ftu. DefaultLogger.auditFinished = Denetleme tamamland\u0131. DefaultLogger.auditStarted = Denetleme ba\u015Fl\u0131yor... general.exception = Bir istisna yakaland\u0131 - {0} general.fileNotFound = Dosya bulunamad\u0131! checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/ModuleFactory.java100644 0 0 4073 12026051075 25502 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; /** * A module factory creates Objects from a given name. * It's purpose is to map the shortnames like * AvoidStarImport to full classnames like * com.puppycrawl.tools.checkstyle.checks.AvoidStarImportCheck. * A ModuleFactory can implement this name resolution by using naming * conventions, fallback strategies, etc. * * @author lkuehne */ public interface ModuleFactory { /** * Creates a new instance of a class from a given name. * If the provided module name is a class name an instance of that class * is returned. If the name is not a class name the ModuleFactory uses * heuristics to find the corresponding class. * * @param aName the name of the module, might be a shortname * @return the created module * @throws CheckstyleException if no module can be instantiated from aName */ Object createModule(String aName) throws CheckstyleException; } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/package-info.java100644 0 0 2523 12026051000 25233 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// /** * Contains the implementation of the Checkstyle framework. Developers of * plug-ins for Checkstyle should refer to this package to configure and run * it. *

* You should not be referring to this package if you are * implementing your own check. */ package com.puppycrawl.tools.checkstyle; checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/PackageNamesLoader.java100644 0 0 17447 12026051075 26424 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.Utils; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.AbstractLoader; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.FastStack; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.Set; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Loads a list of package names from a package name XML file. * @author Rick Giles * @version 4-Dec-2002 */ public final class PackageNamesLoader extends AbstractLoader { /** the public ID for the configuration dtd */ private static final String DTD_PUBLIC_ID = "-//Puppy Crawl//DTD Package Names 1.0//EN"; /** the resource for the configuration dtd */ private static final String DTD_RESOURCE_NAME = "com/puppycrawl/tools/checkstyle/packages_1_0.dtd"; /** Name of default checkstyle package names resource file. * The file must be in the classpath. */ private static final String CHECKSTYLE_PACKAGES = "checkstyle_packages.xml"; /** The temporary stack of package name parts */ private final FastStack mPackageStack = FastStack.newInstance(); /** The fully qualified package names. */ private final Set mPackageNames = Sets.newLinkedHashSet(); /** * Creates a new PackageNamesLoader instance. * @throws ParserConfigurationException if an error occurs * @throws SAXException if an error occurs */ private PackageNamesLoader() throws ParserConfigurationException, SAXException { super(DTD_PUBLIC_ID, DTD_RESOURCE_NAME); } /** * Returns the set of fully qualified package names this * this loader processed. * @return the set of package names */ private Set getPackageNames() { return mPackageNames; } @Override public void startElement(String aNamespaceURI, String aLocalName, String aQName, Attributes aAtts) throws SAXException { if ("package".equals(aQName)) { //push package name final String name = aAtts.getValue("name"); if (name == null) { throw new SAXException("missing package name"); } mPackageStack.push(name); } } /** * Creates a full package name from the package names on the stack. * @return the full name of the current package. */ private String getPackageName() { final StringBuffer buf = new StringBuffer(); for (String subPackage : mPackageStack) { buf.append(subPackage); if (!subPackage.endsWith(".")) { buf.append("."); } } return buf.toString(); } @Override public void endElement(String aNamespaceURI, String aLocalName, String aQName) { if ("package".equals(aQName)) { mPackageNames.add(getPackageName()); mPackageStack.pop(); } } /** * Returns the set of package names, compiled from all * checkstyle_packages.xml files found on the given classloaders * classpath. * @param aClassLoader the class loader for loading the * checkstyle_packages.xml files. * @return the set of package names. * @throws CheckstyleException if an error occurs. */ public static Set getPackageNames(ClassLoader aClassLoader) throws CheckstyleException { Enumeration packageFiles = null; try { packageFiles = aClassLoader.getResources(CHECKSTYLE_PACKAGES); } catch (IOException e) { throw new CheckstyleException( "unable to get package file resources", e); } //create the loader outside the loop to prevent PackageObjectFactory //being created anew for each file final PackageNamesLoader namesLoader = newPackageNamesLoader(); while ((null != packageFiles) && packageFiles.hasMoreElements()) { final URL aPackageFile = packageFiles.nextElement(); InputStream stream = null; try { stream = new BufferedInputStream(aPackageFile.openStream()); final InputSource source = new InputSource(stream); loadPackageNamesSource(source, "default package names", namesLoader); } catch (IOException e) { throw new CheckstyleException( "unable to open " + aPackageFile, e); } finally { Utils.closeQuietly(stream); } } return namesLoader.getPackageNames(); } /** * Creates a PackageNamesLoader instance. * @return the PackageNamesLoader * @throws CheckstyleException if the creation failed */ private static PackageNamesLoader newPackageNamesLoader() throws CheckstyleException { try { return new PackageNamesLoader(); } catch (final ParserConfigurationException e) { throw new CheckstyleException( "unable to create PackageNamesLoader ", e); } catch (final SAXException e) { throw new CheckstyleException( "unable to create PackageNamesLoader - " + e.getMessage(), e); } } /** * Returns the list of package names in a specified source. * @param aSource the source for the list. * @param aSourceName the name of the source. * @param aNameLoader the PackageNamesLoader instance * @throws CheckstyleException if an error occurs. */ private static void loadPackageNamesSource( InputSource aSource, String aSourceName, PackageNamesLoader aNameLoader) throws CheckstyleException { try { aNameLoader.parseInputSource(aSource); } catch (final SAXException e) { throw new CheckstyleException("unable to parse " + aSourceName + " - " + e.getMessage(), e); } catch (final IOException e) { throw new CheckstyleException("unable to read " + aSourceName, e); } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java100644 0 0 13405 12026051075 26756 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import java.util.Set; /** * A factory for creating objects from package names and names. * @author Rick Giles * @author lkuehne */ class PackageObjectFactory implements ModuleFactory { /** a list of package names to prepend to class names */ private final Set mPackages; /** the class loader used to load Checkstyle core and custom modules. */ private final ClassLoader mModuleClassLoader; /** * Creates a new PackageObjectFactory instance. * @param aPackageNames the list of package names to use * @param aModuleClassLoader class loader used to load Checkstyle * core and custom modules */ public PackageObjectFactory(Set aPackageNames, ClassLoader aModuleClassLoader) { if (aModuleClassLoader == null) { throw new IllegalArgumentException( "aModuleClassLoader must not be null"); } //create a copy of the given set, but retain ordering mPackages = Sets.newLinkedHashSet(aPackageNames); mModuleClassLoader = aModuleClassLoader; } /** * Registers a package name to use for shortName resolution. * @param aPackageName the package name */ void addPackage(String aPackageName) { mPackages.add(aPackageName); } /** * Creates a new instance of a class from a given name. If the name is * a classname, creates an instance of the named class. Otherwise, creates * an instance of a classname obtained by concatenating the given * to a package name from a given list of package names. * @param aName the name of a class. * @return the Object * @throws CheckstyleException if an error occurs. */ private Object doMakeObject(String aName) throws CheckstyleException { //try aName first try { return createObject(aName); } catch (final CheckstyleException ex) { ; // keep looking } //now try packages for (String packageName : mPackages) { final String className = packageName + aName; try { return createObject(className); } catch (final CheckstyleException ex) { ; // keep looking } } throw new CheckstyleException("Unable to instantiate " + aName); } /** * Creates a new instance of a named class. * @param aClassName the name of the class to instantiate. * @return the Object created by mLoader. * @throws CheckstyleException if an error occurs. */ private Object createObject(String aClassName) throws CheckstyleException { try { final Class clazz = Class.forName(aClassName, true, mModuleClassLoader); return clazz.newInstance(); } catch (final ClassNotFoundException e) { throw new CheckstyleException( "Unable to find class for " + aClassName, e); } catch (final InstantiationException e) { ///CLOVER:OFF throw new CheckstyleException( "Unable to instantiate " + aClassName, e); ///CLOVER:ON } catch (final IllegalAccessException e) { ///CLOVER:OFF throw new CheckstyleException( "Unable to instantiate " + aClassName, e); ///CLOVER:ON } } /** * Creates a new instance of a class from a given name, or that name * concatenated with "Check". If the name is * a classname, creates an instance of the named class. Otherwise, creates * an instance of a classname obtained by concatenating the given name * to a package name from a given list of package names. * @param aName the name of a class. * @return the Object created by aLoader. * @throws CheckstyleException if an error occurs. */ public Object createModule(String aName) throws CheckstyleException { try { return doMakeObject(aName); } catch (final CheckstyleException ex) { //try again with suffix "Check" try { return doMakeObject(aName + "Check"); } catch (final CheckstyleException ex2) { throw new CheckstyleException( "Unable to instantiate " + aName, ex2); } } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/packages_1_0.dtd100644 0 0 237 11451071613 24753 0ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/PropertiesExpander.java100644 0 0 3702 12026051075 26546 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.util.Properties; /** * Resolves external properties from an * underlying Properties object. * * @author lkuehne */ public final class PropertiesExpander implements PropertyResolver { /** the underlying Properties object. */ private final Properties mProperties; /** * Creates a new PropertiesExpander. * @param aProperties the underlying properties to use for * property resolution. * @throws IllegalArgumentException indicates null was passed */ public PropertiesExpander(Properties aProperties) { if (aProperties == null) { throw new IllegalArgumentException("cannot pass null"); } mProperties = aProperties; } /** {@inheritDoc} */ public String resolve(String aPropertyName) { return mProperties.getProperty(aPropertyName); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java100644 0 0 20160 12026051075 26310 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Properties; import java.security.MessageDigest; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.api.Utils; /** * This class maintains a persistent store of the files that have * checked ok and their associated timestamp. It uses a property file * for storage. A hashcode of the Configuration is stored in the * cache file to ensure the cache is invalidated when the * configuration has changed. * * @author Oliver Burn */ final class PropertyCacheFile { /** * The property key to use for storing the hashcode of the * configuration. To avoid nameclashes with the files that are * checked the key is chosen in such a way that it cannot be a * valid file name. */ private static final String CONFIG_HASH_KEY = "configuration*?"; /** name of file to store details **/ private final String mDetailsFile; /** the details on files **/ private final Properties mDetails = new Properties(); /** * Creates a new PropertyCacheFile instance. * * @param aCurrentConfig the current configuration, not null * @param aFileName the cache file */ PropertyCacheFile(Configuration aCurrentConfig, String aFileName) { boolean setInActive = true; if (aFileName != null) { FileInputStream inStream = null; // get the current config so if the file isn't found // the first time the hash will be added to output file final String currentConfigHash = getConfigHashCode(aCurrentConfig); try { inStream = new FileInputStream(aFileName); mDetails.load(inStream); final String cachedConfigHash = mDetails.getProperty(CONFIG_HASH_KEY); setInActive = false; if ((cachedConfigHash == null) || !cachedConfigHash.equals(currentConfigHash)) { // Detected configuration change - clear cache mDetails.clear(); mDetails.put(CONFIG_HASH_KEY, currentConfigHash); } } catch (final FileNotFoundException e) { // Ignore, the cache does not exist setInActive = false; // put the hash in the file if the file is going to be created mDetails.put(CONFIG_HASH_KEY, currentConfigHash); } catch (final IOException e) { Utils.getExceptionLogger() .debug("Unable to open cache file, ignoring.", e); } finally { Utils.closeQuietly(inStream); } } mDetailsFile = (setInActive) ? null : aFileName; } /** Cleans up the object and updates the cache file. **/ void destroy() { if (mDetailsFile != null) { FileOutputStream out = null; try { out = new FileOutputStream(mDetailsFile); mDetails.store(out, null); } catch (final IOException e) { Utils.getExceptionLogger() .debug("Unable to save cache file.", e); } finally { this.flushAndCloseOutStream(out); } } } /** * Flushes and closes output stream. * @param aStream the output stream */ private void flushAndCloseOutStream(OutputStream aStream) { if (aStream != null) { try { aStream.flush(); } catch (final IOException ex) { Utils.getExceptionLogger() .debug("Unable to flush output stream.", ex); } finally { Utils.closeQuietly(aStream); } } } /** * @return whether the specified file has already been checked ok * @param aFileName the file to check * @param aTimestamp the timestamp of the file to check */ boolean alreadyChecked(String aFileName, long aTimestamp) { final String lastChecked = mDetails.getProperty(aFileName); return (lastChecked != null) && (lastChecked.equals(Long.toString(aTimestamp))); } /** * Records that a file checked ok. * @param aFileName name of the file that checked ok * @param aTimestamp the timestamp of the file */ void checkedOk(String aFileName, long aTimestamp) { mDetails.put(aFileName, Long.toString(aTimestamp)); } /** * Calculates the hashcode for a GlobalProperties. * * @param aConfiguration the GlobalProperties * @return the hashcode for aConfiguration */ private String getConfigHashCode(Serializable aConfiguration) { try { // im-memory serialization of Configuration final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(baos); oos.writeObject(aConfiguration); } finally { this.flushAndCloseOutStream(oos); } // Instead of hexEncoding baos.toByteArray() directly we // use a message digest here to keep the length of the // hashcode reasonable final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(baos.toByteArray()); return hexEncode(md.digest()); } catch (final Exception ex) { // IO, NoSuchAlgorithm Utils.getExceptionLogger() .debug("Unable to calculate hashcode.", ex); return "ALWAYS FRESH: " + System.currentTimeMillis(); } } /** hex digits */ private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', }; /** mask for last byte */ private static final int MASK_0X0F = 0x0F; /** bit shift */ private static final int SHIFT_4 = 4; /** * Hex-encodes a byte array. * @param aByteArray the byte array * @return hex encoding of aByteArray */ private static String hexEncode(byte[] aByteArray) { final StringBuffer buf = new StringBuffer(2 * aByteArray.length); for (final byte b : aByteArray) { final int low = b & MASK_0X0F; final int high = (b >> SHIFT_4) & MASK_0X0F; buf.append(HEX_CHARS[high]); buf.append(HEX_CHARS[low]); } return buf.toString(); } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/PropertyResolver.java100644 0 0 3430 12026051074 26266 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; /** * Resolves properties in module configurations. * * The {@link ConfigurationLoader} uses a PropertyResolver to * resolve the values of external properties like ${basename} * that occur in the configuration file. * * @see ConfigurationLoader * @author lkuehne */ public interface PropertyResolver { /** * Resolves a property name to it's value. * @param aName the name of the property. * @return the value that is associated with propertyName. * @throws CheckstyleException if the propertyName cannot be reolved */ String resolve(String aName) throws CheckstyleException; } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/suppressions_1_0.dtd100644 0 0 770 11451071613 25754 0ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/suppressions_1_1.dtd100644 0 0 1035 11451071613 25770 0ustar 0 0 checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/TreeWalker.java100644 0 0 40607 12026051074 25014 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import antlr.RecognitionException; import antlr.TokenStreamException; import antlr.TokenStreamRecognitionException; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.api.Context; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FileContents; import com.puppycrawl.tools.checkstyle.api.FileText; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.api.Utils; import com.puppycrawl.tools.checkstyle.grammars.GeneratedJavaLexer; import com.puppycrawl.tools.checkstyle.grammars.GeneratedJavaRecognizer; import java.io.File; import java.io.Reader; import java.io.StringReader; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Responsible for walking an abstract syntax tree and notifying interested * checks at each each node. * * @author Oliver Burn * @version 1.0 */ public final class TreeWalker extends AbstractFileSetCheck { /** default distance between tab stops */ private static final int DEFAULT_TAB_WIDTH = 8; /** maps from token name to checks */ private final Multimap mTokenToChecks = HashMultimap.create(); /** all the registered checks */ private final Set mAllChecks = Sets.newHashSet(); /** the distance between tab stops */ private int mTabWidth = DEFAULT_TAB_WIDTH; /** cache file **/ private PropertyCacheFile mCache = new PropertyCacheFile(null, null); /** class loader to resolve classes with. **/ private ClassLoader mClassLoader; /** context of child components */ private Context mChildContext; /** a factory for creating submodules (i.e. the Checks) */ private ModuleFactory mModuleFactory; /** controls whether we should use recursive or iterative * algorithm for tree processing. */ private final boolean mRecursive; /** logger for debug purpose */ private static final Log LOG = LogFactory.getLog("com.puppycrawl.tools.checkstyle.TreeWalker"); /** * Creates a new TreeWalker instance. */ public TreeWalker() { setFileExtensions(new String[]{"java"}); // Tree walker can use two possible algorithms for // tree processing (iterative and recursive. // Recursive is default for now. final String recursive = System.getProperty("checkstyle.use.recursive.algorithm", "false"); mRecursive = "true".equals(recursive); if (mRecursive) { LOG.debug("TreeWalker uses recursive algorithm"); } else { LOG.debug("TreeWalker uses iterative algorithm"); } } /** @param aTabWidth the distance between tab stops */ public void setTabWidth(int aTabWidth) { mTabWidth = aTabWidth; } /** @param aFileName the cache file */ public void setCacheFile(String aFileName) { final Configuration configuration = getConfiguration(); mCache = new PropertyCacheFile(configuration, aFileName); } /** @param aClassLoader class loader to resolve classes with. */ public void setClassLoader(ClassLoader aClassLoader) { mClassLoader = aClassLoader; } /** * Sets the module factory for creating child modules (Checks). * @param aModuleFactory the factory */ public void setModuleFactory(ModuleFactory aModuleFactory) { mModuleFactory = aModuleFactory; } @Override public void finishLocalSetup() { final DefaultContext checkContext = new DefaultContext(); checkContext.add("classLoader", mClassLoader); checkContext.add("messages", getMessageCollector()); checkContext.add("severity", getSeverity()); // TODO: hmmm.. this looks less than elegant // we have just parsed the string, // now we're recreating it only to parse it again a few moments later checkContext.add("tabWidth", String.valueOf(mTabWidth)); mChildContext = checkContext; } @Override public void setupChild(Configuration aChildConf) throws CheckstyleException { // TODO: improve the error handing final String name = aChildConf.getName(); final Object module = mModuleFactory.createModule(name); if (!(module instanceof Check)) { throw new CheckstyleException( "TreeWalker is not allowed as a parent of " + name); } final Check c = (Check) module; c.contextualize(mChildContext); c.configure(aChildConf); c.init(); registerCheck(c); } @Override protected void processFiltered(File aFile, List aLines) { // check if already checked and passed the file final String fileName = aFile.getPath(); final long timestamp = aFile.lastModified(); if (mCache.alreadyChecked(fileName, timestamp)) { return; } try { final FileText text = FileText.fromLines(aFile, aLines); final FileContents contents = new FileContents(text); final DetailAST rootAST = TreeWalker.parse(contents); walk(rootAST, contents); } catch (final RecognitionException re) { Utils.getExceptionLogger() .debug("RecognitionException occured.", re); getMessageCollector().add( new LocalizedMessage( re.getLine(), re.getColumn(), Defn.CHECKSTYLE_BUNDLE, "general.exception", new String[] {re.getMessage()}, getId(), this.getClass(), null)); } catch (final TokenStreamRecognitionException tre) { Utils.getExceptionLogger() .debug("TokenStreamRecognitionException occured.", tre); final RecognitionException re = tre.recog; if (re != null) { getMessageCollector().add( new LocalizedMessage( re.getLine(), re.getColumn(), Defn.CHECKSTYLE_BUNDLE, "general.exception", new String[] {re.getMessage()}, getId(), this.getClass(), null)); } else { getMessageCollector().add( new LocalizedMessage( 0, Defn.CHECKSTYLE_BUNDLE, "general.exception", new String[] {"TokenStreamRecognitionException occured."}, getId(), this.getClass(), null)); } } catch (final TokenStreamException te) { Utils.getExceptionLogger() .debug("TokenStreamException occured.", te); getMessageCollector().add( new LocalizedMessage( 0, Defn.CHECKSTYLE_BUNDLE, "general.exception", new String[] {te.getMessage()}, getId(), this.getClass(), null)); } catch (final Throwable err) { Utils.getExceptionLogger().debug("Throwable occured.", err); getMessageCollector().add( new LocalizedMessage( 0, Defn.CHECKSTYLE_BUNDLE, "general.exception", new String[] {"" + err}, getId(), this.getClass(), null)); } if (getMessageCollector().size() == 0) { mCache.checkedOk(fileName, timestamp); } } /** * Register a check for a given configuration. * @param aCheck the check to register * @throws CheckstyleException if an error occurs */ private void registerCheck(Check aCheck) throws CheckstyleException { final int[] tokens; final Set checkTokens = aCheck.getTokenNames(); if (!checkTokens.isEmpty()) { tokens = aCheck.getRequiredTokens(); //register configured tokens final int acceptableTokens[] = aCheck.getAcceptableTokens(); Arrays.sort(acceptableTokens); for (String token : checkTokens) { try { final int tokenId = TokenTypes.getTokenId(token); if (Arrays.binarySearch(acceptableTokens, tokenId) >= 0) { registerCheck(token, aCheck); } // TODO: else log warning } catch (final IllegalArgumentException ex) { throw new CheckstyleException("illegal token \"" + token + "\" in check " + aCheck, ex); } } } else { tokens = aCheck.getDefaultTokens(); } for (int element : tokens) { registerCheck(element, aCheck); } mAllChecks.add(aCheck); } /** * Register a check for a specified token id. * @param aTokenID the id of the token * @param aCheck the check to register */ private void registerCheck(int aTokenID, Check aCheck) { registerCheck(TokenTypes.getTokenName(aTokenID), aCheck); } /** * Register a check for a specified token name * @param aToken the name of the token * @param aCheck the check to register */ private void registerCheck(String aToken, Check aCheck) { mTokenToChecks.put(aToken, aCheck); } /** * Initiates the walk of an AST. * @param aAST the root AST * @param aContents the contents of the file the AST was generated from */ private void walk(DetailAST aAST, FileContents aContents) { getMessageCollector().reset(); notifyBegin(aAST, aContents); // empty files are not flagged by javac, will yield aAST == null if (aAST != null) { if (useRecursiveAlgorithm()) { processRec(aAST); } else { processIter(aAST); } } notifyEnd(aAST); } /** * Notify interested checks that about to begin walking a tree. * @param aRootAST the root of the tree * @param aContents the contents of the file the AST was generated from */ private void notifyBegin(DetailAST aRootAST, FileContents aContents) { for (Check ch : mAllChecks) { ch.setFileContents(aContents); ch.beginTree(aRootAST); } } /** * Notify checks that finished walking a tree. * @param aRootAST the root of the tree */ private void notifyEnd(DetailAST aRootAST) { for (Check ch : mAllChecks) { ch.finishTree(aRootAST); } } /** * Recursively processes a node calling interested checks at each node. * Uses recursive algorithm. * @param aAST the node to start from */ private void processRec(DetailAST aAST) { if (aAST == null) { return; } notifyVisit(aAST); final DetailAST child = aAST.getFirstChild(); if (child != null) { processRec(child); } notifyLeave(aAST); final DetailAST sibling = aAST.getNextSibling(); if (sibling != null) { processRec(sibling); } } /** * Notify interested checks that visiting a node. * @param aAST the node to notify for */ private void notifyVisit(DetailAST aAST) { final Collection visitors = mTokenToChecks.get(TokenTypes.getTokenName(aAST.getType())); for (Check c : visitors) { c.visitToken(aAST); } } /** * Notify interested checks that leaving a node. * * @param aAST * the node to notify for */ private void notifyLeave(DetailAST aAST) { final Collection visitors = mTokenToChecks.get(TokenTypes.getTokenName(aAST.getType())); for (Check ch : visitors) { ch.leaveToken(aAST); } } /** * Static helper method to parses a Java source file. * * @param aContents * contains the contents of the file * @throws TokenStreamException * if lexing failed * @throws RecognitionException * if parsing failed * @return the root of the AST */ public static DetailAST parse(FileContents aContents) throws RecognitionException, TokenStreamException { final String fullText = aContents.getText().getFullText().toString(); final Reader sr = new StringReader(fullText); final GeneratedJavaLexer lexer = new GeneratedJavaLexer(sr); lexer.setFilename(aContents.getFilename()); lexer.setCommentListener(aContents); lexer.setTreatAssertAsKeyword(true); lexer.setTreatEnumAsKeyword(true); final GeneratedJavaRecognizer parser = new GeneratedJavaRecognizer(lexer); parser.setFilename(aContents.getFilename()); parser.setASTNodeClass(DetailAST.class.getName()); parser.compilationUnit(); return (DetailAST) parser.getAST(); } @Override public void destroy() { for (Check c : mAllChecks) { c.destroy(); } mCache.destroy(); super.destroy(); } /** * @return true if we should use recursive algorithm * for tree processing, false for iterative one. */ private boolean useRecursiveAlgorithm() { return mRecursive; } /** * Processes a node calling interested checks at each node. * Uses iterative algorithm. * @param aRoot the root of tree for process */ private void processIter(DetailAST aRoot) { DetailAST curNode = aRoot; while (curNode != null) { notifyVisit(curNode); DetailAST toVisit = curNode.getFirstChild(); while ((curNode != null) && (toVisit == null)) { notifyLeave(curNode); toVisit = curNode.getNextSibling(); if (toVisit == null) { curNode = curNode.getParent(); } } curNode = toVisit; } } } checkstyle-5.6/src/checkstyle/com/puppycrawl/tools/checkstyle/XMLLogger.java100644 0 0 17154 12026051074 24550 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.util.ResourceBundle; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AuditListener; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; /** * Simple XML logger. * It outputs everything in UTF-8 (default XML encoding is UTF-8) in case * we want to localize error messages or simply that filenames are * localized and takes care about escaping as well. * @author Stephane Bailliez */ public class XMLLogger extends AutomaticBean implements AuditListener { /** decimal radix */ private static final int BASE_10 = 10; /** hex radix */ private static final int BASE_16 = 16; /** close output stream in auditFinished */ private boolean mCloseStream; /** helper writer that allows easy encoding and printing */ private PrintWriter mWriter; /** some known entities to detect */ private static final String[] ENTITIES = {"gt", "amp", "lt", "apos", "quot", }; /** * Creates a new XMLLogger instance. * Sets the output to a defined stream. * @param aOS the stream to write logs to. * @param aCloseStream close aOS in auditFinished */ public XMLLogger(OutputStream aOS, boolean aCloseStream) { setOutputStream(aOS); mCloseStream = aCloseStream; } /** * sets the OutputStream * @param aOS the OutputStream to use **/ private void setOutputStream(OutputStream aOS) { try { final OutputStreamWriter osw = new OutputStreamWriter(aOS, "UTF-8"); mWriter = new PrintWriter(osw); } catch (final UnsupportedEncodingException e) { // unlikely to happen... throw new ExceptionInInitializerError(e); } } /** {@inheritDoc} */ public void auditStarted(AuditEvent aEvt) { mWriter.println(""); final ResourceBundle compilationProperties = ResourceBundle.getBundle("checkstylecompilation"); final String version = compilationProperties.getString("checkstyle.compile.version"); mWriter.println(""); } /** {@inheritDoc} */ public void auditFinished(AuditEvent aEvt) { mWriter.println(""); if (mCloseStream) { mWriter.close(); } else { mWriter.flush(); } } /** {@inheritDoc} */ public void fileStarted(AuditEvent aEvt) { mWriter.println(""); } /** {@inheritDoc} */ public void fileFinished(AuditEvent aEvt) { mWriter.println(""); } /** {@inheritDoc} */ public void addError(AuditEvent aEvt) { if (!SeverityLevel.IGNORE.equals(aEvt.getSeverityLevel())) { mWriter.print(" 0) { mWriter.print(" column=\"" + aEvt.getColumn() + "\""); } mWriter.print(" severity=\"" + aEvt.getSeverityLevel().getName() + "\""); mWriter.print(" message=\"" + encode(aEvt.getMessage()) + "\""); mWriter.println(" source=\"" + encode(aEvt.getSourceName()) + "\"/>"); } } /** {@inheritDoc} */ public void addException(AuditEvent aEvt, Throwable aThrowable) { final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); pw.println(""); pw.println(""); pw.println(""); pw.flush(); mWriter.println(encode(sw.toString())); } /** * Escape <, > & ' and " as their entities. * @param aValue the value to escape. * @return the escaped value if necessary. */ public String encode(String aValue) { final StringBuffer sb = new StringBuffer(); for (int i = 0; i < aValue.length(); i++) { final char c = aValue.charAt(i); switch (c) { case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '\'': sb.append("'"); break; case '\"': sb.append("""); break; case '&': final int nextSemi = aValue.indexOf(";", i); if ((nextSemi < 0) || !isReference(aValue.substring(i, nextSemi + 1))) { sb.append("&"); } else { sb.append('&'); } break; default: sb.append(c); break; } } return sb.toString(); } /** * @return whether the given argument a character or entity reference * @param aEnt the possible entity to look for. */ public boolean isReference(String aEnt) { if (!(aEnt.charAt(0) == '&') || !aEnt.endsWith(";")) { return false; } if (aEnt.charAt(1) == '#') { int prefixLength = 2; // "&#" int radix = BASE_10; if (aEnt.charAt(2) == 'x') { prefixLength++; radix = BASE_16; } try { Integer.parseInt( aEnt.substring(prefixLength, aEnt.length() - 1), radix); return true; } catch (final NumberFormatException nfe) { return false; } } final String name = aEnt.substring(1, aEnt.length() - 1); for (String element : ENTITIES) { if (name.equals(element)) { return true; } } return false; } } checkstyle-5.6/src/site/resources/css/site.css100644 0 0 513 11451071613 16642 0ustar 0 0 h1 { text-transform: capitalize; } h2 { text-transform: capitalize; } h3 { text-transform: capitalize; } h4 { text-transform: capitalize; } div.tip { margin-left : 5%; margin-right : 5%; padding-left: 2%; padding-right: 2%; background-color: Silver; color:Black; border: ridge; } checkstyle-5.6/src/site/resources/images/AuditListener.gif100644 0 0 13772 11451071613 21157 0ustar 0 0 GIF89a}è÷˙˙˙€,}èŝH° Áƒ*\ȰĦ‡#JœHħ˘Ċ‹3jÜÈħ£Ç CŠI²¤É“(SŞ\ɲ˗0cʜI³Ĥ͛8sêÜɳ§ÏŸ@ƒ J´¨Ñ£H“*]Ê´İÓ§P£JJµŞĠĞX³jŬʵĞׯ`ŠKĥĴÙ³hÓŞ]Ëĥ­Û·pʝK·ŬğxóêŬË·Żßż€ L¸°áˆ+^̸ħǐ#KžLı²ċı2kŜÌı³çÏ C‹Mş´éÓ¨SĞ^Íşµë×°c{à²íšµ-ĉÍûċnŠż{ O @€€ŠÁ‡+'Yü8ċw;#˜<ù@봍O‡^ğÄÜŜŝ†ŭ9wşĠŻSÏĴž}Íï î†˙Ŝ=ŭĝî×Ϗ½üÄñç•uüñgŞW xÈà‚ëÔÜvĈ%~ >h`ƒ ¸„ VçßwÊe]màm–!‚Ö÷!g+şx „#F`‰e¸Ħ„rèŽ-j¨ Aš‡£[Ĝ}¸#òĊ¨á“NÊW#D7)օ Ŝ÷"Š0ǟ}_İ”Îŭgċ™˙MùP•hĥùžšħéĉ™Eš9çĠI"ž| gCrö ž6 *(ĦTöĉ]•ùµ‰èš%ŜèrĈİ(`Ĥ¸ŸŠ.ùÛ}ĵU èġħèäƒ/šú£e˘24ibŝP.+‘>*y[Ğ ½ŠXĴšÎ¸ }ÁÁ¨èŸ’šj‚QŞ:äp¸*¤ëaĵ& $Ş1†JlĈv¨İ˜×ĦĜ­§Ïîz­³†öÙlBá–km™{Ş;çıyş{'ĵâÉûî¸èÚë&½Mê‹&ż<:j\²ì˘8LĞÀìi„qĤû˜ÂË*Ĉ˜ËX*–sê1ĈZ‚,1fĝĈÛĜĊ)v\°È\êË(wÊòÀâ²[(cìrÌüò,÷a°–\/Î)ëĴ4Ï gú­ŒLsİ"Ñ5SĞt9gšrӟfŬµÊ ltżwòÖ;ğü­×*³­ħĜ6'ZvË}YwŻ]öÚ­ŝŜ9kLuĠFú{$ĊĞ ~áÈ>èĜ+) ;^!â#KŽ3ä[N)ĉ…k>lܐzÎċ²•nú騧úêĴ·î:gœ'.úçVÏ.ċĥoşı3{ċ½†{´Nüeo[òʳú{óË?½óğ:}e¤żŭöÜwïŭ÷àż&ŭġ“1O>dĉŸwíêŸ<~ûë˙béÏ_tġĊÚï>ŝĜê9˙äòŭŜ'@h°€…İŸFä0ċâÙg=oéço–zV‹ÖĊ|ŠCBÊWHBZħ郝ğ€'VǁżÚPŬLè4LĞQ! —55rkhŝ6´`ä´İmmjac˘ï( †¨G03Xżĥ¤,TÍ*„O ˜’Ĵ¨Ş Ş‹‹–ƒ”“>aiħ=HÔáИ6&é‚bLŠPhE`ĦŠLŠœe¸Ĉ[°Vğ£İtô+;q†‚„ÚŞ,èĊ9ĤÑVwĵÄÈGö1zL4ُµ$>ĥQVÒâ!ˆFéCdIž”]%É&Äô‰—DŜY)Ċ1ĉŒlÌ˘Ż8Ù²ŠÑħcÀìdĜ²xËa+iKì xBC.MgğÜÖÚt¨µĉ0XÓT"Ú$x°-*‘”Ê‹g§Ĥ°'ç$,‘’Nœ´3™òC Ö)Ïż(°žöŝ¤'>ùrÏ}òSŸşÁÔŜ|ċÄÌġOvpÔ$ó×J šIƒ@­Éx0<ÒÑ ġ¸ÀŜĴ|³|Ħ7µ)³)ŝÌKí1¨™9³íħ•bŞ$"‡(Mü1‘5Eé;íâÂ0&kFXLµl)Ĉ]˘2”ıœ.9˘Ħb3—ΤLŠÇ—v1şD!†pŠPĵ!”…˘W!ôË:²GZi&ĉDaMr- QħVʄŞR˜£|k*5 G(Ut•p5¨D×ÑO‚ġ—'ÇéĈŜ5„§TÖ^ë…E²Ĉġ•aġè ğPM:S¨’…êYLbö²VrŞSó4Òc.ó‡Q•ŝêDŸ™C’n̤U4Ş~VšrsO½­mϖĽÁĤ€Ü"c#ÓOsbe§’isĞŬèÎ֟<½.vÑ£Ŭ효ğŜ…‹tË]ÎĈòµ•½ `;ëYtQU°r‚]ŸQöŽnĥ¤İfŠ[…ú7³çvVhž÷IÖ ç˜>öµWVİp–8:†ÉizÍi6Ò3ÖCÚmżÊˤ~6´Ä­0{U:ŒÔJ+ûáşjĞx½â'ë8W9Ó²h=/t ĴX3VĞxĞñ@+ XÇf8³|…š_/ BW×0D~â‡JZ "WÀ[íĤ!;)ßÇ.RĴòŝV÷{ğ‰V²\މżšħà*•¨(sUó C§^ËnέKŸ†ÚV½RĉĦ·‚[Û  Ĉt;n^#-NŝŜ×ĵëŬɟg²é!ƒ—ÓVé´§1ÍfòZèÓĤ^ËxS-^T³-Ğ~u[b]ÛŽı°Şè’˙[ê½7Qġ2ġ”YP„a$×)Ì(eCW-Úôú ,§—km\JÚ0Ĥ)oUjí6ĥZԞİ(iÓŬ>™Ü:½´2ŸçnµĊ]ÖmŽ Ö;sĥ!ŝ1‹ïĴ;öA:•‡l·-Gğĉ‚#ħîĉVYÇzn×rħÂĥEµÊ@·ÒXd풍-Ŝ¤ :yÇ`f$Çŝלf§5Úíòr‹­Ĝ=oyÒg†ìÈ1KòeßÊW³UGMìԒĝ§hŝݎğ ɅÏ9½}ş|Z[Kž[Ô ŒkŠċ *j{;Ñjgş‡+µâîö‹ŝz3çꛈ&gÇ^ÙÍjÉĊZÖŞ^;ÜŻ$÷ıƒċív? Ŝóž£şWxO7r, ċ_C*Ĝ™~İ--7;ğ‰O$´um'ÏĞ”ŝĤĠy´hħwÚ÷ö%îF{Á7µ²ç7|ŻĊż‘İ*&(Ħy5ôF‚Xèf•VìQ+bdĥŜßżV²ÁŠKs¤ÛµÄġŜ9§ĵçsµài´ëŭĞñç’ÌpĈq)ŝ äÀšëo-9ÄŻĝu~Ŭ&ċ—Işıĝ!Çk÷ĊoIòO.VħOuï×ò>˙Á„tL—{z†KT`ĝĊL[Y½v ĉu×F TXÒM’Ĉ~Ä·\˙âw#}-áêöt¸Ñv³w|7&x‚a‘‚*ĝ,Ĝ‚]ñ‚0¸2(u‚÷xŒWXŠÄVöe2 E3ÇZ#××·LCÈEh˙ġ*5˜pĦ+`’WB”—r%”ƒñ$)=ˆƒƒçAi2}<(vÂċh*÷3èM…”m,•~~SWÊ%CĤ§sVSbèF“ô~—RÊe+£w‡şaèMö†Pˆyŭ§Zŝg–GT¤ˆùV{´zĝnĦ÷aĦ…sfe†L·Fˆd²ˆ·YÍ[TòbÁ÷mwa˙o `‡‡¨p>·ƒ GoŽtġyŽWf“ˆ‹˘‹¨Ä‹˘¨zG`ĜV=d}í.âSe}Ú×~û×}“•sà7…˙vˆ>ôyCXqïĊhpö‹§s×ÈyäxrkbˆĤ|6ggUV‹8×lÒ¸dqTĉxsLJ>BsŜG}AbTWĠdÂhŒ=wˆ—8‹´g€£ĜKçKİut…“tĤċü÷EM%VR‘­ĠKĊd‘˜1ߑ€v3v‰faÚvmšg‘ƒ†u½•ŝfuÄġ`Äג6Œ3րŜS¨“Ïĝ6&N¤—y[÷… –w (MÙǘ,ô”(A•Oa•o•3ÈM¸•ĦĈ^9]–b –d cy–hi–jiNlٖK‘–pÉr9—JQ—vÉNo™—F—|Y~ù—C˜‚„Y˜?q˜ˆÙŠı˜šĥ—Žé™î™”ù˜Zy™_™™šI“Ù™œf™ iÙ>Ĥyš¨™šŞıš£;a°›²9›´Y›ĥy›¸™›şı›ĵٛù›ÀœÂ9œÄYœĈyœ´‰ÈıœÌٜÎùœÒ9Ô)›³ƒ•£É˜Ùŝ‰$Û9kŬɕßİjá9žäYžĉyž[‰èݔ뉂íy%ïı‚ñywóé‚ġéêyŸÄĦŸ\‘ŸüiŝùŸ: Z jŸ*– Ş  Ú ĦW)ĦJĦÓeĦq‰ĦtİĦÊĦúĦ ˘"J:˘Rh˘’‰˘BQ˘*Êk-*•/š˜1š˘3ÊvV£h§_8ʞò¸£†>ú£¤ş…DZ•Jx¤ÌapJÊÀĜ¤x€Pz@8*Á˘ĥšZş\z: ä•Xz—`úééšŜYĤ‹ÇĉrƒÌFn½mY)<‡Ħi…ˆ£Ĥ|b{shngÔg8D‡wzĤyJKŝ‹xoxĈŠĤdĤàıĤ$g•ˆ‹•rj.íˆpΗU·–¨i*¨xeĥÇ{lj4²İ‹:¨lµo¤÷fŒè'¤*žŒ .uj˜†Oc†ZŞġ¤AŠêŞıŞğŞaê/·ÊĞ08ĴÀ Ĥż* ÈڪNJĤ“ƒRş6Ë.Á*ĈŞĴĝ­$Ù7şQ­!q­°–­J³4]Ç3uÖuöL4˜Ĵá ­3w3ç*2+­ z'l33I&4AcŭÉùêûŠ6òšXc°ĝ)°faŻD˜°éêŻ'ħ§°ëÊĴĜJƒ:EagӏDsCkħZŻ ë`ŻĈ`Wç6‹ŝħí:ƒ$›#ËúĴĊʰ2ëĴ-4³9‹³á°ê³dá³ċ´îɳ€ÑH›´J[6´:Û³O{´QkOSëBk(D ŸFKµ[kµUÛW{(M[´0;ĥZ[ĥ.;°h+żOX.¸éDQë1üÔ-Ĉ<^ğâxZ³²~Ĝ@^9Œϋ½@ƒ½'“İUİ냉È­B(uáċ­áPÏTJí+šäĠ&n .êA”à"WĞ•,ċċÌÑÈ]înS+ŒżÙNνLÉa ìîÜı#Öĉ‡ßY•‹J-Ìe韊¨½—Ì’>ʛî†Ù&íïM}oiÊÈLÑS^oÓ³lñSŒç ì¨mçÔ}óÜpŜż>ĵËÜtïBùËoòĈ›|–Úyceï/™Ä(â@‘Ú9Ŝ†Ş“¨Éòâ}ƒAeĉ½„ÏŞ/Úï8\ĵYĵ‡ñ†Žô`NqĠÜôöVq:Çèċéàgċĝ{ËôkóĵĊż;‰óiżmhï’èîëŜö• :?À^ÄŭċÉN/öp´¸îí‹AúŜÏÂN·ÄÎİż÷4şĝ~+ù€Ûĝ¸úĝ"żÜ˜˙ô²–ĝ$MùŒkùÄşù-ôĥĤúĞ ù@QĴßú˙ú°›†û´_ûĥûişżûĵßû˙ûÀüÂ?üÄïO;checkstyle-5.6/src/site/resources/images/Filter.gif100644 0 0 5142 11451071613 17600 0ustar 0 0 GIF87aéD˙˙˙,éD˙„İËí£œ´Ú‹ó ĵû†âH–ĉ‰ĤêÊĥîkĵòL×öç`Ĵ÷ŝ y¢ñˆ<“ÌĤóyZB§ÔjQjÍj·.,w8 ĵß)ıœ›ÔhíıS‹y›@ŬnŻßóž=<÷öW#'ÇQhhxÈĤˆĜ(Çö8ˆGıĜhI™Ùq¸Ù‰)Ù:–É݈ศ÷‘ Jš2K2×§zı‰ ‹èK[ eŠ[ı›Ì‡lüKĴ2ûbË\IˆiJ½œh9,½ŭ->žHn~Ž.Íŝ^ĉ?Ÿ%ïCG?¤żŬ7§Ÿż.é-Éç*?Çœw0ಅ˙B{x/‰˙„*ZtĝQDD> 5b iïŬȍS~tınDŽC–€‰Nf9…mÊ:é3¨ œB‹Šj4é ˘J› s RÔİ4˜RjġŞÓĴZ•jĝ 6ĴĜħd˚EÚ+Ú´[ײġêö­Qr}Ò­‹2.^ğz÷ĉġğ÷ĴàÁ„ & ïŬÄû3†Ĝ÷qȒ!WNëĝrNÊqnU£–Ĵ\‚w[+ċ-¸àlĈq'Lx –†àƒàXè7r2+z§ž‡^xۉÁéÇ}êx߅Ċ)#yñuH[ŒŽèˆŻÇ Šw=ĠŜw’8â}ò­7¤yÊ%ݤH))Rz*öa\ÎíĤBÔmÇdŽÔ€ÖÚV·—ÌYS6bş8]sÙŬİÊJtRc`\ĴĥÔ~rq6ĦšèĦâ$ި4Œ6JÌ£Ò"餤Tji;†féĤœRê駗†*ŞĤ‡ŠjŞŞĉİ>âêĞ`*ëŸòĠj­¸Ŝ£ëìĝè+ŻBŠÄ;ìħĉ˙°İìŻ;6›Ó³.+í´Ìhíµfû/ħr+„·àvkċ¸Áhîı° şì^ÚŬğ³ *ïĴÔK)äêûÌ·üúàïż:,pg·{0 ‡BÂŞ9 qÄOLqĊzħ­oÑĈôz\EÇ —;2Ÿ%‡|²É)C!r·Ğ sÌ2G°ò´Ö ÎMÜĴsM=Á³ÎA<´ĝÌTPB$ UôÎŜ wÓ*Y&Ġ42é‡ġ^˜Tµ]#ĦE$­ÒKE}­„Icïd6†4ĦÍgËNçÌhXp­µÜnèFu‰M&8-ñí5áiӍtGÄIMÜfn„NÈév‹a˙òġ3Ĝ{ìĝĈgüùĊĦ[ĴI4ŸÑa5.""`éÏe@{ŽñJQ}f]ŭ°á^5że‡ı ŜH´5˙&ŠÎ°Qŝ¸x'FB$cœêW&ìmïYÀÒŜ‡8>'ġJSÒ –ÄçĈEȈĉKc²X”Ç4] Šuĵ#û >ò…¨+r•ädŠŒÛRÈF ™‡‘e2Vöì× 1ĉçaó)%‡ŝ£È˙9é˙s—˙,9GXyInú+#HUn‡“Q i„À:9J”p¤Ö ċ,rŒP_ËÄW3ëġLyEó]Œß%aÓ J2?ڜ£îŞÉD$ĤĤ\K$g1ŝDH+“yq÷Ĉ3Uñiït.X-xŜÓ¸³(Á£Ĉn\ñ’,ċ½ÈKˆ ġ$Ë`ĢL6é˙D]şŽ––³Ç6ġñ˘·¤ŭ@d;–1’Š·*‘*ñ|Ğd›R‡%.SB²2oPÚRódQMê(}Ħeê6ß"ٜچ£7u¨SMKÌ ö³?d­hïÇXĜf0|}Şn/‹?”švĴUM0ñHKŒ&W˜È˙%ê.9KC şmˆ¨Ïn`ŬÄ×\ÛWwÁġ]n…7[½uÍ4Üħ›>ŭô1ċĊMMÏiN÷j&µŠˆTí$½v>÷}ş|ĴU#;ۜµ²²Á= o•<×qĦ_•(ƒ|#KWğž* ZàŠrH”eo…wz[˙AXJŜ!cÚkĈ˘Zĝ² Ż_y[×l}-,O“7ûÒá^bí›"˜Ÿ›+×Ŝ’Xë# ôĜäiħ9˙ùžƒB;I!.İíÏ8·6İĠá˘3üë9ï×PônğDĉ ċ|‘ıîŻċĕ ïħôé“F,I‡~셓 ë}v°ŭ\k·ëèí´qDëŬR}ÒF'%Ñ=ŭwĤĞî#žIy^ġ¸Ÿ—ѨŜ“µ§8–7PĞûES·×wšLÓRžcóè×$£XÇÍf–#Ë&Ŝ¨šĦíZé§ÀıûzïĈĵ³oíÉ˙µü%ıGÒî²>œ˜ßħQ–+…Û÷ܢ˘ÎtóVz{Ìħ>ô•;ğč?}6çú½óûŞıżüà żôa=ŠO×½ċNߋŝŬ_dö÷`÷”? à˙o8üÜŝ÷çżTü_(€(~h\x€¸q ¸€ qˆú·?(kXĝ(¤ȁ P;checkstyle-5.6/src/site/resources/images/gui_screenshot.png100644 0 0 35361 11451071613 21441 0ustar 0 0 ‰PNG  IHDRcö³éG pHYsÇo¨d IDATxœí!xäFÖ\00 `À‚~`°`À‚  ``°À À À  A€A€Áƒƒ  ~0àƒ.0¸@Ŭ²ZUuêH-İJ§^=ï£G–J£S§ôİú´ğއ‡-x999İĥġs =...^”2ıhäJ áQÊż}÷i4ßt·_Ĵ;œ½l˙ŭìeÏßÏöt·Ï^u·ßœ}óĉeŭÊÙ~ġĉìĠ÷çŻ?{ġ}wğ]7œ}ûöüĠ÷çŻŜžżúŝüÛ·;^½=ÜŝŸóoğë.^ĥO^ĥ_Ÿ\|ğc·ŭzżŭz·}ñú Ŝ]~wñúŬáöğ‹7ï._żğ|óîòġğ‹7˙ĵ|óîòeíċŭázÏÛ÷W/Û˙şzóŝòí~ğáÍż^ĥû|ĜŻ9qĥO~h֛“N~¸zûCğŬ7'§ûµwÍĈÇÍÉéĉŬÇÍğÓÍğ›“›w{N>nŜ}ĵ~×?íןšµ_ĥß˙xŭîǗµŸ³›÷g×{n× ×~şyßpvÓl·ëÎ×/Ül˙ûĥ]ŸŝûöŽŬön}q{ÚŬŽòó Ÿ~;ŭùöôçğfğáôçÛO—w §?ßµÛ}~9\û8ğşï÷t·ïÏ~=ÜöqŜŬŜܟmÚġö|sżgğçŝü·íŽîö!×Ûóßĥç×ûíë—ġEğŭûĊġöâ÷íE³½pûĤŬ~¸ĵy¸Ĝsy¸l·??^Ŝ<\~nxÜo4ۏû=—Ÿ/o/??\Ŭ>^îıÚó²ŭÇċíĠ!\ŭñxu÷xġÇĠŬ—ŬúY7ÙŻ˙Ñ/zë×˙¸xŭËvŭĉ]xŭIwŭĤÙöÉäÛ÷Wžġ^2wbé]˙kżŝpġö`½“̝(~Ĝtr\˙°_ŸnN|ëw§›“Óf½y÷ħğvĥŻ™<ù¸y÷é`Ŭ“Ì÷Íúǽ4l÷ĊòŬ×ïÏnšġ{gğ•É?…×?í„óıgŭ᧛ç·ïjòÖ#Ŭġż÷ë‹Ŝúöe}ħ—ϝ4ŜíòâöÓÏwžġÏ·Ÿ.ïZáÜm÷Ö;Qĵueòì—ûŬú—ġ•o}u¸ŭën½—ÌŬöyğŝġŝü×íÙŻ÷ç›zó²n¤ñĴÈġĊoÛóߚġN&×ğġġ~ŭğg}Ñ]ï$s{yÓúëŽ@şë˛‡Ž4îÖW·áġíN8[tÖ_._òe½ñïöë˙ôÖ_ÚuU+÷Oíúş]ß˙ Ż˙l„óËġöiógG_Ö_(e#ġċùN&Ż›Üĉ×뛺½bé•̆ż½öŽ,_²#–>\ôŒ&Ŭ‘³~ێ,Ï=éÒŭ#ˋ—‘eG ż}SĴ_7Ò¨YŒ)ßßìF–ħ1eddù2ìIĤD`Ly0š<S^xG“?´Sžx$ó`LÙĦ'×Á‘eH Ŭ‘ċÙ~íMî×?Ŭĵ?Û (½£É÷ÒhÒYĥ’ùïîúöÔ]·CFadùsw}×Yvdr7¸ŒŒ&/ĊÑä/÷#Ë+wdyßYŝz˙"™á‘ċùĤYïF“‘eoŬŒ)ŭÊŜȲ7ĤìŽ,/‚éÈ1ċn4ÙSÖ·û‘egyéŒ)ݤ1ċcO2;cÊÑäG 1ċ}—ŜhòE2ŻïŸ˙|ÚÈ£Éî˜rû2Ĥôċš“““ĦċÇ]E”/ÈÓOġsŭġòŞŝëáE)Ÿüöt/gΘòSdù÷Ŭĝò›1ċĞŜÈr·>ó,ÛqdwdıG~ӎ&Ŭ‘e}~0²üŸîGŻÎö˨QYžt×Θòüp4ıĊŭş?Žü‡4šl$s7²Ü‰âEw4ÙY|èŞMŝk7ŽÜ,ŻN:#ËiüMĈ”oğ£Éf{÷ĦëU_ ğ£ÉΘò3š<ñ| ğٍ&?É#˛ȲS~ˆŽ,<óŽ,oğ#Ëû‘ċİ0ĤuF–O×ۧ͟_ħĵÙ~íHĉNċ ‡–wµRŝġġòj§ħŸożüŸ7ġOçġï›/ß½­/υ`{yÊĤ†qyÊŬıċ)›ÚÈS’§$OIž’yÊÑJY…—ċ”òëvûċğ·ġçÛúóíwŻëß7_˙s_}:żôŒ)÷2Ùĥ{Ĉċ)wÚĉd({WùĉÍÙ^ĠÏġġĉŝâ§ÛğğÇŜȲUÊPž²Ŭî dğŬ ¤;ĤìŽ#Ŭ^Ĉ”ßżaoğ'™MžòE,ÉS’§$OIž’<ċŞò”Ç(÷cĜ1JyuywŝÍíŸO7?^oïŻ~ûĞÍ/wçoÎ?Ŝœ|wqóûĥKyLÙd({Êw xû£nž²3²§tGíĥ{uò”ä)ÉS’§$OışßÖ??ŭvóáġġĉŝ귇ÓnzÊ:–§ì)ó”/Í1eğßŭÊŜG²Ŭ<ċáçħyÊŜ8’<%yJò”ä)ÉS’§Ż”ww›_îêçúááññŸ>×כû§˙~½ĝéöêçğ™Œċ)ĥ[Q<üîkG)ûß} ˆċyhLùMG,{ÉĥcJŝŸ’<%yJò”ä)³ÊS†Ċ:­RNúŬ×çş~˙÷éôŸ›ĞŸïnoîîO˙ıÙürw½ıßŜ÷“”Ŭ`ŬÏT{yÊo^;%}ƒH÷P(OÙŭ¸µŭÊùtŝŸ²W yJò”ä)ÉS’§Lž§Ş”ŝKD3r ”7żmëçúöĉáôŸ›ËóÛó7͞.­XĉöğŻ]™äw_ÉS’§$OIžÒXžrĉͨ”Ÿ>\ßü½ğ{lò‘·7ğ´ğğ{ĵşĵğùmûċ˙zŝħ2“ß}íf(ùŬWò”ä)ÉS’§Ì6OyĦ^T~ÜU†ċ)/ÏoŻ7÷·77żmoo7÷כûğğǧ˙~}zúÚËSòğŻä)ÉS’§$OIžrPžòdĉeÜU´Jوċ›“k™èïvG–ÌOIž’<%yJò”ä)ğyʜQ)ċ rËS2?%yJò”ä)ÉSĉŸ§Ì™ R@‹G)O?žÎö/Q){˙ CÌĴ…ĊZ*ŸÈÇHK£|zšÈ‰(ċ Ħpˆ™µ°XKċùXiA)!1ÄÌZ@)ĦXPJH 1³PJ(”rĵ?˜ÜŞU°ş˜)ĥ­½-ċ½÷#ÒğŜɓ7Äê‚sDŽt9Á?´£eB„ú]2An)y'-ğ"uêċmı^fQÊí_Ük{NĜږy÷@nm¤ŒÈïëŽw;‰m!Kx.W)›xžX)])ċ¸CĦĦ6Ôî3M{SJžK…à*e÷#”,”2“û…Aô”Òŭü|iì-ŬCnáèĦPȍPÓËíîĈ dN¨o&oGY)y.NW)Ŭxè‰ċ˘cÊhT‘–µÑ v‡ü ½{2Lx€\*“ċÑ3âÓWŜŬÊ,ĦĠVĦ”rɚç’QV£”µ:”£ĠB†( rCCŝ êıİ Ó?ˆô'ò\Z5Y+ğÇÍ(%w4ȸú{öv&7†úô5‡Ö YÂs ĤWÊAKòû™ŝ×ì,RHxgĝ3J)½?e° N?n”ßżÙŝ5v~ÊI”’ğ Rş3byIĤ”Ìm ݘ])}Ó5ôYĉĥ€T´JÙĠËö`ĴŞŞ; ”ċM8:÷˜ ğɑW˙ŸjòıƒêÑǛP2TÏ|Áœ9ŜÊÄ <[ DwLyúqÓEÏö0ld²Ûö²ÖGÌmy DsrÁĞ|? Òż™ê9Òĝè)… żÙ¤ġÉL–”Ùöè}úÚŻ”ÍoñTUĠT'ż}×G˙RïîìÛۖO읒ÉKñz¤pĦ֗‹g¨ñšz Œ–Ao*İÌóZ³ÜĦ”<[ÊaĈï)Ñ0Ġá"ìLnĦğż·ÚĉÙb•Œ~÷µ¸Œg‚ĉ€g‹UÖñğŻÓB4ÀlħJFyJ€ É(O !ċ)£†2ë,Ï:ò”ÌO İ`~J ;óSöJêkÙµV‘è)EAóÙFöjžĉEj Ġ@pSóSvw†ĥŬòBÉn´EŻ­$jIá|ĥñzRŜ„ĉEœ…`~ʐ)‚RúwOÚhÖ[R24_QDßtӚ ‚³4ÌO2erŒŠF³ĤrMa˘y„Ó”B󭑵+eôÁi ƒóSşDğeoğ]zċ½û5—ëFsoZıUhBz)×M¨”§= ÎOŞÙŬĦĦûCGğQ;˘Â ùŠ"*0iM:^) NcœŸÒŬí–Ħ’Ñŭè-‰VX4_QĴ]) ÎÒXâw_52ÙĥèhĴħ—Ġ9˘YĥDSa!|ĥ‰êGĥJ)%8 a‰ß}]L)Ûkıñä.ŜĞ÷ ‡*‰ŜˆĤ’îQ˘™ĉ+ÙĞyš§4žà´ÍżûŞìŜ˜–ä€Xâw_­ ú½jh>È‚37–ÈSĴ—%ò”Çàŭ);€ĊX"Oy “(%3vÀh–ÈSñJÉܖp Yç)e³C_‘íİ}ô§‚şä›§ĴœÛ2şÇ{˘PgċûŞÊù§a²Áƒ^ ÖMP²3ó4Ż&8!Ûôëì{‚h‚˘XRz×^› N“dš§ĴRÌm9SOpŬ{´÷˘*żx÷Żš ĵNËÁ“ŜèŝIp–LĤyÊúıŸÛrĤž²6t´;­PrĠE!7Jr“–TJÁ‚32ÍS6è_Ž +e­è  ŠÔĝà̇Ló”-Ê_˜D)½Êí!z‚šÀ<ÑÖÉ\)5fœVÉ4OْƒR֝ѭw§÷·÷¨·ÁÂŜYÉh*h‚1Oój‚rÎS6è•r’Üï°²ÎSÖÌ%İ1’§˜ #yÊ>q€É1’§l¨œŸ&hżÂƒRÀ8Lċ) íD,`Ĥò”^l÷£”0kyÊPyXÊ˙ù4´y„Ż„ìr(÷ìúıÚ˙ éêĴ›5sKx>”ŒÁŽŭF)ëÀ‡!BŻÖô(:żçĜ{Ŭ£ÂÛ:ÎÏ ıY—7£EĦÀ“mó|°yJ ƒyJ”a-OİY’;V„İ<%Àä˜ÊS 7Ù#ıß`-˜ÊS†î€Ñd§”\ e%{jżÙlIU€ž|ó”UUuG²ĵ G5_êñëö^Â[‰·6áZJwı…e·È%+ß?‡…vêíÔ7M°p,@ÈEË?ȒPĵE‹u {[Jhtıe‡6zè~…òrÉÊ\pÊdš§ĴŞŞıjóŻÑħ`sHó+êÑV˘A8E¨!TR¨Aòıò}É%£vNú4Aò&˜ïÍj|•Ü‚Ó|pFÉ4OÙ(eóïUU5Ĥo(‚Rjŝ2Ú˘§ŒˆıÁ'İıDÔ*½1 +%M0w,‰×ò$·£q&ÁYTpzÉ4OÙSÊú9RÖ ‘#zúˆžġĠCÇôÍuǵ8Mĥ –$[tŸ-²a§½àô’iž²ê|úÚìi”2ôÉêñJ•a9B5h6ĵu†Œ‰Z2ÈòcŒ‘6˘Ċi‚´M° ^;“ïuĤ·-ÎB‚S ӂğĦ–œúJVœQ2ÍSĥ,Ĥ”½ĊÛÒr|¸5ȕxË{+TzÀ-ìZ½)½1њA$o‚]”­%^?GÛ1Zƒ\I4fùM_ùBƒü½ċ•’ož²AŻ”ƒ–ä~€µuž²f.‘H~rhÈ‚sVŒä)fÂHž²O\`rŒä)*ç§ ÚŻ ”0SyÊF)C;KİC•¸G£'ĥ;C%Ëċj½Ĉ„nšÀ6šFÌÓĵQ‚³2ÍSVUĠ\µù3:ĴŞŞüœşW;½5D·Ŭ?·‡=A³èU³jhÛÈnLîIY½ÎÂÉ4OÙ(ċĥӅF+·°~ÏL=A_Oèħn@Ċş”’à„Ló”=ĴŸ‹VÊAeV MPî3=ı?×Ğ”ƒÊÀ82ÍSVO_›L*ewj •œĵ'˜ì4A!¸˜‰KG+%ÁY™ĉ)·ĠĠá×VċĉŸU),9mO°Úh‚˘p]ÜŸ£•òȒç*È4OÙ żĴġJ.İ”ŜN5_O2Öh‚˘ˆŽ´š´ ’×~w?ÁiLó”-Êŝs¤RnA6SO\eP1ĥ‘ŸÉ=İ7à,Ló”-‹)e{-7ÚĵïĵÂyż\IÔċ½ĴšÀ6²·s6/t”à,„|ó” BàşĊôKrżÀZÈ:OıU+%ÀL䞧HËÄyÊäómvÙN7 tò{€TLœ§L~?]†*÷U(œ‰ó”Éï§Ë íD,Šeâ#Bžrcʴ̗§dL™!Ħr0İfL ä)w ”i‘3ˆŜ2ÊAJ™ rC$÷?J Ĉó”úÂ(eZääbhÀá=4y ĤBnÊlÍËÁ6H yÊ(%xĦyÊ•nèıÉoĉƒ>^8ä)w¸ŸËy—ä7 Cž@‚¨½pc È.Jn^kgMp‰Á}mö4Júdu í ö ½—îî^ •Ö*kÑj¸ħ\ç{[-•m^3N0˜§ĴŸëêkĞšH­”µŻƒ…âŻwŠûgôÄ:ċB5GÚŞg΃ËAӚ9˜Ô;Jp‹ÁŸ$áĦApŽÁ¨½pc9„\”ܰyB‚³ ĉ)+ĉ§âĞŸĦzĉè9¸ħ%ÈÁ'^9qËt7Î0˜§Ĵ˜ŸrˆŻ4&œ%¸Ñ0ĞSJÁH‚³ ĉ)+ĉ§â+I£ëg n´ŠÜ(É}âš'Ip–ƒÁ.f•’ù)5•ĞÒT8aĞáFÛDÙ9¸(•Rœ™c_)kĉ§{M…ĥn´MŝJÙ <ï~‚³LÌ*%óS†œ#Tşş×ŝÉ[ 7ÚĤçŠA_ҐmgÉTÊúı˜ŸRwQµËtÜXí³8CŒÁY26•²ò–„RÊ'˘”+rZˆĥZ“B ‚Ì*eÇĴ[Ñë†ŝìíÑlGŻ(—ÏA)q£a”ÎO}\PÊy•2ú˘úÓ[À[I¨ŝÍ öxĉ ”¸Ñdžz~#C{ÎbA)=Ñ#/Éï –´ Á6璠”(%€Ju³n J){‡ù)JÇĴRÊr‡ĉÊü”`S)+ĉ§ÔŬ‘|³.1şÉp£1ĵmşŭ|| Ħšà,ƒJY1?ċ¨‹†Î]ĤçàFcxӂ3ñ×‚Ì*%óSj.*WİpÂVf¨|C(”’à\/ö•²f~ÊħWÑT8aĞáFc(•Ò+Ğ Ĥƒ‹Yd~ʐs„ŞBW÷Ú?yĞáFc-ċnçà–%'TÊúı˜ŸRwQµËtÜhR*[yIkéàbS)ë!oI(|"Jı"7f…R)3–œ`V)ëŝBˆà,”Ò=ò’ü`IPJ› ñ¸lCp. J RH ”Q1ë@Ñ ”²w˜Ÿ tÌ*ċ ,wèkÌO 6•²b~JŬÉ7; 7{›ŜÊÊ'ÑŞ Îò0¨”óSŽşhèÜezn4†÷™ë}vgċ"Ùg˜UJĉ§Ô\TJSᄭ†ÍPù†PŜıı(•Rœ™c_)kĉ§{M…ĥn4†÷–sVʐ–œ`V)™Ÿ2äĦŞĠ½öOŜj¸ÑŜ; íÌÁ-½Àóî'8ËÄ RÖÏuĊü”ş‹jĴ]ĤóàF{è•2Eƒà,›JYyKB)ċQÊı1+V§”Ħ‡Á f•²ÎcÖ­èuCööhĥ£W”Ë研¸ÑÔ¸.ıÙ' ”ó*eôE5ô§·€·’PŭĦ›ìñÍA)qñŜ²·”nOe6Á ('zä%ù}À’ ”6Aq#Ĝ†à\”@@)£bÖ-€˘A)eï0?%@é˜UÊAYî×\™Ÿl*eĊü”ş;’ovÜ%F7n4†·-%7X0;´‡à,ƒJY1?ċ¨‹†Î]ĤçàFcxÓîĥĈuiÍvwœbV)™ŸRsQı*M…ĥn4CBÉŜÈÁEİ”’àÌûJY3?ċĜĞh*œ°Ġp£1V§”!'8ÁĴR2?eÈ9BUĦĞ{íŸĵĠp£1BwêŬŸƒ[zçŬOp–‰AĴŸëŠù)uĠXğLçÁöX—RFƒà,›JYyKB)ċQÊı1+ôŠ˜ƒsĵƒ­ygɘUÊ:Y·˘× ŭÙَۣ^Q.ŸƒRâFK(ñıy†>.(ċĵJ}Q ŭé-à­$Tèf{ĵGsPJܸF4NêùċÍ N@)k_ôÈKòû€%A)m‚ĈF° Áı$(%€J RFÄĴ[EƒRÊŜa~J€Ò1Ğ”ƒ²ÜĦŻı2?%ĜTʊù)uw$ßì¸KŒn2Üh o[Kn°`vhÁY•²b~ÊQ ğLÏÁĈ>ĤŬmëҚíî$8 ÄĴR2?ĉ˘rUš 'l5Üh†*0„’Ŭ•ƒ‹R)%Á™9ö•²f~ÊħWÑT8aĞáFcĴN)COp‚Yd~ʐs„ŞBW÷Ú?yĞáFc„î´ğżçŸ 5.ÁY2•²~+ĉ§Ô]Tcí27ÚCéŠöÖEÑ` 8KĈĤRÖCŜ’PJùD”rEnÌ ï- ~H”Ħ‡Á f•²ÎcÖ­èuCööhĥ£W”Ë研¸ÑšGĵĈuù˜Mp J9ŻRF_TCz x+ ĠşYÁïÑ”7“ġnObvMpJYû˘G^’ß, Ji47‚mÎ%A)$PJ ”2ê fŬ(”RöóS”ŽY”ċ}͕ù)ÀĤRVÌOİğ#ùfÇ]bt“áFcxÛBXrƒ³C{ÎB0¨”óSŽşhèÜezn4†÷1ínk\—Ölw'ÁY f•’ù)5•ĞÒT8aĞáF3T!”ì\”J) ÎÌħŻ”5óS޽ŠĤ [ 7cuJx‚Ì*%óS†œ#Tşş×ŝÉ[ 7{§ŜÌÄ-½Àóî'8ËÄ RÖÏuĊü”ş‹jĴ]ĤóàF{·ìuWZEƒà,›JYyKB)ċQÊı1+V§”Ħ‡Á f•²ÎcÖ­èuCÖᇈpQhŞÒ×9 ¸Ñ/ċ£”‚' ”ó*eôE5ô§·€·’PŭĦ›ìñÍA)qñĥ…àħä f g  ”žè‘—ä÷K‚RڍǍ`‚sIN?ž6¨¤F) (İJ ĊѨŸ bÖ-€˘A)eï0?%@é˜UÊAYî×\™Ÿl*eĊü”ş;’ovÜ%F7n4Fè6ğû3tK4„j‚³< *eĊü”£.:w™žƒzĉ Ïâ\ä5à„Rş/ͲJd~JÍEċŞ4NĜj¸Ñ U`U‹ šÜìy'ôĈ”‚LU)kĉ§{M…ĥn4†ÜY2tŽlÁY2î§Ż!™\™R2?eÈ9BUĦĞ{íŸĵĠp£1B^êí… –Í&8Ëě§l<ĥÖBòZ˜yQñà`€yˆrÜèQ@ÄZ b`…xƒÈbàVV˜ELLlèQ@D[ÂÂÇ||`B…À,^°@ĦÉʉ–kˆhKxù^PĜAB“-×)–²àĵì|ĵÀĜa%pn Ù ĴÈı €H .܀d 4ó°Ёb (Q >agED??Šü 0K@ œ•l ,jˆ4Kyx@#?ˆbdàħYùÁ>aà‡†0  Ċ3?@‘b ?++ĜF ñ@˜âû„ b '(ÁsBĴa[@D[ÂÈÎ t0+(C0ÀH„fVˆ% (Ĉ5 ‹\DtŽg`ċa 0”@‡Bj 0JĜ8Ħր(óóiĊ +0|xXYA+++šO¸ ĦĊ‰H¸l, @ D”&¨@Aö€lbċp >'`VH|€­zÄ ܖ°ƒƒ…———…'‰œ Yxà `°ħÂ-ZÀÊ ô +¤î—-Ā5ĝÀÀÀŒ`~ ÌïŒĴPÏ£â(€ú„ZĴ`°‚ ç„z„ €°XÁÈ 2èP\x€, aŒPïƒ ”xĦ4NÀ–-€Ä=(Ö!ê³Şddaĉ+°óXÀı˜•‘b:/;4 Y^@À9\ €˘l 'ĵ  LKXYY@YÌş˜‘—…‘â>`@­ä)ğÀĊ<`UÂÉ ŽuhK €°ĉ`ĦÊŠPùδ„…Œ@+yÁlV;@ı\@-áú)@ĞÙ5 @1`-pyYYĝXAħÉJ¤ì, Äd`Îg„ĝ…d $^ –pC‹ RĤÀ’/r³™'ĵ@w³5ħò1‚²`0ƒ•–ĥ ™% LÊ✠‚^ÏRÉÀ*GYù@´‹‘d4H„d/PÒ ‚ä$`"g€+2ÌgC~Á†0 [`Œ€ ;ŒrpÇ P²Z J̌ĵ £Á1JĉàÌÈ.S@yš|9áî ¸@•(˘YXĜÁ)—ÈäĊ; +@[ĝĜA~ù$ I‰@Êĵ Ÿ€ËPÊçd@ġ?@Á-éb€(‚3<‰ċx À @hĤd%- É ħ„\ĵ£)ց €ˆ+…Y!™–_2Hâ`†–)há äî-`áÄȀR/‚ *FPE’DÈ Ş_PÍ 4ŸQhA@!ħùXáU0£°#wœxÀí7`˘—-H2à*Ÿ‘âPâbJ3 €ĜcA–0²°˘•š,ĵàbĠHc€ĝ\•00p˘÷ığOÀ‰g“ĊVHı²TĤ€bQhA@!˘ĞÀPg€ D N˙<ÀÊVĵː,Ĝ BH)Y@Ċ ¨ĉċ„äu´Î#@1  ˜ÇYT4‚28Ph-,"ĝÁ%ˆÊ<  ´=ʑààâW%Ĵhħ„b 0*€Žĉ O€@Sx@Ä,P‘Â,x€2, 6 ¸DcÇ=ĜX”-„ĊXÍÄ N]À‡fFHÉÊÎ fg ú@ÁĊÁÀm›˘G(@ĦX MŒÀˆgaçX İòà=ÈnP&VP’681h@X,–`Ÿ€Êuä4ĊϘ @‹€ql0 µğ0K_ Hݍl Ü'Œ X.88ùÀݎĊ' P`Ĥ~€–Òˆ.xp} .p} .`4ó²C‡Ÿ•ĉW¨O°{„ €€í[pñËN]Ĵ`ġÀˆG< 8ĈAċ¤ä‡Tĵ`K ö1òò ĝ„ĞGĝˆÀ [ÂÎğ<² T+ šĜÜĉ%a°B`°³'²O°$_ `l]Šv ~PĠÊÔ |Şn|h!Ĉ’ċ $¸ ċia@ò 'ށ"€×Q<àĈ"°pbVHi*ÀxDS ,"ÀLN~„O°&_ ÊĈ PR/€b€6xùġ°2`·U5r˙„GĴ@S² xĴ‘™Q ZŒä6ìħČ]TKxAġ ;´5ŠxXXqĝ„§GĝÜ!GµÖ êìÁÈĥ×H'@R ¤~8Ô°6P[$İ5À` Ô Àŭö qN~€b׺<àÁPÓn ?¨ĥ`dÍ0CT•0‚ò#(˙›Àú‹É'8S*@„\!âÙ`ġŠ VHÔ|ŞàÍÀ’Ĝad Pƒû§GĝԌe5ÁĈ‚,aAÄ/¤dĠ_â‘‘\í²0@ƒ%uáÎrŒ^XVíH>:žÜ5–:°è-VFhı‰Ü˘aĊk @1€{O Š Ù¤3xĠÂ*é – ›Šß'JY<öZijÀ†Ñᖰ€‚ l ;Ĵ”uLyZ@àn;$0Xّâv £ĦcfP#€u!<¸`İڂĊg @AĞ Vh,À}nï@Ğ\PÀmM°‚‹‘,° Ċm @A½L¤$ îk‚ÇX (î>BX Î6$¸€ĤC-aáA^FܖĴ:Ĥ{hf„H§œA,‹—ñ<ì (Ĉ ¸- XC€4B´4’ê4C‚•^Ĵ@XÀšÒ¸çá!ş. ¤Ê‡•—6óhÄK† àĥ-ĈUl Xp†µ0<‚·ŸB XÛĜÊö 1j êX@ H€Ĝ:UTħ €†AĠ+d l h˜VmÛK`EĴ¤X@(c+Ĵ‘PۑÜâ…TgĴ°ĥ¨ċİaHħ €KRFPĞT)k%` ¨×dɌà˘4¨Ç²Š¤à dK@mmp× Üƒ-âAĠ¤ ³³óS„ÚßĉvhĦ7XÄ3@z  ĝ–),<¤F<@1`iv2Âz‡Ĵ°ÔĊÂ)`e·ŝIOp„M ´CÊOÂÀÔÄ™„ŽD“ ›%ŒK€éÚòµçyyÈÏ'„s„\É@hŬ\VS-  Checkstyle ${projectVersion} Checkstyle http://checkstyle.sourceforge.net images/logo.png

././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/AnnotationUseNoTrailingComma.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/AnnotationUseNoTrailingComm100644 0 0 1744 11451071614 31641 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; @SuppressWarnings({}) public class AnnotationUseNoTrailingComma { @SuppressWarnings({"common"}) public void foo() { @SuppressWarnings({"common","foo"}) Object o = new Object() { @SuppressWarnings(value={"common"}) public String toString() { @SuppressWarnings(value={"leo","herbie"}) final String pooches = "leo.herbie"; return pooches; } }; } @Test2(value={(false) ? "" : "foo"}, more={(true) ? "" : "bar"}) @Pooches2(tokens={},other={}) enum P { @Pooches2(tokens={Pooches2.class},other={1}) L, @Test2(value={}, more={(false) ? "" : "unchecked"}) Y; } } @interface Test2 { String[] value(); String[] more() default {}; } @interface Pooches2 { Class[] tokens(); int[] other(); } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/AnnotationUseWithTrailingComma.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/AnnotationUseWithTrailingCo100644 0 0 2711 11451071614 31641 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; //this file compiles in eclipse 3.4 but not with Sun's JDK 1.6.0.11 /** FIXME: CheckStyle's ANTL grammar cannot handle this syntax @SuppressWarnings({,}) */ public class AnnotationUseWithTrailingComma { @SuppressWarnings({"common",}) public void foo() { @SuppressWarnings({"common","foo",}) Object o = new Object() { @SuppressWarnings(value={"common",}) public String toString() { @SuppressWarnings(value={"leo","herbie",}) final String pooches = "leo.herbie"; return pooches; } }; } @Test(value={(false) ? "" : "foo",}, more={(true) ? "" : "bar",}) /** FIXME: CheckStyle's ANTL grammar cannot handle this syntax @Pooches(tokens={,},other={,}) */ enum P { @Pooches(tokens={Pooches.class,},other={1,}) L, /** FIXME: CheckStyle's ANTL grammar cannot handle this syntax @Test(value={,}, more={(false) ? "" : "unchecked",}) */ Y; } } @interface Test { String[] value(); String[] more() default {}; /** FIXME: CheckStyle's ANTL grammar cannot handle this syntax String[] moreAr() default {,}; */ } @interface Pooches { Class[] tokens(); int[] other(); } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/BadAnnonOverride.java100644 0 0 1647 11451071614 30351 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; public class BadAnnonOverride { Runnable r = new Runnable() { /** * {@inheritDoc} */ public void run() { Throwable t = new Throwable() { /** * {@inheritDoc} */ public String toString() { return "junk"; } }; } }; void doFoo(Runnable r) { doFoo(new Runnable() { /** * {@inheritDoc} */ public void run() { Throwable t = new Throwable() { /** * {@inheritDoc} */ public String toString() { return "junk"; } }; } }); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/BadDeprecatedAnnotation.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/BadDeprecatedAnnotation.jav100644 0 0 1346 11451071614 31526 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; /** * @deprecated * stuff */ public class BadDeprecatedAnnotation { /** * @deprecated stuff */ protected BadDeprecatedAnnotation() { } /** * @deprecated stuff */ public String toString() { return ""; } /** * @deprecated stuff */ enum Rock { /** * @deprecated stuff */ Metallica } } /** * @deprecated stuff */ interface Foo { /** * @deprecated stuff */ interface Bar { } } /** * @deprecated stuff */ @interface Bleh { /** * @deprecated stuff */ int bleh(); } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/BadDeprecatedJavadoc.java100644 0 0 1347 11451071614 31125 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; import java.lang.annotation.Inherited; @Deprecated public class BadDeprecatedJavadoc { /** * @Deprecated this is not the same */ @Deprecated protected BadDeprecatedJavadoc() { } @Deprecated @Override public String toString() { return ""; } @Deprecated enum Rock { /** * */ @Bleh2(bleh=1) @Deprecated Metallica } } /** * */ @Deprecated interface Foo2 { @Deprecated interface Bar { } } /** */ @Deprecated @interface Bleh2 { /** * * @return */ @Deprecated int bleh(); } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/BadOverrideFromObject.java100644 0 0 1377 11451071614 31332 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; public class BadOverrideFromObject { /** * {@inheritDoc} */ public boolean equals(Object obj) { return false; } /** * {@inheritDoc no violation} * * @inheritDocs} * * {@inheritDoc */ public int hashCode() { return 1; } class Junk { /** * {@inheritDoc} */ protected void finalize() throws Throwable { } } } interface HashEq2 { /** * {@inheritDoc} */ public int hashCode(); } enum Bleh3 { B; /** * {@inheritDoc} */ public String toString() { return "B"; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/BadOverrideFromOther.java100644 0 0 1765 11451071614 31206 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; import java.io.Serializable; public class BadOverrideFromOther implements IFoo2 { /** * {@inheritDoc} */ public void doFoo() { } public void doFoo2() { } } interface IFoo2 { void doFoo(); } interface IBar2 extends IFoo2 { /** * {@inheritDoc} */ public void doFoo(); } class MoreJunk2 extends BadOverrideFromOther { /** * {@inheritDoc} */ public void doFoo() { } /** * {@inheritDoc} */ public void doFoo2() { } class EvenMoreJunk extends MoreJunk2 implements Serializable { /** * {@inheritDoc} */ public void doFoo() { } /** * {@inheritDoc} */ public void doFoo2() { } } } enum Football2 implements IFoo2, IBar2 { Detroit_Lions; /** * {@inheritDoc} */ public void doFoo() { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/BadPackageAnnotation1.java100644 0 0 315 11451071614 31216 0ustar 0 0 @GunNRoses //this will not compile in Sun's compiler as of 1.6.0.11 package com.puppycrawl.tools.checkstyle.annotation; public class BadPackageAnnotation1 { } @interface GunNRoses { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/BadPackageAnnotation2.java100644 0 0 365 11451071614 31224 0ustar 0 0 @Package//this will not compile in Sun's compiler as of 1.6.0.11 @Metallica package com.puppycrawl.tools.checkstyle.annotation; public class BadPackageAnnotation2 { } @interface Package { } @interface Metallica { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/DifferentUseStyles.java100644 0 0 2060 11451071614 30746 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; @Deprecated @SomeArrays(pooches={DOGS.LEO}) @SuppressWarnings({""}) public class DifferentUseStyles { } @SomeArrays(pooches={DOGS.LEO}, um={}, duh={"bleh"}) @SuppressWarnings("") //compact_no_array @Deprecated() class Dep { } @Deprecated @SomeArrays(pooches={DOGS.LEO}) @SuppressWarnings({""}) enum SON { @Deprecated @SomeArrays(pooches={DOGS.LEO}, um={""}, duh={"bleh"}) @APooch(dog=DOGS.HERBIE) @Another("") //compact_no_array ETHAN } @Deprecated() enum DOGS { @Deprecated() LEO, HERBIE } @interface SomeArrays { @Another("") //compact String[] um() default {}; @Another({""}) //compact String[] duh() default {}; @Another(value={""}) //expanded DOGS[] pooches(); } @Another(value={""}) //expanded enum E { } @interface APooch { DOGS dog(); } @interface Another { String[] value(); @Another({"foo", "bar"}) //compact style String value1() default ""; } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/GoodAnnonOverride.java100644 0 0 2460 11451071614 30545 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; public class GoodAnnonOverride { Runnable r = new Runnable() { public void run() { Throwable t = new Throwable() { /** * {@inheritDoc} */ @Override public String toString() { return "junk"; } }; } }; void doFoo(Runnable r) { doFoo(new Runnable() { public void run() { Throwable t = new Throwable() { /** * {@inheritDoc} */ @Override public String toString() { return "junk"; } }; } }); } void doFoo2(Runnable r) { doFoo(new Runnable() { public void run() { Throwable t = new Throwable() { /** * {@inheritDoc} */ @java.lang.Override public String toString() { return "junk"; } }; } }); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/GoodDeprecated.java100644 0 0 2056 11451071614 30035 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; /** * @deprecated * bleh */ @Deprecated public class GoodDeprecated { /** * @deprecated bleh */ @Deprecated protected GoodDeprecated() { } /** * @deprecated bleh */ @Deprecated @Override public String toString() { return ""; } /** * @deprecated bleh */ @Deprecated enum Rock { /** * @deprecated bleh */ @Bleh2(bleh=2) @Deprecated Metallica } } /** * @deprecated bleh */ @Deprecated interface Foo5 { /** * @deprecated bleh */ @Deprecated interface Bar { } } /** * @deprecated bleh */ @Deprecated @interface Bleh6 { /** * @deprecated bleh */ @Deprecated int bleh(); } /** * @deprecated bleh */ @java.lang.Deprecated @interface FullName { /** * @deprecated bleh */ @java.lang.Deprecated int bleh(); } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/GoodOverrideFromObject.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/GoodOverrideFromObject.java100644 0 0 1751 11451071614 31530 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; public class GoodOverrideFromObject { /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { return false; } /** * {@inheritDoc no violation} * * @inheritDocs} * * {@inheritDoc */ @Override public int hashCode() { return 1; } class Junk { /** * {@inheritDoc} */ @Override protected void finalize() throws Throwable { } } } interface HashEq { /** * {@inheritDoc} */ @Override public int hashCode(); } enum Bleh1 { B; /** * {@inheritDoc} */ @Override public String toString() { return "B"; } } enum Bleh22 { B; /** * {@inheritDoc} */ @java.lang.Override public String toString() { return "B"; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/GoodOverrideFromOther.java100644 0 0 2376 11451071614 31407 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; import java.io.Serializable; public class GoodOverrideFromOther implements IFoo { public void doFoo() { } public void doFoo2() { } } interface IFoo { void doFoo(); } interface IBar extends IFoo { public void doFoo(); } class MoreJunk extends GoodOverrideFromOther { /** * {@inheritDoc} */ @Override public void doFoo() { } /** * {@inheritDoc} */ @Override public void doFoo2() { } class EvenMoreJunk extends MoreJunk implements Serializable { /** * {@inheritDoc} */ @Override public void doFoo() { } /** * {@inheritDoc} */ @Override public void doFoo2() { } } class EvenMoreMoreJunk extends MoreJunk implements Serializable { /** * {@inheritDoc} */ @java.lang.Override public void doFoo() { } /** * {@inheritDoc} */ @java.lang.Override public void doFoo2() { } } } enum Football implements IFoo, IBar { Detroit_Lions; public void doFoo() { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/NotOverride.java100644 0 0 534 11451071614 27403 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; public class NotOverride { /** * {@inheritDoc} */ private void bleh() { } /** * {@inheritDoc} */ public static void eh() { } /** * {@inheritDoc} */ public String junk = ""; void dodoo() {} } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/package-info.java100644 0 0 104 11451071614 27460 0ustar 0 0 @Deprecated package com.puppycrawl.tools.checkstyle.annotation; checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/SpecialCaseDeprecated.java100644 0 0 2264 11451071614 31322 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; /** * @deprecated bleh * @deprecated boo */ @Deprecated public class SpecialCaseDeprecated { /** * @deprecated bleh * @deprecated boo */ public int i; /** * @deprecated */ public void foo() { } /** * @deprecated */ @Deprecated public void foo2() { } /** * @deprecated * @deprecated */ @Deprecated public void foo3() { } /** * @deprecated bleh * @deprecated */ @Deprecated public void foo4() { } /** * @deprecated * @deprecated bleh */ @Deprecated public void foo5() { } void local(@Deprecated String s) { } void local2( /** @deprecated bleh*/ String s) { } void local3(/** @deprecated */ @Deprecated String s) { } /** * @Deprecated */ void dontUse() { } /** * @Deprecated * @deprecated * because I said. */ @Deprecated void dontUse2() { } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/SuppressWarningsCompact.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/SuppressWarningsCompact.jav100644 0 0 4365 11451071614 31674 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; import java.lang.annotation.Documented; @SuppressWarnings({"unchecked", "unused"}) public class SuppressWarningsCompact { @SuppressWarnings({" "}) class Empty { @SuppressWarnings({"unchecked", ""}) public Empty() { } } @SuppressWarnings({"unused"}) enum Duh { @SuppressWarnings({"unforgiven", " un"}) D; public static void foo() { @SuppressWarnings({"unused"}) Object o = new SuppressWarningsCompact() { @Override @SuppressWarnings({"unchecked"}) public String toString() { return ""; } }; } } @SuppressWarnings({"abcun"}) @Documented @interface Sweet { int cool(); } @Documented @SuppressWarnings({}) @interface MoreSweetness { @SuppressWarnings({"unused", "bleh"}) int cool(); } public class Junk { @SuppressWarnings({}) int a = 1; @SuppressWarnings({"unchecked"}) @Deprecated int b = 1; void doFoo(String s, @SuppressWarnings({"unchecked"})String y) { } } @SuppressWarnings({(false) ? "unchecked" : "", (false) ? "unchecked" : ""}) class Cond { @SuppressWarnings({(false) ? "" : "unchecked"}) public Cond() { } @SuppressWarnings({(false) ? (true) ? " " : "unused" : "unchecked", (false) ? (true) ? " " : "unused" : "unchecked"}) public void aCond1() { } @SuppressWarnings({(false) ? "unchecked" : (true) ? " " : "unused"}) public void aCond2() { } @java.lang.SuppressWarnings({(false) ? "unchecked" : ("" == "") ? (false) ? (true) ? "" : "foo" : " " : "unused", (false) ? "unchecked" : ("" == "") ? (false) ? (true) ? "" : "foo" : " " : "unused"}) public void seriously() { } } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/SuppressWarningsExpanded.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/SuppressWarningsExpanded.ja100644 0 0 4543 11451071614 31646 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; import java.lang.annotation.Documented; @SuppressWarnings(value={"unchecked", "unused"}) public class SuppressWarningsExpanded { @SuppressWarnings(value={" "}) class Empty { @SuppressWarnings(value={"unchecked", ""}) public Empty() { } } @SuppressWarnings(value={"unused"}) enum Duh { @SuppressWarnings(value={"unforgiven", " un"}) D; public static void foo() { @SuppressWarnings(value={"unused"}) Object o = new SuppressWarningsExpanded() { @Override @SuppressWarnings(value={"unchecked"}) public String toString() { return ""; } }; } } @SuppressWarnings(value={"abcun"}) @Documented @interface Sweet { int cool(); } @Documented @SuppressWarnings(value={}) @interface MoreSweetness { @SuppressWarnings(value={"unused", "bleh"}) int cool(); } public class Junk { @SuppressWarnings(value={}) int a = 1; @SuppressWarnings(value={"unchecked"}) @Deprecated int b = 1; void doFoo(String s, @SuppressWarnings(value={"unchecked"})String y) { } } @SuppressWarnings(value={(false) ? "unchecked" : "", (false) ? "unchecked" : ""}) class Cond { @SuppressWarnings(value={(false) ? "" : "unchecked"}) public Cond() { } @SuppressWarnings(value={(false) ? (true) ? " " : "unused" : "unchecked", (false) ? (true) ? " " : "unused" : "unchecked"}) public void aCond1() { } @SuppressWarnings(value={(false) ? "unchecked" : (true) ? " " : "unused"}) public void aCond2() { } @java.lang.SuppressWarnings(value={(false) ? "unchecked" : ("" == "") ? (false) ? (true) ? "" : "foo" : " " : "unused", (false) ? "unchecked" : ("" == "") ? (false) ? (true) ? "" : "foo" : " " : "unused"}) public void seriously() { } } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/SuppressWarningsSingle.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/annotation/SuppressWarningsSingle.java100644 0 0 4012 11451071614 31655 0ustar 0 0 package com.puppycrawl.tools.checkstyle.annotation; import java.lang.annotation.Documented; @SuppressWarnings("unchecked") public class SuppressWarningsSingle { @SuppressWarnings(" ") class Empty { @SuppressWarnings("") public Empty() { } } @SuppressWarnings("unused") enum Duh { @SuppressWarnings("unforgiven") D; public static void foo() { @SuppressWarnings("unused") Object o = new SuppressWarningsSingle() { @Override @SuppressWarnings("unchecked") public String toString() { return ""; } }; } } @SuppressWarnings("abcun") @Documented @interface Sweet { int cool(); } @Documented @SuppressWarnings("abcun") @interface MoreSweetness { @SuppressWarnings("unused") int cool(); } public class Junk { @SuppressWarnings("") int a = 1; @SuppressWarnings("unchecked") @Deprecated int b = 1; void doFoo(String s, @SuppressWarnings("unchecked")String y) { } } @SuppressWarnings((false) ? "unchecked" : "") class Cond { @SuppressWarnings((false) ? "" : "unchecked") public Cond() { } @SuppressWarnings((false) ? (true) ? " " : "unused" : "unchecked") public void aCond1() { } @SuppressWarnings((false) ? "unchecked" : (true) ? " " : "unused") public void aCond2() { } @java.lang.SuppressWarnings((false) ? "unchecked" : ("" == "") ? (false) ? (true) ? "" : "foo" : " " : "unused") public void seriously() { } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputClone.java100644 0 0 3426 11451071614 26337 0ustar 0 0 package com.puppycrawl.tools.checkstyle.coding; public class InputClone { public InputClone() throws CloneNotSupportedException { super.equals(new String()); super.clone(); } public Object clone() throws CloneNotSupportedException { return super.clone(); } public void method() throws CloneNotSupportedException { super.clone(); } { super.clone(); } } class NoSuperClone { public Object clone() { return null; } } class InnerClone { public Object clone() { class Inner { public Object clone() throws CloneNotSupportedException { return super.clone(); } } return null; } } // This could not pass as valid semantically but tests that // type arguments are ignored when checking super calls class CloneWithTypeArguments { public Object clone() { return super.clone(); } } class CloneWithTypeArgumentsAndNoSuper { public Object clone() { return null; } } //Check that super keword isn't snagged here class MyClassWithGenericSuperMethod { void someMethod(java.util.List l) { } /** * Not a valid clone override. Should not get flagged. * @param o some object * @return a cloned Object? */ public static Object clone(Object o) { return null; } } class AnotherClass { /** * Not a valid clone override. Should not get flagged. * @param t some type * @param a type * @return a cloned type? */ public T clone(T t) { return null; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputDeclarationOrder.java100644 0 0 10033 11451071614 30530 0ustar 0 0 package net.ubiquity.tools.checkstyle.tests; public class InputDeclarationOrder { static final int FOO2 = 3; // error public before package public static final int FOO = 3; private static final int FOO3 = 3; // eror public before package and private public static final int FOO4 = 3; private static final String ERROR = "error"; // error protected before private protected static final String ERROR1 = "error"; // error public before private public static final String WARNING = "warning"; private int mMaxInitVars = 3; // error statics should be before instance members // error publics before private public static final int MAX_ITER_VARS = 3; private class InnerClass { private static final int INNER_FOO = 2; // error public before private public static final int INNER_FOO2 = 2; public InnerClass() { int foo = INNER_FOO; foo += INNER_FOO2; foo += INNER_FOO3; } // error member variables should be before methods or ctors // error public before private public static final int INNER_FOO3 = 2; } public int getFoo1() { return mFoo; } // error ctors before methods public InputDeclarationOrder() { String foo = ERROR; foo += ERROR1; foo += WARNING; int fooInt = mMaxInitVars; fooInt += MAX_ITER_VARS; fooInt += mFoo; } public static int getFoo2() { return 13; } public int getFoo() { return mFoo; } private static int getFoo21() { return 14; } // error member variables should be before methods or ctors private int mFoo = 0; } enum InputDeclarationOrderEnum { ENUM_VALUE_1, ENUM_VALUE_2, ENUM_VALUE_3 { private static final int INNER_FOO = 2; // error public before private public static final int INNER_FOO2 = 2; public void doIt() { } // error member variables should be before methods or ctors // error public before private public static final int INNER_FOO3 = 2; }; static final int FOO2 = 3; // error public before package public static final int FOO = 3; private static final int FOO3 = 3; // eror public before package and private public static final int FOO4 = 3; private static final String ERROR = "error"; // error protected before private protected static final String ERROR1 = "error"; // error public before private public static final String WARNING = "warning"; private int mMaxInitVars = 3; // error statics should be before instance members // error publics before private public static final int MAX_ITER_VARS = 3; private class InnerClass { private static final int INNER_FOO = 2; // error public before private public static final int INNER_FOO2 = 2; public InnerClass() { int foo = INNER_FOO; foo += INNER_FOO2; foo += INNER_FOO3; } // error member variables should be before methods or ctors // error public before private public static final int INNER_FOO3 = 2; } public int getFoo1() { return mFoo; } // error ctors before methods InputDeclarationOrderEnum() { String foo = ERROR; foo += ERROR1; foo += WARNING; int fooInt = mMaxInitVars; fooInt += MAX_ITER_VARS; fooInt += mFoo; } public static int getFoo2() { return 2; } public int getFoo() { return mFoo; } private static int getFoo21() { return 1; } // error member variables should be before methods or ctors private int mFoo = 0; } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputDefaultComesLast.java100644 0 0 1214 11451071614 30467 0ustar 0 0 public class InputDefaultComesLast { void method(int i) { // switch with last default switch (i) { case 1: break; case 2: break; default: // do something :) } // switch w/o default (not a problem) switch (i) { case 1: break; case 2: break; } // VIOLATION!!! default is not the last one. switch (i) { case 1: break; default: break; case 2: break; } } } @interface InputDefaultComesLastAnnotation { int blag() default 1; }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputEqualsAvoidNull.java100644 0 0 11104 11511035405 30352 0ustar 0 0 package com.puppycrawl.tools.checkstyle.coding; public class InputEqualsAvoidNull { public boolean equals(Object o) { return false; } /** * methods that should get flagged * @return */ public void flagForEquals() { Object o = new Object(); String s = "pizza"; o.equals("hot pizza"); o.equals(s = "cold pizza"); o.equals(((s = "cold pizza"))); o.equals("cheese" + "ham" + "sauce"); o.equals(("cheese" + "ham") + "sauce"); o.equals((("cheese" + "ham")) + "sauce"); } /** * methods that should get flagged */ public void flagForEqualsIgnoreCase() { String s = "pizza"; s.equalsIgnoreCase("hot pizza"); s.equalsIgnoreCase(s = "cold pizza"); s.equalsIgnoreCase(((s = "cold pizza"))); s.equalsIgnoreCase("cheese" + "ham" + "sauce"); s.equalsIgnoreCase(("cheese" + "ham") + "sauce"); s.equalsIgnoreCase((("cheese" + "ham")) + "sauce"); } /** * methods that should get flagged */ public void flagForBoth() { Object o = new Object(); String s = "pizza"; o.equals("hot pizza"); o.equals(s = "cold pizza"); o.equals(((s = "cold pizza"))); o.equals("cheese" + "ham" + "sauce"); o.equals(("cheese" + "ham") + "sauce"); o.equals((("cheese" + "ham")) + "sauce"); s.equalsIgnoreCase("hot pizza"); s.equalsIgnoreCase(s = "cold pizza"); s.equalsIgnoreCase(((s = "cold pizza"))); s.equalsIgnoreCase("cheese" + "ham" + "sauce"); s.equalsIgnoreCase(("cheese" + "ham") + "sauce"); s.equalsIgnoreCase((("cheese" + "ham")) + "sauce"); } /** * methods that should not get flagged * * @return */ public void noFlagForEquals() { Object o = new Object(); String s = "peperoni"; o.equals(s += "mushrooms"); (s = "thin crust").equals("thick crust"); (s += "garlic").equals("basil"); ("Chicago Style" + "NY Style").equals("California Style" + "Any Style"); equals("peppers"); "onions".equals(o); o.equals(new Object()); o.equals(equals(o)); equals("yummy"); new Object().equals("more cheese"); InputEqualsAvoidNullOutter outter = new InputEqualsAvoidNullOutter(); outter.new InputEqualsAvoidNullInner().equals("eat pizza and enjoy inner classes"); } /** * methods that should not get flagged */ public void noFlagForEqualsIgnoreCase() { String s = "peperoni"; String s1 = "tasty"; s.equalsIgnoreCase(s += "mushrooms"); s1.equalsIgnoreCase(s += "mushrooms"); (s = "thin crust").equalsIgnoreCase("thick crust"); (s += "garlic").equalsIgnoreCase("basil"); ("Chicago Style" + "NY Style").equalsIgnoreCase("California Style" + "Any Style"); "onions".equalsIgnoreCase(s); s.equalsIgnoreCase(new String()); s.equals(s1); new String().equalsIgnoreCase("more cheese"); } public void noFlagForBoth() { Object o = new Object(); String s = "peperoni"; String s1 = "tasty"; o.equals(s += "mushrooms"); (s = "thin crust").equals("thick crust"); (s += "garlic").equals("basil"); ("Chicago Style" + "NY Style").equals("California Style" + "Any Style"); equals("peppers"); "onions".equals(o); o.equals(new Object()); o.equals(equals(o)); equals("yummy"); new Object().equals("more cheese"); InputEqualsAvoidNullOutter outter = new InputEqualsAvoidNullOutter(); outter.new InputEqualsAvoidNullInner().equals("eat pizza and enjoy inner classes"); s.equalsIgnoreCase(s += "mushrooms"); s1.equalsIgnoreCase(s += "mushrooms"); (s = "thin crust").equalsIgnoreCase("thick crust"); (s += "garlic").equalsIgnoreCase("basil"); ("Chicago Style" + "NY Style").equalsIgnoreCase("California Style" + "Any Style"); "onions".equalsIgnoreCase(s); s.equalsIgnoreCase(new String()); s.equals(s1); new String().equalsIgnoreCase("more cheese"); } } class InputEqualsAvoidNullOutter { public class InputEqualsAvoidNullInner { public boolean equals(Object o) { return true; } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputExplicitInit.java100644 0 0 3014 11451071614 27675 0ustar 0 0 public class InputExplicitInit { private int x = 0; private Object bar = null; private int y = 1; private long y1 = 1 - 1; private long y3; private long y4 = 0L; private boolean b1 = false; private boolean b2 = true; private boolean b3; private String str = ""; java.lang.String str1 = null, str3 = null; int ar1[] = null; int ar2[] = new int[1]; int ar3[]; float f1 = 0f; double d1 = 0.0; static char ch; static char ch1 = 0; static char ch2 = '\0'; static char ch3 = '\1'; void method() { int xx = 0; String s = null; } } interface interface1{ int TOKEN_first = 0x00; int TOKEN_second = 0x01; int TOKEN_third = 0x02; } class InputExplicitInit2 { private Bar bar = null; private Bar[] barArray = null; } enum InputExplicitInit3 { A, B { private int x = 0; private Bar bar = null; private Bar[] barArray = null; private int y = 1; }; private int x = 0; private Bar bar = null; private Bar[] barArray = null; private int y = 1; } @interface annotation1{ int TOKEN_first = 0x00; int TOKEN_second = 0x01; int TOKEN_third = 0x02; } class ForEach { public ForEach(java.util.Collection strings) { for(String s : strings) //this should not even be checked { } } } class Bar { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputFallThrough.java100644 0 0 23546 11451071614 27543 0ustar 0 0 public class InputFallThrough { void method(int i, int j, boolean cond) { while (true) { switch (i) { case 0: // no problem case 1: i++; break; case 2: i++; case 3: //fall through!!! i++; break; case 4: return; case 5: throw new RuntimeException(""); case 6: continue; case 7: { break; } case 8: { return; } case 9: { throw new RuntimeException(""); } case 10: { continue; } case 11: { i++; } case 12: //fall through!!! if (false) break; else break; case 13: if (true) { return; } case 14: if (true) { return; } else { //do nothing } case 15: //fall through!!! do { System.out.println("something"); return; } while(true); case 16: for (int j1 = 0; j1 < 10; j1++) { System.err.println("something"); return; } case 17: while (true) throw new RuntimeException(""); case 18: while(cond) { break; } case 19: //fall through!!! try { i++; break; } catch (RuntimeException e) { break; } catch (Error e) { return; } case 20: try { i++; break; } catch (RuntimeException e) { } catch (Error e) { return; } case 21: //fall through!!! try { i++; } catch (RuntimeException e) { i--; } finally { break; } case 22: try { i++; break; } catch (RuntimeException e) { i--; break; } finally { i++; } case 23: //fall through!!! switch (j) { case 1: continue; case 2: return; default: return; } case 24: switch (j) { case 1: continue; case 2: break; default: return; } default: //fall through!!! // this is the last label i++; } } } /* Like above, but all fall throughs with relief comment */ void methodFallThru(int i, int j, boolean cond) { while (true) { switch (i) { case -1: // FALLTHRU case 0: // no problem case 1: i++; break; case 2: i++; // fallthru case 3: i++; break; case 4: return; case 5: throw new RuntimeException(""); case 6: continue; case 7: { break; } case 8: { return; } case 9: { throw new RuntimeException(""); } case 10: { continue; } case 11: { i++; } // fallthru case 12: if (false) break; else break; case 13: if (true) { return; } case 14: if (true) { return; } else { //do nothing } // fallthru case 15: do { System.out.println("something"); return; } while(true); case 16: for (int j1 = 0; j1 < 10; j1++) { System.err.println("something"); return; } case 17: while (cond) throw new RuntimeException(""); case 18: while(cond) { break; } // fallthru case 19: try { i++; break; } catch (RuntimeException e) { break; } catch (Error e) { return; } case 20: try { i++; break; } catch (RuntimeException e) { } catch (Error e) { return; } // fallthru case 21: try { i++; } catch (RuntimeException e) { i--; } finally { break; } case 22: try { i++; break; } catch (RuntimeException e) { i--; break; } finally { i++; } /* fallthru */ case 23: switch (j) { case 1: continue; case 2: return; default: return; } case 24: i++; /* fallthru */ case 25: i++; break; case 26: switch (j) { case 1: continue; case 2: break; default: return; } // fallthru default: // this is the last label i++; // fallthru } } } /* Test relief comment. */ void methodFallThruCC(int i, int j, boolean cond) { while (true) { switch (i){ case 0: i++; // fallthru case 1: i++; // fallthru case 2: { i++; } // fallthru case 3: i++; /* fallthru */case 4: break; case 5: i++; // fallthru } } } /* Like above, but C-style comments. */ void methodFallThruC(int i, int j, boolean cond) { while (true) { switch (i){ case 0: i++; /* fallthru */ case 1: i++; /* fallthru */ case 2: i++; /* fallthru */case 3: break; case 4: i++; /* fallthru */ } } } /* Like above, but C-style comments with no spaces. */ void methodFallThruC2(int i, int j, boolean cond) { while (true) { switch (i){ case 0: i++; /*fallthru*/ case 1: i++; /*fallthru*/ case 2: i++; /*fallthru*/case 3: break; case 4: i++; /*fallthru*/ } } } /* C-style comments with other default fallthru-comment. */ void methodFallThruCOtherWords(int i, int j, boolean cond) { while (true) { switch (i){ case 0: i++; /* falls through */ case 1: i++; /* falls through */ case 2: i++; /* falls through */case 3: break; case 4: i++; /* falls through */ } } } /* C-style comments with custom fallthru-comment. */ void methodFallThruCCustomWords(int i, int j, boolean cond) { while (true) { switch (i){ case 0: i++; /* Continue with next case */ case 1: i++; /* Continue with next case */ case 2: i++; /* Continue with next case */case 3: break; case 4: i++; /* Continue with next case */ } } } void methodFallThruLastCaseGroup(int i, int j, boolean cond) { while (true) { switch (i){ case 0: i++; // fallthru } switch (i){ case 0: i++; // fallthru } switch (i){ case 0: i++; /* fallthru */ } } } void method1472228(int i) { switch(i) { case 2: // do nothing break; default: } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputFinalize.java100644 0 0 1616 11451071614 27037 0ustar 0 0 package com.puppycrawl.tools.checkstyle.coding; public class InputFinalize { public InputFinalize() throws Throwable { super.equals(new String()); super.finalize(); } public void finalize() throws Throwable { super.finalize(); } public void method() throws Throwable { super.finalize(); } { super.finalize(); } } class NoSuperFinalize { public void finalize() { } } class InnerFinalize { public void finalize() { class Inner { public void finalize() throws Throwable { super.finalize(); } } } } //Check that super keword isn't snagged here class MyClassWithGenericSuperMethod1 { void someMethod(java.util.List l) { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputFinalLocalVariable.java100644 0 0 4731 11451071614 30751 0ustar 0 0 package com.puppycrawl.tools.checkstyle.coding; public class InputFinalLocalVariable { private int m_ClassVariable = 0; static { int i, j = 0; Runnable runnable = new Runnable() { public void run() { } }; } public InputFinalLocalVariable() { int i = 0; final int j = 2; int z; Object obj = new Object(); int k = 0; String x = obj.toString(); k++; k = 2; Runnable runnable = new Runnable() { public void run() { int q = 0; } }; } public void method(int aArg, final int aFinal, int aArg2) { int z = 0; z++; aArg2++; } public void aMethod() { int i = 0; final int j = 2; int z; Object obj = new Object(); int k = 0; String x = obj.toString(); k++; final class Inner { public Inner() { int w = 0; Runnable runnable = new Runnable() { public void run() { } }; } } } public void anotherMethod() { boolean aBool = true; for (int i = 0, j = 1, k = 1; j < 10 ; j++) { k++; aBool = false; } int l = 0; { int weird = 0; int j = 0; int k = 0; { l++; } } int weird = 0; weird++; final InnerClass ic = new InnerClass(); ic.mInner2 = 1; } class InnerClass { private int mInner = 0; public int mInner2 = 0; } } interface Inter { void method(int aParam); } abstract class AbstractClass { public abstract void abstractMethod(int aParam); } class Blah { static { for(int a : getInts()) { } } static int[] getInts() { return null; } } class test_1241722 { private Object o_; public void doSomething(Object _o) { System.out.println(_o); } public void doSomething2(Object _o1) { o_ = _o1; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputHasFinalizer.java100644 0 0 1343 11451071614 27652 0ustar 0 0 package com.puppycrawl.tools.checkstyle.coding; public class InputHasFinalizer { public void finalize() { // It's not enough to check if the METHOD_DEF branch contains a PARAMETER_DEF, as that would // treat this method as having a parameter. Runnable runnable = new Runnable() { public void run() { reallyFinalize("hi"); } // generates a PARAMETER_DEF AST inside the METHOD_DEF of finalize() private void reallyFinalize(String s) { } }; runnable.run(); } // should not be reported by NoFinalizer check public void finalize(String x) { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputIllegalCatchCheck.java100644 0 0 714 11451071614 30526 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.coding; public class InputIllegalCatchCheck { public void foo() { try { } catch (RuntimeException e) { } catch (Exception e) { } catch (Throwable e) { } } public void bar() { try { } catch (java.lang.RuntimeException e) { } catch (java.lang.Exception e) { } catch (java.lang.Throwable e) { } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputIllegalThrowsCheck.java100644 0 0 657 11511035417 30776 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.coding; public class InputIllegalThrowsCheck { public void method() throws NullPointerException { } public java.lang.Throwable methodOne() throws RuntimeException { return null; } public void methodTwo() throws java.lang.RuntimeException, java.lang.Error { } public void finalize() throws Throwable { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputIllegalType.java100644 0 0 1143 11451071614 27504 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.coding; import java.util.Hashtable; public class InputIllegalType { private AbstractClass a = null; private NotAnAbstractClass b = null; private com.puppycrawl.tools.checkstyle.checks.coding.InputIllegalType.AbstractClass c = null; private com.puppycrawl.tools.checkstyle.checks.coding.InputIllegalType.NotAnAbstractClass d = null; private abstract class AbstractClass {} private class NotAnAbstractClass {} private java.util.Hashtable table1() { return null; } private Hashtable table2() { return null; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputInnerAssignment.java100644 0 0 5156 11714704773 30420 0ustar 0 0 package com.puppycrawl.tools.checkstyle.coding; public class InputInnerAssignment { void innerAssignments() { int a; int b; int c; a = b = c = 1; // flag two inner assignments String s = Integer.toString(b = 2); // flag inner assignment Integer i = new Integer(a += 5); // flag inner assigment c = b++; // common practice, don't flag // even though technically an assigment to b for (int j = 0; j < 6; j += 2) { // common practice, don't flag a += j; } } public void demoBug1195047Comment3() { // inner assignment should flag all assignments to b or bb but none of those to i or j int y = 1; int b = 0; boolean bb; int i; if (bb = false) {} for (i = 0; bb = false; i = i + 1) {} while (bb = false) {} if ((bb = false)) {} for (int j = 0; (bb = false); j += 1) {} while ((bb = false)) {} i = (bb = false) ? (b = 2) : (b += 1); i = (b += 1) + (b -= 1); do {i += 1;} while (bb = false); } public static void demoInputStreamIdiom(java.io.InputStream is) throws java.io.IOException { int b; while ((b = is.read()) != -1) // common idiom to avoid clumsy loop control logic, don't flag (make configurable later) { // work with b } } public static void demoNoBrace() { // code that doesn't contain braces around conditional code // results in a parse tree without SLISTs // no assignement should be flagged here int sum = 0; for (int i = 0; i < 3; i++) sum = sum + i; if (sum > 4) sum += 2; else if (sum < 2) sum += 1; else sum += 100; while (sum > 4) sum -= 1; do sum = sum + 1; while (sum < 6); } @SuppressWarnings(value = "unchecked") public java.util.Collection allParams() { java.util.ArrayList params = new java.util.ArrayList(); params.add("one"); params.add("two"); return params; } // Taken from JDK7 java.lang.Package src code. private static Manifest loadManifest(String fn) { try (FileInputStream fis = new FileInputStream(fn); JarInputStream jis = new JarInputStream(fis, false)) { return jis.getManifest(); } catch (IOException e) { return null; } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputJUnitTest.java100644 0 0 1701 11451071614 27162 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.coding; import junit.framework.*; public class InputJUnitTest extends TestCase { public static Test suite() { return new TestSuite(""); } // correct protected void setUp() {} // correct public void tearDown() {} // correct } class BadTest1 extends TestCase { private void setUp() {} // private!!! public static void tearDown() {} // static!!! static Test suite() { return new TestSuite(""); } // non-public } class BadTest2 extends TestCase { public void SetUp() {} // wrong name public int tearDown() {} // wrong return type public static Test[] suite() {} // wrong return type } class BadTest3 extends TestCase { public void setUp(int i) {} // too many args public void tear_down() {} // correct (unchecked) public Test suite() { return new TestSuite(""); } // non-static public void tearDown(int i) {} // too many args } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputMissingCtor.java100644 0 0 274 11451071614 27516 0ustar 0 0 public class InputMissingCtor { } // we shouln't flag abtract classes abstract class AbstactClass { } // this class has ctor class CorrectClass { CorrectClass() { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputModifiedControl.java100644 0 0 2505 11451071614 30355 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for FOR_ITERATION and whitespace. // Created: 2003 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.io.Serializable; class InputModifiedControl { int k; void method1() { //Violations: for (int i = 0; i < 1; i++) { i++; } for (int i = 0; i < 1; i++) { i = i + 1; } for (int i = 0; i < 1; i++) { for (int j = 0; j < 1; i++) { --i; } } for (int i = 0, j = 0; i < 1; i++) { j++; } // Ok: for (int i = 0; i < 1; i++) { } for (int i = 0; i < 1; i++) { int x = i; } for (int i = 0; i < 1; i++) { Serializable s = new Serializable() { int i = 3; void a() { System.out.println(i++); } }; } for (int k = 0; k < 1; k++) { this.k++; } String[] sa = {"a", "b"}; for(String s:sa) {} for(String s:sa) { s = "new string"; } } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputMultipleStringLiterals.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputMultipleStringLiterals.jav100644 0 0 1424 11451071614 31614 0ustar 0 0 package com.puppycrawl.tools.checkstyle.coding; public class InputMultipleStringLiterals { String m = "StringContents"; String m1 = "SingleString"; String m2 = "DoubleString" + "DoubleString"; String m3 = "" + ""; String m4 = "" + ""; String debugStr = ", " + ", " + ", "; void method1() { String a1 = "StringContents"; System.out.println("StringContents"); // The following is not reported, since it is two string literals. String a2 = "String" + "Contents"; } @SuppressWarnings("unchecked") void method2(){} @SuppressWarnings("unchecked") void method3(){} @SuppressWarnings("unchecked") void method4(){} @SuppressWarnings("unchecked") void method5(){} } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputMultipleVariableDeclarations.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputMultipleVariableDeclaratio100644 0 0 1201 11511035405 31570 0ustar 0 0 public class InputMultipleVariableDeclarations { int i, j; int i1; int j1; void method1() { String str, str1; java.lang.Object obj; Object obj1; } // second definition is wrapped // line of VARIABLE_DEF is not the same as first line of the definition java.lang.String string; java.lang.String strings[]; //both definitions is wrapped java.lang. String string1; java.lang.String strings1[]; void method2() { for (int i=0, j=0; i < 10; i++, j--) { } for(int i=0; i<4;i++) { } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputNestedForDepth.java100644 0 0 3515 11451071614 30154 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// //checkstyle: Checks Java source code for adherence to a set of rules. //Copyright (C) 2001-2004 Oliver Burn // //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of the License, or (at your option) any later version. // //This library 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 //Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public //License along with this library; if not, write to the Free Software //Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.testinput.coding; /** * This Class contains no logic, but serves as test-input for the unit tests for the * NestedForDepthCheck-checkstyle enhancement. * @author Alexander Jesse * @see com.puppycrawl.tools.checkstyle.checks.coding.NestedForDepthCheck */ public class InputNestedForDepth { /** * Dummy method containing 5 layers of for-statements. */ public void nestedForFiveLevel() { int i = 0; int i1 = 0; int i2 = 0; int i3 = 0; int i4 = 0; int i5 = 0; for (i1 = 0; i1 < 10; i1++) { for (i2 = 0; i2 < 10; i2++) { for (i3 = 0; i3 < 10; i3++) { for (i4 = 0; i4 < 10; i4++) { for (i5 = 0; i5 < 10; i5++) { i += 1; } } } } } } }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputNestedIfDepth.java100644 0 0 2232 11451071614 27757 0ustar 0 0 public class InputNestedIfDepth { void foo() { // nesting == 0 if (true) { } // nesting == 1 if (true) { if (true) { } } // nesting == 2 if (true) { if (true) { if (true) { } } } } void fooWithElse() { // nesting == 0 if (true) { } else { } // nesting == 1 if (true) { if (true) { } else { } } else { if (false) { } else { } } // nesting == 2 if (true) { if (true) { if (true) { } else { } } else { if (false) { } else { } } } else { if (true) { if (true) { } else { } } else { if (false) { } else { } } } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputNestedTryDepth.java100644 0 0 1561 11451071614 30203 0ustar 0 0 public class InputNestedTryDepth { void foo() { // nesting == 0 try { } catch (Exception e) { } // nesting == 1 try { try { } catch (Exception e) { } } catch (Exception e) { } // nesting == 2 try { try { try { } catch (Exception e) { } } catch (Exception e) { } } catch (Exception e) { } // nesting == 3 try { try { try { try { } catch (Exception e) { } } catch (Exception e) { } } catch (Exception e) { } } catch (Exception e) { } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputNoPackage.java100644 0 0 101 11451071614 27072 0ustar 0 0 /** * No package here. */ public class InputNoPackage { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputParameterAssignment.java100644 0 0 704 11451071614 31224 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.coding; public class InputParameterAssignment { int field; void foo1(int field) { int i = field; this.field = field; i++; field = 0; field += 1; this.field++; field--; } void foo2() { field = 0; } void foo3(String field, int field1) { this.field = (field1 += field.length()); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputRequireThis.java100644 0 0 2651 11646533001 27541 0ustar 0 0 package com.puppycrawl.tools.checkstyle.coding; import java.awt.Toolkit; public class InputRequireThis { int i; void method1() { i = 3; } void method2(int i) { i++; this.i = i; method1(); try { this.method1(); } catch (RuntimeException e) { e.printStackTrace(); } this.i--; Integer.toString(10); } void method3() { i = 3; } void method4() { this.method3(); this.method3(); } int I = 0; private class I {} } enum MyEnum { A, B { void doSomething() { z = 1; } }; int z; private MyEnum() { z = 0; } } class Bug2123003 { @Rock(band = "GnR") private String band; class Inner { @Rock(band = {"GnR"}) private String band; } class Inner2 { @Rock(band = {(true) ? "GnR" : "Tool"}) private String band; } @interface Rock { String[] band() default "Metallica"; } } class Bug1155921 { private static int CONST = 1; private static int static_method() { return 1; } private int method1() { return CONST; } private int method2() { return static_method(); } }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputReturnCount.java100644 0 0 2211 11451071614 27556 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.coding; public class InputReturnCount { public boolean equals(Object obj) { int i = 1; switch (i) { case 1: return true; case 2: return true; case 3: return true; case 4: return true; case 5: return true; case 6: return true; } return false; } void foo(int i) { switch (i) { case 1: return; case 2: return; case 3: return; case 4: return; case 5: return; case 6: return; } return; } void foo1(int i) { if (i == 1) { return; } Object obj = new Object() { void method1(int i) { switch (i) { case 1: return; case 2: return; case 3: return; case 4: return; case 5: return; } return; } }; return; } } class Test { public Test() {} } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputReturnFromCatchCheck.java100644 0 0 734 11451071614 31262 0ustar 0 0 package com.puppycrawl.tools.checkstyle.coding; public class InputReturnFromCatchCheck { public void foo() { try { System.currentTimeMillis(); } catch (Exception e) { return; } } public void bar() { try { System.currentTimeMillis(); } catch (Exception e) { if (System.currentTimeMillis() == 0) { return; } } } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputReturnFromFinallyCheck.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputReturnFromFinallyCheck.jav100644 0 0 1321 11451071614 31506 0ustar 0 0 package com.puppycrawl.tools.checkstyle.coding; public class InputReturnFromFinallyCheck { public void foo() { try { System.currentTimeMillis(); } finally { return; } } public void bar() { try { System.currentTimeMillis(); } finally { if (System.currentTimeMillis() == 0) { return; } } } public void thisNull() { boolean result = (this == null) || (null == this); boolean result2 = (this != null) && (null != this); boolean result3 = (this.getClass().getName() == String.valueOf(null == System.getProperty("abc"))); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputStringLiteralEquality.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputStringLiteralEquality.java100644 0 0 2445 11451071614 31600 0ustar 0 0 package com.puppycrawl.tools.checkstyle.coding; /** * Input file for the StringLiteralEqualityCheck * @author Lars Kühne */ public class InputStringLiteralEquality { void foo(String name) { if (name == "Lars") { // flagged, should use equals } if ("Oleg" == name) { // flagged, should use equals } if ("Oliver" == "Oliver") { // doesn't make much sense because this can be evaluated // to true at compile time, but is flagged anyway } String compare = "Rick"; if (name == compare) { // currently not flagged. // // Implementing this is very complicated, we would need // - type info on the == operands // - prevent false alarms where the user explicitly wants // to compare object identities // // My current feeling is that we should leave finding // this one to manual code inspections. After all MCI is // what some of us get paid for :-) } if ("Rick".toUpperCase() == "Rick".toLowerCase()) { // completly dynamic, don't flag } } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputUnnecessaryParentheses.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/coding/InputUnnecessaryParentheses.jav100644 0 0 4152 11451071614 31634 0ustar 0 0 public class InputUnnecessaryParentheses { int f1() { int x = 0; for (int i = (0+1); ((i) < (6+6)); i += (1+0)) { x += (i + 100); (x) += (i + 100); x = (x + i + 100); (x) = (x + i + 100); } for (int i = (0+1); (i) < ((6+6)); i += (1+0)) { System.out.println("hi"); } return (0); } private int f2(int arg1, double arg2) { int x, a, b, c, d; String e, f; x = 0; a = 0; b = 0; c = (a + b); d = c - 1; int i = (int) arg2; i = ((int) arg2); x += (i + 100 + arg1); a = (a + b) * (c + d); b = ((((a + b) * (c + d)))); c = (((a) <= b)) ? 0 : 1; d = (a) + (b) * (600) / (int) (12.5f) + (int) (arg2); e = ("this") + ("that") + ("is" + "other"); f = ("this is a really, really long string that should be truncated."); return (x + a + b + d); } private boolean f3() { int x = f2((1), (13.5)); boolean b = (true); return (b); } public static int f4(int z, int a) { int r = (z * a); r = (a > z) ? a : z; r = ((a > z) ? a : z); r = (a > z) ? a : (z + z); return (r * r - 1); } public void f5() { int x, y; x = 0; y = 0; if (x == y) { print(x); } if ((x > y)) { print(y); } while ((x < 10)) { print(x++); } do { print((y+=100)); } while (y < (4000)); } private void f6(TypeA a) { TypeB b = (TypeB) a; TypeC c = ((TypeC) a); int r = 12345; r <<= (3); TypeD d = ((TypeD) a); } private void print(int arg) { System.out.println("arg = " + arg); } static class TypeA {} static class TypeB extends TypeA {} static class TypeC extends TypeA {} static class TypeD extends TypeA {} } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/ComplexityCheckTestInput.java100644 0 0 4070 11451071613 27762 0ustar 0 0 package com.puppycrawl.tools.checkstyle; public class ComplexityCheckTestInput { public void foo() { while (true) { Runnable runnable = new Runnable() { public void run() { while (true) { } } }; new Thread(runnable).start(); } } public void bar() { if (System.currentTimeMillis() == 0) { if (System.currentTimeMillis() == 0 && System.currentTimeMillis() == 0) { } if (System.currentTimeMillis() == 0 || System.currentTimeMillis() == 0) { } } } public void simpleElseIf() { if (System.currentTimeMillis() == 0) { } else if (System.currentTimeMillis() == 0) { } else { } } public void stupidElseIf() { if (System.currentTimeMillis() == 0) { } else { if (System.currentTimeMillis() == 0) { } else { if (System.currentTimeMillis() == 0) { } } if (System.currentTimeMillis() == 0) { } } } public ComplexityCheckTestInput() { int i = 1; if (System.currentTimeMillis() == 0) { } else if (System.currentTimeMillis() == 0) { } else { } } // STATIC_INIT static { int i = 1; if (System.currentTimeMillis() == 0) { } else if (System.currentTimeMillis() == 0) { } else { } } // INSTANCE_INIT { int i = 1; if (System.currentTimeMillis() == 0) { } else if (System.currentTimeMillis() == 0) { } else { } } /** Inner */ public ComplexityCheckTestInput(int aParam) { Runnable runnable = new Runnable() { public void run() { while (true) { } } }; new Thread(runnable).start(); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/ComplexityOverflow.java100644 0 0 11707 11451071613 26715 0ustar 0 0 package com.puppycrawl.tools.checkstyle; /** * This class has methods that have an NPath complexity larger than MAXINT. * Test case for bug 1654769. */ public class ComplexityOverflow { public void provokeNpathIntegerOverflow() { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { } } } } } } } } if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { } } } } } } } } if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { } } } } } } } } if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { } } } } } } } } if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { } } } } } } } } if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { } } } } } } } } if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { } } } } } } } } if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { } } } } } } } } if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { } } } } } } } } if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { if (true) { } } } } } } } } } }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/checkstyle_checks.xml100644 0 0 2140 11451071614 27771 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/custom_messages.xml100644 0 0 1236 11451071614 27521 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/empty_configuration.xml100644 0 0 335 11451071614 30364 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/included.xml100644 0 0 336 11451071614 26067 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/including.xml100644 0 0 526 11451071614 26255 0ustar 0 0 ]> &includedConfig; checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/missing_config_name.xml100644 0 0 407 11451071614 30275 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/missing_config_parent.xml100644 0 0 342 11451071614 30644 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/missing_property_name.xml100644 0 0 407 11451071614 30714 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/missing_property_value.xml100644 0 0 407 11451071614 31110 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/configs/subdir/including.xml100644 0 0 531 11451071614 27541 0ustar 0 0 ]> &includedConfig; ././@LongLink100644 0 0 156 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/HideUtilityClassContructor3041574_1.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/HideUtilityClassContructor30415100644 0 0 341 11453312066 31222 0ustar 0 0 package com.puppycrawl.tools.checkstyle.design; import java.io.Serializable; public abstract class HideUtilityClassContructor3041574_1 implements Serializable { private static final long serialVersionUID = 1L; }././@LongLink100644 0 0 156 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/HideUtilityClassContructor3041574_2.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/HideUtilityClassContructor30415100644 0 0 330 11453312066 31220 0ustar 0 0 package com.puppycrawl.tools.checkstyle.design; import java.io.Serializable; public class HideUtilityClassContructor3041574_2 implements Serializable { private static final long serialVersionUID = 1L; }././@LongLink100644 0 0 156 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/HideUtilityClassContructor3041574_3.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/HideUtilityClassContructor30415100644 0 0 2360 11453312066 31245 0ustar 0 0 package com.puppycrawl.tools.checkstyle.design; import java.io.Serializable; public class HideUtilityClassContructor3041574_3 implements Serializable { private static final long serialVersionUID = 1L; public HideUtilityClassContructor3041574_3(int i) { // no code } public String getValue() { return ""; } // It is NOT Utility Inner class @SuppressWarnings("unused") public static class Event { // Top level class have access to fields - no need in public getters private String ind; private String ind1; public Event(String value){ // do a lot of calculations } // static because this method is utility public static String getEmptyString() { return ""; } } // It is Utility Inner class @SuppressWarnings("unused") public static class Event1 { private String ind; private String ind1; private Event1(){ // do a lot of calculations } // static because this method is utility public static String getEmptyString() { return ""; } } }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/InputInnerClassCheck.java100644 0 0 2421 11451071614 30276 0ustar 0 0 package com.puppycrawl.tools.checkstyle.design; public class InputInnerClassCheck { public int test1 = 100; public void methodTestInner1() { double test2 = 200; class InnerInMethod1 { void methodTest1() { System.out.println("test1"); } } int test3 = 300; //error } public void methodTestInner2() { int test5 = 500; class InnerInMethod2 { int test6 = 500; } int test6 = 600; //error int test8 = 800; //error } class Inner1 { int test4 = 400; public void methodTestInner3() { int test9 = 500; class InnerInMethod3 { int test10 = 500; } int test11 = 600; //error int test12 = 800; //error } } void methodTest2() { //error System.out.println("test2"); } } class Temp2 { class Inner1 { int test4 = 400; public void methodTestInner3() { int test9 = 500; class InnerInMethod3 { int test10 = 500; } int test11 = 600; //error int test12 = 800; //error } } void methodTest2() { //error System.out.println("test2"); } private int i = 0; //error } class Temp3 { class InnerCheck { private int I = 0; } public int[] getDefaultTokens() { return new int[]{1, }; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/InputMutableException.java100644 0 0 1154 11451071614 30551 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.design; public class InputMutableException { public class FooException { private final int _finalErrorCode; private int _errorCode = 1; public FooException() { _finalErrorCode = 1; } public class FooExceptionThisIsNot { private final int _finalErrorCode; private int _errorCode = 1; public FooExceptionThisIsNot() { _finalErrorCode = 1; } } } public class FooError { private int _errorCode; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/InputNonUtilityClass.java100644 0 0 1016 11451071614 30402 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.design; import java.awt.Dimension; import javax.swing.JPanel; /** * Not a util class because it's not directly derived from java.lang.Object. */ public class InputNonUtilityClass extends JPanel { /** HideUtilityClassConstructorCheck should not report this */ public InputNonUtilityClass() { this.setPreferredSize(new Dimension(100, 100)); } public static void utilMethod() { System.out.println("I'm a utility method"); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/InputRegression1762702.java100644 0 0 605 11451071614 30152 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.design; /** * Input for HideUtilityClassConstructorCheck, a non utility class that has * * @author lkuehne */ public class InputRegression1762702 { public long constructionTime = System.currentTimeMillis(); public static InputRegression1762702 create() { return new InputRegression1762702(); } }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/design/InputThrowsCount.java100644 0 0 757 11451071614 27570 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.design; import java.awt.AWTException; public class InputThrowsCount { void method1() throws Exception { } void methdo2() throws java.awt.AWTException { } void method3() throws Exception, AWTException { } void method4() throws Exception, java.awt.AWTException { } void method5() throws Exception, AWTException, Throwable { } void method6() { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/duplicates/A.java100644 0 0 325 11451071614 25304 0ustar 0 0 import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class A { public static final int X = 0; public static final int Y = 1; public static final int Z = 2; }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/duplicates/B.java100644 0 0 327 11451071614 25307 0ustar 0 0 import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class B { public static final int Y = 1; public static final int X = 0; public static final int Z = 2; } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/duplicates/InnerDup.java100644 0 0 1420 11451071614 26665 0ustar 0 0 public class InnerDup { int x = 0; public void m1() { x += 1; x += 2; x += 3; x += 4; x += 5; x += 6; x += 7; x += 8; x += 9; x += 10; x += 11; x += 12; } public void m2() { x += 1; x += 2; x += 3; x += 4; x += 5; x += 6; x += 7; x += 8; x += 9; x += 10; x += 11; x += 12; x += 13; x += 14; } public void m3() { x += 1; x += 2; x += 3; x += 4; x += 5; x += 6; x += 7; x += 8; x += 9; x += 10; } }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/duplicates/LotsOfEmptyLines.java100644 0 0 455 11451071614 30350 0ustar 0 0 // A class that contains lots of empty lines // such files frequently occur in the JDK source code, most notably the machine generated nio Buffer variants public class LotsOfEmptyLines { // 15 empty lines } // 15 empty lines below checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/duplicates/Overlapping.java100644 0 0 771 11451071614 27417 0ustar 0 0 // A class that has overlapping areas of duplication (min=3) public class Overlapping { public void m1() { int a = 0; int b = 0; int c = 0; int d = 0; } public void m2() { int a = 0; int b = 0; int c = 0; } public void m3() { int b = 0; int c = 0; int d = 0; } public void m4() { int a = 0; int b = 0; int c = 0; int d = 0; } }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/duplicates/Shorty.java100644 0 0 146 11451071614 26415 0ustar 0 0 // A class that is shorter than the number of lines considered a duplicate public class Shorty { }././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/filters/InputSuppressionCommentFilter.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/filters/InputSuppressionCommentFilter.100644 0 0 3263 11451071614 31664 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; /** * Test input for using comments to suppress errors. * @author Rick Giles **/ class InputSuppressionCommentFilter { private int I; /* CHECKSTYLE:OFF */ private int J; /* CHECKSTYLE:ON */ private int K; //CSOFF: MemberNameCheck|ConstantNameCheck private int L; private static final int m = 0; /* * CSON: MemberNameCheck */ private int M2; private static final int n = 0; //CSON: ConstantNameCheck //CS_OFF private int P; //CS_ON private int Q; //CS_OFF: ConstantNameCheck private int R; private static final int s = 0; //CS_ON //CHECKSTYLE:OFF private int T; //CHECKSTYLE:ON //UNUSED OFF: aInt public static void doit1(int aInt) { } //UNUSED ON: aInt public static void doit2(int aInt) { } public void doit3() { try { // lots of code omitted for(int i = 0; i < 10; i++) { // more code omitted while(true) { try { //CHECKSTYLE:OFF } catch(Exception e) { //CHECKSTYLE:ON } } // code omitted } //CHECKSTYLE:OFF } catch(Exception ex) { //CHECKSTYLE:ON } } } ././@LongLink100644 0 0 160 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/filters/InputSuppressWithNearbyCommentFilter.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/filters/InputSuppressWithNearbyComment100644 0 0 4424 11451071614 31727 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; /** * Test input for using comments to suppress errors. * * @author Mick Killianey */ class InputSuppressWithNearbyCommentFilter { private int A1; // SUPPRESS CHECKSTYLE MemberNameCheck private int A2; /* SUPPRESS CHECKSTYLE MemberNameCheck */ /* SUPPRESS CHECKSTYLE MemberNameCheck */ private int A3; private int B1; // SUPPRESS CHECKSTYLE MemberNameCheck private int B2; /* SUPPRESS CHECKSTYLE MemberNameCheck */ /* SUPPRESS CHECKSTYLE MemberNameCheck */ private int B3; private int C1; // ALLOW MemberName ON NEXT LINE private int C2; private int C3; private int D1; private int D2; // ALLOW MemberName ON PREVIOUS LINE private int D3; private static final int e1 = 0; private int E2; private int E3; // ALLOW ConstantName UNTIL THIS LINE+2 private static final int e4 = 0; private int E5; private static final int e6 = 0; private int E7; private int E8; /* ALLOW MemberName UNTIL THIS LINE-3 */ private static final int e9 = 0; // ALLOW Unused UNTIL THIS LINE+5 public static void doit1(int aInt) // this is +1 { } public static void doit2(int aInt) // this is +5 { } public static void doit3(int aInt) // this is +9 { } public void doit4() { try { // blah blah blah for(int i = 0; i < 10; i++) { // blah blah blah while(true) { try { // blah blah blah } catch(Exception e) { // bad bad bad } catch (Throwable t) { // ALLOW CATCH Throwable BECAUSE I threw this together. } } // blah blah blah } // blah blah blah } catch(Exception ex) { // ALLOW CATCH Exception BECAUSE I am an exceptional person. } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/Bug3553541.java100644 0 0 516 12022116142 26060 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; import java.util.List; import java.util.ArrayList; // Demonstrates the bug #3553541 class Bug3553541 { List a; { a = new ArrayList(); } List b; { b = new ArrayList(); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/EofBug1667137.java100644 0 0 543 12022104011 26507 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; // Demonstrates the bug #1667137 class EofBug1667137 { void checkstyleIsBroken() { EofBug1667137 borkage = new EofBug1667137() { T borked(T brokenness) { return brokenness; } }; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/InputEmbeddedNullChar.java100644 0 0 537 11451071614 30747 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; public class InputEmbeddedNullChar { public void doSomething() { // String below has an embedded null in it as well as char 036 repeated // twice - none of shich should cause a problem as they're all valid // UTF-8 String cctCxlMsg = ":ET:OE:}}"; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/InputGrammar.java100644 0 0 246 11451071614 27210 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; /** * Input for grammar test. */ public class InputGrammar { int İ = 1; // illegal, unless UTF-8 } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/InputHexFloat.java100644 0 0 555 11451071614 27337 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; /** * Input for hex float and double test. */ public class InputHexFloat { double f1 = 0x.0P10; double f2 = 0x1.P-1; double f3 = 0Xab1P0; double f4 = 0Xab1ap+20; double f5 = 0Xab1ap+20D; double f6 = 0Xab1ap+20d; double f7 = 0Xab1ap+20f; double f8 = 0Xab1ap+20F; } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/InputJava7Diamond.java100644 0 0 516 11631401072 30061 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; import java.util.*; public class InputJava7Diamond { HashMap map = new HashMap(); HashMap map2 = new HashMap<>(); HashMap> map3 = new HashMap<>(); ArrayList list = new ArrayList<>(); } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/InputJava7MultiCatch.java100644 0 0 1613 11631401072 30562 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; import java.io.*; /** * Input for Java 7 multi-catch. */ public class InputJava7MultiCatch { public static class CustomException extends Exception { } public static class AnotherCustomException extends Exception { } public static void logException(Exception e) { } public static void main(String[] args) { try { FileInputStream in = new FileInputStream("InputJava7MultiCatch.java"); throw new CustomException(); } catch (FileNotFoundException | CustomException e) { logException(e); } try { FileInputStream in = new FileInputStream("InputJava7MultiCatch.java"); throw new CustomException(); } catch (final FileNotFoundException | CustomException | test.foo.AnotherCustomException e) { logException(e); } } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/InputJava7NumericalLiterals.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/InputJava7NumericalLiterals.j100644 0 0 4547 11631401072 31465 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; /** * Input for Java 7 numerical literals. */ public class InputJava7NumericalLiterals { int i1 = 0b00011110; int i2 = 0B00011110; int i3 = 0xA; int i4 = 0x1___A_F; int i5 = 0b1; int i6 = 0b1___1_0; int i7 = 0; int i8 = 02; int i9 = 0_123; int i10 = 1; int i11 = 1___3; int i12 = 1_43_43598_7; long l1 = 0b00011110L; long l2 = 0B00011110l; long l3 = 0xAL; long l4 = 0x1___A_FL; long l5 = 0b1L; long l6 = 0b1___1_0L; long l7 = 0l; long l8 = 02L; long l9 = 0_123l; long l10 = 1l; long l11 = 1___3l; long l12 = 1_43_43598_7L; long l13 = 1_43_43598_7; // int promoted to long // the grammar considers floating point values to be of type "float" by default which is wrong, it should be "double". float f1 = .1f; float f2 = 1.; // double "downgraded" to float float f3 = 0f; float f4 = 1e0; // double "downgraded" to float float f5 = 1e0f; float f6 = 12.345F; float f7 = .5____2_1; // double "downgraded" to float float f8 = 1__42__3.; // double "downgraded" to float float f9 = 0__2_4__324f; float f10 = 1_34e0; // double "downgraded" to float float f11 = 1__1_2e0f; float f12 = 2_1___2.3__4_5F; float f13 = 1_34e0__4__3; // double "downgraded" to float float f14 = 1__1_2e00__000_4f; float f15 = 2_1___2.3__4_5e00______0_5F; double d1 = .1d; double d2 = 1.D; double d3 = 0d; double d4 = 1e0D; double d5 = 1e0d; double d6 = 12.345D; double d7 = .5____2_1d; double d8 = 1__42__3.D; double d9 = 0__2_4__324d; double d10 = 1_34e0d; double d11 = 1__1_2e0d; double d12 = 2_1___2.3__4_5D; double d13 = 1_34e0__4__3d; double d14 = 1__1_2e00__000_4d; double d15 = 2_1___2.3__4_5e00______0_5D; double d16 = 0.12___34; // "float" promoted to double float hf1 = 0x.1___AFp1; // double "downgraded" to float float hf2 = 0x.1___AFp0__0__0f; float hf3 = 0x2__3_34.4___AFP00_00f; double hd1 = 0x.1___AFp1; double hd2 = 0x.1___AFp0__0__0d; double hd3 = 0x2__3_34.4___AFP00_00d; int doc1 = 1234_5678; long doc2 = 1_2_3_4__5_6_7_8L; int doc3 = 0b0001_0010_0100_1000; double doc4 = 3.141_592_653_589_793d; double doc5 = 0x1.ffff_ffff_ffff_fP1_023; // Double.MAX_VALUE } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/InputJava7StringSwitch.java100644 0 0 626 11631401072 31140 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; /** * Input for Java 7 String in Switch. */ public class InputJava7StringSwitch { public static void main(String[] args) { String mystr = "value" + "2"; switch (mystr) { case "value1": break; case "value2": break; default: break; } } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/InputJava7TryWithResources.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/InputJava7TryWithResources.ja100644 0 0 2311 11636450517 31514 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; /** * Input for Java 7 try-with-resources. */ public class InputJava7TryWithResources { public static class MyResource implements AutoCloseable { @Override public void close() throws Exception { } } public static void main(String[] args) throws Exception { try (MyResource resource = new MyResource()) { } try (MyResource resource = new MyResource()) { } finally { } try (MyResource resource = new MyResource();) { } catch (Exception e) { } try (MyResource resource = new MyResource();) { } catch (Exception e) { } catch (Throwable t) { } finally { } try (MyResource resource = new MyResource(); MyResource resource2 = new MyResource()) { } catch (Exception e) { } catch (Throwable t) { } finally { } try (MyResource resource = new MyResource(); MyResource resource2 = new MyResource();) { } catch (Exception e) { } catch (Throwable t) { } finally { } try (@SuppressWarnings("all") final MyResource resource = new MyResource()) { } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/InputVararg.java100644 0 0 265 11451071614 27045 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; /** * Input for vararg test. */ public class InputVararg { public static void main(String... args) { } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/LineCommentAtTheEndOfFile.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/LineCommentAtTheEndOfFile.jav100644 0 0 165 11631376755 31333 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; public class LineCommentAtTheEndOfFile { } // EOF on this linecheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/grammars/UnicodeEscape.java100644 0 0 2012 11650673154 27332 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; /** * Input for unicode escapes. */ public class UnicodeEscape { char a = '\u005cr'; char b = '\u005cn'; char c = '\u005ct'; char d = '\uuuu005cn'; char e = '\u005c\u005c'; char f = '\u005c''; char g = '"'; String h = "\u005c""; String i = "'"; char j = '\"'; String k = "\'"; char l = '\u005C''; char m = '\uABCD'; char n = '\u00AB'; char o = '\u005B'; char p = '\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu005cr'; // Tests the lookahead char q = '\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu005D'; char wtf1 = '\u005c\u005c'; // This is a legal backslash String wtf2 = "\\u005c"; // = "\u005c", with a single backslash, and != a backslash! // There is an ambiguity in the grammar, the interpretation is done as "\\" + "u005c" //char wtf3 = '\\u005c'; // This is therefore, illegal //char z = '\u005cu005c'; /* This is illegal */ } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/header/H1.java100644 0 0 170 11451071614 24465 0ustar 0 0 /* * (C) 2006 correct header */ package com.puppycrawl.tools.checkstyle.checks.header; public class H1 { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/header/H1.properties100644 0 0 44 11451071614 25720 0ustar 0 0 # # (C) 2006 correct header # x=ycheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/header/H1.xml100644 0 0 120 11451071614 24337 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/header/H2.java100644 0 0 171 11451071614 24467 0ustar 0 0 /* * (C) '06 incorrect header */ package com.puppycrawl.tools.checkstyle.checks.header; public class H2 { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/header/H2.properties100644 0 0 3 11451071614 25674 0ustar 0 0 x=ycheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/header/H2.xml100644 0 0 113 11451071614 24342 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/import-control_broken.xml100644 0 0 317 11451071614 27177 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/import-control_complete.xml100644 0 0 1052 11451071614 27544 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/import-control_one-re.xml100644 0 0 777 11451071614 27116 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/import-control_one.xml100644 0 0 705 11451071614 26501 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/import-control_two-re.xml100644 0 0 1161 11451071614 27152 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/import-control_two.xml100644 0 0 1051 11451071614 26544 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/import-control_wrong.xml100644 0 0 333 11451071614 27051 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImport.java100644 0 0 5631 11631376755 27021 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.imports; import com.puppycrawl.tools.checkstyle.imports.*; import com.puppycrawl.tools.checkstyle.imports.GlobalProperties; import java.io.*; import java.lang.*; import java.lang.String; import java.sql.Connection; import java.util.List; import java.util.List; import sun.net.ftpclient.FtpClient; import java.util.Iterator; import java.util.Enumeration; import java.util.Arrays; import javax.swing.JToolBar; import javax.swing.JToggleButton; import javax.swing.ScrollPaneLayout; import javax.swing.BorderFactory; import static java.io.File.listRoots; import static javax.swing.WindowConstants.*; import static javax.swing.WindowConstants.*; import static java.io.File.createTempFile; import static sun.net.ftpclient.FtpClient.*; import java.awt.Component; import java.awt.Graphics2D; import java.awt.HeadlessException; import java.awt.Label; import java.util.Date; import java.util.Calendar; import java.util.BitSet; /** * Test case for imports * Here's an import used only by javadoc: {@link Date}. * @author Oliver Burn * @author lkuehne * @author Michael Studman * @see Calendar Should avoid unused import for Calendar **/ class InputImport { /** ignore **/ private Class mUse1 = Connection.class; /** ignore **/ private Class mUse2 = java.io.File.class; /** ignore **/ private Class mUse3 = Iterator[].class; /** ignore **/ private Class mUse4 = java.util.Enumeration[].class; /** usage of illegal import **/ private FtpClient ftpClient = null; /** usage via static method, both normal and fully qualified */ { int[] x = {}; Arrays.sort(x); Object obj = javax.swing.BorderFactory.createEmptyBorder(); File[] files = listRoots(); } /** usage of inner class as type */ private JToolBar.Separator mSep = null; /** usage of inner class in Constructor */ private Object mUse5 = new ScrollPaneLayout.UIRessource(); /** usage of inner class in constructor, fully qualified */ private Object mUse6 = new javax.swing.JToggleButton.ToggleButtonModel(); /** we use class name as member's name. * also an inline JavaDoc-only import {@link Vector linkText} */ private int Component; /** * method comment with JavaDoc-only import {@link BitSet#aMethod()} */ public void Label() {} /** * Renders to a {@linkplain Graphics2D graphics context}. * @throws HeadlessException if no graphis environment can be found. * @exception HeadlessException if no graphis environment can be found. */ public void render() {} } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportBug.java100644 0 0 434 11451071614 27415 0ustar 0 0 package com.puppycrawl.tools.checkstyle.imports; import java.net.URL; public class InputImportBug { private static String URL = "This is a String object"; public InputImportBug() throws Exception { URL url = new URL("file://this.is.a.url.object"); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportControl.java100644 0 0 321 11451071614 30313 0ustar 0 0 package com.puppycrawl.tools.checkstyle.imports; import java.awt.Image; import javax.swing.border.*; import java.io.File; import static java.awt.Button.ABORT; public class InputImportControl { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder.java100644 0 0 672 11451071614 27757 0ustar 0 0 import java.awt.Button; import java.awt.Frame; import java.awt.Dialog; import java.awt.event.ActionEvent; import static java.awt.Button.ABORT ; import javax.swing.JComponent; import javax.swing.JTable; import java.io.File; import static java.io.File.createTempFile; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import static javax.swing.WindowConstants.*; public class InputImportOrder { } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrderCaseInsensitive.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrderCaseInsensitiv100644 0 0 351 11451071614 31701 0ustar 0 0 import java.io.File; import java.io.InputStream; import java.io.IOException; import java.io.Reader; import static java.io.InputStream.*; import static java.io.IOException.*; public class InputImportOrderCaseInsensitive { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_Above.java100644 0 0 1030 11451071614 31100 0ustar 0 0 package com.puppycrawl.tools.checkstyle.imports; import static java.awt.Button.ABORT; import static javax.swing.WindowConstants.*; import static java.awt.Button.ABORT; import java.awt.Button; import java.awt.Frame; import java.awt.Dialog; import java.awt.event.ActionEvent; import javax.swing.JComponent; import javax.swing.JTable; import java.io.File; import static java.io.File.createTempFile; import java.io.IOException; import java.io.InputStream; import java.io.Reader; public class InputImportOrder_Above { }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_Bottom.java100644 0 0 1032 11451071614 31312 0ustar 0 0 package com.puppycrawl.tools.checkstyle.imports; import java.awt.Button; import java.awt.Dialog; import java.awt.Frame; import java.awt.event.ActionEvent; import java.io.IOException; import java.io.InputStream; import javax.swing.JComponent; import javax.swing.JTable; import static java.io.File.*; import java.io.File; import static java.io.File.createTempFile; import static java.awt.Button.ABORT; import static javax.swing.WindowConstants.*; import java.io.Reader; public class InputImportOrder_Bottom { }././@LongLink100644 0 0 161 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_HonorsTokensProperty.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_HonorsTokensP100644 0 0 404 11451071614 31664 0ustar 0 0 package com.puppycrawl.tools.checkstyle.imports; import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE; import static java.awt.Button.ABORT; import java.awt.Dialog; import java.awt.Button; public class InputImportOrder_HonorsTokensProperty { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_InFlow.java100644 0 0 1157 11451071614 31254 0ustar 0 0 package com.puppycrawl.tools.checkstyle.imports; import java.awt.Button; import static java.awt.Button.ABORT; import java.awt.Frame; import java.awt.Dialog; import java.awt.event.ActionEvent; import javax.swing.JComponent; import static javax.swing.WindowConstants.HIDE_ON_CLOSE; import static javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE; import static javax.swing.WindowConstants.*; import javax.swing.JTable; import static java.io.File.createTempFile; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; public class InputImportOrder_InFlow { }././@LongLink100644 0 0 171 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_NoFailureForRedundantImports.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_NoFailureForR100644 0 0 253 11451071614 31567 0ustar 0 0 package com.puppycrawl.tools.checkstyle.imports; import java.awt.Button; import java.awt.Button; public class InputImportOrder_NoFailureForRedundantImports { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_Top.java100644 0 0 1025 11451071614 30612 0ustar 0 0 package com.puppycrawl.tools.checkstyle.imports; import static java.io.File.createTempFile; import static java.awt.Button.ABORT; import static javax.swing.WindowConstants.*; import java.awt.Button; import java.awt.Dialog; import java.awt.Frame; import java.awt.event.ActionEvent; import java.io.IOException; import java.io.InputStream; import javax.swing.JComponent; import javax.swing.JTable; import static java.io.File.*; import java.io.File; import java.io.Reader; public class InputImportOrder_Top { }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_Under.java100644 0 0 1030 11451071614 31121 0ustar 0 0 package com.puppycrawl.tools.checkstyle.imports; import java.awt.Button; import java.awt.Frame; import java.awt.Dialog; import java.awt.event.ActionEvent; import javax.swing.JComponent; import javax.swing.JTable; import static java.awt.Button.ABORT; import static javax.swing.WindowConstants.*; import static java.awt.Button.ABORT; import static java.io.File.createTempFile; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; public class InputImportOrder_Under { }././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_Wildcard.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_Wildcard.java100644 0 0 536 11451071614 31567 0ustar 0 0 // groups are configured as follows // com.puppycrawl,*,java // the trailing javax.crypto.Cipher; should be flagged as an error. import com.puppycrawl.tools.checkstyle.imports.InputImportOrder_Above; import javax.crypto.BadPaddingException; import java.util.List; import javax.crypto.Cipher; public class InputImportOrder_Wildcard { } ././@LongLink100644 0 0 160 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_WildcardUnspecified.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/InputImportOrder_WildcardUnspe100644 0 0 605 11451071614 31657 0ustar 0 0 package com.puppycrawl.tools.checkstyle.imports; // groups are configured as follows // com.puppycrawl,*,java // the trailing javax.crypto.Cipher; should be flagged as an error. import java.io.File; import java.io.IOException; import java.util.Iterator; import com.puppycrawl.tools.checkstyle.imports.InputImportBug; public class InputImportOrder_WildcardUnspecified { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/imports/package-info.java100644 0 0 554 11451071614 27014 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Annotated package definition to check if import is declared unused // Created: 2005 //////////////////////////////////////////////////////////////////////////////// @MyAnnotation package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.MyAnnotation;checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputBraceAdjustment.java100644 0 0 1051 11451071614 31413 0ustar 0 0 /* * InputBraceAdjustment.java * * Created on February 21, 2003, 11:21 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputBraceAdjustment { /** Creates a new instance of InputBraceAdjustment */ public InputBraceAdjustment() { // sorry about the religious commentary... :) boolean uglyGnuStyle = true; if (uglyGnuStyle) { System.out.println("ugly GNU style braces"); } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputCaseLevel.java100644 0 0 771 11451071614 30173 0ustar 0 0 /* * InputCaseLevel.java * * Created on February 21, 2003, 11:15 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputCaseLevel { /** Creates a new instance of InputCaseLevel */ public InputCaseLevel() { int test = 4; switch (test) { case 4: break; case 2: break; default: break; } } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidArrayInitIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidArrayInitInden100644 0 0 4114 11451071614 31612 0ustar 0 0 /* * InputInvalidArrayInitIndent.java * * Created on December 9, 2002, 9:57 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputInvalidArrayInitIndent { int[] array = new int[] {1, 2, 3}; int[] arrayb = new int[] {1, 2, 3}; int[] arrayc = new int[] {1, 2, 3}; int[] array2 = new int[] { 1, 2, 3 }; int[] array2b = new int[] { 1, 2, 3 }; int[] array3 = new int[] { 1, 2, 3 }; int[] array4 = new int[] { 1, 2, 3 }; int[] array5 = new int[] {1, 2, 3}; int[] array6 = new int[] { 1, 2, 3, 4,}; int[] array7 = new int[] { 1, 2, 3 }; int[] array8 = new int[] { }; int[] array9 = new int[] { }; int[][] array10 = new int[][] { new int[] { 1, 2, 3}, new int[] { 1, 2, 3}, }; int[][] array10b = new int[][] { new int[] { 1, 2, 3}, new int[] { 1, 2, 3}, }; private void func1(int[] arg) { } /** Creates a new instance of InputValidArrayInitIndent */ public InputInvalidArrayInitIndent() { func1(new int[] { 1, 2, 3 }); } private static char[] sHexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private void myFunc3() { char[] sHexChars2 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] sHexChars3 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] sHexChars4 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidAssignIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidAssignIndent.j100644 0 0 1020 11451071614 31541 0ustar 0 0 public class InputInvalidAssignIndent { void foo(String[] args) { String line = mIndentCheck[ getLineNo()]; String line1 = getLine(); line1 = getLine(); int i = 1; // TODO: this should be illegal. i = 3; // TODO: add more testing } private String[] mIndentCheck = null; int getLineNo() { return 1; } String getLine() { return ""; } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidBlockIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidBlockIndent.ja100644 0 0 4106 11451071614 31520 0ustar 0 0 /* * InputValidBlockIndent.java * * Created on December 8, 2002, 12:06 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputInvalidBlockIndent { /** Creates a new instance of InputValidBlockIndent */ public InputInvalidBlockIndent() { } public void method1() { { } { } { } { } { } { } { int var = 3; var += 3; } { int var = 3; var += 3; } { int var = 5; } { int var = 3; var += 3; { int innerVar = 4; innerVar += var; } } { int var = 3; var += 3; { int innerVar = 4; innerVar += var; } } { int var = 3; var += 3; { int innerVar = 4; innerVar += var; } } } // static init at beginning of line is broken for now static { int var = 4; } static { int var = 4; } static { int var = 4; } static { int var = 4; } static { int var = 4; } static { int var = 4; } static { int var = 4; } static { int var = 4; } static { int var = 4; } static { int var = 4; } { int var = 4; } { int var = 4; } { int var = 4; } { int var = 4; } { int var = 4; } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidClassDefIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidClassDefIndent100644 0 0 7007 11451071614 31564 0ustar 0 0 /* * InputValidMethodIndent.java * * Created on November 11, 2002, 10:13 PM */ package com.puppycrawl.tools.checkstyle.indention; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; /** * * @author jrichard */ public class InputInvalidClassDefIndent extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } class InputInvalidClassDefIndentB extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } class InputInvalidClassDefIndentC { } class InputValidClassDefIndent2 extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } class InputValidClassDefIndent3 extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } final class InputValidClassDefIndent4 extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } final class InputValidClassDefIndent5 extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } final class InputValidClassDefIndent5b extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } class InputInvalidClassDefIndentc extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } final class InputValidClassDefIndent6 extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { class foo { } class fooBS { } class foo2 { public int x; } class foo3 { public int x; } class foo3b { public int x; } class foo4 { public int x; } class foo4c { public int x; } class foo4b { public int x; } private void myMethod() { class localFoo { } class localFoo1 { } class localFoo2 { int x; int func() { return 3; } } new JButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); new JButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); new JButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); new JButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = 2; } }); Object o = new ActionListener() { public void actionPerformed(ActionEvent e) { } }; myfunc2(10, 10, 10, myfunc3(11, 11, 11, 11), 10, 10, 10); } private void myfunc2(int a, int b, int c, int d, int e, int f, int g) { } private int myfunc3(int a, int b, int c, int d) { return 1; } } final class InputValidClassDefIndent4d extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidForIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidForIndent.java100644 0 0 2635 11451071614 31550 0ustar 0 0 /* * InputValidForIndent.java * * Created on November 10, 2002, 10:04 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputInvalidForIndent { /** Creates a new instance of InputValidForIndent */ public InputInvalidForIndent() { } private void method1() { for (int i=0; i<10; i++) { } for (int i=0; i<10; i++) { } for (int i=0; i<10; i++) { System.getProperty("foo"); } for (int i=0; i<10; i++) { boolean test = true; if (test) { // mixed styles are OK System.getProperty("foo"); } } for ( int i=0; i<10; i++) { } for ( int i=0; i<10; i++) { } for (int i=0; i<10; i++) { } for (int i=0; i<10 && 4<5 && 7<8; i++) { } for (int i=0; i<10; i++) { System.getProperty("foo"); } for (int i=0; i<10; i++ ) { System.getProperty("foo"); } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidIfIndent.java100644 0 0 12752 11451071614 31401 0ustar 0 0 /* * ValidIndent.java * * Created on November 6, 2002, 9:39 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputInvalidIfIndent { // ctor with rcurly on same line public InputInvalidIfIndent() { } // ctor with rcurly on next line public InputInvalidIfIndent(int dummy) { } // method with rcurly on same line public void method() { } // method with rcurly on next line public void method2() { } // method with a bunch of params public void method2(int x, int y, int w, int h) { } // params on multiple lines public void method2(int x, int y, int w, int h, int x1, int y1, int w1, int h1) { } // test ifs public void emptyIfTest() { boolean test = true; // lcurly on same line if (test) { } // lcurly on next line -- if, rcurly indented too far, lcurly not far enough // if (test) { } if (test) { } // lcurly for if and else on same line -- too much space after if on same line -- ALLOWED if (test) { } else { // this is not allowed } // lcurly for if and else on same line if (test) { } else { } // lcurly for if and else on same line -- mixed braces if (test) { } else { } // lcurly for if and else on same line -- mixed braces if (test) { } else { } // lcurly for if and else on same line -- mixed braces if (test) { } else { } // lcurly for if and else on same line -- mixed braces, unnested if (test) { } else { } } ///// same as above, with statements public void populatedIfTest() { boolean test = false; // no braces if if (test) System.getProperty("blah"); // no braces if/else if (test) System.getProperty("blah"); else System.getProperty("blah"); // lcurly on same line, and stmt if (test) { System.getProperty("blah"); } // lcurly on next line and stmt if (test) { System.getProperty("blah"); } // lcurly for if and else on same line if (test) { System. getProperty("blah"); } else { System. getProperty("blah"); } // lcurly for if and else on same line if (test) { System.getProperty("blah"); System.getProperty("blah"); } else { System.getProperty("blah"); System.getProperty("blah"); } // lcurly for if and else on same line -- mixed braces if (test) { System.getProperty("blah"); } else { System.getProperty("blah"); } // lcurly for if and else on same line -- mixed braces if (test) { System.getProperty("blah"); } else { System.getProperty("blah"); } // lcurly for if and else on same line -- mixed braces if (test) { System.getProperty("blah"); } else { System.getProperty("blah"); } // lcurly for if and else on same line -- mixed braces, unnested if (test) { System.getProperty("blah"); } else { System.getProperty("blah"); } if (test && 7 < 8 && 8 < 9 && 10 < 11) { } if (test) return; if (test) { } else if (7 < 8) { } else if (8 < 9) { } if (test) { System.getProperty("blah"); } else if (7 < 8) { System.getProperty("blah"); } else if (8 < 9) { System.getProperty("blah"); } if (test) System.getProperty("blah"); else if (7 < 8) System.getProperty("blah"); else if (8 < 9) System.getProperty("blah"); // TODO: bother to support this style? if (test) { System.getProperty("blah"); } else if (7 < 8) { System.getProperty("blah"); } else if (8 < 9) { System.getProperty("blah"); } if (test) { System.getProperty("blah"); } } public void parenIfTest() { boolean test = true; if (test ) { System.getProperty("blah"); } if (test ) { System.getProperty("blah"); } if ( test ) { System.getProperty("blah"); } } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidLabelIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidLabelIndent.ja100644 0 0 1655 11451071614 31513 0ustar 0 0 /* * InputInvalidLabelIndent.java * * Created on February 22, 2003, 12:11 AM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputInvalidLabelIndent { /** Creates a new instance of InputInvalidLabelIndent */ public InputInvalidLabelIndent() { boolean test = true; while (test) { label: System.out.println("label test"); if (test) { unusedLabel: System.out.println("more testing"); } } label2: System.out.println("toplevel"); label3: System.out.println("toplevel"); System.out.println("toplevel"); label4: System.out.println("toplevel"); label5: System .out. println("toplevel"); } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidMethodIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidMethodIndent.j100644 0 0 7333 11451071614 31552 0ustar 0 0 /* * InputInalidMethodIndent.java * * Created on November 11, 2002, 10:14 PM */ package com.puppycrawl.tools.checkstyle.indentation; import java.util.Arrays; /** * * @author jrichard */ public class InputInvalidMethodIndent { /** Creates a new instance of InputInalidMethodIndent */ public InputInvalidMethodIndent() { } // ctor with rcurly on next line public InputInvalidMethodIndent(int dummy) { } // method with rcurly on same line public void method() { } // method with rcurly on next line public void method2() { } // method with a bunch of params public int method2(int x, int y, int w, int h) { return 1; } // params on multiple lines public void method2(int x, int y, int w, int h, int x1, int y1, int w1, int h1) { } // params on multiple lines public void method3(int x, int y, int w, int h, int x1, int y1, int w1, int h1) { System.getProperty("foo"); } // params on multiple lines public void method4(int x, int y, int w, int h, int x1, int y1, int w1, int h1) { boolean test = true; if (test) { System.getProperty("foo"); } } public final void method5() { boolean test = true; if (test) { System.getProperty("foo"); } } public final void method6() { boolean test = true; if (test) { System.getProperty("foo"); } } public InputInvalidMethodIndent(int dummy, int dummy2) { System.getProperty("foo"); } void method6a() { boolean test = true; if (test) { System.getProperty("foo"); } System.out.println("methods are: " + Arrays.asList( new String[] {"method"}).toString()); System.out.println("methods are: " + Arrays.asList( new String[] {"method"}).toString()); System.out.println("methods are: " + Arrays.asList( new String[] {"method"}).toString()); System.out.println("methods are: " + Arrays.asList( new String[] {"method"}).toString()); String blah = (String) System.getProperty( new String("type")); String blah1 = (String) System.getProperty( new String("type") ); System.out.println("methods are: " + Arrays.asList( new String[] {"method"}).toString() ); } private void myfunc2(int a, int b, int c, int d, int e, int f, int g) { } private int myfunc3(int a, int b, int c, int d) { return 1; } private void myMethod() { myfunc2(3, 4, 5, 6, 7, 8, 9); myfunc2(3, 4, method2(3, 4, 5, 6) + 5, 6, 7, 8, 9); // TODO: this is not illegal, but probably should be // myfunc3(11, 11, Integer. // getInteger("mytest").intValue(), // 11); System.out.toString() .equals("blah"); } private void myFunc() throws Exception { } void method7() { // return incorrectly indented return; } void method8() { // thow invorrectly indented throw new RuntimeException(""); } public int[] method9() { return null; } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidSwitchIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidSwitchIndent.j100644 0 0 3514 11451071614 31570 0ustar 0 0 /* * InputValidSwitchIndent.java * * Created on November 27, 2002, 11:40 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputInvalidSwitchIndent { private static final int CONST = 5; private static final int CONST2 = 2; private static final int CONST3 = 3; /** Creates a new instance of InputInvalidSwitchIndent */ public InputInvalidSwitchIndent() { } private void method1() { int s = 3; switch (s) { case 4: System.out.println(""); break; case CONST: break; case CONST2: case CONST3: break; default: System.out.println(""); break; } // some people like to add curlys to their cases: switch (s) { case 4: { System.out.println(""); break; } case CONST2: case CONST3: { System.out.println(""); break; } case 22: { System.out.println(""); break; } } // check broken 'case' lines switch (s) { case CONST: break; case CONST2: case CONST3: { System.out.println(""); break; } } switch (s) { } switch (s) { } switch (s) { } } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidTryIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidTryIndent.java100644 0 0 3253 11451071614 31575 0ustar 0 0 /* * InputInvalidTryIndent.java * * Created on December 31, 2002, 7:18 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputInvalidTryIndent { /** Creates a new instance of InputInvalidTryIndent */ public InputInvalidTryIndent() { } public void method() { try { } catch (Throwable t) { System.out.println("err"); } try { System.out.println("test"); } finally { System.out.println("finally"); } try { } catch (Throwable t) { System.out.println("err"); } finally { } try { } catch (Exception t) { System.out.println("err"); } catch (Throwable t) { System.out.println("err"); } try { } catch (Exception t) { } catch (Throwable t) { } try { System.out.println("try"); } catch (Exception t) { System.out.println("err"); System.out.println("err"); System.out.println("err"); } catch (Throwable t) { System.out.println("err"); } finally { } try { System.out.println("try"); } catch (Exception t) { System.out.println("err"); System.out.println("err"); } catch (Throwable t) { System.out.println("err"); } finally { } } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidWhileIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputInvalidWhileIndent.ja100644 0 0 3503 11451071614 31536 0ustar 0 0 /* * InputValidWhileIndent.java * * Created on November 10, 2002, 9:16 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputInvalidWhileIndent { /** Creates a new instance of InputValidWhileIndent */ public InputInvalidWhileIndent() { } private void method1() { boolean test = true; while (test) { } while (test) { } while (test) { System.getProperty("foo"); } while (test) { System.getProperty("foo"); } while (test) { System.getProperty("foo"); System.getProperty("foo"); } while (test) { System.getProperty("foo"); System.getProperty("foo"); } while (test) { // TODO: this is allowed if (test) { System.getProperty("foo"); } System.getProperty("foo"); } while (test && 4 < 7 && 8 < 9 && 3 < 4) { } while (test && 4 < 7 && 8 < 9 && 3 < 4) { } while (test && 4 < 7 && 8 < 9 && 3 < 4) { } while (test && 4 < 7 && 8 < 9 && 3 < 4 ) { } while (test && 4 < 7 && 8 < 9 && 3 < 4 ) { } while (test && 4 < 7 && 8 < 9 && 3 < 4 ) { } while (true) { continue; } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputUseTabs.java100644 0 0 646 11451071614 27677 0ustar 0 0 /* * InputUseTabs.java * * Created on December 24, 2002, 10:28 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputUseTabs { /** Creates a new instance of InputUseTabs */ public InputUseTabs() { boolean test = true; if (test) { while ( test == false) { System.exit(2); } } System.exit(3); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputUseTwoSpaces.java100644 0 0 1421 11451071614 30726 0ustar 0 0 /* * InputUseTabs.java * * Created on December 24, 2002, 10:28 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputUseTwoSpaces { /** Creates a new instance of InputUseTabs */ public InputUseTwoSpaces() { boolean test = true; if (test) { while ( test == false) { System.exit(2); } } System.exit(3); } } class Test { public static void main(String[] args) { System.out.println(" Hello" + new Object() { public String toString() { return "World"; } }); new Object() .toString() .toString() .toString() .toString() .toString(); } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidArrayInitIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidArrayInitIndent.100644 0 0 4351 11451071614 31530 0ustar 0 0 /* * InputValidArrayInitIndent.java * * Created on December 9, 2002, 9:57 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputValidArrayInitIndent { private static char[] sHexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int[] array = new int[] {1, 2, 3}; int[] array2 = new int[] { 1, 2, 3 }; int[] array3 = new int[] { 1, 2, 3 }; int[] array4 = new int[] { 1, 2, 3 }; int[] array5 = new int[] {1, 2, 3}; // check nesting on first line int[] array6 = new int[] { 1, 2, 3 }; int[] array6a = new int[] { 1, 2, 3, 4}; // nesting int[] array7 = new int[] { 1, 2, 3 }; String[][] mStuff = new String[][] { { "key", "value" } }; String[][] mStuff1 = new String[][] { { "key", "value" } }; int[] array8 = new int[] { }; int[] array9 = new int[] { }; int[][] array10 = new int[][] { new int[] { 1, 2, 3}, new int[] { 1, 2, 3}, }; int[][] array10b = new int[][] { new int[] { 1, 2, 3}, new int[] { 1, 2, 3}, }; private void func1(int[] arg) { char[] sHexChars2 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] sHexChars3 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] sHexChars4 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; } /** Creates a new instance of InputValidArrayInitIndent */ public InputValidArrayInitIndent() { func1(new int[] {1, 2}); func1(new int[] {}); func1(new int[] { 1, 2, 3 }); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidAssignIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidAssignIndent.jav100644 0 0 2663 11451071614 31557 0ustar 0 0 public class InputValidAssignIndent { void foo(String[] args) { int i = 1 + 2 + 3; String line = mIndentCheck[ getLineNo()]; String line1 = getLine(); line1 = getLine(); int i1 = 1; i = 3; Integer brace = (candidate == SLIST) ? candidate : null; AnInterfaceFooWithALongName f = new AnInterfaceFooWithALongName() { public void bar() { } }; AnInterfaceFooWithALongName f1 = new AnInterfaceFooWithALongName() { public void bar() { } }; // XXX: need to be fixed // function.lastArgument().candidate = parameters; // function.lastArgument().candidate // = // parameters; // TODO: add more testing } private interface AnInterfaceFooWithALongName { void bar(); } private static final int SLIST = 1; private static final int parameters = 1; int candidate = 0; private String[] mIndentCheck = null; private InputValidAssignIndent function = null; int getLineNo() { return 1; } String getLine() { return ""; } InputValidAssignIndent lastArgument() { return this; } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidBinaryOpIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidBinaryOpIndent.j100644 0 0 3071 11451071614 31521 0ustar 0 0 /* * InputValidBinaryOpIndent.java * * Created on December 2, 2002, 10:24 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputValidBinaryOpIndent { /** Creates a new instance of InputValidBinaryOpIndent */ public InputValidBinaryOpIndent() { } private void method1() { boolean test = true; int i, j, k = 4; int x = 4; int y = 7; i = x + k; j = y + x + k; int one = 1, two = 2, three = 3, four = 4; int answer; answer = (one + one) / 2; answer = (one + one) / 2; answer = (one + one) / 2; answer = (one + one) / 2; answer = ((one + one) / 2) + 4; if (one + one == two) { System.out.println("true"); } if (one + one == two) { } if (one + one == two && 1 + 1 == two) { } if (one + one == two && 1 + 1 == two) { } if ((one + one) == two && (1 + 1) == two) { } if ((one + one) == two && (1 + 1) == two) { } if ((one + one) == two && (1 + 1) == two) { } } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidBlockIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidBlockIndent.java100644 0 0 6101 11451071614 31515 0ustar 0 0 /* * InputValidBlockIndent.java * * Created on December 8, 2002, 12:06 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputValidBlockIndent { /** Creates a new instance of InputValidBlockIndent */ public InputValidBlockIndent() { } public void method1() { { } { } { int var = 3; var += 3; } { int var = 5; } { int var = 3; var += 3; { int innerVar = 4; innerVar += var; } } } static { int var = 4; } static { int var = 4; } static { int var = 4; } { int var = 4; } { int var = 4; } { int var = 4; } } enum EquivalenceTester { /** * An equivalence tester that decides based on {@link Object#equals(Object) equals}. */ OBJECT_ATTRIBUTES { /** * {@inheritDoc} */ public boolean areEqual( final Object first, final Object second ) { return true; } /** * {@inheritDoc} */ public int hashCode( final Object target ) { return 1; } }, /** * An equivalence tester that decides based on {@code ==}. */ OBJECT_IDENTITIES { /** * {@inheritDoc} */ public boolean areEqual( final Object first, final Object second ) { return first == second; } /** * {@inheritDoc} */ public int hashCode( final Object target ) { return System.identityHashCode( target ); } }; /** * Tells whether the two given objects are considered equivalent. * * @param first first comparand * @param second second comparand * @return whether {@code first} and {@code second} are considered equivalent */ public abstract boolean areEqual( Object first, Object second ); /** * Computes a hash code for the given object. * * @param target object to compute a hash for * @return the computed hash */ public abstract int hashCode( Object target ); } class bug1251988 { private int a; // non static initializer { if (a == 1) { } } } class bug1260079 { public bug1260079() { new Thread() { public void run() { System.out.println("ran"); } }.start(); } } class bug1336737 { private static enum Command { IMPORT("import"), LIST("list"); private final String c; Command(String c) { this.c = c; } public String toString() { return c; } } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidClassDefIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidClassDefIndent.j100644 0 0 6601 11451071614 31464 0ustar 0 0 /* * InputValidMethodIndent.java * * Created on November 11, 2002, 10:13 PM */ package com.puppycrawl.tools.checkstyle.indentation; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; /** * * @author jrichard */ public class InputValidClassDefIndent extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } class InputValidClassDefIndent2 extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } class InputValidClassDefIndent3 extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } final class InputValidClassDefIndent4 extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } final class InputValidClassDefIndent4a extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } final class InputValidClassDefIndent5 extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { } final class InputValidClassDefIndent6 extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { class foo { } class foo2 { public int x; } class foo3 { public int x; } class foo4 { public int x; } private void myMethod() { class localFoo { } class localFoo2 { int x; int func() { return 3; } } // TODO: this is broken right now: // 1) this is both an expression and an OBJBLOCK // 2) methods aren't yet parsed // 3) only CLASSDEF is handled now, not OBJBLOCK new JButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); new JButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = 2; } }); Object o = new ActionListener() { public void actionPerformed(ActionEvent e) { } }; myfunc2(10, 10, 10, myfunc3(11, 11, 11, 11), 10, 10, 10); } private void myfunc2(int a, int b, int c, int d, int e, int f, int g) { } private int myfunc3(int a, int b, int c, int d) { return 1; } /** The less than or equal operator. */ public static final Operator LT_OR_EQUAL = new Operator( "<=", new OperatorHelper() { public boolean compare(int value1, int value2) { return (value1 <= value2); } public boolean compare(Comparable obj1, Comparable obj2) { return (obj1.compareTo(obj2) <= 0); } }); } class HashingContainer { @Deprecated public Object[] table; @Override public String toString() { return ""; } } class Operator { public Operator(String str, OperatorHelper handler) { } } class OperatorHelper { } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidCommaIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidCommaIndent.java100644 0 0 1707 11451071614 31526 0ustar 0 0 /* * InputValidCommaIndent.java * * Created on December 1, 2002, 2:20 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputValidCommaIndent { /** Creates a new instance of InputValidCommaIndent */ public InputValidCommaIndent() { } public void method1(int x, int y, int z) { boolean test = true; int i, j = 2, k = 4, l, m = 4; boolean longVarName = true; boolean myotherLongVariableName = false; if (j == 2 || longVarName == true || myotherLongVariableName == true || myotherLongVariableName == false || longVarName == true) { } if ((j == 2 && k == 3) || test) { System.out.println("test"); } } public void method1(int a, int x, int y, int z) { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidDotIndent.java100644 0 0 4270 11451071614 31216 0ustar 0 0 /* * InputValidDotIndent.java * * Created on November 24, 2002, 1:22 PM */ package com.puppycrawl.tools.checkstyle.indentation; import javax. swing. border. AbstractBorder; import javax .swing .border .BevelBorder; import javax.swing.plaf.metal.MetalButtonUI; /** * * @author jrichard */ public class InputValidDotIndent { /** Creates a new instance of InputValidDotIndent */ public InputValidDotIndent() { System.out.println(); System. out.println(); System.out. println(); System. out. println(); System .out .println(); BevelBorder border = new javax.swing.border.BevelBorder(BevelBorder.LOWERED); border = new javax.swing.border. BevelBorder(BevelBorder.LOWERED); border = new javax.swing.border.BevelBorder( BevelBorder.LOWERED); border = new javax. swing. border. BevelBorder(BevelBorder.LOWERED); border = new javax. swing .border .BevelBorder(BevelBorder.LOWERED); border = new javax. swing .border .BevelBorder(BevelBorder. LOWERED); Class c = javax.swing. plaf.metal.MetalButtonUI.class; Class c1 = javax.swing .plaf.metal.MetalButtonUI.class; Class c2 = javax.swing .plaf.metal. MetalButtonUI.class; Class c3 = javax.swing .plaf.metal .MetalButtonUI.class; Class c4 = javax. swing.plaf.metal. MetalButtonUI.class; border = new javax. swing .border.BevelBorder(BevelBorder. LOWERED); } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidDoWhileIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidDoWhileIndent.ja100644 0 0 3132 11451071614 31470 0ustar 0 0 /* * InputvalidDoWhileIndent.java * * Created on December 8, 2002, 9:05 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputValidDoWhileIndent { public InputValidDoWhileIndent() { } public void method1() { boolean test = true; do System.getProperty("foo"); while (test) ; do System.getProperty("foo"); while (test); do { } while (test); do { } while (test); do { System.getProperty("foo"); } while (test); do { System.getProperty("foo"); } while (test); do { System.getProperty("foo"); } while (test); do { System.getProperty("foo"); System.getProperty("foo"); } while (test); do { System.getProperty("foo"); System.getProperty("foo"); } while (test); do { if (test) { System.getProperty("foo"); } System.getProperty("foo"); } while (test); do System.getProperty("foo"); while (test); if (test) { do System.getProperty("foo"); while (test); } do { } while (test && 7 < 8 && 5 < 6 && 9 < 10); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidForIndent.java100644 0 0 3225 11451071614 31215 0ustar 0 0 /* * InputValidForIndent.java * * Created on November 10, 2002, 10:04 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputValidForIndent { /** Creates a new instance of InputValidForIndent */ public InputValidForIndent() { } private void method1(int[] indices) { for (int i=0; i<10; i++) System.getProperty("foo"); for (int i=0; i<10; i++) System.getProperty("foo"); for (int i=0; i<10; i++) { } for (int i=0; i<10; i++) { } for (int i=0; i<10; i++) { System.getProperty("foo"); } for (int i=0; i<10; i++) { boolean test = true; if (test) { // mixed styles are OK System.getProperty("foo"); } } for ( int i=0; i<10; i++) { } for (int i=0; i<10 && 4<5 && 7<8; i++) { } for (int i=0; i<10 && 4<5 && 7<8; i++) { } for (int i=0; i<10 && 4<5 && 7<8; i++) { } for (int i=0; i<10; i++ ) { System.getProperty("foo"); } for ( final int index : indices ) { System.err.println(index); } for ( final int index : indices ) { System.err.println(index); } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidIfIndent.java100644 0 0 11552 11451071614 31047 0ustar 0 0 /* * ValidIndent.java * * Created on November 6, 2002, 9:39 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputValidIfIndent { // test ifs public void emptyIfTest() { boolean test = true; // lcurly on same line if (test) { } // lcurly on next line if (test) { } // lcurly for if and else on same line if (test) { } else { } // lcurly for if and else on same line if (test) { } else { } // lcurly for if and else on same line -- mixed braces if (test) { } else { } // lcurly for if and else on same line -- mixed braces if (test) { } else { } // lcurly for if and else on same line -- mixed braces if (test) { } else { } // lcurly for if and else on same line -- mixed braces, unnested if (test) { } else { } if (foo() || test || test) { } } ///// same as above, with statements public void populatedIfTest() { boolean test = false; // no braces if if (test) System.getProperty("blah"); // no braces if/else if (test) System.getProperty("blah"); else System.getProperty("blah"); // lcurly on same line, and stmt if (test) { System.getProperty("blah"); } // lcurly on next line and stmt if (test) { System.getProperty("blah"); } // lcurly for if and else on same line if (test) { System.getProperty("blah"); } else { System. getProperty("blah"); } // lcurly for if and else on same line if (test) { System.getProperty("blah"); System.getProperty("blah"); } else { System.getProperty("blah"); } // lcurly for if and else on same line -- mixed braces if (test) { System.getProperty("blah"); } else { System.getProperty("blah"); } // lcurly for if and else on same line -- mixed braces if (test) { System.getProperty("blah"); } else { System.getProperty("blah"); } // lcurly for if and else on same line -- mixed braces if (test) { System.getProperty("blah"); } else { System.getProperty("blah"); } // lcurly for if and else on same line -- mixed braces, unnested if (test) { System.getProperty("blah"); } else { System.getProperty("blah"); } if (test) System.getProperty("blah"); if (test) System.getProperty("blah"); else System.getProperty("foo"); if (test) System.getProperty("blah"); else System.getProperty("foo"); if (test) System.getProperty("blah"); else System.getProperty("foo"); if (test && 7 < 8 && 8 < 9 && 10 < 11) { } if (test) return; if (test) { } else if (7 < 8) { } else if (8 < 9) { } if (test) { System.getProperty("blah"); } else if (7 < 8) { System.getProperty("blah"); } else if (8 < 9) { System.getProperty("blah"); } if (test) System.getProperty("blah"); else if (7 < 8) System.getProperty("blah"); else if (8 < 9) System.getProperty("blah"); // TODO: bother to support this style? if (test) { System.getProperty("blah"); } else if (7 < 8) { System.getProperty("blah"); } else if (8 < 9) { System.getProperty("blah"); } } public void parenIfTest() { boolean test = true; if (test ) { System.getProperty("blah"); } // if (test ) { System.getProperty("blah"); } if ( test ) { System.getProperty("blah"); } if (test ) { } } boolean foo() { return true; } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidInterfaceDefIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidInterfaceDefInde100644 0 0 746 11451071614 31511 0ustar 0 0 /* * InputValidInterfaceDefIndent.java * * Created on December 12, 2002, 12:05 AM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public interface InputValidInterfaceDefIndent { void myfunc(); interface myInterface2 { } public interface myInterface3 extends myInterface2 { } public interface myInterface4 extends myInterface2 { void myFunc2(); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidLabelIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidLabelIndent.java100644 0 0 1246 11451071614 31507 0ustar 0 0 /* * InputValidLabelIndent.java * * Created on February 21, 2003, 11:28 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputValidLabelIndent { /** Creates a new instance of InputValidLabelIndent */ public InputValidLabelIndent() { boolean test = true; while (test) { label: System.out.println("label test"); if (test) { unusedLabel: System.out.println("more testing"); } } label2: System.out.println("toplevel"); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidMethodIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidMethodIndent.jav100644 0 0 10774 11451071614 31575 0ustar 0 0 /* * InputValidMethodIndent.java * * Created on November 11, 2002, 10:13 PM */ package com.puppycrawl.tools.checkstyle.indentation; import java.util.Arrays; /** * * @author jrichard */ public class InputValidMethodIndent extends java.awt.event.MouseAdapter implements java.awt.event.MouseListener { // ctor with rcurly on same line public InputValidMethodIndent() { } private InputValidMethodIndent(boolean test) { boolean test2 = true; int i = 4 + 4; } private InputValidMethodIndent(boolean test, boolean test2) { boolean test3 = true; int i = 4 + 4; } private InputValidMethodIndent(boolean test, boolean test2, boolean test3) { boolean test4 = true; int i = 4 + 4; } // ctor with rcurly on next line public InputValidMethodIndent(int dummy) { } // method with rcurly on same line public String method1() { return "hi"; } // method with rcurly on next line public void method2() { } // method with a bunch of params public int method2(int x, int y, int w, int h) { return 1; } // params on multiple lines public void method2(int x, int y, int w, int h, int x1, int y1, int w1, int h1) { } // params on multiple lines public void method3(int x, int y, int w, int h, int x1, int y1, int w1, int h1) { System.getProperty("foo"); } // params on multiple lines public void method4(int x, int y, int w, int h, int x1, int y1, int w1, int h1) { boolean test = true; int i = 4 + 4; i += 5; i += 5 + 4; if (test) { System.getProperty("foo"); } else { System.getProperty("foo"); } for (int j=0;j<10; j++) { System.getProperty("foo"); } myfunc2(10, 10, 10, myfunc3(11, 11, 11, 11), 10, 10, 10); myfunc3(11, 11, Integer. getInteger("mytest").intValue(), 11); myfunc3( 1, 2, 3, 4); } // strange IMHO, but I suppose this should be allowed public void method5() { } private void myfunc2(int a, int b, int c, int d, int e, int f, int g) { } private int myfunc3(int a, int b, int c, int d) { return 1; } void method6() { System.out.println("methods are: " + Arrays.asList( new String[] {"method"}).toString()); System.out.println("methods are: " + Arrays.asList( new String[] {"method"} ).toString()); System.out.println("methods are: " + Arrays.asList( new String[] {"method"}).toString() ); myfunc2(3, 4, 5, 6, 7, 8, 9); myfunc2(3, 4, method2(3, 4, 5, 6) + 5, 6, 7, 8, 9); System.out.println("methods are: " + Arrays.asList( new String[] {"method"}).toString()); System.out.println("methods are: " + Arrays.asList( new String[] {"method"}).toString()); String blah = (String) System.getProperty( new String("type")); System.out.println(method1() + "mytext" + " at indentation level not at correct indentation, " + method1()); System.out.println( method1() + "mytext" + " at indentation level not at correct indentation, " + method1()); System.out.toString() .equals("blah"); if (!areOnSameLine((DetailAST)aChild.expr.getFirstChild(), (DetailAST) expr.getFirstChild())) { } if (System.out.write(new byte[0], 0, 0)) { System.out.println("blah"); } } private void myFunc() throws Exception { } private void myFunc() throws Exception { } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidSwitchIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidSwitchIndent.jav100644 0 0 4005 11451071614 31564 0ustar 0 0 /* * InputValidSwitchIndent.java * * Created on November 27, 2002, 11:40 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputValidSwitchIndent { private static final int CONST = 5; private static final int CONST2 = 2; private static final int CONST3 = 3; /** Creates a new instance of InputValidSwitchIndent */ public InputValidSwitchIndent() { } private void method1() { int s = 3; switch (s) { case 4: System.out.println(""); break; case CONST: break; case CONST2: case CONST3: break; default: System.out.println(""); break; } // some people like to add curlys to their cases: switch (s) { case 4: { System.out.println(""); break; } case CONST: break; case CONST2: case CONST3: { System.out.println(""); break; } default: break; } // check broken 'case' lines switch (s) { case 4: { System.out.println(""); break; } case CONST: break; case CONST2: case CONST3: { System.out.println(""); break; } default: break; } switch (s) { } switch (s) { default: System.out.println(""); break; } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidTryIndent.java100644 0 0 3233 11451071614 31244 0ustar 0 0 /* * InputValidTryIndent.java * * Created on December 31, 2002, 6:56 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputValidTryIndent { /** Creates a new instance of InputValidTryIndent */ public InputValidTryIndent() { } public void method() { try { } catch (Throwable t) { System.out.println("err"); } try { System.out.println("test"); } finally { System.out.println("finally"); } try { } catch (Throwable t) { System.out.println("err"); } finally { } try { } catch (Exception t) { System.out.println("err"); } catch (Throwable t) { System.out.println("err"); } try { } catch (Exception t) { } catch (Throwable t) { } try { System.out.println("try"); } catch (Exception t) { System.out.println("err"); System.out.println("err"); } catch (Throwable t) { System.out.println("err"); } finally { } try { System.out.println("try"); } catch (Exception t) { System.out.println("err"); System.out.println("err"); } catch (Throwable t) { System.out.println("err"); } finally { } } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidTryResourcesIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidTryResourcesInde100644 0 0 1211 11652742176 31662 0ustar 0 0 package com.puppycrawl.tools.checkstyle.indentation; import java.io.FileInputStream; import java.io.IOException; import java.util.jar.JarInputStream; import java.util.jar.Manifest; // Forcing a commit class InputValidTryResourcesIndent { // Taken from JDK7 java.lang.Package src code. private static Manifest loadManifest(String fn) { try (FileInputStream fis = new FileInputStream(fn); // This should be an error JarInputStream jis = new JarInputStream(fis, false)) { return jis.getManifest(); } catch (IOException e) { return null; } } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidWhileIndent.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidWhileIndent.java100644 0 0 2742 11451071614 31542 0ustar 0 0 /* * InputValidWhileIndent.java * * Created on November 10, 2002, 9:16 PM */ package com.puppycrawl.tools.checkstyle.indentation; /** * * @author jrichard */ public class InputValidWhileIndent { /** Creates a new instance of InputValidWhileIndent */ public InputValidWhileIndent() { } private void method1() { boolean test = true; while (test) System.getProperty("foo"); while (test) System.getProperty("foo"); while (test) { } while (test) { } while (test) { System.getProperty("foo"); } while (test) { System.getProperty("foo"); } while (test) { System.getProperty("foo"); System.getProperty("foo"); } while (test) { System.getProperty("foo"); System.getProperty("foo"); } while (test) { if (test) { System.getProperty("foo"); } System.getProperty("foo"); } while (test) System.getProperty("foo"); if (test) { while (test) System.getProperty("foo"); } while (test && 4 < 7 && 8 < 9 && 3 < 4) { } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/Input15Extensions.java100644 0 0 1030 11451071613 26325 0ustar 0 0 // someexamples of 1.5 extensions @interface MyAnnotation1 { String name(); int version(); } @MyAnnotation1(name = "ABC", version = 1) public class Input15Extensions { } enum Enum1 { A, B, C; Enum1() {} public String toString() { return ""; //some custom implementation } } interface TestRequireThisEnum { enum DAY_OF_WEEK { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputAnonInnerLength.java100644 0 0 7167 11451071613 27072 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2002 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.awt.event.MouseEvent; import java.awt.event.MouseAdapter; import javax.swing.JButton; /** * Tests for length of anonymous inner types * @author Rob Worth * @author Lars Kühne **/ public class InputAnonInnerLength { /** * Check that instantiations of normal classes work OK. */ private JButton mButton = new JButton(); private class MyInner { private MyInner(int[] anArray) { } } /** * the AnonInnerLengthCheck works with 'new' and RCURLY - check that * it will not confuse constructors calls with array params with * anon inners. */ private MyInner myInner = new MyInner(new int[]{ // make the array span multiple lines 1, 2, 3, 4, 5, 6, 7, } ); /** anon inner in member variable initialization which is 21 lines long */ private Runnable mRunnable1 = new Runnable() { public void run() // should not have to be documented, class is anon. { System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); } }; /** anon inner in member variable initialization which is 20 lines long */ private Runnable mRunnable2 = new Runnable() { public void run() // should not have to be documented, class is anon. { System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); System.out.println("running"); } }; /** anon inner in constructor. */ InputAnonInnerLength() { mButton.addMouseListener( new MouseAdapter() { public void mouseClicked( MouseEvent aEv ) { System.out.println("click"); } } ); } /** anon inner in method */ public void addInputAnonInner() { mButton.addMouseListener( new MouseAdapter() { public void mouseClicked( MouseEvent aEv ) { System.out.println("click"); } } ); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputArrayTrailingComma.java100644 0 0 1265 11451071613 27557 0ustar 0 0 package com.puppycrawl.tools.checkstyle; public class InputArrayTrailingComma { int[] a1 = new int[] { 1, 2, 3, }; int[] a2 = new int[] { 1, 2, 3 }; int[] b1 = new int[] {1, 2, 3,}; int[] b2 = new int[] {1, 2, 3}; int[][] c1 = new int[][] {{1, 2,}, {3, 3,}, {5, 6,},}; int[][] c2 = new int[][] {{1, 2}, {3, 3,}, {5, 6,}}; int[][] d1 = new int[][] { {1, 2,}, {3, 3,}, {5, 6,}, }; int[][] d2 = new int[][] { {1, 2}, {3, 3,}, {5, 6,} }; int[] e1 = new int[] { }; } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputArrayTypeStyle.java100644 0 0 2176 11451071613 26775 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for ArrayTypeStyle (Java vs C) * @author lkuehne **/ public class InputArrayTypeStyle { private int[] javaStyle = new int[0]; private int cStyle[] = new int[0]; public static void mainJava(String[] aJavaStyle) { } public static void mainC(String aCStyle[]) { final int[] blah = new int[0]; final boolean isOK1 = aCStyle instanceof String[]; final boolean isOK2 = aCStyle instanceof java.lang.String[]; final boolean isOK3 = blah instanceof int[]; } public class Test { public Test[] variable; public Test[] getTests() { // we shouldn't check methods because there is no alternatives. return null; } public Test[] getNewTest() { return null; } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputBraces.java100644 0 0 4634 11451071613 25234 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for correct use of braces. * @author Oliver Burn **/ class InputBraces { /** @return helper func **/ boolean condition() { return false; } /** Test do/while loops **/ void testDoWhile() { // Valid do { testDoWhile(); } while (condition()); // Invalid do testDoWhile(); while (condition()); } /** Test while loops **/ void testWhile() { // Valid while (condition()) { testWhile(); } // Invalid while(condition()); while (condition()) testWhile(); while (condition()) if (condition()) testWhile(); } /** Test for loops **/ void testFor() { // Valid for (int i = 1; i < 5; i++) { testFor(); } // Invalid for(int i = 1;i < 5;i++); for (int i = 1; i < 5; i++) testFor(); for (int i = 1; i < 5; i++) if (i > 2) testFor(); } /** Test if constructs **/ public void testIf() { // Valid if (condition()) { testIf(); } else if (condition()) { testIf(); } else { testIf(); } // Invalid if (condition()); if (condition()) testIf(); if (condition()) testIf(); else testIf(); if (condition()) testIf(); else { testIf(); } if (condition()) { testIf(); } else testIf(); if (condition()) if (condition()) testIf(); } void whitespaceAfterSemi() { //reject int i = 1;int j = 2; //accept for (;;) { } } /** Empty constructor block. **/ public InputBraces() {} /** Empty method block. **/ public void emptyImplementation() {} } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputCovariant.java100644 0 0 4423 11451071613 25757 0ustar 0 0 package com.puppycrawl.tools.checkstyle; /** * Test file for covariant equals methods. * @author Rick Giles */ public class InputCovariant { private class Inner { public boolean equals(Inner aInner) { return false; } } private class Inner2 { public boolean equals(Inner2 aInner2) { return false; } public boolean equals(Object aObj) { return false; } } public boolean equals(InputCovariant aInputCovariant) { return false; } } class InputCovariant2 { public boolean equals(InputCovariant2 aInputCovariant2) { return false; } public boolean equals(Object aObject) { return false; } } class InputCovariant3 { public boolean equals(InputCovariant3 aInputCovariant3) { return false; } public boolean equals(java.lang.Object aObject) { return false; } } class InputCovariant4 { public boolean equals(int i) { return false; } } class Anonymous { Comparable comp = new Comparable() { public int compareTo(Object aObject) { return 0; } public boolean equals(String aString) { return false; } }; public boolean equals(Object aObject) { return false; } public void method() { Double d = new Double(1); } } abstract class InputCovariant5 { public abstract boolean equals(InputCovariant4 aInputCovariant4); } interface InputCovariant6 { public boolean equals(InputCovariant5 aInputCovariant5); } class InputGenericCovariant7 { public boolean equals(InputGenericCovariant7 aInputCovariant7) { return true; } public boolean equals(Object aObject) { return false; } } class InputGenericCovariant8 { public boolean equals(InputGenericCovariant8 aInputCovariant8) { return true; } public boolean equals(Object aObject) { return false; } }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputDesignForExtension.java100644 0 0 4037 11451071613 27607 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for the "design for inheritance" check. * @author Lars Kühne **/ public abstract class InputDesignForExtension { // some methods that are OK public interface InterfaceOK { void implicitlyAbstract(); } final class ClassOK { protected void finalThroughClassDef() { System.out.println("no way to override"); } } protected void nonFinalButEmpty() { } public void nonFinalButEmpty2() { // comments don't count as content... } private void aPrivateMethod() { System.out.println("no way to override"); } protected abstract void nonFinalButAbstract(); // this one is bad: neither abtract, final, or empty protected void doh() { System.out.println("nonempty and overriding possible"); } // has a potentially complex implementation in native code. // We can't check that, so to be safe DesignForExtension requires // native methods to also be final public native void aNativeMethod(); // tries to trigger bug #884035 // MyComparator is a private class, so there cannot be subclasses // and it should not be neccessary to declare compare() as final private class MyComparator implements java.util.Comparator { public int compare(Object o1, Object o2) { // some complex stuff that would normally trigger an error report if (o1.hashCode() > o2.hashCode()) { return -1; } else { return 1; } } } } // enums should be skipped enum TEnum { FIRST, SECOND; public int value() { return 3; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputEmptyFile.txt100644 0 0 0 11451071613 25530 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputEmptyStatement.java100644 0 0 1775 11451071613 27023 0ustar 0 0 package com.puppycrawl.tools.checkstyle; /** * Input class for testing EmptyStatementCheck * @author Rick Giles * @version 5-May-2003 */ public class InputEmptyStatement { public InputEmptyStatement() { ; } public void EmptyMethod() { ; } public void EmptyStatements(boolean cond) { for (;cond;); for (;cond;) { ; } if (true); if (true) { ; } if (cond) { int i; } else { ; } switch (1) { case 1 : ; default : ; } while (cond); while (cond) { ; } do; while (cond); do { ; } while (cond); try { ; } catch (Exception ex) { ; } finally { ; } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputFinalClass.java100644 0 0 3701 11451071613 26046 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2003 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; public class InputFinalClass { private InputFinalClass() {} } class test2 {} class test3 { class test4 { private test4() {} } } class test5 { private test5() {} test5(int i) {} } class test6 { public test6() {} } // Typesafe enum with operation // abstract classes cannot be final, see bug #837012 abstract class Operation { abstract double eval(double a, double b); public static final Operation PLUS = new Operation("+") { double eval(double a, double b) { return a + b; } }; public static final Operation MINUS = new Operation("-") { double eval(double a, double b) { return a - b; } }; private String _name; private Operation(String name) { this._name = name; } } // Typesafe enum with operation // abstract classes cannot be final, see bug #837012 interface Evaluatable { double eval(double a, double b); } // abstract class without it's own abstract method decl abstract class Operation2 implements Evaluatable { public static final Operation2 PLUS = new Operation2("+") { public double eval(double a, double b) { return a + b; } }; public static final Operation2 MINUS = new Operation2("-") { public double eval(double a, double b) { return a - b; } }; private String _name; private Operation2(String name) { this._name = name; } } enum testenum1 { A, B; testenum1() {} } enum testenum2 { A, B; public static class someinnerClass { private someinnerClass() {} } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputFinalParameters.java100644 0 0 7204 11451071613 27106 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2003 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import javax.swing.AbstractAction; import javax.swing.Action; import java.awt.event.ActionEvent; /** * Test case for detecting missing final parameters. * @author Lars Kühne **/ class InputFinalParameters { /** no param constructor */ InputFinalParameters() { } /** non final param constructor */ InputFinalParameters(String s) { } /** non final param constructor */ InputFinalParameters(final Integer i) { } /** final param constructor with annotation */ InputFinalParameters(final @MyAnnotation3 Class i) { } /** non-final param constructor with annotation*/ InputFinalParameters(@MyAnnotation3 Boolean i) { } /** mixed */ InputFinalParameters(String s, final Integer i) { } /** no param method */ void method() { } /** non final param method */ void method(String s) { } /** final param method */ void method(final Integer i) { } /** final param method with annotation **/ void method(@MyAnnotation3 final Object s) { } /** non-final param method with annotation **/ void method(@MyAnnotation3 Class s) { } /** mixed */ void method(String s, final Integer i) { } /** interface methods should not be flagged. */ interface TestInterface { void method(String s); } /** methods in anonymous inner classes */ void holder() { Action a = new AbstractAction() { public void actionPerformed(ActionEvent e) { } void somethingElse(@MyAnnotation3 ActionEvent e) { } }; Action b = new AbstractAction() { public void actionPerformed(final ActionEvent e) { } void somethingElse(@MyAnnotation3 final ActionEvent e) { } }; } /** methods with complicated types of the parameters. */ void methodA(java.lang.String aParam) { } void methodB(String[] args) { } void methodC(java.lang.String[] args) { } /** some catch blocks */ void method1() { try { System.err.println(""); } catch (java.lang.NullPointerException npe) { npe.printStackTrace(); } catch (@MyAnnotation3 final ClassCastException e) { e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } catch (@MyAnnotation3 NoClassDefFoundError e) { e.printStackTrace(); } } } abstract class AbstractClass { public abstract void abstractMethod(int aParam); } class Foo { /* Some for-each clauses */ public void Bar() { for(String s : someExpression()) { } for(final String s : someExpression()) { } for(@MyAnnotation3 String s : someExpression()) { } for(@MyAnnotation3 final String s : someExpression()) { } } private String[] someExpression() { return null; } } @interface MyAnnotation3 { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputForWhitespace.java100644 0 0 2127 11451071613 26573 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for FOR_ITERATION and whitespace. // Created: 2003 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; class InputForWhitespace { void method1() { for (int i = 0; i < 1; i++) { } for (int i = 0; i < 1;i++) { } for (int i = 0; i < 1;i++ ) { } for (int i = 0; i < 1; i++ ) { } for (int i = 0; i < 1;) { i++; } for (int i = 0; i < 1; ) { i++; } // test eol, there is no space after second SEMI for (int i = 0; i < 1; ) { i++; } } void method2() { for ( int i = 0; i < 1; i++ ) { } for ( int i = 0; i < 1; ) { i++; } int i = 0; for ( ; i < 1; i++ ) { } for (; i < 2; i++ ) { } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputGenerics.java100644 0 0 1377 11451071613 25575 0ustar 0 0 package com.puppycrawl.tools.checkstyle; import java.util.Collection; import java.util.Map; public class InputGenerics, C extends D&E, F extends Collection> { } //No whitespace after commas class BadCommas < A,B,C extends Map < A,String > > { private java.util.Hashtable < Integer, D > p = new java.util.Hashtable < Integer, D > (); } class Wildcard { public static void foo(Collection < ? extends Wildcard[] > collection) { // A statement is important in this method to flush out any // issues with parsing the wildcard in the signature collection.size(); } } // we need these interfaces for generics interface D { } interface E { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/inputHeader.java100644 0 0 120 11451071614 25230 0ustar 0 0 package com.puppycrawl.tools.checkstyle; class inputHeader {} // One line test checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputHiddenField.java100644 0 0 11346 11646533001 26212 0ustar 0 0 package com.puppycrawl.tools.checkstyle; //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2002 //////////////////////////////////////////////////////////////////////////////// /** * Test case for hidden fields * @author Rick Giles **/ class InputHiddenField { private int hidden = 0; public InputHiddenField() { int hidden = 0; //shadows field } public InputHiddenField(int hidden) //parameter shadows field { } public void shadow() { int hidden = 0; //shadows field } public void shadowFor() { for (int hidden = 0; hidden < 1; hidden++) { //shadows field } } public void shadowParam(int hidden) //parameter shadows field { } public class Inner { private int innerHidden = 0; public Inner() { int innerHidden = 0; //shadows field } public Inner(int innerHidden) //shadows field { } private void innerShadow() { int innerHidden = 0; //shadows inner field int hidden = 0; //shadows outer field } private void innerShadowFor() { for (int innerHidden = 0; innerHidden < 1; innerHidden++) { } //shadows outer field for (int hidden = 0; hidden < 1; hidden++) { } } private void shadowParam( int innerHidden, //parameter shadows inner field int hidden //parameter shadows outer field ) { } { int innerHidden = 0;//shadows inner field int hidden = 0; //shadows outer field } } { int hidden = 0;//shadows field } } interface NothingHidden { public static int notHidden = 0; // not an error public void noShadow(int notHidden); } /** tests ignoring the parameter of a property setter method */ class PropertySetter { private int prop; /** setter */ public void setProp(int prop) { this.prop = prop; } /** error - incorrect method name */ public void setprop(int prop) { this.prop = prop; } /** error - more than one parameter */ public void setProp(int prop, int extra) { this.prop = prop; } } /** tests a non-void method */ class PropertySetter2 { private int prop; /** error - not a void method */ public int setProp(int prop) { this.prop = prop; return 0; } } /** tests for static fields */ class StaticFields { private static int hidden; public static void staticMethod() { int hidden; } public void method() { int hidden; } static { int hidden; } { int hidden; } } /** tests static methods & initializers */ class StaticMethods { private int notHidden; public static void method() { // local variables of static methods don't hide instance fields. int notHidden; } static { // local variables of static initializers don't hide instance fields. int notHidden; } private int x; private static int y; static class Inner { void useX(int x) { x++; } void useY(int y) { y++; } } } enum HiddenEnum { A(129), B(283), C(1212) { /** * Should not be flagged as error as we don't check * hidden class level fields */ int hidden; public void doSomething() { //Should be flagged as hiding enum constant member int hidden = 0; } }; int hidden; static int hiddenStatic; /** * ctor parameter hides member */ HiddenEnum(int hidden) { } public void doSomething() { //Should be flagged as hiding static member int hidden = 0; } public static void doSomethingStatic() { //Should be flagged as hiding static member int hiddenStatic = 0; } } // we should ignore this if user wants (ignoreAbstractMethods is true) abstract class InputHiddenFieldBug1084512 { String x; public abstract void methodA(String x); } class Bug3370946 { private int xAxis; public void setxAxis(int xAxis) { this.xAxis = xAxis; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputHiddenFieldReorder.java100644 0 0 5656 11451071613 27524 0ustar 0 0 package com.puppycrawl.tools.checkstyle; //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2002 //////////////////////////////////////////////////////////////////////////////// /** * Test case for hidden fields * @author Rick Giles **/ class InputHiddenFieldReorder { public InputHiddenFieldReorder() { int hidden = 0; //shadows field } public InputHiddenFieldReorder(int hidden) //parameter shadows field { } public void shadow() { int hidden = 0; //shadows field } public void shadowFor() { for (int hidden = 0; hidden < 1; hidden++) { //shadows field } } public void shadowParam(int hidden) //parameter shadows field { } public class Inner { // private int innerHidden = 0; public Inner() { int innerHidden = 0; //shadows field } public Inner(int innerHidden) //shadows field { } private void innerShadow() { int innerHidden = 0; //shadows inner field int hidden = 0; //shadows outer field } private void innerShadowFor() { for (int innerHidden = 0; innerHidden < 1; innerHidden++) { } //shadows outer field for (int hidden = 0; hidden < 1; hidden++) { } } private void shadowParam( int innerHidden, //parameter shadows inner field int hidden //parameter shadows outer field ) { } { int innerHidden = 0;//shadows inner field int hidden = 0; //shadows outer field } private int innerHidden = 0; } { int hidden = 0;//shadows field } private int hidden = 0; } interface NothingHiddenReorder { public static int notHidden = 0; // not an error public void noShadow(int notHidden); } enum HiddenEnum1 { A(129), B(283), C(1212) { public void doSomething() { //Should be flagged as hiding enum constant member int hidden = 0; } /** * Should not be flagged as error as we don't check * hidden class level fields */ int hidden; }; /** * ctor parameter hides member */ HiddenEnum1(int hidden) { } public void doSomething() { //Should be flagged as hiding static member int hidden = 0; } public static void doSomethingStatic() { //Should be flagged as hiding static member int hiddenStatic = 0; } int hidden; static int hiddenStatic; } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputIllegalTokens.java100644 0 0 1000 11451071613 26552 0ustar 0 0 package com.puppycrawl.tools.checkstyle; /** * Test for illegal tokens */ public class InputIllegalTokens { public void defaultMethod() { int i = 0; switch (i) { default: i--; i++; break; } } public native void nativeMethod(); public void methodWithLiterals() { final String ref = " */ private void method3() { } /** * This should fail even.though.there are embedded periods */ private void method4() { } /** * Test HTML in Javadoc comment *
*
This guy is missing end of bold tag *
The dt and dd don't require end tags. *
* Extra tag shouldn't be here * * @param arg1 dummy. */ private void method5(int arg1) { } /** * Protected check should fail */ protected void method6() { } /** * Package protected check should fail */ void method7() { } /** * Public check should fail * should fail < */ public void method8() { } /** {@inheritDoc} **/ public void method9() { } // Testcases to excercize the Tag parser (bug 843887) /** * Real men don't use XHTML. *
*
* < br/> * */ private void method10() { // should be the only error } /** * Tag content can be really mean. *

* Sometimes a p tag is closed. *

*

* Sometimes it's not. * * * Attributes can contain spaces and nested quotes. * * * * */ private void method11() { // JavadocStyle should not report any error for this method } /** * Tags for two lines. * Link Text */ private void method12() {// JavadocStyle should not report any error for this method } /** * First sentence. *

     * +--LITERAL_DO (do)
     *     |
     *     +--SLIST ({)
     *         |
     *         +--EXPR
     *             |
     *             +--ASSIGN (=)
     *                 |
     *                 +--IDENT (x)
     *                 +--METHOD_CALL (()
     *                     |
     *                     +--DOT (.)
     *                         |
     *                         +--IDENT (rand)
     *                         +--IDENT (nextInt)
     *                     +--ELIST
     *                         |
     *                         +--EXPR
     *                             |
     *                             +--NUM_INT (10)
     *                     +--RPAREN ())
     *         +--SEMI (;)
     *         +--RCURLY (})
     *     +--LPAREN (()
     *     +--EXPR
     *         |
     *         +--LT (<)
     *             |
     *             +--IDENT (x)
     *             +--NUM_INT (5)
     *     +--RPAREN ())
     *     +--SEMI (;)
     * 
*/ private void method13() {// JavadocStyle should not report any error for this method } /** * Some problematic javadoc. Sample usage: *
*/ private void method14() { // empty line between javadoc and method is critical (bug 841942) } /** * Empty line between javadoc and method declaration cause wrong * line number for reporting error (bug 841942) */ private void method15() { // should report unended first sentance (check line number of the error) } /** Description of field: {@value}. */ public static final int dummy = 4911; /** */ public void method16() { // should report empty javadoc } /** * @param a A parameter */ protected void method17(String a) { // should report empty javadoc (no text before parameter) } /** * @exception RuntimeException shoul be thrown */ void method18(String a) { // should report empty javadoc (no text before exception) } /** */ private static int ASDF = 0; // should report empty javdoc /** @see java.lang.Object */ public void method19() { // should report empty javadoc (no text before see tag) } public enum Test //Should complain about no javadoc { /** * Value 1 without a period */ value1, /** * Value 2 with a period. */ value2, } /** * A test class. * @param this is NOT an unclosed T1 tag * @param for bug 1649020. * @author Foo Bar */ public class TestClass { /** * Retrieves X. * @return a value */ public T1 getX() { return null; } /** * Retrieves Y. * @param this is not an unclosed V tag * @return a value */ public V getY() { return null; } /** * Retrieves Z. * * @param this is not an unclosed KEY_T tag * @return a value */ public KEY_T getZ_1649020_1() { return null; } /** * Retrieves something. * * @param strange type * @return a value */ public KEY_T_$_1_t getEh_1649020_2() { return null; } /** * Retrieves more something. * * @param <$_12_xY_z> strange type * @return a value */ public <$_12_xY_z> $_12_xY_z getUmmm_1649020_3() { return null; } } /** * Checks if the specified IClass needs to be * annotated with the @Type annotation. */ public void foo_1291847_1() { } /** * Returns the string containing the properties of * @Type annotation. */ public void foo_1291847_2() { } /** * Checks generics javadoc. * * @param strings this is a List * @param test Map> a map indexed on String of Lists of Strings. */ public void method20() { } /** * Checks HTML tags in javadoc. * * HTML no good tag * Tests * */ public void method21() { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputLeftCurlyAnnotations.java100644 0 0 2470 11451071613 30160 0ustar 0 0 package com.puppycrawl.tools.checkstyle; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.List; @TestClassAnnotation class InputLeftCurlyAnnotations { private static final int X = 10; @Override public boolean equals(Object other) { return false; } @Override @SuppressWarnings("unused") public int hashCode() { int a = 10; return 1; } @Override @SuppressWarnings({"unused", "unchecked", "static-access"}) public String toString() { Integer i = this.X; List l = new ArrayList(); return "SomeString"; } } @TestClassAnnotation class InputLeftCurlyAnnotations2 { private static final int X = 10; @Override public boolean equals(Object other) { return false; } @Override @SuppressWarnings("unused") public int hashCode() { int a = 10; return 1; } @Override @SuppressWarnings({"unused", "unchecked", "static-access"}) public String toString() { Integer i = this.X; List l = new ArrayList(); return "SomeString"; } } @Target(ElementType.TYPE) @interface TestClassAnnotation { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputLeftCurlyMethod.java100644 0 0 3475 11451071613 27111 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for correct use of braces. * @author Oliver Burn **/ class InputLeftCurlyMethod { InputLeftCurlyMethod() {} InputLeftCurlyMethod(String aOne) { } InputLeftCurlyMethod(int aOne) { } void method1() {} void method2() { } void method3() { } void method4() { } void method5(String aOne, String aTwo) { } void method6(String aOne, String aTwo) { } } enum InputLeftCurlyMethodEnum { CONSTANT1("hello") { void method1() {} void method2() { } void method3() { } void method4() { } void method5(String aOne, String aTwo) { } void method6(String aOne, String aTwo) { } }, CONSTANT2("hello") { }, CONSTANT3("hellohellohellohellohellohellohellohellohellohellohellohellohellohello") { }; private InputLeftCurlyMethodEnum(String value) { } void method1() {} void method2() { } void method3() { } void method4() { } void method5(String aOne, String aTwo) { } void method6(String aOne, String aTwo) { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputLeftCurlyOther.java100644 0 0 4267 11451071613 26752 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for correct use of braces. * @author Oliver Burn **/ class InputLeftCurlyOther { /** @see test method **/ int foo() throws InterruptedException { int x = 1; int a = 2; while (true) { try { if (x > 0) { break; } else if (x < 0) { ; } else { break; } switch (a) { case 0: break; default: break; } } catch (Exception e) { break; } finally { break; } } synchronized (this) { do { x = 2; } while (x == 2); } this.wait(666 ); // Bizarre, but legal for (int k = 0; k < 1; k++) { String innerBlockVariable = ""; } // test input for bug reported by Joe Comuzzi if (System.currentTimeMillis() > 1000) return 1; else return 2; } // Test static initialiser static { int x = 1; // should not require any javadoc } public enum GreetingsEnum { HELLO, GOODBYE }; void method2() { boolean flag = true; if (flag) { System.out.println("heh"); flag = !flag; } System.err. println("Xe-xe"); // it is ok to have rcurly on the same line as previous // statement if lcurly on the same line. if (flag) { System.err.println("it is ok."); } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputLineBreaks.java100644 0 0 1612 11451071613 26045 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2009 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for dealing with various line termination schemes. * @author Martin von Gagern **/ class InputLineBreaks { int firstLine; int cr; int oneQuearter; int crlf; int middleLine; int lfcr; int threeQuarters; int cr2; int lastLine; } /* When splitting on \r\n, \r and \n, the lines should be numbered thus: 13 int firstLine;\n 14 int cr;\r 15 int oneQuearter;\n 16 int crlf;\r\n 17 int middleLine;\n 18 int lfcr;\n 19 \r 20 int threeQuarters;\n 21 int cr2;\r 22 int lastLine;\n */ checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputMagicNumber.java100644 0 0 10363 11511035405 26236 0ustar 0 0 package com.puppycrawl.tools.checkstyle; /** * Describe class InputMagicNumber * @author Rick Giles * @version 6-May-2003 */ public class InputMagicNumber { public void magicMethod() { //constants, ignore final int INT_CONST = 101; final long LONG_CONST1 = 100L; final long LONG_CONST2 = 100l; final float FLOAT_CONST1 = 1.5F; final float FLOAT_CONST2 = 1.5f; final double DOUBLE_CONST1 = 1.5D; final double DOUBLE_CONST2 = 1.5d; final double DOUBLE_CONST3 = 1.5; //ignore by default int int_var1 = 1; int int_var2 = (2); long long_var1 = 0L; long long_var2 = 0l; double double_var1 = 0D; double double_var2 = 0d; int[] int_array = new int[2]; int_var1 = 1 + 2; int_var1 += 1; double_var1 = 1.0 + 2.0; for (int i = 0; i < 2; i++); if (1 < 2); if (1.0 < 2.0); //magic numbers int int_magic1 = 3; double double_magic1 = 1.5; int int_magic2 = (3 + 4); int_array = new int[3]; int_magic1 += 3; double_magic1 *= 1.5; for (int j = 3; j < 5; j += 3) { int_magic1++; } if (int_magic1 < 3) { int_magic1 = int_magic1 + 3; } //octal int octalVar0 = 00; int octalVar8 = 010; int octalVar9 = 011; long longOctalVar8 = 010L; long longOctalVar9 = 011l; //hex int hexVar0 = 0x0; int hexVar16 = 0x10; int hexVar17 = 0X011; long longHexVar0 = 0x0L; long longHexVar16 = 0x10L; long longHexVar17 = 0X11l; } } interface Blah { int LOW = 5; int HIGH = 78; } class ArrayMagicTest { private static final int[] NONMAGIC = {3}; private int[] magic = {3}; private static final int[][] NONMAGIC2 = {{1}, {2}, {3}}; } /** test long hex */ class LongHex { long l = 0xffffffffL; } /** test signed values */ class Signed { public static final int CONST_PLUS_THREE = +3; public static final int CONST_MINUS_TWO = -2; private int mPlusThree = +3; private int mMinusTwo = -2; private double mPlusDecimal = +3.5; private double mMinusDecimal = -2.5; } /** test octal and hex negative values */ class NegativeOctalHex { private int hexIntMinusOne = 0xffffffff; private long hexLongMinusOne = 0xffffffffffffffffL; private long hexIntMinValue = 0x80000000; private long hexLongMinValue = 0x8000000000000000L; private int octalIntMinusOne = 037777777777; private long octalLongMinusOne = 01777777777777777777777L; private long octalIntMinValue = 020000000000; private long octalLongMinValue = 01000000000000000000000L; } class Cast { public static final int TESTINTVAL = (byte) 0x80; } class ComplexAndFlagged { public static final java.util.List MYLIST = new java.util.ArrayList() { public int size() { // should be flagged although technically inside const definition return 378; } }; } class ComplexButNotFlagged { // according to user feedback this is typical code that should not be flagged // (at least in the default configuration of MagicNumberCheck) public static final Integer DEFAULT_INT = new Integer(27); public static final int SECS_PER_DAY = 24 * 60 * 60; public static final javax.swing.border.Border STD_BORDER = javax.swing.BorderFactory.createEmptyBorder(3, 3, 3, 3); } enum MyEnum { A(3), B(54); private MyEnum(int value) { } } class TestHashCodeMethod { // valid hash code method public int hashCode() { return 31; } // invalid hash code method: has parameters public int hashCode(int val) { return 42; } // invalid hash code method: misspelled public int hashcode() { return 13; } static { int x=21; } { int y=37; } public TestHashCodeMethod() { int z=101; } @javax.management.MXBean(42) public void another() { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputMethNameEqualClsName.java100644 0 0 1713 11451071613 27761 0ustar 0 0 package com.puppycrawl.tools.checkstyle; /** * Test input for MethodNameCheck specifically * whether the method name equals the class name. * * @author Travis Schneeberger */ public class InputMethNameEqualClsName { //illegal name public int InputMethNameEqualClsName() { return 0; } //illegal name private int PRIVATEInputMethNameEqualClsName() { return 0; } class Inner { //illegal name public int Inner() { return 0; } //OK name - name of the outter class's ctor public int InputMethNameEqualClsName() { return 0; } } public void anotherMethod() { new InputMethNameEqualClsName() { //illegal name public int InputMethNameEqualClsName() { return 1; } }; } } interface SweetInterface { //illegal name int SweetInterface(); } class Outter { //illegal name public void Outter() { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputMissingSwitchDefault.java100644 0 0 574 11451071613 30114 0ustar 0 0 public class InputMissingSwitchDefault { public void foo() { int i = 1; switch (i) { case 1: i++; break; case 2: i--; break; default: return; } } } class bad_test { public void foo() { int i = 1; switch (i) { case 1: i++; break; case 2: i--; break; } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputModifier.java100644 0 0 6065 11545733666 25614 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for Modifier checks: * - order of modifiers * - use of 'public' in interface definition * @author lkuehne */ strictfp final class InputModifier // illegal order of modifiers for class { /** Illegal order of modifiers for variables */ static private boolean sModifierOrderVar = false; /** * Illegal order of modifiers for methods. Make sure that the * first and last modifier from the JLS sequence is used. */ strictfp private void doStuff() { } /** Single annotation without other modifiers */ @MyAnnotation2 void someMethod() { } /** Illegal order of annotation - must come first */ private @MyAnnotation2 void someMethod2() { } /** Annotation in middle of other modifiers otherwise in correct order */ private @MyAnnotation2 strictfp void someMethod3() { } /** Correct order */ @MyAnnotation2 private strictfp void someMethod4() { } /** Annotation in middle of other modifiers otherwise in correct order */ @MyAnnotation2 private static @MyAnnotation4 strictfp void someMethod5() { } /** holder for redundant 'public' modifier check. */ public static interface InputRedundantPublicModifier { /** redundant 'public' modifier */ public void a(); /** all OK */ void b(); /** redundant abstract modifier */ abstract void c(); /** redundant 'public' modifier */ public float PI_PUBLIC = (float) 3.14; /** redundant 'abstract' modifier (field can not be absract)*/ // abstract float PI_ABSTRACT = (float) 3.14; /** redundant 'final' modifier */ final float PI_FINAL = (float) 3.14; /** all OK */ float PI_OK = (float) 3.14; } /** redundant 'final' modifier */ private final void method() { } } /** Holder for redundant 'final' check. */ final class RedundantFinalClass { /** redundant 'final' modifier */ public final void finalMethod() { } /** OK */ public void method() { } } /** Holder for redundant modifiers of inner implementation */ interface InnerImplementation { InnerImplementation inner = new InnerImplementation() { /** compiler requires 'public' modifier */ public void method() { } }; void method(); } /** Holder for redundant modifiers of annotation fields/variables */ @interface Annotation { public String s1 = ""; final String s2 = ""; static String s3 = ""; String s4 = ""; public String blah(); abstract String blah2(); } @interface MyAnnotation2 { } @interface MyAnnotation4 { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputNestedBlocks.java100644 0 0 3211 11451071613 26403 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for finding nested blocks. * @author lkuehne **/ class InputNestedBlocks { static { // OK } public void method() { int x = 0; // if (condition that is not important anymore) { // nested block, should be marked int z = 1; int y = z; } if (x == 1) { // OK x = 2; } // case statements are a bit complicated, // they do not have its own variable scope by default. // Hence it may be OK in some development teams to allow // nested blocks if they are the complete case body. switch (x) { case 0: // OK x = 3; break; case 1: // Not OK, SLIST is not complete case body { x = 1; } break; case 2: // OK if allowInSwitchCase is true, SLIST is complete case body { x = 1; break; } case 3: // test fallthrough default: // Not OK, SLIST is not complete case body System.out.println("Hello"); { x = 2; } } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputNewlineAtEndOfFile.java100644 0 0 700 11451071613 27405 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2003 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for detection of an existing newline at EOF, using the * NewlineAtEndOfFileCheck. * @author Christopher Lenz **/ public interface InputNewlineAtEndOfFile { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputNoNewlineAtEndOfFile.java100644 0 0 674 11451071613 27714 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2003 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for detection of missing newlines at EOF, using the * NewlineAtEndOfFileCheck. * @author Christopher Lenz **/ public interface InputNoNewlineAtEndOfFile { }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputOpWrap.java100644 0 0 2031 11451071613 25232 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for detecting operator wrapping. * @author Lars Kïż½hne **/ class InputOpWrap { void test() { int x = 1 + 2 - 3 - 4; x = x + 2; boolean y = true && false; y = true && false; y = false && true; } void testAssignment() { int x = 0; //error when checking assignment operators with EOL wrap option int y = 0; } < T extends Comparable & java.io.Serializable > void testGenerics1() { Comparable < String > c = new String(); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputPublicOnly.java100644 0 0 5475 11451071613 26121 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; public class InputPublicOnly // ignore - need javadoc { private interface InnerInterface // ignore - when not relaxed about Javadoc { String CONST = "InnerInterface"; // ignore - w.n.r.a.j void method(); // ignore - when not relaxed about Javadoc class InnerInnerClass // ignore - when not relaxed about Javadoc { private int mData; // ignore - when not relaxed about Javadoc private InnerInnerClass() { final Runnable r = new Runnable() { public void run() {}; }; } void method2() // ignore - when not relaxed about Javadoc { final Runnable r = new Runnable() { public void run() {}; }; } } } private class InnerClass // ignore { private int mDiff; // ignore - when not relaxed about Javadoc void method() // ignore - when not relaxed about Javadoc { } } private int mSize; // ignore - when not relaxed about Javadoc int mLen; // ignore - when not relaxed about Javadoc protected int mDeer; // ignore public int aFreddo; // ignore // ignore - need Javadoc private InputPublicOnly(int aA) { } // ignore - need Javadoc when not relaxed InputPublicOnly(String aA) { } // ignore - always need javadoc protected InputPublicOnly(Object aA) { } // ignore - always need javadoc public InputPublicOnly(Class aA) { } // ignore - when not relaxed about Javadoc private void method(int aA) { } // ignore - when not relaxed about Javadoc void method(Long aA) { } // ignore - need javadoc protected void method(Class aA) { } // ignore - need javadoc public void method(StringBuffer aA) { } /** A param tag should not be required here when relaxed about Javadoc. Writing a little documentation should not be worse than not writing any documentation at all. */ private void method(String aA) { } /** This inner class has no author tag, which is OK. */ public class InnerWithoutAuthor { } /** {@inheritDoc} */ public String toString() { return super.toString(); } @Deprecated @Override public int hashCode() { return super.hashCode(); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputRedundantThrows.java100644 0 0 1571 11451071613 27165 0ustar 0 0 import java.io.IOException; public class InputRedundantThrows { // wrong contains subclasses InputRedundantThrows() throws java.io.IOException, java.io.FileNotFoundException { } // wrong uncheck exception void method1() throws RuntimeException { } // wrong - duplicate void method2() throws IOException, java.io.IOException { } // bad - no information for checking exception // void method3() // throws WrongException // we will throw exception here, thus I remove it from the test input // { // } // right void method4() throws IOException, ClassNotFoundException { } void method5() throws /* WrongException, */ IOException { } void method6() throws NullPointerException, RuntimeException { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputRegexpHeader1.java100644 0 0 150 11451071613 26426 0ustar 0 0 package blah; import java.awt.*; /** * Some doc. */ public class InputRegexpHeader1 { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputRegexpHeader2.java100644 0 0 244 11451071613 26433 0ustar 0 0 package blah; import java.awt.*; import java.awt.event.*; import java.io.*; /** * * blah blah * @see foo */ public class InputRegexpHeader2 { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputRegexpHeader3.java100644 0 0 116 11451071613 26432 0ustar 0 0 package blah; import java.awt.*; public class InputRegexpHeader3 { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputRegexpHeader4.java100644 0 0 141 11451071613 26431 0ustar 0 0 package blah; import java.awt.*; import java.awt.*; import java.awt.*; import java.awt.*; checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputRegexpSmallHeader.java100644 0 0 105 11451071613 27336 0ustar 0 0 package blah; /** */ public class InputRegexpSmallHeader {} checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputScopeAnonInner.java100644 0 0 2726 11451071613 26716 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.awt.event.MouseEvent; import java.awt.event.MouseAdapter; import javax.swing.JButton; /** * Tests for anonymous inner types * @author Lars Kühne **/ public class InputScopeAnonInner { /** button. */ private JButton mButton = new JButton(); /** anon inner in member variable initialization. */ private Runnable mRunnable = new Runnable() { public void run() // should not have to be documented, class is anon. { System.out.println("running"); } }; /** anon inner in constructor. */ InputScopeAnonInner() { mButton.addMouseListener( new MouseAdapter() { public void mouseClicked( MouseEvent aEv ) { System.out.println("click"); } } ); } /** anon inner in method */ public void addInputAnonInner() { mButton.addMouseListener( new MouseAdapter() { public void mouseClicked( MouseEvent aEv ) { System.out.println("click"); } } ); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputScopeInnerClasses.java100644 0 0 2207 11451071613 27412 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** Checks javadoc scoping for inner classes. Once the Javadoc Check Scope has been left, all inner elements should not be reported as error, even if they belong to the checkscope if isolated. @author lkuehne */ public class InputScopeInnerClasses { public class InnerPublic { protected class InnerProtected { class InnerPackage { private class InnerPrivate { // no javadoc required for package scope class PrivateHiddenPackage { } protected class PrivateHiddenProtected { } public class PrivateHiddenPublic { } } } } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputScopeInnerInterfaces.java100644 0 0 2525 11451071613 30103 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; public class InputScopeInnerInterfaces { // inner interfaces with different scopes private interface PrivateInterface { public String CA = "CONST A"; String CB = "CONST b"; public void ma(); void mb(); } interface PackageInnerInterface { public String CA = "CONST A"; String CB = "CONST b"; public void ma(); void mb(); } protected interface ProtectedInnerInterface { public String CA = "CONST A"; String CB = "CONST b"; public void ma(); void mb(); } public interface PublicInnerInterface { public String CA = "CONST A"; String CB = "CONST b"; public void ma(); void mb(); } private class MyClass1 { } class MyClass2 { } private interface MyInterface1 { } interface MyInterface2 { } protected enum MyEnum { } private @interface MyAnnotation { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputSemantic.java100644 0 0 11126 11451071613 25612 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.io.*; // star import for instantiation tests import java.awt.Dimension; // explicit import for instantiation tests import java.awt.Color; /** * Test case for detecting simple semantic errors. * @author Lars Kühne **/ class InputSemantic { /* Boolean instantiation in a static initializer */ static { Boolean x = new Boolean(true); } /* Boolean instantiation in a non-static initializer */ { Boolean x = new Boolean(true); Boolean[] y = new Boolean[]{Boolean.TRUE, Boolean.FALSE}; } /** fully qualified Boolean instantiation in a method. **/ Boolean getBoolean() { return new java.lang.Boolean(true); } void otherInstantiations() { // instantiation of classes in the same package Object o1 = new InputBraces(); Object o2 = new InputModifier(); // classes in another package with .* import ByteArrayOutputStream s = new ByteArrayOutputStream(); File f = new File("/tmp"); // classes in another package with explicit import Dimension dim = new Dimension(); Color col = new Color(0, 0, 0); } void exHandlerTest() { try { ; // do stuff and don't handle exceptions in some cases } catch (IllegalStateException emptyCatchIsAlwaysAnError) { } catch (NullPointerException ex) { // can never happen, but only commentig this is currently an error // Possible future enhancement: allowEmptyCatch="commented" } catch (ArrayIndexOutOfBoundsException ex) { ; // can never happen, semicolon makes checkstyle happy // this is a workaround for above problem } catch (NegativeArraySizeException ex) { { } // can never happen, empty compound statement is another workaround } catch (UnsupportedOperationException handledException) { System.out.println(handledException.getMessage()); } catch (SecurityException ex) { /* hello */ } catch (StringIndexOutOfBoundsException ex) {} catch (IllegalArgumentException ex) { } try { } finally { } try { // something } finally { // something } try { ; // something } finally { ; // statement } } /** test **/ private static final long IGNORE = 666l + 666L; public class EqualsVsHashCode1 { public boolean equals(int a) // wrong arg type, don't flag { return a == 1; } } public class EqualsVsHashCode2 { public boolean equals(String a) // flag { return true; } } public class EqualsVsHashCode3 { public boolean equals(Object a) // don't flag { return true; } public int hashCode() { return 0; } } public class EqualsVsHashCode4 { // in anon inner class ByteArrayOutputStream bos1 = new ByteArrayOutputStream() { public boolean equals(Object a) // don't flag { return true; } public int hashCode() { return 0; } }; ByteArrayOutputStream bos2 = new ByteArrayOutputStream() { public boolean equals(Object a) // flag { return true; } }; } public void triggerEmptyBlockWithoutBlock() { // an if statement without a block to increase test coverage if (true) return; } // empty instance initializer { } public class EqualsVsHashCode5 { public boolean equals(int a) // wrong arg type, don't flag even with generics { return a == 1; } } public class EqualsVsHashCode6 { public boolean equals(Comparable a) // flag, weven with generics { return true; } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputSimple.java100644 0 0 12463 11451071613 25305 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: Feb-2001 // Ignore error //////////////////////////////////////////////////////////////////////////////// @java.lang.annotation.Documented package com.puppycrawl.tools.checkstyle; import java.io.*; /** * Contains simple mistakes: * - Long lines * - Tabs * - Format of variables and parameters * - Order of modifiers * @author Oliver Burn **/ final class InputSimple { // Long line ---------------------------------------------------------------- // Contains a tab -> <- // Contains trailing whitespace -> // Name format tests // /** Invalid format **/ public static final int badConstant = 2; /** Valid format **/ public static final int MAX_ROWS = 2; /** Invalid format **/ private static int badStatic = 2; /** Valid format **/ private static int sNumCreated = 0; /** Invalid format **/ private int badMember = 2; /** Valid format **/ private int mNumCreated1 = 0; /** Valid format **/ protected int mNumCreated2 = 0; /** commas are wrong **/ private int[] mInts = new int[] {1,2, 3, 4}; // // Accessor tests // /** should be private **/ public static int sTest1; /** should be private **/ protected static int sTest3; /** should be private **/ static int sTest2; /** should be private **/ int mTest1; /** should be private **/ public int mTest2; // // Parameter name format tests // /** * @return hack * @param badFormat1 bad format * @param badFormat2 bad format * @param badFormat3 bad format * @throws java.lang.Exception abc **/ int test1(int badFormat1,int badFormat2, final int badFormat3) throws java.lang.Exception { return 0; } /** method that is 20 lines long **/ private void longMethod() { // a line // a line // a line // a line // a line // a line // a line // a line // a line // a line // a line // a line // a line // a line // a line // a line // a line // a line } /** constructor that is 10 lines long **/ private InputSimple() { // a line // a line // a line // a line // a line // a line // a line // a line } /** test local variables */ private void localVariables() { // normal decl int abc = 0; int ABC = 0; // final decls final int cde = 0; final int CDE = 0; // decl in for loop init statement for (int k = 0; k < 1; k++) { String innerBlockVariable = ""; } for (int I = 0; I < 1; I++) { String InnerBlockVariable = ""; } } /** test method pattern */ void ALL_UPPERCASE_METHOD() { } /** test illegal constant **/ private static final int BAD__NAME = 3; // A very, very long line that is OK because it matches the regexp "^.*is OK.*regexp.*$" // long line that has a tab -> <- and would be OK if tab counted as 1 char // tabs that count as one char because of their position -> <- -> <-, OK /** some lines to test the error column after tabs */ void errorColumnAfterTabs() { // with tab-width 8 all statements below start at the same column, // with different combinations of ' ' and '\t' before the statement int tab0 =1; int tab1 =1; int tab2 =1; int tab3 =1; int tab4 =1; int tab5 =1; } // FIXME: /* FIXME: a * FIXME: * TODO */ /* NOTHING */ /* YES */ /* FIXME: x */ /* YES!! */ /** test long comments **/ void veryLong() { /* blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah enough talk */ } /** * @see to lazy to document all args. Testing excessive # args **/ void toManyArgs(int aArg1, int aArg2, int aArg3, int aArg4, int aArg5, int aArg6, int aArg7, int aArg8, int aArg9) { } } /** Test class for variable naming in for each clauses. */ class InputSimple2 { /** Some more Javadoc. */ public void doSomething() { //"O" should be named "o" for (Object O : new java.util.ArrayList()) { } } } /** Test enum for member naming check */ enum MyEnum1 { /** ABC constant */ ABC, /** XYZ constant */ XYZ; /** Should be mSomeMemeber */ private int someMember; } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputSimplifyBoolean.java100644 0 0 2757 11451071613 27135 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** Contains boolean logic that can be simplified. @author lkuehne */ public class InputSimplifyBoolean { public static boolean isOddMillis() { boolean even = System.currentTimeMillis() % 2 == 0; // can be simplified to "if (even)" if (even == true) { return false; } else { return true; } // return can be simplified to "return !even" } public static boolean isOddMillis2() { boolean even = System.currentTimeMillis() % 2 == 0; // can be simplified to "return !even" if (!even) return true; else return false; } public static boolean giveMeTrue() { boolean tt = isOddMillis() || true; boolean ff = isOddMillis() && false; return !false || (true != false); } public void tryToProvokeNPE() { if (true) { } else { } if (true) { return; } else { return; } } public boolean ifNoElse() { if (isOddMillis()) { return true; } return false; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputTrailingComment.java100644 0 0 1512 11451071613 27121 0ustar 0 0 public class InputTrailingComment { int i; // don't use trailing comments :) // it fine to have comment w/o any statement /* good c-style comment. */ int j; /* bad c-style comment. */ void method1() { /* some c-style multi-line comment*/ Runnable r = (new Runnable() { public void run() { } }); /* we should allow this */ } // we should allow this /* Let's check multi-line comments. */ /* c-style */ // cpp-style /* c-style 1 */ /*c-style 2 */ void method2(long ms /* we should ignore this */) { /* comment before text */int z; /* int y */int y/**/; } /** * comment with trailing space */ final static public String NAME="Some Name"; // NOI18N } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputTypeParamsTags.java100644 0 0 1461 11451071613 26734 0ustar 0 0 package com.puppycrawl.tools.checkstyle; /** * Some explanation. * @param A type param * @param Another type param * @param The wrong type param * @author Nobody * @version 1.0 */ public class InputTypeParamsTags { /** * Some explanation. * @param A type param * @param Another type param * @return a string */ public String doSomething() { return null; } /** * Some explanation. * @param The wrong type param */ public void doSomethingElse() { } /** * Some explanation. * @param aAnEl A parameter * @param A type parameter */ public void doSomethingElse2(L aAnEl) { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputUncommentedMain.java100644 0 0 3457 11451071613 27122 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2003 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Test case for UncommentedMainCheck * @author o_sukhodolsky */ public class InputUncommentedMain { // uncommented main public static void main(String[] args) { System.out.println("InputUncommentedMain.main()"); } } class Main { // uncommented main in class Main public static void main(String[] args) { System.out.println("Main.main()"); } } class UncommentedMainTest1 { // one more uncommented main public static void main(java.lang.String[] args) { System.out.println("test1.main()"); } } class UncommentedMainTest2 { // wrong arg type public static void main(int args) { System.out.println("test2.main()"); } } class UncommentedMainTest3 { // no-public main static void main(String[] args) { System.out.println("test3.main()"); } } class UncommentedMainTest4 { // non-static main public void main(String[] args) { System.out.println("test4.main()"); } } class UncommentedMainTest5 { // wrong return type public static int main(String[] args) { System.out.println("test5.main()"); return 1; } } class UncommentedMainTest6 { // too many params public static void main(String[] args, int param) { System.out.println("test6.main()"); } } class UncommentedMainTest7 { // main w/o params public static void main() { System.out.println("test7.main()"); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputWhitespace.java100644 0 0 12103 11451071613 26137 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com . puppycrawl .tools. checkstyle; /** * Class for testing whitespace issues. * error missing author tag **/ class InputWhitespace { /** ignore assignment **/ private int mVar1=1; /** ignore assignment **/ private int mVar2 =1; /** Should be ok **/ private int mVar3 = 1; /** method **/ void method1() { final int a = 1; int b= 1; // Ignore 1 b=1; // Ignore 1 b+=1; // Ignore 1 b -=- 1 + (+ b); // Ignore 2 b = b ++ + b --; // Ignore 1 b = ++ b - -- b; // Ignore 1 } /** method **/ void method2() { synchronized(this) { } try{ } catch(RuntimeException e){ } } /** skip blank lines between comment and code, should be ok **/ private int mVar4 = 1; /** test WS after void return */ private void fastExit() { boolean complicatedStuffNeeded = true; if( !complicatedStuffNeeded ) { return; // should not complain about missing WS after return } else { // do complicated stuff } } /** test WS after non void return @return 2 */ private int nonVoid() { if ( true ) { return(2); // should complain about missing WS after return } else { return 2; // this is ok } } /** test casts **/ private void testCasts() { Object o = (Object) new Object(); // ok o = (Object)o; // error o = ( Object ) o; // ok o = (Object) o; // ok } /** test questions **/ private void testQuestions() { boolean b = (1 == 2)?true:false; b = (1==2) ? false : true; } /** star test **/ private void starTest() { int x = 2 *3* 4; } /** boolean test **/ private void boolTest() { boolean a = true; boolean x = ! a; int z = ~1 + ~ 2; } /** division test **/ private void divTest() { int a = 4 % 2; int b = 4% 2; int c = 4 %2; int d = 4%2; int e = 4 / 2; int f = 4/ 2; int g = 4 /2; int h = 4/2; } /** @return dot test **/ private java .lang. String dotTest() { Object o = new java.lang.Object(); o. toString(); o .toString(); o . toString(); return o.toString(); } /** assert statement test */ public void assertTest() { // OK assert true; // OK assert true : "Whups"; // evil colons, should be OK assert "OK".equals(null) ? false : true : "Whups"; // missing WS around assert assert(true); // missing WS around colon assert true:"Whups"; } /** another check */ void donBradman(Runnable aRun) { donBradman(new Runnable() { public void run() { } }); final Runnable r = new Runnable() { public void run() { } }; } /** rfe 521323, detect whitespace before ';' */ void rfe521323() { doStuff() ; // ^ whitespace for (int i = 0 ; i < 5; i++) { // ^ whitespace } } /** bug 806243 (NoWhitespaceBeforeCheck error for anonymous inner class) */ private int i ; // ^ whitespace private int i1, i2, i3 ; // ^ whitespace private int i4, i5, i6; /** bug 806243 (NoWhitespaceBeforeCheck error for anonymous inner class) */ void bug806243() { Object o = new InputWhitespace() { private int j ; // ^ whitespace }; } void doStuff() { } } /** * Bug 806242 (NoWhitespaceBeforeCheck error with an interface). * @author o_sukhodolsky * @version 1.0 */ interface IFoo { void foo() ; // ^ whitespace } /** * Avoid Whitespace errors in for loop. * @author lkuehne * @version 1.0 */ class SpecialCasesInForLoop { void forIterator() { // avoid conflict between WhiteSpaceAfter ';' and ParenPad(nospace) for (int i = 0; i++ < 5;) { // ^ no whitespace } // bug 895072 // avoid confilct between ParenPad(space) and NoWhiteSpace before ';' int i = 0; for ( ; i < 5; i++ ) { // ^ whitespace } for (int anInt : getSomeInts()) { //Should be ignored } } int[] getSomeInts() { int i = (int) ( 2 / 3 ); return null; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputWriteTag.java100644 0 0 1253 11451071613 25555 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2004 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * Testing tag writing * @author Daniel Grenner * @incomplete This class needs more code... * @doubletag first text * @doubletag second text * @emptytag */ class InputWriteTag { /** * @todo Add a constructor comment */ public InputWriteTag() { } public void method() { } /** * @todo Add a comment */ public void anotherMethod() { } }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/InputWriteTag2.java100644 0 0 1166 11451071613 25642 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2004 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; /** * @incomplete This enum needs more code... */ enum InputWriteTag2 { /** * @incomplete This enum constant needs more code... */ FOO; } /** * @incomplete This annotation needs more code... */ @interface InputWriteTag3 { /** * @incomplete This annotation field needs more code... */ int foo() default 0; } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/java.header100644 0 0 327 11451071614 24221 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Test case file for checkstyle. // Created: 2001 ////////////////////////////////////////////////////////////////////////////////checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/bothfiles/Ignored.java100644 0 0 123 11451071614 27740 0ustar 0 0 package com.puppycrawl.tools.checkstyle.javadoc.bothfiles; class Ignored { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/bothfiles/package-info.java100644 0 0 74 11451071614 30662 0ustar 0 0 package com.puppycrawl.tools.checkstyle.javadoc.bothfiles; checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/bothfiles/package.html100644 0 0 7 11451071614 27730 0ustar 0 0 Ignoredcheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/InputBadTag.java100644 0 0 133 11451071614 26535 0ustar 0 0 /** * The following is a bad tag. * @mytag Hello */ public class InputBadTag { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/InputInheritDoc.java100644 0 0 1357 11451071614 27474 0ustar 0 0 public class InputInheritDoc { /** {@inheritDoc} */ InputInheritDoc() { } /** {@inheritDoc} */ private void privateMethod() { } /** {@inheritDoc} */ void packageMethod() { } /** {@inheritDoc} */ protected void protectedMethod() { } /** {@inheritDoc} */ public void publicMethod() { } /** {@inheritDoc} */ private static void privateStaticMethod() { } /** {@inheritDoc} */ static void packageStaticMethod() { } /** {@inheritDoc} */ protected static void protectedStaticMethod() { } /** {@inheritDoc} */ public static void publicStaticMethod() { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/InputNoJavadoc.java100644 0 0 4271 11451071614 27306 0ustar 0 0 public class InputNoJavadoc { public int i1; protected int i2; int i3; private int i4; public void foo1() {} protected void foo2() {} void foo3() {} private void foo4() {} protected class ProtectedInner { public int i1; protected int i2; int i3; private int i4; public void foo1() {} protected void foo2() {} void foo3() {} private void foo4() {} } class PackageInner { public int i1; protected int i2; int i3; private int i4; public void foo1() {} protected void foo2() {} void foo3() {} private void foo4() {} } private class PrivateInner { public int i1; protected int i2; int i3; private int i4; public void foo1() {} protected void foo2() {} void foo3() {} private void foo4() {} } } class PackageClass { public int i1; protected int i2; int i3; private int i4; public void foo1() {} protected void foo2() {} void foo3() {} private void foo4() {} public class PublicInner { public int i1; protected int i2; int i3; private int i4; public void foo1() {} protected void foo2() {} void foo3() {} private void foo4() {} } protected class ProtectedInner { public int i1; protected int i2; int i3; private int i4; public void foo1() {} protected void foo2() {} void foo3() {} private void foo4() {} } class PackageInner { public int i1; protected int i2; int i3; private int i4; public void foo1() {} protected void foo2() {} void foo3() {} private void foo4() {} } private class PrivateInner { public int i1; protected int i2; int i3; private int i4; public void foo1() {} protected void foo2() {} void foo3() {} private void foo4() {} } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/InputSetterGetter.java100644 0 0 1372 11451071614 30062 0ustar 0 0 public class InputSetterGetter { private int mNumber; public void setNumber(final int number) { mNumber = number; } public int getNumber() { return mNumber; } public void setNumber1() { mNumber = number; } public void setNumber2(int number) { mNumber = number; firePropertyChanged(); } public void getNumber2() { } public int getCost1(int forMe) { return 666; } public int getCost2() { x = 4; return 666; } public int getCost3() throws Exception { return 666; } public boolean isSomething() { return false; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkghtml/Ignored.java100644 0 0 121 11451071614 27425 0ustar 0 0 package com.puppycrawl.tools.checkstyle.javadoc.pkghtml; class Ignored { } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkghtml/package.html100644 0 0 7 11451071614 27417 0ustar 0 0 Ignored././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/annotation/package-info.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/annotation/package-inf100644 0 0 465 11744743240 31445 0ustar 0 0 /** * This is a valid package documentation. <--- See the period after the * first sentence. * *

* hurray for javadocs in html *
* with a legacy non-closed br element *

*/ @java.lang.annotation.Documented package com.puppycrawl.tools.checkstyle.javadoc.pkginfo.annotation; ././@LongLink100644 0 0 156 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/invalidformat/package-info.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/invalidformat/package-100644 0 0 140 11451071614 31415 0ustar 0 0 /** * blah blah */ package com.puppycrawl.tools.checkstyle.javadoc.pkginfo.invalidformat; ././@LongLink100644 0 0 157 12026055133 10253 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/invalidinherit/package-info.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/invalidinherit/package100644 0 0 202 11451071614 31511 0ustar 0 0 /** * {@inheritDoc} Where are we inheriting from */ package com.puppycrawl.tools.checkstyle.javadoc.pkginfo.invalidinherit; ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/valid/package-info.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/pkginfo/valid/package-info.jav100644 0 0 417 11451071614 31317 0ustar 0 0 /** * This is a valid package documentation. <--- See the period after the * first sentence. * *

* hurray for javadocs in html *
* with a legacy non-closed br element *

*/ package com.puppycrawl.tools.checkstyle.javadoc.pkginfo.valid; checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/javadoc/TestGenerics.java100644 0 0 2010 11451071614 27006 0ustar 0 0 public class TestGenerics { /** * @throws E in some cases * @throws RE in some cases */ public void method1() throws E { } /** * RuntimeException is not declared. */ public void method2() throws RE { } /** * @throws E in some cases * @throws RE in other cases */ public void method3() throws E, RE { } /** * @throws RE in some cases * @throws NPE in some other cases */ public void method4() throws NPE, RE { } public class InnerClass { /** * @throws E in some case * @throws RE in some other cases */ public void method1() throws RuntimeException, RE, java.lang.RuntimeException { } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/messages.properties100644 0 0 533 11451071614 26052 0ustar 0 0 # input file for TranslationCheck # a key that is available in all translations hello=Hello # whitespace at end of key should be trimmed before comparing. # the german translation does not contain whitespace, no error should # be reported here cancel = Cancel # a key that is missing in german translation only.english=only english checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/messages_de.properties100644 0 0 535 11451071614 26524 0ustar 0 0 # input file for TranslationCheck # a key that is available in all translations hello=Hallo # whitespace at end of key should be trimmed before comparing. # the german translation does not contain whitespace, no error should # be reported here cancel=Abbrechen # a key that is missing in german translation #only.english=only english ././@LongLink100644 0 0 165 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/metrics/BooleanExpressionComplexityCheckTestInput.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/metrics/BooleanExpressionComplexityChe100644 0 0 1343 11451071614 31673 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.metrics; public class BooleanExpressionComplexityCheckTestInput { private boolean _a = false; private boolean _b = false; private boolean _c = false; private boolean _d = false; public void foo() { if (_a && _b || _c ^ _d) { } if (((_a && (_b & _c)) || (_c ^ _d))) { } if (_a && _b && _c) { } if (_a & _b) { } if (_a) { } } public boolean equals(Object object) { return (((_a && (_b & _c)) || (_c ^ _d) || (_a && _d))); } public boolean bitwise() { return (((_a & (_b & _c)) | (_c ^ _d) | (_a & _d))); } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/metrics/ClassCouplingCheckTestInput.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/metrics/ClassCouplingCheckTestInput.ja100644 0 0 1504 11451071614 31512 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.metrics; import javax.naming.*; import java.util.*; public class ClassCouplingCheckTestInput { private class InnerClass { public List _list = new ArrayList(); } private class AnotherInnerClass { public String _string = ""; } public Set _set = new HashSet(); public Map _map = new HashMap(); public String _string = ""; public int[] _intArray = new int[0]; public InnerClass _innerClass = new InnerClass(); public AnotherInnerClass _anotherInnerClass = new AnotherInnerClass(); public void foo() throws NamingException { } } enum InnerEnum { VALUE1; private InnerEnum() { map2 = new HashMap(); } private Set map1 = new HashSet(); private Map map2; } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/metrics/JavaNCSSCheckTestInput.java100644 0 0 3333 11451071614 30645 0ustar 0 0 // should give an ncss of 35 package com.puppycrawl.tools.checkstyle.metrics; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; //should give an ncss of 22 public class JavaNCSSCheckTestInput { private Object mObject; //should count as 2 private void testMethod1() { //should count as 1 int x = 1, y = 2; } //should count as 4 private void testMethod2() { int abc = 0; //should count as 2 testLabel: abc = 1; } //should give an ncss of 12 private void testMethod3() { int a = 0; switch (a) { case 1: //falls through case 2: System.out.println("Hello"); break; default: break; } ItemListener lis = new ItemListener() { //should give an ncss of 2 public void itemStateChanged(ItemEvent e) { System.out.println("Hello"); } }; } //should give an ncss of 2 private class TestInnerClass { private Object test; } } //should give an ncss of 10 class TestTopLevelNestedClass { private Object mObject; //should give an ncss of 8 private void testMethod() { for (int i=0; i<10; i++) { if (i==0) { //should count as 1 int x = 1, y = 2; } else { int abc = 0; //should count as 2 testLabel: abc = 1; } } } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/MyAnnotation.java100644 0 0 775 11451071613 25417 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // Annotation for use by package definitions // Created: 2005 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import java.lang.annotation.Target; import java.lang.annotation.ElementType; /** * Annotation for use by package definitions * @author Michael Studman */ @Target(value=ElementType.PACKAGE) public @interface MyAnnotation { }checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/naming/InputAbstractClassName.java100644 0 0 1264 11452563037 30643 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.naming; abstract public class InputAbstractClassName { } // abstract --> ^Abstract.*$|^.*Factory$ abstract class NonAbstractClassName { } abstract class FactoryWithBadName { } abstract class AbstractClassName { abstract class NonAbstractInnerClass { } } abstract class ClassFactory { abstract class WellNamedFactory { } } class NonAbstractClass { } //^Abstract.*$|^.*Factory$ --> abstract class AbstractClass { } class Class1Factory { } abstract class AbstractClassName2 { class AbstractInnerClass { } } abstract class Class2Factory { class WellNamedFactory { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/naming/InputConstantNames.java100644 0 0 372 11451071614 30037 0ustar 0 0 import java.io.ObjectStreamField; public class InputConstantNames { private static final long serialVersionUID = 1L; //should be ignored private static final ObjectStreamField[] serialPersistentFields = {}; // should be ignored too } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/naming/InputMemberName.java100644 0 0 362 11451071614 27271 0ustar 0 0 public class InputMemberName { public int mPublic; protected int mProtected; int mPackage; private int mPrivate; public int _public; protected int _protected; int _package; private int _private; } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/naming/InputMethodNameExtra.java100644 0 0 653 11451071614 30311 0ustar 0 0 public class InputMethodNameExtra { public void doit() { createNameHistoryDetails(historyDetails, previousNameService, entityId, new More.ViewChangeHistoryBaseAction.ChangeHistoryDisplayName(agencyName) { String getDisplayName() { return getPreviousName(TypeOfName.AGENCY_NAME); } }); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/naming/InputTypeParameterName.java100644 0 0 1425 11451071614 30665 0ustar 0 0 import java.io.Serializable; public class InputTypeParameterName { public void foo() { } void foo(int i) { } } class Other { foo getOne() { return null; } Tfo$o2T getTwo(Tfo$o2T a) { return null; } foo getShadow() { return null; } static class Junk { <_fo extends foo> void getMoreFoo() { } } } class MoreOther { void getMore() { new Other() { void getMoreFoo() { } }; // Other o = new Other() { // void getMoreFoo() { // } // }; } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/regexp.header100644 0 0 53 11451071614 24546 0ustar 0 0 ^/*$ // .* // Created: 2002 ^.*$ ^.*$ checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/regexp.header1100644 0 0 37 11451071614 24631 0ustar 0 0 ^/*$ // .* ^.*$ ^.*$ ^.*$ checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/regexp.header2100644 0 0 70 11451071614 24627 0ustar 0 0 ^package ^$ ^import ^$ ^/\*\* ^ \*([^/]|$) ^ \*/ checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/suppressions_bad_int.xml100644 0 0 414 11451071614 27102 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/suppressions_multiple.xml100644 0 0 704 11451071614 27337 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/suppressions_none.xml100644 0 0 324 11451071614 26441 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/suppressions_no_check.xml100644 0 0 361 11451071614 27254 0ustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/suppressions_no_file.xml100644 0 0 363 11451071614 27120 0ustar 0 0 ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/whitespace/InputGenericWhitespaceCheck.javacheckstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/whitespace/InputGenericWhitespaceCheck100644 0 0 2766 11451071614 31605 0ustar 0 0 package com.puppycrawl.tools.checkstyle; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.Collections; class InputGenericWhitespaceCheck implements Comparable, Serializable { void meth() { List x = new ArrayList(); List> y = new ArrayList>(); List < Integer > a = new ArrayList < Integer > (); List < List < Integer > > b = new ArrayList < List < Integer > > (); } public int compareTo(InputGenericWhitespaceCheck aObject) { return 0; } public static Callable callable(Runnable task, T result) { return null; } public staticCallable callable2(Runnable task, T result) { Map, Integer> x = new HashMap, Integer>(); for (final Map.Entry, Integer> entry : x.entrySet()) { entry.getValue(); } Class[] parameterClasses = new Class[0]; return null; } public int getConstructor(Class... parameterTypes) { Collections.emptySet(); Collections. emptySet(); return 666; } InputGenericWhitespaceCheck(List things, int i) { } public InputGenericWhitespaceCheck(List things) { } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/whitespace/InputMethodParamPad.java100644 0 0 2771 11451071614 31020 0ustar 0 0 package com.puppycrawl.tools.checkstyle.whitespace; import java.util.Vector; /** Test input for MethodDefPadCheck */ public class InputMethodParamPad { public InputMethodParamPad() { super(); } public InputMethodParamPad (int aParam) { super (); } public InputMethodParamPad (double aParam) { super (); } public void method() { } public void method (int aParam) { } public void method (double aParam) { // invoke constructor InputMethodParamPad pad = new InputMethodParamPad(); pad = new InputMethodParamPad (); pad = new InputMethodParamPad (); // call method method(); method (); method (); } public void dottedCalls() { this.method(); this.method (); this.method (); InputMethodParamPad p = new InputMethodParamPad(); p.method(); p.method (); p.method (); java.lang.Integer.parseInt("0"); java.lang.Integer.parseInt ("0"); java.lang.Integer.parseInt ("0"); } public void newArray() { int[] a = new int[]{0, 1}; java.util.Vector v = new java.util.Vector(); java.util.Vector v1 = new Vector(); } } checkstyle-5.6/src/testinputs/com/puppycrawl/tools/checkstyle/whitespace/InputWhitespaceAround.java100644 0 0 660 11652651451 31420 0ustar 0 0 package com.puppycrawl.tools.checkstyle.whitespace; public class InputWhitespaceAround { protected InputWhitespaceAround ( int i ) { this (); toString (); } protected InputWhitespaceAround () { super (); } public void enhancedFor () { int[] i = new int[2]; for ( int j: i ) { System.out.println ( j ); } } } checkstyle-5.6/src/testinputs/resources/checkstyle/checkstyle_checks.xml100644 0 0 1767 11631376755 24263 0ustar 0 0 checkstyle-5.6/src/testinputs/resources/checkstyle/suppressions.xml100644 0 0 324 11631376755 23326 0ustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/api/AbstractViolationReporterTest.java100644 0 0 10172 12026050776 30541 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import static org.junit.Assert.assertEquals; import java.util.TreeSet; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Assert; import org.junit.Test; /** * Tests to ensure that default messagebundle is determined correctly. * * @author lkuehne */ public class AbstractViolationReporterTest extends BaseCheckTestSupport { private final Check emptyCheck = new Check() { @Override public int[] getDefaultTokens() { return new int[0]; } }; @Test public void testGetMessageBundleWithPackage() { assertEquals("com.mycompany.checks.messages", emptyCheck.getMessageBundle("com.mycompany.checks.MyCoolCheck")); } @Test public void testGetMessageBundleWithoutPackage() { assertEquals("messages", emptyCheck.getMessageBundle("MyCoolCheck")); } @Test public void testCustomMessage() throws CheckstyleException { DefaultConfiguration config = createCheckConfig(emptyCheck.getClass()); config.addMessage("msgKey", "This is a custom message."); emptyCheck.configure(config); LocalizedMessages collector = new LocalizedMessages(); emptyCheck.setMessages(collector); emptyCheck.log(0, "msgKey"); TreeSet messages = collector.getMessages(); Assert.assertTrue(messages.size() == 1); Assert.assertEquals("This is a custom message.", messages.first() .getMessage()); } @Test public void testCustomMessageWithParameters() throws CheckstyleException { DefaultConfiguration config = createCheckConfig(emptyCheck.getClass()); config.addMessage("msgKey", "This is a custom message with {0}."); emptyCheck.configure(config); LocalizedMessages collector = new LocalizedMessages(); emptyCheck.setMessages(collector); emptyCheck.log(0, "msgKey", "TestParam"); TreeSet messages = collector.getMessages(); Assert.assertTrue(messages.size() == 1); Assert.assertEquals("This is a custom message with TestParam.", messages.first().getMessage()); } @Test(expected = IllegalArgumentException.class) public void testCustomMessageWithParametersNegative() throws CheckstyleException { DefaultConfiguration config = createCheckConfig(emptyCheck.getClass()); config.addMessage("msgKey", "This is a custom message {0."); emptyCheck.configure(config); LocalizedMessages collector = new LocalizedMessages(); emptyCheck.setMessages(collector); emptyCheck.log(0, "msgKey", "TestParam"); TreeSet messages = collector.getMessages(); Assert.assertTrue(messages.size() == 1); //we expect an exception here because of the bogus custom message //format messages.first().getMessage(); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/api/AutomaticBeanTest.java100644 0 0 3303 12026050776 26060 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class AutomaticBeanTest { private static class TestBean extends AutomaticBean { public void setName(String aName) { } } private final DefaultConfiguration mConf = new DefaultConfiguration( "testConf"); private final TestBean mTestBean = new TestBean(); @Test(expected = CheckstyleException.class) public void testNoSuchAttribute() throws CheckstyleException { mConf.addAttribute("NonExisting", "doesn't matter"); mTestBean.configure(mConf); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/api/DetailASTTest.java100644 0 0 11266 12026050776 25145 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import com.puppycrawl.tools.checkstyle.TreeWalker; import java.io.File; import java.io.FileFilter; import java.text.MessageFormat; import org.junit.Test; /** * TestCase to check DetailAST. * @author Oliver Burn */ public class DetailASTTest { @Test public void testGetChildCount() { final DetailAST root = new DetailAST(); final DetailAST firstLevelA = new DetailAST(); final DetailAST firstLevelB = new DetailAST(); final DetailAST secondLevelA = new DetailAST(); root.setFirstChild(firstLevelA); firstLevelA.setParent(root); firstLevelA.setFirstChild(secondLevelA); firstLevelA.setNextSibling(firstLevelB); firstLevelB.setParent(root); secondLevelA.setParent(firstLevelA); assertEquals(0, secondLevelA.getChildCount()); assertEquals(0, firstLevelB.getChildCount()); assertEquals(1, firstLevelA.getChildCount()); assertEquals(2, root.getChildCount()); assertEquals(2, root.getChildCount()); assertNull(root.getPreviousSibling()); assertNull(firstLevelA.getPreviousSibling()); assertNull(secondLevelA.getPreviousSibling()); assertEquals(firstLevelA, firstLevelB.getPreviousSibling()); } @Test public void testTreeStructure() throws Exception { checkDir(new File(System.getProperty("testinputs.dir"))); } private void checkDir(File dir) throws Exception { File[] files = dir.listFiles(new FileFilter() { public boolean accept(File file) { return (file.getName().endsWith(".java") || file.isDirectory()) && !file.getName().endsWith("InputGrammar.java"); } }); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { checkFile(files[i].getCanonicalPath()); } else if (files[i].isDirectory()) { checkDir(files[i]); } } } private void checkFile(String filename) throws Exception { final FileText text = new FileText(new File(filename), System.getProperty("file.encoding", "UTF-8")); final FileContents contents = new FileContents(text); final DetailAST rootAST = TreeWalker.parse(contents); checkTree(rootAST, null, null, filename, rootAST); } private void checkTree(final DetailAST node, final DetailAST parent, final DetailAST prev, final String filename, final DetailAST root) { Object[] params = new Object[] { node, parent, prev, filename, root, }; String msg = MessageFormat.format( "Bad parent node={0} parent={1} filename={3} root={4}", params); assertEquals(msg, parent, node.getParent()); msg = MessageFormat.format( "Bad prev node={0} prev={2} parent={1} filename={3} root={4}", params); assertEquals(msg, prev, node.getPreviousSibling()); if (node.getFirstChild() != null) { checkTree(node.getFirstChild(), node, null, filename, root); } if (node.getNextSibling() != null) { checkTree(node.getNextSibling(), parent, node, filename, root); } } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/api/FastStackTest.java100644 0 0 5120 12026050776 25226 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Test; public class FastStackTest { @Test(expected = IllegalStateException.class) public void testPeek() { new FastStack().peek(); } @Test(expected = IllegalStateException.class) public void testPop() { new FastStack().pop(); } @Test public void testNormal() { final FastStack fs = FastStack.newInstance(); assertNotNull(fs); assertTrue(fs.isEmpty()); assertEquals(0, fs.size()); final int num = 100; for (int i = 0; i < num; i++) { fs.push(i); } assertEquals(num, fs.size()); assertFalse(fs.isEmpty()); assertEquals(1, fs.peek(1).intValue()); assertEquals(num - 1, fs.peek().intValue()); assertEquals(num, fs.size()); for (int i = 0; i < num; i++) { fs.pop(); } assertTrue(fs.isEmpty()); assertEquals(0, fs.size()); fs.push(666); assertEquals(1, fs.size()); assertFalse(fs.isEmpty()); assertTrue(fs.contains(666)); assertFalse(fs.contains(667)); fs.clear(); assertFalse(fs.contains(666)); assertTrue(fs.isEmpty()); assertEquals(0, fs.size()); assertFalse(fs.iterator().hasNext()); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/api/ScopeTest.java100644 0 0 10400 12026050775 24430 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Test; public class ScopeTest { @Test(expected = IllegalArgumentException.class) public void testMisc() { final Scope o = Scope.getInstance("public"); assertNotNull(o); assertEquals("public", o.toString()); assertEquals("public", o.getName()); Scope.getInstance("unknown"); // will fail } @Test public void testMixedCaseSpaces() { Scope.getInstance("NothinG "); Scope.getInstance(" PuBlic"); Scope.getInstance(" ProteCted"); Scope.getInstance(" PackAge "); Scope.getInstance("privaTe "); Scope.getInstance("AnonInner"); } @Test public void testIsInAnonInner() { assertTrue(Scope.NOTHING.isIn(Scope.ANONINNER)); assertTrue(Scope.PUBLIC.isIn(Scope.ANONINNER)); assertTrue(Scope.PROTECTED.isIn(Scope.ANONINNER)); assertTrue(Scope.PACKAGE.isIn(Scope.ANONINNER)); assertTrue(Scope.PRIVATE.isIn(Scope.ANONINNER)); assertTrue(Scope.ANONINNER.isIn(Scope.ANONINNER)); } @Test public void testIsInPrivate() { assertTrue(Scope.NOTHING.isIn(Scope.PRIVATE)); assertTrue(Scope.PUBLIC.isIn(Scope.PRIVATE)); assertTrue(Scope.PROTECTED.isIn(Scope.PRIVATE)); assertTrue(Scope.PACKAGE.isIn(Scope.PRIVATE)); assertTrue(Scope.PRIVATE.isIn(Scope.PRIVATE)); assertTrue(!Scope.ANONINNER.isIn(Scope.PRIVATE)); } @Test public void testIsInPackage() { assertTrue(Scope.NOTHING.isIn(Scope.PACKAGE)); assertTrue(Scope.PUBLIC.isIn(Scope.PACKAGE)); assertTrue(Scope.PROTECTED.isIn(Scope.PACKAGE)); assertTrue(Scope.PACKAGE.isIn(Scope.PACKAGE)); assertTrue(!Scope.PRIVATE.isIn(Scope.PACKAGE)); assertTrue(!Scope.ANONINNER.isIn(Scope.PACKAGE)); } @Test public void testIsInProtected() { assertTrue(Scope.NOTHING.isIn(Scope.PROTECTED)); assertTrue(Scope.PUBLIC.isIn(Scope.PROTECTED)); assertTrue(Scope.PROTECTED.isIn(Scope.PROTECTED)); assertTrue(!Scope.PACKAGE.isIn(Scope.PROTECTED)); assertTrue(!Scope.PRIVATE.isIn(Scope.PROTECTED)); assertTrue(!Scope.ANONINNER.isIn(Scope.PROTECTED)); } @Test public void testIsInPublic() { assertTrue(Scope.NOTHING.isIn(Scope.PUBLIC)); assertTrue(Scope.PUBLIC.isIn(Scope.PUBLIC)); assertTrue(!Scope.PROTECTED.isIn(Scope.PUBLIC)); assertTrue(!Scope.PACKAGE.isIn(Scope.PUBLIC)); assertTrue(!Scope.PRIVATE.isIn(Scope.PUBLIC)); assertTrue(!Scope.ANONINNER.isIn(Scope.PUBLIC)); } @Test public void testIsInNothing() { assertTrue(Scope.NOTHING.isIn(Scope.NOTHING)); assertTrue(!Scope.PUBLIC.isIn(Scope.NOTHING)); assertTrue(!Scope.PROTECTED.isIn(Scope.NOTHING)); assertTrue(!Scope.PACKAGE.isIn(Scope.NOTHING)); assertTrue(!Scope.PRIVATE.isIn(Scope.NOTHING)); assertTrue(!Scope.ANONINNER.isIn(Scope.NOTHING)); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/api/SeverityLevelTest.java100644 0 0 3452 12026050775 26152 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; public class SeverityLevelTest { @Test(expected = IllegalArgumentException.class) public void testMisc() { final SeverityLevel o = SeverityLevel.getInstance("info"); assertNotNull(o); assertEquals("info", o.toString()); assertEquals("info", o.getName()); SeverityLevel.getInstance("unknown"); // will fail } @Test public void testMixedCaseSpaces() { SeverityLevel.getInstance("IgnoRe "); SeverityLevel.getInstance(" iNfo"); SeverityLevel.getInstance(" WarniNg"); SeverityLevel.getInstance(" ERROR "); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/api/TokenTypesTest.java100644 0 0 2633 12026050775 25455 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.api; import static org.junit.Assert.assertEquals; import org.junit.Test; public class TokenTypesTest { @Test public void testGetShortDescription() { assertEquals("short description for EQUAL", "The == (equal) operator.", TokenTypes .getShortDescription("EQUAL")); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/BaseCheckTestSupport.java100644 0 0 11601 11451071614 26013 0ustar 0 0 package com.puppycrawl.tools.checkstyle; import static org.junit.Assert.assertEquals; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.Configuration; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Properties; public abstract class BaseCheckTestSupport { /** a brief logger that only display info about errors */ protected static class BriefLogger extends DefaultLogger { public BriefLogger(OutputStream out) { super(out, true); } @Override public void auditStarted(AuditEvent evt) {} @Override public void fileFinished(AuditEvent evt) {} @Override public void fileStarted(AuditEvent evt) {} } protected final ByteArrayOutputStream mBAOS = new ByteArrayOutputStream(); protected final PrintStream mStream = new PrintStream(mBAOS); protected final Properties mProps = new Properties(); public static DefaultConfiguration createCheckConfig(Class aClazz) { final DefaultConfiguration checkConfig = new DefaultConfiguration(aClazz.getName()); return checkConfig; } protected Checker createChecker(Configuration aCheckConfig) throws Exception { final DefaultConfiguration dc = createCheckerConfig(aCheckConfig); final Checker c = new Checker(); // make sure the tests always run with english error messages // so the tests don't fail in supported locales like german final Locale locale = Locale.ENGLISH; c.setLocaleCountry(locale.getCountry()); c.setLocaleLanguage(locale.getLanguage()); c.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); c.configure(dc); c.addListener(new BriefLogger(mStream)); return c; } protected DefaultConfiguration createCheckerConfig(Configuration aConfig) { final DefaultConfiguration dc = new DefaultConfiguration("configuration"); final DefaultConfiguration twConf = createCheckConfig(TreeWalker.class); // make sure that the tests always run with this charset dc.addAttribute("charset", "iso-8859-1"); dc.addChild(twConf); twConf.addChild(aConfig); return dc; } protected static String getPath(String aFilename) throws IOException { final File f = new File(System.getProperty("testinputs.dir"), aFilename); return f.getCanonicalPath(); } protected static String getSrcPath(String aFilename) throws IOException { final File f = new File(System.getProperty("testsrcs.dir"), aFilename); return f.getCanonicalPath(); } protected void verify(Configuration aConfig, String aFileName, String[] aExpected) throws Exception { verify(createChecker(aConfig), aFileName, aFileName, aExpected); } protected void verify(Checker aC, String aFileName, String[] aExpected) throws Exception { verify(aC, aFileName, aFileName, aExpected); } protected void verify(Checker aC, String aProcessedFilename, String aMessageFileName, String[] aExpected) throws Exception { verify(aC, new File[] {new File(aProcessedFilename)}, aMessageFileName, aExpected); } protected void verify(Checker aC, File[] aProcessedFiles, String aMessageFileName, String[] aExpected) throws Exception { mStream.flush(); final List theFiles = Lists.newArrayList(); Collections.addAll(theFiles, aProcessedFiles); final int errs = aC.process(theFiles); // process each of the lines final ByteArrayInputStream bais = new ByteArrayInputStream(mBAOS.toByteArray()); final LineNumberReader lnr = new LineNumberReader(new InputStreamReader(bais)); for (int i = 0; i < aExpected.length; i++) { final String expected = aMessageFileName + ":" + aExpected[i]; final String actual = lnr.readLine(); assertEquals("error message " + i, expected, actual); } assertEquals("unexpected output: " + lnr.readLine(), aExpected.length, errs); aC.destroy(); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/BaseFileSetCheckTestSupport.java100644 0 0 664 11451071614 27236 0ustar 0 0 package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.Configuration; public class BaseFileSetCheckTestSupport extends BaseCheckTestSupport { @Override protected DefaultConfiguration createCheckerConfig( Configuration aCheckConfig) { final DefaultConfiguration dc = new DefaultConfiguration("root"); dc.addChild(aCheckConfig); return dc; } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/CheckerTest.java100644 0 0 23401 12026051000 24135 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import java.io.File; import java.util.TreeSet; import org.junit.Test; public class CheckerTest { @Test public void testDosBasedir() throws Exception { final Checker c = new Checker(); c.setBasedir("c:/a\\b/./c\\..\\d"); assertEquals("C:\\a\\b\\d", c.getBasedir()); } @Test public void testOsBasedir() throws Exception { final Checker c = new Checker(); // we need something to create absolute path // let's take testinputs.dir String testinputs_dir = System.getProperty("testinputs.dir") .replace('/', File.separatorChar) .replace('\\', File.separatorChar); if (!testinputs_dir.endsWith(File.separator)) { testinputs_dir += File.separator; } final String instr = testinputs_dir + "indentation/./..\\coding\\"; c.setBasedir(instr); assertTrue((testinputs_dir + "coding").equalsIgnoreCase(c.getBasedir())); } @Test public void testDestroy() throws Exception { final DebugChecker c = new DebugChecker(); final DebugAuditAdapter aa = new DebugAuditAdapter(); c.addListener(aa); final DebugFilter f = new DebugFilter(); c.addFilter(f); c.destroy(); // should remove al listeners and filters // Let's try fire some events c.fireAuditStarted(); c.fireAuditFinished(); c.fireFileStarted("Some File Name"); c.fireFileFinished("Some File Name"); final TreeSet msgs = Sets.newTreeSet(); msgs.add(new LocalizedMessage(0, 0, "a Bundle", "message.key", new Object[] {"arg"}, null, getClass(), null)); c.fireErrors("Some File Name", msgs); assertFalse("Checker.destroy() doesn't remove listeners.", aa.wasCalled()); assertFalse("Checker.destroy() doesn't remove filters.", f.wasCalled()); } @Test public void testAddListener() throws Exception { final DebugChecker c = new DebugChecker(); final DebugAuditAdapter aa = new DebugAuditAdapter(); c.addListener(aa); // Let's try fire some events c.fireAuditStarted(); assertTrue("Checker.fireAuditStarted() doesn't call listener", aa.wasCalled()); aa.resetListener(); c.fireAuditFinished(); assertTrue("Checker.fireAuditFinished() doesn't call listener", aa.wasCalled()); aa.resetListener(); c.fireFileStarted("Some File Name"); assertTrue("Checker.fireFileStarted() doesn't call listener", aa.wasCalled()); aa.resetListener(); c.fireFileFinished("Some File Name"); assertTrue("Checker.fireFileFinished() doesn't call listener", aa.wasCalled()); aa.resetListener(); final TreeSet msgs = Sets.newTreeSet(); msgs.add(new LocalizedMessage(0, 0, "a Bundle", "message.key", new Object[] {"arg"}, null, getClass(), null)); c.fireErrors("Some File Name", msgs); assertTrue("Checker.fireErrors() doesn't call listener", aa.wasCalled()); } @Test public void testRemoveListener() throws Exception { final DebugChecker c = new DebugChecker(); final DebugAuditAdapter aa = new DebugAuditAdapter(); final DebugAuditAdapter aa2 = new DebugAuditAdapter(); c.addListener(aa); c.addListener(aa2); c.removeListener(aa); // Let's try fire some events c.fireAuditStarted(); assertTrue("Checker.fireAuditStarted() doesn't call listener", aa2.wasCalled()); assertFalse("Checker.fireAuditStarted() does call removed listener", aa.wasCalled()); aa2.resetListener(); c.fireAuditFinished(); assertTrue("Checker.fireAuditFinished() doesn't call listener", aa2.wasCalled()); assertFalse("Checker.fireAuditFinished() does call removed listener", aa.wasCalled()); aa2.resetListener(); c.fireFileStarted("Some File Name"); assertTrue("Checker.fireFileStarted() doesn't call listener", aa2.wasCalled()); assertFalse("Checker.fireFileStarted() does call removed listener", aa.wasCalled()); aa2.resetListener(); c.fireFileFinished("Some File Name"); assertTrue("Checker.fireFileFinished() doesn't call listener", aa2.wasCalled()); assertFalse("Checker.fireFileFinished() does call removed listener", aa.wasCalled()); aa2.resetListener(); final TreeSet msgs = Sets.newTreeSet(); msgs.add(new LocalizedMessage(0, 0, "a Bundle", "message.key", new Object[] {"arg"}, null, getClass(), null)); c.fireErrors("Some File Name", msgs); assertTrue("Checker.fireErrors() doesn't call listener", aa2.wasCalled()); assertFalse("Checker.fireErrors() does call removed listener", aa.wasCalled()); } @Test public void testAddFilter() throws Exception { final DebugChecker c = new DebugChecker(); final DebugFilter f = new DebugFilter(); c.addFilter(f); // Let's try fire some events // we do not call filter in fireAuditStarted() (fix for 1080343) // c.fireAuditStarted(); // assertTrue("Checker.fireAuditStarted() doesn't call filter", f.wasCalled()); // we do not call filter in fireAuditFinished() (fix for 1080343) // f.resetFilter(); // c.fireAuditFinished(); // assertTrue("Checker.fireAuditFinished() doesn't call filter", f.wasCalled()); // we do not call filter in fireFileStarted() (fix for 1080343) // f.resetFilter(); // c.fireFileStarted("Some File Name"); // assertTrue("Checker.fireFileStarted() doesn't call filter", f.wasCalled()); // we do not call filter in fireFileFinished() (fix for 1080343) // f.resetFilter(); // c.fireFileFinished("Some File Name"); // assertTrue("Checker.fireFileFinished() doesn't call filter", f.wasCalled()); f.resetFilter(); final TreeSet msgs = Sets.newTreeSet(); msgs.add(new LocalizedMessage(0, 0, "a Bundle", "message.key", new Object[] {"arg"}, null, getClass(), null)); c.fireErrors("Some File Name", msgs); assertTrue("Checker.fireErrors() doesn't call filter", f.wasCalled()); } @Test public void testRemoveFilter() throws Exception { final DebugChecker c = new DebugChecker(); final DebugFilter f = new DebugFilter(); final DebugFilter f2 = new DebugFilter(); c.addFilter(f); c.addFilter(f2); c.removeFilter(f); // Let's try fire some events // we do call filter in fireErrors() only (fix for 1080343) // c.fireAuditStarted(); // assertTrue("Checker.fireAuditStarted() doesn't call filter", f2.wasCalled()); // assertFalse("Checker.fireAuditStarted() does call removed filter", f.wasCalled()); // we do call filter in fireErrors() only (fix for 1080343) // f2.resetFilter(); // c.fireAuditFinished(); // assertTrue("Checker.fireAuditFinished() doesn't call filter", f2.wasCalled()); // assertFalse("Checker.fireAuditFinished() does call removed filter", f.wasCalled()); // we do call filter in fireErrors() only (fix for 1080343) // f2.resetFilter(); // c.fireFileStarted("Some File Name"); // assertTrue("Checker.fireFileStarted() doesn't call filter", f2.wasCalled()); // assertFalse("Checker.fireFileStarted() does call removed filter", f.wasCalled()); // we do call filter in fireErrors() only (fix for 1080343) // f2.resetFilter(); // c.fireFileFinished("Some File Name"); // assertTrue("Checker.fireFileFinished() doesn't call filter", f2.wasCalled()); // assertFalse("Checker.fireFileFinished() does call removed filter", f.wasCalled()); f2.resetFilter(); final TreeSet msgs = Sets.newTreeSet(); msgs.add(new LocalizedMessage(0, 0, "a Bundle", "message.key", new Object[] {"arg"}, null, getClass(), null)); c.fireErrors("Some File Name", msgs); assertTrue("Checker.fireErrors() doesn't call filter", f2.wasCalled()); assertFalse("Checker.fireErrors() does call removed filter", f.wasCalled()); } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationUseStyleTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationUseStyleTest.ja100644 0 0 22726 12026050772 31514 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.annotation; import java.io.File; import org.junit.Test; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class AnnotationUseStyleTest extends BaseCheckTestSupport { /** * Test that annotation parens are always present. * @throws Exception */ @Test public void testParansAlways() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(AnnotationUseStyleCheck.class); checkConfig.addAttribute("closingParens", "ALWAYS"); checkConfig.addAttribute("elementStyle", "ignore"); checkConfig.addAttribute("trailingArrayComma", "ignore"); final String[] expected = { "3: Annotation must have closing parenthesis.", "18: Annotation must have closing parenthesis.", "23: Annotation must have closing parenthesis.", }; verify(checkConfig, getPath("annotation" + File.separator + "DifferentUseStyles.java"), expected); } /** * Test that annotation parens are never present. * @throws Exception */ @Test public void testParansNever() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(AnnotationUseStyleCheck.class); checkConfig.addAttribute("closingParens", "NEVER"); checkConfig.addAttribute("elementStyle", "ignore"); checkConfig.addAttribute("trailingArrayComma", "ignore"); final String[] expected = { "13: Annotation cannot have closing parenthesis.", "30: Annotation cannot have closing parenthesis.", "33: Annotation cannot have closing parenthesis.", }; verify(checkConfig, getPath("annotation" + File.separator + "DifferentUseStyles.java"), expected); } @Test public void testStyleExpanded() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(AnnotationUseStyleCheck.class); checkConfig.addAttribute("closingParens", "ignore"); checkConfig.addAttribute("elementStyle", "EXPANDED"); checkConfig.addAttribute("trailingArrayComma", "ignore"); final String[] expected = { "5: Annotation style must be 'EXPANDED'.", "12: Annotation style must be 'EXPANDED'.", "20: Annotation style must be 'EXPANDED'.", "26: Annotation style must be 'EXPANDED'.", "39: Annotation style must be 'EXPANDED'.", "41: Annotation style must be 'EXPANDED'.", "58: Annotation style must be 'EXPANDED'.", }; verify(checkConfig, getPath("annotation" + File.separator + "DifferentUseStyles.java"), expected); } @Test public void testStyleCompact() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(AnnotationUseStyleCheck.class); checkConfig.addAttribute("closingParens", "ignore"); checkConfig.addAttribute("elementStyle", "COMPACT"); checkConfig.addAttribute("trailingArrayComma", "ignore"); final String[] expected = { "43: Annotation style must be 'COMPACT'.", "47: Annotation style must be 'COMPACT'.", }; verify(checkConfig, getPath("annotation" + File.separator + "DifferentUseStyles.java"), expected); } @Test public void testStyleCompactNoArray() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(AnnotationUseStyleCheck.class); checkConfig.addAttribute("closingParens", "ignore"); checkConfig.addAttribute("elementStyle", "COMPACT_NO_ARRAY"); checkConfig.addAttribute("trailingArrayComma", "ignore"); final String[] expected = { "5: Annotation style must be 'COMPACT_NO_ARRAY'.", "20: Annotation style must be 'COMPACT_NO_ARRAY'.", "41: Annotation style must be 'COMPACT_NO_ARRAY'.", "43: Annotation style must be 'COMPACT_NO_ARRAY'.", "47: Annotation style must be 'COMPACT_NO_ARRAY'.", }; verify(checkConfig, getPath("annotation" + File.separator + "DifferentUseStyles.java"), expected); } @Test public void testCommaAlwaysViolations() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(AnnotationUseStyleCheck.class); checkConfig.addAttribute("closingParens", "ignore"); checkConfig.addAttribute("elementStyle", "ignore"); checkConfig.addAttribute("trailingArrayComma", "ALWAYS"); final String[] expected = { "3:20: Annotation array values must contain trailing comma.", "6:30: Annotation array values must contain trailing comma.", "10:40: Annotation array values must contain trailing comma.", "13:44: Annotation array values must contain trailing comma.", "16:54: Annotation array values must contain trailing comma.", "24:37: Annotation array values must contain trailing comma.", "24:65: Annotation array values must contain trailing comma.", "26:21: Annotation array values must contain trailing comma.", "26:30: Annotation array values must contain trailing comma.", "29:39: Annotation array values must contain trailing comma.", "29:49: Annotation array values must contain trailing comma.", "32:21: Annotation array values must contain trailing comma.", "32:56: Annotation array values must contain trailing comma.", }; verify(checkConfig, getPath("annotation" + File.separator + "AnnotationUseNoTrailingComma.java"), expected); } @Test public void testCommaAlwaysNoViolations() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(AnnotationUseStyleCheck.class); checkConfig.addAttribute("closingParens", "ignore"); checkConfig.addAttribute("elementStyle", "ignore"); checkConfig.addAttribute("trailingArrayComma", "ALWAYS"); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "AnnotationUseWithTrailingComma.java"), expected); } @Test public void testCommaNeverViolations() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(AnnotationUseStyleCheck.class); checkConfig.addAttribute("closingParens", "ignore"); checkConfig.addAttribute("elementStyle", "ignore"); checkConfig.addAttribute("trailingArrayComma", "NEVER"); final String[] expected = { "9:32: Annotation array values cannot contain trailing comma.", "13:42: Annotation array values cannot contain trailing comma.", "16:46: Annotation array values cannot contain trailing comma.", "19:56: Annotation array values cannot contain trailing comma.", "27:38: Annotation array values cannot contain trailing comma.", "27:67: Annotation array values cannot contain trailing comma.", "33:39: Annotation array values cannot contain trailing comma.", "33:50: Annotation array values cannot contain trailing comma.", }; verify(checkConfig, getPath("annotation" + File.separator + "AnnotationUseWithTrailingComma.java"), expected); } @Test public void testCommaNeverNoViolations() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(AnnotationUseStyleCheck.class); checkConfig.addAttribute("closingParens", "ignore"); checkConfig.addAttribute("elementStyle", "ignore"); checkConfig.addAttribute("trailingArrayComma", "NEVER"); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "AnnotationUseNoTrailingComma.java"), expected); } @Test public void testEverythingMixed() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(AnnotationUseStyleCheck.class); checkConfig.addAttribute("closingParens", "ignore"); checkConfig.addAttribute("elementStyle", "ignore"); checkConfig.addAttribute("trailingArrayComma", "ignore"); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "DifferentUseStyles.java"), expected); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/annotation/MissingDeprecatedTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/annotation/MissingDeprecatedTest.jav100644 0 0 13501 12026050772 31453 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.annotation; import java.io.File; import org.junit.Test; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class MissingDeprecatedTest extends BaseCheckTestSupport { /** * Tests that memebers that are only deprecated via javadoc are flagged. */ @Test public void testBadDeprecatedAnnotation() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingDeprecatedCheck.class); final String[] expected = { "7: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "12: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "19: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "26: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "31: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "38: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "43: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "51: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "56: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", }; verify(checkConfig, getPath("annotation" + File.separator + "BadDeprecatedAnnotation.java"), expected); } /** * Tests that memebers that are only deprecated via the annotation are flagged. */ @Test public void testBadDeprecatedJavadoc() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingDeprecatedCheck.class); final String[] expected = { "5: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "11: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "16: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "23: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "29: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "38: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "40: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "48: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "55: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", }; verify(checkConfig, getPath("annotation" + File.separator + "BadDeprecatedJavadoc.java"), expected); } /** * Tests various special deprecation conditions such as duplicate or empty tags. */ @Test public void testSpecialCaseDeprecated() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingDeprecatedCheck.class); final String[] expected = { "5: Duplicate @deprecated tag.", "12: Duplicate @deprecated tag.", "14: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "17: Missing a Javadoc comment.", "19: Must include both @java.lang.Deprecated annotation and @deprecated Javadoc tag with description.", "24: Missing a Javadoc comment.", "32: Missing a Javadoc comment.", "33: Duplicate @deprecated tag.", "33: Missing a Javadoc comment.", "42: Duplicate @deprecated tag.", "42: Missing a Javadoc comment.", "50: Missing a Javadoc comment.", "51: Duplicate @deprecated tag.", }; verify(checkConfig, getPath("annotation" + File.separator + "SpecialCaseDeprecated.java"), expected); } /** * Tests that good forms of deprecation are not flagged. */ @Test public void testGoodDeprecated() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingDeprecatedCheck.class); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "GoodDeprecated.java"), expected); } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/annotation/MissingOverrideCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/annotation/MissingOverrideCheckTest.100644 0 0 25402 12026050772 31432 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.annotation; import java.io.File; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class MissingOverrideCheckTest extends BaseCheckTestSupport { /** * This tests that classes not extending anything explicitly will be correctly * flagged for only including the inheritDoc tag. * @throws Exception */ @Test public void testBadOverrideFromObject() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); checkConfig.addAttribute("javaFiveCompatibility", "false"); final String[] expected = { "8: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "30: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "41: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "50: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", }; verify(checkConfig, getPath("annotation" + File.separator + "BadOverrideFromObject.java"), expected); } /** * This tests that classes not extending anything explicitly will be correctly * flagged for only including the inheritDoc tag even in Java 5 compatibility mode. * @throws Exception */ @Test public void testBadOverrideFromObjectJ5Compat() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); checkConfig.addAttribute("javaFiveCompatibility", "true"); final String[] expected = { "8: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "30: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "41: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "50: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", }; verify(checkConfig, getPath("annotation" + File.separator + "BadOverrideFromObject.java"), expected); } /** * This tests classes that are extending things explicitly will be correctly * flagged for only including the inheritDoc tag. * @throws Exception */ @Test public void testBadOverrideFromOther() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); final String[] expected = { "10: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "26: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "34: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "40: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "47: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "53: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "63: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", }; verify(checkConfig, getPath("annotation" + File.separator + "BadOverrideFromOther.java"), expected); } /** * This tests classes that are extending things explicitly will NOT be flagged while in * Java 5 compatibility mode. * @throws Exception */ @Test public void testBadOverrideFromOtherJ5Compat() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); checkConfig.addAttribute("javaFiveCompatibility", "true"); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "BadOverrideFromOther.java"), expected); } /** * This tests anonymous inner classes that are overriding methods are correctly flagged * for only including the inheritDoc tag. * @throws Exception */ @Test public void testBadAnnonOverride() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); final String[] expected = { "10: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "16: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "29: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", "35: Must include @java.lang.Override annotation when {@inheritDoc} Javadoc tag exists.", }; verify(checkConfig, getPath("annotation" + File.separator + "BadAnnonOverride.java"), expected); } /** * This tests anonymous inner classes that are overriding methods are NOT flagged while in * Java 5 compatibility mode. * @throws Exception */ @Test public void testBadAnnonOverrideJ5Compat() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); checkConfig.addAttribute("javaFiveCompatibility", "true"); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "BadAnnonOverride.java"), expected); } /** * Tests that inheritDoc misuse is properly flagged or missing Javadocs do not cause a problem. * @throws Exception */ @Test public void testNotOverride() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); final String[] expected = { "8: The Javadoc {@inheritDoc} tag is not valid at this location.", "15: The Javadoc {@inheritDoc} tag is not valid at this location.", //this wont be flagged because this check only checks methods. //"22: The Javadoc comment contains an {@inheritDoc} tag. The tag is not valid at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "NotOverride.java"), expected); } /** * This tests that classes not extending anything explicitly will be correctly * flagged for only including the inheritDoc tag. * @throws Exception */ @Test public void testGoodOverrideFromObject() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); checkConfig.addAttribute("javaFiveCompatibility", "false"); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "GoodOverrideFromObject.java"), expected); } /** * This tests that classes not extending anything explicitly will be correctly * flagged for only including the inheritDoc tag even in Java 5 compatibility mode. * @throws Exception */ @Test public void testGoodOverrideFromObjectJ5Compat() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); checkConfig.addAttribute("javaFiveCompatibility", "true"); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "GoodOverrideFromObject.java"), expected); } /** * This tests classes that are extending things explicitly will be correctly * flagged for only including the inheritDoc tag. * @throws Exception */ @Test public void testGoodOverrideFromOther() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "GoodOverrideFromOther.java"), expected); } /** * This tests classes that are extending things explicitly will NOT be flagged while in * Java 5 compatibility mode. * @throws Exception */ @Test public void testGoodOverrideFromOtherJ5Compat() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); checkConfig.addAttribute("javaFiveCompatibility", "true"); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "GoodOverrideFromOther.java"), expected); } /** * This tests anonymous inner classes that are overriding methods are correctly flagged * for only including the inheritDoc tag. * @throws Exception */ @Test public void testGoodAnnonOverride() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "GoodAnnonOverride.java"), expected); } /** * This tests anonymous inner classes that are overriding methods are NOT flagged while in * Java 5 compatibility mode. * @throws Exception */ @Test public void testGoodAnnonOverrideJ5Compat() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingOverrideCheck.class); checkConfig.addAttribute("javaFiveCompatibility", "true"); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "GoodAnnonOverride.java"), expected); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/annotation/PackageAnnotationTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/annotation/PackageAnnotationTest.jav100644 0 0 5552 12026050771 31435 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.annotation; import java.io.File; import org.junit.Test; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class PackageAnnotationTest extends BaseCheckTestSupport { /** * This tests 1 package annotation that is not in the package-info.java file. * * @throws Exception */ @Test public void testBadPackageAnnotation1() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(PackageAnnotationCheck.class); final String[] expected = { "0: Package annotations must be in the package-info.java info.", }; verify(checkConfig, getPath("annotation" + File.separator + "BadPackageAnnotation1.java"), expected); } /** * This tests 2 package annotations that are not in the package-info.java file. * * @throws Exception */ @Test public void testBadPackageAnnotation2() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(PackageAnnotationCheck.class); final String[] expected = { "0: Package annotations must be in the package-info.java info.", }; verify(checkConfig, getPath("annotation" + File.separator + "BadPackageAnnotation2.java"), expected); } /** * This tests a package annotation that is in the package-info.java file. * * @throws Exception */ @Test public void testGoodPackageAnnotation() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(PackageAnnotationCheck.class); final String[] expected = { }; verify(checkConfig, getPath("annotation" + File.separator + "package-info.java"), expected); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/annotation/SuppressWarningsTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/annotation/SuppressWarningsTest.java100644 0 0 136136 12026050771 31610 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.annotation; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class SuppressWarningsTest extends BaseCheckTestSupport { /** * Tests SuppressWarnings with default regex. * @throws Exception */ @Test public void testSingleDefault() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); final String[] expected = { "8:23: The warning ' ' cannot be suppressed at this location.", "11:27: The warning '' cannot be suppressed at this location.", "53:27: The warning '' cannot be suppressed at this location.", "64:47: The warning '' cannot be suppressed at this location.", "67:37: The warning '' cannot be suppressed at this location.", "72:46: The warning ' ' cannot be suppressed at this location.", "77:60: The warning ' ' cannot be suppressed at this location.", "82:93: The warning '' cannot be suppressed at this location.", "82:106: The warning ' ' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsSingle.java"), expected); } /** * Tests SuppressWarnings all warnings disabled on everything. * @throws Exception */ @Test public void testSingleAll() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", ".*"); final String[] expected = { "5:19: The warning 'unchecked' cannot be suppressed at this location.", "8:23: The warning ' ' cannot be suppressed at this location.", "11:27: The warning '' cannot be suppressed at this location.", "17:23: The warning 'unused' cannot be suppressed at this location.", "20:27: The warning 'unforgiven' cannot be suppressed at this location.", "25:31: The warning 'unused' cannot be suppressed at this location.", "29:35: The warning 'unchecked' cannot be suppressed at this location.", "37:23: The warning 'abcun' cannot be suppressed at this location.", "44:23: The warning 'abcun' cannot be suppressed at this location.", "47:27: The warning 'unused' cannot be suppressed at this location.", "53:27: The warning '' cannot be suppressed at this location.", "56:27: The warning 'unchecked' cannot be suppressed at this location.", "59:48: The warning 'unchecked' cannot be suppressed at this location.", "64:33: The warning 'unchecked' cannot be suppressed at this location.", "64:47: The warning '' cannot be suppressed at this location.", "67:37: The warning '' cannot be suppressed at this location.", "67:42: The warning 'unchecked' cannot be suppressed at this location.", "72:46: The warning ' ' cannot be suppressed at this location.", "72:54: The warning 'unused' cannot be suppressed at this location.", "72:65: The warning 'unchecked' cannot be suppressed at this location.", "77:37: The warning 'unchecked' cannot be suppressed at this location.", "77:60: The warning ' ' cannot be suppressed at this location.", "77:68: The warning 'unused' cannot be suppressed at this location.", "82:47: The warning 'unchecked' cannot be suppressed at this location.", "82:93: The warning '' cannot be suppressed at this location.", "82:98: The warning 'foo' cannot be suppressed at this location.", "82:106: The warning ' ' cannot be suppressed at this location.", "82:115: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsSingle.java"), expected); } /** * Tests SuppressWarnings unchecked warning disabled on everything. * @throws Exception */ @Test public void testSingleNoUnchecked() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*"); final String[] expected = { "5:19: The warning 'unchecked' cannot be suppressed at this location.", "29:35: The warning 'unchecked' cannot be suppressed at this location.", "56:27: The warning 'unchecked' cannot be suppressed at this location.", "59:48: The warning 'unchecked' cannot be suppressed at this location.", "64:33: The warning 'unchecked' cannot be suppressed at this location.", "67:42: The warning 'unchecked' cannot be suppressed at this location.", "72:65: The warning 'unchecked' cannot be suppressed at this location.", "77:37: The warning 'unchecked' cannot be suppressed at this location.", "82:47: The warning 'unchecked' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsSingle.java"), expected); } /** * Tests SuppressWarnings unchecked warning disabled on certain tokens. * @throws Exception */ @Test public void testSingleNoUncheckedTokens() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*"); checkConfig.addAttribute("tokens", "CLASS_DEF,METHOD_DEF"); final String[] expected = { "5:19: The warning 'unchecked' cannot be suppressed at this location.", "29:35: The warning 'unchecked' cannot be suppressed at this location.", "64:33: The warning 'unchecked' cannot be suppressed at this location.", "72:65: The warning 'unchecked' cannot be suppressed at this location.", "77:37: The warning 'unchecked' cannot be suppressed at this location.", "82:47: The warning 'unchecked' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsSingle.java"), expected); } /** * Tests SuppressWarnings un* warning disabled on everything. * @throws Exception */ @Test public void testSingleNoUnWildcard() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", ".*un.*"); final String[] expected = { "5:19: The warning 'unchecked' cannot be suppressed at this location.", "17:23: The warning 'unused' cannot be suppressed at this location.", "20:27: The warning 'unforgiven' cannot be suppressed at this location.", "25:31: The warning 'unused' cannot be suppressed at this location.", "29:35: The warning 'unchecked' cannot be suppressed at this location.", "37:23: The warning 'abcun' cannot be suppressed at this location.", "44:23: The warning 'abcun' cannot be suppressed at this location.", "47:27: The warning 'unused' cannot be suppressed at this location.", "56:27: The warning 'unchecked' cannot be suppressed at this location.", "59:48: The warning 'unchecked' cannot be suppressed at this location.", "64:33: The warning 'unchecked' cannot be suppressed at this location.", "67:42: The warning 'unchecked' cannot be suppressed at this location.", "72:54: The warning 'unused' cannot be suppressed at this location.", "72:65: The warning 'unchecked' cannot be suppressed at this location.", "77:37: The warning 'unchecked' cannot be suppressed at this location.", "77:68: The warning 'unused' cannot be suppressed at this location.", "82:47: The warning 'unchecked' cannot be suppressed at this location.", "82:115: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsSingle.java"), expected); } /** * Tests SuppressWarnings unchecked, unused warning disabled on everything. * @throws Exception */ @Test public void testSingleNoUncheckedUnused() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*|^unused$"); final String[] expected = { "5:19: The warning 'unchecked' cannot be suppressed at this location.", "17:23: The warning 'unused' cannot be suppressed at this location.", "25:31: The warning 'unused' cannot be suppressed at this location.", "29:35: The warning 'unchecked' cannot be suppressed at this location.", "47:27: The warning 'unused' cannot be suppressed at this location.", "56:27: The warning 'unchecked' cannot be suppressed at this location.", "59:48: The warning 'unchecked' cannot be suppressed at this location.", "64:33: The warning 'unchecked' cannot be suppressed at this location.", "67:42: The warning 'unchecked' cannot be suppressed at this location.", "72:54: The warning 'unused' cannot be suppressed at this location.", "72:65: The warning 'unchecked' cannot be suppressed at this location.", "77:37: The warning 'unchecked' cannot be suppressed at this location.", "77:68: The warning 'unused' cannot be suppressed at this location.", "82:47: The warning 'unchecked' cannot be suppressed at this location.", "82:115: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsSingle.java"), expected); } /** * Tests SuppressWarnings *, unchecked, unused warning disabled on everything. * @throws Exception */ @Test public void testSingleNoUncheckedUnusedAll() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*|^unused$*|.*"); final String[] expected = { "5:19: The warning 'unchecked' cannot be suppressed at this location.", "8:23: The warning ' ' cannot be suppressed at this location.", "11:27: The warning '' cannot be suppressed at this location.", "17:23: The warning 'unused' cannot be suppressed at this location.", "20:27: The warning 'unforgiven' cannot be suppressed at this location.", "25:31: The warning 'unused' cannot be suppressed at this location.", "29:35: The warning 'unchecked' cannot be suppressed at this location.", "37:23: The warning 'abcun' cannot be suppressed at this location.", "44:23: The warning 'abcun' cannot be suppressed at this location.", "47:27: The warning 'unused' cannot be suppressed at this location.", "53:27: The warning '' cannot be suppressed at this location.", "56:27: The warning 'unchecked' cannot be suppressed at this location.", "59:48: The warning 'unchecked' cannot be suppressed at this location.", "64:33: The warning 'unchecked' cannot be suppressed at this location.", "64:47: The warning '' cannot be suppressed at this location.", "67:37: The warning '' cannot be suppressed at this location.", "67:42: The warning 'unchecked' cannot be suppressed at this location.", "72:46: The warning ' ' cannot be suppressed at this location.", "72:54: The warning 'unused' cannot be suppressed at this location.", "72:65: The warning 'unchecked' cannot be suppressed at this location.", "77:37: The warning 'unchecked' cannot be suppressed at this location.", "77:60: The warning ' ' cannot be suppressed at this location.", "77:68: The warning 'unused' cannot be suppressed at this location.", "82:47: The warning 'unchecked' cannot be suppressed at this location.", "82:93: The warning '' cannot be suppressed at this location.", "82:98: The warning 'foo' cannot be suppressed at this location.", "82:106: The warning ' ' cannot be suppressed at this location.", "82:115: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsSingle.java"), expected); } /** * Tests SuppressWarnings with default regex. * @throws Exception */ @Test public void testCompactDefault() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); final String[] expected = { "8:24: The warning ' ' cannot be suppressed at this location.", "11:41: The warning '' cannot be suppressed at this location.", "44:23: The warning '' cannot be suppressed at this location.", "53:27: The warning '' cannot be suppressed at this location.", "64:48: The warning '' cannot be suppressed at this location.", "64:76: The warning '' cannot be suppressed at this location.", "67:38: The warning '' cannot be suppressed at this location.", "72:47: The warning ' ' cannot be suppressed at this location.", "72:98: The warning ' ' cannot be suppressed at this location.", "77:61: The warning ' ' cannot be suppressed at this location.", "82:94: The warning '' cannot be suppressed at this location.", "82:107: The warning ' ' cannot be suppressed at this location.", "82:181: The warning '' cannot be suppressed at this location.", "82:194: The warning ' ' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsCompact.java"), expected); } /** * Tests SuppressWarnings all warnings disabled on everything. * @throws Exception */ @Test public void testCompactAll() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", ".*"); final String[] expected = { "5:20: The warning 'unchecked' cannot be suppressed at this location.", "5:33: The warning 'unused' cannot be suppressed at this location.", "8:24: The warning ' ' cannot be suppressed at this location.", "11:28: The warning 'unchecked' cannot be suppressed at this location.", "11:41: The warning '' cannot be suppressed at this location.", "17:24: The warning 'unused' cannot be suppressed at this location.", "20:28: The warning 'unforgiven' cannot be suppressed at this location.", "20:42: The warning ' un' cannot be suppressed at this location.", "25:32: The warning 'unused' cannot be suppressed at this location.", "29:36: The warning 'unchecked' cannot be suppressed at this location.", "37:24: The warning 'abcun' cannot be suppressed at this location.", "44:23: The warning '' cannot be suppressed at this location.", "47:28: The warning 'unused' cannot be suppressed at this location.", "47:38: The warning 'bleh' cannot be suppressed at this location.", "53:27: The warning '' cannot be suppressed at this location.", "56:28: The warning 'unchecked' cannot be suppressed at this location.", "59:49: The warning 'unchecked' cannot be suppressed at this location.", "64:34: The warning 'unchecked' cannot be suppressed at this location.", "64:48: The warning '' cannot be suppressed at this location.", "64:62: The warning 'unchecked' cannot be suppressed at this location.", "64:76: The warning '' cannot be suppressed at this location.", "67:38: The warning '' cannot be suppressed at this location.", "67:43: The warning 'unchecked' cannot be suppressed at this location.", "72:47: The warning ' ' cannot be suppressed at this location.", "72:55: The warning 'unused' cannot be suppressed at this location.", "72:66: The warning 'unchecked' cannot be suppressed at this location.", "72:98: The warning ' ' cannot be suppressed at this location.", "72:106: The warning 'unused' cannot be suppressed at this location.", "72:117: The warning 'unchecked' cannot be suppressed at this location.", "77:38: The warning 'unchecked' cannot be suppressed at this location.", "77:61: The warning ' ' cannot be suppressed at this location.", "77:69: The warning 'unused' cannot be suppressed at this location.", "82:48: The warning 'unchecked' cannot be suppressed at this location.", "82:94: The warning '' cannot be suppressed at this location.", "82:99: The warning 'foo' cannot be suppressed at this location.", "82:107: The warning ' ' cannot be suppressed at this location.", "82:115: The warning 'unused' cannot be suppressed at this location.", "82:135: The warning 'unchecked' cannot be suppressed at this location.", "82:181: The warning '' cannot be suppressed at this location.", "82:186: The warning 'foo' cannot be suppressed at this location.", "82:194: The warning ' ' cannot be suppressed at this location.", "82:202: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsCompact.java"), expected); } /** * Tests SuppressWarnings unchecked warning disabled on everything. * @throws Exception */ @Test public void testCompactNoUnchecked() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*"); final String[] expected = { "5:20: The warning 'unchecked' cannot be suppressed at this location.", "11:28: The warning 'unchecked' cannot be suppressed at this location.", "29:36: The warning 'unchecked' cannot be suppressed at this location.", "56:28: The warning 'unchecked' cannot be suppressed at this location.", "59:49: The warning 'unchecked' cannot be suppressed at this location.", "64:34: The warning 'unchecked' cannot be suppressed at this location.", "64:62: The warning 'unchecked' cannot be suppressed at this location.", "67:43: The warning 'unchecked' cannot be suppressed at this location.", "72:66: The warning 'unchecked' cannot be suppressed at this location.", "72:117: The warning 'unchecked' cannot be suppressed at this location.", "77:38: The warning 'unchecked' cannot be suppressed at this location.", "82:48: The warning 'unchecked' cannot be suppressed at this location.", "82:135: The warning 'unchecked' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsCompact.java"), expected); } /** * Tests SuppressWarnings unchecked warning disabled on certain tokens. * @throws Exception */ @Test public void testCompactNoUncheckedTokens() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*"); checkConfig.addAttribute("tokens", "CLASS_DEF"); final String[] expected = { "5:20: The warning 'unchecked' cannot be suppressed at this location.", "64:34: The warning 'unchecked' cannot be suppressed at this location.", "64:62: The warning 'unchecked' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsCompact.java"), expected); } /** * Tests SuppressWarnings un* warning disabled on everything. * @throws Exception */ @Test public void testCompactNoUnWildcard() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "un.*"); final String[] expected = { "5:20: The warning 'unchecked' cannot be suppressed at this location.", "5:33: The warning 'unused' cannot be suppressed at this location.", "11:28: The warning 'unchecked' cannot be suppressed at this location.", "17:24: The warning 'unused' cannot be suppressed at this location.", "20:28: The warning 'unforgiven' cannot be suppressed at this location.", "25:32: The warning 'unused' cannot be suppressed at this location.", "29:36: The warning 'unchecked' cannot be suppressed at this location.", "47:28: The warning 'unused' cannot be suppressed at this location.", "56:28: The warning 'unchecked' cannot be suppressed at this location.", "59:49: The warning 'unchecked' cannot be suppressed at this location.", "64:34: The warning 'unchecked' cannot be suppressed at this location.", "64:62: The warning 'unchecked' cannot be suppressed at this location.", "67:43: The warning 'unchecked' cannot be suppressed at this location.", "72:55: The warning 'unused' cannot be suppressed at this location.", "72:66: The warning 'unchecked' cannot be suppressed at this location.", "72:106: The warning 'unused' cannot be suppressed at this location.", "72:117: The warning 'unchecked' cannot be suppressed at this location.", "77:38: The warning 'unchecked' cannot be suppressed at this location.", "77:69: The warning 'unused' cannot be suppressed at this location.", "82:48: The warning 'unchecked' cannot be suppressed at this location.", "82:115: The warning 'unused' cannot be suppressed at this location.", "82:135: The warning 'unchecked' cannot be suppressed at this location.", "82:202: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsCompact.java"), expected); } /** * Tests SuppressWarnings unchecked, unused warning disabled on everything. * @throws Exception */ @Test public void testCompactNoUncheckedUnused() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*|^unused$"); final String[] expected = { "5:20: The warning 'unchecked' cannot be suppressed at this location.", "5:33: The warning 'unused' cannot be suppressed at this location.", "11:28: The warning 'unchecked' cannot be suppressed at this location.", "17:24: The warning 'unused' cannot be suppressed at this location.", "25:32: The warning 'unused' cannot be suppressed at this location.", "29:36: The warning 'unchecked' cannot be suppressed at this location.", "47:28: The warning 'unused' cannot be suppressed at this location.", "56:28: The warning 'unchecked' cannot be suppressed at this location.", "59:49: The warning 'unchecked' cannot be suppressed at this location.", "64:34: The warning 'unchecked' cannot be suppressed at this location.", "64:62: The warning 'unchecked' cannot be suppressed at this location.", "67:43: The warning 'unchecked' cannot be suppressed at this location.", "72:55: The warning 'unused' cannot be suppressed at this location.", "72:66: The warning 'unchecked' cannot be suppressed at this location.", "72:106: The warning 'unused' cannot be suppressed at this location.", "72:117: The warning 'unchecked' cannot be suppressed at this location.", "77:38: The warning 'unchecked' cannot be suppressed at this location.", "77:69: The warning 'unused' cannot be suppressed at this location.", "82:48: The warning 'unchecked' cannot be suppressed at this location.", "82:115: The warning 'unused' cannot be suppressed at this location.", "82:135: The warning 'unchecked' cannot be suppressed at this location.", "82:202: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsCompact.java"), expected); } /** * Tests SuppressWarnings *, unchecked, unused warning disabled on everything. * @throws Exception */ @Test public void testCompactNoUncheckedUnusedAll() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*|^unused$*|.*"); final String[] expected = { "5:20: The warning 'unchecked' cannot be suppressed at this location.", "5:33: The warning 'unused' cannot be suppressed at this location.", "8:24: The warning ' ' cannot be suppressed at this location.", "11:28: The warning 'unchecked' cannot be suppressed at this location.", "11:41: The warning '' cannot be suppressed at this location.", "17:24: The warning 'unused' cannot be suppressed at this location.", "20:28: The warning 'unforgiven' cannot be suppressed at this location.", "20:42: The warning ' un' cannot be suppressed at this location.", "25:32: The warning 'unused' cannot be suppressed at this location.", "29:36: The warning 'unchecked' cannot be suppressed at this location.", "37:24: The warning 'abcun' cannot be suppressed at this location.", "44:23: The warning '' cannot be suppressed at this location.", "47:28: The warning 'unused' cannot be suppressed at this location.", "47:38: The warning 'bleh' cannot be suppressed at this location.", "53:27: The warning '' cannot be suppressed at this location.", "56:28: The warning 'unchecked' cannot be suppressed at this location.", "59:49: The warning 'unchecked' cannot be suppressed at this location.", "64:34: The warning 'unchecked' cannot be suppressed at this location.", "64:48: The warning '' cannot be suppressed at this location.", "64:62: The warning 'unchecked' cannot be suppressed at this location.", "64:76: The warning '' cannot be suppressed at this location.", "67:38: The warning '' cannot be suppressed at this location.", "67:43: The warning 'unchecked' cannot be suppressed at this location.", "72:47: The warning ' ' cannot be suppressed at this location.", "72:55: The warning 'unused' cannot be suppressed at this location.", "72:66: The warning 'unchecked' cannot be suppressed at this location.", "72:98: The warning ' ' cannot be suppressed at this location.", "72:106: The warning 'unused' cannot be suppressed at this location.", "72:117: The warning 'unchecked' cannot be suppressed at this location.", "77:38: The warning 'unchecked' cannot be suppressed at this location.", "77:61: The warning ' ' cannot be suppressed at this location.", "77:69: The warning 'unused' cannot be suppressed at this location.", "82:48: The warning 'unchecked' cannot be suppressed at this location.", "82:94: The warning '' cannot be suppressed at this location.", "82:99: The warning 'foo' cannot be suppressed at this location.", "82:107: The warning ' ' cannot be suppressed at this location.", "82:115: The warning 'unused' cannot be suppressed at this location.", "82:135: The warning 'unchecked' cannot be suppressed at this location.", "82:181: The warning '' cannot be suppressed at this location.", "82:186: The warning 'foo' cannot be suppressed at this location.", "82:194: The warning ' ' cannot be suppressed at this location.", "82:202: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsCompact.java"), expected); } /** * Tests SuppressWarnings with default regex. * @throws Exception */ @Test public void testExpandedDefault() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); final String[] expected = { "8:30: The warning ' ' cannot be suppressed at this location.", "11:47: The warning '' cannot be suppressed at this location.", "44:29: The warning '' cannot be suppressed at this location.", "53:33: The warning '' cannot be suppressed at this location.", "64:54: The warning '' cannot be suppressed at this location.", "64:82: The warning '' cannot be suppressed at this location.", "67:44: The warning '' cannot be suppressed at this location.", "72:53: The warning ' ' cannot be suppressed at this location.", "72:104: The warning ' ' cannot be suppressed at this location.", "77:67: The warning ' ' cannot be suppressed at this location.", "82:100: The warning '' cannot be suppressed at this location.", "82:113: The warning ' ' cannot be suppressed at this location.", "82:187: The warning '' cannot be suppressed at this location.", "82:200: The warning ' ' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsExpanded.java"), expected); } /** * Tests SuppressWarnings all warnings disabled on everything. * @throws Exception */ @Test public void testExpandedAll() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", ".*"); final String[] expected = { "5:26: The warning 'unchecked' cannot be suppressed at this location.", "5:39: The warning 'unused' cannot be suppressed at this location.", "8:30: The warning ' ' cannot be suppressed at this location.", "11:34: The warning 'unchecked' cannot be suppressed at this location.", "11:47: The warning '' cannot be suppressed at this location.", "17:30: The warning 'unused' cannot be suppressed at this location.", "20:34: The warning 'unforgiven' cannot be suppressed at this location.", "20:48: The warning ' un' cannot be suppressed at this location.", "25:38: The warning 'unused' cannot be suppressed at this location.", "29:42: The warning 'unchecked' cannot be suppressed at this location.", "37:30: The warning 'abcun' cannot be suppressed at this location.", "44:29: The warning '' cannot be suppressed at this location.", "47:34: The warning 'unused' cannot be suppressed at this location.", "47:44: The warning 'bleh' cannot be suppressed at this location.", "53:33: The warning '' cannot be suppressed at this location.", "56:34: The warning 'unchecked' cannot be suppressed at this location.", "59:55: The warning 'unchecked' cannot be suppressed at this location.", "64:40: The warning 'unchecked' cannot be suppressed at this location.", "64:54: The warning '' cannot be suppressed at this location.", "64:68: The warning 'unchecked' cannot be suppressed at this location.", "64:82: The warning '' cannot be suppressed at this location.", "67:44: The warning '' cannot be suppressed at this location.", "67:49: The warning 'unchecked' cannot be suppressed at this location.", "72:53: The warning ' ' cannot be suppressed at this location.", "72:61: The warning 'unused' cannot be suppressed at this location.", "72:72: The warning 'unchecked' cannot be suppressed at this location.", "72:104: The warning ' ' cannot be suppressed at this location.", "72:112: The warning 'unused' cannot be suppressed at this location.", "72:123: The warning 'unchecked' cannot be suppressed at this location.", "77:44: The warning 'unchecked' cannot be suppressed at this location.", "77:67: The warning ' ' cannot be suppressed at this location.", "77:75: The warning 'unused' cannot be suppressed at this location.", "82:54: The warning 'unchecked' cannot be suppressed at this location.", "82:100: The warning '' cannot be suppressed at this location.", "82:105: The warning 'foo' cannot be suppressed at this location.", "82:113: The warning ' ' cannot be suppressed at this location.", "82:121: The warning 'unused' cannot be suppressed at this location.", "82:141: The warning 'unchecked' cannot be suppressed at this location.", "82:187: The warning '' cannot be suppressed at this location.", "82:192: The warning 'foo' cannot be suppressed at this location.", "82:200: The warning ' ' cannot be suppressed at this location.", "82:208: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsExpanded.java"), expected); } /** * Tests SuppressWarnings unchecked warning disabled on everything. * @throws Exception */ @Test public void testExpandedNoUnchecked() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*"); final String[] expected = { "5:26: The warning 'unchecked' cannot be suppressed at this location.", "11:34: The warning 'unchecked' cannot be suppressed at this location.", "29:42: The warning 'unchecked' cannot be suppressed at this location.", "56:34: The warning 'unchecked' cannot be suppressed at this location.", "59:55: The warning 'unchecked' cannot be suppressed at this location.", "64:40: The warning 'unchecked' cannot be suppressed at this location.", "64:68: The warning 'unchecked' cannot be suppressed at this location.", "67:49: The warning 'unchecked' cannot be suppressed at this location.", "72:72: The warning 'unchecked' cannot be suppressed at this location.", "72:123: The warning 'unchecked' cannot be suppressed at this location.", "77:44: The warning 'unchecked' cannot be suppressed at this location.", "82:54: The warning 'unchecked' cannot be suppressed at this location.", "82:141: The warning 'unchecked' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsExpanded.java"), expected); } /** * Tests SuppressWarnings unchecked warning disabled on certain tokens. * @throws Exception */ @Test public void testExpandedNoUncheckedTokens() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*"); checkConfig.addAttribute("tokens", "CLASS_DEF"); final String[] expected = { "5:26: The warning 'unchecked' cannot be suppressed at this location.", "64:40: The warning 'unchecked' cannot be suppressed at this location.", "64:68: The warning 'unchecked' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsExpanded.java"), expected); } /** * Tests SuppressWarnings un* warning disabled on everything. * @throws Exception */ @Test public void testExpandedNoUnWildcard() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "un.*"); final String[] expected = { "5:26: The warning 'unchecked' cannot be suppressed at this location.", "5:39: The warning 'unused' cannot be suppressed at this location.", "11:34: The warning 'unchecked' cannot be suppressed at this location.", "17:30: The warning 'unused' cannot be suppressed at this location.", "20:34: The warning 'unforgiven' cannot be suppressed at this location.", "25:38: The warning 'unused' cannot be suppressed at this location.", "29:42: The warning 'unchecked' cannot be suppressed at this location.", "47:34: The warning 'unused' cannot be suppressed at this location.", "56:34: The warning 'unchecked' cannot be suppressed at this location.", "59:55: The warning 'unchecked' cannot be suppressed at this location.", "64:40: The warning 'unchecked' cannot be suppressed at this location.", "64:68: The warning 'unchecked' cannot be suppressed at this location.", "67:49: The warning 'unchecked' cannot be suppressed at this location.", "72:61: The warning 'unused' cannot be suppressed at this location.", "72:72: The warning 'unchecked' cannot be suppressed at this location.", "72:112: The warning 'unused' cannot be suppressed at this location.", "72:123: The warning 'unchecked' cannot be suppressed at this location.", "77:44: The warning 'unchecked' cannot be suppressed at this location.", "77:75: The warning 'unused' cannot be suppressed at this location.", "82:54: The warning 'unchecked' cannot be suppressed at this location.", "82:121: The warning 'unused' cannot be suppressed at this location.", "82:141: The warning 'unchecked' cannot be suppressed at this location.", "82:208: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsExpanded.java"), expected); } /** * Tests SuppressWarnings unchecked, unused warning disabled on everything. * @throws Exception */ @Test public void testExpandedNoUncheckedUnused() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*|^unused$"); final String[] expected = { "5:26: The warning 'unchecked' cannot be suppressed at this location.", "5:39: The warning 'unused' cannot be suppressed at this location.", "11:34: The warning 'unchecked' cannot be suppressed at this location.", "17:30: The warning 'unused' cannot be suppressed at this location.", "25:38: The warning 'unused' cannot be suppressed at this location.", "29:42: The warning 'unchecked' cannot be suppressed at this location.", "47:34: The warning 'unused' cannot be suppressed at this location.", "56:34: The warning 'unchecked' cannot be suppressed at this location.", "59:55: The warning 'unchecked' cannot be suppressed at this location.", "64:40: The warning 'unchecked' cannot be suppressed at this location.", "64:68: The warning 'unchecked' cannot be suppressed at this location.", "67:49: The warning 'unchecked' cannot be suppressed at this location.", "72:61: The warning 'unused' cannot be suppressed at this location.", "72:72: The warning 'unchecked' cannot be suppressed at this location.", "72:112: The warning 'unused' cannot be suppressed at this location.", "72:123: The warning 'unchecked' cannot be suppressed at this location.", "77:44: The warning 'unchecked' cannot be suppressed at this location.", "77:75: The warning 'unused' cannot be suppressed at this location.", "82:54: The warning 'unchecked' cannot be suppressed at this location.", "82:121: The warning 'unused' cannot be suppressed at this location.", "82:141: The warning 'unchecked' cannot be suppressed at this location.", "82:208: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsExpanded.java"), expected); } /** * Tests SuppressWarnings *, unchecked, unused warning disabled on everything. * @throws Exception */ @Test public void testExpandedNoUncheckedUnusedAll() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(SuppressWarningsCheck.class); checkConfig.addAttribute("format", "^unchecked$*|^unused$*|.*"); final String[] expected = { "5:26: The warning 'unchecked' cannot be suppressed at this location.", "5:39: The warning 'unused' cannot be suppressed at this location.", "8:30: The warning ' ' cannot be suppressed at this location.", "11:34: The warning 'unchecked' cannot be suppressed at this location.", "11:47: The warning '' cannot be suppressed at this location.", "17:30: The warning 'unused' cannot be suppressed at this location.", "20:34: The warning 'unforgiven' cannot be suppressed at this location.", "20:48: The warning ' un' cannot be suppressed at this location.", "25:38: The warning 'unused' cannot be suppressed at this location.", "29:42: The warning 'unchecked' cannot be suppressed at this location.", "37:30: The warning 'abcun' cannot be suppressed at this location.", "44:29: The warning '' cannot be suppressed at this location.", "47:34: The warning 'unused' cannot be suppressed at this location.", "47:44: The warning 'bleh' cannot be suppressed at this location.", "53:33: The warning '' cannot be suppressed at this location.", "56:34: The warning 'unchecked' cannot be suppressed at this location.", "59:55: The warning 'unchecked' cannot be suppressed at this location.", "64:40: The warning 'unchecked' cannot be suppressed at this location.", "64:54: The warning '' cannot be suppressed at this location.", "64:68: The warning 'unchecked' cannot be suppressed at this location.", "64:82: The warning '' cannot be suppressed at this location.", "67:44: The warning '' cannot be suppressed at this location.", "67:49: The warning 'unchecked' cannot be suppressed at this location.", "72:53: The warning ' ' cannot be suppressed at this location.", "72:61: The warning 'unused' cannot be suppressed at this location.", "72:72: The warning 'unchecked' cannot be suppressed at this location.", "72:104: The warning ' ' cannot be suppressed at this location.", "72:112: The warning 'unused' cannot be suppressed at this location.", "72:123: The warning 'unchecked' cannot be suppressed at this location.", "77:44: The warning 'unchecked' cannot be suppressed at this location.", "77:67: The warning ' ' cannot be suppressed at this location.", "77:75: The warning 'unused' cannot be suppressed at this location.", "82:54: The warning 'unchecked' cannot be suppressed at this location.", "82:100: The warning '' cannot be suppressed at this location.", "82:105: The warning 'foo' cannot be suppressed at this location.", "82:113: The warning ' ' cannot be suppressed at this location.", "82:121: The warning 'unused' cannot be suppressed at this location.", "82:141: The warning 'unchecked' cannot be suppressed at this location.", "82:187: The warning '' cannot be suppressed at this location.", "82:192: The warning 'foo' cannot be suppressed at this location.", "82:200: The warning ' ' cannot be suppressed at this location.", "82:208: The warning 'unused' cannot be suppressed at this location.", }; verify(checkConfig, getPath("annotation" + File.separator + "SuppressWarningsExpanded.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/ArrayTypeStyleCheckTest.java100644 0 0 4466 12026050775 27744 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class ArrayTypeStyleCheckTest extends BaseCheckTestSupport { @Test public void testJavaStyle() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ArrayTypeStyleCheck.class); final String[] expected = { "14:23: Array brackets at illegal position.", "20:44: Array brackets at illegal position.", }; verify(checkConfig, getPath("InputArrayTypeStyle.java"), expected); } @Test public void testCStyle() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ArrayTypeStyleCheck.class); checkConfig.addAttribute("javaStyle", "false"); final String[] expected = { "13:16: Array brackets at illegal position.", "16:39: Array brackets at illegal position.", "22:18: Array brackets at illegal position.", "30:20: Array brackets at illegal position.", }; verify(checkConfig, getPath("InputArrayTypeStyle.java"), expected); } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/blocks/AvoidNestedBlocksCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/blocks/AvoidNestedBlocksCheckTest.ja100644 0 0 4500 12026050771 31255 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class AvoidNestedBlocksCheckTest extends BaseCheckTestSupport { @Test public void testStrictSettings() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AvoidNestedBlocksCheck.class); final String[] expected = { "22:9: Avoid nested blocks.", "44:17: Avoid nested blocks.", "50:17: Avoid nested blocks.", "58:17: Avoid nested blocks.", }; verify(checkConfig, getPath("InputNestedBlocks.java"), expected); } @Test public void testAllowSwitchInCase() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AvoidNestedBlocksCheck.class); checkConfig.addAttribute("allowInSwitchCase", Boolean.TRUE.toString()); final String[] expected = { "22:9: Avoid nested blocks.", "44:17: Avoid nested blocks.", "58:17: Avoid nested blocks.", }; verify(checkConfig, getPath("InputNestedBlocks.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyBlockCheckTest.java100644 0 0 7311 12026050770 30314 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class EmptyBlockCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(EmptyBlockCheck.class); final String[] expected = { "52:65: Must have at least one statement.", "54:41: Must have at least one statement.", "71:38: Must have at least one statement.", "72:52: Must have at least one statement.", "73:45: Must have at least one statement.", "75:13: Must have at least one statement.", "77:17: Must have at least one statement.", "79:13: Must have at least one statement.", "82:17: Must have at least one statement.", "178:5: Must have at least one statement.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testText() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(EmptyBlockCheck.class); checkConfig.addAttribute("option", BlockOption.TEXT.toString()); final String[] expected = { "52:65: Empty catch block.", "72:52: Empty catch block.", "73:45: Empty catch block.", "75:13: Empty try block.", "77:17: Empty finally block.", "178:5: Empty INSTANCE_INIT block.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testStatement() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(EmptyBlockCheck.class); checkConfig.addAttribute("option", BlockOption.STMT.toString()); final String[] expected = { "52:65: Must have at least one statement.", "54:41: Must have at least one statement.", "71:38: Must have at least one statement.", "72:52: Must have at least one statement.", "73:45: Must have at least one statement.", "75:13: Must have at least one statement.", "77:17: Must have at least one statement.", "79:13: Must have at least one statement.", "82:17: Must have at least one statement.", "178:5: Must have at least one statement.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheckTest.java100644 0 0 17436 12026050770 30205 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class LeftCurlyCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(LeftCurlyCheck.class); } @Test public void testDefault() throws Exception { final String[] expected = { "8:1: '{' should be on the previous line.", "12:5: '{' should be on the previous line.", "21:5: '{' should be on the previous line.", "30:5: '{' should be on the previous line.", "39:5: '{' should be on the previous line.", }; verify(mCheckConfig, getPath("InputScopeInnerInterfaces.java"), expected); } @Test public void testNL() throws Exception { mCheckConfig.addAttribute("option", LeftCurlyOption.NL.toString()); final String[] expected = { "49:14: '{' should be on a new line.", "53:14: '{' should be on a new line.", "58:18: '{' should be on a new line.", "62:18: '{' should be on a new line.", "67:12: '{' should be on a new line.", "72:18: '{' should be on a new line.", }; verify(mCheckConfig, getPath("InputScopeInnerInterfaces.java"), expected); } @Test public void testNLOW() throws Exception { mCheckConfig.addAttribute("option", LeftCurlyOption.NLOW.toString()); final String[] expected = { "8:1: '{' should be on the previous line.", "12:5: '{' should be on the previous line.", "21:5: '{' should be on the previous line.", "30:5: '{' should be on the previous line.", "39:5: '{' should be on the previous line.", "49:14: '{' should be on a new line.", "53:14: '{' should be on a new line.", "58:18: '{' should be on a new line.", "62:18: '{' should be on a new line.", "67:12: '{' should be on a new line.", "72:18: '{' should be on a new line.", }; verify(mCheckConfig, getPath("InputScopeInnerInterfaces.java"), expected); } @Test public void testDefault2() throws Exception { final String[] expected = { "12:1: '{' should be on the previous line.", "17:5: '{' should be on the previous line.", "24:5: '{' should be on the previous line.", "31:5: '{' should be on the previous line.", "39:1: '{' should be on the previous line.", "41:5: '{' should be on the previous line.", "46:9: '{' should be on the previous line.", "53:9: '{' should be on the previous line.", "69:5: '{' should be on the previous line.", "77:5: '{' should be on the previous line.", "84:5: '{' should be on the previous line.", }; verify(mCheckConfig, getPath("InputLeftCurlyMethod.java"), expected); } @Test public void testNL2() throws Exception { mCheckConfig.addAttribute("option", LeftCurlyOption.NL.toString()); final String[] expected = { "14:39: '{' should be on a new line.", "21:20: '{' should be on a new line.", "34:31: '{' should be on a new line.", "43:24: '{' should be on a new line.", "56:35: '{' should be on a new line.", "60:24: '{' should be on a new line.", "74:20: '{' should be on a new line.", "87:31: '{' should be on a new line.", }; verify(mCheckConfig, getPath("InputLeftCurlyMethod.java"), expected); } @Test public void testDefault3() throws Exception { final String[] expected = { "12:1: '{' should be on the previous line.", "15:5: '{' should be on the previous line.", "19:9: '{' should be on the previous line.", "21:13: '{' should be on the previous line.", "23:17: '{' should be on the previous line.", "30:17: '{' should be on the previous line.", "34:17: '{' should be on the previous line.", "42:13: '{' should be on the previous line.", "46:13: '{' should be on the previous line.", "52:9: '{' should be on the previous line.", "54:13: '{' should be on the previous line.", "63:9: '{' should be on the previous line.", "83:5: '{' should be on the previous line.", "89:5: '{' should be on the previous line.", }; verify(mCheckConfig, getPath("InputLeftCurlyOther.java"), expected); } @Test public void testNL3() throws Exception { mCheckConfig.addAttribute("option", LeftCurlyOption.NL.toString()); final String[] expected = { "26:33: '{' should be on a new line.", "91:19: '{' should be on a new line.", "97:19: '{' should be on a new line.", }; verify(mCheckConfig, getPath("InputLeftCurlyOther.java"), expected); } @Test public void testMissingBraces() throws Exception { final String[] expected = { "12:1: '{' should be on the previous line.", "15:5: '{' should be on the previous line.", "21:5: '{' should be on the previous line.", "34:5: '{' should be on the previous line.", "51:5: '{' should be on the previous line.", "69:5: '{' should be on the previous line.", "105:5: '{' should be on the previous line.", }; verify(mCheckConfig, getPath("InputBraces.java"), expected); } @Test public void testDefaultWithAnnotations() throws Exception { final String[] expected = { "10:1: '{' should be on the previous line.", "14:5: '{' should be on the previous line.", "21:5: '{' should be on the previous line.", }; verify(mCheckConfig, getPath("InputLeftCurlyAnnotations.java"), expected); } @Test public void testNLWithAnnotations() throws Exception { mCheckConfig.addAttribute("option", LeftCurlyOption.NL.toString()); final String[] expected = { "35:34: '{' should be on a new line.", "38:41: '{' should be on a new line.", "44:27: '{' should be on a new line.", "58:32: '{' should be on a new line.", }; verify(mCheckConfig, getPath("InputLeftCurlyAnnotations.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/blocks/NeedBracesCheckTest.java100644 0 0 4704 12026050770 30241 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class NeedBracesCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NeedBracesCheck.class); final String[] expected = { "29: 'do' construct must use '{}'s." , "41: 'while' construct must use '{}'s." , "42: 'while' construct must use '{}'s." , "44: 'while' construct must use '{}'s." , "45: 'if' construct must use '{}'s." , "58: 'for' construct must use '{}'s." , "59: 'for' construct must use '{}'s." , "61: 'for' construct must use '{}'s." , "63: 'if' construct must use '{}'s." , "82: 'if' construct must use '{}'s." , "83: 'if' construct must use '{}'s." , "85: 'if' construct must use '{}'s." , "87: 'else' construct must use '{}'s." , "89: 'if' construct must use '{}'s." , "97: 'else' construct must use '{}'s." , "99: 'if' construct must use '{}'s." , "100: 'if' construct must use '{}'s." , }; verify(checkConfig, getPath("InputBraces.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheckTest.java100644 0 0 6547 12026050770 30351 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.blocks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class RightCurlyCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(RightCurlyCheck.class); } @Test public void testDefault() throws Exception { final String[] expected = { "25:17: '}' should be on the same line.", "28:17: '}' should be on the same line.", "40:13: '}' should be on the same line.", "44:13: '}' should be on the same line.", "93:27: '}' should be alone on a line.", "93:27: '}' should be on a new line.", }; verify(mCheckConfig, getPath("InputLeftCurlyOther.java"), expected); } @Test public void testSame() throws Exception { mCheckConfig.addAttribute("option", RightCurlyOption.SAME.toString()); final String[] expected = { "25:17: '}' should be on the same line.", "28:17: '}' should be on the same line.", "40:13: '}' should be on the same line.", "44:13: '}' should be on the same line.", "93:27: '}' should be alone on a line.", "93:27: '}' should be on a new line.", }; verify(mCheckConfig, getPath("InputLeftCurlyOther.java"), expected); } @Test public void testAlone() throws Exception { mCheckConfig.addAttribute("option", RightCurlyOption.ALONE.toString()); final String[] expected = { "93:27: '}' should be alone on a line.", "93:27: '}' should be on a new line.", }; verify(mCheckConfig, getPath("InputLeftCurlyOther.java"), expected); } @Test public void testShouldStartLine() throws Exception { mCheckConfig.addAttribute("option", RightCurlyOption.ALONE.toString()); mCheckConfig.addAttribute("shouldStartLine", "false"); final String[] expected = { "93:27: '}' should be alone on a line.", }; verify(mCheckConfig, getPath("InputLeftCurlyOther.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/ClassResolverTest.java100644 0 0 5036 12026050775 26626 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import com.google.common.collect.Sets; import java.util.Set; import org.junit.Test; public class ClassResolverTest { @Test public void testMisc() throws ClassNotFoundException { final Set imps = Sets.newHashSet(); imps.add("java.io.File"); imps.add("nothing.will.match.*"); imps.add("java.applet.*"); ClassResolver cr = new ClassResolver(Thread.currentThread().getContextClassLoader(), null, imps); assertNotNull(cr); try { cr.resolve("who.will.win.the.world.cup", ""); fail("Should not resolve class"); } catch (ClassNotFoundException e) { } cr.resolve("java.lang.String", ""); cr.resolve("StringBuffer", ""); cr.resolve("AppletContext", ""); try { cr.resolve("ChoiceFormat", ""); fail(); } catch (ClassNotFoundException e) { } imps.add("java.text.ChoiceFormat"); cr.resolve("ChoiceFormat", ""); cr = new ClassResolver(Thread.currentThread().getContextClassLoader(), "java.util", imps); cr.resolve("List", ""); try { cr.resolve("two.nil.england", ""); fail(); } catch (ClassNotFoundException e) { } } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/ArrayTrailingCommaCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/ArrayTrailingCommaCheckTest.j100644 0 0 3431 12026050767 31273 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class ArrayTrailingCommaCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ArrayTrailingCommaCheck.class); final String[] expected = { "17: Array should contain trailing comma.", "34: Array should contain trailing comma.", "37: Array should contain trailing comma.", }; verify(checkConfig, getPath("InputArrayTrailingComma.java"), expected); } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/AvoidInlineConditionalsCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/AvoidInlineConditionalsCheckT100644 0 0 3402 12026050767 31350 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class AvoidInlineConditionalsCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AvoidInlineConditionalsCheck.class); final String[] expected = { "97:29: Avoid inline conditionals.", "98:20: Avoid inline conditionals.", "150:34: Avoid inline conditionals.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheckTest.java100644 0 0 3665 12026050767 31350 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class CovariantEqualsCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(CovariantEqualsCheck.class); final String[] expected = { "11:24: covariant equals without overriding equals(java.lang.Object).", "30:20: covariant equals without overriding equals(java.lang.Object).", "64:20: covariant equals without overriding equals(java.lang.Object).", "78:28: covariant equals without overriding equals(java.lang.Object).", }; verify(checkConfig, getPath("InputCovariant.java"), expected); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheckTest.jav100644 0 0 14207 12026050767 31341 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class DeclarationOrderCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DeclarationOrderCheck.class); final String[] expected = { "8:5: Variable access definition in wrong order.", "13:5: Variable access definition in wrong order.", "18:5: Variable access definition in wrong order.", "21:5: Variable access definition in wrong order.", "27:5: Static variable definition in wrong order.", "27:5: Variable access definition in wrong order.", "34:9: Variable access definition in wrong order.", "45:9: Static variable definition in wrong order.", "45:9: Variable access definition in wrong order.", "54:5: Constructor definition in wrong order.", "80:5: Instance variable definition in wrong order.", "92:9: Variable access definition in wrong order.", "100:9: Static variable definition in wrong order.", "100:9: Variable access definition in wrong order.", "106:5: Variable access definition in wrong order.", "111:5: Variable access definition in wrong order.", "116:5: Variable access definition in wrong order.", "119:5: Variable access definition in wrong order.", "125:5: Static variable definition in wrong order.", "125:5: Variable access definition in wrong order.", "132:9: Variable access definition in wrong order.", "143:9: Static variable definition in wrong order.", "143:9: Variable access definition in wrong order.", "152:5: Constructor definition in wrong order.", "178:5: Instance variable definition in wrong order.", }; verify(checkConfig, getPath("coding/InputDeclarationOrder.java"), expected); } @Test public void testOnlyConstructors() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DeclarationOrderCheck.class); checkConfig.addAttribute("ignoreConstructors", "false"); checkConfig.addAttribute("ignoreMethods", "true"); checkConfig.addAttribute("ignoreModifiers", "true"); final String[] expected = { "45:9: Static variable definition in wrong order.", "54:5: Constructor definition in wrong order.", "80:5: Instance variable definition in wrong order.", "100:9: Static variable definition in wrong order.", "143:9: Static variable definition in wrong order.", "152:5: Constructor definition in wrong order.", "178:5: Instance variable definition in wrong order.", }; verify(checkConfig, getPath("coding/InputDeclarationOrder.java"), expected); } @Test public void testOnlyModifiers() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DeclarationOrderCheck.class); checkConfig.addAttribute("ignoreConstructors", "true"); checkConfig.addAttribute("ignoreMethods", "true"); checkConfig.addAttribute("ignoreModifiers", "false"); final String[] expected = { "8:5: Variable access definition in wrong order.", "13:5: Variable access definition in wrong order.", "18:5: Variable access definition in wrong order.", "21:5: Variable access definition in wrong order.", "27:5: Static variable definition in wrong order.", "27:5: Variable access definition in wrong order.", "34:9: Variable access definition in wrong order.", "45:9: Static variable definition in wrong order.", "45:9: Variable access definition in wrong order.", "80:5: Instance variable definition in wrong order.", "92:9: Variable access definition in wrong order.", "100:9: Static variable definition in wrong order.", "100:9: Variable access definition in wrong order.", "106:5: Variable access definition in wrong order.", "111:5: Variable access definition in wrong order.", "116:5: Variable access definition in wrong order.", "119:5: Variable access definition in wrong order.", "125:5: Static variable definition in wrong order.", "125:5: Variable access definition in wrong order.", "132:9: Variable access definition in wrong order.", "143:9: Static variable definition in wrong order.", "143:9: Variable access definition in wrong order.", "178:5: Instance variable definition in wrong order.", }; verify(checkConfig, getPath("coding/InputDeclarationOrder.java"), expected); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/DefaultComesLastCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/DefaultComesLastCheckTest.jav100644 0 0 3351 12026050767 31275 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class DefaultComesLastCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DefaultComesLastCheck.class); final String[] expected = { "22:9: Default should be last label in the switch.", }; verify(checkConfig, getPath("coding" + File.separator + "InputDefaultComesLast.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/EmptyStatementCheckTest.java100644 0 0 4353 12026050766 31224 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class EmptyStatementCheckTest extends BaseCheckTestSupport { @Test public void testEmptyStatements() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(EmptyStatementCheck.class); final String[] expected = { "12:7: Empty statement.", "17:7: Empty statement.", "22:19: Empty statement.", "26:10: Empty statement.", "29:16: Empty statement.", "33:10: Empty statement.", "43:10: Empty statement.", "49:13: Empty statement.", "51:13: Empty statement.", "54:19: Empty statement.", "58:10: Empty statement.", "61:9: Empty statement.", "66:10: Empty statement.", "72:10: Empty statement.", "76:10: Empty statement.", "80:10: Empty statement.", }; verify(checkConfig, getPath("InputEmptyStatement.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullTest.java100644 0 0 13425 12026050766 30373 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class EqualsAvoidNullTest extends BaseCheckTestSupport { @Test public void testEqualsWithDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(EqualsAvoidNullCheck.class); final String[] expected = { "18:17: String literal expressions should be on the left side of an equals comparison.", "20:17: String literal expressions should be on the left side of an equals comparison.", "22:17: String literal expressions should be on the left side of an equals comparison.", "24:17: String literal expressions should be on the left side of an equals comparison.", "26:17: String literal expressions should be on the left side of an equals comparison.", "28:17: String literal expressions should be on the left side of an equals comparison.", "37:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", "39:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", "41:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", "43:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", "45:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", "47:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", "57:17: String literal expressions should be on the left side of an equals comparison.", "59:17: String literal expressions should be on the left side of an equals comparison.", "61:17: String literal expressions should be on the left side of an equals comparison.", "63:17: String literal expressions should be on the left side of an equals comparison.", "65:17: String literal expressions should be on the left side of an equals comparison.", "67:17: String literal expressions should be on the left side of an equals comparison.", "69:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", "71:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", "73:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", "75:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", "77:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", "79:27: String literal expressions should be on the left side of an equalsIgnoreCase comparison.", }; verify(checkConfig, getPath("coding" + File.separator + "InputEqualsAvoidNull.java"), expected); } @Test public void testEqualsWithoutEqualsIgnoreCase() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(EqualsAvoidNullCheck.class); checkConfig.addAttribute("ignoreEqualsIgnoreCase", "true"); final String[] expected = { "18:17: String literal expressions should be on the left side of an equals comparison.", "20:17: String literal expressions should be on the left side of an equals comparison.", "22:17: String literal expressions should be on the left side of an equals comparison.", "24:17: String literal expressions should be on the left side of an equals comparison.", "26:17: String literal expressions should be on the left side of an equals comparison.", "28:17: String literal expressions should be on the left side of an equals comparison.", "57:17: String literal expressions should be on the left side of an equals comparison.", "59:17: String literal expressions should be on the left side of an equals comparison.", "61:17: String literal expressions should be on the left side of an equals comparison.", "63:17: String literal expressions should be on the left side of an equals comparison.", "65:17: String literal expressions should be on the left side of an equals comparison.", "67:17: String literal expressions should be on the left side of an equals comparison.", }; verify(checkConfig, getPath("coding" + File.separator + "InputEqualsAvoidNull.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/EqualsHashCodeCheckTest.java100644 0 0 3565 12026050766 31076 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class EqualsHashCodeCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(EqualsHashCodeCheck.class); final String[] expected = { "126:9: Definition of 'equals()' without corresponding definition of 'hashCode()'.", "163:13: Definition of 'equals()' without corresponding definition of 'hashCode()'.", "191:9: Definition of 'equals()' without corresponding definition of 'hashCode()'.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheckTe100644 0 0 7042 12026050766 31441 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class ExplicitInitializationCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExplicitInitializationCheck.class); final String[] expected = { "2:17: Variable 'x' explicitly initialized to '0' (default value for its type).", "3:20: Variable 'bar' explicitly initialized to 'null' (default value for its type).", "7:18: Variable 'y4' explicitly initialized to '0' (default value for its type).", "8:21: Variable 'b1' explicitly initialized to 'false' (default value for its type).", "12:22: Variable 'str1' explicitly initialized to 'null' (default value for its type).", "12:35: Variable 'str3' explicitly initialized to 'null' (default value for its type).", "13:9: Variable 'ar1' explicitly initialized to 'null' (default value for its type).", "16:11: Variable 'f1' explicitly initialized to '0' (default value for its type).", "17:12: Variable 'd1' explicitly initialized to '0' (default value for its type).", "20:17: Variable 'ch1' explicitly initialized to '\\0' (default value for its type).", "21:17: Variable 'ch2' explicitly initialized to '\\0' (default value for its type).", "37:25: Variable 'bar' explicitly initialized to 'null' (default value for its type).", "38:27: Variable 'barArray' explicitly initialized to 'null' (default value for its type).", "45:21: Variable 'x' explicitly initialized to '0' (default value for its type).", "46:29: Variable 'bar' explicitly initialized to 'null' (default value for its type).", "47:31: Variable 'barArray' explicitly initialized to 'null' (default value for its type).", "50:17: Variable 'x' explicitly initialized to '0' (default value for its type).", "51:25: Variable 'bar' explicitly initialized to 'null' (default value for its type).", "52:27: Variable 'barArray' explicitly initialized to 'null' (default value for its type).", }; verify(checkConfig, getPath("coding" + File.separator + "InputExplicitInit.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheckTest.java100644 0 0 15104 12026050765 30473 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class FallThroughCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(FallThroughCheck.class); final String[] expected = { "12:13: Fall through from previous branch of the switch statement.", "36:13: Fall through from previous branch of the switch statement.", "51:13: Fall through from previous branch of the switch statement.", "68:13: Fall through from previous branch of the switch statement.", "85:13: Fall through from previous branch of the switch statement.", "103:13: Fall through from previous branch of the switch statement.", "121:13: Fall through from previous branch of the switch statement.", "367:11: Fall through from previous branch of the switch statement.", "370:11: Fall through from previous branch of the switch statement.", "372:40: Fall through from previous branch of the switch statement.", }; verify(checkConfig, getPath("coding" + File.separator + "InputFallThrough.java"), expected); } @Test public void testLastCaseGroup() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(FallThroughCheck.class); checkConfig.addAttribute("checkLastCaseGroup", "true"); final String[] expected = { "12:13: Fall through from previous branch of the switch statement.", "36:13: Fall through from previous branch of the switch statement.", "51:13: Fall through from previous branch of the switch statement.", "68:13: Fall through from previous branch of the switch statement.", "85:13: Fall through from previous branch of the switch statement.", "103:13: Fall through from previous branch of the switch statement.", "121:13: Fall through from previous branch of the switch statement.", "121:13: Fall through from the last branch of the switch statement.", "367:11: Fall through from previous branch of the switch statement.", "370:11: Fall through from previous branch of the switch statement.", "372:40: Fall through from previous branch of the switch statement.", "374:11: Fall through from the last branch of the switch statement.", }; verify(checkConfig, getPath("coding" + File.separator + "InputFallThrough.java"), expected); } @Test public void testOwnPattern() throws Exception { final String ownPattern = "Continue with next case"; final DefaultConfiguration checkConfig = createCheckConfig(FallThroughCheck.class); checkConfig.addAttribute("reliefPattern", ownPattern); final String[] expected = { "12:13: Fall through from previous branch of the switch statement.", "36:13: Fall through from previous branch of the switch statement.", "51:13: Fall through from previous branch of the switch statement.", "68:13: Fall through from previous branch of the switch statement.", "85:13: Fall through from previous branch of the switch statement.", "103:13: Fall through from previous branch of the switch statement.", "121:13: Fall through from previous branch of the switch statement.", "143:11: Fall through from previous branch of the switch statement.", "168:11: Fall through from previous branch of the switch statement.", "184:11: Fall through from previous branch of the switch statement.", "202:11: Fall through from previous branch of the switch statement.", "220:11: Fall through from previous branch of the switch statement.", "239:11: Fall through from previous branch of the switch statement.", "250:26: Fall through from previous branch of the switch statement.", "264:11: Fall through from previous branch of the switch statement.", "279:11: Fall through from previous branch of the switch statement.", "282:11: Fall through from previous branch of the switch statement.", "286:11: Fall through from previous branch of the switch statement.", "288:25: Fall through from previous branch of the switch statement.", "304:11: Fall through from previous branch of the switch statement.", "307:11: Fall through from previous branch of the switch statement.", "309:25: Fall through from previous branch of the switch statement.", "325:11: Fall through from previous branch of the switch statement.", "328:11: Fall through from previous branch of the switch statement.", "330:23: Fall through from previous branch of the switch statement.", "346:11: Fall through from previous branch of the switch statement.", "349:11: Fall through from previous branch of the switch statement.", "351:30: Fall through from previous branch of the switch statement.", }; verify(checkConfig, getPath("coding" + File.separator + "InputFallThrough.java"), expected); } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheckTest.j100644 0 0 6554 12026050765 31227 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class FinalLocalVariableCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(FinalLocalVariableCheck.class); final String[] expected = { "9:13: Variable 'i' should be declared final.", "9:16: Variable 'j' should be declared final.", "10:18: Variable 'runnable' should be declared final.", "20:13: Variable 'i' should be declared final.", "24:13: Variable 'z' should be declared final.", "26:16: Variable 'obj' should be declared final.", "30:16: Variable 'x' should be declared final.", "36:18: Variable 'runnable' should be declared final.", "40:21: Variable 'q' should be declared final.", "56:13: Variable 'i' should be declared final.", "60:13: Variable 'z' should be declared final.", "62:16: Variable 'obj' should be declared final.", "66:16: Variable 'x' should be declared final.", "74:21: Variable 'w' should be declared final.", "75:26: Variable 'runnable' should be declared final.", "88:18: Variable 'i' should be declared final.", "96:17: Variable 'weird' should be declared final.", "97:17: Variable 'j' should be declared final.", "98:17: Variable 'k' should be declared final.", }; verify(checkConfig, getPath("coding/InputFinalLocalVariable.java"), expected); } @Test public void testParameter() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(FinalLocalVariableCheck.class); checkConfig.addAttribute("tokens", "PARAMETER_DEF"); final String[] expected = { "45:28: Variable 'aArg' should be declared final.", "149:36: Variable '_o' should be declared final.", "154:37: Variable '_o1' should be declared final.", }; verify(checkConfig, getPath("coding/InputFinalLocalVariable.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheckTest.java100644 0 0 30771 12026050765 30422 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class HiddenFieldCheckTest extends BaseCheckTestSupport { @Test public void testNoParameters() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); checkConfig.addAttribute("tokens", "VARIABLE_DEF"); final String[] expected = { "18:13: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "200:17: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); final String[] expected = { "18:13: 'hidden' hides a field.", "21:33: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "49:26: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "69:17: 'innerHidden' hides a field.", "70:17: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "100:29: 'prop' hides a field.", "106:29: 'prop' hides a field.", "112:29: 'prop' hides a field.", "124:28: 'prop' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "179:23: 'y' hides a field.", "200:17: 'hidden' hides a field.", "210:20: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", "230:41: 'x' hides a field.", "236:30: 'xAxis' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } /** tests ignoreFormat property */ @Test public void testIgnoreFormat() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); checkConfig.addAttribute("ignoreFormat", "^i.*$"); final String[] expected = { "18:13: 'hidden' hides a field.", "21:33: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "56:17: 'hidden' hides a field.", "64:22: 'hidden' hides a field.", "70:17: 'hidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "100:29: 'prop' hides a field.", "106:29: 'prop' hides a field.", "112:29: 'prop' hides a field.", "124:28: 'prop' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "179:23: 'y' hides a field.", "200:17: 'hidden' hides a field.", "210:20: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", "230:41: 'x' hides a field.", "236:30: 'xAxis' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } /** tests ignoreSetter property */ @Test public void testIgnoreSetter() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); checkConfig.addAttribute("ignoreSetter", "true"); final String[] expected = { "18:13: 'hidden' hides a field.", "21:33: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "49:26: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "69:17: 'innerHidden' hides a field.", "70:17: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "106:29: 'prop' hides a field.", "112:29: 'prop' hides a field.", "124:28: 'prop' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "179:23: 'y' hides a field.", "200:17: 'hidden' hides a field.", "210:20: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", "230:41: 'x' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } /** tests ignoreConstructorParameter property */ @Test public void testIgnoreConstructorParameter() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); checkConfig.addAttribute("ignoreConstructorParameter", "true"); final String[] expected = { "18:13: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "69:17: 'innerHidden' hides a field.", "70:17: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "100:29: 'prop' hides a field.", "106:29: 'prop' hides a field.", "112:29: 'prop' hides a field.", "124:28: 'prop' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "179:23: 'y' hides a field.", "200:17: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", "230:41: 'x' hides a field.", "236:30: 'xAxis' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } /** Test against a class with field declarations in different order */ @Test public void testReordered() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); final String[] expected = { "18:13: 'hidden' hides a field.", "21:40: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "49:26: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "69:17: 'innerHidden' hides a field.", "70:17: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "83:13: 'hidden' hides a field.", "105:17: 'hidden' hides a field.", "118:21: 'hidden' hides a field.", "125:13: 'hidden' hides a field.", "131:13: 'hiddenStatic' hides a field.", }; verify(checkConfig, getPath("InputHiddenFieldReorder.java"), expected); } @Test public void testIgnoreAbstractMethods() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); checkConfig.addAttribute("ignoreAbstractMethods", "true"); final String[] expected = { "18:13: 'hidden' hides a field.", "21:33: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "49:26: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "69:17: 'innerHidden' hides a field.", "70:17: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "100:29: 'prop' hides a field.", "106:29: 'prop' hides a field.", "112:29: 'prop' hides a field.", "124:28: 'prop' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "179:23: 'y' hides a field.", "200:17: 'hidden' hides a field.", "210:20: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", "236:30: 'xAxis' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/IllegalCatchCheckTest.java100644 0 0 5342 12026050765 30553 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class IllegalCatchCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(IllegalCatchCheck.class); String[] expected = { "6:11: Catching 'RuntimeException' is not allowed.", "7:11: Catching 'Exception' is not allowed.", "8:11: Catching 'Throwable' is not allowed.", "14:11: Catching 'java.lang.RuntimeException' is not allowed.", "15:11: Catching 'java.lang.Exception' is not allowed.", "16:11: Catching 'java.lang.Throwable' is not allowed.", }; verify(checkConfig, getPath("coding" + File.separator + "InputIllegalCatchCheck.java"), expected); } @Test public void testIllegalClassNames() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(IllegalCatchCheck.class); checkConfig.addAttribute("illegalClassNames", "java.lang.Error, java.lang.Exception, java.lang.Throwable"); String[] expected = { "7:11: Catching 'Exception' is not allowed.", "8:11: Catching 'Throwable' is not allowed.", "15:11: Catching 'java.lang.Exception' is not allowed.", "16:11: Catching 'java.lang.Throwable' is not allowed.", }; verify(checkConfig, getPath("coding" + File.separator + "InputIllegalCatchCheck.java"), expected); } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheckTest100644 0 0 4522 12026050764 31433 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class IllegalInstantiationCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IllegalInstantiationCheck.class); checkConfig.addAttribute( "classes", "java.lang.Boolean," + "com.puppycrawl.tools.checkstyle.InputModifier," + "java.io.File," + "java.awt.Color"); final String[] expected = { "19:21: Instantiation of java.lang.Boolean should be avoided.", "24:21: Instantiation of java.lang.Boolean should be avoided.", "31:16: Instantiation of java.lang.Boolean should be avoided.", "38:21: Instantiation of " + "com.puppycrawl.tools.checkstyle.InputModifier " + "should be avoided.", "41:18: Instantiation of java.io.File should be avoided.", "44:21: Instantiation of java.awt.Color should be avoided.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/IllegalThrowsCheckTest.java100644 0 0 7605 12026050764 31022 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; import java.io.File; public class IllegalThrowsCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(IllegalThrowsCheck.class); String[] expected = { "9:51: Throwing 'RuntimeException' is not allowed.", "14:45: Throwing 'java.lang.RuntimeException' is not allowed.", "14:73: Throwing 'java.lang.Error' is not allowed.", }; verify(checkConfig, getPath("coding" + File.separator + "InputIllegalThrowsCheck.java"), expected); } @Test public void testIllegalClassNames() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(IllegalThrowsCheck.class); checkConfig.addAttribute("illegalClassNames", "java.lang.Error, java.lang.Exception, NullPointerException"); String[] expected = { "5:33: Throwing 'NullPointerException' is not allowed.", "14:73: Throwing 'java.lang.Error' is not allowed.", }; verify(checkConfig, getPath("coding" + File.separator + "InputIllegalThrowsCheck.java"), expected); } /** * Test to validate the IllegalThrowsCheck with ignoredMethodNames attribute * @throws Exception */ @Test public void testIgnoreMethodNames() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(IllegalThrowsCheck.class); checkConfig.addAttribute("ignoredMethodNames", "methodTwo"); String[] expected = { "9:51: Throwing 'RuntimeException' is not allowed.", "18:35: Throwing 'Throwable' is not allowed.", }; verify(checkConfig, getPath("coding" + File.separator + "InputIllegalThrowsCheck.java"), expected); } /** * Test to validate the IllegalThrowsCheck with both the attributes specified * @throws Exception */ @Test public void testIllegalClassNamesWithIgnoreMethodNames() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(IllegalThrowsCheck.class); checkConfig.addAttribute("illegalClassNames", "java.lang.Error, java.lang.Exception, NullPointerException, Throwable"); checkConfig.addAttribute("ignoredMethodNames", "methodTwo"); String[] expected = { "5:33: Throwing 'NullPointerException' is not allowed.", "18:35: Throwing 'Throwable' is not allowed.", }; verify(checkConfig, getPath("coding" + File.separator + "InputIllegalThrowsCheck.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenCheckTest.java100644 0 0 4241 12026050764 30605 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class IllegalTokenCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IllegalTokenCheck.class); final String[] expected = { "11:9: Using 'switch' is not allowed.", "14:18: Using '--' is not allowed.", "15:18: Using '++' is not allowed.", }; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } @Test public void testNative() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IllegalTokenCheck.class); checkConfig.addAttribute("tokens", "LITERAL_NATIVE"); final String[] expected = { "20:12: Using 'native' is not allowed.", }; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheckTest.jav100644 0 0 4662 12026050764 31320 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class IllegalTokenTextCheckTest extends BaseCheckTestSupport { @Test public void testCaseSensitive() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IllegalTokenTextCheck.class); checkConfig.addAttribute("tokens", "STRING_LITERAL"); checkConfig.addAttribute("format", "a href"); final String[] expected = { "24:28: Token text matches the illegal pattern 'a href'.", }; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } @Test public void testCaseInSensitive() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IllegalTokenTextCheck.class); checkConfig.addAttribute("tokens", "STRING_LITERAL"); checkConfig.addAttribute("format", "a href"); checkConfig.addAttribute("ignoreCase", "true"); final String[] expected = { "24:28: Token text matches the illegal pattern 'a href'.", "25:32: Token text matches the illegal pattern 'a href'.", }; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheckTest.java100644 0 0 10342 12026050763 30464 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Before; import org.junit.Test; public class IllegalTypeCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(IllegalTypeCheck.class); } @Test public void testDefaults() throws Exception { String[] expected = { "6:13: Declaring variables, return values or parameters of type 'AbstractClass' is not allowed.", "9:13: Declaring variables, return values or parameters of type " + "'com.puppycrawl.tools.checkstyle.checks.coding.InputIllegalType.AbstractClass'" + " is not allowed.", "16:13: Declaring variables, return values or parameters of type 'java.util.Hashtable' is not allowed.", "17:13: Declaring variables, return values or parameters of type 'Hashtable' is not allowed.", }; verify(mCheckConfig, getPath("coding" + File.separator + "InputIllegalType.java"), expected); } @Test public void testIgnoreMethodNames() throws Exception { mCheckConfig.addAttribute("ignoredMethodNames", "table2"); String[] expected = { "6:13: Declaring variables, return values or parameters of type 'AbstractClass' is not allowed.", "9:13: Declaring variables, return values or parameters of type " + "'com.puppycrawl.tools.checkstyle.checks.coding.InputIllegalType.AbstractClass'" + " is not allowed.", "16:13: Declaring variables, return values or parameters of type 'java.util.Hashtable' is not allowed.", }; verify(mCheckConfig, getPath("coding" + File.separator + "InputIllegalType.java"), expected); } @Test public void testFormat() throws Exception { mCheckConfig.addAttribute("format", "^$"); String[] expected = { "16:13: Declaring variables, return values or parameters of type 'java.util.Hashtable' is not allowed.", "17:13: Declaring variables, return values or parameters of type 'Hashtable' is not allowed.", }; verify(mCheckConfig, getPath("coding" + File.separator + "InputIllegalType.java"), expected); } @Test public void testLegalAbstractClassNames() throws Exception { mCheckConfig.addAttribute("legalAbstractClassNames", "AbstractClass"); String[] expected = { "9:13: Declaring variables, return values or parameters of type " + "'com.puppycrawl.tools.checkstyle.checks.coding.InputIllegalType.AbstractClass'" + " is not allowed.", "16:13: Declaring variables, return values or parameters of type 'java.util.Hashtable' is not allowed.", "17:13: Declaring variables, return values or parameters of type 'Hashtable' is not allowed.", }; verify(mCheckConfig, getPath("coding" + File.separator + "InputIllegalType.java"), expected); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/InnerAssignmentCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/InnerAssignmentCheckTest.java100644 0 0 5113 12026050763 31335 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class InnerAssignmentCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(InnerAssignmentCheck.class); final String[] expected = { "11:15: Inner assignments should be avoided.", "11:19: Inner assignments should be avoided.", "13:39: Inner assignments should be avoided.", "15:35: Inner assignments should be avoided.", "33:16: Inner assignments should be avoided.", "34:24: Inner assignments should be avoided.", "35:19: Inner assignments should be avoided.", "36:17: Inner assignments should be avoided.", "37:29: Inner assignments should be avoided.", "38:20: Inner assignments should be avoided.", "39:17: Inner assignments should be avoided.", "39:31: Inner assignments should be avoided.", "39:41: Inner assignments should be avoided.", "40:16: Inner assignments should be avoided.", "40:27: Inner assignments should be avoided.", "41:32: Inner assignments should be avoided.", }; verify(checkConfig, getPath("coding" + File.separator + "InputInnerAssignment.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/JUnitTestCaseCheckTest.java100644 0 0 4417 12026050763 30724 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class JUnitTestCaseCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(JUnitTestCaseCheck.class); String[] expected = { "14:5: The method 'setUp' must be public or protected.", "15:5: The method 'tearDown' shouldn't be static.", "16:5: The method 'suite' must be declared static.", "21:5: The method 'SetUp' should be named 'setUp'.", "22:5: The method 'tearDown' must be declared with a void return type.", "23:5: The method 'suite' must be declared with a junit.framework.Test return type.", "28:5: The method 'setUp' must be declared with no parameters.", "30:5: The method 'suite' must be declared static.", "31:5: The method 'tearDown' must be declared with no parameters.", }; verify(checkConfig, getPath("coding" + File.separator + "InputJUnitTest.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/MagicNumberCheckTest.java100644 0 0 36154 12026050763 30453 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class MagicNumberCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MagicNumberCheck.class); final String[] expected = { "41:26: '3' is a magic number.", "42:32: '1.5' is a magic number.", "43:27: '3' is a magic number.", "43:31: '4' is a magic number.", "45:29: '3' is a magic number.", "47:23: '3' is a magic number.", "48:26: '1.5' is a magic number.", "50:22: '3' is a magic number.", "50:29: '5' is a magic number.", "50:37: '3' is a magic number.", "54:26: '3' is a magic number.", "55:39: '3' is a magic number.", "60:25: '010' is a magic number.", "61:25: '011' is a magic number.", "63:30: '010L' is a magic number.", "64:30: '011l' is a magic number.", "68:24: '0x10' is a magic number.", "69:24: '0X011' is a magic number.", "71:29: '0x10L' is a magic number.", "72:29: '0X11l' is a magic number.", "85:28: '3' is a magic number.", "92:14: '0xffffffffL' is a magic number.", "100:30: '+3' is a magic number.", "101:29: '-2' is a magic number.", "102:35: '+3.5' is a magic number.", "103:36: '-2.5' is a magic number.", "111:35: '0x80000000' is a magic number.", "112:36: '0x8000000000000000L' is a magic number.", "115:37: '020000000000' is a magic number.", "116:38: '01000000000000000000000L' is a magic number.", "131:20: '378' is a magic number.", "160:16: '31' is a magic number.", "165:16: '42' is a magic number.", "170:16: '13' is a magic number.", "174:15: '21' is a magic number.", "178:15: '37' is a magic number.", "182:15: '101' is a magic number.", "185:30: '42' is a magic number.", }; verify(checkConfig, getPath("InputMagicNumber.java"), expected); } @Test public void testIgnoreSome() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MagicNumberCheck.class); checkConfig.addAttribute("ignoreNumbers", "0, 1, 3.0, 8, 16"); checkConfig.addAttribute("ignoreAnnotation", "true"); final String[] expected = { "22:25: '2' is a magic number.", "28:35: '2' is a magic number.", "30:24: '2' is a magic number.", "32:29: '2.0' is a magic number.", "34:29: '2' is a magic number.", "36:17: '2' is a magic number.", "38:19: '2.0' is a magic number.", "42:32: '1.5' is a magic number.", "43:31: '4' is a magic number.", "48:26: '1.5' is a magic number.", "50:29: '5' is a magic number.", "61:25: '011' is a magic number.", "64:30: '011l' is a magic number.", "69:24: '0X011' is a magic number.", "72:29: '0X11l' is a magic number.", "92:14: '0xffffffffL' is a magic number.", "101:29: '-2' is a magic number.", "102:35: '+3.5' is a magic number.", "103:36: '-2.5' is a magic number.", "109:34: '0xffffffff' is a magic number.", "110:36: '0xffffffffffffffffL' is a magic number.", "111:35: '0x80000000' is a magic number.", "112:36: '0x8000000000000000L' is a magic number.", "113:36: '037777777777' is a magic number.", "114:38: '01777777777777777777777L' is a magic number.", "115:37: '020000000000' is a magic number.", "116:38: '01000000000000000000000L' is a magic number.", "131:20: '378' is a magic number.", "160:16: '31' is a magic number.", "165:16: '42' is a magic number.", "170:16: '13' is a magic number.", "174:15: '21' is a magic number.", "178:15: '37' is a magic number.", "182:15: '101' is a magic number.", }; verify(checkConfig, getPath("InputMagicNumber.java"), expected); } @Test public void testIgnoreNone() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MagicNumberCheck.class); checkConfig.addAttribute("ignoreNumbers", ""); checkConfig.addAttribute("ignoreAnnotation", "true"); final String[] expected = { "21:24: '1' is a magic number.", "22:25: '2' is a magic number.", "23:26: '0L' is a magic number.", "24:26: '0l' is a magic number.", "25:30: '0D' is a magic number.", "26:30: '0d' is a magic number.", "28:35: '2' is a magic number.", "30:20: '1' is a magic number.", "30:24: '2' is a magic number.", "31:21: '1' is a magic number.", "32:23: '1.0' is a magic number.", "32:29: '2.0' is a magic number.", "34:22: '0' is a magic number.", "34:29: '2' is a magic number.", "36:13: '1' is a magic number.", "36:17: '2' is a magic number.", "38:13: '1.0' is a magic number.", "38:19: '2.0' is a magic number.", "41:26: '3' is a magic number.", "42:32: '1.5' is a magic number.", "43:27: '3' is a magic number.", "43:31: '4' is a magic number.", "45:29: '3' is a magic number.", "47:23: '3' is a magic number.", "48:26: '1.5' is a magic number.", "50:22: '3' is a magic number.", "50:29: '5' is a magic number.", "50:37: '3' is a magic number.", "54:26: '3' is a magic number.", "55:39: '3' is a magic number.", "59:25: '00' is a magic number.", "60:25: '010' is a magic number.", "61:25: '011' is a magic number.", "63:30: '010L' is a magic number.", "64:30: '011l' is a magic number.", "67:23: '0x0' is a magic number.", "68:24: '0x10' is a magic number.", "69:24: '0X011' is a magic number.", "70:28: '0x0L' is a magic number.", "71:29: '0x10L' is a magic number.", "72:29: '0X11l' is a magic number.", "85:28: '3' is a magic number.", "92:14: '0xffffffffL' is a magic number.", "100:30: '+3' is a magic number.", "101:29: '-2' is a magic number.", "102:35: '+3.5' is a magic number.", "103:36: '-2.5' is a magic number.", "109:34: '0xffffffff' is a magic number.", "110:36: '0xffffffffffffffffL' is a magic number.", "111:35: '0x80000000' is a magic number.", "112:36: '0x8000000000000000L' is a magic number.", "113:36: '037777777777' is a magic number.", "114:38: '01777777777777777777777L' is a magic number.", "115:37: '020000000000' is a magic number.", "116:38: '01000000000000000000000L' is a magic number.", "131:20: '378' is a magic number.", "160:16: '31' is a magic number.", "165:16: '42' is a magic number.", "170:16: '13' is a magic number.", "174:15: '21' is a magic number.", "178:15: '37' is a magic number.", "182:15: '101' is a magic number.", }; verify(checkConfig, getPath("InputMagicNumber.java"), expected); } @Test public void testIntegersOnly() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MagicNumberCheck.class); checkConfig.addAttribute("tokens", "NUM_INT, NUM_LONG"); checkConfig.addAttribute("ignoreAnnotation", "true"); final String[] expected = { "41:26: '3' is a magic number.", "43:27: '3' is a magic number.", "43:31: '4' is a magic number.", "45:29: '3' is a magic number.", "47:23: '3' is a magic number.", "50:22: '3' is a magic number.", "50:29: '5' is a magic number.", "50:37: '3' is a magic number.", "54:26: '3' is a magic number.", "55:39: '3' is a magic number.", "60:25: '010' is a magic number.", "61:25: '011' is a magic number.", "63:30: '010L' is a magic number.", "64:30: '011l' is a magic number.", "68:24: '0x10' is a magic number.", "69:24: '0X011' is a magic number.", "71:29: '0x10L' is a magic number.", "72:29: '0X11l' is a magic number.", "85:28: '3' is a magic number.", "92:14: '0xffffffffL' is a magic number.", "100:30: '+3' is a magic number.", "101:29: '-2' is a magic number.", "111:35: '0x80000000' is a magic number.", "112:36: '0x8000000000000000L' is a magic number.", "115:37: '020000000000' is a magic number.", "116:38: '01000000000000000000000L' is a magic number.", "131:20: '378' is a magic number.", "160:16: '31' is a magic number.", "165:16: '42' is a magic number.", "170:16: '13' is a magic number.", "174:15: '21' is a magic number.", "178:15: '37' is a magic number.", "182:15: '101' is a magic number.", }; verify(checkConfig, getPath("InputMagicNumber.java"), expected); } @Test public void testIgnoreNegativeOctalHex() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MagicNumberCheck.class); checkConfig.addAttribute("ignoreNumbers", "-9223372036854775808, -2147483648, -1, 0, 1, 2"); checkConfig.addAttribute("tokens", "NUM_INT, NUM_LONG"); checkConfig.addAttribute("ignoreAnnotation", "true"); final String[] expected = { "41:26: '3' is a magic number.", "43:27: '3' is a magic number.", "43:31: '4' is a magic number.", "45:29: '3' is a magic number.", "47:23: '3' is a magic number.", "50:22: '3' is a magic number.", "50:29: '5' is a magic number.", "50:37: '3' is a magic number.", "54:26: '3' is a magic number.", "55:39: '3' is a magic number.", "60:25: '010' is a magic number.", "61:25: '011' is a magic number.", "63:30: '010L' is a magic number.", "64:30: '011l' is a magic number.", "68:24: '0x10' is a magic number.", "69:24: '0X011' is a magic number.", "71:29: '0x10L' is a magic number.", "72:29: '0X11l' is a magic number.", "85:28: '3' is a magic number.", "92:14: '0xffffffffL' is a magic number.", "100:30: '+3' is a magic number.", "101:29: '-2' is a magic number.", "131:20: '378' is a magic number.", "160:16: '31' is a magic number.", "165:16: '42' is a magic number.", "170:16: '13' is a magic number.", "174:15: '21' is a magic number.", "178:15: '37' is a magic number.", "182:15: '101' is a magic number.", }; verify(checkConfig, getPath("InputMagicNumber.java"), expected); } @Test public void testIgnoreHashCodeMethod() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MagicNumberCheck.class); checkConfig.addAttribute("ignoreHashCodeMethod", "true"); checkConfig.addAttribute("ignoreAnnotation", "true"); final String[] expected = { "41:26: '3' is a magic number.", "42:32: '1.5' is a magic number.", "43:27: '3' is a magic number.", "43:31: '4' is a magic number.", "45:29: '3' is a magic number.", "47:23: '3' is a magic number.", "48:26: '1.5' is a magic number.", "50:22: '3' is a magic number.", "50:29: '5' is a magic number.", "50:37: '3' is a magic number.", "54:26: '3' is a magic number.", "55:39: '3' is a magic number.", "60:25: '010' is a magic number.", "61:25: '011' is a magic number.", "63:30: '010L' is a magic number.", "64:30: '011l' is a magic number.", "68:24: '0x10' is a magic number.", "69:24: '0X011' is a magic number.", "71:29: '0x10L' is a magic number.", "72:29: '0X11l' is a magic number.", "85:28: '3' is a magic number.", "92:14: '0xffffffffL' is a magic number.", "100:30: '+3' is a magic number.", "101:29: '-2' is a magic number.", "102:35: '+3.5' is a magic number.", "103:36: '-2.5' is a magic number.", "111:35: '0x80000000' is a magic number.", "112:36: '0x8000000000000000L' is a magic number.", "115:37: '020000000000' is a magic number.", "116:38: '01000000000000000000000L' is a magic number.", "131:20: '378' is a magic number.", "165:16: '42' is a magic number.", "170:16: '13' is a magic number.", "174:15: '21' is a magic number.", "178:15: '37' is a magic number.", "182:15: '101' is a magic number.", }; verify(checkConfig, getPath("InputMagicNumber.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/MissingCtorCheckTest.java100644 0 0 3340 12026050762 30471 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class MissingCtorCheckTest extends BaseCheckTestSupport { @Test public void testMissingSwitchDefault() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MissingCtorCheck.class); final String[] expected = { "1:1: Class should define a constructor.", }; verify(checkConfig, getPath("coding" + File.separator + "InputMissingCtor.java"), expected); } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/MissingSwitchDefaultCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/MissingSwitchDefaultCheckTest100644 0 0 3465 12026050762 31420 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class MissingSwitchDefaultCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(MissingSwitchDefaultCheck.class); } @Test public void testMissingSwitchDefault() throws Exception { final String[] expected = { "15:9: switch without \"default\" clause.", }; verify( mCheckConfig, getPath("InputMissingSwitchDefault.java"), expected); } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheckT100644 0 0 3731 12026050762 31327 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class ModifiedControlVariableCheckTest extends BaseCheckTestSupport { @Test public void testModifiedControlVariable() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ModifiedControlVariableCheck.class); final String[] expected = { "14:14: Control variable 'i' is modified.", "17:15: Control variable 'i' is modified.", "20:37: Control variable 'i' is modified.", "21:17: Control variable 'i' is modified.", "25:14: Control variable 'j' is modified.", "49:15: Control variable 's' is modified.", }; verify(checkConfig, getPath("coding/InputModifiedControl.java"), expected); } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/MultipleStringLiteralsCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/MultipleStringLiteralsCheckTe100644 0 0 7472 12026050762 31435 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class MultipleStringLiteralsCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MultipleStringLiteralsCheck.class); checkConfig.addAttribute("allowedDuplicates", "2"); checkConfig.addAttribute("ignoreStringsRegexp", ""); final String[] expected = { "5:16: The String \"StringContents\" appears 3 times in the file.", "8:17: The String \"\" appears 4 times in the file.", "10:23: The String \", \" appears 3 times in the file.", }; verify(checkConfig, getPath("coding" + File.separator + "InputMultipleStringLiterals.java"), expected); } @Test public void testItIgnoreEmpty() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MultipleStringLiteralsCheck.class); checkConfig.addAttribute("allowedDuplicates", "2"); final String[] expected = { "5:16: The String \"StringContents\" appears 3 times in the file.", "10:23: The String \", \" appears 3 times in the file.", }; verify(checkConfig, getPath("coding" + File.separator + "InputMultipleStringLiterals.java"), expected); } @Test public void testItIgnoreEmptyAndComaSpace() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MultipleStringLiteralsCheck.class); checkConfig.addAttribute("allowedDuplicates", "2"); checkConfig.addAttribute("ignoreStringsRegexp", "^((\"\")|(\", \"))$"); final String[] expected = { "5:16: The String \"StringContents\" appears 3 times in the file.", }; verify(checkConfig, getPath("coding" + File.separator + "InputMultipleStringLiterals.java"), expected); } @Test public void testItWithoutIgnoringAnnotations() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MultipleStringLiteralsCheck.class); checkConfig.addAttribute("allowedDuplicates", "3"); checkConfig.addAttribute("ignoreOccurrenceContext", ""); final String[] expected = { "19:23: The String \"unchecked\" appears 4 times in the file.", }; verify(checkConfig, getPath("coding" + File.separator + "InputMultipleStringLiterals.java"), expected); } } ././@LongLink100644 0 0 162 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsC100644 0 0 4167 12026050761 31416 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; import java.io.File; public class MultipleVariableDeclarationsCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MultipleVariableDeclarationsCheck.class); final String[] expected = { "3:5: Each variable declaration must be in its own statement.", "4:5: Only one variable definition per line allowed.", "7:9: Each variable declaration must be in its own statement.", "8:9: Only one variable definition per line allowed.", "12:5: Only one variable definition per line allowed.", "15:5: Only one variable definition per line allowed.", }; verify(checkConfig, getPath("coding" + File.separator + "InputMultipleVariableDeclarations.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheckTest.java100644 0 0 6241 12026050761 31110 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; /** * The unit-test for the NestedForDepthCheck-checkstyle enhancement. * @see com.puppycrawl.tools.checkstyle.checks.coding.NestedForDepthCheck */ public class NestedForDepthCheckTest extends BaseCheckTestSupport { /** * Call the check allowing 2 layers of nested for-statements. This * means the top-level for can contain up to 2 levels of nested for * statements. As the testinput has 4 layers of for-statements below * the top-level for statement, this must cause 2 error-messages. * * @throws Exception necessary to fulfill JUnit's * interface-requirements for test-methods */ @Test public void testNestedTooDeep() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NestedForDepthCheck.class); checkConfig.addAttribute("max", "2"); final String[] expected = { "43:11: Nested for depth is 3 (max allowed is 2).", "44:13: Nested for depth is 4 (max allowed is 2).", }; verify(checkConfig, getPath("coding/InputNestedForDepth.java"), expected); } /** * Call the check allowing 4 layers of nested for-statements. This * means the top-level for can contain up to 4 levels of nested for * statements. As the testinput has 4 layers of for-statements below * the top-level for statement, this must not cause an * error-message. * * @throws Exception necessary to fulfill JUnit's * interface-requirements for test-methods */ @Test public void testNestedOk() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NestedForDepthCheck.class); checkConfig.addAttribute("max", "4"); final String[] expected = { }; verify(checkConfig, getPath("coding/InputNestedForDepth.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/NestedIfDepthCheckTest.java100644 0 0 4224 12026050761 30717 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class NestedIfDepthCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NestedIfDepthCheck.class); final String[] expected = { "17:17: Nested if-else depth is 2 (max allowed is 1).", "43:17: Nested if-else depth is 2 (max allowed is 1).", }; verify(checkConfig, getPath("coding/InputNestedIfDepth.java"), expected); } // checkConfig.addAttribute("max", "2"); @Test public void testCustomNestingDepth() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NestedIfDepthCheck.class); checkConfig.addAttribute("max", "2"); final String[] expected = { }; verify(checkConfig, getPath("coding/InputNestedIfDepth.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/NestedTryDepthCheckTest.java100644 0 0 4336 12026050761 31143 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class NestedTryDepthCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NestedTryDepthCheck.class); final String[] expected = { "20:17: Nested try depth is 2 (max allowed is 1).", "31:17: Nested try depth is 2 (max allowed is 1).", "32:21: Nested try depth is 3 (max allowed is 1).", }; verify(checkConfig, getPath("coding/InputNestedTryDepth.java"), expected); } @Test public void testCustomNestingDepth() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NestedTryDepthCheck.class); checkConfig.addAttribute("max", "2"); final String[] expected = { "32:21: Nested try depth is 3 (max allowed is 2).", }; verify(checkConfig, getPath("coding/InputNestedTryDepth.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheckTest.java100644 0 0 3663 12026050760 27573 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; /** * NoCloneCheck test. */ public class NoCloneCheckTest extends BaseCheckTestSupport { @Test public void testHasClone() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NoCloneCheck.class); final String[] expected = { "10: Avoid using clone method.", "27: Avoid using clone method.", "35: Avoid using clone method.", "39: Avoid using clone method.", "52: Avoid using clone method.", "60: Avoid using clone method.", }; verify(checkConfig, getPath("coding" + File.separator + "InputClone.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/NoFinalizerCheckTest.java100644 0 0 4063 12026050760 30451 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; /** * NoFinalizerCheck test. * * @author smckay@google.com (Steve McKay) */ public class NoFinalizerCheckTest extends BaseCheckTestSupport { @Test public void testHasFinalizer() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NoFinalizerCheck.class); final String[] expected = { "5: Avoid using finalizer method.", }; verify(checkConfig, getPath("coding/InputHasFinalizer.java"), expected); } @Test public void testHasNoFinalizer() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NoFinalizerCheck.class); final String[] expected = { }; verify(checkConfig, getPath("coding/InputFallThrough.java"), expected); } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheckInput.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheckInput100644 0 0 10135 11451330227 31373 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// //checkstyle: Checks Java source code for adherence to a set of rules. //Copyright (C) 2001-2004 Oliver Burn // //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of the License, or (at your option) any later version. // //This library 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 //Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public //License along with this library; if not, write to the Free Software //Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; /** * This Class contains no logic, but serves as test-input for the unit tests for the * OneStatementPerLineCheck-checkstyle enhancement. * @author Alexander Jesse * @see com.puppycrawl.tools.checkstyle.checks.metrics.ExcessiveTypePerFileCheck */ public class OneStatementPerLineCheckInput { /** * Dummy innerclass to test the behaviour in the case of a smalltalk-style * statements (myObject.firstMethod().secondMethod().thirdMethod()). * For this programming style each method must return the obejct itself this. */ class SmallTalkStyle { SmallTalkStyle doSomething1() { return this; } SmallTalkStyle doSomething2() { return this; } SmallTalkStyle doSomething3() { return this; } } /** * Dummy variable to work on. */ private int one = 0; /** * Dummy variable to work on. */ private int two = 0; /** * Simple legal method */ public void doLegal() { one = 1; two = 2; } /** * The illegal format is used in a coment. Therefor the whole method is legal. */ public void doLegalComment() { one = 1; //one = 1; two = 2; two = 2; /* * one = 1; two = 2; */ } /** * The illegal format is used within a String. Therefor the whole method is legal. */ public void doLegalString() { one = 1; two = 2; System.out.println("one = 1; two = 2"); } /** * Within the for-header there are 3 Statements, but this is legal. */ public void doLegalForLoop() { for (int i = 0; i < 20; i++) { one = i; } } /** * Simplest form a an illegal layout. */ public void doIllegal() { one = 1; two = 2; } /** * Smalltalk-style is considered as one statement. */ public void doIllegalSmallTalk() { SmallTalkStyle smalltalker = new SmallTalkStyle(); smalltalker.doSomething1().doSomething2().doSomething3(); } /** * Smalltalk-style is considered as one statement. */ public void doIllegalSmallTalk2() { SmallTalkStyle smalltalker = new SmallTalkStyle(); smalltalker.doSomething1() .doSomething2() .doSomething3(); } /** * While theoretically being distributed over two lines, this is a sample * of 2 statements on one line. */ public void doIllegal2() { one = 1 ; two = 2; } /** * The StringBuffer is a Java-API-class that permits smalltalk-style concatenation * on the append-method. */ public void doStringBuffer() { StringBuffer sb = new StringBuffer(); sb.append("test "); sb.append("test2 ").append("test3 "); appendToSpringBuffer(sb, "test4"); } /** * indirect stringbuffer-method. Used only internally. * @param sb The stringbuffer we want to append something * @param text The text to append */ private void appendToSpringBuffer(StringBuffer sb, String text) { sb.append(text); } }././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheckTest.100644 0 0 3402 12026050760 31250 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class OneStatementPerLineCheckTest extends BaseCheckTestSupport { @Test public void testMultiCaseClass() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(OneStatementPerLineCheck.class); final String[] expected = { "99:18: Only one statement per line allowed.", "127:11: Only one statement per line allowed.", }; verify(checkConfig, getSrcPath("checks/coding/OneStatementPerLineCheckInput.java"), expected); } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/PackageDeclarationCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/PackageDeclarationCheckTest.j100644 0 0 5076 12026050760 31247 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class PackageDeclarationCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(PackageDeclarationCheck.class); String[] expected = { "4: Missing package declaration.", }; verify(checkConfig, getPath("coding" + File.separator + "InputNoPackage.java"), expected); } @Test public void testDefault1() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(PackageDeclarationCheck.class); final String dname = "com/puppycrawl/tools/checkstyle/checks/coding" .replace('/', File.separatorChar); String[] expected = { "1:9: Package declaration does not match directory '" + dname + "'.", }; verify(checkConfig, getPath("coding" + File.separator + "InputIllegalCatchCheck.java"), expected); } @Test public void testQuiet() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(PackageDeclarationCheck.class); checkConfig.addAttribute("ignoreDirectoryName", "true"); String[] expected = { }; verify(checkConfig, getPath("coding" + File.separator + "InputIllegalCatchCheck.java"), expected); } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/ParameterAssignmentCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/ParameterAssignmentCheckTest.100644 0 0 3712 12026050757 31346 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class ParameterAssignmentCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParameterAssignmentCheck.class); final String[] expected = { "9:15: Assignment of parameter 'field' is not allowed.", "10:15: Assignment of parameter 'field' is not allowed.", "12:14: Assignment of parameter 'field' is not allowed.", "20:30: Assignment of parameter 'field1' is not allowed.", }; verify(checkConfig, getPath("coding" + File.separator + "InputParameterAssignment.java"), expected); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/RedundantThrowsCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/RedundantThrowsCheckTest.java100644 0 0 13621 12026050757 31412 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class RedundantThrowsCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(RedundantThrowsCheck.class); } @Test public void testDefaults() throws Exception { final String[] expected = { "7:37: Redundant throws: 'java.io.FileNotFoundException' is subclass of 'java.io.IOException'.", "13:16: Redundant throws: 'RuntimeException' is unchecked exception.", "19:29: Redundant throws: 'java.io.IOException' listed more then one time.", "39:27: Redundant throws: 'NullPointerException' is subclass of 'RuntimeException'.", "39:27: Redundant throws: 'NullPointerException' is unchecked exception.", "39:49: Redundant throws: 'RuntimeException' is unchecked exception.", }; verify(mCheckConfig, getPath("InputRedundantThrows.java"), expected); } @Test public void testAllowUnchecked() throws Exception { mCheckConfig.addAttribute("allowUnchecked", "true"); final String[] expected = { "7:37: Redundant throws: 'java.io.FileNotFoundException' is subclass of 'java.io.IOException'.", "19:29: Redundant throws: 'java.io.IOException' listed more then one time.", // "35:27: Unable to get class information for WrongException.", "39:27: Redundant throws: 'NullPointerException' is subclass of 'RuntimeException'.", }; verify(mCheckConfig, getPath("InputRedundantThrows.java"), expected); } @Test public void testAllowSubclasses() throws Exception { mCheckConfig.addAttribute("allowSubclasses", "true"); final String[] expected = { "13:16: Redundant throws: 'RuntimeException' is unchecked exception.", "19:29: Redundant throws: 'java.io.IOException' listed more then one time.", "39:27: Redundant throws: 'NullPointerException' is unchecked exception.", "39:49: Redundant throws: 'RuntimeException' is unchecked exception.", }; verify(mCheckConfig, getPath("InputRedundantThrows.java"), expected); } @Test public void testRejectDuplicatesOnly() throws Exception { mCheckConfig.addAttribute("allowSubclasses", "true"); mCheckConfig.addAttribute("allowUnchecked", "true"); final String[] expected = { "19:29: Redundant throws: 'java.io.IOException' listed more then one time.", }; verify(mCheckConfig, getPath("InputRedundantThrows.java"), expected); } @Test public void test_1168408_1() throws Exception { final String[] expected = {}; verify(mCheckConfig, getSrcPath("checks/javadoc/Input_01.java"), expected); } @Test public void test_1168408_2() throws Exception { final String[] expected = {}; verify(mCheckConfig, getSrcPath("checks/javadoc/Input_02.java"), expected); } @Test public void test_1168408_3() throws Exception { final String[] expected = {}; verify(mCheckConfig, getSrcPath("checks/javadoc/Input_03.java"), expected); } @Test public void test_1220726() throws Exception { final String[] expected = {}; verify(mCheckConfig, getSrcPath("checks/javadoc/BadCls.java"), expected); } @Test public void test_generics_params() throws Exception { final String[] expected = { "15:34: Redundant throws: 'RE' is unchecked exception.", "23:37: Redundant throws: 'RE' is subclass of 'E'.", "23:37: Redundant throws: 'RE' is unchecked exception.", "31:69: Redundant throws: 'NPE' is subclass of 'RE'.", "31:69: Redundant throws: 'NPE' is unchecked exception.", "31:74: Redundant throws: 'RE' is unchecked exception.", "41:38: Redundant throws: 'RuntimeException' is subclass of 'RE'.", "41:38: Redundant throws: 'RuntimeException' is unchecked exception.", "41:56: Redundant throws: 'RE' is unchecked exception.", "42:13: Redundant throws: 'java.lang.RuntimeException' is unchecked exception.", "42:13: Redundant throws: 'java.lang.RuntimeException' listed more then one time.", }; verify(mCheckConfig, getPath("javadoc/TestGenerics.java"), expected); } @Test public void test_1379666() throws Exception { final String[] expected = {}; verify(mCheckConfig, getSrcPath("checks/javadoc/Input_1379666.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheckTest.java100644 0 0 6712 12026050757 30506 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class RequireThisCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RequireThisCheck.class); final String[] expected = { "8:9: Reference to instance variable 'i' needs \"this.\".", "14:9: Method call to 'method1' needs \"this.\".", "28:9: Reference to instance variable 'i' needs \"this.\".", "53:9: Reference to instance variable 'z' needs \"this.\".", // "13:9: Unable find where 'j' is declared.", }; verify(checkConfig, getPath("coding" + File.separator + "InputRequireThis.java"), expected); } @Test public void testMethodsOnly() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RequireThisCheck.class); checkConfig.addAttribute("checkFields", "false"); final String[] expected = { "14:9: Method call to 'method1' needs \"this.\".", }; verify(checkConfig, getPath("coding" + File.separator + "InputRequireThis.java"), expected); } @Test public void testFieldsOnly() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RequireThisCheck.class); checkConfig.addAttribute("checkMethods", "false"); final String[] expected = { "8:9: Reference to instance variable 'i' needs \"this.\".", "28:9: Reference to instance variable 'i' needs \"this.\".", "53:9: Reference to instance variable 'z' needs \"this.\".", // "13:9: Unable find where 'j' is declared.", }; verify(checkConfig, getPath("coding" + File.separator + "InputRequireThis.java"), expected); } @Test public void testGenerics() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RequireThisCheck.class); final String[] expected = {}; verify(checkConfig, getPath("Input15Extensions.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheckTest.java100644 0 0 4450 12026050757 30527 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class ReturnCountCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ReturnCountCheck.class); final String[] expected = { "18:5: Return count is 7 (max allowed is 2).", "35:17: Return count is 6 (max allowed is 2).", }; verify(checkConfig, getPath("coding" + File.separator + "InputReturnCount.java"), expected); } @Test public void testFormat() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ReturnCountCheck.class); checkConfig.addAttribute("format", "^$"); final String[] expected = { "5:5: Return count is 7 (max allowed is 2).", "18:5: Return count is 7 (max allowed is 2).", "35:17: Return count is 6 (max allowed is 2).", }; verify(checkConfig, getPath("coding" + File.separator + "InputReturnCount.java"), expected); } } ././@LongLink100644 0 0 157 12026055133 10253 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/SimplifyBooleanExpressionCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/SimplifyBooleanExpressionChec100644 0 0 3564 12026050756 31464 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class SimplifyBooleanExpressionCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(SimplifyBooleanExpressionCheck.class); final String[] expected = { "20:18: Expression can be simplified.", "41:36: Expression can be simplified.", "42:36: Expression can be simplified.", "43:16: Expression can be simplified.", "43:32: Expression can be simplified.", }; verify(checkConfig, getPath("InputSimplifyBoolean.java"), expected); } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/SimplifyBooleanReturnCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/SimplifyBooleanReturnCheckTes100644 0 0 3323 12026050756 31424 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class SimplifyBooleanReturnCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(SimplifyBooleanReturnCheck.class); final String[] expected = { "20:9: Conditional logic can be removed.", "33:9: Conditional logic can be removed.", }; verify(checkConfig, getPath("InputSimplifyBoolean.java"), expected); } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/StringLiteralEqualityCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/StringLiteralEqualityCheckTes100644 0 0 3635 12026050756 31437 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class StringLiteralEqualityCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(StringLiteralEqualityCheck.class); final String[] expected = { "11:18: Literal Strings should be compared using equals(), not '=='.", "16:20: Literal Strings should be compared using equals(), not '=='.", "21:22: Literal Strings should be compared using equals(), not '=='.", }; verify(checkConfig, getPath("coding" + File.separator + "InputStringLiteralEquality.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/SuperCloneCheckTest.java100644 0 0 3415 12026050756 30315 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class SuperCloneCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(SuperCloneCheck.class); final String[] expected = { "27:19: Method 'clone' should call 'super.clone'.", "35:19: Method 'clone' should call 'super.clone'.", "60:23: Method 'clone' should call 'super.clone'.", }; verify(checkConfig, getPath("coding/InputClone.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/SuperFinalizeCheckTest.java100644 0 0 3341 12026050755 31013 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class SuperFinalizeCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(SuperFinalizeCheck.class); final String[] expected = { "27:17: Method 'finalize' should call 'super.finalize'.", "34:17: Method 'finalize' should call 'super.finalize'.", }; verify(checkConfig, getPath("coding/InputFinalize.java"), expected); } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheckTe100644 0 0 12502 12026050755 31464 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; /** * Test fixture for the UnnecessaryParenthesesCheck. * * @author Eric K. Roe */ public class UnnecessaryParenthesesCheckTest extends BaseCheckTestSupport { private static final String TEST_FILE = "coding" + File.separator + "InputUnnecessaryParentheses.java"; @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnnecessaryParenthesesCheck.class); final String[] expected = { "4:22: Unnecessary parentheses around assignment right-hand side.", "4:29: Unnecessary parentheses around expression.", "4:31: Unnecessary parentheses around identifier 'i'.", "4:46: Unnecessary parentheses around assignment right-hand side.", "5:15: Unnecessary parentheses around assignment right-hand side.", "6:14: Unnecessary parentheses around identifier 'x'.", "6:17: Unnecessary parentheses around assignment right-hand side.", "7:15: Unnecessary parentheses around assignment right-hand side.", "8:14: Unnecessary parentheses around identifier 'x'.", "8:17: Unnecessary parentheses around assignment right-hand side.", "11:22: Unnecessary parentheses around assignment right-hand side.", "11:30: Unnecessary parentheses around identifier 'i'.", "11:46: Unnecessary parentheses around assignment right-hand side.", "15:17: Unnecessary parentheses around literal '0'.", "25:11: Unnecessary parentheses around assignment right-hand side.", "29:11: Unnecessary parentheses around assignment right-hand side.", "31:11: Unnecessary parentheses around assignment right-hand side.", "33:11: Unnecessary parentheses around assignment right-hand side.", "34:16: Unnecessary parentheses around identifier 'a'.", "35:14: Unnecessary parentheses around identifier 'a'.", "35:20: Unnecessary parentheses around identifier 'b'.", "35:26: Unnecessary parentheses around literal '600'.", "35:40: Unnecessary parentheses around literal '12.5f'.", "35:56: Unnecessary parentheses around identifier 'arg2'.", "36:14: Unnecessary parentheses around string \"this\".", "36:25: Unnecessary parentheses around string \"that\".", "37:11: Unnecessary parentheses around assignment right-hand side.", "37:14: Unnecessary parentheses around string \"this is a really, really...\".", "39:16: Unnecessary parentheses around return value.", "43:21: Unnecessary parentheses around literal '1'.", "43:26: Unnecessary parentheses around literal '13.5'.", "44:22: Unnecessary parentheses around literal 'true'.", "45:17: Unnecessary parentheses around identifier 'b'.", "49:17: Unnecessary parentheses around assignment right-hand side.", "51:11: Unnecessary parentheses around assignment right-hand side.", "53:16: Unnecessary parentheses around return value.", "63:13: Unnecessary parentheses around expression.", "67:16: Unnecessary parentheses around expression.", "72:19: Unnecessary parentheses around expression.", "73:23: Unnecessary parentheses around literal '4000'.", "78:19: Unnecessary parentheses around assignment right-hand side.", "80:11: Unnecessary parentheses around assignment right-hand side.", "80:16: Unnecessary parentheses around literal '3'.", "81:27: Unnecessary parentheses around assignment right-hand side.", }; verify(checkConfig, getPath(TEST_FILE), expected); } @Test public void test15Extensions() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnnecessaryParenthesesCheck.class); final String[] expected = {}; verify(checkConfig, getPath("Input15Extensions.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/DescendantTokenCheckTest.java100644 0 0 32046 12026050775 30067 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class DescendantTokenCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); final String[] expected = {}; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } @Test public void testMaximumNumber() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "LITERAL_NATIVE"); checkConfig.addAttribute("limitedTokens", "LITERAL_NATIVE"); checkConfig.addAttribute("maximumNumber", "0"); final String[] expected = { "20:12: Count of 1 for 'LITERAL_NATIVE' descendant 'LITERAL_NATIVE' exceeds maximum count 0.", }; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } @Test public void testMessage() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "LITERAL_NATIVE"); checkConfig.addAttribute("limitedTokens", "LITERAL_NATIVE"); checkConfig.addAttribute("maximumNumber", "0"); checkConfig.addAttribute("maximumMessage", "Using ''native'' is not allowed."); final String[] expected = { "20:12: Using 'native' is not allowed.", }; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } @Test public void testMinimumNumber() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "LITERAL_SWITCH"); checkConfig.addAttribute("limitedTokens", "LITERAL_DEFAULT"); checkConfig.addAttribute("minimumNumber", "2"); final String[] expected = { "11:9: Count of 1 for 'LITERAL_SWITCH' descendant 'LITERAL_DEFAULT' is less than minimum count 2.", }; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } @Test public void testMinimumDepth() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "LITERAL_SWITCH"); checkConfig.addAttribute("limitedTokens", "LITERAL_DEFAULT"); checkConfig.addAttribute("maximumNumber", "0"); checkConfig.addAttribute("minimumDepth", "3"); final String[] expected = {}; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } @Test public void testMaximumDepth() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "LITERAL_SWITCH"); checkConfig.addAttribute("limitedTokens", "LITERAL_DEFAULT"); checkConfig.addAttribute("maximumNumber", "0"); checkConfig.addAttribute("maximumDepth", "1"); final String[] expected = {}; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } @Test public void testEmptyStatements() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "EMPTY_STAT"); checkConfig.addAttribute("limitedTokens", "EMPTY_STAT"); checkConfig.addAttribute("maximumNumber", "0"); checkConfig.addAttribute("maximumDepth", "0"); checkConfig.addAttribute("maximumMessage", "Empty statement."); final String[] expected = { "12:7: Empty statement.", "17:7: Empty statement.", "22:19: Empty statement.", "26:10: Empty statement.", "29:16: Empty statement.", "33:10: Empty statement.", "43:10: Empty statement.", "49:13: Empty statement.", "51:13: Empty statement.", "54:19: Empty statement.", "58:10: Empty statement.", "61:9: Empty statement.", "66:10: Empty statement.", "72:10: Empty statement.", "76:10: Empty statement.", "80:10: Empty statement.", }; verify(checkConfig, getPath("InputEmptyStatement.java"), expected); } @Test public void testMissingSwitchDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "LITERAL_SWITCH"); checkConfig.addAttribute("limitedTokens", "LITERAL_DEFAULT"); checkConfig.addAttribute("minimumNumber", "1"); checkConfig.addAttribute("maximumDepth", "2"); checkConfig.addAttribute("minimumMessage", "switch without \"default\" clause."); final String[] expected = { "15:9: switch without \"default\" clause.", }; verify(checkConfig, getPath("InputMissingSwitchDefault.java"), expected); } @Test public void testStringLiteralEquality() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "EQUAL,NOT_EQUAL"); checkConfig.addAttribute("limitedTokens", "STRING_LITERAL"); checkConfig.addAttribute("maximumNumber", "0"); checkConfig.addAttribute("maximumDepth", "1"); checkConfig.addAttribute("maximumMessage", "Literal Strings should be compared using equals(), not ''==''."); final String[] expected = { "11:18: Literal Strings should be compared using equals(), not '=='.", "16:20: Literal Strings should be compared using equals(), not '=='.", "21:22: Literal Strings should be compared using equals(), not '=='.", }; verify(checkConfig, getPath("coding" + File.separator + "InputStringLiteralEquality.java"), expected); } @Test public void testIllegalTokenDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "LITERAL_SWITCH, POST_INC, POST_DEC"); checkConfig.addAttribute("limitedTokens", "LITERAL_SWITCH, POST_INC, POST_DEC"); checkConfig.addAttribute("maximumNumber", "0"); checkConfig.addAttribute("maximumDepth", "0"); checkConfig.addAttribute("maximumMessage", "Using ''{2}'' is not allowed."); final String[] expected = { "11:9: Using 'LITERAL_SWITCH' is not allowed.", "14:18: Using 'POST_DEC' is not allowed.", "15:18: Using 'POST_INC' is not allowed.", }; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } @Test public void testIllegalTokenNative() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "LITERAL_NATIVE"); checkConfig.addAttribute("limitedTokens", "LITERAL_NATIVE"); checkConfig.addAttribute("maximumNumber", "0"); checkConfig.addAttribute("maximumDepth", "0"); checkConfig.addAttribute("maximumMessage", "Using ''{2}'' is not allowed."); final String[] expected = { "20:12: Using 'LITERAL_NATIVE' is not allowed.", }; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } @Test public void testReturnFromCatch() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "LITERAL_CATCH"); checkConfig.addAttribute("limitedTokens", "LITERAL_RETURN"); checkConfig.addAttribute("maximumNumber", "0"); checkConfig.addAttribute("maximumMessage", "Return from catch is not allowed."); String[] expected = { "7:11: Return from catch is not allowed.", "15:11: Return from catch is not allowed.", }; verify(checkConfig, getPath("coding" + File.separator + "InputReturnFromCatchCheck.java"), expected); } @Test public void testReturnFromFinally() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "LITERAL_FINALLY"); checkConfig.addAttribute("limitedTokens", "LITERAL_RETURN"); checkConfig.addAttribute("maximumNumber", "0"); checkConfig.addAttribute("maximumMessage", "Return from finally is not allowed."); String[] expected = { "7:11: Return from finally is not allowed.", "15:11: Return from finally is not allowed.", }; verify(checkConfig, getPath("coding" + File.separator + "InputReturnFromFinallyCheck.java"), expected); } @Test public void testNoSum() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "NOT_EQUAL,EQUAL"); checkConfig.addAttribute("limitedTokens", "LITERAL_THIS,LITERAL_NULL"); checkConfig.addAttribute("maximumNumber", "1"); checkConfig.addAttribute("maximumMessage", "What are you doing?"); String[] expected = { }; verify(checkConfig, getPath("coding" + File.separator + "InputReturnFromFinallyCheck.java"), expected); } @Test public void testWithSumCustomMsg() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "NOT_EQUAL,EQUAL"); checkConfig.addAttribute("limitedTokens", "LITERAL_THIS,LITERAL_NULL"); checkConfig.addAttribute("maximumNumber", "1"); checkConfig.addAttribute("maximumDepth", "1"); checkConfig.addAttribute("maximumMessage", "this cannot be null."); checkConfig.addAttribute("sumTokenCounts", "true"); String[] expected = { "22:32: this cannot be null.", "22:50: this cannot be null.", "23:33: this cannot be null.", "23:51: this cannot be null.", }; verify(checkConfig, getPath("coding" + File.separator + "InputReturnFromFinallyCheck.java"), expected); } @Test public void testWithSumDefaultMsg() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(DescendantTokenCheck.class); checkConfig.addAttribute("tokens", "NOT_EQUAL,EQUAL"); checkConfig.addAttribute("limitedTokens", "LITERAL_THIS,LITERAL_NULL"); checkConfig.addAttribute("maximumNumber", "1"); checkConfig.addAttribute("maximumDepth", "1"); checkConfig.addAttribute("sumTokenCounts", "true"); String[] expected = { "22:32: Total count of 2 exceeds maximum count 1 under 'EQUAL'.", "22:50: Total count of 2 exceeds maximum count 1 under 'EQUAL'.", "23:33: Total count of 2 exceeds maximum count 1 under 'NOT_EQUAL'.", "23:51: Total count of 2 exceeds maximum count 1 under 'NOT_EQUAL'.", }; verify(checkConfig, getPath("coding" + File.separator + "InputReturnFromFinallyCheck.java"), expected); } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheckTest.j100644 0 0 3500 12026050755 31323 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class DesignForExtensionCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(DesignForExtensionCheck.class); final String[] expected = { "46:5: Method 'doh' is not designed for extension - needs to be abstract, final or empty.", "54:5: Method 'aNativeMethod' is not designed for extension - needs to be abstract, final or empty.", }; verify(checkConfig, getPath("InputDesignForExtension.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheckTest.java100644 0 0 3432 12026050755 30261 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class FinalClassCheckTest extends BaseCheckTestSupport { @Test public void testFianlClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(FinalClassCheck.class); final String[] expected = { "7: Class InputFinalClass should be declared as final.", "15: Class test4 should be declared as final.", "109: Class someinnerClass should be declared as final.", }; verify(checkConfig, getPath("InputFinalClass.java"), expected); } } ././@LongLink100644 0 0 161 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/HideUtilityClassConstructorCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/HideUtilityClassConstructorCh100644 0 0 10016 12026050755 31504 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class HideUtilityClassConstructorCheckTest extends BaseCheckTestSupport { /** only static methods and no constructor - default ctor is visible */ @Test public void testUtilClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { "11:1: Utility classes should not have a public or default constructor.", }; verify(checkConfig, getPath("InputArrayTypeStyle.java"), expected); } /** nonstatic methods - always OK */ @Test public void testNonUtilClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; verify(checkConfig, getPath("InputDesignForExtension.java"), expected); } @Test public void testDerivedNonUtilClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; verify(checkConfig, getPath("design" + File.separator + "InputNonUtilityClass.java"), expected); } @Test public void testOnlyNonstaticFieldNonUtilClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; verify(checkConfig, getPath("design" + File.separator + "InputRegression1762702.java"), expected); } @Test public void testEmptyAbstractClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; verify(checkConfig, getPath("design" + File.separator + "HideUtilityClassContructor3041574_1.java"), expected); } @Test public void testEmptyClassWithOnlyPrivateFields() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; verify(checkConfig, getPath("design" + File.separator + "HideUtilityClassContructor3041574_2.java"), expected); } @Test public void testClassWithStaticInnerClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HideUtilityClassConstructorCheck.class); final String[] expected = { }; verify(checkConfig, getPath("design" + File.separator + "HideUtilityClassContructor3041574_3.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/InnerTypeLastCheckTest.java100644 0 0 4737 12026050754 31013 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class InnerTypeLastCheckTest extends BaseCheckTestSupport { @Test public void testMembersBeforeInner() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(InnerTypeLastCheck.class); final String[] expected = { "15:17: Fields and methods should be before inner classes.", "25:17: Fields and methods should be before inner classes.", "26:17: Fields and methods should be before inner classes.", "39:25: Fields and methods should be before inner classes.", "40:25: Fields and methods should be before inner classes.", "44:9: Fields and methods should be before inner classes.", "60:25: Fields and methods should be before inner classes.", "61:25: Fields and methods should be before inner classes.", "65:9: Fields and methods should be before inner classes.", "69:9: Fields and methods should be before inner classes.", "78:5: Fields and methods should be before inner classes.", }; verify(checkConfig, getPath("design" + File.separator + "InputInnerClassCheck.java"), expected); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/InterfaceIsTypeCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/InterfaceIsTypeCheckTest.java100644 0 0 4333 12026050754 31300 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class InterfaceIsTypeCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(InterfaceIsTypeCheck.class); final String[] expected = { "25: interfaces should describe a type and hence have methods.", }; verify(checkConfig, getPath("InputInterfaceIsType.java"), expected); } @Test public void testAllowMarker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(InterfaceIsTypeCheck.class); checkConfig.addAttribute("allowMarkerInterfaces", "false"); final String[] expected = { "20: interfaces should describe a type and hence have methods.", "25: interfaces should describe a type and hence have methods.", }; verify(checkConfig, getPath("InputInterfaceIsType.java"), expected); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/MutableExceptionCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/MutableExceptionCheckTest.jav100644 0 0 3371 12026050754 31352 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class MutableExceptionCheckTest extends BaseCheckTestSupport { @Test public void test() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(MutableExceptionCheck.class); String[] expected = { "6:9: The field '_errorCode' must be declared final.", "23:9: The field '_errorCode' must be declared final.", }; verify(checkConfig, getPath("design" + File.separator + "InputMutableException.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheckTest.java100644 0 0 4276 12026050754 30547 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class ThrowsCountCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(ThrowsCountCheck.class); String[] expected = { "14:20: Throws count is 2 (max allowed is 1).", "18:20: Throws count is 2 (max allowed is 1).", "22:20: Throws count is 3 (max allowed is 1).", }; verify(checkConfig, getPath("design" + File.separator + "InputThrowsCount.java"), expected); } @Test public void testMax() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(ThrowsCountCheck.class); checkConfig.addAttribute("max", "2"); String[] expected = { "22:20: Throws count is 3 (max allowed is 2).", }; verify(checkConfig, getPath("design" + File.separator + "InputThrowsCount.java"), expected); } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheckTest.j100644 0 0 10216 12026050754 31375 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.Checker; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class VisibilityModifierCheckTest extends BaseCheckTestSupport { private Checker getChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(VisibilityModifierCheck.class); checkConfig.addAttribute("publicMemberPattern", "^f[A-Z][a-zA-Z0-9]*$"); return createChecker(checkConfig); } @Test public void testInner() throws Exception { final String[] expected = { "30:24: Variable 'rData' must be private and have accessor methods.", "33:27: Variable 'protectedVariable' must be private and have accessor methods.", "36:17: Variable 'packageVariable' must be private and have accessor methods.", "41:29: Variable 'sWeird' must be private and have accessor methods.", "43:19: Variable 'sWeird2' must be private and have accessor methods.", "77:20: Variable 'someValue' must be private and have accessor methods.", }; verify(getChecker(), getPath("InputInner.java"), expected); } @Test public void testIgnoreAccess() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(VisibilityModifierCheck.class); checkConfig.addAttribute("publicMemberPattern", "^r[A-Z]"); checkConfig.addAttribute("protectedAllowed", "true"); checkConfig.addAttribute("packageAllowed", "true"); final String[] expected = { "17:20: Variable 'fData' must be private and have accessor methods.", "77:20: Variable 'someValue' must be private and have accessor methods.", }; verify(checkConfig, getPath("InputInner.java"), expected); } @Test public void testSimple() throws Exception { final String[] expected = { "39:19: Variable 'mNumCreated2' must be private and have accessor methods.", "49:23: Variable 'sTest1' must be private and have accessor methods.", "51:26: Variable 'sTest3' must be private and have accessor methods.", "53:16: Variable 'sTest2' must be private and have accessor methods.", "56:9: Variable 'mTest1' must be private and have accessor methods.", "58:16: Variable 'mTest2' must be private and have accessor methods.", }; verify(getChecker(), getPath("InputSimple.java"), expected); } @Test public void testStrictJavadoc() throws Exception { final String[] expected = { "44:9: Variable 'mLen' must be private and have accessor methods.", "45:19: Variable 'mDeer' must be private and have accessor methods.", "46:16: Variable 'aFreddo' must be private and have accessor methods.", }; verify(getChecker(), getPath("InputPublicOnly.java"), expected); } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/duplicates/StrictDuplicateCodeCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/duplicates/StrictDuplicateCodeCheckT100644 0 0 11005 12026050754 31402 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.duplicates; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.Checker; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.Configuration; import java.io.File; import org.junit.Test; public class StrictDuplicateCodeCheckTest extends BaseCheckTestSupport { @Override protected DefaultConfiguration createCheckerConfig( Configuration aCheckConfig) { final DefaultConfiguration dc = new DefaultConfiguration("root"); dc.addChild(aCheckConfig); return dc; } @Test public void testDefaultSettings() throws Exception { final Configuration checkConfig = createCheckConfig(StrictDuplicateCodeCheck.class); final String innerDupPath = getPath("duplicates/InnerDup.java"); final String[] expected = { "6: Found duplicate of 13 lines in " + innerDupPath + ", starting from line 22", }; final File[] checkedFiles = new File[] { new File(innerDupPath), new File(getPath("duplicates/Shorty.java")), }; verify(createChecker(checkConfig), checkedFiles, innerDupPath, expected); } @Test public void testSmallMin() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(StrictDuplicateCodeCheck.class); checkConfig.addAttribute("min", "3"); final String aPath = getPath("duplicates/A.java"); final String bPath = getPath("duplicates/B.java"); final String[] expected = { // imports should not be marked because developer cannot avoid them // same constant def should not be marked because order is important for this check }; final File[] checkedFiles = new File[] { new File(aPath), new File(bPath), }; verify(createChecker(checkConfig), checkedFiles, aPath, expected); } @Test public void testOverlapping() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(StrictDuplicateCodeCheck.class); checkConfig.addAttribute("min", "3"); final String path = getPath("duplicates/Overlapping.java"); final String[] expected = { "6: Found duplicate of 3 lines in " + path + ", starting from line 13", "6: Found duplicate of 5 lines in " + path + ", starting from line 25", "7: Found duplicate of 5 lines in " + path + ", starting from line 19", "13: Found duplicate of 3 lines in " + path + ", starting from line 25", "19: Found duplicate of 4 lines in " + path + ", starting from line 26", }; final File[] checkedFiles = new File[] { new File(path), }; final Checker checker = createChecker(checkConfig); verify(checker, checkedFiles, path, expected); } @Test public void testWhitespaceIsIgnored() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(StrictDuplicateCodeCheck.class); final String path = getPath("duplicates/LotsOfEmptyLines.java"); final String[] expected = { }; final File[] checkedFiles = new File[] { new File(path), }; final Checker checker = createChecker(checkConfig); verify(checker, checkedFiles, path, expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/FileSetCheckLifecycleTest.java100644 0 0 5104 12026050774 30143 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import static org.junit.Assert.assertTrue; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import com.puppycrawl.tools.checkstyle.api.Configuration; import java.io.File; import java.util.List; import org.junit.Test; public class FileSetCheckLifecycleTest extends BaseCheckTestSupport { @Override protected DefaultConfiguration createCheckerConfig( Configuration aCheckConfig) { final DefaultConfiguration dc = new DefaultConfiguration("root"); dc.addChild(aCheckConfig); return dc; } public static class TestFileSetCheck extends AbstractFileSetCheck { private static boolean destroyed; @Override public void destroy() { destroyed = true; } public static boolean isDestroyed() { return destroyed; } @Override protected void processFiltered(File aFile, List aLines) { } } @Test public void testTranslation() throws Exception { final Configuration checkConfig = createCheckConfig(TestFileSetCheck.class); final String[] expected = { }; verify(checkConfig, getPath("InputScopeAnonInner.java"), expected); assertTrue("destroy() not called by Checker", TestFileSetCheck.isDestroyed()); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheckTest.java100644 0 0 10733 12026050774 30071 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class FinalParametersCheckTest extends BaseCheckTestSupport { @Test public void testDefaultTokens() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(FinalParametersCheck.class); final String[] expected = { "23:26: Parameter s should be final.", "38:26: Parameter i should be final.", "43:26: Parameter s should be final.", "53:17: Parameter s should be final.", "69:17: Parameter s should be final.", "75:17: Parameter s should be final.", "90:45: Parameter e should be final.", "93:36: Parameter e should be final.", "110:18: Parameter aParam should be final.", "113:18: Parameter args should be final.", "116:18: Parameter args should be final.", }; verify(checkConfig, getPath("InputFinalParameters.java"), expected); } @Test public void testCtorToken() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(FinalParametersCheck.class); checkConfig.addAttribute("tokens", "CTOR_DEF"); final String[] expected = { "23:26: Parameter s should be final.", "38:26: Parameter i should be final.", "43:26: Parameter s should be final.", }; verify(checkConfig, getPath("InputFinalParameters.java"), expected); } @Test public void testMethodToken() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(FinalParametersCheck.class); checkConfig.addAttribute("tokens", "METHOD_DEF"); final String[] expected = { "53:17: Parameter s should be final.", "69:17: Parameter s should be final.", "75:17: Parameter s should be final.", "90:45: Parameter e should be final.", "93:36: Parameter e should be final.", "110:18: Parameter aParam should be final.", "113:18: Parameter args should be final.", "116:18: Parameter args should be final.", }; verify(checkConfig, getPath("InputFinalParameters.java"), expected); } @Test public void testCatchToken() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(FinalParametersCheck.class); checkConfig.addAttribute("tokens", "LITERAL_CATCH"); final String[] expected = { "125:16: Parameter npe should be final.", "131:16: Parameter e should be final.", "134:16: Parameter e should be final.", }; verify(checkConfig, getPath("InputFinalParameters.java"), expected); } @Test public void testForEachClauseToken() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(FinalParametersCheck.class); checkConfig.addAttribute("tokens", "FOR_EACH_CLAUSE"); final String[] expected = { "150:13: Parameter s should be final.", "158:13: Parameter s should be final.", }; verify(checkConfig, getPath("InputFinalParameters.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheckTest.java100644 0 0 20261 12026050753 27426 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.header; import static org.junit.Assert.fail; import com.puppycrawl.tools.checkstyle.BaseFileSetCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import org.junit.Test; public class HeaderCheckTest extends BaseFileSetCheckTestSupport { @Test public void testStaticHeader() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("java.header")); checkConfig.addAttribute("ignoreLines", ""); final String[] expected = { "1: Missing a header - not enough lines in file.", }; verify(checkConfig, getPath("inputHeader.java"), expected); } @Test public void testRegexpHeader() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("regexp.header")); final String[] expected = { "3: Line does not match expected header line of '// Created: 2002'.", }; verify(checkConfig, getPath("InputScopeAnonInner.java"), expected); } @Test public void testInlineRegexpHeader() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("header", "^/*$\\n// .*\\n// Created: 2002\\n^//.*\\n^//.*"); final String[] expected = { "3: Line does not match expected header line of '// Created: 2002'.", }; verify(checkConfig, getPath("InputScopeAnonInner.java"), expected); } @Test public void testFailureForMultilineRegexp() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("header", "^(.*\\n.*)"); try { createChecker(checkConfig); fail("Checker creation should not succeed when regexp spans multiple lines"); } catch (CheckstyleException ex) { // expected exception } } @Test public void testRegexpHeaderIgnore() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("regexp.header1")); final String[] expected = { }; verify(checkConfig, getPath("InputScopeAnonInner.java"), expected); } @Test public void testRegexpHeaderMulti1() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("regexp.header2")); checkConfig.addAttribute("multiLines", "3, 6"); final String[] expected = { }; verify(checkConfig, getPath("InputRegexpHeader1.java"), expected); } @Test public void testRegexpHeaderMulti2() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("regexp.header2")); checkConfig.addAttribute("multiLines", "3, 6"); final String[] expected = { }; verify(checkConfig, getPath("InputRegexpHeader2.java"), expected); } @Test public void testRegexpHeaderMulti3() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("regexp.header2")); checkConfig.addAttribute("multiLines", "3, 7"); final String[] expected = { }; verify(checkConfig, getPath("InputRegexpHeader1.java"), expected); } @Test public void testRegexpHeaderMulti4() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("regexp.header2")); checkConfig.addAttribute("multiLines", "3, 5, 6, 7"); final String[] expected = { }; verify(checkConfig, getPath("InputRegexpHeader3.java"), expected); } @Test public void testRegexpHeaderMulti5() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("regexp.header2")); checkConfig.addAttribute("multiLines", "3"); final String[] expected = { "1: Missing a header - not enough lines in file.", }; verify(checkConfig, getPath("InputRegexpHeader4.java"), expected); } @Test public void testRegexpHeaderSmallHeader() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("regexp.header2")); checkConfig.addAttribute("multiLines", "3, 6"); final String[] expected = { }; verify(checkConfig, getPath("InputRegexpSmallHeader.java"), expected); } @Test public void testNoHeader() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HeaderCheck.class); // No header file specified try { createChecker(checkConfig); fail(); } catch (CheckstyleException ex) { // expected exception } } @Test public void testNonExistingHeaderFile() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("nonexisting.file")); try { createChecker(checkConfig); fail(); } catch (CheckstyleException ex) { // expected exception } } @Test public void testInvalidCharset() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("java.header")); checkConfig.addAttribute("charset", "XSO-8859-1"); try { createChecker(checkConfig); fail(); } catch (CheckstyleException ex) { // expected exception } } @Test public void testEmptyFilename() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HeaderCheck.class); checkConfig.addAttribute("headerFile", ""); try { createChecker(checkConfig); fail("Checker creation should not succeed with invalid headerFile"); } catch (CheckstyleException ex) { // expected exception } } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/AvoidStarImportTest.java100644 0 0 7343 12026050753 30622 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class AvoidStarImportTest extends BaseCheckTestSupport { @Test public void testDefaultOperation() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AvoidStarImportCheck.class); final String[] expected = { "7: Using the '.*' form of import should be avoided - com.puppycrawl.tools.checkstyle.imports.*.", "9: Using the '.*' form of import should be avoided - java.io.*.", "10: Using the '.*' form of import should be avoided - java.lang.*.", "25: Using the '.*' form of import should be avoided - javax.swing.WindowConstants.*.", "26: Using the '.*' form of import should be avoided - javax.swing.WindowConstants.*.", "28: Using the '.*' form of import should be avoided - sun.net.ftpclient.FtpClient.*.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected); } @Test public void testExcludes() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AvoidStarImportCheck.class); checkConfig.addAttribute("excludes", "java.io,java.lang,javax.swing.WindowConstants.*, javax.swing.WindowConstants"); // allow the java.io/java.lang,javax.swing.WindowConstants star imports final String[] expected2 = new String[] { "7: Using the '.*' form of import should be avoided - com.puppycrawl.tools.checkstyle.imports.*.", "28: Using the '.*' form of import should be avoided - sun.net.ftpclient.FtpClient.*.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected2); } @Test public void testAllowClassImports() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AvoidStarImportCheck.class); checkConfig.addAttribute("allowClassImports", "true"); // allow all class star imports final String[] expected2 = new String[] { "25: Using the '.*' form of import should be avoided - javax.swing.WindowConstants.*.", "26: Using the '.*' form of import should be avoided - javax.swing.WindowConstants.*.", "28: Using the '.*' form of import should be avoided - sun.net.ftpclient.FtpClient.*.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected2); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/AvoidStaticImportTest.java100644 0 0 11530 12026050753 31151 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class AvoidStaticImportTest extends BaseCheckTestSupport { @Test public void testDefaultOperation() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AvoidStaticImportCheck.class); final String[] expected = { "23: Using a static member import should be avoided - java.io.File.listRoots.", "25: Using a static member import should be avoided - javax.swing.WindowConstants.*.", "26: Using a static member import should be avoided - javax.swing.WindowConstants.*.", "27: Using a static member import should be avoided - java.io.File.createTempFile.", "28: Using a static member import should be avoided - sun.net.ftpclient.FtpClient.*.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected); } @Test public void testStarExcludes() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AvoidStaticImportCheck.class); checkConfig.addAttribute("excludes", "java.io.File.*,sun.net.ftpclient.FtpClient.*"); // allow the java.io.File.*/sun.net.ftpclient.FtpClient.* star imports final String[] expected = { "25: Using a static member import should be avoided - javax.swing.WindowConstants.*.", "26: Using a static member import should be avoided - javax.swing.WindowConstants.*.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected); } @Test public void testMemberExcludes() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AvoidStaticImportCheck.class); checkConfig.addAttribute("excludes", "java.io.File.listRoots"); // allow the java.io.File.listRoots member imports final String[] expected = { "25: Using a static member import should be avoided - javax.swing.WindowConstants.*.", "26: Using a static member import should be avoided - javax.swing.WindowConstants.*.", "27: Using a static member import should be avoided - java.io.File.createTempFile.", "28: Using a static member import should be avoided - sun.net.ftpclient.FtpClient.*.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected); } @Test public void testBogusMemberExcludes() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AvoidStaticImportCheck.class); checkConfig.addAttribute( "excludes", "java.io.File.listRoots.listRoots, javax.swing.WindowConstants," + "sun.net.ftpclient.FtpClient.*FtpClient, sun.net.ftpclient.FtpClientjunk, java.io.File.listRootsmorejunk"); // allow the java.io.File.listRoots member imports final String[] expected = { "23: Using a static member import should be avoided - java.io.File.listRoots.", "25: Using a static member import should be avoided - javax.swing.WindowConstants.*.", "26: Using a static member import should be avoided - javax.swing.WindowConstants.*.", "27: Using a static member import should be avoided - java.io.File.createTempFile.", "28: Using a static member import should be avoided - sun.net.ftpclient.FtpClient.*.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/GuardTest.java100644 0 0 15147 12026050753 26616 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; public class GuardTest { @Test public void testPkgGuard1() { final Guard g = new Guard(true, false, "pkg", false, false); assertNotNull(g); assertEquals(AccessResult.UNKNOWN, g.verifyImport("asda")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("p")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkga")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a.b")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg")); } @Test public void testPkgGuard2() { final Guard g = new Guard(true, false, "pkg", true, false); assertNotNull(g); assertEquals(AccessResult.UNKNOWN, g.verifyImport("asda")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("p")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg.a.b")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg")); } @Test public void testClassGuard() { final Guard g = new Guard(true, false, "pkg.a", false); assertNotNull(g); assertEquals(AccessResult.UNKNOWN, g.verifyImport("asda")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("p")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkga")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg.a.b")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg")); } @Test public void testPkgGuard1re() { final Guard g = new Guard(true, false, "pkg", false, true); assertNotNull(g); assertEquals(AccessResult.UNKNOWN, g.verifyImport("asda")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("p")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkga")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a.b")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg")); } @Test public void testPkgGuard2re() { final Guard g = new Guard(true, false, "pkg", true, true); assertNotNull(g); assertEquals(AccessResult.UNKNOWN, g.verifyImport("asda")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("p")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg.a.b")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg")); } @Test public void testClassGuardre() { final Guard g = new Guard(true, false, "pkg.a", true); assertNotNull(g); assertEquals(AccessResult.UNKNOWN, g.verifyImport("asda")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("p")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkga")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg.a.b")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg")); } @Test public void testPkgGuard1re2() { final Guard g = new Guard(true, false, "(pkg|hallo)", false, true); assertNotNull(g); assertEquals(AccessResult.UNKNOWN, g.verifyImport("asda")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("p")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkga")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a.b")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("halloa")); assertEquals(AccessResult.ALLOWED, g.verifyImport("hallo.a")); assertEquals(AccessResult.ALLOWED, g.verifyImport("hallo.a.b")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("hallo")); } @Test public void testPkgGuard2re2() { final Guard g = new Guard(true, false, "(pkg|hallo)", true, true); assertNotNull(g); assertEquals(AccessResult.UNKNOWN, g.verifyImport("asda")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("p")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg.a.b")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg")); assertEquals(AccessResult.ALLOWED, g.verifyImport("hallo.a")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("hallo.a.b")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("hallo")); } @Test public void testClassGuardre2() { final Guard g = new Guard(true, false, "pk[gx]\\.a", true); assertNotNull(g); assertEquals(AccessResult.UNKNOWN, g.verifyImport("asda")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("p")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkga")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkg.a")); assertEquals(AccessResult.ALLOWED, g.verifyImport("pkx.a")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg.a.b")); assertEquals(AccessResult.UNKNOWN, g.verifyImport("pkg")); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheckTest.java100644 0 0 4637 12026050752 31237 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class IllegalImportCheckTest extends BaseCheckTestSupport { @Test public void testWithSupplied() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IllegalImportCheck.class); checkConfig.addAttribute("illegalPkgs", "java.io"); final String[] expected = { "9:1: Import from illegal package - java.io.*.", "23:1: Import from illegal package - java.io.File.listRoots.", "27:1: Import from illegal package - java.io.File.createTempFile.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected); } @Test public void testWithDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IllegalImportCheck.class); final String[] expected = { "15:1: Import from illegal package - sun.net.ftpclient.FtpClient.", "28:1: Import from illegal package - sun.net.ftpclient.FtpClient.*.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected); } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckRegExTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckRegExTest.100644 0 0 4667 12026050752 31402 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class ImportControlCheckRegExTest extends BaseCheckTestSupport { @Test public void testOne() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportControlCheck.class); checkConfig.addAttribute("file", System.getProperty("testinputs.dir") + "/import-control_one-re.xml"); final String[] expected = {"5:1: Disallowed import - java.io.File."}; verify(checkConfig, getPath("imports" + File.separator + "InputImportControl.java"), expected); } @Test public void testTwo() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportControlCheck.class); checkConfig.addAttribute("file", System.getProperty("testinputs.dir") + "/import-control_two-re.xml"); final String[] expected = { "3:1: Disallowed import - java.awt.Image.", "4:1: Disallowed import - javax.swing.border.*.", "6:1: Disallowed import - java.awt.Button.ABORT.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportControl.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckTest.java100644 0 0 11614 12026050752 31317 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import static org.junit.Assert.fail; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import java.io.File; import org.junit.Test; public class ImportControlCheckTest extends BaseCheckTestSupport { @Test public void testOne() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportControlCheck.class); checkConfig.addAttribute("file", System.getProperty("testinputs.dir") + "/import-control_one.xml"); final String[] expected = {"5:1: Disallowed import - java.io.File."}; verify(checkConfig, getPath("imports" + File.separator + "InputImportControl.java"), expected); } @Test public void testTwo() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportControlCheck.class); checkConfig.addAttribute("file", System.getProperty("testinputs.dir") + "/import-control_two.xml"); final String[] expected = { "3:1: Disallowed import - java.awt.Image.", "4:1: Disallowed import - javax.swing.border.*.", "6:1: Disallowed import - java.awt.Button.ABORT.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportControl.java"), expected); } @Test public void testWrong() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportControlCheck.class); checkConfig.addAttribute("file", System.getProperty("testinputs.dir") + "/import-control_wrong.xml"); final String[] expected = {"1:40: Import control file does not handle this package."}; verify(checkConfig, getPath("imports" + File.separator + "InputImportControl.java"), expected); } @Test public void testMissing() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportControlCheck.class); final String[] expected = {"1:40: Missing an import control file."}; verify(checkConfig, getPath("imports" + File.separator + "InputImportControl.java"), expected); } @Test public void testEmpty() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportControlCheck.class); checkConfig.addAttribute("file", " "); final String[] expected = {"1:40: Missing an import control file."}; verify(checkConfig, getPath("imports" + File.separator + "InputImportControl.java"), expected); } @Test public void testUnknown() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportControlCheck.class); checkConfig.addAttribute("file", "unknown-file"); final String[] expected = {}; try { verify(checkConfig, getPath("imports" + File.separator + "InputImportControl.java"), expected); fail("should fail"); } catch (CheckstyleException ex) { ; } } @Test public void testBroken() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportControlCheck.class); checkConfig.addAttribute("file", System.getProperty("testinputs.dir") + "/import-control_broken.xml"); final String[] expected = {}; try { verify(checkConfig, getPath("imports" + File.separator + "InputImportControl.java"), expected); fail("should fail"); } catch (CheckstyleException ex) { ; } } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoaderTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoaderTest.java100644 0 0 3126 12026050752 31467 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import static org.junit.Assert.assertNotNull; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import java.io.File; import org.junit.Test; public class ImportControlLoaderTest { @Test public void testLoad() throws CheckstyleException { final PkgControl root = ImportControlLoader.load(new File(System .getProperty("testinputs.dir") + "/import-control_complete.xml").toURI()); assertNotNull(root); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheckTest.java100644 0 0 22172 12026050751 30752 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class ImportOrderCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); final String[] expected = { "3: Wrong order for 'java.awt.Dialog' import.", "7: Wrong order for 'javax.swing.JComponent' import.", "9: Wrong order for 'java.io.File' import.", "11: Wrong order for 'java.io.IOException' import.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder.java"), expected); } @Test public void testGroups() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); checkConfig.addAttribute("groups", "java.awt"); checkConfig.addAttribute("groups", "javax.swing"); checkConfig.addAttribute("groups", "java.io"); final String[] expected = { "3: Wrong order for 'java.awt.Dialog' import.", "11: Wrong order for 'java.io.IOException' import.", "14: Wrong order for 'javax.swing.WindowConstants.*' import.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder.java"), expected); } @Test public void testGroupsRegexp() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); checkConfig.addAttribute("groups", "java, /^javax?\\.(awt|swing)\\./"); checkConfig.addAttribute("ordered", "false"); final String[] expected = { "9: Wrong order for 'java.io.File' import.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder.java"), expected); } @Test public void testSeparated() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); checkConfig.addAttribute("groups", "java.awt, javax.swing, java.io"); checkConfig.addAttribute("separated", "true"); checkConfig.addAttribute("ordered", "false"); final String[] expected = { "7: 'javax.swing.JComponent' should be separated from previous imports.", "9: 'java.io.File' should be separated from previous imports.", "14: Wrong order for 'javax.swing.WindowConstants.*' import.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder.java"), expected); } @Test public void testCaseInsensitive() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); checkConfig.addAttribute("caseSensitive", "false"); final String[] expected = { }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrderCaseInsensitive.java"), expected); } @Test public void testTop() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); checkConfig.addAttribute("option", "top"); final String[] expected = { "4: Wrong order for 'java.awt.Button.ABORT' import.", "18: Wrong order for 'java.io.File.*' import.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder_Top.java"), expected); } @Test public void testAbove() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); checkConfig.addAttribute("option", "above"); final String[] expected = { "5: Wrong order for 'java.awt.Button.ABORT' import.", "8: Wrong order for 'java.awt.Dialog' import.", "13: Wrong order for 'java.io.File' import.", "14: Wrong order for 'java.io.File.createTempFile' import.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder_Above.java"), expected); } @Test public void testInFlow() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); checkConfig.addAttribute("option", "inflow"); final String[] expected = { "6: Wrong order for 'java.awt.Dialog' import.", "11: Wrong order for 'javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE' import.", "12: Wrong order for 'javax.swing.WindowConstants.*' import.", "13: Wrong order for 'javax.swing.JTable' import.", "15: Wrong order for 'java.io.File.createTempFile' import.", "16: Wrong order for 'java.io.File' import.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder_InFlow.java"), expected); } @Test public void testUnder() throws Exception { // is default (testDefault) final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); checkConfig.addAttribute("option", "under"); final String[] expected = { "5: Wrong order for 'java.awt.Dialog' import.", "11: Wrong order for 'java.awt.Button.ABORT' import.", "14: Wrong order for 'java.io.File' import.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder_Under.java"), expected); } @Test public void testBottom() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); checkConfig.addAttribute("option", "bottom"); final String[] expected = { "15: Wrong order for 'java.io.File' import.", "18: Wrong order for 'java.awt.Button.ABORT' import.", "21: Wrong order for 'java.io.Reader' import.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder_Bottom.java"), expected); } @Test public void testHonorsTokenProperty() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); checkConfig.addAttribute("tokens", "IMPORT"); final String[] expected = { "6: Wrong order for 'java.awt.Button' import.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder_HonorsTokensProperty.java"), expected); } @Test public void testWildcard() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); checkConfig.addAttribute("groups", "com,*,java"); final String[] expected = { "9: Wrong order for 'javax.crypto.Cipher' import.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder_Wildcard.java"), expected); } @Test public void testWildcardUnspecified() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); /* */ checkConfig.addAttribute("groups", "java,javax,org"); final String[] expected = {}; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder_WildcardUnspecified.java"), expected); } @Test public void testNoFailureForRedundantImports() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportOrderCheck.class); final String[] expected = {}; verify(checkConfig, getPath("imports" + File.separator + "InputImportOrder_NoFailureForRedundantImports.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/PkgControlRegExpTest.java100644 0 0 10330 12026050751 30734 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Before; import org.junit.Test; public class PkgControlRegExpTest { private final PkgControl pcRoot = new PkgControl("com.kazgroup.courtlink"); private final PkgControl pcCommon = new PkgControl(pcRoot, "common"); @Before public void setUp() throws Exception { pcRoot.addGuard(new Guard(false, false, ".*\\.(spring|lui)framework", false, true)); pcRoot.addGuard(new Guard(false, false, "org\\.hibernate", false, true)); pcRoot.addGuard(new Guard(true, false, "org\\.(apache|lui)\\.commons", false, true)); pcCommon.addGuard(new Guard(true, false, "org\\.h.*", false, true)); } @Test public void testFullPkg() { assertEquals("com.kazgroup.courtlink", pcRoot.getFullPackage()); assertEquals("com.kazgroup.courtlink.common", pcCommon.getFullPackage()); } @Test public void testLocateFinest() { assertEquals(pcRoot, pcRoot .locateFinest("com.kazgroup.courtlink.domain")); assertEquals(pcCommon, pcRoot .locateFinest("com.kazgroup.courtlink.common.api")); assertNull(pcRoot.locateFinest("com")); } @Test public void testCheckAccess() { assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess( "org.springframework.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess( "org.luiframework.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess( "de.springframework.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess( "de.luiframework.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.ALLOWED, pcCommon .checkAccess("org.apache.commons.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.ALLOWED, pcCommon .checkAccess("org.lui.commons.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess( "org.apache.commons", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess( "org.lui.commons", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.ALLOWED, pcCommon.checkAccess( "org.hibernate.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess( "com.badpackage.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.DISALLOWED, pcRoot.checkAccess( "org.hibernate.something", "com.kazgroup.courtlink")); } @Test public void testUnknownPkg() { assertNull(pcRoot.locateFinest("net.another")); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/PkgControlTest.java100644 0 0 6626 12026050751 27616 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Before; import org.junit.Test; public class PkgControlTest { private final PkgControl pcRoot = new PkgControl("com.kazgroup.courtlink"); private final PkgControl pcCommon = new PkgControl(pcRoot, "common"); @Before public void setUp() throws Exception { pcRoot.addGuard(new Guard(false, false, "org.springframework", false, false)); pcRoot.addGuard(new Guard(false, false, "org.hibernate", false, false)); pcRoot.addGuard(new Guard(true, false, "org.apache.commons", false, false)); pcCommon.addGuard(new Guard(true, false, "org.hibernate", false, false)); } @Test public void testFullPkg() { assertEquals("com.kazgroup.courtlink", pcRoot.getFullPackage()); assertEquals("com.kazgroup.courtlink.common", pcCommon.getFullPackage()); } @Test public void testLocateFinest() { assertEquals(pcRoot, pcRoot .locateFinest("com.kazgroup.courtlink.domain")); assertEquals(pcCommon, pcRoot .locateFinest("com.kazgroup.courtlink.common.api")); assertNull(pcRoot.locateFinest("com")); } @Test public void testCheckAccess() { assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess( "org.springframework.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.ALLOWED, pcCommon .checkAccess("org.apache.commons.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess( "org.apache.commons", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.ALLOWED, pcCommon.checkAccess( "org.hibernate.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.DISALLOWED, pcCommon.checkAccess( "com.badpackage.something", "com.kazgroup.courtlink.common")); assertEquals(AccessResult.DISALLOWED, pcRoot.checkAccess( "org.hibernate.something", "com.kazgroup.courtlink")); } @Test public void testUnknownPkg() { assertNull(pcRoot.locateFinest("net.another")); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/RedundantImportCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/RedundantImportCheckTest.jav100644 0 0 4264 12026050751 31444 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class RedundantImportCheckTest extends BaseCheckTestSupport { @Test public void testWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RedundantImportCheck.class); final String[] expected = { "7:1: Redundant import from the same package - com.puppycrawl.tools.checkstyle.imports.*.", "8:38: Redundant import from the same package - com.puppycrawl.tools.checkstyle.imports.GlobalProperties.", "10:1: Redundant import from the java.lang package - java.lang.*.", "11:1: Redundant import from the java.lang package - java.lang.String.", "14:1: Duplicate import to line 13 - java.util.List.", "26:1: Duplicate import to line 25 - javax.swing.WindowConstants.*.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/imports/UnusedImportsCheckTest.java100644 0 0 10343 12026050751 31322 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.imports; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class UnusedImportsCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedImportsCheck.class); final String[] expected = { "8:45: Unused import - com.puppycrawl.tools.checkstyle.imports.GlobalProperties.", "11:8: Unused import - java.lang.String.", "13:8: Unused import - java.util.List.", "14:8: Unused import - java.util.List.", "17:8: Unused import - java.util.Enumeration.", "20:8: Unused import - javax.swing.JToggleButton.", "22:8: Unused import - javax.swing.BorderFactory.", "27:15: Unused import - java.io.File.createTempFile.", //"29:8: Unused import - java.awt.Component.", // Should be detected "30:8: Unused import - java.awt.Graphics2D.", "31:8: Unused import - java.awt.HeadlessException.", "32:8: Unused import - java.awt.Label.", "33:8: Unused import - java.util.Date.", "34:8: Unused import - java.util.Calendar.", "35:8: Unused import - java.util.BitSet.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected); } @Test public void testProcessJavadoc() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedImportsCheck.class); checkConfig.addAttribute("processJavadoc", "true"); final String[] expected = { "8:45: Unused import - com.puppycrawl.tools.checkstyle.imports.GlobalProperties.", "11:8: Unused import - java.lang.String.", "13:8: Unused import - java.util.List.", "14:8: Unused import - java.util.List.", "17:8: Unused import - java.util.Enumeration.", "20:8: Unused import - javax.swing.JToggleButton.", "22:8: Unused import - javax.swing.BorderFactory.", "27:15: Unused import - java.io.File.createTempFile.", //"29:8: Unused import - java.awt.Component.", // Should be detected "32:8: Unused import - java.awt.Label.", }; verify(checkConfig, getPath("imports" + File.separator + "InputImport.java"), expected); } @Test public void testAnnotations() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedImportsCheck.class); final String[] expected = {}; verify(checkConfig, getPath("imports" + File.separator + "package-info.java"), expected); } @Test public void testBug() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UnusedImportsCheck.class); final String[] expected = {}; verify(checkConfig, getPath("imports" + File.separator + "InputImportBug.java"), expected); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.jav100644 0 0 130174 12026050750 31457 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.indentation; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.Checker; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; /** * * @author jrichard */ public class IndentationCheckTest extends BaseCheckTestSupport { @Test public void testInvalidLabel() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final String[] expected = { "20: label child at indentation level 10 not at correct indentation, 8", "24: label child at indentation level 16 not at correct indentation, 12", "29: label child at indentation level 2 not at correct indentation, 4", "32: label child at indentation level 18 not at correct indentation, 8", "33: ctor def child at indentation level 18 not at correct indentation, 8", "35: label child at indentation level 6 not at correct indentation, 8", "35: method call child at indentation level 6 not at correct indentation, 8", "37: label child at indentation level 6 not at correct indentation, 8", "37: method call child at indentation level 6 not at correct indentation, 8", }; verify(checkConfig, getPath("indentation/InputInvalidLabelIndent.java"), expected); } @Test public void testValidLabel() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final String[] expected = { }; verify(checkConfig, getPath("indentation/InputValidLabelIndent.java"), expected); } @Test public void testValidIfWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidIfIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testValidDotWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidDotIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testValidMethodWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidMethodIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testInvalidMethodWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputInvalidMethodIndent.java"); final String[] expected = { "17: ctor def rcurly at indentation level 6 not at correct indentation, 4", "20: ctor def modifier at indentation level 6 not at correct indentation, 4", "21: ctor def lcurly at indentation level 2 not at correct indentation, 4", "22: ctor def rcurly at indentation level 6 not at correct indentation, 4", "25: method def modifier at indentation level 2 not at correct indentation, 4", "26: method def rcurly at indentation level 6 not at correct indentation, 4", "63: method def modifier at indentation level 5 not at correct indentation, 4", "64: method def modifier at indentation level 5 not at correct indentation, 4", "65: method def return type at indentation level 5 not at correct indentation, 4", "74: method def modifier at indentation level 3 not at correct indentation, 4", "75: method def modifier at indentation level 3 not at correct indentation, 4", "76: method def return type at indentation level 3 not at correct indentation, 4", "77: method def at indentation level 5 not at correct indentation, 4", "87: ctor def child at indentation level 4 not at correct indentation, 8", "87: method call child at indentation level 4 not at correct indentation, 8", "92: method def child at indentation level 6 not at correct indentation, 8", "93: if at indentation level 6 not at correct indentation, 8", "94: if child at indentation level 10 not at correct indentation, 12", "94: method call child at indentation level 10 not at correct indentation, 12", "95: if rcurly at indentation level 6 not at correct indentation, 8", "98: method call child at indentation level 10 not at correct indentation, 12", "104: method call child at indentation level 14 not at correct indentation, 16", "107: method call child at indentation level 10 not at correct indentation, 12", "112: method call child at indentation level 14 not at correct indentation, 16", "116: method call child at indentation level 10 not at correct indentation, 12", "120: method call child at indentation level 10 not at correct indentation, 12", "121: method call rparen at indentation level 6 not at correct indentation, 8", "125: method call rparen at indentation level 6 not at correct indentation, 8", "139: method call child at indentation level 10 not at correct indentation, 12", "142: method call child at indentation level 10 not at correct indentation, 12", "152: method call child at indentation level 6 not at correct indentation, 12", "158: method def throws at indentation level 6 not at correct indentation, 8", "164: method def child at indentation level 4 not at correct indentation, 8", "169: method def child at indentation level 4 not at correct indentation, 8", "173: method def return type at indentation level 0 not at correct indentation, 4", }; verify(c, fname, expected); } @Test public void testInvalidSwitchWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputInvalidSwitchIndent.java"); final String[] expected = { "26: switch at indentation level 6 not at correct indentation, 8", "28: case child at indentation level 10 not at correct indentation, 12", "29: block child at indentation level 14 not at correct indentation, 16", "29: method call child at indentation level 14 not at correct indentation, 16", "33: block child at indentation level 14 not at correct indentation, 16", "35: case child at indentation level 14 not at correct indentation, 12", "36: case child at indentation level 10 not at correct indentation, 12", "39: case child at indentation level 10 not at correct indentation, 12", "40: block child at indentation level 14 not at correct indentation, 16", "40: method call child at indentation level 14 not at correct indentation, 16", "41: block child at indentation level 14 not at correct indentation, 16", "49: block child at indentation level 14 not at correct indentation, 16", "49: method call child at indentation level 14 not at correct indentation, 16", "50: block child at indentation level 18 not at correct indentation, 16", "51: block rcurly at indentation level 10 not at correct indentation, 12", "55: block lcurly at indentation level 10 not at correct indentation, 12", "58: block rcurly at indentation level 14 not at correct indentation, 12", "62: block lcurly at indentation level 14 not at correct indentation, 12", "65: block rcurly at indentation level 10 not at correct indentation, 12", "72: case child at indentation level 14 not at correct indentation, 16", "77: case child at indentation level 14 not at correct indentation, 16", "85: switch rcurly at indentation level 6 not at correct indentation, 8", "88: switch lcurly at indentation level 6 not at correct indentation, 8", "89: switch rcurly at indentation level 10 not at correct indentation, 8", "91: switch lcurly at indentation level 10 not at correct indentation, 8", "92: switch rcurly at indentation level 6 not at correct indentation, 8", }; verify(c, fname, expected); } @Test public void testValidSwitchWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidSwitchIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testValidArrayInitWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidArrayInitIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testInvalidArrayInitWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputInvalidArrayInitIndent.java"); final String[] expected = { "17: member def type at indentation level 2 not at correct indentation, 4", "18: member def type at indentation level 6 not at correct indentation, 4", "20: member def type at indentation level 2 not at correct indentation, 4", "22: array initialization rcurly at indentation level 6 not at correct indentation, 2", "24: member def type at indentation level 6 not at correct indentation, 4", "25: array initialization child at indentation level 8 not at correct indentation, 10", "26: array initialization rcurly at indentation level 4 not at correct indentation, 6", "29: array initialization child at indentation level 9 not at correct indentation, 8", "30: array initialization child at indentation level 7 not at correct indentation, 8", "31: array initialization child at indentation level 9 not at correct indentation, 8", "36: array initialization lcurly at indentation level 2 not at correct indentation, 4", "40: array initialization rcurly at indentation level 6 not at correct indentation, 4", "44: array initialization lcurly at indentation level 2 not at correct indentation, 4", "48: array initialization child at indentation level 20 not at correct indentation, [8, 31]", "49: array initialization child at indentation level 4 not at correct indentation, [8, 31]", "54: array initialization child at indentation level 6 not at correct indentation, 8", "59: member def type at indentation level 2 not at correct indentation, 4", "61: member def type at indentation level 6 not at correct indentation, 4", "62: array initialization rcurly at indentation level 2 not at correct indentation, 6", "65: array initialization child at indentation level 6 not at correct indentation, 8", "72: array initialization child at indentation level 10 not at correct indentation, 12", "85: array initialization child at indentation level 8 not at correct indentation, 12", "96: array initialization child at indentation level 10 not at correct indentation, 12", "97: array initialization child at indentation level 14 not at correct indentation, 12", "100: array initialization child at indentation level 10 not at correct indentation, 12", "101: array initialization child at indentation level 14 not at correct indentation, 12", "102: array initialization rcurly at indentation level 6 not at correct indentation, 8", "105: array initialization lcurly at indentation level 6 not at correct indentation, 8", "106: array initialization child at indentation level 14 not at correct indentation, 12", "107: array initialization child at indentation level 10 not at correct indentation, 12", "108: array initialization rcurly at indentation level 6 not at correct indentation, 8", }; verify(c, fname, expected); } @Test public void testValidTryWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidTryIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testInvalidTryWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputInvalidTryIndent.java"); final String[] expected = { "21: try at indentation level 9 not at correct indentation, 8", "22: try rcurly at indentation level 7 not at correct indentation, 8", "24: catch rcurly at indentation level 7 not at correct indentation, 8", "26: try at indentation level 4 not at correct indentation, 8", "27: method call child at indentation level 8 not at correct indentation, 12", "27: try child at indentation level 8 not at correct indentation, 12", "28: try rcurly at indentation level 4 not at correct indentation, 8", "29: finally child at indentation level 8 not at correct indentation, 12", "29: method call child at indentation level 8 not at correct indentation, 12", "34: catch child at indentation level 8 not at correct indentation, 12", "34: method call child at indentation level 8 not at correct indentation, 12", "39: try rcurly at indentation level 10 not at correct indentation, 8", "41: catch rcurly at indentation level 6 not at correct indentation, 8", "48: catch rcurly at indentation level 5 not at correct indentation, 8", "55: catch child at indentation level 10 not at correct indentation, 12", "55: method call child at indentation level 10 not at correct indentation, 12", "56: catch child at indentation level 14 not at correct indentation, 12", "57: catch child at indentation level 10 not at correct indentation, 12", "57: method call child at indentation level 10 not at correct indentation, 12", "59: catch at indentation level 6 not at correct indentation, 8", "66: try lcurly at indentation level 10 not at correct indentation, 8", "68: try rcurly at indentation level 10 not at correct indentation, 8", "70: catch lcurly at indentation level 6 not at correct indentation, 8", "73: catch rcurly at indentation level 10 not at correct indentation, 8", "76: catch child at indentation level 10 not at correct indentation, 12", "76: method call child at indentation level 10 not at correct indentation, 12", }; verify(c, fname, expected); } // TODO: needs to be finished @Test public void testInvalidClassDefWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputInvalidClassDefIndent.java"); final String[] expected = { "19: class def ident at indentation level 2 not at correct indentation, 0", "19: class def modifier at indentation level 2 not at correct indentation, 0", "25: class def lcurly at indentation level 2 not at correct indentation, 0", "28: class def rcurly at indentation level 2 not at correct indentation, 0", "31: class def ident at indentation level 2 not at correct indentation, 0", "35: class def rcurly at indentation level 2 not at correct indentation, 0", "40: class def child at indentation level 2 not at correct indentation, 4", "41: class def child at indentation level 2 not at correct indentation, 4", "47: class def child at indentation level 2 not at correct indentation, 4", "55: class def child at indentation level 2 not at correct indentation, 4", "56: class def child at indentation level 2 not at correct indentation, 4", "61: class def ident at indentation level 2 not at correct indentation, 0", "61: class def modifier at indentation level 2 not at correct indentation, 0", "62: class def lcurly at indentation level 2 not at correct indentation, 0", "70: class def rcurly at indentation level 2 not at correct indentation, 0", "74: class def child at indentation level 2 not at correct indentation, 4", "83: class def child at indentation level 2 not at correct indentation, 4", "83: class def ident at indentation level 2 not at correct indentation, 4", "85: class def ident at indentation level 6 not at correct indentation, 4", "88: class def child at indentation level 2 not at correct indentation, 4", "88: class def ident at indentation level 2 not at correct indentation, 4", "92: member def modifier at indentation level 6 not at correct indentation, 8", "93: member def type at indentation level 12 not at correct indentation, 8", "98: member def type at indentation level 10 not at correct indentation, 8", "103: member def modifier at indentation level 6 not at correct indentation, 8", "108: class def rcurly at indentation level 6 not at correct indentation, 4", "110: class def ident at indentation level 6 not at correct indentation, 4", "116: class def child at indentation level 6 not at correct indentation, 8", "116: class def ident at indentation level 6 not at correct indentation, 8", "119: class def ident at indentation level 10 not at correct indentation, 8", "121: class def rcurly at indentation level 10 not at correct indentation, 8", "124: member def type at indentation level 10 not at correct indentation, 12", "129: method def child at indentation level 10 not at correct indentation, 8", "130: object def lcurly at indentation level 8 not at correct indentation, [10, 14]", "134: object def rcurly at indentation level 8 not at correct indentation, [10, 14]", "138: object def lcurly at indentation level 6 not at correct indentation, [8, 12]", "139: method def modifier at indentation level 12 not at correct indentation, 10", "141: method def rcurly at indentation level 12 not at correct indentation, 10", "142: object def rcurly at indentation level 6 not at correct indentation, [8, 12]", "147: method def modifier at indentation level 10 not at correct indentation, 12", "149: method def rcurly at indentation level 10 not at correct indentation, 12", // TODO: extends and implements need to be added }; verify(c, fname, expected); } @Test public void testInvalidBlockWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputInvalidBlockIndent.java"); final String[] expected = { "22: block lcurly at indentation level 7 not at correct indentation, 8", "23: block lcurly at indentation level 9 not at correct indentation, 8", "25: block lcurly at indentation level 9 not at correct indentation, 8", "26: block rcurly at indentation level 7 not at correct indentation, 8", "28: block lcurly at indentation level 6 not at correct indentation, 8", "30: block rcurly at indentation level 6 not at correct indentation, 8", "31: block lcurly at indentation level 6 not at correct indentation, 8", "34: block lcurly at indentation level 9 not at correct indentation, 8", "35: block child at indentation level 13 not at correct indentation, 12", "37: block child at indentation level 13 not at correct indentation, 12", "38: block rcurly at indentation level 9 not at correct indentation, 8", "41: block lcurly at indentation level 6 not at correct indentation, 8", "42: block child at indentation level 10 not at correct indentation, 12", "44: block child at indentation level 10 not at correct indentation, 12", "45: block rcurly at indentation level 6 not at correct indentation, 8", "48: block lcurly at indentation level 6 not at correct indentation, 8", "51: block child at indentation level 10 not at correct indentation, 12", "55: block lcurly at indentation level 10 not at correct indentation, 12", "59: block rcurly at indentation level 10 not at correct indentation, 12", "64: block child at indentation level 10 not at correct indentation, 12", "66: block lcurly at indentation level 10 not at correct indentation, 12", "67: block child at indentation level 14 not at correct indentation, 16", "82: block rcurly at indentation level 10 not at correct indentation, 12", "91: static initialization at indentation level 2 not at correct indentation, 4", "92: static initialization at indentation level 6 not at correct indentation, 4", "96: static initialization child at indentation level 7 not at correct indentation, 8", "99: static initialization at indentation level 6 not at correct indentation, 4", "101: static initialization rcurly at indentation level 2 not at correct indentation, 4", "103: static initialization at indentation level 2 not at correct indentation, 4", "105: static initialization rcurly at indentation level 6 not at correct indentation, 4", "107: static initialization at indentation level 2 not at correct indentation, 4", "109: static initialization child at indentation level 6 not at correct indentation, 8", "112: static initialization lcurly at indentation level 2 not at correct indentation, 4", "113: static initialization child at indentation level 6 not at correct indentation, 8", "114: static initialization rcurly at indentation level 6 not at correct indentation, 4", "119: static initialization child at indentation level 6 not at correct indentation, 8", "124: static initialization child at indentation level 4 not at correct indentation, 8", "125: static initialization rcurly at indentation level 2 not at correct indentation, 4", "130: static initialization rcurly at indentation level 6 not at correct indentation, 4", "133: block lcurly at indentation level 2 not at correct indentation, 4", "134: block lcurly at indentation level 6 not at correct indentation, 4", "137: block lcurly at indentation level 2 not at correct indentation, 4", "139: block rcurly at indentation level 6 not at correct indentation, 4", "141: block lcurly at indentation level 6 not at correct indentation, 4", "143: block rcurly at indentation level 2 not at correct indentation, 4", "146: block child at indentation level 6 not at correct indentation, 8", }; verify(c, fname, expected); } @Test public void testInvalidIfWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputInvalidIfIndent.java"); final String[] expected = { "50: if at indentation level 1 not at correct indentation, 8", "55: if at indentation level 9 not at correct indentation, 8", "56: if lcurly at indentation level 9 not at correct indentation, 8", "57: if rcurly at indentation level 7 not at correct indentation, 8", "59: if at indentation level 6 not at correct indentation, 8", "60: if lcurly at indentation level 5 not at correct indentation, 8", "61: if rcurly at indentation level 5 not at correct indentation, 8", "65: if rcurly at indentation level 10 not at correct indentation, 8", "66: else rcurly at indentation level 7 not at correct indentation, 8", "69: if at indentation level 9 not at correct indentation, 8", "70: if lcurly at indentation level 7 not at correct indentation, 8", "72: else at indentation level 9 not at correct indentation, 8", "74: else rcurly at indentation level 9 not at correct indentation, 8", "77: if at indentation level 10 not at correct indentation, 8", "78: if rcurly at indentation level 7 not at correct indentation, 8", "79: else at indentation level 9 not at correct indentation, 8", "80: else lcurly at indentation level 7 not at correct indentation, 8", "81: else rcurly at indentation level 9 not at correct indentation, 8", "85: if at indentation level 9 not at correct indentation, 8", "86: if lcurly at indentation level 9 not at correct indentation, 8", "87: if rcurly at indentation level 9 not at correct indentation, 8", "88: else lcurly at indentation level 7 not at correct indentation, 8", "89: else rcurly at indentation level 10 not at correct indentation, 8", "92: if at indentation level 6 not at correct indentation, 8", "93: if lcurly at indentation level 10 not at correct indentation, 8", "94: if rcurly at indentation level 10 not at correct indentation, 8", "95: else rcurly at indentation level 7 not at correct indentation, 8", "98: if at indentation level 5 not at correct indentation, 8", "99: if rcurly at indentation level 11 not at correct indentation, 8", "100: else at indentation level 5 not at correct indentation, 8", "101: else rcurly at indentation level 11 not at correct indentation, 8", // "110: dot left side \"System\" at indentation level 14 not at correct indentation, 12", "121: if child at indentation level 14 not at correct indentation, 12", "126: if lcurly at indentation level 10 not at correct indentation, 8", "127: if child at indentation level 10 not at correct indentation, 12", "127: method call child at indentation level 10 not at correct indentation, 12", "132: if child at indentation level 14 not at correct indentation, 12", // TODO: should be 16, not 12 "133: method call child at indentation level 10 not at correct indentation, 12", "135: else child at indentation level 10 not at correct indentation, 12", // TODO: why we get this message (it's duplicate of previous). "135: method call child at indentation level 10 not at correct indentation, 12", "136: method call child at indentation level 8 not at correct indentation, 12", "143: if child at indentation level 16 not at correct indentation, 12", "144: if rcurly at indentation level 9 not at correct indentation, 8", "147: else child at indentation level 16 not at correct indentation, 12", "153: if child at indentation level 0 not at correct indentation, 12", "153: method call child at indentation level 0 not at correct indentation, 12", "157: else child at indentation level 40 not at correct indentation, 12", "164: if child at indentation level 14 not at correct indentation, 12", "167: else child at indentation level 14 not at correct indentation, 12", "173: if child at indentation level 10 not at correct indentation, 12", "173: method call child at indentation level 10 not at correct indentation, 12", "175: else child at indentation level 10 not at correct indentation, 12", "175: method call child at indentation level 10 not at correct indentation, 12", "179: if at indentation level 10 not at correct indentation, 8", "180: if child at indentation level 14 not at correct indentation, 12", "181: if rcurly at indentation level 10 not at correct indentation, 8", "182: else at indentation level 10 not at correct indentation, 8", "183: else child at indentation level 14 not at correct indentation, 12", "184: else rcurly at indentation level 10 not at correct indentation, 8", "187: if child at indentation level 9 not at correct indentation, 12", "188: if child at indentation level 11 not at correct indentation, 12", "192: if child at indentation level 10 not at correct indentation, 12", "195: if rcurly at indentation level 7 not at correct indentation, 8", "202: if child at indentation level 10 not at correct indentation, 12", "202: method call child at indentation level 10 not at correct indentation, 12", "204: if child at indentation level 10 not at correct indentation, 12", "204: method call child at indentation level 10 not at correct indentation, 12", "211: method call child at indentation level 10 not at correct indentation, 12", "220: if at indentation level 10 not at correct indentation, 12", "224: if child at indentation level 18 not at correct indentation, 20", "224: method call child at indentation level 18 not at correct indentation, 20", "228: if rcurly at indentation level 40 not at correct indentation, 8", "235: if rparen at indentation level 10 not at correct indentation, 8", "240: if rparen at indentation level 6 not at correct indentation, 8", "246: if lparen at indentation level 6 not at correct indentation, 8", "248: if rparen at indentation level 6 not at correct indentation, 8", }; verify(c, fname, expected); } @Test public void testInvalidWhileWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputInvalidWhileIndent.java"); final String[] expected = { "21: while at indentation level 9 not at correct indentation, 8", "22: while rcurly at indentation level 7 not at correct indentation, 8", "24: while at indentation level 7 not at correct indentation, 8", "25: while lcurly at indentation level 9 not at correct indentation, 8", "26: while rcurly at indentation level 9 not at correct indentation, 8", "28: while at indentation level 9 not at correct indentation, 8", "29: while lcurly at indentation level 6 not at correct indentation, 8", "30: while child at indentation level 14 not at correct indentation, 12", "31: while rcurly at indentation level 6 not at correct indentation, 8", "33: while at indentation level 10 not at correct indentation, 8", "35: while rcurly at indentation level 10 not at correct indentation, 8", "37: while at indentation level 10 not at correct indentation, 8", "40: while rcurly at indentation level 10 not at correct indentation, 8", "42: while at indentation level 6 not at correct indentation, 8", "43: while lcurly at indentation level 10 not at correct indentation, 8", "46: while rcurly at indentation level 6 not at correct indentation, 8", "49: if at indentation level 14 not at correct indentation, 12", "50: if child at indentation level 18 not at correct indentation, 16", "51: if rcurly at indentation level 14 not at correct indentation, 12", "52: while child at indentation level 14 not at correct indentation, 12", "53: while rcurly at indentation level 10 not at correct indentation, 8", "56: while child at indentation level 10 not at correct indentation, 12", "62: while child at indentation level 10 not at correct indentation, 12", "67: while child at indentation level 10 not at correct indentation, 12", "74: while rparen at indentation level 5 not at correct indentation, 8", "81: while rparen at indentation level 10 not at correct indentation, 8", "88: while rparen at indentation level 10 not at correct indentation, 8", "95: while child at indentation level 8 not at correct indentation, 12", }; verify(c, fname, expected); } @Test public void testInvalidForWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputInvalidForIndent.java"); final String[] expected = { "22: for at indentation level 6 not at correct indentation, 8", "23: for rcurly at indentation level 10 not at correct indentation, 8", "25: for at indentation level 9 not at correct indentation, 8", "26: for lcurly at indentation level 6 not at correct indentation, 8", "27: for rcurly at indentation level 6 not at correct indentation, 8", "31: for child at indentation level 10 not at correct indentation, 12", "31: method call child at indentation level 10 not at correct indentation, 12", "32: for rcurly at indentation level 10 not at correct indentation, 8", "35: for lcurly at indentation level 10 not at correct indentation, 8", "36: for child at indentation level 10 not at correct indentation, 12", "44: for child at indentation level 10 not at correct indentation, 12", "50: for at indentation level 7 not at correct indentation, 8", "51: for child at indentation level 10 not at correct indentation, 12", "60: for child at indentation level 7 not at correct indentation, 12", "65: for at indentation level 6 not at correct indentation, 8", "66: for child at indentation level 10 not at correct indentation, 12", "67: for child at indentation level 14 not at correct indentation, 16", "68: for child at indentation level 10 not at correct indentation, 12", "73: for rcurly at indentation level 39 not at correct indentation, 8", "77: for rparen at indentation level 12 not at correct indentation, 8", }; verify(c, fname, expected); } @Test public void testValidForWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidForIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testValidDoWhileWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidDoWhileIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testValidBlockWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidBlockIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testValidWhileWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidWhileIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testValidClassDefWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidClassDefIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testValidInterfaceDefWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidInterfaceDefIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testValidCommaWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final Checker c = createChecker(checkConfig); final String fname = getPath("indentation/InputValidCommaIndent.java"); final String[] expected = { }; verify(c, fname, expected); } @Test public void testTabs() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("basicOffset", Integer.valueOf(4).toString()); checkConfig.addAttribute("tabWidth", Integer.valueOf(4).toString()); final String[] expected = { "25: ctor def child at indentation level 9 not at correct indentation, 8", }; verify(checkConfig, getPath("indentation/InputUseTabs.java"), expected); } @Test public void testIndentationLevel() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("basicOffset", Integer.valueOf(2).toString()); final String[] expected = { "25: ctor def child at indentation level 5 not at correct indentation, 4", }; verify(checkConfig, getPath("indentation/InputUseTwoSpaces.java"), expected); } @Test public void testCaseLevel() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("caseIndent", Integer.valueOf(0).toString()); final String[] expected = { "23: case child at indentation level 10 not at correct indentation, 8", }; verify(checkConfig, getPath("indentation/InputCaseLevel.java"), expected); } @Test public void testBraceAdjustment() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); checkConfig.addAttribute("braceAdjustment", Integer.valueOf(2).toString()); final String[] expected = { "24: if rcurly at indentation level 8 not at correct indentation, 10", }; verify(checkConfig, getPath("indentation/InputBraceAdjustment.java"), expected); } @Test public void testInvalidAssignWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final String[] expected = { "6: method call child at indentation level 10 not at correct indentation, 12", "8: method call child at indentation level 10 not at correct indentation, 12", "10: method call child at indentation level 10 not at correct indentation, 12", "12: assign at indentation level 9 not at correct indentation, 12", "13: assign child at indentation level 10 not at correct indentation, 12", }; verify(checkConfig, getPath("indentation/InputInvalidAssignIndent.java"), expected); } @Test public void testValidAssignWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final String[] expected = {}; verify(checkConfig, getPath("indentation/InputValidAssignIndent.java"), expected); } @Test public void test15Extensions() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final String[] expected = {}; verify(checkConfig, getPath("Input15Extensions.java"), expected); } @Test public void testTryResources() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); final String[] expected = { //"something is expected, but there is nothing", }; verify(checkConfig, getPath("indentation/InputValidTryResourcesIndent.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/BadCls.java100644 0 0 212 11451071614 25701 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.javadoc; class BadCls { class X extends Exception {} void m() throws X {} } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/InputTags.java100644 0 0 16603 11451071614 26542 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// //Test case file for checkstyle. //Created: 2001 //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import java.io.IOException; // Tests for Javadoc tags. class InputTags1 { // Invalid - should be Javadoc private int mMissingJavadoc; // Invalid - should be Javadoc void method1() { } /** @param unused asd **/ void method2() { } /** missing return **/ int method3() { return 3; } /** * missing return * @param aOne ignored **/ int method4(int aOne) { return aOne; } /** missing throws **/ void method5() throws Exception { } /** * @see missing throws * @see need to see tags to avoid shortcut logic **/ void method6() throws Exception { } /** @throws WrongException error **/ void method7() throws Exception, NullPointerException { } /** missing param **/ void method8(int aOne) { } /** * @see missing param * @see need to see tags to avoid shortcut logic **/ void method9(int aOne) { } /** @param WrongParam error **/ void method10(int aOne, int aTwo) { } /** * @param Unneeded parameter * @return also unneeded **/ void method11() { } /** * @return first one * @return duplicate **/ int method12() { return 0; } /** * @param aOne * @param aTwo * * This is a multiline piece of javadoc * Unlike the previous one, it actually has content * @param aThree * * * This also has content * @param aFour * * @param aFive **/ void method13(int aOne, int aTwo, int aThree, int aFour, int aFive) { } /** @param aOne Perfectly legal **/ void method14(int aOne) { } /** @throws java.io.IOException * just to see if this is also legal **/ void method14() throws java.io.IOException { } // Test static initialiser static { int x = 1; // should not require any javadoc } // test initialiser { int z = 2; // should not require any javadoc } /** handle where variable declaration over several lines **/ private static final int ON_SECOND_LINE = 2; /** * Documenting different causes for the same exception * in separate tags is OK (bug 540384). * * @throws java.io.IOException if A happens * @throws java.io.IOException if B happens **/ void method15() throws java.io.IOException { } /** {@inheritDoc} **/ public String toString() { return super.toString(); } /** getting code coverage up **/ static final int serialVersionUID = 666; //**********************************************************************/ // Method Name: method16 /** * handle the case of an elaborate header surrounding javadoc comments * * @param aOne valid parameter content */ //**********************************************************************/ void method16(int aOne) { } /** * @throws ThreadDeath although bad practice, should be silently ignored * @throws ArrayStoreException another r/t subclass * @throws IllegalMonitorStateException should be told to remove from throws */ void method17() throws IllegalMonitorStateException { } /** * declaring the imported version of an Exception and documenting * the full class name is OK (bug 658805). * @throws java.io.IOException if bad things happen. */ void method18() throws IOException { throw new IOException("to make compiler happy"); } /** * reverse of bug 658805. * @throws IOException if bad things happen. */ void method19() throws java.io.IOException { throw new IOException("to make compiler happy"); } /** * Bug 579190, "expected return tag when one is there". * * Linebreaks after return tag should be legal. * * @return * the bug that states that linebreak should be legal */ int method20() { return 579190; } /** * Bug XXX, "two tags for the same exception" * * @exception java.io.IOException for some reasons * @exception IOException for another reason */ void method21() throws IOException { } /** * RFE 540383, "Unused throws tag for exception subclass" * * @exception IOException for some reasons * @exception java.io.FileNotFoundException for another reasons */ void method22() throws IOException { } /** * @exception WrongException exception w/o class info but matched by name */ void method23() throws WrongException { } /** * Bug 803577, "allowThrowsTagsForSubclasses/allowMissingThrowsTag interfere" * * no exception tag for IOException, but here is a tag for its subclass. * @exception java.io.FileNotFoundException for another reasons */ void method24() throws IOException { } /** * Bug 841942, "ArrayIndexOutOfBounds in JavadocStyle". * @param aParam there is no such param in the method. * The problem should be reported with correct line number. */ void method25() { } /** {@inheritDoc} */ int method26() { return 0; } /** * {@inheritDoc} * @return something very important. */ int method27(int aParam) { return 0; } /** * @return something very important. * {@inheritDoc} */ int method28(int aParam) { return 0; } /** * {@inheritDoc} * * @return 1 */ public int foo(Object _arg) { return 1; } } enum InputTagsEnum { CONSTANT_A, /** * */ CONSTANT_B, CONSTANT_C { /** * */ public void someMethod() { } public void someOtherMethod() { } } } @interface InputTagsAnnotation { String someField(); int A_CONSTANT = 0; /** Some javadoc. */ int B_CONSTANT = 1; /** @return This tag is not valid here */ String someField2(); } /** * Some javadoc. */ public class InputTags { /** * Constructor. */ public InputTags() { } /** * Sample method. * @param arg1 first argument * @param arg2 second argument * @return java.lang.String the result string * @throws java.lang.Exception in case of problem */ public final String myMethod(final String arg1, final Object arg2) throws Exception { return null; } } /** * Added to make this file compilable. */ class WrongException extends RuntimeException { } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/Input_01.java100644 0 0 2026 11451071614 26175 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.javadoc; /** Test 1. */ public class Input_01 { /** Do 1. * @throws TestException1 when error occurrs. */ public void doStuff1() throws TestException1 { try { doStuff2(); } catch (final TestException2 e) { } throw new Input_01().new TestException1(""); } /** Do 2. * @throws TestException2 when error occurrs. */ private static void doStuff2() throws TestException2 { throw new TestException2(""); } /** Exception 1. */ class TestException1 extends Exception { /** Exception 1. * @param messg message */ TestException1(String messg) { super(messg); } } /** Exception 2. */ public static class TestException2 extends Exception { /** Exception 2. * @param messg message */ TestException2(String messg) { super(messg); } } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/Input_02.java100644 0 0 2020 11451071614 26170 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.javadoc; /** Test 2. */ public class Input_02 { /** Exception 1. */ class TestException1 extends Exception { /** Exception 1. * @param messg message */ TestException1(String messg) { super(messg); } } /** Exception 2. */ public static class TestException2 extends Exception { /** Exception 2. * @param messg message */ TestException2(String messg) { super(messg); } } /** Do 1. * @throws TestException1 when error occurrs. */ public void doStuff1() throws TestException1 { try { doStuff2(); } catch (final TestException2 e) { } throw new Input_02().new TestException1(""); } /** Do 2. * @throws TestException2 when error occurrs. */ private static void doStuff2() throws TestException2 { throw new TestException2(""); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/Input_03.java100644 0 0 2123 11451071614 26175 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.javadoc; /** Test 3. */ public class Input_03 { /** Do 1. * @throws TestException1 when error occurrs. * @throws TestException2 when error occurrs. */ public void doStuff1() throws TestException1, TestException2 { try { doStuff2(); } catch (final TestException2 e) { } throw new Input_03().new TestException1(""); } /** Do 2. * @throws TestException2 when error occurrs. */ private static void doStuff2() throws TestException2 { throw new TestException2(""); } /** Exception 1. */ class TestException1 extends Exception { /** Exception 1. * @param messg message */ TestException1(String messg) { super(messg); } } /** Exception 2. */ public static class TestException2 extends Exception { /** Exception 2. * @param messg message */ TestException2(String messg) { super(messg); } } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/Input_1379666.java100644 0 0 1635 11451071614 26627 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.javadoc; /** * comment. */ public class Input_1379666 { /** * @throws BadStringFormat some text */ public void ok() throws BadStringFormat { } /** * @throws Input_1379666.BadStringFormat some text */ public void error1() throws com.puppycrawl.tools.checkstyle.checks.javadoc.Input_1379666.BadStringFormat { } /** * Some comment. * @throws com.puppycrawl.tools.checkstyle.checks.javadoc.Input_1379666.BadStringFormat some text */ public void error2() throws Input_1379666.BadStringFormat { } /** * Some exception class. */ public static class BadStringFormat extends Exception { /** * Some comment. * @param s string. */ BadStringFormat(String s) { super(s); } } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheckTest.java100644 0 0 46660 12026050750 31135 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.Scope; import java.io.File; import org.junit.Before; import org.junit.Test; public class JavadocMethodCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(JavadocMethodCheck.class); } @Test public void testTags() throws Exception { final String[] expected = { "14:5: Missing a Javadoc comment.", "18:9: Unused @param tag for 'unused'.", "24: Expected an @return tag.", "33: Expected an @return tag.", "40:16: Expected @throws tag for 'Exception'.", "49:16: Expected @throws tag for 'Exception'.", "53:9: Unused @throws tag for 'WrongException'.", "55:16: Expected @throws tag for 'Exception'.", "55:27: Expected @throws tag for 'NullPointerException'.", "60:22: Expected @param tag for 'aOne'.", "68:22: Expected @param tag for 'aOne'.", "72:9: Unused @param tag for 'WrongParam'.", "73:23: Expected @param tag for 'aOne'.", "73:33: Expected @param tag for 'aTwo'.", "78:8: Unused @param tag for 'Unneeded'.", "79: Unused Javadoc tag.", "87:8: Duplicate @return tag.", "109:23: Expected @param tag for 'aOne'.", "109:55: Expected @param tag for 'aFour'.", "109:66: Expected @param tag for 'aFive'.", "178:8: Unused @throws tag for 'ThreadDeath'.", "179:8: Unused @throws tag for 'ArrayStoreException'.", "236:8: Unused @throws tag for 'java.io.FileNotFoundException'.", "254:8: Unused @throws tag for 'java.io.FileNotFoundException'.", "256:28: Expected @throws tag for 'IOException'.", "262:8: Unused @param tag for 'aParam'.", "320:9: Missing a Javadoc comment.", "329:5: Missing a Javadoc comment.", "333: Unused Javadoc tag.", }; verify(mCheckConfig, getSrcPath("checks/javadoc/InputTags.java"), expected); } @Test public void testTagsWithResolver() throws Exception { mCheckConfig.addAttribute("allowUndeclaredRTE", "true"); final String[] expected = { "14:5: Missing a Javadoc comment.", "18:9: Unused @param tag for 'unused'.", "24: Expected an @return tag.", "33: Expected an @return tag.", "40:16: Expected @throws tag for 'Exception'.", "49:16: Expected @throws tag for 'Exception'.", "55:16: Expected @throws tag for 'Exception'.", "55:27: Expected @throws tag for 'NullPointerException'.", "60:22: Expected @param tag for 'aOne'.", "68:22: Expected @param tag for 'aOne'.", "72:9: Unused @param tag for 'WrongParam'.", "73:23: Expected @param tag for 'aOne'.", "73:33: Expected @param tag for 'aTwo'.", "78:8: Unused @param tag for 'Unneeded'.", "79: Unused Javadoc tag.", "87:8: Duplicate @return tag.", "109:23: Expected @param tag for 'aOne'.", "109:55: Expected @param tag for 'aFour'.", "109:66: Expected @param tag for 'aFive'.", "236:8: Unused @throws tag for 'java.io.FileNotFoundException'.", "254:8: Unused @throws tag for 'java.io.FileNotFoundException'.", "256:28: Expected @throws tag for 'IOException'.", "262:8: Unused @param tag for 'aParam'.", "320:9: Missing a Javadoc comment.", "329:5: Missing a Javadoc comment.", "333: Unused Javadoc tag.", }; verify(mCheckConfig, getSrcPath("checks/javadoc/InputTags.java"), expected); } @Test public void testStrictJavadoc() throws Exception { final String[] expected = { "12:9: Missing a Javadoc comment.", "18:13: Missing a Javadoc comment.", "25:13: Missing a Javadoc comment.", "38:9: Missing a Javadoc comment.", "49:5: Missing a Javadoc comment.", "54:5: Missing a Javadoc comment.", "59:5: Missing a Javadoc comment.", "64:5: Missing a Javadoc comment.", "69:5: Missing a Javadoc comment.", "74:5: Missing a Javadoc comment.", "79:5: Missing a Javadoc comment.", "84:5: Missing a Javadoc comment.", "94:32: Expected @param tag for 'aA'.", }; verify(mCheckConfig, getPath("InputPublicOnly.java"), expected); } @Test public void testNoJavadoc() throws Exception { mCheckConfig.addAttribute("scope", Scope.NOTHING.getName()); final String[] expected = {}; verify(mCheckConfig, getPath("InputPublicOnly.java"), expected); } // pre 1.4 relaxed mode is roughly equivalent with check=protected @Test public void testRelaxedJavadoc() throws Exception { mCheckConfig.addAttribute("scope", Scope.PROTECTED.getName()); final String[] expected = { "59:5: Missing a Javadoc comment.", "64:5: Missing a Javadoc comment.", "79:5: Missing a Javadoc comment.", "84:5: Missing a Javadoc comment.", }; verify(mCheckConfig, getPath("InputPublicOnly.java"), expected); } @Test public void testScopeInnerInterfacesPublic() throws Exception { mCheckConfig.addAttribute("scope", Scope.PUBLIC.getName()); final String[] expected = { "43:9: Missing a Javadoc comment.", "44:9: Missing a Javadoc comment.", }; verify(mCheckConfig, getPath("InputScopeInnerInterfaces.java"), expected); } @Test public void testScopeAnonInnerPrivate() throws Exception { mCheckConfig.addAttribute("scope", Scope.PRIVATE.getName()); final String[] expected = {}; verify(mCheckConfig, getPath("InputScopeAnonInner.java"), expected); } @Test public void testScopeAnonInnerAnonInner() throws Exception { mCheckConfig.addAttribute("scope", Scope.ANONINNER.getName()); final String[] expected = { "26:9: Missing a Javadoc comment.", "39:17: Missing a Javadoc comment.", "53:17: Missing a Javadoc comment.", }; verify(mCheckConfig, getPath("InputScopeAnonInner.java"), expected); } @Test public void testScopeAnonInnerWithResolver() throws Exception { mCheckConfig.addAttribute("allowUndeclaredRTE", "true"); final String[] expected = {}; verify(mCheckConfig, getPath("InputScopeAnonInner.java"), expected); } @Test public void testTagsWithSubclassesAllowed() throws Exception { mCheckConfig.addAttribute("allowThrowsTagsForSubclasses", "true"); final String[] expected = { "14:5: Missing a Javadoc comment.", "18:9: Unused @param tag for 'unused'.", "24: Expected an @return tag.", "33: Expected an @return tag.", "40:16: Expected @throws tag for 'Exception'.", "49:16: Expected @throws tag for 'Exception'.", "55:16: Expected @throws tag for 'Exception'.", "55:27: Expected @throws tag for 'NullPointerException'.", "60:22: Expected @param tag for 'aOne'.", "68:22: Expected @param tag for 'aOne'.", "72:9: Unused @param tag for 'WrongParam'.", "73:23: Expected @param tag for 'aOne'.", "73:33: Expected @param tag for 'aTwo'.", "78:8: Unused @param tag for 'Unneeded'.", "79: Unused Javadoc tag.", "87:8: Duplicate @return tag.", "109:23: Expected @param tag for 'aOne'.", "109:55: Expected @param tag for 'aFour'.", "109:66: Expected @param tag for 'aFive'.", "178:8: Unused @throws tag for 'ThreadDeath'.", "179:8: Unused @throws tag for 'ArrayStoreException'.", "256:28: Expected @throws tag for 'IOException'.", "262:8: Unused @param tag for 'aParam'.", "320:9: Missing a Javadoc comment.", "329:5: Missing a Javadoc comment.", "333: Unused Javadoc tag.", }; verify(mCheckConfig, getSrcPath("checks/javadoc/InputTags.java"), expected); } @Test public void testScopes() throws Exception { final String[] expected = { "8:5: Missing a Javadoc comment.", "9:5: Missing a Javadoc comment.", "10:5: Missing a Javadoc comment.", "11:5: Missing a Javadoc comment.", "19:9: Missing a Javadoc comment.", "20:9: Missing a Javadoc comment.", "21:9: Missing a Javadoc comment.", "22:9: Missing a Javadoc comment.", "31:9: Missing a Javadoc comment.", "32:9: Missing a Javadoc comment.", "33:9: Missing a Javadoc comment.", "34:9: Missing a Javadoc comment.", "43:9: Missing a Javadoc comment.", "44:9: Missing a Javadoc comment.", "45:9: Missing a Javadoc comment.", "46:9: Missing a Javadoc comment.", "56:5: Missing a Javadoc comment.", "57:5: Missing a Javadoc comment.", "58:5: Missing a Javadoc comment.", "59:5: Missing a Javadoc comment.", "67:9: Missing a Javadoc comment.", "68:9: Missing a Javadoc comment.", "69:9: Missing a Javadoc comment.", "70:9: Missing a Javadoc comment.", "79:9: Missing a Javadoc comment.", "80:9: Missing a Javadoc comment.", "81:9: Missing a Javadoc comment.", "82:9: Missing a Javadoc comment.", "91:9: Missing a Javadoc comment.", "92:9: Missing a Javadoc comment.", "93:9: Missing a Javadoc comment.", "94:9: Missing a Javadoc comment.", "103:9: Missing a Javadoc comment.", "104:9: Missing a Javadoc comment.", "105:9: Missing a Javadoc comment.", "106:9: Missing a Javadoc comment.", }; verify(mCheckConfig, getPath("javadoc" + File.separator + "InputNoJavadoc.java"), expected); } @Test public void testScopes2() throws Exception { mCheckConfig.addAttribute("scope", Scope.PROTECTED.getName()); final String[] expected = { "8:5: Missing a Javadoc comment.", "9:5: Missing a Javadoc comment.", "19:9: Missing a Javadoc comment.", "20:9: Missing a Javadoc comment.", }; verify(mCheckConfig, getPath("javadoc" + File.separator + "InputNoJavadoc.java"), expected); } @Test public void testExcludeScope() throws Exception { mCheckConfig.addAttribute("scope", Scope.PRIVATE.getName()); mCheckConfig.addAttribute("excludeScope", Scope.PROTECTED.getName()); final String[] expected = { "10:5: Missing a Javadoc comment.", "11:5: Missing a Javadoc comment.", "21:9: Missing a Javadoc comment.", "22:9: Missing a Javadoc comment.", "31:9: Missing a Javadoc comment.", "32:9: Missing a Javadoc comment.", "33:9: Missing a Javadoc comment.", "34:9: Missing a Javadoc comment.", "43:9: Missing a Javadoc comment.", "44:9: Missing a Javadoc comment.", "45:9: Missing a Javadoc comment.", "46:9: Missing a Javadoc comment.", "56:5: Missing a Javadoc comment.", "57:5: Missing a Javadoc comment.", "58:5: Missing a Javadoc comment.", "59:5: Missing a Javadoc comment.", "67:9: Missing a Javadoc comment.", "68:9: Missing a Javadoc comment.", "69:9: Missing a Javadoc comment.", "70:9: Missing a Javadoc comment.", "79:9: Missing a Javadoc comment.", "80:9: Missing a Javadoc comment.", "81:9: Missing a Javadoc comment.", "82:9: Missing a Javadoc comment.", "91:9: Missing a Javadoc comment.", "92:9: Missing a Javadoc comment.", "93:9: Missing a Javadoc comment.", "94:9: Missing a Javadoc comment.", "103:9: Missing a Javadoc comment.", "104:9: Missing a Javadoc comment.", "105:9: Missing a Javadoc comment.", "106:9: Missing a Javadoc comment.", }; verify(mCheckConfig, getPath("javadoc" + File.separator + "InputNoJavadoc.java"), expected); } @Test public void testAllowMissingJavadoc() throws Exception { mCheckConfig.addAttribute("allowMissingJavadoc", "true"); final String[] expected = {}; verify(mCheckConfig, getPath("javadoc" + File.separator + "InputNoJavadoc.java"), expected); } @Test public void testSetterGetterOff() throws Exception { final String[] expected = { "5:5: Missing a Javadoc comment.", "10:5: Missing a Javadoc comment.", "15:5: Missing a Javadoc comment.", "20:5: Missing a Javadoc comment.", "26:5: Missing a Javadoc comment.", "30:5: Missing a Javadoc comment.", "35:5: Missing a Javadoc comment.", "41:5: Missing a Javadoc comment.", "46:5: Missing a Javadoc comment.", }; verify(mCheckConfig, getPath("javadoc" + File.separator + "InputSetterGetter.java"), expected); } @Test public void testSetterGetterOn() throws Exception { mCheckConfig.addAttribute("allowMissingPropertyJavadoc", "true"); final String[] expected = { "15:5: Missing a Javadoc comment.", "20:5: Missing a Javadoc comment.", "26:5: Missing a Javadoc comment.", "30:5: Missing a Javadoc comment.", "35:5: Missing a Javadoc comment.", "41:5: Missing a Javadoc comment.", }; verify(mCheckConfig, getPath("javadoc" + File.separator + "InputSetterGetter.java"), expected); } @Test public void testTypeParamsTags() throws Exception { final String[] expected = { "26:8: Unused @param tag for ''.", "28:13: Expected @param tag for ''.", }; verify(mCheckConfig, getPath("InputTypeParamsTags.java"), expected); } @Test public void test_1168408_1() throws Exception { final String[] expected = {}; verify(mCheckConfig, getSrcPath("checks/javadoc/Input_01.java"), expected); } @Test public void test_1168408_2() throws Exception { final String[] expected = {}; verify(mCheckConfig, getSrcPath("checks/javadoc/Input_02.java"), expected); } @Test public void test_1168408_3() throws Exception { mCheckConfig.addAttribute("allowThrowsTagsForSubclasses", "true"); mCheckConfig.addAttribute("allowUndeclaredRTE", "true"); final String[] expected = {}; verify(mCheckConfig, getSrcPath("checks/javadoc/Input_03.java"), expected); } @Test public void test_generics_1() throws Exception { mCheckConfig.addAttribute("allowThrowsTagsForSubclasses", "true"); mCheckConfig.addAttribute("allowUndeclaredRTE", "true"); final String[] expected = { "15:34: Expected @throws tag for 'RE'.", "31:13: Expected @param tag for ''.", "38:12: Unused @throws tag for 'E'.", "41:38: Expected @throws tag for 'RuntimeException'.", "42:13: Expected @throws tag for 'java.lang.RuntimeException'.", }; verify(mCheckConfig, getPath("javadoc/TestGenerics.java"), expected); } @Test public void test_generics_2() throws Exception { mCheckConfig.addAttribute("allowThrowsTagsForSubclasses", "true"); final String[] expected = { "15:34: Expected @throws tag for 'RE'.", "31:13: Expected @param tag for ''.", "38:12: Unused @throws tag for 'E'.", "41:38: Expected @throws tag for 'RuntimeException'.", "42:13: Expected @throws tag for 'java.lang.RuntimeException'.", }; verify(mCheckConfig, getPath("javadoc/TestGenerics.java"), expected); } @Test public void test_generics_3() throws Exception { final String[] expected = { "6:8: Unused @throws tag for 'RE'.", "15:34: Expected @throws tag for 'RE'.", "31:13: Expected @param tag for ''.", "38:12: Unused @throws tag for 'E'.", "41:38: Expected @throws tag for 'RuntimeException'.", "42:13: Expected @throws tag for 'java.lang.RuntimeException'.", }; verify(mCheckConfig, getPath("javadoc/TestGenerics.java"), expected); } @Test public void test_1379666() throws Exception { mCheckConfig.addAttribute("allowThrowsTagsForSubclasses", "true"); mCheckConfig.addAttribute("allowUndeclaredRTE", "true"); final String[] expected = {}; verify(mCheckConfig, getSrcPath("checks/javadoc/Input_1379666.java"), expected); } @Test public void testInheritDoc() throws Exception { final String[] expected = { "4:5: Invalid use of the {@inheritDoc} tag.", "9:5: Invalid use of the {@inheritDoc} tag.", "29:5: Invalid use of the {@inheritDoc} tag.", "34:5: Invalid use of the {@inheritDoc} tag.", "39:5: Invalid use of the {@inheritDoc} tag.", "44:5: Invalid use of the {@inheritDoc} tag.", }; verify(mCheckConfig, getPath("javadoc/InputInheritDoc.java"), expected); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheckTest.java100644 0 0 7343 12026050750 31223 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.Configuration; import org.junit.Test; public class JavadocPackageCheckTest extends BaseCheckTestSupport { @Override protected DefaultConfiguration createCheckerConfig( Configuration aCheckConfig) { final DefaultConfiguration dc = new DefaultConfiguration("root"); dc.addChild(aCheckConfig); return dc; } @Test public void testMissing() throws Exception { final Configuration checkConfig = createCheckConfig(JavadocPackageCheck.class); final String[] expected = { "0: Missing package-info.java file.", }; verify( createChecker(checkConfig), getSrcPath("checks/javadoc/BadCls.java"), getSrcPath("checks/javadoc/BadCls.java"), expected); } @Test public void testBoth() throws Exception { final Configuration checkConfig = createCheckConfig(JavadocPackageCheck.class); final String[] expected = { "0: Legacy package.html file should be removed.", }; verify(createChecker(checkConfig), getPath("javadoc/bothfiles/Ignored.java"), getPath("javadoc/bothfiles/Ignored.java"), expected); } @Test public void testHtmlDisallowed() throws Exception { final Configuration checkConfig = createCheckConfig(JavadocPackageCheck.class); final String[] expected = { "0: Missing package-info.java file.", }; verify(createChecker(checkConfig), getPath("javadoc/pkghtml/Ignored.java"), getPath("javadoc/pkghtml/Ignored.java"), expected); } @Test public void testHtmlAllowed() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocPackageCheck.class); checkConfig.addAttribute("allowLegacy", "true"); final String[] expected = {}; verify(createChecker(checkConfig), getPath("javadoc/pkghtml/Ignored.java"), getPath("javadoc/pkghtml/package-info.java"), expected); } @Test public void testAnnotation() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocPackageCheck.class); final String[] expected = {}; verify(createChecker(checkConfig), getPath("javadoc/pkginfo/annotation/package-info.java"), getPath("javadoc/pkginfo/annotation/package-info.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheckTest.java100644 0 0 33121 12026050750 31001 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import java.io.File; import org.junit.Test; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class JavadocStyleCheckTest extends BaseCheckTestSupport { @Test public void testDefaultSettings() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); final String[] expected = { "20: First sentence should end with a period.", "53: First sentence should end with a period.", "63:11: Unclosed HTML tag found: This guy is missing end of bold tag", "66:7: Extra HTML tag found: Extra tag shouldn't be here", "68:19: Unclosed HTML tag found: dummy.", "74: First sentence should end with a period.", "75:23: Unclosed HTML tag found: should fail", "81: First sentence should end with a period.", "82:31: Unclosed HTML tag found: should fail", "88: First sentence should end with a period.", "89:31: Extra HTML tag found: ", "90: Incomplete HTML tag found: * should fail <", "109:39: Extra HTML tag found: ", "186:8: Unclosed HTML tag found:
", "193: First sentence should end with a period.", "238: First sentence should end with a period.", "335:33: Extra HTML tag found: ", }; verify(checkConfig, getPath("InputJavadocStyleCheck.java"), expected); } @Test public void testFirstSentence() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); checkConfig.addAttribute("checkFirstSentence", "true"); checkConfig.addAttribute("checkHtml", "false"); final String[] expected = { "20: First sentence should end with a period.", "53: First sentence should end with a period.", "74: First sentence should end with a period.", "81: First sentence should end with a period.", "88: First sentence should end with a period.", "193: First sentence should end with a period.", "238: First sentence should end with a period.", }; verify(checkConfig, getPath("InputJavadocStyleCheck.java"), expected); } @Test public void testFirstSentenceFormat() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); checkConfig.addAttribute("checkFirstSentence", "true"); checkConfig.addAttribute("checkHtml", "false"); checkConfig.addAttribute("endOfSentenceFormat", "([.][ \t\n\r\f<])|([.]$)"); final String[] expected = { "20: First sentence should end with a period.", "32: First sentence should end with a period.", "39: First sentence should end with a period.", "53: First sentence should end with a period.", "74: First sentence should end with a period.", "81: First sentence should end with a period.", "88: First sentence should end with a period.", "193: First sentence should end with a period.", "238: First sentence should end with a period.", }; verify(checkConfig, getPath("InputJavadocStyleCheck.java"), expected); } @Test public void testHtml() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); checkConfig.addAttribute("checkFirstSentence", "false"); checkConfig.addAttribute("checkHtml", "true"); final String[] expected = { "63:11: Unclosed HTML tag found: This guy is missing end of bold tag", "66:7: Extra HTML tag found: Extra tag shouldn't be here", "68:19: Unclosed HTML tag found: dummy.", "75:23: Unclosed HTML tag found: should fail", "82:31: Unclosed HTML tag found: should fail", "89:31: Extra HTML tag found: ", "90: Incomplete HTML tag found: * should fail <", "109:39: Extra HTML tag found: ", "186:8: Unclosed HTML tag found:
", "335:33: Extra HTML tag found: ", }; verify(checkConfig, getPath("InputJavadocStyleCheck.java"), expected); } @Test public void testScopePublic() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); checkConfig.addAttribute("checkFirstSentence", "true"); checkConfig.addAttribute("checkHtml", "true"); checkConfig.addAttribute("checkEmptyJavadoc", "true"); checkConfig.addAttribute("scope", "public"); final String[] expected = { "88: First sentence should end with a period.", "89:31: Extra HTML tag found: ", "90: Incomplete HTML tag found: * should fail <", "205: Javadoc has empty description section.", "230: Javadoc has empty description section.", "238: First sentence should end with a period.", "335:33: Extra HTML tag found: ", }; verify(checkConfig, getPath("InputJavadocStyleCheck.java"), expected); } @Test public void testScopeProtected() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); checkConfig.addAttribute("checkFirstSentence", "true"); checkConfig.addAttribute("checkHtml", "true"); checkConfig.addAttribute("checkEmptyJavadoc", "true"); checkConfig.addAttribute("scope", "protected"); final String[] expected = { "74: First sentence should end with a period.", "75:23: Unclosed HTML tag found: should fail", "88: First sentence should end with a period.", "89:31: Extra HTML tag found: ", "90: Incomplete HTML tag found: * should fail <", "205: Javadoc has empty description section.", "211: Javadoc has empty description section.", "230: Javadoc has empty description section.", "238: First sentence should end with a period.", "335:33: Extra HTML tag found: ", }; verify(checkConfig, getPath("InputJavadocStyleCheck.java"), expected); } @Test public void testScopePackage() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); checkConfig.addAttribute("checkFirstSentence", "true"); checkConfig.addAttribute("checkHtml", "true"); checkConfig.addAttribute("checkEmptyJavadoc", "true"); checkConfig.addAttribute("scope", "package"); final String[] expected = { "74: First sentence should end with a period.", "75:23: Unclosed HTML tag found: should fail", "81: First sentence should end with a period.", "82:31: Unclosed HTML tag found: should fail", "88: First sentence should end with a period.", "89:31: Extra HTML tag found: ", "90: Incomplete HTML tag found: * should fail <", "205: Javadoc has empty description section.", "211: Javadoc has empty description section.", "218: Javadoc has empty description section.", "230: Javadoc has empty description section.", "238: First sentence should end with a period.", "335:33: Extra HTML tag found: ", }; verify(checkConfig, getPath("InputJavadocStyleCheck.java"), expected); } @Test public void testEmptyJavadoc() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); checkConfig.addAttribute("checkFirstSentence", "false"); checkConfig.addAttribute("checkHtml", "false"); checkConfig.addAttribute("checkEmptyJavadoc", "true"); final String[] expected = { "205: Javadoc has empty description section.", "211: Javadoc has empty description section.", "218: Javadoc has empty description section.", "225: Javadoc has empty description section.", "230: Javadoc has empty description section.", }; verify(checkConfig, getPath("InputJavadocStyleCheck.java"), expected); } @Test public void testExcludeScope() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); checkConfig.addAttribute("scope", "private"); checkConfig.addAttribute("excludeScope", "protected"); final String[] expected = { "20: First sentence should end with a period.", "53: First sentence should end with a period.", "63:11: Unclosed HTML tag found: This guy is missing end of bold tag", "66:7: Extra HTML tag found: Extra tag shouldn't be here", "68:19: Unclosed HTML tag found: dummy.", "81: First sentence should end with a period.", "82:31: Unclosed HTML tag found: should fail", "109:39: Extra HTML tag found: ", "186:8: Unclosed HTML tag found:
", "193: First sentence should end with a period.", }; verify(checkConfig, getPath("InputJavadocStyleCheck.java"), expected); } @Test public void packageInfoInheritDoc() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); final String[] expected = { "1: First sentence should end with a period.", }; String basePath = "javadoc" + File.separator + "pkginfo" + File.separator + "invalidinherit" + File.separator; verify(createChecker(checkConfig), getPath(basePath + "package-info.java"), expected); } @Test public void packageInfoInvalid() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); final String[] expected = { "1: First sentence should end with a period.", }; String basePath = "javadoc" + File.separator + "pkginfo" + File.separator + "invalidformat" + File.separator; verify(createChecker(checkConfig), getPath(basePath + "package-info.java"), expected); } @Test public void packageInfoAnnotation() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); final String[] expected = { }; String basePath = "javadoc" + File.separator + "pkginfo" + File.separator + "annotation" + File.separator; verify(createChecker(checkConfig), getPath(basePath + "package-info.java"), expected); } @Test public void packageInfoMissing() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); final String[] expected = { "1: Missing a Javadoc comment.", }; String basePath = "javadoc" + File.separator + "bothfiles" + File.separator; verify(createChecker(checkConfig), getPath(basePath + "package-info.java"), expected); } @Test public void packageInfoValid() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocStyleCheck.class); final String[] expected = {}; String basePath = "javadoc" + File.separator + "pkginfo" + File.separator + "valid" + File.separator; verify(createChecker(checkConfig), getPath(basePath + "package-info.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheckTest.java100644 0 0 33135 12026050750 30627 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.Scope; import java.io.File; import org.junit.Test; /** * @author Oliver.Burn * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class JavadocTypeCheckTest extends BaseCheckTestSupport { @Test public void testTags() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); final String[] expected = { "8: Missing a Javadoc comment.", "302: Missing a Javadoc comment.", "327: Missing a Javadoc comment.", }; verify(checkConfig, getSrcPath("checks/javadoc/InputTags.java"), expected); } @Test public void testInner() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); final String[] expected = { "14: Missing a Javadoc comment.", "21: Missing a Javadoc comment.", "27: Missing a Javadoc comment.", }; verify(checkConfig, getPath("InputInner.java"), expected); } @Test public void testStrict() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); final String[] expected = { "7: Missing a Javadoc comment.", "9: Missing a Javadoc comment.", "14: Missing a Javadoc comment.", "34: Missing a Javadoc comment.", }; verify(checkConfig, getPath("InputPublicOnly.java"), expected); } @Test public void testProtected() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("scope", Scope.PROTECTED.getName()); final String[] expected = { "7: Missing a Javadoc comment.", }; verify(checkConfig, getPath("InputPublicOnly.java"), expected); } @Test public void testPublic() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("scope", Scope.PUBLIC.getName()); final String[] expected = { "7: Missing a Javadoc comment.", "38: Missing a Javadoc comment.", }; verify(checkConfig, getPath("InputScopeInnerInterfaces.java"), expected); } @Test public void testProtest() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("scope", Scope.PROTECTED.getName()); final String[] expected = { "7: Missing a Javadoc comment.", "29: Missing a Javadoc comment.", "38: Missing a Javadoc comment.", "65: Missing a Javadoc comment.", }; verify(checkConfig, getPath("InputScopeInnerInterfaces.java"), expected); } @Test public void testPkg() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute( "scope", Scope.getInstance("package").getName()); final String[] expected = { "18: Missing a Javadoc comment.", "20: Missing a Javadoc comment.", "22: Missing a Javadoc comment.", }; verify(checkConfig, getPath("InputScopeInnerClasses.java"), expected); } @Test public void testEclipse() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute( "scope", Scope.getInstance("public").getName()); final String[] expected = { "18: Missing a Javadoc comment.", }; verify(checkConfig, getPath("InputScopeInnerClasses.java"), expected); } @Test public void testAuthorRequired() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("authorFormat", "\\S"); final String[] expected = { "13: Type Javadoc comment is missing an @author tag.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } @Test public void testAuthorRegularEx() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("authorFormat", "0*"); final String[] expected = { "22: Type Javadoc comment is missing an @author tag.", "58: Type Javadoc comment is missing an @author tag.", "94: Type Javadoc comment is missing an @author tag.", }; verify(checkConfig, getPath("InputJavadoc.java"), expected); } @Test public void testAuthorRegularExError() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("authorFormat", "ABC"); final String[] expected = { "13: Type Javadoc tag @author must match pattern 'ABC'.", "22: Type Javadoc comment is missing an @author tag.", "31: Type Javadoc tag @author must match pattern 'ABC'.", "49: Type Javadoc tag @author must match pattern 'ABC'.", "58: Type Javadoc comment is missing an @author tag.", "67: Type Javadoc tag @author must match pattern 'ABC'.", "85: Type Javadoc tag @author must match pattern 'ABC'.", "94: Type Javadoc comment is missing an @author tag.", "103: Type Javadoc tag @author must match pattern 'ABC'.", }; verify(checkConfig, getPath("InputJavadoc.java"), expected); } @Test public void testVersionRequired() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("versionFormat", "\\S"); final String[] expected = { "13: Type Javadoc comment is missing an @version tag.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } @Test public void testVersionRegularEx() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("versionFormat", "^\\p{Digit}+\\.\\p{Digit}+$"); final String[] expected = { "22: Type Javadoc comment is missing an @version tag.", "58: Type Javadoc comment is missing an @version tag.", "94: Type Javadoc comment is missing an @version tag.", }; verify(checkConfig, getPath("InputJavadoc.java"), expected); } @Test public void testVersionRegularExError() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("versionFormat", "\\$Revision.*\\$"); final String[] expected = { "13: Type Javadoc tag @version must match pattern '\\$Revision.*\\$'.", "22: Type Javadoc comment is missing an @version tag.", "31: Type Javadoc tag @version must match pattern '\\$Revision.*\\$'.", "40: Type Javadoc tag @version must match pattern '\\$Revision.*\\$'.", "49: Type Javadoc tag @version must match pattern '\\$Revision.*\\$'.", "58: Type Javadoc comment is missing an @version tag.", "67: Type Javadoc tag @version must match pattern '\\$Revision.*\\$'.", "76: Type Javadoc tag @version must match pattern '\\$Revision.*\\$'.", "85: Type Javadoc tag @version must match pattern '\\$Revision.*\\$'.", "94: Type Javadoc comment is missing an @version tag.", "103: Type Javadoc tag @version must match pattern '\\$Revision.*\\$'.", "112: Type Javadoc tag @version must match pattern '\\$Revision.*\\$'.", }; verify(checkConfig, getPath("InputJavadoc.java"), expected); } @Test public void testScopes() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); final String[] expected = { "1: Missing a Javadoc comment.", "13: Missing a Javadoc comment.", "25: Missing a Javadoc comment.", "37: Missing a Javadoc comment.", "50: Missing a Javadoc comment.", "61: Missing a Javadoc comment.", "73: Missing a Javadoc comment.", "85: Missing a Javadoc comment.", "97: Missing a Javadoc comment.", }; verify(checkConfig, getPath("javadoc" + File.separator + "InputNoJavadoc.java"), expected); } @Test public void testScopes2() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("scope", Scope.PROTECTED.getName()); final String[] expected = { "1: Missing a Javadoc comment.", "13: Missing a Javadoc comment.", }; verify(checkConfig, getPath("javadoc" + File.separator + "InputNoJavadoc.java"), expected); } @Test public void testExcludeScope() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("scope", Scope.PRIVATE.getName()); checkConfig.addAttribute("excludeScope", Scope.PROTECTED.getName()); final String[] expected = { "25: Missing a Javadoc comment.", "37: Missing a Javadoc comment.", "50: Missing a Javadoc comment.", "61: Missing a Javadoc comment.", "73: Missing a Javadoc comment.", "85: Missing a Javadoc comment.", "97: Missing a Javadoc comment.", }; verify(checkConfig, getPath("javadoc" + File.separator + "InputNoJavadoc.java"), expected); } @Test public void testTypeParameters() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); final String[] expected = { "7:4: Unused @param tag for ''.", "11: Type Javadoc comment is missing an @param tag.", }; verify(checkConfig, getPath("InputTypeParamsTags.java"), expected); } @Test public void testAllowMissingTypeParameters() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("allowMissingParamTags", "true"); final String[] expected = { "7:4: Unused @param tag for ''.", }; verify(checkConfig, getPath("InputTypeParamsTags.java"), expected); } @Test public void testBadTag() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); final String[] expected = { "3:4: Unknown tag 'mytag'.", }; verify(checkConfig, getPath("javadoc" + File.separator + "InputBadTag.java"), expected); } @Test public void testBadTagSuppress() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocTypeCheck.class); checkConfig.addAttribute("allowUnknownTags", "true"); final String[] expected = { }; verify(checkConfig, getPath("javadoc" + File.separator + "InputBadTag.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocUtilsTest.java100644 0 0 11536 12026050747 30057 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.puppycrawl.tools.checkstyle.api.Comment; import com.puppycrawl.tools.checkstyle.api.JavadocTagInfo; import java.util.List; import org.junit.Test; public class JavadocUtilsTest { @Test public void testTags() { final String [] text = { "/** @see elsewhere ", " * {@link List }, {@link List link text }", " {@link List#add(Object) link text}", " * {@link Class link text}", }; final Comment comment = new Comment(text, 1, 4, text[3].length()); final JavadocTags allTags = JavadocUtils.getJavadocTags(comment, JavadocUtils.JavadocTagType.ALL); assertEquals(5, allTags.getValidTags().size()); } @Test public void testTagType() { final String [] text = { "/** @see block", " * {@link List inline}, {@link List#add(Object)}", }; final Comment comment = new Comment(text, 1, 2, text[1].length()); final JavadocTags blockTags = JavadocUtils.getJavadocTags(comment, JavadocUtils.JavadocTagType.BLOCK); final JavadocTags inlineTags = JavadocUtils.getJavadocTags(comment, JavadocUtils.JavadocTagType.INLINE); assertEquals(1, blockTags.getValidTags().size()); assertEquals(2, inlineTags.getValidTags().size()); } @Test public void testInlineTagLinkText() { final String [] text = { "/** {@link List link text }", }; final Comment comment = new Comment(text, 1, 1, text[0].length()); final List tags = JavadocUtils.getJavadocTags( comment, JavadocUtils.JavadocTagType.ALL).getValidTags(); assertEquals("List link text", tags.get(0).getArg1()); } @Test public void testInlineTagMethodRef() { final String [] text = { "/** {@link List#add(Object)}", }; final Comment comment = new Comment(text, 1, 1, text[0].length()); final List tags = JavadocUtils.getJavadocTags( comment, JavadocUtils.JavadocTagType.ALL).getValidTags(); assertEquals("List#add(Object)", tags.get(0).getArg1()); } @Test public void testTagPositions() { final String [] text = { "/** @see elsewhere", " also {@link Name value} */", }; final Comment comment = new Comment(text, 1, 2, text[1].length()); final List tags = JavadocUtils.getJavadocTags( comment, JavadocUtils.JavadocTagType.ALL).getValidTags(); assertEquals(2, tags.size()); for (final JavadocTag tag : tags) { if (JavadocTagInfo.SEE.getName().equals(tag.getTagName())) { assertEquals(1, tag.getLineNo()); assertEquals(5, tag.getColumnNo()); } else if (JavadocTagInfo.LINK.getName().equals(tag.getTagName())) { assertEquals(2, tag.getLineNo()); assertEquals(10, tag.getColumnNo()); } else { fail("Unexpected tag: " + tag); } } } @Test public void testInvalidTags() { final String [] text = { "/** @fake block", " * {@bogus inline}", " * {@link List valid}", }; final Comment comment = new Comment(text, 1, 3, text[2].length()); final JavadocTags allTags = JavadocUtils.getJavadocTags(comment, JavadocUtils.JavadocTagType.ALL); assertEquals(2, allTags.getInvalidTags().size()); assertEquals(1, allTags.getValidTags().size()); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocVariableCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocVariableCheckTest.jav100644 0 0 20770 12026050747 31301 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.Scope; import java.io.File; import org.junit.Test; public class JavadocVariableCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocVariableCheck.class); final String[] expected = { "11:5: Missing a Javadoc comment.", "304:5: Missing a Javadoc comment.", "311:5: Missing a Javadoc comment.", "330:5: Missing a Javadoc comment.", }; verify(checkConfig, getSrcPath("checks/javadoc/InputTags.java"), expected); } @Test public void testAnother() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocVariableCheck.class); final String[] expected = { "17:9: Missing a Javadoc comment.", "24:9: Missing a Javadoc comment.", "30:13: Missing a Javadoc comment.", }; verify(checkConfig, getPath("InputInner.java"), expected); } @Test public void testAnother2() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocVariableCheck.class); checkConfig.addAttribute("scope", Scope.PUBLIC.getName()); final String[] expected = { }; verify(checkConfig, getPath("InputInner.java"), expected); } @Test public void testAnother3() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocVariableCheck.class); final String[] expected = { "11:9: Missing a Javadoc comment.", "16:13: Missing a Javadoc comment.", "36:9: Missing a Javadoc comment.", "43:5: Missing a Javadoc comment.", "44:5: Missing a Javadoc comment.", "45:5: Missing a Javadoc comment.", "46:5: Missing a Javadoc comment.", }; verify(checkConfig, getPath("InputPublicOnly.java"), expected); } @Test public void testAnother4() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocVariableCheck.class); checkConfig.addAttribute("scope", Scope.PUBLIC.getName()); final String[] expected = { "46:5: Missing a Javadoc comment.", }; verify(checkConfig, getPath("InputPublicOnly.java"), expected); } @Test public void testScopes() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocVariableCheck.class); final String[] expected = { "3:5: Missing a Javadoc comment.", "4:5: Missing a Javadoc comment.", "5:5: Missing a Javadoc comment.", "6:5: Missing a Javadoc comment.", "14:9: Missing a Javadoc comment.", "15:9: Missing a Javadoc comment.", "16:9: Missing a Javadoc comment.", "17:9: Missing a Javadoc comment.", "26:9: Missing a Javadoc comment.", "27:9: Missing a Javadoc comment.", "28:9: Missing a Javadoc comment.", "29:9: Missing a Javadoc comment.", "38:9: Missing a Javadoc comment.", "39:9: Missing a Javadoc comment.", "40:9: Missing a Javadoc comment.", "41:9: Missing a Javadoc comment.", "51:5: Missing a Javadoc comment.", "52:5: Missing a Javadoc comment.", "53:5: Missing a Javadoc comment.", "54:5: Missing a Javadoc comment.", "62:9: Missing a Javadoc comment.", "63:9: Missing a Javadoc comment.", "64:9: Missing a Javadoc comment.", "65:9: Missing a Javadoc comment.", "74:9: Missing a Javadoc comment.", "75:9: Missing a Javadoc comment.", "76:9: Missing a Javadoc comment.", "77:9: Missing a Javadoc comment.", "86:9: Missing a Javadoc comment.", "87:9: Missing a Javadoc comment.", "88:9: Missing a Javadoc comment.", "89:9: Missing a Javadoc comment.", "98:9: Missing a Javadoc comment.", "99:9: Missing a Javadoc comment.", "100:9: Missing a Javadoc comment.", "101:9: Missing a Javadoc comment.", }; verify(checkConfig, getPath("javadoc" + File.separator + "InputNoJavadoc.java"), expected); } @Test public void testScopes2() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocVariableCheck.class); checkConfig.addAttribute("scope", Scope.PROTECTED.getName()); final String[] expected = { "3:5: Missing a Javadoc comment.", "4:5: Missing a Javadoc comment.", "14:9: Missing a Javadoc comment.", "15:9: Missing a Javadoc comment.", }; verify(checkConfig, getPath("javadoc" + File.separator + "InputNoJavadoc.java"), expected); } @Test public void testExcludeScope() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(JavadocVariableCheck.class); checkConfig.addAttribute("scope", Scope.PRIVATE.getName()); checkConfig.addAttribute("excludeScope", Scope.PROTECTED.getName()); final String[] expected = { "5:5: Missing a Javadoc comment.", "6:5: Missing a Javadoc comment.", "16:9: Missing a Javadoc comment.", "17:9: Missing a Javadoc comment.", "26:9: Missing a Javadoc comment.", "27:9: Missing a Javadoc comment.", "28:9: Missing a Javadoc comment.", "29:9: Missing a Javadoc comment.", "38:9: Missing a Javadoc comment.", "39:9: Missing a Javadoc comment.", "40:9: Missing a Javadoc comment.", "41:9: Missing a Javadoc comment.", "51:5: Missing a Javadoc comment.", "52:5: Missing a Javadoc comment.", "53:5: Missing a Javadoc comment.", "54:5: Missing a Javadoc comment.", "62:9: Missing a Javadoc comment.", "63:9: Missing a Javadoc comment.", "64:9: Missing a Javadoc comment.", "65:9: Missing a Javadoc comment.", "74:9: Missing a Javadoc comment.", "75:9: Missing a Javadoc comment.", "76:9: Missing a Javadoc comment.", "77:9: Missing a Javadoc comment.", "86:9: Missing a Javadoc comment.", "87:9: Missing a Javadoc comment.", "88:9: Missing a Javadoc comment.", "89:9: Missing a Javadoc comment.", "98:9: Missing a Javadoc comment.", "99:9: Missing a Javadoc comment.", "100:9: Missing a Javadoc comment.", "101:9: Missing a Javadoc comment.", }; verify(checkConfig, getPath("javadoc" + File.separator + "InputNoJavadoc.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/javadoc/WriteTagCheckTest.java100644 0 0 20144 12026050747 30146 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.javadoc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.Checker; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; /** * @author Daniel Grenner */ public class WriteTagCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(WriteTagCheck.class); } @Test public void testDefaultSettings() throws Exception { final String[] expected = { }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testTag() throws Exception { mCheckConfig.addAttribute("tag", "@author"); mCheckConfig.addAttribute("tagFormat", "\\S"); final String[] expected = { "10: @author=Daniel Grenner", }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testMissingFormat() throws Exception { mCheckConfig.addAttribute("tag", "@author"); final String[] expected = { "10: @author=Daniel Grenner", }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testTagSeverity() throws Exception { mCheckConfig.addAttribute("tag", "@incomplete"); mCheckConfig.addAttribute("tagFormat", "\\S"); mCheckConfig.addAttribute("tagSeverity", "warning"); final String[] expected = { "11: warning: @incomplete=This class needs more code...", }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testDoubleTag() throws Exception { mCheckConfig.addAttribute("tag", "@doubletag"); mCheckConfig.addAttribute("tagFormat", "\\S"); final String[] expected = { "12: @doubletag=first text", "13: @doubletag=second text", }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testEmptyTag() throws Exception { mCheckConfig.addAttribute("tag", "@emptytag"); mCheckConfig.addAttribute("tagFormat", ""); final String[] expected = { "14: @emptytag=", }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testMissingTag() throws Exception { mCheckConfig.addAttribute("tag", "@missingtag"); final String[] expected = { "16: Type Javadoc comment is missing an @missingtag tag.", }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testMethod() throws Exception { mCheckConfig.addAttribute("tag", "@todo"); mCheckConfig.addAttribute("tagFormat", "\\S"); mCheckConfig.addAttribute("tokens", "INTERFACE_DEF, CLASS_DEF, METHOD_DEF, CTOR_DEF"); mCheckConfig.addAttribute("severity", "ignore"); final String[] expected = { "19: @todo=Add a constructor comment", "30: @todo=Add a comment", }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testSeverity() throws Exception { mCheckConfig.addAttribute("tag", "@author"); mCheckConfig.addAttribute("tagFormat", "\\S"); mCheckConfig.addAttribute("severity", "ignore"); final String[] expected = { "10: @author=Daniel Grenner", }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testIgnoreMissing() throws Exception { mCheckConfig.addAttribute("tag", "@todo2"); mCheckConfig.addAttribute("tagFormat", "\\S"); mCheckConfig.addAttribute("severity", "ignore"); final String[] expected = { }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testRegularEx() throws Exception { mCheckConfig.addAttribute("tag", "@author"); mCheckConfig.addAttribute("tagFormat", "0*"); final String[] expected = { }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testRegularExError() throws Exception { mCheckConfig.addAttribute("tag", "@author"); mCheckConfig.addAttribute("tagFormat", "ABC"); final String[] expected = { "10: Type Javadoc tag @author must match pattern 'ABC'.", }; verify(mCheckConfig, getPath("InputWriteTag.java"), expected); } @Test public void testEnumsAndAnnotations() throws Exception { mCheckConfig.addAttribute("tag", "@incomplete"); mCheckConfig.addAttribute("tagFormat", ".*"); mCheckConfig.addAttribute("severity", "ignore"); mCheckConfig.addAttribute("tagSeverity", "error"); mCheckConfig.addAttribute("tokens", "ANNOTATION_DEF, ENUM_DEF, ANNOTATION_FIELD_DEF, ENUM_CONSTANT_DEF"); final String[] expected = { "9: @incomplete=This enum needs more code...", "13: @incomplete=This enum constant needs more code...", "19: @incomplete=This annotation needs more code...", "23: @incomplete=This annotation field needs more code...", }; verify(mCheckConfig, getPath("InputWriteTag2.java"), expected); } @Override protected void verify(Checker aC, File[] aProcessedFiles, String aMessageFileName, String[] aExpected) throws Exception { mStream.flush(); final List theFiles = Lists.newArrayList(); Collections.addAll(theFiles, aProcessedFiles); final int errs = aC.process(theFiles); // process each of the lines final ByteArrayInputStream bais = new ByteArrayInputStream(mBAOS.toByteArray()); final LineNumberReader lnr = new LineNumberReader(new InputStreamReader(bais)); for (int i = 0; i < aExpected.length; i++) { final String expected = aMessageFileName + ":" + aExpected[i]; final String actual = lnr.readLine(); assertEquals("error message " + i, expected, actual); } assertTrue("unexpected output: " + lnr.readLine(), aExpected.length >= errs); aC.destroy(); } } ././@LongLink100644 0 0 162 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityC100644 0 0 4440 12026050746 31541 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class BooleanExpressionComplexityCheckTest extends BaseCheckTestSupport { @Test public void test() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(BooleanExpressionComplexityCheck.class); String[] expected = { "13:9: Boolean expression complexity is 4 (max allowed is 3).", "32:9: Boolean expression complexity is 6 (max allowed is 3).", }; verify(checkConfig, getPath("metrics" + File.separator + "BooleanExpressionComplexityCheckTestInput.java"), expected); } @Test public void testNoBitwise() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(BooleanExpressionComplexityCheck.class); checkConfig.addAttribute("max", "5"); checkConfig.addAttribute("tokens", "BXOR,LAND,LOR"); String[] expected = { }; verify(checkConfig, getPath("metrics" + File.separator + "BooleanExpressionComplexityCheckTestInput.java"), expected); } } ././@LongLink100644 0 0 163 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCoupling100644 0 0 4102 12026050746 31446 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class ClassDataAbstractionCouplingCheckTest extends BaseCheckTestSupport { @Test public void test() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(ClassDataAbstractionCouplingCheck.class); checkConfig.addAttribute("max", "0"); String[] expected = { "6:1: Class Data Abstraction Coupling is 4 (max allowed is 0) classes [AnotherInnerClass, HashMap, HashSet, InnerClass].", "7:5: Class Data Abstraction Coupling is 1 (max allowed is 0) classes [ArrayList].", "27:1: Class Data Abstraction Coupling is 2 (max allowed is 0) classes [HashMap, HashSet].", }; verify(checkConfig, getPath("metrics" + File.separator + "ClassCouplingCheckTestInput.java"), expected); } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheckTe100644 0 0 4373 12026050746 31415 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class ClassFanOutComplexityCheckTest extends BaseCheckTestSupport { @Test public void test() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(ClassFanOutComplexityCheck.class); checkConfig.addAttribute("max", "0"); String[] expected = { "6:1: Class Fan-Out Complexity is 7 (max allowed is 0).", "7:5: Class Fan-Out Complexity is 2 (max allowed is 0).", "27:1: Class Fan-Out Complexity is 4 (max allowed is 0).", }; verify(checkConfig, getPath("metrics" + File.separator + "ClassCouplingCheckTestInput.java"), expected); } @Test public void test15() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(ClassFanOutComplexityCheck.class); checkConfig.addAttribute("max", "0"); String[] expected = { }; verify(checkConfig, getPath("Input15Extensions.java"), expected); } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/CyclomaticComplexityCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/CyclomaticComplexityCheckTes100644 0 0 4513 12026050746 31501 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class CyclomaticComplexityCheckTest extends BaseCheckTestSupport { @Test public void test() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(CyclomaticComplexityCheck.class); checkConfig.addAttribute("max", "0"); final String[] expected = { "4:5: Cyclomatic Complexity is 2 (max allowed is 0).", "7:17: Cyclomatic Complexity is 2 (max allowed is 0).", "17:5: Cyclomatic Complexity is 6 (max allowed is 0).", "27:5: Cyclomatic Complexity is 3 (max allowed is 0).", "34:5: Cyclomatic Complexity is 5 (max allowed is 0).", "48:5: Cyclomatic Complexity is 3 (max allowed is 0).", "58:5: Cyclomatic Complexity is 3 (max allowed is 0).", "67:5: Cyclomatic Complexity is 3 (max allowed is 0).", "76:5: Cyclomatic Complexity is 1 (max allowed is 0).", "79:13: Cyclomatic Complexity is 2 (max allowed is 0).", }; verify(checkConfig, getPath("ComplexityCheckTestInput.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/JavaNCSSCheckTest.java100644 0 0 4723 12026050745 30012 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; /** * Testcase for the JavaNCSS-Check. * * @author Lars Ködderitzsch */ public class JavaNCSSCheckTest extends BaseCheckTestSupport { @Test public void test() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(JavaNCSSCheck.class); checkConfig.addAttribute("methodMaximum", "0"); checkConfig.addAttribute("classMaximum", "1"); checkConfig.addAttribute("fileMaximum", "2"); String[] expected = { "2:1: NCSS for this file is 35 (max allowed is 2).", "9:1: NCSS for this class is 22 (max allowed is 1).", "14:5: NCSS for this method is 2 (max allowed is 0).", "21:5: NCSS for this method is 4 (max allowed is 0).", "30:5: NCSS for this method is 12 (max allowed is 0).", "42:13: NCSS for this method is 2 (max allowed is 0).", "49:5: NCSS for this class is 2 (max allowed is 1).", "56:1: NCSS for this class is 10 (max allowed is 1).", "61:5: NCSS for this method is 8 (max allowed is 0).", }; verify(checkConfig, getPath("metrics" + File.separator + "JavaNCSSCheckTestInput.java"), expected); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheckTest.jav100644 0 0 5724 12026050745 31373 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.metrics; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.text.NumberFormat; import org.junit.Test; public class NPathComplexityCheckTest extends BaseCheckTestSupport { @Test public void testCalculation() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(NPathComplexityCheck.class); checkConfig.addAttribute("max", "0"); String[] expected = { "4:5: NPath Complexity is 2 (max allowed is 0).", "7:17: NPath Complexity is 2 (max allowed is 0).", "17:5: NPath Complexity is 5 (max allowed is 0).", "27:5: NPath Complexity is 3 (max allowed is 0).", "34:5: NPath Complexity is 7 (max allowed is 0).", "48:5: NPath Complexity is 3 (max allowed is 0).", "58:5: NPath Complexity is 3 (max allowed is 0).", "67:5: NPath Complexity is 3 (max allowed is 0).", "76:5: NPath Complexity is 1 (max allowed is 0).", "79:13: NPath Complexity is 2 (max allowed is 0).", }; verify(checkConfig, getPath("ComplexityCheckTestInput.java"), expected); } @Test public void testIntegerOverflow() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(NPathComplexityCheck.class); checkConfig.addAttribute("max", "0"); final long largerThanMaxInt = 3486784401L; // use i18n for number formating so test wont fail in non-english environments final String expectedComplexity = NumberFormat.getInstance().format(largerThanMaxInt); String[] expected = { "9:5: NPath Complexity is " + expectedComplexity + " (max allowed is 0).", }; verify(checkConfig, getPath("ComplexityOverflow.java"), expected); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/modifier/ModifierOrderCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/modifier/ModifierOrderCheckTest.java100644 0 0 4164 12026050745 31323 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.modifier; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class ModifierOrderCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ModifierOrderCheck.class); final String[] expected = { "14:10: 'final' modifier out of order with the JLS suggestions.", "18:12: 'private' modifier out of order with the JLS suggestions.", "24:14: 'private' modifier out of order with the JLS suggestions.", "34:13: '@MyAnnotation2' annotation modifier does not preceed non-annotation modifiers.", "39:13: '@MyAnnotation2' annotation modifier does not preceed non-annotation modifiers.", "49:35: '@MyAnnotation4' annotation modifier does not preceed non-annotation modifiers.", }; verify(checkConfig, getPath("InputModifier.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierTest.java100644 0 0 4364 12026050745 31240 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.modifier; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class RedundantModifierTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RedundantModifierCheck.class); final String[] expected = { "54:12: Redundant 'static' modifier.", "57:9: Redundant 'public' modifier.", "63:9: Redundant 'abstract' modifier.", "66:9: Redundant 'public' modifier.", //"69:9: Redundant 'abstract' modifier.", "72:9: Redundant 'final' modifier.", "79:13: Redundant 'final' modifier.", "88:12: Redundant 'final' modifier.", "116:5: Redundant 'public' modifier.", "117:5: Redundant 'final' modifier.", "118:5: Redundant 'static' modifier.", "120:5: Redundant 'public' modifier.", "121:5: Redundant 'abstract' modifier.", }; verify(checkConfig, getPath("InputModifier.java"), expected); } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheckTest.ja100644 0 0 10051 12026050745 31257 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class AbstractClassNameCheckTest extends BaseCheckTestSupport { @Test public void testIllegalAbstractClassName() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AbstractClassNameCheck.class); checkConfig.addAttribute("ignoreName", "false"); checkConfig.addAttribute("ignoreModifier", "true"); final String[] expected = { "3:1: Name 'InputAbstractClassName' must match pattern '^Abstract.*$|^.*Factory$'.", "6:1: Name 'NonAbstractClassName' must match pattern '^Abstract.*$|^.*Factory$'.", "9:1: Name 'FactoryWithBadName' must match pattern '^Abstract.*$|^.*Factory$'.", "13:5: Name 'NonAbstractInnerClass' must match pattern '^Abstract.*$|^.*Factory$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputAbstractClassName.java"), expected); } @Test public void testIllegalClassType() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AbstractClassNameCheck.class); checkConfig.addAttribute("ignoreName", "true"); checkConfig.addAttribute("ignoreModifier", "false"); final String[] expected = { "26:1: Class 'AbstractClass' must be declared as 'abstract'.", "29:1: Class 'Class1Factory' must be declared as 'abstract'.", "33:5: Class 'AbstractInnerClass' must be declared as 'abstract'.", "38:5: Class 'WellNamedFactory' must be declared as 'abstract'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputAbstractClassName.java"), expected); } @Test public void testAllVariants() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AbstractClassNameCheck.class); checkConfig.addAttribute("ignoreName", "false"); checkConfig.addAttribute("ignoreModifier", "false"); final String[] expected = { "3:1: Name 'InputAbstractClassName' must match pattern '^Abstract.*$|^.*Factory$'.", "6:1: Name 'NonAbstractClassName' must match pattern '^Abstract.*$|^.*Factory$'.", "9:1: Name 'FactoryWithBadName' must match pattern '^Abstract.*$|^.*Factory$'.", "13:5: Name 'NonAbstractInnerClass' must match pattern '^Abstract.*$|^.*Factory$'.", "26:1: Class 'AbstractClass' must be declared as 'abstract'.", "29:1: Class 'Class1Factory' must be declared as 'abstract'.", "33:5: Class 'AbstractInnerClass' must be declared as 'abstract'.", "38:5: Class 'WellNamedFactory' must be declared as 'abstract'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputAbstractClassName.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/ConstantNameCheckTest.java100644 0 0 7331 12026050745 30635 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import static org.junit.Assert.fail; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import java.io.File; import org.junit.Test; public class ConstantNameCheckTest extends BaseCheckTestSupport { @Test public void testIllegalRegexp() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ConstantNameCheck.class); checkConfig.addAttribute("format", "\\"); try { createChecker(checkConfig); fail(); } catch (CheckstyleException ex) { // expected exception } } @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ConstantNameCheck.class); final String[] expected = { "25:29: Name 'badConstant' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "142:30: Name 'BAD__NAME' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testAccessControlTuning() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ConstantNameCheck.class); checkConfig.addAttribute("applyToPublic", "false"); checkConfig.addAttribute("applyToProtected", "false"); checkConfig.addAttribute("applyToPackage", "false"); final String[] expected = { "142:30: Name 'BAD__NAME' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testInterfaceAndAnnotation() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ConstantNameCheck.class); final String[] expected = { "24:16: Name 'data' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "64:16: Name 'data' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", }; verify(checkConfig, getPath("InputInner.java"), expected); } @Test public void testDefault1() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ConstantNameCheck.class); final String[] expected = { }; verify(checkConfig, getPath("naming" + File.separator + "InputConstantNames.java"), expected); } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/LocalFinalVariableNameCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/LocalFinalVariableNameCheckTe100644 0 0 4642 12026050744 31230 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class LocalFinalVariableNameCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(LocalFinalVariableNameCheck.class); final String[] expected = { "123:19: Name 'CDE' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testSet() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(LocalFinalVariableNameCheck.class); checkConfig.addAttribute("format", "[A-Z]+"); final String[] expected = { "122:19: Name 'cde' must match pattern '[A-Z]+'.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testInnerClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(LocalFinalVariableNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("InputInner.java"), expected); } } ././@LongLink100644 0 0 147 12026055133 10252 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/LocalVariableNameCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/LocalVariableNameCheckTest.ja100644 0 0 5311 12026050744 31210 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class LocalVariableNameCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(LocalVariableNameCheck.class); final String[] expected = { "119:13: Name 'ABC' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "130:18: Name 'I' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "132:20: Name 'InnerBlockVariable' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "207:21: Name 'O' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testInnerClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(LocalVariableNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("InputInner.java"), expected); } @Test public void testCatchParameter() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(LocalVariableNameCheck.class); checkConfig.addAttribute("tokens", "PARAMETER_DEF"); checkConfig.addAttribute("format", "^e$"); final String[] expected = { "74:24: Name 'ex' must match pattern '^e$'.", }; verify(checkConfig, getPath("InputEmptyStatement.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/MemberNameCheckTest.java100644 0 0 15610 12026050744 30271 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.io.File; import org.junit.Test; public class MemberNameCheckTest extends BaseCheckTestSupport { @Test public void testSpecified() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); checkConfig.addAttribute("format", "^m[A-Z][a-zA-Z0-9]*$"); final String[] expected = { "35:17: Name 'badMember' must match pattern '^m[A-Z][a-zA-Z0-9]*$'.", "224:17: Name 'someMember' must match pattern '^m[A-Z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testInnerClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = { "56:25: Name 'ABC' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("InputInner.java"), expected); } @Test public void testDefaults() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = { "8:16: Name '_public' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "9:19: Name '_protected' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "10:9: Name '_package' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "11:17: Name '_private' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputMemberName.java"), expected); } @Test public void testUnderlined() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); checkConfig.addAttribute("format", "^_[a-z]*$"); final String[] expected = { "3:16: Name 'mPublic' must match pattern '^_[a-z]*$'.", "4:19: Name 'mProtected' must match pattern '^_[a-z]*$'.", "5:9: Name 'mPackage' must match pattern '^_[a-z]*$'.", "6:17: Name 'mPrivate' must match pattern '^_[a-z]*$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputMemberName.java"), expected); } @Test public void testPublicOnly() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); checkConfig.addAttribute("format", "^_[a-z]*$"); checkConfig.addAttribute("applyToProtected", "false"); checkConfig.addAttribute("applyToPackage", "false"); checkConfig.addAttribute("applyToPrivate", "false"); final String[] expected = { "3:16: Name 'mPublic' must match pattern '^_[a-z]*$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputMemberName.java"), expected); } @Test public void testProtectedOnly() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); checkConfig.addAttribute("format", "^_[a-z]*$"); checkConfig.addAttribute("applyToPublic", "false"); checkConfig.addAttribute("applyToPackage", "false"); checkConfig.addAttribute("applyToPrivate", "false"); final String[] expected = { "4:19: Name 'mProtected' must match pattern '^_[a-z]*$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputMemberName.java"), expected); } @Test public void testPackageOnly() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); checkConfig.addAttribute("format", "^_[a-z]*$"); checkConfig.addAttribute("applyToPublic", "false"); checkConfig.addAttribute("applyToProtected", "false"); checkConfig.addAttribute("applyToPrivate", "false"); final String[] expected = { "5:9: Name 'mPackage' must match pattern '^_[a-z]*$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputMemberName.java"), expected); } @Test public void testPrivateOnly() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); checkConfig.addAttribute("format", "^_[a-z]*$"); checkConfig.addAttribute("applyToPublic", "false"); checkConfig.addAttribute("applyToProtected", "false"); checkConfig.addAttribute("applyToPackage", "false"); final String[] expected = { "6:17: Name 'mPrivate' must match pattern '^_[a-z]*$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputMemberName.java"), expected); } @Test public void testNotPrivate() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); checkConfig.addAttribute("applyToPrivate", "false"); final String[] expected = { "8:16: Name '_public' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "9:19: Name '_protected' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "10:9: Name '_package' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputMemberName.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheckTest.java100644 0 0 12751 12026050744 30305 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class MethodNameCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodNameCheck.class); final String[] expected = { "137:10: Name 'ALL_UPPERCASE_METHOD' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testMethodEqClass() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodNameCheck.class); final String[] expected = { "12:16: Method Name 'InputMethNameEqualClsName' must not equal the enclosing class name.", "12:16: Name 'InputMethNameEqualClsName' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "17:17: Name 'PRIVATEInputMethNameEqualClsName' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "23:20: Method Name 'Inner' must not equal the enclosing class name.", "23:20: Name 'Inner' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "28:20: Name 'InputMethNameEqualClsName' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "37:24: Method Name 'InputMethNameEqualClsName' must not equal the enclosing class name.", "37:24: Name 'InputMethNameEqualClsName' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "47:9: Method Name 'SweetInterface' must not equal the enclosing class name.", "47:9: Name 'SweetInterface' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "53:17: Method Name 'Outter' must not equal the enclosing class name.", "53:17: Name 'Outter' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("InputMethNameEqualClsName.java"), expected); } @Test public void testMethodEqClassAllow() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodNameCheck.class); checkConfig.addAttribute("allowClassName", "true"); //allow method names and class names to equal final String[] expected = { "12:16: Name 'InputMethNameEqualClsName' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "17:17: Name 'PRIVATEInputMethNameEqualClsName' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "23:20: Name 'Inner' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "28:20: Name 'InputMethNameEqualClsName' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "37:24: Name 'InputMethNameEqualClsName' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "47:9: Name 'SweetInterface' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "53:17: Name 'Outter' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("InputMethNameEqualClsName.java"), expected); } @Test public void testAccessTuning() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodNameCheck.class); checkConfig.addAttribute("allowClassName", "true"); //allow method names and class names to equal checkConfig.addAttribute("applyToPrivate", "false"); //allow method names and class names to equal final String[] expected = { "12:16: Name 'InputMethNameEqualClsName' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "23:20: Name 'Inner' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "28:20: Name 'InputMethNameEqualClsName' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "37:24: Name 'InputMethNameEqualClsName' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "47:9: Name 'SweetInterface' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "53:17: Name 'Outter' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("InputMethNameEqualClsName.java"), expected); } @Test public void testForNpe() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodNameCheck.class); final String[] expected = { }; verify(checkConfig, getPath("naming/InputMethodNameExtra.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/PackageNameCheckTest.java100644 0 0 4033 12026050744 30372 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class PackageNameCheckTest extends BaseCheckTestSupport { @Test public void testSpecified() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(PackageNameCheck.class); checkConfig.addAttribute("format", "[A-Z]+"); final String[] expected = { "6:42: Name 'com.puppycrawl.tools.checkstyle' must match pattern '[A-Z]+'.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(PackageNameCheck.class); final String[] expected = { }; verify(checkConfig, getPath("InputSimple.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/ParameterNameCheckTest.java100644 0 0 5114 12026050743 30757 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class ParameterNameCheckTest extends BaseCheckTestSupport { @Test public void testCatch() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParameterNameCheck.class); checkConfig.addAttribute("format", "^NO_WAY_MATEY$"); final String[] expected = { }; verify(checkConfig, getPath("InputLeftCurlyOther.java"), expected); } @Test public void testSpecified() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParameterNameCheck.class); checkConfig.addAttribute("format", "^a[A-Z][a-zA-Z0-9]*$"); final String[] expected = { "71:19: Name 'badFormat1' must match pattern '^a[A-Z][a-zA-Z0-9]*$'.", "71:34: Name 'badFormat2' must match pattern '^a[A-Z][a-zA-Z0-9]*$'.", "72:25: Name 'badFormat3' must match pattern '^a[A-Z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParameterNameCheck.class); final String[] expected = { }; verify(checkConfig, getPath("InputSimple.java"), expected); } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/StaticVariableNameCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/StaticVariableNameCheckTest.j100644 0 0 4360 12026050743 31246 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class StaticVariableNameCheckTest extends BaseCheckTestSupport { @Test public void testSpecified() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(StaticVariableNameCheck.class); checkConfig.addAttribute("format", "^s[A-Z][a-zA-Z0-9]*$"); final String[] expected = { "30:24: Name 'badStatic' must match pattern '^s[A-Z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testAccessTuning() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(StaticVariableNameCheck.class); checkConfig.addAttribute("format", "^s[A-Z][a-zA-Z0-9]*$"); checkConfig.addAttribute("applyToPrivate", "false"); // allow method names and class names to equal final String[] expected = { }; verify(checkConfig, getPath("InputSimple.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/TypeNameCheckTest.java100644 0 0 4015 12026050743 27757 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class TypeNameCheckTest extends BaseCheckTestSupport { @Test public void testSpecified() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(TypeNameCheck.class); checkConfig.addAttribute("format", "^inputHe"); final String[] expected = { }; verify(checkConfig, getPath("inputHeader.java"), expected); } @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(TypeNameCheck.class); final String[] expected = { "1:48: Name 'inputHeader' must match pattern '^[A-Z][a-zA-Z0-9]*$'.", }; verify(checkConfig, getPath("inputHeader.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/naming/TypeParameterNameTest.java100644 0 0 7572 12026050743 30675 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.naming; import java.io.File; import org.junit.Test; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class TypeParameterNameTest extends BaseCheckTestSupport { @Test public void testClassDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ClassTypeParameterNameCheck.class); final String[] expected = { "3:38: Name 't' must match pattern '^[A-Z]$'.", "11:14: Name 'foo' must match pattern '^[A-Z]$'.", "25:24: Name 'foo' must match pattern '^[A-Z]$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputTypeParameterName.java"), expected); } @Test public void testMethodDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodTypeParameterNameCheck.class); final String[] expected = { "5:13: Name 'TT' must match pattern '^[A-Z]$'.", "7:6: Name 'e_e' must match pattern '^[A-Z]$'.", "17:6: Name 'Tfo$o2T' must match pattern '^[A-Z]$'.", "21:6: Name 'foo' must match pattern '^[A-Z]$'.", "26:10: Name '_fo' must match pattern '^[A-Z]$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputTypeParameterName.java"), expected); } @Test public void testClassFooName() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ClassTypeParameterNameCheck.class); checkConfig.addAttribute("format", "^foo$"); final String[] expected = { "3:38: Name 't' must match pattern '^foo$'.", "31:18: Name 'T' must match pattern '^foo$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputTypeParameterName.java"), expected); } @Test public void testMethodFooName() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodTypeParameterNameCheck.class); checkConfig.addAttribute("format", "^foo$"); final String[] expected = { "5:13: Name 'TT' must match pattern '^foo$'.", "7:6: Name 'e_e' must match pattern '^foo$'.", "17:6: Name 'Tfo$o2T' must match pattern '^foo$'.", "26:10: Name '_fo' must match pattern '^foo$'.", "33:6: Name 'E' must match pattern '^foo$'.", "35:14: Name 'T' must match pattern '^foo$'.", //"40:14: Name 'EE' must match pattern '^foo$'.", }; verify(checkConfig, getPath("naming" + File.separator + "InputTypeParameterName.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java100644 0 0 6720 12026050774 30377 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import org.junit.Test; public class NewlineAtEndOfFileCheckTest extends BaseCheckTestSupport { @Override protected DefaultConfiguration createCheckerConfig( Configuration aCheckConfig) { final DefaultConfiguration dc = new DefaultConfiguration("root"); dc.addChild(aCheckConfig); return dc; } @Test public void testNewlineAtEndOfFile() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NewlineAtEndOfFileCheck.class); checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF.toString()); final String[] expected = {}; verify( createChecker(checkConfig), getPath("InputNewlineAtEndOfFile.java"), expected); } @Test public void testNoNewlineAtEndOfFile() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NewlineAtEndOfFileCheck.class); checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF.toString()); final String[] expected = { "0: File does not end with a newline.", }; verify( createChecker(checkConfig), getPath("InputNoNewlineAtEndOfFile.java"), expected); } @Test(expected = CheckstyleException.class) public void testSetLineSeparatorFailure() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NewlineAtEndOfFileCheck.class); checkConfig.addAttribute("lineSeparator", "ct"); createChecker(checkConfig); } @Test public void testEmptyFileFile() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NewlineAtEndOfFileCheck.class); checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF.toString()); final String[] expected = { "0: File does not end with a newline.", }; verify( createChecker(checkConfig), getPath("InputEmptyFile.txt"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/OuterTypeFilenameCheckTest.java100644 0 0 3701 12026050774 30372 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import org.junit.Test; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; public class OuterTypeFilenameCheckTest extends BaseCheckTestSupport { @Test public void testGood() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(OuterTypeFilenameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("InputIllegalTokens.java"), expected); } @Test public void testBad() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(OuterTypeFilenameCheck.class); final String[] expected = { "3: The name of the outer type and the file do not match.", }; verify(checkConfig, getPath("Input15Extensions.java"), expected); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpMultilineCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpMultilineCheckTest.java100644 0 0 10522 12026050743 31413 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; import com.puppycrawl.tools.checkstyle.BaseFileSetCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; public class RegexpMultilineCheckTest extends BaseFileSetCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(RegexpMultilineCheck.class); } @Test public void testIt() throws Exception { final String illegal = "System\\.(out)|(err)\\.print(ln)?\\("; mCheckConfig.addAttribute("format", illegal); final String[] expected = { "69: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testMessageProperty() throws Exception { final String illegal = "System\\.(out)|(err)\\.print(ln)?\\("; final String message = "Bad line :("; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("message", message); final String[] expected = { "69: " + message, }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testIgnoreCaseTrue() throws Exception { final String illegal = "SYSTEM\\.(OUT)|(ERR)\\.PRINT(LN)?\\("; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreCase", "true"); final String[] expected = { "69: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testIgnoreCaseFalse() throws Exception { final String illegal = "SYSTEM\\.(OUT)|(ERR)\\.PRINT(LN)?\\("; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreCase", "false"); final String[] expected = {}; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testIllegalFailBelowErrorLimit() throws Exception { final String illegal = "^import"; mCheckConfig.addAttribute("format", illegal); final String[] expected = { "7: Line matches the illegal pattern '" + illegal + "'.", "8: Line matches the illegal pattern '" + illegal + "'.", "9: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } // Need to fix the line endings in the input file @Ignore @Test public void testCarriageReturn() throws Exception { final String illegal = "\\r"; mCheckConfig.addAttribute("format", illegal); final String[] expected = { "14: Line matches the illegal pattern '" + illegal + "'.", "16: Line matches the illegal pattern '" + illegal + "'.", "19: Line matches the illegal pattern '" + illegal + "'.", "21: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputLineBreaks.java"), expected); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineCheckTest.jav100644 0 0 6240 12026050742 31362 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; import com.puppycrawl.tools.checkstyle.BaseFileSetCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class RegexpSinglelineCheckTest extends BaseFileSetCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(RegexpSinglelineCheck.class); } @Test public void testIt() throws Exception { final String illegal = "System\\.(out)|(err)\\.print(ln)?\\("; mCheckConfig.addAttribute("format", illegal); final String[] expected = { "69: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testMessageProperty() throws Exception { final String illegal = "System\\.(out)|(err)\\.print(ln)?\\("; final String message = "Bad line :("; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("message", message); final String[] expected = { "69: " + message, }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testIgnoreCaseTrue() throws Exception { final String illegal = "SYSTEM\\.(OUT)|(ERR)\\.PRINT(LN)?\\("; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreCase", "true"); final String[] expected = { "69: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testIgnoreCaseFalse() throws Exception { final String illegal = "SYSTEM\\.(OUT)|(ERR)\\.PRINT(LN)?\\("; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreCase", "false"); final String[] expected = {}; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheckTest100644 0 0 22345 12026050742 31431 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.regexp; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class RegexpSinglelineJavaCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(RegexpSinglelineJavaCheck.class); } @Test public void testIt() throws Exception { final String illegal = "System\\.(out)|(err)\\.print(ln)?\\("; mCheckConfig.addAttribute("format", illegal); final String[] expected = { "69: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testMessageProperty() throws Exception { final String illegal = "System\\.(out)|(err)\\.print(ln)?\\("; final String message = "Bad line :("; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("message", message); final String[] expected = { "69: " + message, }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testIgnoreCaseTrue() throws Exception { final String illegal = "SYSTEM\\.(OUT)|(ERR)\\.PRINT(LN)?\\("; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreCase", "true"); final String[] expected = { "69: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testIgnoreCaseFalse() throws Exception { final String illegal = "SYSTEM\\.(OUT)|(ERR)\\.PRINT(LN)?\\("; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreCase", "false"); final String[] expected = {}; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testIgnoreCommentsCppStyle() throws Exception { // See if the comment is removed properly final String illegal = "don't use trailing comments"; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsFalseCppStyle() throws Exception { // See if the comment is removed properly final String illegal = "don't use trailing comments"; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreComments", "false"); final String[] expected = { "2: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsCStyle() throws Exception { // See if the comment is removed properly final String illegal = "c-style 1"; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsFalseCStyle() throws Exception { final String illegal = "c-style 1"; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreComments", "false"); final String[] expected = { "17: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsMultipleCStyle() throws Exception { // See if a second comment on the same line is removed properly final String illegal = "c-style 2"; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsMultiLine() throws Exception { final String illegal = "Let's check multi-line comments"; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsInlineStart() throws Exception { final String illegal = "long ms /"; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsInlineEnd() throws Exception { final String illegal = "int z"; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreComments", "true"); final String[] expected = { "20: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsInlineMiddle() throws Exception { final String illegal = "int y"; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreComments", "true"); final String[] expected = { "21: Line matches the illegal pattern '" + illegal + "'.", }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsNoSpaces() throws Exception { // make sure the comment is not turned into spaces final String illegal = "long ms "; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void test1371588() throws Exception { // StackOverflowError with trailing space and ignoreComments final String illegal = "\\s+$"; mCheckConfig.addAttribute("format", illegal); mCheckConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testExistingInDoc() throws Exception { final String required = "Test case file"; mCheckConfig.addAttribute("format", required); mCheckConfig.addAttribute("minimum", "1"); mCheckConfig.addAttribute("maximum", "1000"); final String[] expected = { }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testExistingInCode() throws Exception { final String required = "package"; mCheckConfig.addAttribute("format", required); mCheckConfig.addAttribute("minimum", "1"); mCheckConfig.addAttribute("maximum", "1000"); final String[] expected = { }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } @Test public void testMissing() throws Exception { final String required = "This text is not in the file"; mCheckConfig.addAttribute("format", required); mCheckConfig.addAttribute("minimum", "1"); mCheckConfig.addAttribute("maximum", "1000"); final String[] expected = { "0: File does not contain at least 1 matches for pattern '" + required + "'.", }; verify(mCheckConfig, getPath("InputSemantic.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/RegexpCheckTest.java100644 0 0 33715 12026050774 26253 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class RegexpCheckTest extends BaseCheckTestSupport { @Test public void testRequiredPass() throws Exception { final String required = "Test case file"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", required); final String[] expected = { }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testRequiredFail() throws Exception { final String required = "This text is not in the file"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", required); final String[] expected = { "0: Required pattern '" + required + "' missing in file.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testRequiredNoDuplicatesPass() throws Exception { final String required = "Test case file"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", required); checkConfig.addAttribute("duplicateLimit", "0"); final String[] expected = { }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testRequiredNoDuplicatesFail() throws Exception { final String required = "Boolean x = new Boolean"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", required); checkConfig.addAttribute("duplicateLimit", "0"); final String[] expected = { "24: Found duplicate pattern '" + required + "'.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testIllegalPass() throws Exception { final String illegal = "This text is not in the file"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); final String[] expected = { }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testIllegalFailBelowErrorLimit() throws Exception { final String illegal = "^import"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("errorLimit", "4"); final String[] expected = { "7: Line matches the illegal pattern '" + illegal + "'.", "8: Line matches the illegal pattern '" + illegal + "'.", "9: Line matches the illegal pattern '" + illegal + "'.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testIllegalFailAboveErrorLimit() throws Exception { final String illegal = "^import"; final String error = "The error limit has been exceeded, " + "the check is aborting, there may be more unreported errors."; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("errorLimit", "3"); final String[] expected = { "7: Line matches the illegal pattern '" + illegal + "'.", "8: Line matches the illegal pattern '" + illegal + "'.", "9: Line matches the illegal pattern '" + error + illegal + "'.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testMessagePropertyGood() throws Exception { final String illegal = "System\\.(out)|(err)\\.print(ln)?\\("; final String message = "Bad line :("; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("message", message); final String[] expected = { "69: Line matches the illegal pattern '" + message + "'.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testMessagePropertyBad() throws Exception { final String illegal = "System\\.(out)|(err)\\.print(ln)?\\("; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("message", null); final String[] expected = { "69: Line matches the illegal pattern '" + illegal + "'.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testIgnoreCaseTrue() throws Exception { final String illegal = "(?i)SYSTEM\\.(OUT)|(ERR)\\.PRINT(LN)?\\("; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); final String[] expected = { "69: Line matches the illegal pattern '" + illegal + "'.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } @Test public void testIgnoreCaseFalse() throws Exception { final String illegalTrue = "(?i)SYSTEM\\.(OUT)|(ERR)\\.PRINT(LN)?\\("; final DefaultConfiguration checkConfigTrue = createCheckConfig(RegexpCheck.class); checkConfigTrue.addAttribute("format", illegalTrue); checkConfigTrue.addAttribute("illegalPattern", "true"); final String[] expectedTrue = { "69: Line matches the illegal pattern '" + illegalTrue + "'.", }; verify(checkConfigTrue, getPath("InputSemantic.java"), expectedTrue); final String illegalFalse = "SYSTEM\\.(OUT)|(ERR)\\.PRINT(LN)?\\("; final DefaultConfiguration checkConfigFalse = createCheckConfig(RegexpCheck.class); checkConfigFalse.addAttribute("format", illegalFalse); checkConfigFalse.addAttribute("illegalPattern", "true"); final String[] expectedFalse = {}; verify(checkConfigFalse, getPath("InputSemantic.java"), expectedFalse); } @Test public void testIgnoreCommentsCppStyle() throws Exception { // See if the comment is removed properly final String illegal = "don't use trailing comments"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(checkConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsFalseCppStyle() throws Exception { // See if the comment is removed properly final String illegal = "don't use trailing comments"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("ignoreComments", "false"); final String[] expected = { "2: Line matches the illegal pattern '" + illegal + "'.", }; verify(checkConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsCStyle() throws Exception { // See if the comment is removed properly final String illegal = "c-style 1"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(checkConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsFalseCStyle() throws Exception { final String illegal = "c-style 1"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("ignoreComments", "false"); final String[] expected = { "17: Line matches the illegal pattern '" + illegal + "'.", }; verify(checkConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsMultipleCStyle() throws Exception { // See if a second comment on the same line is removed properly final String illegal = "c-style 2"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(checkConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsMultiLine() throws Exception { final String illegal = "Let's check multi-line comments"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(checkConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsInlineStart() throws Exception { final String illegal = "long ms /"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(checkConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsInlineEnd() throws Exception { final String illegal = "int z"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("ignoreComments", "true"); final String[] expected = { "20: Line matches the illegal pattern '" + illegal + "'.", }; verify(checkConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsInlineMiddle() throws Exception { final String illegal = "int y"; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("ignoreComments", "true"); final String[] expected = { "21: Line matches the illegal pattern '" + illegal + "'.", }; verify(checkConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testIgnoreCommentsNoSpaces() throws Exception { // make sure the comment is not turned into spaces final String illegal = "long ms "; final DefaultConfiguration checkConfig = createCheckConfig(RegexpCheck.class); checkConfig.addAttribute("format", illegal); checkConfig.addAttribute("illegalPattern", "true"); checkConfig.addAttribute("ignoreComments", "true"); final String[] expected = { }; verify(checkConfig, getPath("InputTrailingComment.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/AnonInnerLengthCheckTest.java100644 0 0 4366 12026050742 31162 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; /** * @author Rob Worth * @author Lars Kühne */ public class AnonInnerLengthCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AnonInnerLengthCheck.class); final String[] expected = { "50:35: Anonymous inner class length is 21 lines (max allowed is 20).", }; verify(checkConfig, getPath("InputAnonInnerLength.java"), expected); } @Test public void testNonDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(AnonInnerLengthCheck.class); checkConfig.addAttribute("max", "6"); final String[] expected = { "50:35: Anonymous inner class length is 21 lines (max allowed is 6).", "75:35: Anonymous inner class length is 20 lines (max allowed is 6).", }; verify(checkConfig, getPath("InputAnonInnerLength.java"), expected); } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/ExecutableStatementCountCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/ExecutableStatementCountCheckT100644 0 0 11516 12026050741 31466 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class ExecutableStatementCountCheckTest extends BaseCheckTestSupport { @Test public void testMaxZero() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExecutableStatementCountCheck.class); checkConfig.addAttribute("max", "0"); final String[] expected = { "4:5: Executable statement count is 3 (max allowed is 0).", "7:17: Executable statement count is 1 (max allowed is 0).", "17:5: Executable statement count is 2 (max allowed is 0).", "27:5: Executable statement count is 1 (max allowed is 0).", "34:5: Executable statement count is 3 (max allowed is 0).", "48:5: Executable statement count is 2 (max allowed is 0).", "58:5: Executable statement count is 2 (max allowed is 0).", "67:5: Executable statement count is 2 (max allowed is 0).", "76:5: Executable statement count is 2 (max allowed is 0).", "79:13: Executable statement count is 1 (max allowed is 0).", }; verify(checkConfig, getPath("ComplexityCheckTestInput.java"), expected); } @Test public void testMethodDef() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExecutableStatementCountCheck.class); checkConfig.addAttribute("max", "0"); checkConfig.addAttribute("tokens", "METHOD_DEF"); final String[] expected = { "4:5: Executable statement count is 3 (max allowed is 0).", "7:17: Executable statement count is 1 (max allowed is 0).", "17:5: Executable statement count is 2 (max allowed is 0).", "27:5: Executable statement count is 1 (max allowed is 0).", "34:5: Executable statement count is 3 (max allowed is 0).", "79:13: Executable statement count is 1 (max allowed is 0).", }; verify(checkConfig, getPath("ComplexityCheckTestInput.java"), expected); } @Test public void testCtorDef() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExecutableStatementCountCheck.class); checkConfig.addAttribute("max", "0"); checkConfig.addAttribute("tokens", "CTOR_DEF"); final String[] expected = { "48:5: Executable statement count is 2 (max allowed is 0).", "76:5: Executable statement count is 2 (max allowed is 0).", }; verify(checkConfig, getPath("ComplexityCheckTestInput.java"), expected); } @Test public void testStaticInit() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExecutableStatementCountCheck.class); checkConfig.addAttribute("max", "0"); checkConfig.addAttribute("tokens", "STATIC_INIT"); final String[] expected = { "58:5: Executable statement count is 2 (max allowed is 0).", }; verify(checkConfig, getPath("ComplexityCheckTestInput.java"), expected); } @Test public void testInstanceInit() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ExecutableStatementCountCheck.class); checkConfig.addAttribute("max", "0"); checkConfig.addAttribute("tokens", "INSTANCE_INIT"); final String[] expected = { "67:5: Executable statement count is 2 (max allowed is 0).", }; verify(checkConfig, getPath("ComplexityCheckTestInput.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/FileLengthCheckTest.java100644 0 0 6032 12026050740 30140 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import static org.junit.Assert.fail; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import org.junit.Test; public class FileLengthCheckTest extends BaseCheckTestSupport { @Override protected DefaultConfiguration createCheckerConfig( Configuration aCheckConfig) { DefaultConfiguration dc = new DefaultConfiguration("root"); dc.addChild(aCheckConfig); return dc; } @Test public void testAlarm() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(FileLengthCheck.class); checkConfig.addAttribute("max", "20"); final String[] expected = { "1: File length is 225 lines (max allowed is 20).", }; verify(createChecker(checkConfig), getPath("InputSimple.java"), getPath("InputSimple.java"), expected); } @Test public void testOK() throws Exception { DefaultConfiguration checkConfig = createCheckConfig(FileLengthCheck.class); checkConfig.addAttribute("max", "2000"); final String[] expected = { }; verify(createChecker(checkConfig), getPath("InputSimple.java"), getPath("InputSimple.java"), expected); } @Test public void testArgs() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(FileLengthCheck.class); try { checkConfig.addAttribute("max", "abc"); createChecker(checkConfig); fail("Should indicate illegal args"); } catch (CheckstyleException ex) { // Expected Exception because of illegal argument for "max" } } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/LineLengthCheckTest.java100644 0 0 4567 12026050740 30163 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class LineLengthCheckTest extends BaseCheckTestSupport { @Test public void testSimple() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(LineLengthCheck.class); checkConfig.addAttribute("max", "80"); checkConfig.addAttribute("ignorePattern", "^.*is OK.*regexp.*$"); final String[] expected = { "18: Line is longer than 80 characters (found 81).", "145: Line is longer than 80 characters (found 83).", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void shouldLogActualLineLength() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(LineLengthCheck.class); checkConfig.addAttribute("max", "80"); checkConfig.addAttribute("ignorePattern", "^.*is OK.*regexp.*$"); checkConfig.addMessage("maxLineLen", "{0},{1}"); final String[] expected = { "18: 80,81", "145: 80,83", }; verify(checkConfig, getPath("InputSimple.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheckInput.java100644 0 0 5751 11451330227 30541 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.sizes; public class MethodCountCheckInput { /** * Dummy inner class to check that the inner-classes methods are not counted * for the outer class. */ public class PublicMethodsInnerclassInnerclass { /** * Dummy method doing nothing */ public void doNothing50() { } /** * Dummy method doing nothing */ public void doNothing51() { } /** * Dummy method doing nothing */ public void doNothing52() { } /** * Dummy method doing nothing */ public void doNothing53() { } /** * Dummy method doing nothing */ public void doNothing54() { } } /** * Dummy inner class to check that the inner-classes methods are not counted * for the outer class. */ public interface PublicMethodsInnerInterface { /** * Dummy method doing nothing */ public void doNothing60(); /** * Dummy method doing nothing */ public void doNothing61(); /** * Dummy method doing nothing */ public abstract void doNothing62(); /** * Dummy method doing nothing */ abstract void doNothing63(); /** * Dummy method doing nothing */ void doNothing64(); } /** * Dummy method doing nothing */ public void doNothing00() { } /** * Dummy method doing nothing */ public void doNothing01() { } /** * Dummy method doing nothing */ public void doNothing02() { } /** * Dummy method doing nothing */ public void doNothing03() { } /** * Dummy method doing nothing */ public void doNothing04() { } /** * Dummy method doing nothing */ protected void doNothing10() { } /** * Dummy method doing nothing */ protected void doNothing11() { } /** * Dummy method doing nothing */ protected void doNothing12() { } /** * Dummy method doing nothing */ protected void doNothing13() { } /** * Dummy method doing nothing */ protected void doNothing14() { } /** * Dummy method doing nothing */ void doNothing20() { } /** * Dummy method doing nothing */ void doNothing21() { } /** * Dummy method doing nothing */ void doNothing22() { } /** * Dummy method doing nothing */ void doNothing23() { } /** * Dummy method doing nothing */ void doNothing24() { } /** * Dummy method doing nothing */ private void doNothing30() { } /** * Dummy method doing nothing */ private void doNothing31() { } /** * Dummy method doing nothing */ private void doNothing32() { } /** * Dummy method doing nothing */ private void doNothing33() { } /** * Dummy method doing nothing */ private void doNothing34() { } }checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheckInput2.java100644 0 0 601 11451330227 30570 0ustar 0 0 package com.puppycrawl.tools.checkstyle.checks.sizes; public enum MethodCountCheckInput2 { RED { @Override void something() {}; }, BLUE { @Override void something() {}; protected void other1() {}; private void other2() {}; }; @Override public String toString() { return ""; }; abstract void something(); } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheckTest.java100644 0 0 6617 12026050740 30361 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class MethodCountCheckTest extends BaseCheckTestSupport { @Test public void testDefaults() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodCountCheck.class); final String[] expected = { }; verify(checkConfig, getSrcPath("checks/sizes/MethodCountCheckInput.java"), expected); } @Test public void testThrees() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodCountCheck.class); checkConfig.addAttribute("maxPrivate", "3"); checkConfig.addAttribute("maxPackage", "3"); checkConfig.addAttribute("maxProtected", "3"); checkConfig.addAttribute("maxPublic", "3"); checkConfig.addAttribute("maxTotal", "3"); final String[] expected = { "3: Number of package methods is 5 (max allowed is 3).", "3: Number of private methods is 5 (max allowed is 3).", "3: Number of protected methods is 5 (max allowed is 3).", "3: Number of public methods is 5 (max allowed is 3).", "3: Total number of methods is 20 (max allowed is 3).", "9: Number of public methods is 5 (max allowed is 3).", "9: Total number of methods is 5 (max allowed is 3).", "45: Number of public methods is 5 (max allowed is 3).", "45: Total number of methods is 5 (max allowed is 3).", }; verify(checkConfig, getSrcPath("checks/sizes/MethodCountCheckInput.java"), expected); } @Test public void testEnum() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodCountCheck.class); checkConfig.addAttribute("maxPrivate", "0"); checkConfig.addAttribute("maxTotal", "2"); final String[] expected = { "9: Number of private methods is 1 (max allowed is 0).", "9: Total number of methods is 3 (max allowed is 2).", }; verify(checkConfig, getSrcPath("checks/sizes/MethodCountCheckInput2.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/MethodLengthCheckTest.java100644 0 0 4577 12026050737 30523 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class MethodLengthCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodLengthCheck.class); checkConfig.addAttribute("max", "19"); final String[] expected = { "79:5: Method length is 20 lines (max allowed is 19).", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testcountEmpty() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodLengthCheck.class); checkConfig.addAttribute("max", "19"); checkConfig.addAttribute("countEmpty", "false"); final String[] expected = { }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testAbstract() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MethodLengthCheck.class); final String[] expected = { }; verify(checkConfig, getPath("InputModifier.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/OuterTypeNumberCheckTest.java100644 0 0 3755 12026050737 31247 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class OuterTypeNumberCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(OuterTypeNumberCheck.class); final String[] expected = { "6:34: Outer types defined is 3 (max allowed is 1).", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testMax30() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(OuterTypeNumberCheck.class); checkConfig.addAttribute("max", "30"); final String[] expected = { }; verify(checkConfig, getPath("InputSimple.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/sizes/ParameterNumberCheckTest.java100644 0 0 5011 12026050737 31212 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.sizes; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class ParameterNumberCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParameterNumberCheck.class); final String[] expected = { "194:10: More than 7 parameters (found 9).", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testNum() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParameterNumberCheck.class); checkConfig.addAttribute("max", "2"); final String[] expected = { "71:9: More than 2 parameters (found 3).", "194:10: More than 2 parameters (found 9).", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void shouldLogActualParameterNumber() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParameterNumberCheck.class); checkConfig.addMessage("maxParam", "{0},{1}"); final String[] expected = { "194:10: 7,9", }; verify(checkConfig, getPath("InputSimple.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/TodoCommentCheckTest.java100644 0 0 3546 12026050773 27227 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class TodoCommentCheckTest extends BaseCheckTestSupport { @Test public void testIt() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(TodoCommentCheck.class); checkConfig.addAttribute("format", "FIXME:"); final String[] expected = { "161: Comment matches to-do format 'FIXME:'.", "162: Comment matches to-do format 'FIXME:'.", "163: Comment matches to-do format 'FIXME:'.", "167: Comment matches to-do format 'FIXME:'.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheckTest.java100644 0 0 4722 12026050773 30070 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class TrailingCommentCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(TrailingCommentCheck.class); } @Test public void testDefaults() throws Exception { final String[] expected = { "2: Don't use trailing comments.", "5: Don't use trailing comments.", "6: Don't use trailing comments.", "16: Don't use trailing comments.", "17: Don't use trailing comments.", "27: Don't use trailing comments.", }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } @Test public void testLegalComment() throws Exception { mCheckConfig.addAttribute("legalComment", "^NOI18N$"); final String[] expected = { "2: Don't use trailing comments.", "5: Don't use trailing comments.", "6: Don't use trailing comments.", "16: Don't use trailing comments.", "17: Don't use trailing comments.", }; verify(mCheckConfig, getPath("InputTrailingComment.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/TranslationCheckTest.java100644 0 0 4674 12026050773 27300 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.Configuration; import java.io.File; import org.junit.Test; public class TranslationCheckTest extends BaseCheckTestSupport { @Override protected DefaultConfiguration createCheckerConfig( Configuration aCheckConfig) { final DefaultConfiguration dc = new DefaultConfiguration("root"); dc.addChild(aCheckConfig); return dc; } @Test public void testTranslation() throws Exception { final Configuration checkConfig = createCheckConfig(TranslationCheck.class); final String[] expected = { "0: Key 'only.english' missing.", }; final File[] propertyFiles = new File[] { new File(getPath("messages_de.properties")), new File(getPath("messages.properties")), }; verify( createChecker(checkConfig), propertyFiles, getPath("messages_de.properties"), expected); } // TODO: test with the same resourcebundle name in different packages // x/messages.properties // key1=x // y/messages.properties // key2=y // should not result in error message about key1 missing in the y bundle } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheckTest.java100644 0 0 4351 12026050773 30055 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class UncommentedMainCheckTest extends BaseCheckTestSupport { @Test public void testDefaults() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UncommentedMainCheck.class); final String[] expected = { "14: Uncommented main method found.", "23: Uncommented main method found.", "32: Uncommented main method found.", }; verify(checkConfig, getPath("InputUncommentedMain.java"), expected); } @Test public void testExcludedClasses() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UncommentedMainCheck.class); checkConfig.addAttribute("excludedClasses", "\\.Main$"); final String[] expected = { "14: Uncommented main method found.", "32: Uncommented main method found.", }; verify(checkConfig, getPath("InputUncommentedMain.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/UpperEllCheckTest.java100644 0 0 3176 12026050773 26526 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class UpperEllCheckTest extends BaseCheckTestSupport { @Test public void testWithChecker() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(UpperEllCheck.class); final String[] expected = { "94:43: Should use uppercase 'L'.", }; verify(checkConfig, getPath("InputSemantic.java"), expected); } } ././@LongLink100644 0 0 160 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyForInitializerPadCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyForInitializerPadChe100644 0 0 4123 12026050737 31423 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class EmptyForInitializerPadCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(EmptyForInitializerPadCheck.class); } @Test public void testDefault() throws Exception { final String[] expected = { "48:14: ';' is preceded with whitespace.", }; verify(mCheckConfig, getPath("InputForWhitespace.java"), expected); } @Test public void testSpaceOption() throws Exception { mCheckConfig.addAttribute("option", PadOption.SPACE.toString()); final String[] expected = { "51:13: ';' is not preceded with whitespace.", }; verify(mCheckConfig, getPath("InputForWhitespace.java"), expected); } } ././@LongLink100644 0 0 155 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyForIteratorPadCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyForIteratorPadCheckT100644 0 0 4177 12026050737 31404 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class EmptyForIteratorPadCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(EmptyForIteratorPadCheck.class); } @Test public void testDefault() throws Exception { final String[] expected = { "27:31: ';' is followed by whitespace.", "43:32: ';' is followed by whitespace.", }; verify(mCheckConfig, getPath("InputForWhitespace.java"), expected); } @Test public void testSpaceOption() throws Exception { mCheckConfig.addAttribute("option", PadOption.SPACE.toString()); final String[] expected = { "23:31: ';' is not followed by whitespace.", }; verify(mCheckConfig, getPath("InputForWhitespace.java"), expected); } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/FileTabCharacterCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/FileTabCharacterCheckTest100644 0 0 7333 12026050736 31333 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.Configuration; import java.io.File; import org.junit.Test; public class FileTabCharacterCheckTest extends BaseCheckTestSupport { @Override protected DefaultConfiguration createCheckerConfig( Configuration aCheckConfig) { final DefaultConfiguration dc = new DefaultConfiguration("root"); dc.addChild(aCheckConfig); return dc; } @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createConfig(false); final String[] expected = { "19:25: File contains tab characters (this is the first instance).", }; final File[] files = { new File(getPath("InputSimple.java")), }; verify(createChecker(checkConfig), files, getPath("InputSimple.java"), expected); } @Test public void testVerbose() throws Exception { final DefaultConfiguration checkConfig = createConfig(true); final String[] expected = { "19:25: Line contains a tab character.", "145:35: Line contains a tab character.", "146:64: Line contains a tab character.", "154:9: Line contains a tab character.", "155:10: Line contains a tab character.", "156:1: Line contains a tab character.", "157:3: Line contains a tab character.", "158:3: Line contains a tab character.", }; final File[] files = { new File(getPath("InputSimple.java")), }; verify(createChecker(checkConfig), files, getPath("InputSimple.java"), expected); } @Test public void testBadFile() throws Exception { final DefaultConfiguration checkConfig = createConfig(false); final String path = getPath("Claira"); final String[] expected = { "0: File not found!", }; final File[] files = { new File(path), }; verify(createChecker(checkConfig), files, path, expected); } /** * Creates a configuration that is functionally close to that in the docs. * @param verbose TODO */ private DefaultConfiguration createConfig(boolean verbose) { final DefaultConfiguration checkConfig = createCheckConfig(FileTabCharacterCheck.class); checkConfig.addAttribute("eachLine", Boolean.toString(verbose)); return checkConfig; } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheckTes100644 0 0 6532 12026050736 31415 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.google.common.collect.Maps; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import java.util.Map; import org.junit.Before; import org.junit.Test; public class GenericWhitespaceCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(GenericWhitespaceCheck.class); Map, Integer> x = Maps.newHashMap(); for (final Map.Entry, Integer> entry : x.entrySet()) { entry.getValue(); } //for (final Entry, Integer> entry : entrySet()) } @Test public void testDefault() throws Exception { final String[] expected = { "16:13: '<' is preceded with whitespace.", "16:15: '<' is followed by whitespace.", "16:23: '>' is preceded with whitespace.", "16:43: '<' is preceded with whitespace.", "16:45: '<' is followed by whitespace.", "16:53: '>' is preceded with whitespace.", "17:13: '<' is preceded with whitespace.", "17:15: '<' is followed by whitespace.", "17:20: '<' is preceded with whitespace.", "17:22: '<' is followed by whitespace.", "17:30: '>' is preceded with whitespace.", "17:32: '>' is followed by whitespace.", "17:32: '>' is preceded with whitespace.", "17:52: '<' is preceded with whitespace.", "17:54: '<' is followed by whitespace.", "17:59: '<' is preceded with whitespace.", "17:61: '<' is followed by whitespace.", "17:69: '>' is preceded with whitespace.", "17:71: '>' is followed by whitespace.", "17:71: '>' is preceded with whitespace.", "30:17: '<' is not preceded with whitespace.", "30:21: '>' is followed by an illegal character.", "42:21: '<' is preceded with whitespace.", "42:30: '>' is followed by whitespace.", }; verify(mCheckConfig, getPath("whitespace/InputGenericWhitespaceCheck.java"), expected); } } ././@LongLink100644 0 0 150 12026055133 10244 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/MethodParamPadCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/MethodParamPadCheckTest.j100644 0 0 12116 12026050736 31301 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class MethodParamPadCheckTest extends BaseCheckTestSupport { private DefaultConfiguration checkConfig; @Before public void setUp() { checkConfig = createCheckConfig(MethodParamPadCheck.class); } @Test public void testDefault() throws Exception { final String[] expected = { "11:32: '(' is preceded with whitespace.", "13:15: '(' is preceded with whitespace.", "17:9: '(' should be on the previous line.", "20:13: '(' should be on the previous line.", "27:24: '(' is preceded with whitespace.", "32:9: '(' should be on the previous line.", "36:39: '(' is preceded with whitespace.", "38:13: '(' should be on the previous line.", "42:16: '(' is preceded with whitespace.", "44:13: '(' should be on the previous line.", "50:21: '(' is preceded with whitespace.", "52:13: '(' should be on the previous line.", "56:18: '(' is preceded with whitespace.", "58:13: '(' should be on the previous line.", "61:36: '(' is preceded with whitespace.", "63:13: '(' should be on the previous line.", }; verify(checkConfig, getPath("whitespace/InputMethodParamPad.java"), expected); } @Test public void testAllowLineBreaks() throws Exception { checkConfig.addAttribute("allowLineBreaks", "true"); final String[] expected = { "11:32: '(' is preceded with whitespace.", "13:15: '(' is preceded with whitespace.", "27:24: '(' is preceded with whitespace.", "36:39: '(' is preceded with whitespace.", "42:16: '(' is preceded with whitespace.", "50:21: '(' is preceded with whitespace.", "56:18: '(' is preceded with whitespace.", "61:36: '(' is preceded with whitespace.", }; verify(checkConfig, getPath("whitespace/InputMethodParamPad.java"), expected); } @Test public void testSpaceOption() throws Exception { checkConfig.addAttribute("option", "space"); final String[] expected = { "6:31: '(' is not preceded with whitespace.", "8:14: '(' is not preceded with whitespace.", "17:9: '(' should be on the previous line.", "20:13: '(' should be on the previous line.", "23:23: '(' is not preceded with whitespace.", "32:9: '(' should be on the previous line.", "35:58: '(' is not preceded with whitespace.", "38:13: '(' should be on the previous line.", "41:15: '(' is not preceded with whitespace.", "44:13: '(' should be on the previous line.", "47:28: '(' is not preceded with whitespace.", "49:20: '(' is not preceded with whitespace.", "52:13: '(' should be on the previous line.", "54:56: '(' is not preceded with whitespace.", "55:17: '(' is not preceded with whitespace.", "58:13: '(' should be on the previous line.", "60:35: '(' is not preceded with whitespace.", "63:13: '(' should be on the previous line.", "66:25: '(' is not preceded with whitespace.", "69:66: '(' is not preceded with whitespace.", "70:57: '(' is not preceded with whitespace.", }; verify(checkConfig, getPath("whitespace/InputMethodParamPad.java"), expected); } @Test public void test1322879() throws Exception { checkConfig.addAttribute("option", PadOption.SPACE.toString()); final String[] expected = { }; verify(checkConfig, getPath("whitespace/InputWhitespaceAround.java"), expected); } } ././@LongLink100644 0 0 153 12026055133 10247 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheckTes100644 0 0 6231 12026050736 31373 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class NoWhitespaceAfterCheckTest extends BaseCheckTestSupport { private DefaultConfiguration checkConfig; @Before public void setUp() { checkConfig = createCheckConfig(NoWhitespaceAfterCheck.class); } @Test public void testDefault() throws Exception { checkConfig.addAttribute("allowLineBreaks", "false"); final String[] expected = { "5:14: '.' is followed by whitespace.", "6:12: '.' is followed by whitespace.", "29:14: '-' is followed by whitespace.", "29:21: '+' is followed by whitespace.", "31:15: '++' is followed by whitespace.", "31:22: '--' is followed by whitespace.", "111:22: '!' is followed by whitespace.", "112:23: '~' is followed by whitespace.", "129:24: '.' is followed by whitespace.", "132:11: '.' is followed by whitespace.", "136:12: '.' is followed by whitespace.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } @Test public void testDotAllowLineBreaks() throws Exception { checkConfig.addAttribute("tokens", "DOT"); final String[] expected = { "5:14: '.' is followed by whitespace.", "129:24: '.' is followed by whitespace.", "136:12: '.' is followed by whitespace.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } @Test public void testTypecast() throws Exception { checkConfig.addAttribute("tokens", "TYPECAST"); final String[] expected = { "87:28: ')' is followed by whitespace.", "89:23: ')' is followed by whitespace.", "241:22: ')' is followed by whitespace.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } } ././@LongLink100644 0 0 154 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceBeforeCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceBeforeCheckTe100644 0 0 6171 12026050735 31353 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class NoWhitespaceBeforeCheckTest extends BaseCheckTestSupport { private DefaultConfiguration checkConfig; @Before public void setUp() { checkConfig = createCheckConfig(NoWhitespaceBeforeCheck.class); } @Test public void testDefault() throws Exception { final String[] expected = { "30:14: '++' is preceded with whitespace.", "30:21: '--' is preceded with whitespace.", "176:18: ';' is preceded with whitespace.", "178:23: ';' is preceded with whitespace.", "185:18: ';' is preceded with whitespace.", "187:27: ';' is preceded with whitespace.", "195:26: ';' is preceded with whitespace.", "211:15: ';' is preceded with whitespace.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } @Test public void testDot() throws Exception { checkConfig.addAttribute("tokens", "DOT"); final String[] expected = { "5:12: '.' is preceded with whitespace.", "6:4: '.' is preceded with whitespace.", "129:17: '.' is preceded with whitespace.", "135:12: '.' is preceded with whitespace.", "136:10: '.' is preceded with whitespace.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } @Test public void testDotAllowLineBreaks() throws Exception { checkConfig.addAttribute("tokens", "DOT"); checkConfig.addAttribute("allowLineBreaks", "yes"); final String[] expected = { "5:12: '.' is preceded with whitespace.", "129:17: '.' is preceded with whitespace.", "136:10: '.' is preceded with whitespace.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } } ././@LongLink100644 0 0 146 12026055133 10251 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapCheckTest.jav100644 0 0 5257 12026050735 31416 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class OperatorWrapCheckTest extends BaseCheckTestSupport { private DefaultConfiguration checkConfig; @Before public void setUp() { checkConfig = createCheckConfig(OperatorWrapCheck.class); } @Test public void testDefault() throws Exception { final String[] expected = { "15:19: '+' should be on a new line.", "16:15: '-' should be on a new line.", "24:18: '&&' should be on a new line.", }; verify(checkConfig, getPath("InputOpWrap.java"), expected); } @Test public void testOpWrapEOL() throws Exception { checkConfig.addAttribute("option", OperatorWrapOption.EOL.toString()); final String[] expected = { "18:13: '-' should be on the previous line.", "22:13: '&&' should be on the previous line.", "27:13: '&&' should be on the previous line.", }; verify(checkConfig, getPath("InputOpWrap.java"), expected); } @Test public void testAssignEOL() throws Exception { checkConfig.addAttribute("tokens", "ASSIGN"); checkConfig.addAttribute("option", OperatorWrapOption.EOL.toString()); final String[] expected = { "33:13: '=' should be on the previous line.", }; verify(checkConfig, getPath("InputOpWrap.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheckTest.java100644 0 0 13440 12026050735 30635 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class ParenPadCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParenPadCheck.class); final String[] expected = { "58:12: '(' is followed by whitespace.", "58:36: ')' is preceded with whitespace.", "74:13: '(' is followed by whitespace.", "74:18: ')' is preceded with whitespace.", "232:27: ')' is preceded with whitespace.", "241:24: '(' is followed by whitespace.", "241:30: ')' is preceded with whitespace.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } @Test public void testSpace() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParenPadCheck.class); checkConfig.addAttribute("option", PadOption.SPACE.toString()); final String[] expected = { "29:20: '(' is not followed by whitespace.", "29:23: ')' is not preceded with whitespace.", "37:22: '(' is not followed by whitespace.", "37:26: ')' is not preceded with whitespace.", "41:15: '(' is not followed by whitespace.", "41:33: ')' is not preceded with whitespace.", "76:20: '(' is not followed by whitespace.", "76:21: ')' is not preceded with whitespace.", "97:22: '(' is not followed by whitespace.", "97:28: ')' is not preceded with whitespace.", "98:14: '(' is not followed by whitespace.", "98:18: ')' is not preceded with whitespace.", "150:28: '(' is not followed by whitespace.", "150:32: ')' is not preceded with whitespace.", "153:16: '(' is not followed by whitespace.", "153:20: ')' is not preceded with whitespace.", "160:21: '(' is not followed by whitespace.", "160:34: ')' is not preceded with whitespace.", "162:20: '(' is not followed by whitespace.", "165:10: ')' is not preceded with whitespace.", "178:14: '(' is not followed by whitespace.", "178:36: ')' is not preceded with whitespace.", "225:14: '(' is not followed by whitespace.", "235:14: '(' is not followed by whitespace.", "235:39: ')' is not preceded with whitespace.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } @Test public void testDefaultForIterator() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParenPadCheck.class); final String[] expected = { "17:34: ')' is preceded with whitespace.", "20:35: ')' is preceded with whitespace.", "40:14: '(' is followed by whitespace.", "40:36: ')' is preceded with whitespace.", "43:14: '(' is followed by whitespace.", "48:27: ')' is preceded with whitespace.", "51:26: ')' is preceded with whitespace.", }; verify(checkConfig, getPath("InputForWhitespace.java"), expected); } @Test public void testSpaceEmptyForIterator() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParenPadCheck.class); checkConfig.addAttribute("option", PadOption.SPACE.toString()); final String[] expected = { "11:14: '(' is not followed by whitespace.", "11:35: ')' is not preceded with whitespace.", "14:14: '(' is not followed by whitespace.", "14:34: ')' is not preceded with whitespace.", "17:14: '(' is not followed by whitespace.", "20:14: '(' is not followed by whitespace.", "23:14: '(' is not followed by whitespace.", "27:14: '(' is not followed by whitespace.", "32:14: '(' is not followed by whitespace.", }; verify(checkConfig, getPath("InputForWhitespace.java"), expected); } @Test public void test1322879() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ParenPadCheck.class); checkConfig.addAttribute("option", PadOption.SPACE.toString()); final String[] expected = { }; verify(checkConfig, getPath("whitespace/InputWhitespaceAround.java"), expected); } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/TypecastParenPadCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/TypecastParenPadCheckTest100644 0 0 5720 12026050735 31414 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class TypecastParenPadCheckTest extends BaseCheckTestSupport { @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(TypecastParenPadCheck.class); final String[] expected = { "89:14: '(' is followed by whitespace.", "89:21: ')' is preceded with whitespace.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } @Test public void testSpace() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(TypecastParenPadCheck.class); checkConfig.addAttribute("option", PadOption.SPACE.toString()); final String[] expected = { "87:21: '(' is not followed by whitespace.", "87:27: ')' is not preceded with whitespace.", "88:14: '(' is not followed by whitespace.", "88:20: ')' is not preceded with whitespace.", "90:14: '(' is not followed by whitespace.", "90:20: ')' is not preceded with whitespace.", "241:18: '(' is not followed by whitespace.", "241:21: ')' is not preceded with whitespace.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } @Test public void test1322879() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(TypecastParenPadCheck.class); checkConfig.addAttribute("option", PadOption.SPACE.toString()); final String[] expected = { }; verify(checkConfig, getPath("whitespace/InputWhitespaceAround.java"), expected); } } ././@LongLink100644 0 0 151 12026055133 10245 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheckTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheckTest.100644 0 0 6513 12026050735 31342 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class WhitespaceAfterCheckTest extends BaseCheckTestSupport { private DefaultConfiguration mCheckConfig; @Before public void setUp() { mCheckConfig = createCheckConfig(WhitespaceAfterCheck.class); } @Test public void testDefault() throws Exception { final String[] expected = { "42:40: ',' is not followed by whitespace.", "71:30: ',' is not followed by whitespace.", }; verify(mCheckConfig, getPath("InputSimple.java"), expected); } @Test public void testCast() throws Exception { final String[] expected = { "88:21: 'cast' is not followed by whitespace.", }; verify(mCheckConfig, getPath("InputWhitespace.java"), expected); } @Test public void testSemi() throws Exception { final String[] expected = { "58:23: ';' is not followed by whitespace.", "58:29: ';' is not followed by whitespace.", "107:19: ';' is not followed by whitespace.", }; verify(mCheckConfig, getPath("InputBraces.java"), expected); } @Test public void testEmptyForIterator() throws Exception { final String[] expected = { "14:31: ';' is not followed by whitespace.", "17:31: ';' is not followed by whitespace.", }; verify(mCheckConfig, getPath("InputForWhitespace.java"), expected); } @Test public void testTypeArgumentAndParameterCommas() throws Exception { final String[] expected = { "11:21: ',' is not followed by whitespace.", "11:23: ',' is not followed by whitespace.", "11:41: ',' is not followed by whitespace.", }; verify(mCheckConfig, getPath("InputGenerics.java"), expected); } @Test public void test1322879() throws Exception { final String[] expected = { }; verify(mCheckConfig, getPath("whitespace/InputWhitespaceAround.java"), expected); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAroundTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAroundTest.java100644 0 0 14505 12026050734 31454 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.whitespace; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Before; import org.junit.Test; public class WhitespaceAroundTest extends BaseCheckTestSupport { private DefaultConfiguration checkConfig; @Before public void setUp() { checkConfig = createCheckConfig(WhitespaceAroundCheck.class); } @Test public void testIt() throws Exception { final String[] expected = { "16:22: '=' is not preceded with whitespace.", "16:23: '=' is not followed by whitespace.", "18:24: '=' is not followed by whitespace.", "26:14: '=' is not preceded with whitespace.", "27:10: '=' is not preceded with whitespace.", "27:11: '=' is not followed by whitespace.", "28:10: '+=' is not preceded with whitespace.", "28:12: '+=' is not followed by whitespace.", "29:13: '-=' is not followed by whitespace.", "37:21: 'synchronized' is not followed by whitespace.", "39:12: 'try' is not followed by whitespace.", "39:12: '{' is not preceded with whitespace.", "41:14: 'catch' is not followed by whitespace.", "41:34: '{' is not preceded with whitespace.", "58:11: 'if' is not followed by whitespace.", "76:19: 'return' is not followed by whitespace.", "97:29: '?' is not preceded with whitespace.", "97:30: '?' is not followed by whitespace.", "97:34: ':' is not preceded with whitespace.", "97:35: ':' is not followed by whitespace.", "98:15: '==' is not preceded with whitespace.", "98:17: '==' is not followed by whitespace.", "104:20: '*' is not followed by whitespace.", "104:21: '*' is not preceded with whitespace.", "119:18: '%' is not preceded with whitespace.", "120:20: '%' is not followed by whitespace.", "121:18: '%' is not preceded with whitespace.", "121:19: '%' is not followed by whitespace.", "123:18: '/' is not preceded with whitespace.", "124:20: '/' is not followed by whitespace.", "125:18: '/' is not preceded with whitespace.", "125:19: '/' is not followed by whitespace.", "153:15: 'assert' is not followed by whitespace.", "156:20: ':' is not preceded with whitespace.", "156:21: ':' is not followed by whitespace.", }; verify(checkConfig, getPath("InputWhitespace.java"), expected); } @Test public void testIt2() throws Exception { final String[] expected = { "153:27: '=' is not followed by whitespace.", "154:27: '=' is not followed by whitespace.", "155:27: '=' is not followed by whitespace.", "156:27: '=' is not followed by whitespace.", "157:27: '=' is not followed by whitespace.", "158:27: '=' is not followed by whitespace.", }; verify(checkConfig, getPath("InputSimple.java"), expected); } @Test public void testIt3() throws Exception { final String[] expected = { "41:14: 'while' is not followed by whitespace.", "58:12: 'for' is not followed by whitespace.", // + ":58:23: ';' is not followed by whitespace.", // + ":58:29: ';' is not followed by whitespace.", "115:27: '{' is not followed by whitespace.", "115:27: '}' is not preceded with whitespace.", "118:40: '{' is not followed by whitespace.", "118:40: '}' is not preceded with whitespace.", }; verify(checkConfig, getPath("InputBraces.java"), expected); } @Test public void testIt4() throws Exception { checkConfig.addAttribute("allowEmptyMethods", "true"); checkConfig.addAttribute("allowEmptyConstructors", "true"); final String[] expected = { "41:14: 'while' is not followed by whitespace.", "58:12: 'for' is not followed by whitespace.", }; verify(checkConfig, getPath("InputBraces.java"), expected); } @Test public void testGenericsTokensAreFlagged() throws Exception { final String[] expected = { "6:67: '&' is not preceded with whitespace.", "6:68: '&' is not followed by whitespace.", }; verify(checkConfig, getPath("InputGenerics.java"), expected); } @Test public void test1322879And1649038() throws Exception { final String[] expected = { }; verify(checkConfig, getPath("whitespace/InputWhitespaceAround.java"), expected); } @Test public void testIgnoreEnhancedForColon() throws Exception { checkConfig.addAttribute("ignoreEnhancedForColon", "false"); final String[] expected = { "18:20: ':' is not preceded with whitespace.", }; verify(checkConfig, getPath("whitespace/InputWhitespaceAround.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java100644 0 0 27745 12026050777 26572 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import org.junit.Test; import java.io.File; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * @author Rick Giles * @author lkuehne */ public class ConfigurationLoaderTest { private Configuration loadConfiguration(String aName) throws CheckstyleException { return loadConfiguration(aName, new Properties()); } private Configuration loadConfiguration( String aName, Properties aProps) throws CheckstyleException { final String fName = System.getProperty("testinputs.dir") + "/configs/" + aName; return ConfigurationLoader.loadConfiguration( fName, new PropertiesExpander(aProps)); } @Test public void testResourceLoadConfiguration() throws Exception { // load config that's only found in the classpath final DefaultConfiguration config = (DefaultConfiguration) ConfigurationLoader.loadConfiguration( "/checkstyle/checkstyle_checks.xml", new PropertiesExpander(new Properties())); verifyConfigNode(config, "Checker", 3, new Properties()); } @Test public void testEmptyConfiguration() throws Exception { final DefaultConfiguration config = (DefaultConfiguration) loadConfiguration("empty_configuration.xml"); verifyConfigNode(config, "Checker", 0, new Properties()); } @Test public void testMissingPropertyName() { try { loadConfiguration("missing_property_name.xml"); fail("missing property name"); } catch (CheckstyleException ex) { assertTrue( ex.getMessage().endsWith( "Attribute \"name\" is required and must be specified " + "for element type \"property\".:8:41")); } } @Test public void testMissingPropertyValue() { try { loadConfiguration("missing_property_value.xml"); fail("missing property value"); } catch (CheckstyleException ex) { assertTrue( ex.getMessage().endsWith( "Attribute \"value\" is required and must be specified " + "for element type \"property\".:8:41")); } } @Test public void testMissingConfigName() { try { loadConfiguration("missing_config_name.xml"); fail("missing module name"); } catch (CheckstyleException ex) { assertTrue( ex.getMessage().endsWith( "Attribute \"name\" is required and must be specified " + "for element type \"module\".:7:23")); } } @Test public void testMissingConfigParent() { try { loadConfiguration("missing_config_parent.xml"); fail("missing module parent"); } catch (CheckstyleException ex) { assertTrue( ex.getMessage().endsWith( "Document root element \"property\", must match DOCTYPE " + "root \"module\".:7:38")); } } @Test public void testCheckstyleChecks() throws Exception { final Properties props = new Properties(); props.put("checkstyle.basedir", "basedir"); final DefaultConfiguration config = (DefaultConfiguration) loadConfiguration( "checkstyle_checks.xml", props); //verify the root, and property substitution final Properties atts = new Properties(); atts.put("tabWidth", "4"); atts.put("basedir", "basedir"); verifyConfigNode(config, "Checker", 3, atts); //verify children final Configuration[] children = config.getChildren(); atts.clear(); verifyConfigNode( (DefaultConfiguration) children[1], "JavadocPackage", 0, atts); verifyConfigNode( (DefaultConfiguration) children[2], "Translation", 0, atts); atts.put("testName", "testValue"); verifyConfigNode( (DefaultConfiguration) children[0], "TreeWalker", 8, atts); //verify TreeWalker's first, last, NoWhitespaceAfterCheck final Configuration[] grandchildren = children[0].getChildren(); atts.clear(); verifyConfigNode( (DefaultConfiguration) grandchildren[0], "AvoidStarImport", 0, atts); atts.put("format", "System.out.println"); verifyConfigNode( (DefaultConfiguration) grandchildren[grandchildren.length - 1], "GenericIllegalRegexp", 0, atts); atts.clear(); atts.put("tokens", "DOT"); atts.put("allowLineBreaks", "true"); verifyConfigNode( (DefaultConfiguration) grandchildren[6], "NoWhitespaceAfter", 0, atts); } @Test public void testCustomMessages() throws CheckstyleException { final Properties props = new Properties(); props.put("checkstyle.basedir", "basedir"); final DefaultConfiguration config = (DefaultConfiguration) loadConfiguration( "custom_messages.xml", props); final Configuration[] children = config.getChildren(); final Configuration[] grandchildren = children[0].getChildren(); assertTrue(((DefaultConfiguration) grandchildren[0]).getMessages() .containsKey("name.invalidPattern")); } private void verifyConfigNode( DefaultConfiguration aConfig, String aName, int aChildrenLength, Properties atts) throws Exception { assertEquals("name.", aName, aConfig.getName()); assertEquals( "children.length.", aChildrenLength, aConfig.getChildren().length); final String[] attNames = aConfig.getAttributeNames(); assertEquals("attributes.length", atts.size(), attNames.length); for (int i = 0; i < attNames.length; i++) { assertEquals( "attribute[" + attNames[i] + "]", atts.get(attNames[i]), aConfig.getAttribute(attNames[i])); } } @Test public void testReplacePropertiesNoReplace() throws CheckstyleException { final String[] testValues = {null, "", "a", "$a", "{a", "{a}", "a}", "$a}", "$", "a$b", }; final Properties props = initProperties(); for (int i = 0; i < testValues.length; i++) { final String value = ConfigurationLoader.replaceProperties( testValues[i], new PropertiesExpander(props), null); assertEquals("\"" + testValues[i] + "\"", value, testValues[i]); } } @Test public void testReplacePropertiesSyntaxError() { final Properties props = initProperties(); try { final String value = ConfigurationLoader.replaceProperties( "${a", new PropertiesExpander(props), null); fail("expected to fail, instead got: " + value); } catch (CheckstyleException ex) { assertEquals("Syntax error in property: ${a", ex.getMessage()); } } @Test public void testReplacePropertiesMissingProperty() { final Properties props = initProperties(); try { final String value = ConfigurationLoader.replaceProperties( "${c}", new PropertiesExpander(props), null); fail("expected to fail, instead got: " + value); } catch (CheckstyleException ex) { assertEquals("Property ${c} has not been set", ex.getMessage()); } } @Test public void testReplacePropertiesReplace() throws CheckstyleException { final String[][] testValues = { {"${a}", "A"}, {"x${a}", "xA"}, {"${a}x", "Ax"}, {"${a}${b}", "AB"}, {"x${a}${b}", "xAB"}, {"${a}x${b}", "AxB"}, {"${a}${b}x", "ABx"}, {"x${a}y${b}", "xAyB"}, {"${a}x${b}y", "AxBy"}, {"x${a}${b}y", "xABy"}, {"x${a}y${b}z", "xAyBz"}, {"$$", "$"}, }; final Properties props = initProperties(); for (int i = 0; i < testValues.length; i++) { final String value = ConfigurationLoader.replaceProperties( testValues[i][0], new PropertiesExpander(props), null); assertEquals("\"" + testValues[i][0] + "\"", testValues[i][1], value); } } private Properties initProperties() { final Properties props = new Properties(); props.put("a", "A"); props.put("b", "B"); return props; } @Test public void testExternalEntity() throws Exception { final Properties props = new Properties(); props.put("checkstyle.basedir", "basedir"); final DefaultConfiguration config = (DefaultConfiguration) loadConfiguration( "including.xml", props); final Properties atts = new Properties(); atts.put("tabWidth", "4"); atts.put("basedir", "basedir"); verifyConfigNode(config, "Checker", 2, atts); } @Test public void testExternalEntitySubdir() throws Exception { final Properties props = new Properties(); props.put("checkstyle.basedir", "basedir"); final DefaultConfiguration config = (DefaultConfiguration) loadConfiguration( "subdir/including.xml", props); final Properties atts = new Properties(); atts.put("tabWidth", "4"); atts.put("basedir", "basedir"); verifyConfigNode(config, "Checker", 2, atts); } @Test public void testExternalEntityFromURI() throws Exception { final Properties props = new Properties(); props.put("checkstyle.basedir", "basedir"); final File file = new File(System.getProperty("testinputs.dir") + "/configs/subdir/including.xml"); final DefaultConfiguration config = (DefaultConfiguration) ConfigurationLoader.loadConfiguration( file.toURI().toString(), new PropertiesExpander(props)); final Properties atts = new Properties(); atts.put("tabWidth", "4"); atts.put("basedir", "basedir"); verifyConfigNode(config, "Checker", 2, atts); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/DebugAuditAdapter.java100644 0 0 2401 11453016761 25246 0ustar 0 0 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AuditListener; class DebugAuditAdapter implements AuditListener { /** keeps track of the number of errors */ private boolean mCalled; public boolean wasCalled() { return mCalled; } public void resetListener() { mCalled = false; } /** @see AuditListener */ public void addError(AuditEvent aEvt) { mCalled = true; } /** @see AuditListener */ public void addException(AuditEvent aEvt, Throwable aThrowable) { mCalled = true; } /** @see AuditListener */ public void auditStarted(AuditEvent aEvt) { mCalled = true; } /** @see AuditListener */ public void fileStarted(AuditEvent aEvt) { mCalled = true; } /** @see AuditListener */ public void auditFinished(AuditEvent aEvt) { mCalled = true; } /** @see AuditListener */ public void fileFinished(AuditEvent aEvt) { mCalled = true; } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/DebugChecker.java100644 0 0 1025 11453016761 24244 0ustar 0 0 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; class DebugChecker extends Checker { public DebugChecker() throws CheckstyleException { } @Override public void fireAuditFinished() { super.fireAuditFinished(); } @Override public void fireAuditStarted() { super.fireAuditStarted(); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/DebugFilter.java100644 0 0 1114 11453016761 24124 0ustar 0 0 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.puppycrawl.tools.checkstyle; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.Filter; class DebugFilter implements Filter { private boolean mCalled; public boolean accept(AuditEvent aEvent) { mCalled = true; return true; } public boolean wasCalled() { return mCalled; } public void resetFilter() { mCalled = false; } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/filters/CSVFilterTest.java100644 0 0 6577 12026050734 26056 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** Tests CSVFilter */ public class CSVFilterTest { @Test public void testDecideSingle() { final IntFilter filter = new CSVFilter("0"); assertFalse("less than", filter.accept(Integer.valueOf(-1))); assertTrue("equal", filter.accept(Integer.valueOf(0))); assertFalse("greater than", filter.accept(Integer.valueOf(1))); } @Test public void testDecidePair() { final IntFilter filter = new CSVFilter("0, 2"); assertFalse("less than", filter.accept(Integer.valueOf(-1))); assertTrue("equal 0", filter.accept(Integer.valueOf(0))); assertFalse("greater than", filter.accept(Integer.valueOf(1))); assertTrue("equal 2", filter.accept(Integer.valueOf(2))); } @Test public void testDecideRange() { final IntFilter filter = new CSVFilter("0-2"); assertFalse("less than", filter.accept(Integer.valueOf(-1))); assertTrue("equal 0", filter.accept(Integer.valueOf(0))); assertTrue("equal 1", filter.accept(Integer.valueOf(1))); assertTrue("equal 2", filter.accept(Integer.valueOf(2))); assertFalse("greater than", filter.accept(Integer.valueOf(3))); } @Test public void testDecideEmptyRange() { final IntFilter filter = new CSVFilter("2-0"); assertFalse("less than", filter.accept(Integer.valueOf(-1))); assertFalse("equal 0", filter.accept(Integer.valueOf(0))); assertFalse("equal 1", filter.accept(Integer.valueOf(1))); assertFalse("equal 2", filter.accept(Integer.valueOf(2))); assertFalse("greater than", filter.accept(Integer.valueOf(3))); } @Test public void testDecideRangePlusValue() { final IntFilter filter = new CSVFilter("0-2, 10"); assertFalse("less than", filter.accept(Integer.valueOf(-1))); assertTrue("equal 0", filter.accept(Integer.valueOf(0))); assertTrue("equal 1", filter.accept(Integer.valueOf(1))); assertTrue("equal 2", filter.accept(Integer.valueOf(2))); assertFalse("greater than", filter.accept(Integer.valueOf(3))); assertTrue("equal 10", filter.accept(Integer.valueOf(10))); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/filters/FilterSetTest.java100644 0 0 4274 12026050734 26146 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; /** Tests SuppressElementFilter */ // TODO: this test should be removed/rewritten public class FilterSetTest { private CSVFilter filter; @Before public void setUp() { filter = new CSVFilter(""); } @Test public void testEmptyChain() { assertFalse("0", filter.accept(Integer.valueOf(0))); } @Test public void testOneFilter() { filter.addFilter(new IntMatchFilter(0)); assertTrue("0", filter.accept(Integer.valueOf(0))); assertFalse("1", filter.accept(Integer.valueOf(1))); } @Test public void testMultipleFilter() { filter.addFilter(new IntMatchFilter(0)); filter.addFilter(new IntRangeFilter(0, 2)); assertTrue("0", filter.accept(Integer.valueOf(0))); assertTrue("1", filter.accept(Integer.valueOf(1))); filter.addFilter(new IntRangeFilter(3, 4)); assertTrue("0 is in [3,4]", filter.accept(Integer.valueOf(0))); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/filters/IntMatchFilterTest.java100644 0 0 4034 12026050734 27114 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** Tests IntMatchFilter */ public class IntMatchFilterTest { @Test public void testDecide() { final IntFilter filter = new IntMatchFilter(0); assertFalse("less than", filter.accept(Integer.valueOf(-1))); assertTrue("equal", filter.accept(Integer.valueOf(0))); assertFalse("greater than", filter.accept(Integer.valueOf(1))); } @Test public void testEquals() { final IntFilter filter = new IntMatchFilter(0); final IntFilter filter2 = new IntMatchFilter(0); final IntFilter filter3 = new IntMatchFilter(1); assertEquals("0", filter, filter2); assertFalse("0 != 1", filter.equals(filter3)); assertFalse("0 != this", filter.equals(this)); assertFalse("0 != null", filter.equals(null)); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/filters/IntRangeFilterTest.java100644 0 0 6135 12026050734 27120 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** Tests IntRangeFilter */ public class IntRangeFilterTest { @Test public void testDecide() { final IntFilter filter = new IntRangeFilter(0, 10); assertFalse("less than", filter.accept(Integer.valueOf(-1))); assertTrue("in range", filter.accept(Integer.valueOf(0))); assertTrue("in range", filter.accept(Integer.valueOf(5))); assertTrue("in range", filter.accept(Integer.valueOf(10))); assertFalse("greater than", filter.accept(Integer.valueOf(11))); } @Test public void testDecideSingle() { final IntFilter filter = new IntRangeFilter(0, 0); assertFalse("less than", filter.accept(Integer.valueOf(-1))); assertTrue("in range", filter.accept(Integer.valueOf(0))); assertFalse("greater than", filter.accept(Integer.valueOf(1))); } @Test public void testDecideEmpty() { final IntFilter filter = new IntRangeFilter(10, 0); assertFalse("out", filter.accept(Integer.valueOf(-1))); assertFalse("out", filter.accept(Integer.valueOf(0))); assertFalse("out", filter.accept(Integer.valueOf(5))); assertFalse("out", filter.accept(Integer.valueOf(10))); assertFalse("out", filter.accept(Integer.valueOf(11))); } @Test public void testEquals() { final IntFilter filter = new IntRangeFilter(0, 2); final IntFilter filter2 = new IntRangeFilter(0, 2); final IntFilter filter3 = new IntRangeFilter(0, 1); final IntFilter filter4 = new IntRangeFilter(1, 2); assertEquals("[0,2] == [0,2]", filter, filter2); assertFalse("[0,2] != [0,1]", filter.equals(filter3)); assertFalse("[0,2] != [1,2]", filter.equals(filter4)); assertFalse("[0,2] != this", filter.equals(this)); assertFalse("[0,2] != null", filter.equals(null)); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilterTest.java100644 0 0 10107 12026050733 30211 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import org.junit.Test; /** Tests SeverityMatchFilter */ public class SeverityMatchFilterTest { private final SeverityMatchFilter filter = new SeverityMatchFilter(); @Test public void testDefault() { final AuditEvent ev = new AuditEvent(this, "Test.java"); assertFalse("no message", filter.accept(ev)); SeverityLevel level = SeverityLevel.ERROR; LocalizedMessage message = new LocalizedMessage(0, 0, "", "", null, level, null, this.getClass(), null); final AuditEvent ev2 = new AuditEvent(this, "ATest.java", message); assertTrue("level:" + level, filter.accept(ev2)); level = SeverityLevel.INFO; message = new LocalizedMessage(0, 0, "", "", null, level, null, this .getClass(), null); final AuditEvent ev3 = new AuditEvent(this, "ATest.java", message); assertFalse("level:" + level, filter.accept(ev3)); } @Test public void testSeverity() { filter.setSeverity("info"); final AuditEvent ev = new AuditEvent(this, "Test.java"); // event with no message has severity level INFO assertTrue("no message", filter.accept(ev)); SeverityLevel level = SeverityLevel.ERROR; LocalizedMessage message = new LocalizedMessage(0, 0, "", "", null, level, null, this.getClass(), null); final AuditEvent ev2 = new AuditEvent(this, "ATest.java", message); assertFalse("level:" + level, filter.accept(ev2)); level = SeverityLevel.INFO; message = new LocalizedMessage(0, 0, "", "", null, level, null, this .getClass(), null); final AuditEvent ev3 = new AuditEvent(this, "ATest.java", message); assertTrue("level:" + level, filter.accept(ev3)); } @Test public void testAcceptOnMatch() { filter.setSeverity("info"); filter.setAcceptOnMatch(false); final AuditEvent ev = new AuditEvent(this, "Test.java"); // event with no message has severity level INFO assertFalse("no message", filter.accept(ev)); SeverityLevel level = SeverityLevel.ERROR; LocalizedMessage message = new LocalizedMessage(0, 0, "", "", null, level, null, this.getClass(), null); final AuditEvent ev2 = new AuditEvent(this, "ATest.java", message); assertTrue("level:" + level, filter.accept(ev2)); level = SeverityLevel.INFO; message = new LocalizedMessage(0, 0, "", "", null, level, null, this .getClass(), null); final AuditEvent ev3 = new AuditEvent(this, "ATest.java", message); assertFalse("level:" + level, filter.accept(ev3)); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/filters/SuppressElementTest.java100644 0 0 10632 12026050733 27415 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import java.util.regex.PatternSyntaxException; import org.junit.Before; import org.junit.Test; /** Tests SuppressElementFilter */ public class SuppressElementTest { private SuppressElement filter; @Before public void setUp() throws PatternSyntaxException { filter = new SuppressElement("Test"); filter.setChecks("Test"); } @Test public void testDecideDefault() { final AuditEvent ev = new AuditEvent(this, "Test.java"); assertTrue(ev.getFileName(), filter.accept(ev)); } @Test public void testDecideLocalizedMessage() { LocalizedMessage message = new LocalizedMessage(0, 0, "", "", null, null, this.getClass(), null); final AuditEvent ev = new AuditEvent(this, "ATest.java", message); //deny because there are matches on file and check names assertFalse("Names match", filter.accept(ev)); } @Test public void testDecideByLine() { LocalizedMessage message = new LocalizedMessage(10, 10, "", "", null, null, this.getClass(), null); final AuditEvent ev = new AuditEvent(this, "ATest.java", message); //deny because there are matches on file name, check name, and line filter.setLines("1-10"); assertFalse("In range 1-10", filter.accept(ev)); filter.setLines("1-9, 11"); assertTrue("Not in 1-9, 11", filter.accept(ev)); } @Test public void testDecideByColumn() { LocalizedMessage message = new LocalizedMessage(10, 10, "", "", null, null, this.getClass(), null); final AuditEvent ev = new AuditEvent(this, "ATest.java", message); //deny because there are matches on file name, check name, and column filter.setColumns("1-10"); assertFalse("In range 1-10", filter.accept(ev)); filter.setColumns("1-9, 11"); assertTrue("Not in 1-9, 1)", filter.accept(ev)); } @Test public void testEquals() throws PatternSyntaxException { final SuppressElement filter2 = new SuppressElement("Test"); filter2.setChecks("Test"); assertEquals("filter, filter2", filter, filter2); final SuppressElement filter3 = new SuppressElement("Test"); filter3.setChecks("Test3"); assertFalse("filter, filter3", filter.equals(filter3)); filter.setColumns("1-10"); assertFalse("filter, filter2", filter.equals(filter2)); filter2.setColumns("1-10"); assertEquals("filter, filter2", filter, filter2); filter.setColumns(null); assertFalse("filter, filter2", filter.equals(filter2)); filter2.setColumns(null); filter.setLines("3,4"); assertFalse("filter, filter2", filter.equals(filter2)); filter2.setLines("3,4"); assertEquals("filter, filter2", filter, filter2); filter.setColumns("1-10"); assertFalse("filter, filter2", filter.equals(filter2)); filter2.setColumns("1-10"); assertEquals("filter, filter2", filter, filter2); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilterTest.java100644 0 0 22704 12026050733 31305 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.Checker; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.TreeWalker; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.checks.FileContentsHolder; import com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck; import com.puppycrawl.tools.checkstyle.checks.naming.ConstantNameCheck; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import java.util.Arrays; import java.util.Collection; import java.util.Locale; import org.junit.Test; public class SuppressionCommentFilterTest extends BaseCheckTestSupport { private static String[] sAllMessages = { "13:17: Name 'I' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "16:17: Name 'J' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "19:17: Name 'K' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "22:17: Name 'L' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "23:30: Name 'm' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "27:17: Name 'M2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "28:30: Name 'n' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "32:17: Name 'P' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "35:17: Name 'Q' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "38:17: Name 'R' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "39:30: Name 's' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "43:17: Name 'T' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "64:23: Catching 'Exception' is not allowed.", "71:11: Catching 'Exception' is not allowed.", }; @Test public void testNone() throws Exception { final DefaultConfiguration filterConfig = null; final String[] suppressed = { }; verifySuppressed(filterConfig, suppressed); } //Supress all checks between default comments @Test public void testDefault() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressionCommentFilter.class); final String[] suppressed = { "16:17: Name 'J' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "43:17: Name 'T' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "64:23: Catching 'Exception' is not allowed.", "71:11: Catching 'Exception' is not allowed.", }; verifySuppressed(filterConfig, suppressed); } @Test public void testCheckC() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressionCommentFilter.class); filterConfig.addAttribute("checkC", "false"); final String[] suppressed = { "43:17: Name 'T' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "64:23: Catching 'Exception' is not allowed.", "71:11: Catching 'Exception' is not allowed.", }; verifySuppressed(filterConfig, suppressed); } @Test public void testCheckCPP() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressionCommentFilter.class); filterConfig.addAttribute("checkCPP", "false"); final String[] suppressed = { "16:17: Name 'J' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verifySuppressed(filterConfig, suppressed); } //Supress all checks between CS_OFF and CS_ON @Test public void testOffFormat() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressionCommentFilter.class); filterConfig.addAttribute("offCommentFormat", "CS_OFF"); filterConfig.addAttribute("onCommentFormat", "CS_ON"); final String[] suppressed = { "32:17: Name 'P' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "38:17: Name 'R' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "39:30: Name 's' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "42:17: Name 'T' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verifySuppressed(filterConfig, suppressed); } //Test supression of checks of only one type //Supress only ConstantNameCheck between CS_OFF and CS_ON @Test public void testOffFormatCheck() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressionCommentFilter.class); filterConfig.addAttribute("offCommentFormat", "CS_OFF"); filterConfig.addAttribute("onCommentFormat", "CS_ON"); filterConfig.addAttribute("checkFormat", "ConstantNameCheck"); final String[] suppressed = { "39:30: Name 's' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", }; verifySuppressed(filterConfig, suppressed); } @Test public void testExpansion() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressionCommentFilter.class); filterConfig.addAttribute("offCommentFormat", "CSOFF\\: ([\\w\\|]+)"); filterConfig.addAttribute("onCommentFormat", "CSON\\: ([\\w\\|]+)"); filterConfig.addAttribute("checkFormat", "$1"); final String[] suppressed = { "22:17: Name 'L' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "23:30: Name 'm' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "28:30: Name 'n' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", }; verifySuppressed(filterConfig, suppressed); } @Test public void testMessage() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressionCommentFilter.class); filterConfig.addAttribute("onCommentFormat", "UNUSED ON\\: (\\w+)"); filterConfig.addAttribute("offCommentFormat", "UNUSED OFF\\: (\\w+)"); filterConfig.addAttribute("checkFormat", "Unused"); filterConfig.addAttribute("messageFormat", "^Unused \\w+ '$1'.$"); final String[] suppressed = { "47:34: Unused parameter 'aInt'.", }; verifySuppressed(filterConfig, suppressed); } public static DefaultConfiguration createFilterConfig(Class aClass) { return new DefaultConfiguration(aClass.getName()); } protected void verifySuppressed(Configuration aFilterConfig, String[] aSuppressed) throws Exception { verify(createChecker(aFilterConfig), getPath("filters/InputSuppressionCommentFilter.java"), removeSuppressed(sAllMessages, aSuppressed)); } @Override protected Checker createChecker(Configuration aFilterConfig) throws CheckstyleException { final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration"); final DefaultConfiguration checksConfig = createCheckConfig(TreeWalker.class); checksConfig.addChild(createCheckConfig(FileContentsHolder.class)); checksConfig.addChild(createCheckConfig(MemberNameCheck.class)); checksConfig.addChild(createCheckConfig(ConstantNameCheck.class)); checksConfig.addChild(createCheckConfig(IllegalCatchCheck.class)); checkerConfig.addChild(checksConfig); if (aFilterConfig != null) { checkerConfig.addChild(aFilterConfig); } final Checker checker = new Checker(); final Locale locale = Locale.ENGLISH; checker.setLocaleCountry(locale.getCountry()); checker.setLocaleLanguage(locale.getLanguage()); checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); checker.configure(checkerConfig); checker.addListener(new BriefLogger(mStream)); return checker; } private String[] removeSuppressed(String[] aFrom, String[] aRemove) { final Collection coll = Lists.newArrayList(Arrays.asList(aFrom)); coll.removeAll(Arrays.asList(aRemove)); return coll.toArray(new String[coll.size()]); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java100644 0 0 12435 12026050732 30125 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.FilterSet; import java.util.regex.PatternSyntaxException; import org.junit.Test; /** * Tests SuppressionsLoader. * @author Rick Giles */ public class SuppressionsLoaderTest { @Test public void testResourceLoadSuppressions() throws CheckstyleException { final FilterSet fc = SuppressionsLoader.loadSuppressions( "/checkstyle/suppressions.xml"); final FilterSet fc2 = new FilterSet(); assertEquals(fc, fc2); } @Test public void testNoSuppressions() throws CheckstyleException { final FilterSet fc = SuppressionsLoader.loadSuppressions( System.getProperty("testinputs.dir") + "/suppressions_none.xml"); final FilterSet fc2 = new FilterSet(); assertEquals(fc, fc2); } @Test public void testLoadFromURL() throws CheckstyleException { final FilterSet fc = SuppressionsLoader.loadSuppressions("http://checkstyle.hg.sourceforge.net/hgweb/checkstyle/checkstyle/raw-file/055e288619a5/src/testinputs/com/puppycrawl/tools/checkstyle/suppressions_none.xml"); final FilterSet fc2 = new FilterSet(); assertEquals(fc, fc2); } @Test(expected = CheckstyleException.class) public void testLoadFromMalformedURL() throws CheckstyleException { SuppressionsLoader.loadSuppressions("http"); } @Test(expected = CheckstyleException.class) public void testLoadFromNonExistingURL() throws CheckstyleException { SuppressionsLoader.loadSuppressions("http://^%$^* %&% %^&"); } @Test public void testMultipleSuppression() throws CheckstyleException, PatternSyntaxException { final FilterSet fc = SuppressionsLoader.loadSuppressions( System.getProperty("testinputs.dir") + "/suppressions_multiple.xml"); final FilterSet fc2 = new FilterSet(); SuppressElement se0 = new SuppressElement("file0"); se0.setChecks("check0"); fc2.addFilter(se0); SuppressElement se1 = new SuppressElement("file1"); se1.setChecks("check1"); se1.setLines("1,2-3"); fc2.addFilter(se1); SuppressElement se2 = new SuppressElement("file2"); se2.setChecks("check2"); se2.setColumns("1,2-3"); fc2.addFilter(se2); SuppressElement se3 = new SuppressElement("file3"); se3.setChecks("check3"); se3.setLines("1,2-3"); se3.setColumns("1,2-3"); fc2.addFilter(se3); assertEquals(fc, fc2); } @Test public void testNoFile() { final String fn = System.getProperty("testinputs.dir") + "/suppressions_no_file.xml"; try { SuppressionsLoader.loadSuppressions(fn); } catch (CheckstyleException ex) { assertEquals( "unable to parse " + fn + " - Attribute \"files\" is required and must be specified for element type \"suppress\".", ex.getMessage()); } } @Test public void testNoCheck() { final String fn = System.getProperty("testinputs.dir") + "/suppressions_no_check.xml"; try { SuppressionsLoader.loadSuppressions(fn); } catch (CheckstyleException ex) { assertEquals( "unable to parse " + fn + " - Attribute \"checks\" is required and must be specified for element type \"suppress\".", ex.getMessage()); } } @Test public void testBadInt() { final String fn = System.getProperty("testinputs.dir") + "/suppressions_bad_int.xml"; try { SuppressionsLoader.loadSuppressions(fn); } catch (CheckstyleException ex) { assertTrue( ex.getMessage(), ex.getMessage().startsWith("number format exception " + fn + " - ")); } } } ././@LongLink100644 0 0 152 12026055133 10246 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilterTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilterTest100644 0 0 24601 12026050733 31652 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.filters; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.Checker; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.TreeWalker; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.checks.FileContentsHolder; import com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck; import com.puppycrawl.tools.checkstyle.checks.naming.ConstantNameCheck; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import java.util.Arrays; import java.util.Collection; import java.util.Locale; import org.junit.Test; public class SuppressWithNearbyCommentFilterTest extends BaseCheckTestSupport { private static String[] sAllMessages = { "14:17: Name 'A1' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "15:17: Name 'A2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "16:59: Name 'A3' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "18:17: Name 'B1' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "19:17: Name 'B2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "20:59: Name 'B3' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "22:17: Name 'C1' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "24:17: Name 'C2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "25:17: Name 'C3' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "27:17: Name 'D1' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "28:17: Name 'D2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "30:17: Name 'D3' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "32:30: Name 'e1' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "33:17: Name 'E2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "34:17: Name 'E3' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "35:30: Name 'e4' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "36:17: Name 'E5' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "37:30: Name 'e6' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "38:17: Name 'E7' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "39:17: Name 'E8' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "40:30: Name 'e9' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "64:23: Catching 'Exception' is not allowed.", "66:23: Catching 'Throwable' is not allowed.", "73:11: Catching 'Exception' is not allowed.", }; @Test public void testNone() throws Exception { final DefaultConfiguration filterConfig = null; final String[] suppressed = { }; verifySuppressed(filterConfig, suppressed); } @Test public void testDefault() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressWithNearbyCommentFilter.class); final String[] suppressed = { "14:17: Name 'A1' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "15:17: Name 'A2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "16:59: Name 'A3' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "18:17: Name 'B1' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "19:17: Name 'B2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "20:59: Name 'B3' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verifySuppressed(filterConfig, suppressed); } @Test public void testCheckC() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressWithNearbyCommentFilter.class); filterConfig.addAttribute("checkC", "false"); final String[] suppressed = { "14:17: Name 'A1' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "18:17: Name 'B1' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verifySuppressed(filterConfig, suppressed); } @Test public void testCheckCPP() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressWithNearbyCommentFilter.class); filterConfig.addAttribute("checkCPP", "false"); final String[] suppressed = { "15:17: Name 'A2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "16:59: Name 'A3' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "19:17: Name 'B2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "20:59: Name 'B3' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verifySuppressed(filterConfig, suppressed); } @Test public void testUsingAVariableMessage() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressWithNearbyCommentFilter.class); filterConfig.addAttribute("commentFormat", "ALLOW CATCH (\\w+) BECAUSE"); filterConfig.addAttribute("checkFormat", "IllegalCatchCheck"); filterConfig.addAttribute("messageFormat", "$1"); filterConfig.addAttribute("influenceFormat", "-1"); final String[] suppressed = { "66:23: Catching 'Throwable' is not allowed.", "73:11: Catching 'Exception' is not allowed.", }; verifySuppressed(filterConfig, suppressed); } @Test public void testUsingAVariableCheckOnNextLine() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressWithNearbyCommentFilter.class); filterConfig.addAttribute("commentFormat", "ALLOW (\\w+) ON NEXT LINE"); filterConfig.addAttribute("checkFormat", "$1"); filterConfig.addAttribute("influenceFormat", "1"); final String[] suppressed = { "24:17: Name 'C2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verifySuppressed(filterConfig, suppressed); } @Test public void testUsingAVariableCheckOnPreviousLine() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressWithNearbyCommentFilter.class); filterConfig.addAttribute("commentFormat", "ALLOW (\\w+) ON PREVIOUS LINE"); filterConfig.addAttribute("checkFormat", "$1"); filterConfig.addAttribute("influenceFormat", "-1"); final String[] suppressed = { "28:17: Name 'D2' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verifySuppressed(filterConfig, suppressed); } @Test public void testVariableCheckOnVariableNumberOfLines() throws Exception { final DefaultConfiguration filterConfig = createFilterConfig(SuppressWithNearbyCommentFilter.class); filterConfig.addAttribute("commentFormat", "ALLOW (\\w+) UNTIL THIS LINE([+-]\\d+)"); filterConfig.addAttribute("checkFormat", "$1"); filterConfig.addAttribute("influenceFormat", "$2"); final String[] suppressed = { "35:30: Name 'e4' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.", "36:17: Name 'E5' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "38:17: Name 'E7' must match pattern '^[a-z][a-zA-Z0-9]*$'.", "39:17: Name 'E8' must match pattern '^[a-z][a-zA-Z0-9]*$'.", }; verifySuppressed(filterConfig, suppressed); } public static DefaultConfiguration createFilterConfig(Class aClass) { return new DefaultConfiguration(aClass.getName()); } protected void verifySuppressed(Configuration aFilterConfig, String[] aSuppressed) throws Exception { verify(createChecker(aFilterConfig), getPath("filters/InputSuppressWithNearbyCommentFilter.java"), removeSuppressed(sAllMessages, aSuppressed)); } @Override protected Checker createChecker(Configuration aFilterConfig) throws CheckstyleException { final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration"); final DefaultConfiguration checksConfig = createCheckConfig(TreeWalker.class); checksConfig.addChild(createCheckConfig(FileContentsHolder.class)); checksConfig.addChild(createCheckConfig(MemberNameCheck.class)); checksConfig.addChild(createCheckConfig(ConstantNameCheck.class)); checksConfig.addChild(createCheckConfig(IllegalCatchCheck.class)); checkerConfig.addChild(checksConfig); if (aFilterConfig != null) { checkerConfig.addChild(aFilterConfig); } final Checker checker = new Checker(); final Locale locale = Locale.ENGLISH; checker.setLocaleCountry(locale.getCountry()); checker.setLocaleLanguage(locale.getLanguage()); checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); checker.configure(checkerConfig); checker.addListener(new BriefLogger(mStream)); return checker; } private String[] removeSuppressed(String[] aFrom, String[] aRemove) { final Collection coll = Lists.newArrayList(Arrays.asList(aFrom)); coll.removeAll(Arrays.asList(aRemove)); return coll.toArray(new String[coll.size()]); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/EmbeddedNullCharTest.java100644 0 0 3415 12026050732 27522 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import org.junit.Test; /** * Tests that embedded nulls in string literals does not halt parsing. * @author Michael Studman */ public class EmbeddedNullCharTest extends BaseCheckTestSupport { @Test public void testCanParse() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("grammars/InputEmbeddedNullChar.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/GeneratedJava14LexerTest.java100644 0 0 1526 11451071615 30252 0ustar 0 0 package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import java.io.IOException; import org.junit.Test; /** * Tests GeneratedJava14Lexer. * @author Rick Giles */ public class GeneratedJava14LexerTest extends BaseCheckTestSupport { @Test public void testUnexpectedChar() throws IOException, Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = { "8:10: Got an exception - Unexpected character 0xa9 in identifier", }; verify(checkConfig, getPath("grammars/InputGrammar.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/HexFloatsTest.java100644 0 0 3350 12026050732 26273 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import org.junit.Test; /** * Tests hex floats and doubles can be parsed. * @author Michael Studman */ public class HexFloatsTest extends BaseCheckTestSupport { @Test public void testCanParse() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("grammars/InputHexFloat.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/Java7DiamondTest.java100644 0 0 3370 12026050732 26644 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import org.junit.Test; /** * Tests Java 7 diamond can be parsed. * @author Dinesh Bolkensteyn (SonarSource) */ public class Java7DiamondTest extends BaseCheckTestSupport { @Test public void testCanParse() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("grammars/InputJava7Diamond.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/Java7MultiCatchTest.java100644 0 0 3402 12026050731 27321 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import org.junit.Test; /** * Tests Java 7 multi-catch can be parsed. * @author Dinesh Bolkensteyn (SonarSource) */ public class Java7MultiCatchTest extends BaseCheckTestSupport { @Test public void testCanParse() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("grammars/InputJava7MultiCatch.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/Java7NumericalLiteralsTest.java100644 0 0 3425 12026050731 30710 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import org.junit.Test; /** * Tests Java 7 numerical literals can be parsed. * @author Dinesh Bolkensteyn (SonarSource) */ public class Java7NumericalLiteralsTest extends BaseCheckTestSupport { @Test public void testCanParse() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("grammars/InputJava7NumericalLiterals.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/Java7StringSwitchTest.java100644 0 0 3411 12026050731 27714 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import org.junit.Test; /** * Tests Java 7 String in switch can be parsed. * @author Dinesh Bolkensteyn (SonarSource) */ public class Java7StringSwitchTest extends BaseCheckTestSupport { @Test public void testCanParse() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("grammars/InputJava7StringSwitch.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/Java7TryWithResourcesTest.java100644 0 0 3425 12026050731 30576 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import org.junit.Test; /** * Tests Java 7 try-with-resources can be parsed. * @author Dinesh Bolkensteyn (SonarSource) */ public class Java7TryWithResourcesTest extends BaseCheckTestSupport { @Test public void testCanParse() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("grammars/InputJava7TryWithResources.java"), expected); } } ././@LongLink100644 0 0 145 12026055133 10250 Lustar 0 0 checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/LineCommentAtTheEndOfFileTest.javacheckstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/LineCommentAtTheEndOfFileTest.java100644 0 0 3477 12026050730 31262 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import org.junit.Test; /** * Checks that file can be parsed, when it ends on line-comment but without * new-line. * * @author Evgeny Mandrikov */ public class LineCommentAtTheEndOfFileTest extends BaseCheckTestSupport { @Test public void testCanParse() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("grammars/LineCommentAtTheEndOfFile.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/UnicodeEscapeTest.java100644 0 0 3404 12026050730 27103 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import org.junit.Test; /** * Tests that extended unicode escapes can be parsed. * @author Dinesh Bolkensteyn (SonarSource) */ public class UnicodeEscapeTest extends BaseCheckTestSupport { @Test public void testCanParse() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("grammars/UnicodeEscape.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/grammars/VarargTest.java100644 0 0 3322 12026050730 25615 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.grammars; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; import org.junit.Test; /** * Tests varargs can be parsed. * @author Michael Studman */ public class VarargTest extends BaseCheckTestSupport { @Test public void testCanParse() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(MemberNameCheck.class); final String[] expected = {}; verify(checkConfig, getPath("grammars/InputVararg.java"), expected); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/PackageNamesLoaderTest.java100644 0 0 6373 12026050777 26254 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import static org.junit.Assert.assertEquals; import com.google.common.collect.Sets; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import java.util.Arrays; import java.util.Set; import org.junit.Test; /** * Enter a description of class PackageNamesLoaderTest.java. * @author Rick Giles * @author lkuehne */ public class PackageNamesLoaderTest { @Test public void testDefault() throws CheckstyleException { final Set packageNames = PackageNamesLoader .getPackageNames(Thread.currentThread() .getContextClassLoader()); validatePackageNames(packageNames); } private void validatePackageNames(Set aPkgNames) { final String[] checkstylePackages = { "com.puppycrawl.tools.checkstyle.", "com.puppycrawl.tools.checkstyle.checks.", "com.puppycrawl.tools.checkstyle.checks.annotation.", "com.puppycrawl.tools.checkstyle.checks.blocks.", "com.puppycrawl.tools.checkstyle.checks.coding.", "com.puppycrawl.tools.checkstyle.checks.design.", "com.puppycrawl.tools.checkstyle.checks.duplicates.", "com.puppycrawl.tools.checkstyle.checks.header.", "com.puppycrawl.tools.checkstyle.checks.imports.", "com.puppycrawl.tools.checkstyle.checks.indentation.", "com.puppycrawl.tools.checkstyle.checks.javadoc.", "com.puppycrawl.tools.checkstyle.checks.metrics.", "com.puppycrawl.tools.checkstyle.checks.modifier.", "com.puppycrawl.tools.checkstyle.checks.naming.", "com.puppycrawl.tools.checkstyle.checks.regexp.", "com.puppycrawl.tools.checkstyle.checks.sizes.", "com.puppycrawl.tools.checkstyle.checks.whitespace.", "com.puppycrawl.tools.checkstyle.filters.", }; assertEquals("pkgNames.length.", checkstylePackages.length, aPkgNames.size()); final Set checkstylePackagesSet = Sets.newHashSet(Arrays.asList(checkstylePackages)); assertEquals("names set.", checkstylePackagesSet, aPkgNames); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/PackageObjectFactoryTest.java100644 0 0 5753 12026050777 26621 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.checks.naming.ConstantNameCheck; import java.util.HashSet; import org.junit.Test; /** * Enter a description of class PackageObjectFactoryTest.java. * @author Rick Giles * @version 8-Dec-2002 */ public class PackageObjectFactoryTest { private final PackageObjectFactory mFactory = new PackageObjectFactory( new HashSet(), Thread.currentThread().getContextClassLoader()); @Test public void testMakeObjectFromName() throws CheckstyleException { final Checker checker = (Checker) mFactory.createModule( "com.puppycrawl.tools.checkstyle.Checker"); assertNotNull(checker); } @Test public void testMakeCheckFromName() throws CheckstyleException { final ConstantNameCheck check = (ConstantNameCheck) mFactory.createModule( "com.puppycrawl.tools.checkstyle.checks.naming.ConstantName"); assertNotNull(check); } @Test public void testMakeObectFromList() throws CheckstyleException { mFactory.addPackage("com."); final Checker checker = (Checker) mFactory.createModule( "puppycrawl.tools.checkstyle.Checker"); assertNotNull(checker); } @Test public void testMakeObectNoClass() { try { mFactory.createModule("NoClass"); fail("Instantiated non-existant class"); } catch (CheckstyleException ex) { assertEquals("CheckstyleException.message", "Unable to instantiate NoClass", ex.getMessage()); } } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/UtilsTest.java100644 0 0 4626 12026050777 23705 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import static org.junit.Assert.assertEquals; import com.puppycrawl.tools.checkstyle.api.Utils; import java.util.regex.Pattern; import org.apache.commons.beanutils.ConversionException; import org.junit.Test; public class UtilsTest { /** * Test Utils.countCharInString. */ @Test public void testLengthExpandedTabs() throws Exception { final String s1 = "\t"; assertEquals(8, Utils.lengthExpandedTabs(s1, s1.length(), 8)); final String s2 = " \t"; assertEquals(8, Utils.lengthExpandedTabs(s2, s2.length(), 8)); final String s3 = "\t\t"; assertEquals(16, Utils.lengthExpandedTabs(s3, s3.length(), 8)); final String s4 = " \t "; assertEquals(9, Utils.lengthExpandedTabs(s4, s4.length(), 8)); assertEquals(0, Utils.lengthMinusTrailingWhitespace("")); assertEquals(0, Utils.lengthMinusTrailingWhitespace(" \t ")); assertEquals(3, Utils.lengthMinusTrailingWhitespace(" 23")); assertEquals(3, Utils.lengthMinusTrailingWhitespace(" 23 \t ")); final Pattern r1 = Utils.getPattern("a"); final Pattern r2 = Utils.getPattern("a"); assertEquals(r1, r2); } @Test(expected = ConversionException.class) public void testBadRegex() { Utils.createPattern("["); } } checkstyle-5.6/src/tests/com/puppycrawl/tools/checkstyle/XMLLoggerTest.java100644 0 0 20264 12026050777 24421 0ustar 0 0 //////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2012 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.google.common.collect.Lists; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import com.puppycrawl.tools.checkstyle.api.Utils; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.List; import java.util.regex.Pattern; import org.junit.Test; /** * Enter a description of class XMLLoggerTest.java. * @author Rick Giles * @version 11-Dec-2002 */ public class XMLLoggerTest { private final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); @Test public void testEncode() throws IOException { final XMLLogger logger = new XMLLogger(outStream, false); final String[][] encodings = { {"<", "<"}, {">", ">"}, {"'", "'"}, {"\"", """}, {"&", "&"}, {"<", "<"}, {"abc;", "abc;"}, }; for (int i = 0; i < encodings.length; i++) { final String encoded = logger.encode(encodings[i][0]); assertEquals("\"" + encodings[i][0] + "\"", encodings[i][1], encoded); } outStream.close(); } @Test public void testIsReference() throws IOException { final XMLLogger logger = new XMLLogger(outStream, false); final String[] reference = { "�", "�", }; for (int i = 0; i < reference.length; i++) { assertTrue("reference: " + reference[i], logger.isReference(reference[i])); } final String[] noReference = { "&", "&;", "&#;", "&#a;", "�", "&#x;", "&#xg;", }; for (int i = 0; i < noReference.length; i++) { assertFalse("no reference: " + noReference[i], logger.isReference(noReference[i])); } outStream.close(); } @Test public void testCloseStream() throws IOException { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); logger.auditFinished(null); final String[] expectedLines = {}; verifyLines(expectedLines); } @Test public void testNoCloseStream() throws IOException { final XMLLogger logger = new XMLLogger(outStream, false); logger.auditStarted(null); logger.auditFinished(null); outStream.close(); final String[] expectedLines = {}; verifyLines(expectedLines); } @Test public void testFileStarted() throws IOException { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final AuditEvent ev = new AuditEvent(this, "Test.java"); logger.fileStarted(ev); logger.auditFinished(null); final String[] expectedLines = {""}; verifyLines(expectedLines); } @Test public void testFileFinished() throws IOException { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final AuditEvent ev = new AuditEvent(this, "Test.java"); logger.fileFinished(ev); logger.auditFinished(null); final String[] expectedLines = {""}; verifyLines(expectedLines); } @Test public void testAddError() throws IOException { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final LocalizedMessage message = new LocalizedMessage(1, 1, "messages.properties", "key", null, SeverityLevel.ERROR, null, this.getClass(), null); final AuditEvent ev = new AuditEvent(this, "Test.java", message); logger.addError(ev); logger.auditFinished(null); final String[] expectedLines = { "", }; verifyLines(expectedLines); } @Test public void testAddException() throws IOException { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final LocalizedMessage message = new LocalizedMessage(1, 1, "messages.properties", null, null, null, this.getClass(), null); final AuditEvent ev = new AuditEvent(this, "Test.java", message); logger.addException(ev, new TestThrowable()); logger.auditFinished(null); final String[] expectedLines = { "<exception>", "<![CDATA[", "stackTrace]]>", "</exception>", "", }; verifyLines(expectedLines); } private String[] getOutStreamLines() throws IOException { final byte[] bytes = outStream.toByteArray(); final ByteArrayInputStream inStream = new ByteArrayInputStream(bytes); final BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); final List lineList = Lists.newArrayList(); while (true) { final String line = reader.readLine(); if (line == null) { break; } lineList.add(line); } reader.close(); return lineList.toArray(new String[lineList.size()]); } /** * Verify output lines from auditStart to auditEnd. * Take into consideration checkstyle element (first and last lines). * @param aExpectedLines expected error report lines */ private void verifyLines(String[] aExpectedLines) throws IOException { final String[] lines = getOutStreamLines(); assertEquals("length.", aExpectedLines.length + 3, lines.length); assertEquals("first line.", "", lines[0]); Pattern checkstyleOpenTag = Utils.getPattern("^$"); assertTrue("second line.", checkstyleOpenTag.matcher(lines[1]).matches()); for (int i = 0; i < aExpectedLines.length; i++) { assertEquals("line " + i + ".", aExpectedLines[i], lines[i + 2]); } assertEquals("last line.", "", lines[lines.length - 1]); } private static class TestThrowable extends Exception { @Override public void printStackTrace(PrintWriter s) { s.print("stackTrace"); } } } checkstyle-5.6/src/xdocs/anttask.xml.vm100644 0 0 31045 11631376756 15432 0ustar 0 0 Ant Task Oliver Burn

This task runs Checkstyle over specified Java files. The task has been tested using ANT 1.5. The latest version of checkstyle can be found at http://checkstyle.sourceforge.net/. This task is included in the checkstyle distribution.

The easiest way is to include checkstyle-${projectVersion}-all.jar in the classpath. This contains all the classes required to run Checkstyle. Alternatively, you must include the compile third party dependencies listed in Project Dependencies in the classpath.

To use the task in a build file, you will need the following taskdef declaration:

<taskdef resource="checkstyletask.properties" classpath="/path/to/checkstyle-${projectVersion}-all.jar"/>

Or, assuming that Checkstyle is in the global classpath (not recommended), then you will need the following taskdef declaration:

<taskdef resource="checkstyletask.properties"/>

Or if you use Ant 1.6 and later and assuming that Checkstyle is in the library search path, then you may use antlib feature of Ant (see http://ant.apache.org/manual/Types/antlib.html for more details). For example:

<project name="foo" ... xmlns:cs="antlib:com.puppycrawl.tools.checkstyle"> ... <cs:checkstyle> ... </cs:checkstyle> ... </project>
Attribute Description Required
file File to run checkstyle on. One of either file or at least one nested fileset element
config Specifies the location of the file that defines the configuration modules. The location can either be a filesystem location, or a name passed to the ClassLoader.getResource() method.
See here for a description of how to define a configuration.
Exactly one of config or configURL
configURL Specifies a URL that defines the configuration modules. See here for a description of how to define a configuration. Exactly one of config or configURL
properties Specifies a file that contains properties for expanded property values of the configuration. Ant properties (like ${basedir}) and nested property elements override the properties in this file. No
failOnViolation Specifies whether the build will continue even if there are violations. Defaults to "true". No
failureProperty The name of a property to set in the event of a violation. No
maxErrors The maximum number of errors that are tolerated before breaking the build or setting the failure property. Defaults to "0". No
maxWarnings The maximum number of warnings that are tolerated before breaking the build or setting the failure property. Defaults to "2147483647", i.e. Integer.MAX_VALUE. No
classpath The classpath to use when looking up classes. Defaults to the current classpath. No
classpathref The classpath to use when looking up classes, given as a reference to a path defined elsewhere. No
omitIgnoredModules For efficiency, Checkstyle does not invoke modules with a configured severity of "ignore" (since their output would be ignored anyway). A small number of modules may choose to log above their configured severity level and so always need to be invoked. This settings specifies that behaviour. Defaults to "true". No

Note that the packageNamesFile parameter has been dropped for Checkstyle 5.0, because of significant changes regarding package name file handling. See for details.

This task supports the nested elements <fileset>, <classpath>, <formatter>, and <property>.

The parameters for the <formatter> element are:

Attribute Description Required
type

The type of output to generate. The valid values are:

Defaults to "plain".

No
toFile The file to write output to. Defaults to standard output. Note, there is no way to explicitly specify standard output. No
useFile Boolean that determines whether output should be sent to a file. Default is true. No

A <property> element provides a property for expanded property values of the configuration. The parameters for the <property> element are:

Attribute Description Required
key

The key for the property.

Yes
value The value of the property specified as a string. Either value or file
file The value of the property specified as a file. This is great for specifying file names relative to the ANT build file. Either value or file

Run checkstyle with configuration file docs/sun_checks.xml on a single file

<checkstyle config="docs/sun_checks.xml" file="Check.java"/>

Run checkstyle on a set of Java files using site-wide configuration and an expanded property value

<checkstyle config="/path/to/site/sun_checks.xml"> <fileset dir="src/checkstyle" includes="**/*.java"/> <!-- Location of cache-file. Something that is project specific --> <property key="checkstyle.cache.file" file="target/cachefile"/> </checkstyle>

Run checkstyle on a set of files and output messages to standard output in plain format, and a file in XML format

<checkstyle config="docs/sun_checks.xml"> <fileset dir="src/checkstyle" includes="**/*.java"/> <formatter type="plain"/> <formatter type="xml" toFile="build/checkstyle_errors.xml"/> </checkstyle>

Run checkstyle with configuration file docs/sun_checks.xml on a file and provide a package names file

<checkstyle config="docs/sun_checks.xml" packageNamesFile="myPackageNames.xml" file="Check.java"/>

Run checkstyle in an automated build and send an email report if style violations are detected

<target name="checkstyle" description="Generates a report of code convention violations."> <checkstyle config="docs/sun_checks.xml" failureProperty="checkstyle.failure" failOnViolation="false"> <formatter type="xml" tofile="checkstyle_report.xml"/> <fileset dir="src" includes="**/*.java"/> </checkstyle> <style in="checkstyle_report.xml" out="checkstyle_report.html" style="checkstyle.xsl"/> </target> <!-- run this target as part of automated build --> <target name="checkstyle-nightly" depends="checkstyle" if="checkstyle.failure" description="Sends email if checkstyle detected code conventions violations."> <!-- use your own server and email addresses below. See Ant documentation for details --> <mail from="qa@some.domain" tolist="someone@some.domain,someoneelse@some.domain" mailhost="mailbox.some.domain" subject="Checkstyle violation(s) in project ${ant.project.name}" files="checkstyle_report.html"/> </target>
checkstyle-5.6/src/xdocs/availablechecks.xml100644 0 0 70605 11743002061 16425 0ustar 0 0 Available Checks Checkstyle Development Team

Checkstyle provides many checks that you can apply to your sourcecode. Below is an alphabetical reference, the site navigation menu provides a reference organized by functionality.

AbstractClassName Ensures that the names of abstract classes conforming to some regular expression.
AnnotationUseStyle This check controls the style with the usage of annotations.
AnonInnerLength Checks for long anonymous inner classes.
ArrayTrailingComma Checks if array initialization contains optional trailing comma.
ArrayTypeStyle Checks the style of array type definitions.
AvoidInlineConditionals Detects inline conditionals.
AvoidNestedBlocks Finds nested blocks.
AvoidStarImport Check that finds import statements that use the * notation.
AvoidStaticImport Check that finds static imports.
BooleanExpressionComplexity Restricts nested boolean operators (&&, ||, &, | and ^) to a specified depth (default = 3).
ClassDataAbstractionCoupling This metric measures the number of instantiations of other classes within the given class.
ClassFanOutComplexity The number of other classes a given class relies on.
ClassTypeParameterName Checks that class type parameter names conform to a format specified by the format property.
ConstantName Checks that constant names conform to a format specified by the format property.
CovariantEquals Checks that if a class defines a covariant method equals, then it defines method equals(java.lang.Object).
CyclomaticComplexity Checks cyclomatic complexity against a specified limit.
DeclarationOrder Checks that the parts of a class or interface declaration appear in the order suggested by the Code Conventions for the Java Programming Language.
DefaultComesLast Check that the default is after all the cases in a switch statement.
DescendantToken Checks for restricted tokens beneath other tokens.
DesignForExtension Checks that classes are designed for inheritance.
EmptyBlock Checks for empty blocks.
EmptyForInitializerPad Checks the padding of an empty for initializer; that is whether a space is required at an empty for initializer, or such spaces are forbidden.
EmptyForIteratorPad Checks the padding of an empty for iterator; that is whether a space is required at an empty for iterator, or such spaces are forbidden.
EmptyStatement Detects empty statements (standalone ';').
EqualsAvoidNull Checks that any combination of String literals with optional assignment is on the left side of an equals() comparison.
EqualsHashCode Checks that classes that override equals() also override hashCode().
ExecutableStatementCount Restricts the number of executable statements to a specified limit (default = 30).
ExplicitInitialization Checks if any class or object member explicitly initialized to default for its type value (null for object references, zero for numeric types and char and false for boolean.
FallThrough Checks for fall through in switch statements Finds locations where a case contains Java code - but lacks a break, return, throw or continue statement.
FileLength Checks for long source files.
FileTabCharacter Checks to see if a file contains a tab character.
FinalClass Checks that class which has only private ctors is declared as final.
FinalLocalVariable Ensures that local variables that never get their values changed, must be declared final.
FinalParameters Check that method/constructor/catch/foreach parameters are final.
GenericWhitespace Checks that the whitespace around the Generic tokens < and > are correct to the typical convention.
Header Checks the header of the source against a fixed header file.
HiddenField Checks that a local variable or a parameter does not shadow a field that is defined in the same class.
HideUtilityClassConstructor Make sure that utility classes (classes that contain only static methods) do not have a public constructor.
IllegalCatch Catching java.lang.Exception, java.lang.Error or java.lang.RuntimeException is almost never acceptable.
IllegalImport Checks for imports from a set of illegal packages.
IllegalInstantiation Checks for illegal instantiations where a factory method is preferred.
IllegalThrows Throwing java.lang.Error or java.lang.RuntimeException is almost never acceptable.
IllegalToken Checks for illegal tokens.
IllegalTokenText Checks for illegal token text.
IllegalType Checks that particular class are never used as types in variable declarations, return values or parameters.
ImportControl Check that controls what packages can be imported in each package.
ImportOrder Ensures that groups of imports come in a specific order.
Indentation Checks correct indentation of Java Code.
InnerAssignment Checks for assignments in subexpressions, such as in String s = Integer.toString(i = 2);.
InnerTypeLast Check nested (internal) classes/interfaces are declared at the bottom of the class after all method and field declarations.
InterfaceIsType Implements Bloch, Effective Java, Item 17 - Use Interfaces only to define types.
JUnitTestCase Ensures that the setUp(), tearDown()methods are named correctly, have no arguments, return void and are either public or protected.
JavaNCSS This check calculates the Non Commenting Source Statements (NCSS) metric for java source files and methods.
JavadocMethod Checks the Javadoc of a method or constructor.
JavadocPackage Checks that all packages have a package documentation.
JavadocStyle Custom Checkstyle Check to validate Javadoc.
JavadocType Checks the Javadoc of a type.
JavadocVariable Checks that a variable has Javadoc comment.
LeftCurly Checks the placement of left curly braces on types, methods and other blocks:
LineLength Checks for long lines.
LocalFinalVariableName Checks that local final variable names conform to a format specified by the format property.
LocalVariableName Checks that local, non-final variable names conform to a format specified by the format property.
MagicNumber Checks for magic numbers.
MemberName Checks that instance variable names conform to a format specified by the format property.
MethodCount Checks the number of methods declared in each type.
MethodLength Checks for long methods.
MethodName Checks that method names conform to a format specified by the format property.
MethodParamPad Checks the padding between the identifier of a method definition, constructor definition, method call, or constructor invocation; and the left parenthesis of the parameter list.
MethodTypeParameterName Checks that class type parameter names conform to a format specified by the format property.
MissingCtor Checks that classes (except abstract one) define a ctor and don't rely on the default one.
MissingDeprecated This class is used to verify that both the
MissingOverride This class is used to verify that the
MissingSwitchDefault Checks that switch statement has "default" clause.
ModifiedControlVariable Check for ensuring that for loop control variables are not modified inside the for block.
ModifierOrder Checks that the order of modifiers conforms to the suggestions in the Java Language specification, sections 8.1.1, 8.3.1 and 8.4.3.
MultipleStringLiterals Checks for multiple occurrences of the same string literal within a single file.
MultipleVariableDeclarations Checks that each variable declaration is in its own statement and on its own line.
MutableException Ensures that exceptions (defined as any class name conforming to some regular expression) are immutable.
NPathComplexity Checks the npath complexity against a specified limit (default = 200).
NeedBraces Checks for braces around code blocks.
NestedForDepth Restricts nested for blocks to a specified depth (default = 1).
NestedIfDepth Restricts nested if-else blocks to a specified depth (default = 1).
NestedTryDepth Restricts nested try-catch-finally blocks to a specified depth (default = 1).
NewlineAtEndOfFile Checks that there is a newline at the end of each file.
NoClone Checks that the clone method is not overridden from the Object class.
NoFinalizer Checks that no method having zero parameters is defined using the name finalize.
NoWhitespaceAfter Checks that there is no whitespace after a token.
NoWhitespaceBefore Checks that there is no whitespace before a token.
OneStatementPerLine Checks there is only one statement per line.
OperatorWrap Checks line wrapping for operators.
OuterTypeFilename Checks that the outer type name and the file name match.
OuterTypeNumber Checks for the number of defined types at the "outer" level.
PackageAnnotation This check makes sure that all package annotations are in the package-info.java file.
PackageDeclaration Ensures there is a package declaration and (optionally) in the correct directory.
PackageName Checks that package names conform to a format specified by the format property.
ParameterAssignment Disallow assignment of parameters.
ParameterName Checks that parameter names conform to a format specified by the format property.
ParameterNumber Checks the number of parameters that a method or constructor has.
ParenPad Checks the padding of parentheses; that is whether a space is required after a left parenthesis and before a right parenthesis, or such spaces are forbidden, with the exception that it does not check for padding of the right parenthesis at an empty for iterator.
RedundantImport Checks for imports that are redundant.
RedundantModifier Checks for redundant modifiers in interface and annotation definitions.
RedundantThrows Checks for redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception.
Regexp A check that makes sure that a specified pattern exists (or not) in the file.
RegexpHeader Checks the header of the source against a header file that contains a
RegexpMultiline Implementation of a check that looks that matches across multiple lines in any file type.
RegexpSingleline Implementation of a check that looks for a single line in any file type.
RegexpSinglelineJava Implementation of a check that looks for a single line in Java files.
RequireThis Checks that code doesn't rely on the "this" default.
ReturnCount Restricts return statements to a specified count (default = 2).
RightCurly Checks the placement of right curly braces.
SimplifyBooleanExpression Checks for overly complicated boolean expressions.
SimplifyBooleanReturn Checks for overly complicated boolean return statements.
StaticVariableName Checks that static, non-final variable names conform to a format specified by the format property.
StrictDuplicateCode Performs a line-by-line comparison of all code lines and reports duplicate code if a sequence of lines differs only in indentation.
StringLiteralEquality Checks that string literals are not used with == or !=.
SuperClone Checks that an overriding clone() method invokes super.clone().
SuperFinalize Checks that an overriding finalize() method invokes super.finalize().
SuppressWarnings This check allows you to specify what warnings that
ThrowsCount Restricts throws statements to a specified count (default = 1).
TodoComment A check for TODO comments.
TrailingComment The check to ensure that requires that comments be the only thing on a line.
Translation The TranslationCheck class helps to ensure the correct translation of code by checking property files for consistency regarding their keys.
TypeName Checks that type names conform to a format specified by the format property.
TypecastParenPad Checks the padding of parentheses for typecasts.
UncommentedMain Detects uncommented main methods.
UnnecessaryParentheses Checks if unnecessary parentheses are used in a statement or expression.
UnusedImports Checks for unused import statements.
UpperEll Checks that long constants are defined with an upper ell.
VisibilityModifier Checks visibility of class members.
WhitespaceAfter Checks that a token is followed by whitespace, with the exception that it does not check for whitespace after the semicolon of an empty for iterator.
WhitespaceAround Checks that a token is surrounded by whitespace.
WriteTag Outputs a JavaDoc tag as information.
checkstyle-5.6/src/xdocs/checks.xml100644 0 0 1420 11451011233 14526 0ustar 0 0 Standard Checks Checkstyle Development Team

The Standard Checkstyle Checks are applicable to general Java coding style and require no external libraries. The standard checks are included in the base distribution.

The site navigation menu lets you browse the individual checks by functionality.

checkstyle-5.6/src/xdocs/cmdline.xml.vm100644 0 0 13556 11631376756 15407 0ustar 0 0 Command Line Oliver Burn

This document describes how to run Checkstyle using the command line tool. The latest version of Checkstyle can be found at http://checkstyle.sourceforge.net. This command line tool is included in the Checkstyle distribution.

The easiest way is to include checkstyle-${projectVersion}-all.jar in the classpath. Alternatively, you must include the compile third party dependencies listed in Project Dependencies in the classpath.

The command line usage is:

java -D<property>=<value> \ com.puppycrawl.tools.checkstyle.Main \ -c <configurationFile> \ [-f <format>] [-p <propertiesFile>] [-o <file>] \ [-r <dir>] file...

Checkstyle will process the specified files and by default report errors to standard out in plain format. Checkstyle requires a configuration XML file that configures the checks to apply. Command line options are:

  • -c configurationFile - specifies the location of the file that defines the configuration modules. The location can either be a filesystem location, or a name passed to the ClassLoader.getResource() method.
  • -f format - specify the output format. Options are "plain" for the DefaultLogger and "xml" for the XMLLogger. Defaults to "plain".
  • -p propertiesFile - specify a properties file to use.
  • -o file - specify the file to output to.
  • -r dir - specify the directory to traverse for Java source files.

Note that the -n packageNamesFile option has been dropped for Checkstyle 5.0, because of significant changes regarding package name file handling. See for details.

Set the properties for expanded property values by either by assigning system properties using the -D<property>=<value> arguments to java or specifying a property file using the -p option. If a property file is specified, the system properties are ignored.

Run checkstyle with configuration file docs/sun_checks.xml on a file

java com.puppycrawl.tools.checkstyle.Main -c docs/sun_checks.xml \ Check.java

Run checkstyle with configuration file docs/sun_checks.xml on all java files in a directory

java com.puppycrawl.tools.checkstyle.Main -c docs/sun_checks.xml \ -r src/

Run checkstyle with configuration file docs/sun_checks.xml on a file and provide a system property

java -Dcheckstyle.cache.file=target/cachefile \ com.puppycrawl.tools.checkstyle.Main -c docs/sun_checks.xml \ Check.java

Run checkstyle with configuration file docs/sun_checks.xml on a file and use properties in a file

java com.puppycrawl.tools.checkstyle.Main -c docs/sun_checks.xml \ -p myCheckstyle.properties Check.java

Run checkstyle with configuration file docs/sun_checks.xml on a file and output to a file in XML format

java com.puppycrawl.tools.checkstyle.Main -c docs/sun_checks.xml \ -f xml -o build/checkstyle_errors.xml Check.java

Run checkstyle with configuration file docs/sun_checks.xml on a file and provide a package names file

java com.puppycrawl.tools.checkstyle.Main -c docs/sun_checks.xml \ -n myPackageNames.xml Check.java

Tip

It is possible to run Checkstyle directly from the JAR file using the -jar option. An example would be:

java -jar checkstyle-${projectVersion}-all.jar \ -c docs/sun_checks.xml Check.java
checkstyle-5.6/src/xdocs/config.xml100644 0 0 141047 11743004117 14614 0ustar 0 0 Configuration Lars Kühne

A Checkstyle configuration specifies which modules to plug in and apply to Java source files. Modules are structured in a tree whose root is the Checker module. The next level of modules contains:

  • FileSetChecks - modules that take a set of input files and fire error messages.
  • Filters - modules that filter audit events, including error messages, for acceptance.
  • AuditListeners - modules that report accepted events.

Many checks are submodules of the TreeWalker FileSetCheck module. The TreeWalker operates by separately transforming each of the Java source files into an abstract syntax tree and then handing the result over to each of its submodules which in turn have a look at certain aspects of the tree.

Checkstyle obtains a configuration from an XML document whose elements specify the configuration's hierarchy of modules and their properties. You provide a file that contains the configuration document when you invoke Checkstyle at the command line, and when you run a Checkstyle task in ant. The documentation directory of the Checkstyle distribution contains a sample configuration file sun_checks.xml which configures Checkstyle to check for the Sun coding conventions.

A module element in the configuration XML document specifies a module identified by the element's name attribute.

Here is a fragment of a typical configuration document:

<module name="Checker"> <module name="JavadocPackage"/> <module name="TreeWalker"> <module name="AvoidStarImport"/> <module name="ConstantName"/> <module name="EmptyBlock"/> </module> </module>

In this configuration:

  • Root module Checker has child FileSetChecks JavadocPackage and TreeWalker. (Module JavadocPackage checks that all packages have package documentation.)
  • Module TreeWalker has submodules AvoidStarImport, ConstantName, and EmptyBlock. (Modules AvoidStarImport, ConstantName, and EmptyBlock check that a Java source file has no star imports, has valid constant names, and has no empty blocks, respectively.)

For each configuration module, Checkstyle loads a class identified by the name attribute of the module. There are several rules for loading a module's class:

  1. Load a class directly according to a package-qualified name, such as loading class com.puppycrawl.tools.checkstyle.TreeWalker for element: <module name="com.puppycrawl.tools.checkstyle.TreeWalker"> This is useful for plugging third-party modules into a configuration.
  2. Load a class of a pre-specified package, such as loading class com.puppycrawl.tools.checkstyle.checks.AvoidStarImport for element <module name="AvoidStarImport"/> Checkstyle applies packages com.puppycrawl.tools.checkstyle, com.puppycrawl.tools.checkstyle.filters, and com.puppycrawl.tools.checkstyle.checks and its sub-packages (only those included in the Checkstyle distribution). You can specify other packages in a package names XML document when you invoke Checkstyle at the command line, and when you run a Checkstyle task in ant.
  3. Apply the above rules to name concatenated with "Check", such as loading class com.puppycrawl.tools.checkstyle.checks.ConstantNameCheck for element <module name="ConstantName"/>

Properties of a module control how the module performs its task. Each module property has a default value, and you are not required to define a property in the configuration document if the default value is satisfactory. To assign a non-default value to a module's property, define a child property element of the module element in the configuration XML document. Also provide appropriate name and value attributes for the property element. For example, property max of module MethodLength specifies the maximum allowable number of lines in a method or constructor, and has default value 150. Here is a configuration of module MethodLength so that the check reports methods and constructors with more than 60 lines:

<module name="MethodLength"> <property name="max" value="60"/> </module>

Command line properties and ant Checkstyle task properties apply to the root Checker module. Also, properties are inherited in the module hierarchy. These features make it easy to define one property value that applies to many modules. For example, the following configuration fragment specifies that a tabWidth of 4 applies to TreeWalker and its submodules:

<module name="Checker"> <module name="JavadocPackage"/> <module name="TreeWalker"> <property name="tabWidth" value="4"/> <module name="AvoidStarImport"/> <module name="ConstantName"/> ... </module> </module>

The value of a module property can be specified through property expansion with the ${property_name} notation, where property_name is a command line property or an ant Checkstyle task property. For example, the following configuration document element gives property headerFile the value of command line property checkstyle.header.file:

<property name="headerFile" value="${checkstyle.header.file}"/>

You can use property expansion to re-specify a module property value without changing the configuration document.

The property element provides an optional default attribute which is used when a property in the value cannot be resolved. For example this configuration snippet from a central configuration file checks that methods have javadoc, but allows individual projects to override the severity by specifying their desired value in the command line property checkstyle.javadoc.severity:

<module name="JavaDocMethod"> <property name="severity" value="${checkstyle.javadoc.severity}" default="error"/> </module>

This feature is a great help when setting up a centralized configuration file (e.g. one file for the whole company) to lower configuration maintenance costs. Projects that are happy with the default can simply use that configuration file as is, but individual projects with special needs have the flexibility to adjust a few settings to fit their needs without having to copy and maintain the whole configuration.

All configurations have root module Checker. Checker contains:

  • FileSetCheck children: modules that check sets of files.
  • Filter children: modules that filter audit events.
  • AuditListener children: modules that report filtered events.

Checker also defines properties that are inherited by all other modules of a configuration.

Properties

name description type default value
basedir base directory name; stripped off in messages about files string null
localeCountry locale country for messages string: either the empty string or an uppercase ISO 3166 2-letter code default locale country for the Java Virtual Machine
localeLanguage locale language for messages string: either the empty string or a lowercase ISO 639 code default locale language for the Java Virtual Machine
charset name of the file charset String System property "file.encoding"

For example, the following configuration fragment specifies base directory src/checkstyle and German locale for all modules:

<module name="Checker"> <property name="basedir" value="src/checkstyle"/> <property name="localeCountry" value="DE"/> <property name="localeLanguage" value="de"/> <module name="JavadocPackage"/> <module name="TreeWalker"> ... </module> </module>

To configure a Checker so that it handles files with the UTF-8 charset:

<module name="Checker"> <property name="charset" value="UTF-8"/> ... </module>

FileSetCheck TreeWalker checks individual Java source files and defines properties that are applicable to checking such files.

Properties

name description type default value
cacheFile caches information about files that have checked ok; used to avoid repeated checks of the same files string null (no cache file)
tabWidth number of expanded spaces for a tab character ('\t'); used in messages and Checks that require a tab width, such as LineLength integer 8
fileExtensions file type extension to identify java files. Setting this property is typically only required if your java source code is preprocessed before compilation and the original files do not have the extension .java String Set java

For example, the following configuration fragment specifies TreeWalker cache file target/cachefile, and a tabWidth of 4:

<module name="Checker"> <module name="TreeWalker"> <property name="cacheFile" value="target/cachefile"/> <property name="tabWidth" value="4"/> ... </module> </module>

To integrate Checkstyle with BEA Weblogic Workshop 8.1:

<module name="Checker"> <module name="TreeWalker"> <property name="fileExtensions" value="java,ejb,jpf"/> ...

The TreeWalker module creates a syntax tree for a Java source file and invokes its submodules, called Checks, during a walk, or traversal, of the nodes of the tree. Every node of the syntax tree has a token. A visit to a node during the traversal triggers all Checks that are configured for its token. For example, if Check MethodLength has been configured as a submodule of TreeWalker, then a visit to a node with a method or a constructor definition token triggers MethodLength to check the number of lines of the node's code block.

Some Checks, such as FileLength and LineLength, apply directly to the source file and do not involve tokens of the syntax tree. Other Checks are associated with configurable sets of tokens that trigger the Checks. For example, this element configures Check MethodLength:

<module name="MethodLength"/>

The default token set for MethodLength is {METHOD_DEF, CTOR_DEF}, method definition and constructor definition tokens, so TreeWalker invokes MethodLength whenever it visits a node with a METHOD_DEF or a CTOR_DEF token.

You specify the trigger tokens for a Check with property tokens. The value of tokens is a list that denotes a subset of the Check's tokens, as in the following element that configures Check MethodLength to check the number of lines of methods only:

<module name="MethodLength"> <property name="tokens" value="METHOD_DEF"/> </module>

To apply particular properties to different subsets of tokens for a Check, repeat the Check. For example, to check that the length of each method is at most 150 lines (the default value of MethodLength property max) and the length of each constructor is at most 60 lines, include the following in the TreeWalker configuration:

<module name="MethodLength"> <property name="tokens" value="METHOD_DEF"/> </module> <module name="MethodLength"> <property name="tokens" value="CTOR_DEF"/> <property name="max" value="60"/> </module>

Configurations of the Checks are specified in the pages under here.

Each check has a severity property that a Checkstyle audit assigns to all violations of the check. The default severity level of a check is error.

You can use the severity property to control the output of the plain formatter for the command line tool and the ANT task. The plain formatter does not report violations with severity level ignore, and notes violations with severity level warning. For example, according to the following configuration fragment, the plain formatter outputs warnings for translation violations:

<module name="Translation"> <property name="severity" value="warning"/> </module>

The XML formatter reports the severity level of every violation as an attribute of the violation's error element.

As of Checkstyle 5 all checks can be configured to report custom, configuration specific messages instead of the Checkstyle default messages. This can be useful in cases where the check message should reference corresponding sections in a coding style document or the default is too generic for developers to understand.

An example usage is:

<module name="MemberName"> <property name="format" value="^m[a-zA-Z0-9]*$"/> <message key="name.invalidPattern" value="Member ''{0}'' must start with a lowercase ''m'' (checked pattern ''{1}'')." /> </module>

Each check configuration element can zero or more message elements. Every check uses one or more distinct message keys to log violations. If you want to customize a certain message you need to specify the message key in the key attribute of the message element.

The value attribute specifies the custom message pattern, as shown in the example above. Placeholders used in the default message can also be used in the custom message. Note that the message pattern must be a valid java.text.MessageFormat style pattern, so be careful about curly braces outside a placeholder definition.

The obvious question is how do you know which message keys a Check uses, so that you can override them? Well, that is the tricky part. To find out which keys a Check uses you currently need to look into the Check's source code, in conjunction with the Check's messages.properties file. Tools/plugins might come to the rescue on this topic, so have a look there.

A Checker module has a set of Filter submodules to filter audit events, including the error messages fired by Checks. A Filter can accept or reject an audit event. If all Filters accept an audit event, then the Checker reports the event. If any Filter rejects an event, then the Checker does not report the event.

Filter SeverityMatchFilter decides audit events according to the severity level of the event.

SeverityMatchFilter Properties
name description type default value
severity the severity level of this filter severity error
acceptOnMatch If acceptOnMatch is true, then the filter accepts an audit event if and only if there is a match between the event's severity level and property severity. If acceptOnMatch is false, then the filter accepts an audit event if and only if there is not a match between the event's severity level and property severity. boolean true

For example, the following configuration fragment directs the Checker to not report audit events with severity level info:

<module name="SeverityMatchFilter"> <property name="severity" value="info"/> <property name="acceptOnMatch" value="false"/> </module>

Filter SuppressionFilter rejects audit events for Check errors according to a suppressions XML document in a file. If there is no configured suppressions file, the Filter accepts all audit events.

SuppressionFilter Properties
name description type default value
file the location of the suppressions XML document file. The order the location is checked is:
  1. as a filesystem location
  2. if no file found, and the location starts with either http:// or https://, then it is interpreted as a URL
  3. if no file found, then passed to the ClassLoader.getResource() method.
string none

For example, the following configuration fragment directs the Checker to use a SuppressionFilter with suppressions file docs/suppressions.xml:

<module name="SuppressionFilter"> <property name="file" value="docs/suppressions.xml"/> </module>

A suppressions XML document contains a set of suppress elements, where each suppress element can have the following attributes:

  • files - a regular expression matched against the file name associated with an audit event. It is mandatory.
  • checks - a regular expression matched against the name of the check associated with an audit event. Optional if id is specified.
  • id - a string matched against the id of the check associated with an audit event. Optional if checks is specified.
  • lines - a comma-separated list of values, where each value is an integer or a range of integers denoted by integer-integer. It is optional.
  • columns - a comma-separated list of values, where each value is an integer or a range of integers denoted by integer-integer. It is optional.

Each audit event is checked against each suppress element. It is suppressed if all specified attributes match against the audit event.

Examples

For example, the following suppressions XML document directs a SuppressionFilter to reject JavadocStyleCheck errors for lines 82 and 108 to 122 of file AbstractComplexityCheck.java, and MagicNumberCheck errors for line 221 of file JavadocStyleCheck.java:

<?xml version="1.0"?> <!DOCTYPE suppressions PUBLIC "-//Puppy Crawl//DTD Suppressions 1.1//EN" "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd"> <suppressions> <suppress checks="JavadocStyleCheck" files="AbstractComplexityCheck.java" lines="82,108-122"/> <suppress checks="MagicNumberCheck" files="JavadocStyleCheck.java" lines="221"/> </suppressions>

As another example, imagine that a configuration contains the following:

<module name="DescendantToken"> <property name="id" value="stringEqual"/> <property name="tokens" value="EQUAL,NOT_EQUAL"/> <property name="limitedTokens" value="STRING_LITERAL"/> <property name="maximumNumber" value="0"/> <property name="maximumDepth" value="1"/> </module> <module name="DescendantToken"> <property name="id" value="switchNoDefault"/> <property name="tokens" value="LITERAL_SWITCH"/> <property name="maximumDepth" value="2"/> <property name="limitedTokens" value="LITERAL_DEFAULT"/> <property name="minimumNumber" value="1"/> </module>

Then the following can be used to suppress only the first check and not the second by using the id attribute:

<suppress id="stringEqual" files="SomeTestCode.java"/>

SuppressionCommentFilter

Filter SuppressionCommentFilter uses pairs of comments to suppress audit events.

Rationale: Sometimes there are legitimate reasons for violating a check. When this is a matter of the code in question and not personal preference, the best place to override the policy is in the code itself. Semi-structured comments can be associated with the check. This is sometimes superior to a separate suppressions file, which must be kept up-to-date as the source file is edited.

Usage: This filter only works in conjunction with a FileContentsHolder, since that check makes the suppression comments in the .java files available sub rosa. A configuration that includes this filter must configure FileContentsHolder as a child module of TreeWalker.

SuppressionCommentFilter Properties
name description type default value
offCommentFormat comment pattern to trigger filter to begin suppression regular expression CHECKSTYLE\:OFF
onCommentFormat comment pattern to trigger filter to end suppression regular expression CHECKSTYLE\:ON
checkFormat check pattern to suppress regular expression .* (all checks)
messageFormat message pattern to suppress regular expression none
checkCPP whether to check C++ style comments (//) boolean true
checkC whether to check C style comments (/* ... */) boolean true
Restrictions

offCommentFormat and onCommentFormat must have equal paren counts.

Examples

To configure the check that makes comments available to the filter:

<module name="TreeWalker"> ... <module name="FileContentsHolder"/> ... </module>

To configure a filter to suppress audit events between a comment containing CHECKSTYLE:OFF and a comment containing CHECKSTYLE:ON:

<module name="SuppressionCommentFilter"/>

To configure a filter to suppress audit events between a comment containing line BEGIN GENERATED CODE and a comment containing line END GENERATED CODE:

<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="BEGIN GENERATED CODE"/> <property name="onCommentFormat" value="END GENERATED CODE"/> </module>

To configure a filter so that // stop constant check and // resume constant check marks legitimate constant names:

<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="stop constant check"/> <property name="onCommentFormat" value="resume constant check"/> <property name="checkFormat" value="ConstantNameCheck"/> </module>

To configure a filter so that UNUSED OFF: var and UNUSED ON: var marks a variable or parameter known not to be used by the code by matching the variable name in the message:

<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="UNUSED OFF\: (\w+)"/> <property name="onCommentFormat" value="UNUSED ON\: (\w+)"/> <property name="checkFormat" value="Unused"/> <property name="messageFormat" value="^Unused \w+ '$1'.$"/> </module>

To configure a filter so that CSOFF: regexp and CSN: regexp mark a matching check:

<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="CSOFF\: ([\w\|]+)"/> <property name="onCommentFormat" value="CSON\: ([\w\|]+)"/> <property name="checkFormat" value="$1"/> </module>

To configure a filter to suppress all audit events between a comment containing CHECKSTYLE_OFF: ALL and a comment containing CHECKSTYLE_OFF: ALL except for the EqualsHashCode check:

<module name="SuppressionCommentFilter"> <property name="offCommentFormat" value="CHECKSTYLE_OFF: ALL"/> <property name="onCommentFormat" value="CHECKSTYLE_ON: ALL"/> <property name="checkFormat" value="^((?!(EqualsHashCode)).)*$"/> </module>

SuppressWithNearbyCommentFilter

Filter SuppressWithNearbyCommentFilter uses individual comments to suppress audit events.

Rationale: Same as SuppressionCommentFilter. Whereas the SuppressionCommentFilter uses matched pairs of filters to turn on/off comment matching, SuppressWithNearbyCommentFilter uses single comments. This requires fewer lines to mark a region, and may be aesthetically preferable in some contexts.

Usage: This filter only works in conjunction with a FileContentsHolder, since that check makes the suppression comments in the .java files available sub rosa. A configuration that includes this filter must configure FileContentsHolder as a child module of TreeWalker.

SuppressWithNearbyCommentFilter Properties
name description type default value
commentFormat comment pattern to trigger filter to begin suppression regular expression SUPPRESS CHECKSTYLE (\w+)
checkFormat check pattern to suppress regular expression .*
messageFormat message pattern to suppress regular expression none
influenceFormat a negative/zero/positive value that defines the number of lines preceding/at/following the suppression comment regular expression 0 (the line containing the comment)
checkCPP whether to check C++ style comments (//) boolean true
checkC whether to check C style comments (/* ... */) boolean true
Examples

To configure the check that makes comments available to the filter:

<module name="TreeWalker"> ... <module name="FileContentsHolder"/> ... </module>

To configure a filter to suppress audit events for check on any line with a comment SUPPRESS CHECKSTYLE check:

<module name="SuppressWithNearbyCommentFilter"/>

To configure a filter to suppress all audit events on any line containing the comment CHECKSTYLE IGNORE THIS LINE:

<module name="SuppressWithNearbyCommentFilter"> <property name="commentFormat" value="CHECKSTYLE IGNORE THIS LINE"/> <property name="checkFormat" value=".*"/> <property name="influenceFormat" value="0"/> </module>

To configure a filter so that // Ok to catch (Throwable|Exception|RuntimeException) here permits the current and previous line to avoid generating an IllegalCatch audit event:

<module name="SuppressWithNearbyCommentFilter"> <property name="commentFormat" value="Ok to catch (\w+) here"/> <property name="checkFormat" value="IllegalCatchCheck"/> <property name="messageFormat" value="$1"/> <property name="influenceFormat" value="-1"/> </module>

To configure a filter so that CHECKSTYLE IGNORE check FOR NEXT var LINES avoids triggering any audits for the given check for the current line and the next var lines (for a total of var+1 lines):

<module name="SuppressWithNearbyCommentFilter"> <property name="commentFormat" value="CHECKSTYLE IGNORE (\w+) FOR NEXT (\d+) LINES"/> <property name="checkFormat" value="$1"/> <property name="influenceFormat" value="$2"/> </module>

In addition to an audit reporter for text or XML output, a Checker can have custom AuditListeners that handle audit events. In order to use a custom listener, add a Checker submodule for the listener and its properties. For example, to configure a Checker so that it uses custom listener VerboseListener to print audit messages to a file named "audit.txt", include the following module in the configuration file:

<module name="com.mycompany.listeners.VerboseListener"> <property name="file" value="audit.txt"/> </module>

Checkstyle loads a module class according to the name of a module element, and automatically appends pre-specified package prefixes to that name in its search for a loadable class. By default, Checkstyle applies packages com.puppycrawl.tools.checkstyle, com.puppycrawl.tools.checkstyle.filters, and com.puppycrawl.tools.checkstyle.checks as well as any sub-packages of com.puppycrawl.tools.checkstyle.checks that are distributed with Checkstyle.

To specify other packages to apply, create a package names XML document in a file named checkstyle_packages.xml, and provide that file in the root of the .jar containing your custom checks.

Note that the support for providing a package names XML document via command line option or as a attribute of an ant Checkstyle task has been dropped with Checkstyle 5.0.

A package names XML document specifies a list of package names. Here is a sample package names XML document for packages com.puppycrawl.tools.checkstyle and com.puppycrawl.tools.checkstyle.checks:

<checkstyle-packages> <package name="com.puppycrawl.tools.checkstyle"> <package name="checks"/> </package> </checkstyle-packages>

Notice that the packages are specified recursively - a child package element is a subpackage of its parent package element.

For example, to incorporate modules from package com.mycompany.checks with Checkstyle modules, create the XML file below and put this file into the root of the jar file which contains your custom check modules. The XML file must be named exactly checkstyle_packages.xml:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE checkstyle-packages PUBLIC "-//Puppy Crawl//DTD Package Names 1.0//EN" "http://www.puppycrawl.com/dtds/packages_1_0.dtd"> <checkstyle-packages> <package name="com.mycompany.checks"/> </checkstyle-packages>

Now you can configure a module of package com.mycompany.checks, say com.mycompany.checks.MethodLimitCheck, with a shortened module element in the configuration document:

<module name="MethodLimit"/>

Note

As of Checkstyle 5.0 it is unnecessary to repeat the package elements for Checkstyle's packages in your custom checkstyle_packages.xml file.

Configuration XML Document

The following DTD for a configuration XML document specifies the hierarchy of modules and their properties:

<?xml version="1.0" encoding="UTF-8"?> <!ELEMENT module (module|property)*> <!ATTLIST module name NMTOKEN #REQUIRED> <!ELEMENT property EMPTY> <!ATTLIST property name NMTOKEN #REQUIRED value CDATA #REQUIRED >

Checkstyle validates a configuration XML document when it loads the document. To validate against the above configuration DTD, include the following document type declaration in your configuration XML document:

<!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">

Checkstyle also strictly enforces the encoding attribute of an XML declaration. If Checkstyle rejects your configuration document's encoding, correct the value of the encoding attribute, or remove the encoding attribute entirely.

For a complete example of a configuration XML document, examine file docs/sun_checks.xml that checks the Sun coding conventions.

Package Names XML Document

This is a DTD for a package names XML document:

<?xml version="1.0" encoding="UTF-8"?> <!ELEMENT checkstyle-packages (package)*> <!ELEMENT package (package)*> <!ATTLIST package name NMTOKEN #REQUIRED>

Checkstyle also validates a package names XML document when it loads the document. To validate against the above package names DTD, include the following document type declaration in your package names XML document:

<!DOCTYPE checkstyle-packages PUBLIC "-//Puppy Crawl//DTD Package Names 1.1//EN" "http://www.puppycrawl.com/dtds/packages_1_1.dtd">

Suppressions XML Document

This is a DTD for a suppressions XML document:

<?xml version="1.0" encoding="UTF-8"?> <!ELEMENT suppressions (suppress*)> <!ELEMENT suppress EMPTY> <!ATTLIST suppress files CDATA #REQUIRED checks CDATA #IMPLIED id CDATA #IMPLIED lines CDATA #IMPLIED columns CDATA #IMPLIED>
checkstyle-5.6/src/xdocs/config_annotation.xml100644 0 0 30336 11451011233 17015 0ustar 0 0 Annotations Checkstyle Development Team

This check controls the style with the usage of annotations.

name description type default value
elementStyle

Defines the annotation element styles.

element style compact_no_array
closingParens Defines the policy for ending parenthesis. closing parens never
trailingArrayComma Defines the policy for trailing comma in arrays. trailing comma never

To configure the check:

<module name="AnnotationUseStyle"/>

To configure the check to enforce an expanded style, with a trailing array comma set to never and always including the closing parenthesis.

<module name="AnnotationUseStyle"> <property name="ElementStyle" value="expanded"/> <property name="TrailingArrayComma" value="never"/> <property name="ClosingParens" value="always"/> </module>

com.puppycrawl.tools.checkstyle.checks.annotation

TreeWalker

Verifies that both the java.lang.Deprecated annotation is present and the @deprecated Javadoc tag is present when either is present.

To configure the check:

<module name="MissingDeprecated"/>

com.puppycrawl.tools.checkstyle.checks.annotation

TreeWalker

Verifies that the java.lang.Override annotation is present when the {@inheritDoc} javadoc tag is present.

name description type default value
javaFiveCompatibility When this property is true this check will only check classes, interfaces, etc. that do not contain the extends or implements keyword or are not anonymous classes. This means it only checks methods overridden from java.lang.Object Java 5 Compatibility mode severely limits this check. It is recommended to only use it on Java 5 source boolean false

To configure the check:

<module name="MissingOverride"/>

To configure the check for the javaFiveCompatibility mode:

<module name="MissingOverride"> <property name="javaFiveCompatibility" value="true"/> </module>

com.puppycrawl.tools.checkstyle.checks.annotation

TreeWalker

This check makes sure that all package annotations are in the package-info.java file.

According to the Java JLS 3rd ed.

The JLS does not enforce the placement of package annotations. This placement may vary based on implementation. The JLS does highly recommend that all package annotations are placed in the package-info.java file. See Java Language specification, sections 7.4.1.1.

To configure the check:

<module name="PackageAnnotation"/>

com.puppycrawl.tools.checkstyle.checks.annotation

TreeWalker

This check allows you to specify what warnings that SuppressWarnings is not allowed to suppress. You can also specify a list of TokenTypes that the configured warning(s) cannot be suppressed on.

Limitations: This check does not consider conditionals inside the SuppressWarnings annotation.
For example: @SupressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused") According to the above example, the "unused" warning is being suppressed not the "unchecked" or "foo" warnings. All of these warnings will be considered and matched against regardless of what the conditional evaluates to.

name description type default value
format The warnings property is a regex pattern. Any warning being suppressed matching this pattern will be flagged. regexp ^$|^\s+$
tokens tokens to check subset of tokens CLASS_DEF, INTERFACE_DEF, ENUM_DEF, ANNOTATION_DEF, ANNOTATION_FIELD_DEF ENUM_CONSTANT_DEF PARAMETER_DEF VARIABLE_DEF METHOD_DEF CTOR_DEF CLASS_DEF, INTERFACE_DEF, ENUM_DEF, ANNOTATION_DEF, ANNOTATION_FIELD_DEF ENUM_CONSTANT_DEF PARAMETER_DEF VARIABLE_DEF METHOD_DEF CTOR_DEF

To configure the check:

<module name="SuppressWarnings"/>

To configure the check so that the "unchecked" and "unused" warnings cannot be suppressed on anything but variable and parameter declarations.

<module name="SuppressWarnings"> <property name="format" value="^unchecked$|^unused$"/> <property name="tokens" value=" CLASS_DEF,INTERFACE_DEF,ENUM_DEF, ANNOTATION_DEF,ANNOTATION_FIELD_DEF, ENUM_CONSTANT_DEF,METHOD_DEF,CTOR_DEF "/> </module>

com.puppycrawl.tools.checkstyle.checks.annotation

TreeWalker

checkstyle-5.6/src/xdocs/config_blocks.xml100644 0 0 36420 11451071615 16132 0ustar 0 0 Block Checks Checkstyle Development Team

Checks for empty blocks.

name description type default value
option policy on block contents block policy stmt
tokens blocks to check subset of tokens LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_IF, LITERAL_FOR, LITERAL_TRY, LITERAL_WHILE, INSTANCE_INIT STATIC_INIT all tokens

To configure the check:

<module name="EmptyBlock"/>

To configure the check for the text policy and only catch blocks:

<module name="EmptyBlock"> <property name="option" value="text"/> <property name="tokens" value="LITERAL_CATCH"/> </module>

com.puppycrawl.tools.checkstyle.checks.blocks

TreeWalker

Checks for the placement of left curly braces ('{') for code blocks. The policy to verify is specified using property option. Policies eol and nlow take into account property maxLineLength.

name description type default value
option policy on placement of a left curly brace ('{') left curly brace policy eol
maxLineLength maximum number of characters in a line integer 80
tokens blocks to check subset of tokens CLASS_DEF, CTOR_DEF, INTERFACE_DEF, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_SWITCH, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, METHOD_DEF all tokens

To configure the check:

<module name="LeftCurly"/>

To configure the check to apply the nl policy to type blocks:

<module name="LeftCurly"> <property name="option" value="nl"/> <property name="tokens" value="CLASS_DEF,INTERFACE_DEF"/> </module>

com.puppycrawl.tools.checkstyle.checks.blocks

TreeWalker

Checks for braces around code blocks.

name description type default value
tokens blocks to check subset of tokens LITERAL_DO, LITERAL_ELSE, LITERAL_IF, LITERAL_FOR, LITERAL_WHILE all tokens

To configure the check:

<module name="NeedBraces"/>

To configure the check for if and else blocks:

<module name="NeedBraces"> <property name="tokens" value="LITERAL_IF, LITERAL_ELSE"/> </module>

com.puppycrawl.tools.checkstyle.checks.blocks

TreeWalker

Checks the placement of right curly braces ('}') for else, try, and catch tokens. The policy to verify is specified using property option.

name description type default value
option policy on placement of a right curly brace ('}') right curly brace policy same
tokens blocks to check subset of tokens LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE
shouldStartLine should we check if '}' starts line. boolean true

To configure the check:

<module name="RightCurly"/>

To configure the check with policy alone for else tokens:

<module name="RightCurly"> <property name="option" value="alone"/> <property name="tokens" value="LITERAL_ELSE"/> </module>

com.puppycrawl.tools.checkstyle.checks.blocks

TreeWalker

Finds nested blocks, i.e. blocks that are used freely in the code.

Rationale: Nested blocks are often leftovers from the debugging process, they confuse the reader.

For example this Check finds the obsolete braces in

public void guessTheOutput() { int whichIsWich = 0; { int whichIsWhich = 2; } System.out.println("value = " + whichIsWhich); }

and debugging / refactoring leftovers such as

// if (conditionThatIsNotUsedAnyLonger) { System.out.println("unconditional"); }

A case in a switch statement does not implicitly form a block. Thus to be able to introduce local variables that have case scope it is necessary to open a nested block. This is supported, set the allowInSwitchCase property to true and include all statements of the case in the block.

switch (a) { case 0: // Never OK, break outside block { x = 1; } break; case 1: // Never OK, statement outside block System.out.println("Hello"); { x = 2; break; } case 1: // OK if allowInSwitchCase is true { System.out.println("Hello"); x = 2; break; } }
name description type default value
allowInSwitchCase Allow nested blocks in case statements boolean false

To configure the check:

<module name="AvoidNestedBlocks"/>

com.puppycrawl.tools.checkstyle.checks.blocks

TreeWalker

checkstyle-5.6/src/xdocs/config_coding.xml100644 0 0 232273 11743002030 16131 0ustar 0 0 Coding Checkstyle Development Team

Checks that array initialization contains a trailing comma.

int[] a = new int[] { 1, 2, 3, };

The check allows to not add a comma if both left and right curlys are on the same line.

return new int[] { 0 };

Rationale: Putting this comma in makes it easier to change the order of the elements or add new elements on the end.

To configure the check:

<module name="ArrayTrailingComma"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Detects inline conditionals. An example inline conditional is this:

String a = getParameter("a"); String b = (a==null || a.length<1) ? null : a.substring(1);

Rationale: Some developers find inline conditionals hard to read, so their company's coding standards forbids them.

To configure the check:

<module name="AvoidInlineConditionals"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that classes that define a covariant equals() method also override method equals(java.lang.Object). Inspired by findbugs.

Rationale: Mistakenly defining a covariant equals() method without overriding method equals(java.lang.Object) can produce unexpected runtime behaviour.

To configure the check:

<module name="CovariantEquals"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Detects empty statements (standalone ;).

To configure the check:

<module name="EmptyStatement"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that any combination of String literals with optional assignment is on the left side of an equals() comparison. The check also processes String.equalsIgnoreCase() invocations (which can be suppressed).

Rationale: Calling the equals() method on String literals will avoid a potential NullPointerException. Also, it is pretty common to see null check right before equals comparisons which is not necessary in the below example.

For example:

String nullString = null; nullString.equals("My_Sweet_String");

should be refactored to:

String nullString = null; "My_Sweet_String".equals(nullString);

Limitations: If the equals method is overridden or a covariant equals method is defined and the implementation is incorrect (where s.equals(t) does not return the same result as t.equals(s)) then rearranging the called on object and parameter may have unexpected results

Java's Autoboxing feature has an affect on how this check is implemented. Pre Java 5 all IDENT + IDENT object concatenations would not cause a NullPointerException even if null. Those situations could have been included in this check. They would simply act as if they surrounded by String.valueof() which would concatenate the String null.

The following example will cause a NullPointerException as a result of what autoboxing does.

Integer i = null, j = null; String number = "5" number.equals(i + j);

Since, it is difficult to determine what kind of Object is being concatenated all ident concatenation is considered unsafe.

name description type default value
ignoreEqualsIgnoreCase whether to ignore String.equalsIgnoreCase() invocations boolean false

To configure the check:

<module name="EqualsAvoidNull"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that classes that override equals() also override hashCode().

Rationale: The contract of equals() and hashCode() requires that equal objects have the same hashCode. Hence, whenever you override equals() you must override hashCode() to ensure that your class can be used in collections that are hash based.

To configure the check:

<module name="EqualsHashCode"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that local variables that never have their values changed are declared final. The check can be configured to also check that unchanged parameters are declared final.

When configured to check parameters, the check ignores parameters of interface methods and abstract methods.

name description type default value
tokens tokens to check subset of tokens PARAMETER_DEF, VARIABLE_DEF VARIABLE_DEF

To configure the check:

<module name="FinalLocalVariable"/>

To configure the check so that it checks local variables and parameters:

<module name="FinalLocalVariable"> <property name="tokens" value="VARIABLE_DEF,PARAMETER_DEF"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that a local variable or a parameter does not shadow a field that is defined in the same class.

name description type default value
tokens tokens to check subset of tokens PARAMETER_DEF, VARIABLE_DEF PARAMETER_DEF, VARIABLE_DEF
ignoreFormat pattern for names to ignore regular expression (not applied)
ignoreConstructorParameter Controls whether to ignore constructor parameters. Boolean false
ignoreSetter Controls whether to ignore the parameter of a property setter method, where the property setter method for field "xyz" has name "setXyz", one parameter named "xyz", and return type void. Boolean false
ignoreAbstractMethods Controls whether to ignore parameters of abstract methods. Boolean false

To configure the check:

<module name="HiddenField"/>

To configure the check so that it checks local variables but not parameters:

<module name="HiddenField"> <property name="tokens" value="VARIABLE_DEF"/> </module>

To configure the check so that it ignores the name "rcsid":

<module name="HiddenField"> <property name="ignoreFormat" value="^rcsid$"/> </module>

To configure the check so that it ignores constructor parameters:

<module name="HiddenField"> <property name="ignoreConstructorParameter" value="true"/> </module>

To configure the check so that it ignores the parameter of setter methods:

<module name="HiddenField"> <property name="ignoreSetter" value="true"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks for illegal instantiations where a factory method is preferred.

Rationale: Depending on the project, for some classes it might be preferable to create instances through factory methods rather than calling the constructor.

A simple example is the java.lang.Boolean class. In order to save memory and CPU cycles, it is preferable to use the predefined constants TRUE and FALSE. Constructor invocations should be replaced by calls to Boolean.valueOf().

Some extremely performance sensitive projects may require the use of factory methods for other classes as well, to enforce the usage of number caches or object pools.

There is a limitation that it is currently not possible to specify array classes.

name description type default value
classes classes that should not be instantiated String Set {}

To configure the check to find instantiations of java.lang.Boolean:

<module name="IllegalInstantiation"> <property name="classes" value="java.lang.Boolean"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks for illegal tokens.

Rational: Certain language features often lead to hard to maintain code or are non-obvious to novice developers. Other features may be discouraged in certain frameworks, such as not having native methods in EJB components.

name description type default value
tokens tokens to check subset of TokenTypes, LITERAL_SWITCH, POST_INC, POST_DEC

To configure the check to find token LITERAL_NATIVE:

<module name="IllegalToken"> <property name="tokens" value="LITERAL_NATIVE"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks for illegal token text.

name description type default value
tokens tokens to check subset of TokenTypes empty
format illegal pattern regular expression ^$ (empty)
ignoreCase Controls whether to ignore case when matching. Boolean false
message Message which is used to notify about violations; if empty then the default message is used. String ""(empty)

To configure the check to forbid String literals containing "a href":

<module name="IllegalTokenText"> <property name="tokens" value="STRING_LITERAL"/> <property name="format" value="a href"/> </module>

To configure the check to forbid leading zeros in an integer literal, other than zero and a hex literal:

<module name="IllegalTokenText"> <property name="tokens" value="NUM_INT,NUM_LONG"/> <property name="format" value="^0[^lx]"/> <property name="ignoreCase" value="true"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks for assignments in subexpressions, such as in String s = Integer.toString(i = 2);.

Rationale: With the exception of for iterators, all assignments should occur in their own toplevel statement to increase readability. With inner assignments like the above it is difficult to see all places where a variable is set.

name description type default value
tokens assignments to check subset of tokens ASSIGN, BAND_ASSIGN, BOR_ASSIGN, BSR_ASSIGN, BXOR_ASSIGN, DIV_ASSIGN, MINUS_ASSIGN, MOD_ASSIGN, PLUS_ASSIGN, SL_ASSIGN, SR_ASSIGN, STAR_ASSIGN all tokens

To configure the check:

<module name="InnerAssignment"/>

To configure the check for only =, +=, and -= operators:

<module name="InnerAssignment"> <property name="tokens" value="ASSIGN,PLUS_ASSIGN,MINUS_ASSIGN"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that there are no "magic numbers", where a magic number is a numeric literal that is not defined as a constant. By default, -1, 0, 1, and 2 are not considered to be magic numbers.

name description type default value
tokens tokens to check subset of tokens NUM_DOUBLE, NUM_FLOAT, NUM_INT, NUM_LONG all tokens
ignoreNumbers non-magic numbers list of numbers -1, 0, 1, 2
ignoreHashCodeMethod ignore magic numbers in hashCode methods boolean false
ignoreAnnotation ignore magic numbers in annotation declarations. boolean false

To configure the check:

<module name="MagicNumber"/>

To configure the check so that it checks floating-point numbers that are neither 0, 0.5, nor 1:

<module name="MagicNumber"> <property name="tokens" value="NUM_DOUBLE, NUM_FLOAT"/> <property name="ignoreNumbers" value="0, 0.5, 1"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that switch statement has "default" clause.

Rationale: It's usually a good idea to introduce a default case in every switch statement. Even if the developer is sure that all currently possible cases are covered, this should be expressed in the default branch, e.g. by using an assertion. This way the code is protected aginst later changes, e.g. introduction of new types in an enumeration type.

To configure the check:

<module name="MissingSwitchDefault"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Check for ensuring that for loop control variables are not modified inside the for block. An example is:

for (int i = 0; i < 1; i++) { i++; }

Rationale: If the control variable is modified inside the loop body, the program flow becomes more difficult to follow. An option is to replace the for loop with a while loop.

To configure the check:

<module name="ModifiedControlVariable"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks for redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception.

name description type default value
allowUnchecked whether unchecked exceptions in throws are allowed or not boolean false
allowSubclasses whether subclass of another declared exception is allowed in throws clause boolean false
logLoadErrors This check may need to load exception classes mentioned in the @throws tag to check whether they are RuntimeExceptions. If loading the class fails, this property allows to control checkstyle's error handling. If set to false a classpath configuration problem is assumed and the TreeWalker stops operating on the class completely. If set to true (the default), checkstyle assumes a typo or refactoring problem in the javadoc and logs the problem in the normal checkstyle report (potentially masking a configuration error). boolean true
suppressLoadErrors When logLoadErrors is set to true, the TreeWalker completely processes a class and displays any problems with loading exceptions as checkstyle violations. When this property is set to true, the violations generated when logLoadErrors is set true are suppressed from being reported as violations in the checkstyle report. boolean false

To configure the default check:

<module name="RedundantThrows"/>

To configure the check to allow unchecked exception in throws clause

<module name="RedundantThrows"> <property name="allowUnchecked" value="true"/> </module>

The classpath should be configured to locate the class information. The classpath configuration is dependent on the mechanism used to invoke Checkstyle.

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks for overly complicated boolean expressions. Currently finds code like if (b == true), b || true, !false, etc.

Rationale: Complex boolean logic makes code hard to understand and maintain.

To configure the check:

<module name="SimplifyBooleanExpression"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks for overly complicated boolean return statements. For example the following code

if (valid()) return false; else return true;

could be written as

return !valid();

The Idea for this Check has been shamelessly stolen from the equivalent PMD rule.

To configure the check:

<module name="SimplifyBooleanReturn"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that string literals are not used with == or !=.

Rationale: Novice Java programmers often use code like:

if (x == "something")

when they mean

if ("something".equals(x))

To configure the check:

<module name="StringLiteralEquality"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Restricts nested for blocks to a specified depth (default = 1).

name description type default value
max allowed nesting depth Integer 1

To configure the check:

<module name="NestedForDepth"/>

To configure the check to allow nesting depth 3:

<module name="NestedForDepth"> <property name="max" value="3"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Restricts nested if-else blocks to a specified depth (default = 1).

name description type default value
max allowed nesting depth Integer 1

To configure the check:

<module name="NestedIfDepth"/>

To configure the check to allow nesting depth 3:

<module name="NestedIfDepth"> <property name="max" value="3"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Restricts nested try blocks to a specified depth (default = 1).

name description type default value
max allowed nesting depth Integer 1

To configure the check:

<module name="NestedTryDepth"/>

To configure the check to allow nesting depth 3:

<module name="NestedTryDepth"> <property name="max" value="3"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that the clone method is not overridden from the Object class.

Rationale: The clone method relies on strange/hard to follow rules that do not work it all situations. Consequently, it is difficult to override correctly. Below are some of the rules/reasons why the clone method should be avoided.

  • Classes supporting the clone method should implement the Cloneable interface but the Cloneable interface does not include the clone method. As a result, it doesn't enforce the method override.
  • The Cloneable interface forces the Object's clone method to work correctly. Without implementing it, the Object's clone method will throw a CloneNotSupportedException.
  • Non-final classes must return the object returned from a call to super.clone().
  • Final classes can use a constructor to create a clone which is different from non-final classes.
  • If a super class implements the clone method incorrectly all subclasses calling super.clone() are doomed to failure.
  • If a class has references to mutable objects then those object references must be replaced with copies in the clone method after calling super.clone().
  • The clone method does not work correctly with final mutable object references because final references cannot be reassigned.
  • If a super class overrides the clone method then all subclasses must provide a correct clone implementation.

Two alternatives to the clone method, in some cases, is a copy constructor or a static factory method to return copies of an object. Both of these approaches are simpler and do not conflict with final fields. The do not force the calling client to handle a CloneNotSuportException. They also are typed therefore no casting is necessary. Finally, they are more flexible since they can take interface types rather than concrete classes.

Sometimes a copy constructor or static factory is not an acceptable alternative to the clone method. The example below highlights the limitation of a copy constructor (or static factory). Assume Square is a subclass for Shape.

Shape s1 = new Square(); System.out.println(s1 instanceof Square); //true

...assume at this point the code knows nothing of s1 being a Square that's the beauty of polymorphism but the code wants to copy the Square which is declared as a Shape, its super type...

Shape s2 = new Shape(s1); //using the copy constructor System.out.println(s2 instanceof Square); //false

The working solution (without knowing about all subclasses and doing many casts) is to do the following (assuming correct clone implementation).

Shape s2 = s1.clone(); System.out.println(s2 instanceof Square); //true

Just keep in mind if this type of polymorphic cloning is required then a properly implemented clone method may be the best choice.

Much of this information was taken from Effective Java: Programming Language Guide First Edition by Joshua Bloch pages 45-52. Give Bloch credit for writing an excellent book.

This check is almost exactly the same as the {@link NoFinalizerCheck}

To configure the check:

<module name="NoClone"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Verifies there are no finalize() methods defined in a class.

To configure the check:

<module name="NoFinalizer"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that an overriding clone() method invokes super.clone().

Reference: Object.clone().

To configure the check:

<module name="SuperClone"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that an overriding finalize() method invokes super.finalize().

Reference: Cleaning Up Unused Objects.

To configure the check:

<module name="SuperFinalize"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Catching java.lang.Exception, java.lang.Error or java.lang.RuntimeException is almost never acceptable.

Rationale: Junior developers often simply catch Exception in an attempt to handle multiple exception classes. This unfortunately leads to code that inadvertantly catchs NPE, OutOfMemoryErrors, etc.

name description type default value
illegalClassNames exception class names to reject list of strings "java.lang.Exception, java.lang.Throwable, java.lang.RuntimeException"

To configure the check:

<module name="IllegalCatch"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

This check can be used to ensure that types are not declared to be thrown. Declaring to throw java.lang.Error or java.lang.RuntimeException is almost never acceptable.

name description type default value
illegalClassNames throw class names to reject list of strings "java.lang.Throwable, java.lang.Error, java.lang.RuntimeException"
ignoredMethodNames names of methods to ignore list of strings finalize

To configure the check:

<module name="IllegalThrows"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Ensure a class is has a package declaration, and (optionally) whether the package name matches the directory name for the source file.

Rationale: Classes that live in the null package cannot be imported. Many novice developers are not aware of this.

name description type default value
ignoreDirectoryName whether to ignore checking that the package declaration matches the source directory name boolean false

To configure the check:

<module name="PackageDeclaration"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Ensures that the setUp(), tearDown()methods are named correctly, have no arguments, return void and are either public or protected.

Also ensures that suite() is named correctly, have no arguments, return junit.framewotk.Test, public and static.

Rationale: often times developers will misname one or more of these methods and not realise that the method is not being called.

To configure the check:

<module name="JUnitTestCase"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Restricts the number of return statements. Default = 2. Ignores specified methods (equals() by default).

Rationale: Too many return points can be indication that code is attempting to do too much or may be difficult to understand.

name description type default value
max maximum allowed number of return statments Integer 2
format method names to ingone regular expression ^equals$ (empty)

To configure the check so that it doesn't allow more than three return statements per method (equals() method ignored):

<module name="ReturnCount"> <property name="max" value="3"/> </module>

To configure the check so that it doesn't allow more than three return statements per method for all methods:

<module name="ReturnCount"> <property name="max" value="3"/> <property name="format" value="^$"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that particular class are never used as types in variable declarations, return values or parameters. Includes a pattern check that by default disallows abstract classes.

Rationale: Helps reduce coupling on concrete classes. In addition abstract classes should be thought of a convenience base class implementations of interfaces and as such are not types themselves.

name description type default value
tokens tokens to check subset of tokens PARAMETER_DEF, VARIABLE_DEF METHOD_DEF PARAMETER_DEF, VARIABLE_DEF METHOD_DEF
illegalClassNames classes that should not be used as types in variable declarations, return values or parameters. String Set "java.util.GregorianCalendar, java.util.Hashtable, java.util.HashSet, java.util.HashMap, java.util.ArrayList, java.util.LinkedList, java.util.LinkedHashMap, java.util.LinkedHashSet, java.util.TreeSet, java.util.TreeMap, java.util.Vector"
legalAbstractClassNames abstract classes that may be used as types. String Set
ignoredMethodNames methods that should not be checked String Set "getInitialContext, getEnvironment"
format pattern for illegal class name regular expression ^(.*[\\.])?Abstract.*$

To configure the check so that it ignore getInstance() method:

<module name="IllegalType"> <property name="ignoredMethodNames" value="getInstance"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

According to Code Conventions for the Java Programming Language , the parts of a class or interface declaration should appear in the following order:

  1. Class (static) variables. First the public class variables, then the protected, then package level (no access modifier), and then the private.
  2. Instance variables. First the public class variables, then the protected, then package level (no access modifier), and then the private.
  3. Constructors
  4. Methods
name description type default value
ignoreConstructors whether to ignore constructors Boolean false
ignoreMethods whether to ignore methods Boolean false
ignoreModifiers whether to ignore modifiers Boolean false

To configure the check:

<module name="DeclarationOrder"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Disallow assignment of parameters.

Rationale: Parameter assignment is often considered poor programming practice. Forcing developers to declare parameters as final is often onerous. Having a check ensure that parameters are never assigned would give the best of both worlds.

To configure the check:

<module name="ParameterAssignment"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks if any class or object member explicitly initialized to default for its type value (null for object references, zero for numeric types and char and false for boolean.

Rationale: each instance variable gets initialized twice, to the same value. Java initializes each instance variable to its default value (0 or null) before performing any initialization specified in the code. So in this case, x gets initialized to 0 twice, and bar gets initialized to null twice. So there is a minor inefficiency. This style of coding is a hold-over from C/C++ style coding, and it shows that the developer isn't really confident that Java really initializes instance variables to default values.

To configure the check:

<module name="ExplicitInitialization"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Check that the default is after all the cases in a switch statement.

Rationale: Java allows default anywhere within the switch statement. But it is more readable if it comes after the last case.

To configure the check:

<module name="DefaultComesLast"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that classes (except abtract one) define a ctor and don't rely on the default one.

To configure the check:

<module name="MissingCtor"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks for fall through in switch statements Finds locations where a case contains Java code - but lacks a break, return, throw or continue statement.

The check honores special comments to supress the warning. By default the text "fallthru", "fall through", "fallthrough", "falls through" and "fallsthrough" are recognized (case sensitive). The comment containing this words must be a one-liner and must be on the last none-empty line before the case triggering the warning or on the same line before the case (urgly, but possible).

switch (i){ case 0: i++; // fall through case 1: i++; // falls through case 2: { i++; } // fallthrough case 3: i++; /* fallthru */case 4: i++ break; }

Note: the check works in assumption that there is no unreachable code in the case.

name description type default value
checkLastCaseGroup Whether we need to check last case group or not. Boolean false
reliefPattern Regulare expression to match the relief comment that supresses the warning about a fall through. regular expression fallthru|falls? ?through

To configure the check:

<module name="FallThrough"/>

or

<module name="FallThrough"> <property name="reliefPattern" value="continue in next case"/> <module name="FallThrough"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks for multiple occurrences of the same string literal within a single file.

Rationale: Code duplication makes maintenance more difficult, so it can be better to replace the multiple occurrences with a constant.

name description type default value
allowedDuplicates The maximum number of occurences to allow without generating a warning Integer 1
ignoreStringsRegexp regexp pattern for ignored strings (with quotation marks) regular expression ^""$ (ignore empty strings)
ignoreOccurrenceContext Token type names where duplicate strings are ignored even if they don't match ignoredStringsRegexp. This allows you to exclude syntactical contexts like Annotations or static initializers from the check. list of token type names ANNOTATION (ignore strings inside the context of an annotation)

To configure the check:

<module name="MultipleStringLiterals"/>

To configure the check so that it allows two occurrences of each string:

<module name="MultipleStringLiterals"> <property name="allowedDuplicates" value="2"/> </module>

To configure the check so that it ignores ", " and empty strings:

<module name="MultipleStringLiterals"> <property name="ignoreStringsRegexp" value='^(("")|(", "))$'/> </module>

To configure the check so that it flags duplicate strings in all syntactical contexts, even in annotations like @SuppressWarnings("unchecked"):

<module name="MultipleStringLiterals"> <property name="ignoreOccurrenceContext" value=""/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that each variable declaration is in its own statement and on its own line.

Rationale: the SUN Code conventions chapter 6.1 recommends that declarations should be one per line/statement.

To configure the check:

<module name="MultipleVariableDeclarations"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks that code doesn't rely on the "this." default, i.e. references to instance variables and methods of the present object are explicitly of the form "this.varName" or "this.methodName(args)".

name description type default value
checkFields whether we should check fields usage or not boolean true
checkMethods whether we should check methods usage or not boolean true

To configure the default check:

<module name="RequireThis"/>

To configure to check this qualifier for fields only:

<module name="RequireThis"> <property name="checkMethods" value="false"/> </module>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks for the use of unnecessary parentheses.

To configure the check:

<module name="UnnecessaryParentheses"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

Checks there is only one statement per line. The following line will be flagged as an error:

x = 1; y = 2; // Two statments on a single line.

To configure the check:

<module name="OneStatementPerLine"/>

com.puppycrawl.tools.checkstyle.checks.coding

TreeWalker

checkstyle-5.6/src/xdocs/config_design.xml100644 0 0 34054 11453312066 16127 0ustar 0 0 Class Design Checkstyle Development Team

Checks visibility of class members. Only static final members may be public; other class members must be private unless property protectedAllowed or packageAllowed is set.

Public members are not flagged if the name matches the public member regular expression (contains "^serialVersionUID$" by default). Note: Checkstyle 2 used to include "^f[A-Z][a-zA-Z0-9]*$" in the default pattern to allow CMP for EJB 1.1 with the default settings. With EJB 2.0 it is not longer necessary to have public access for persistent fields, hence the default has been changed.

Rationale: Enforce encapsulation.

name description type default value
packageAllowed whether package visible members are allowed boolean false
protectedAllowed whether protected members are allowed boolean false
publicMemberPattern pattern for public members that should be ignored regular expression ^serialVersionUID$

To configure the check:

<module name="VisibilityModifier"/>

To configure the check so that it allows package visible members:

<module name="VisibilityModifier"> <property name="packageAllowed" value="true"/> </module>

To configure the check so that it allows no public members:

<module name="VisibilityModifier"> <property name="publicMemberPattern" value="^$"/> </module>

com.puppycrawl.tools.checkstyle.checks.design

TreeWalker

Checks that a class which has only private constructors is declared as final.

To configure the check:

<module name="FinalClass"/>

com.puppycrawl.tools.checkstyle.checks.design

TreeWalker

Implements Bloch, Effective Java, Item 17 - Use Interfaces only to define types.

According to Bloch, an interface should describe a type. It is therefore inappropriate to define an interface that does not contain any methods but only constants. The Standard class javax.swing.SwingConstants is an example of a class that would be flagged by this check.

The check can be configured to also disallow marker interfaces like java.io.Serializable, that do not contain methods or constants at all.

name description type default value
allowMarkerInterfaces Controls whether marker interfaces like Serializable are allowed. Boolean true

To configure the check:

<module name="InterfaceIsType"/>

com.puppycrawl.tools.checkstyle.checks.design

TreeWalker

Make sure that utility classes (classes that contain only static methods or fields in their API) do not have a public constructor.

Rationale: Instantiating utility classes does not make sense. Hence the constructors should either be private or (if you want to allow subclassing) protected. A common mistake is forgetting to hide the default constructor.

If you make the constructor protected you may want to consider the following constructor implementation technique to disallow instantiating subclasses:

public class StringUtils // not final to allow subclassing { protected StringUtils() { // prevents calls from subclass throw new UnsupportedOperationException(); } public static int count(char c, String s) { // ... } }

To configure the check:

<module name="HideUtilityClassConstructor"/>

com.puppycrawl.tools.checkstyle.checks.design

TreeWalker

Checks that classes are designed for extension. More specifically, it enforces a programming style where superclasses provide empty "hooks" that can be implemented by subclasses.

The exact rule is that nonprivate, nonstatic methods of classes that can be subclassed must either be

  • abstract or
  • final or
  • have an empty implementation

Rationale: This API design style protects superclasses against beeing broken by subclasses. The downside is that subclasses are limited in their flexibility, in particular they cannot prevent execution of code in the superclass, but that also means that subclasses cannot corrupt the state of the superclass by forgetting to call the super method.

None.

To configure the check:

<module name="DesignForExtension"/>

com.puppycrawl.tools.checkstyle.checks.design

TreeWalker

Ensures that exceptions (defined as any class name conforming to some regular expression) are immutable. That is, have only final fields.

The current algorithm is very simple it checks that all members of exception are final. User can still mutates an exception's instance (e.g. Throwable has setStackTrace(StackTraceElement[] stackTrace) method which changes stack trace). But, at least, all information provided by this exception type is unchangable.

Rationale: Exception instances should represent an error condition. Having non final fields not only allows the state to be modified by accident and therefore mask the original condition but also allows developers to accidentally forget to initialise state thereby leading to code catching the exception to draw incorrect conclusions based on the state.

name description type default value
format pattern for name of exception class. regular expression ^.*Exception$|^.*Error$

To configure the check:

<module name="MutableException"/>

com.puppycrawl.tools.checkstyle.checks.design

TreeWalker

Restricts throws statements to a specified count (default = 1).

Rationale: Exceptions form part of a methods interface. Declaring a method to throw too many differently rooted exceptions makes exception handling onerous and leads to poor programming practices such as catch (Exception). This check forces developers to put exceptions into a heirachy such that in the simplest case, only one type of exception need be checked for by a caller but allows any sub-classes to be caught specifically if necessary.

name description type default value
max maximum allowed number of throws statments Integer 1

To configure the check so that it doesn't allow more than two throws per method:

<module name="ThrowsCount"> <property name="max" value="2"/> </module>

com.puppycrawl.tools.checkstyle.checks.design

TreeWalker

Check nested (internal) classes/interfaces are declared at the bottom of the class after all method and field declarations.

To configure the check:

<module name="InnerTypeLast"/>

com.puppycrawl.tools.checkstyle.checks.design

TreeWalker

checkstyle-5.6/src/xdocs/config_duplicates.xml100644 0 0 10337 11451071615 17011 0ustar 0 0 Duplicate code Checkstyle Development Team

Duplicate code detection allows you to find code that has been generated by Copy/Paste programming. Duplicate code typically leads to higher maintainance cost because bugs will need to be fixed twice, more code needs to be tested, etc.

There are many trade-offs when writing a duplicate code detection tool. Some of the conflicting goals are:

  • Fast
  • Low memory usage
  • Avoid false alarms
  • Support multiple/arbitrary languages (Java, JSP, C++, ...)
  • Support Fuzzy matches (comments, whitespace, linebreaks, variable renaming, etc.)

The check provided here, StrictDuplicateCode, is fast enough to facilitate checking very large code bases in acceptable time (minutes). It consumes very little memory, false alarms are impossible. While it supports multiple languages it does not support fuzzy matches (that's why it's called Strict).

Note that there are brilliant commercial implementations of duplicate code detection tools. One that is particularly noteworthy is Simian from RedHill Consulting, Inc. Simian has managed to find a very good balance of the above tradeoffs. It is superior to the checks in this package in many repects. Simian is reasonably priced (free for noncommercial projects) and includes a Checkstyle plugin.

The following table summarizes the characteristics of the available Checkstyle plugins for duplicate code detection:

Name Speed Memory Usage False Alarms Supported languages Fuzzy matches
StrictDuplicateCode High Very Low Impossible any language No
Simian Very high Low Possible but very unlikely many languages, including Java and C/C++/C# Limited support

We encourage all users of Checkstyle to evaluate Simian as an alternative to the Checks we offer in our distribution.

Performs a line-by-line comparison of all code lines and reports duplicate code if a sequence of lines differs only in indentation. All import statements in Java code are ignored, any other line - including javadoc, whitespace lines between methods, etc. - is considered (which is why the check is called strict).

name description type default value
min how many lines must be equal to be considered a duplicate int 12
fileExtensions file type extension of files to process String Set {}

To configure the check:

<module name="StrictDuplicateCode"/>

To configure the check so that it allows larger equivalent blocks:

<module name="StrictDuplicateCode"> <property name="min" value="15"/> </module>

com.puppycrawl.tools.checkstyle.checks.duplicates

Checker

checkstyle-5.6/src/xdocs/config_header.xml100644 0 0 25606 11451071615 16111 0ustar 0 0 Headers Checkstyle Development Team

Checks that a source file begins with a specified header. Property headerFile specifies a file that contains the required header. Alternatively, the header specification can be set directly in the header property without the need for an external file.

Property ignoreLines specifies the line numbers to ignore when matching lines in a header file. This property is very useful for supporting headers that contain copyright dates. For example, consider the following header:

line 1: //////////////////////////////////////////////////////////////////// line 2: // checkstyle: line 3: // Checks Java source code for adherence to a set of rules. line 4: // Copyright (C) 2002 Oliver Burn line 5: ////////////////////////////////////////////////////////////////////

Since the year information will change over time, you can tell Checkstyle to ignore line 4 by setting property ignoreLines to 4.

name description type default value
headerFile name of the file containing the required header string null
charset character encoding to use when reading the headerFile string the charset property of the parent Checker module
header the required header specified inline. Individual header lines must be separated by the string "\n" (even on platforms with a different line separator), see examples below. string null
ignoreLines line numbers to ignore list of integers {}
fileExtensions file type extension of files to process String Set {}

To configure the check to use header file "java.header" and ignore lines 2, 3, and 4 and only process Java files:

<module name="Header"> <property name="headerFile" value="java.header"/> <property name="ignoreLines" value="2, 3, 4"/> <property name="fileExtensions" value="java"/> </module>

To configure the check to verify that each file starts with the header

// Copyright (C) 2004 MyCompany // All rights reserved

without the need for an external header file:

<module name="Header"> <property name="header" value="// Copyright (C) 2004 MyCompany\n// All rights reserved"/> </module>

com.puppycrawl.tools.checkstyle.checks.header

Checker

Checks the header of a source file against a header that contains a regular expression for each line of the source header.

Rationale: In some projects checking against a fixed header is not sufficient, e.g. the header might require a copyright line where the year information is not static.

For example, consider the following header:

line 1: ^/{71}$ line 2: ^// checkstyle:$ line 3: ^// Checks Java source code for adherence to a set of rules\.$ line 4: ^// Copyright \(C\) \d\d\d\d Oliver Burn$ line 5: ^// Last modification by \$Author.*\$$ line 6: ^/{71}$ line 7: line 8: ^package line 9: line 10: ^import line 11: line 12: ^/\*\* line 13: ^ \*([^/]|$) line 14: ^ \*/

Lines 1 and 6 demonstrate a more compact notation for 71 '/' characters. Line 4 enforces that the copyright notice includes a four digit year. Line 5 is an example how to enforce revision control keywords in a file header. Lines 12-14 is a template for javadoc (line 13 is so complicated to remove conflict with and of javadoc comment).

Different programming languages have different comment syntax rules, but all of them start a comment with a non-word character. Hence you can often use the non-word character class to abstract away the concrete comment syntax and allow checking the header for different languages with a single header definition. For example, consider the following header specification (note that this is not the full Apache license header):

line 1: ^#! line 2: ^<\?xml.*>$ line 3: ^\W*$ line 4: ^\W*Copyright 2006 The Apache Software Foundation or its licensors, as applicable\.$ line 5: ^\W*Licensed under the Apache License, Version 2\.0 \(the "License"\);$ line 6: ^\W*$

Lines 1 and 2 leave room for technical header lines, e.g. the "#!/bin/sh" line in Unix shell scripts, or the xml file header of XML files. Set the multiline property to "1, 2" so these lines can be ignored for file types where they do no apply. Lines 3 through 6 define the actual header content. Note how lines 2, 4 and 5 use escapes for characters that have special regexp semantics.

name description type default value
headerFile name of the file containing the required header string null
charset character encoding to use when reading the headerFile string the charset property of the parent Checker module
header the required header specified inline. Individual header lines must be separated by the string "\n" (even on platforms with a different line separator), and regular expressions must not span multiple lines. string null
multiLines line numbers to repeat (zero or more times) list of integers {}
fileExtensions file type extension of files to process String Set {}

To configure the check to use header file "java.header" and 10 and 13 muli-lines:

<module name="RegexpHeader"> <property name="headerFile" value="java.header"/> <property name="multiLines" value="10, 13"/> </module>

To configure the check to verify that each file starts with the header

^// Copyright \(C\) (\d\d\d\d -)? 2004 MyCompany$ ^// All rights reserved$

without the need for an external header file:

<module name="RegexpHeader"> <property name="header" value="^// Copyright \(C\) (\d\d\d\d -)? 2004 MyCompany$\n^// All rights reserved$"/> </module>

Note: ignoreLines property has been removed from this check to simplify it. To make some line optional use "^.*$" regexp for this line.

com.puppycrawl.tools.checkstyle.checks.header

Checker

checkstyle-5.6/src/xdocs/config_imports.xml100644 0 0 45275 11631376756 16400 0ustar 0 0 Imports Checkstyle Development Team

Checks that there are no import statements that use the * notation.

Rationale: Importing all classes from a package or static members from a class leads to tight coupling between packages or classes and might lead to problems when a new version of a library introduces name clashes.

name description type default value
excludes packages where star imports are allowed. Note that this property is not recursive, subpackages of excluded packages are not automatically excluded. list of strings empty list
allowClassImports whether to allow starred class imports like import java.util.*;. Boolean false
allowStaticMemberImports whether to allow starred static member imports like import static org.junit.Assert.*; Boolean false

An example how to configure the check so that star imports from packages java.io and java.net as well as static members from class from java.lang.Math are allowed:

<module name="AvoidStarImport"> <property name="excludes" value="java.io,java.net,java.lang.Math"/> <property name="allowClassImports" value="false"/> <property name="allowStaticMemberImports" value="false"/> </module>

com.puppycrawl.tools.checkstyle.checks.imports

TreeWalker

Checks that there are no static import statements.

Rationale: Importing static members can lead to naming conflicts between class' members. It may lead to poor code readability since it may no longer be clear what class a member resides in (without looking at the import statement).

name description type default value
excludes Allows for certain classes via a star notation to be excluded such as java.lang.Math.* or specific static members to be excluded like java.lang.System.out for a variable or java.lang.Math.random for a method.
If you exclude a starred import on a class this automatically excludes each member individually.
For example: Excluding java.lang.Math.*. will allow the import of each static member in the Math class individually like java.lang.Math.PI.
list of strings empty list

An example of how to configure the check so that the java.lang.System.out member and all members from java.lang.Math are allowed:

<module name="AvoidStaticImport"> <property name="excludes" value="java.lang.System.out,java.lang.Math.*"/> </module>

com.puppycrawl.tools.checkstyle.checks.imports

TreeWalker

Checks for imports from a set of illegal packages. By default, the check rejects all sun.* packages since programs that contain direct calls to the sun.* packages are not 100% Pure Java. To reject other packages, set property illegalPkgs to a list of the illegal packages.

name description type default value
illegalPkgs packages to reject list of strings sun

To configure the check:

<module name="IllegalImport"/>

To configure the check so that it rejects packages java.io.* and java.sql.*:

<module name="IllegalImport"> <property name="illegalPkgs" value="java.io, java.sql"/> </module>

com.puppycrawl.tools.checkstyle.checks.imports

TreeWalker

Checks for redundant import statements. An import statement is considered redundant if:

  • It is a duplicate of another import. This is, when a class is imported more than once.
  • The class imported is from the java.lang package, e.g. importing java.lang.String.
  • The class imported is from the same package.

To configure the check:

<module name="RedundantImport"/>

com.puppycrawl.tools.checkstyle.checks.imports

TreeWalker

Checks for unused import statements. Checkstyle uses a simple but very reliable algorithm to report on unused import statements. An import statement is considered unused if:

  • It is not referenced in the file. The algorithm does not support wild-card imports like import java.io.*;. Most IDE's provide very sophisticated checks for imports that handle wild-card imports.
  • It is a duplicate of another import. This is when a class is imported more than once.
  • The class imported is from the java.lang package. For example importing java.lang.String.
  • The class imported is from the same package.
  • Optionally: it is referenced in Javadoc comments. This check is off by default, as it is considered bad practice to introduce a compile time dependency for documentation purposes only. As an example, the import java.util.Date would be considered referenced with the Javadoc comment {@link Date}. The alternative to avoid introducing a compile time dependency would be to write the Javadoc comment as {@link java.util.Date}.

The main limitation of this check is handling the case where an imported type has the same name as a declaration, such as a member variable.

For example, in the following case the import java.awt.Component will not be flagged as unused:

import java.awt.Component; class FooBar { private Object Component; // IMHO bad practise ... }
name description type default value
processJavadoc whether to process Javadoc boolean false

To configure the check:

<module name="UnusedImports"/>

com.puppycrawl.tools.checkstyle.checks.imports

TreeWalker

Checks the ordering/grouping of imports. Features are:

  • groups imports: ensures that groups of imports come in a specific order (e.g., java. comes first, javax. comes second, then everything else)
  • adds a separation between groups : ensures that a blank line sit between each group
  • sorts imports inside each group: ensures that imports within each group are in lexicographic order
  • sorts according to case: ensures that the comparison between imports is case sensitive
  • groups static imports: ensures the relative order between regular imports and static imports (see import orders)
name description type default value
option policy on the relative order between regular imports and static imports import order under
groups list of imports groups (every group identified either by a common prefix string, or by a regular expression enclosed in forward slashes (e.g. /regexp/) list of strings empty list
ordered whether imports within group should be sorted Boolean true
separated whether imports groups should be separated by, at least, one blank line Boolean false
caseSensitive whether string comparision should be case sensitive or not Boolean true

To configure the check so that it requires that:

  • "java" and "javax" packages together first, then "org" and then all other imports
  • imports will be sorted in the groups
  • groups are separated by, at least, one blank line
  • static imports are above each local groups
<module name="ImportOrder"> <property name="groups" value="/^javax?\./,org"/> <property name="ordered" value="true"/> <property name="separated" value="true"/> <property name="option" value="above"/> </module>

com.puppycrawl.tools.checkstyle.checks.imports

TreeWalker

Controls what can be imported in each package. Useful for ensuring that application layering rules are not violated, especially on large projects.

The DTD for a import control XML document is at http://www.puppycrawl.com/dtds/import_control_1_1.dtd. It contains documentation on each of the elements and attributes.

The check validates a XML document when it loads the document. To validate against the above DTD, include the following document type declaration in your XML document:

<!DOCTYPE import-control PUBLIC
    "-//Puppy Crawl//DTD Import Control 1.1//EN"
    "http://www.puppycrawl.com/dtds/import_control_1_1.dtd">
        
name description type default value
file name of the file containing the import control configuration. string null
url url of the file containing the import control configuration. string null

To configure the check using a import control file called "import-control.xml", then have the following:

<module name="ImportControl"> <property name="file" value="import-control.xml"/> </module>

In the example below, all classes beginning with an I in the package java.awt are allowed. In the package java.io only the classes File and InputStream are allowed.

<import-control pkg="com.puppycrawl.tools.checkstyle"> <allow class="java\.awt\.I.*" regex="true"/> <allow class="java\.io\.(File|InputStream)" local-only="true" regex="true"/> </import-control>

For an example import control file, look at the file called import-control.xml which is part of the Checkstyle distribution.

com.puppycrawl.tools.checkstyle.checks.imports

TreeWalker

checkstyle-5.6/src/xdocs/config_javadoc.xml100644 0 0 70157 11456541115 16273 0ustar 0 0 Javadoc Comments Checkstyle Development Team

Checks that each Java package has a Javadoc file used for commenting. By default it only allows a package-info.java file, but can be configured to allow a package.html file.

An error will be reported if both files exist as this is not allowed by the Javadoc tool.

name description type default value
allowLegacy If set then allow the use of a package.html file. boolean false

To configure the check:

<module name="JavadocPackage"/>

com.puppycrawl.tools.checkstyle.checks.javadoc

Checker

Checks Javadoc comments for class and interface definitions. By default, does not check for author or version tags. The scope to verify is specified using the Scope class and defaults to Scope.PRIVATE. To verify another scope, set property scope to one of the Scope constants. To define the format for an author tag or a version tag, set property authorFormat or versionFormat respectively to a regular expression.

Error messages about type parameters for which no param tags are present can be suppressed by defining property allowMissingParamTags.

name description type default value
scope visibility scope where Javadoc comments are checked scope private
excludeScope visibility scope where Javadoc comments are not checked scope null
authorFormat pattern for @author tag regular expression null (tag not required)
versionFormat pattern for @version tag regular expression null (tag not required)
allowMissingParamTags whether to ignore errors when a class has type parameters but does not have matching param tags in the javadoc. boolean false
allowUnknownTags whether to ignore errors when a Javadoc tag is not recognised. boolean false
tokens definitions to check subset of tokens INTERFACE_DEF, CLASS_DEF INTERFACE_DEF, CLASS_DEF,

To configure the default check:

<module name="JavadocType"/>

To configure the check for public scope:

<module name="JavadocType"> <property name="scope" value="public"/> </module>

To configure the check for an @author tag:

<module name="JavadocType"> <property name="authorFormat" value="\S"/> </module>

To configure the check for a CVS revision version tag:

<module name="JavadocType"> <property name="versionFormat" value="\$Revision.*\$"/> </module>

To configure the check for private classes only:

<module name="JavadocType"> <property name="scope" value="private"/> <property name="excludescope" value="package"/> </module>

com.puppycrawl.tools.checkstyle.checks.javadoc

TreeWalker

Checks the Javadoc of a method or constructor. By default, does not check for unused throws. To allow documented java.lang.RuntimeExceptions that are not declared, set property allowUndeclaredRTE to true. The scope to verify is specified using the Scope class and defaults to Scope.PRIVATE. To verify another scope, set property scope to a different scope.

Error messages about parameters and type parameters for which no param tags are present can be suppressed by defining property allowMissingParamTags. Error messages about exceptions which are declared to be thrown, but for which no throws tag is present can be suppressed by defining property allowMissingThrowsTags. Error messages about methods which return non-void but for which no return tag is present can be suppressed by defining property allowMissingReturnTag.

Javadoc is not required on a method that is tagged with the @Override annotation. However under Java 5 it is not possible to mark a method required for an interface (this was corrected under Java 6). Hence Checkstyle supports using the convention of using a single {@inheritDoc} tag instead of all the other tags.

Note that only inheritable items will allow the {@inheritDoc} tag to be used in place of comments. Static methods at all visibilities, private non-static methods and constructors are not inheritable.

For example, if the following method is implementing a method required by an interface, then the Javadoc could be done as:

/** {@inheritDoc} */
public int checkReturnTag(final int aTagIndex,
                          JavadocTag[] aTags,
                          int aLineNo)

The classpath may need to be configured to locate the class information. The classpath configuration is dependent on the mechanism used to invoke Checkstyle.

name description type default value
scope visibility scope where Javadoc comments are checked scope private
excludeScope visibility scope where Javadoc comments are not checked scope null
allowUndeclaredRTE whether to allow documented exceptions that are not declared if they are a subclass of java.lang.RuntimeException boolean false
allowThrowsTagsForSubclasses whether to allow documented exceptions that are subclass of one of declared exception. boolean false
allowMissingParamTags whether to ignore errors when a method has parameters but does not have matching param tags in the javadoc. boolean false
allowMissingThrowsTags whether to ignore errors when a method declares that it throws exceptions but does have matching throws tags in the javadoc. boolean false
allowMissingReturnTag whether to ignore errors when a method returns non-void type does have a return tag in the javadoc. boolean false
allowMissingJavadoc whether to ignore errors when a method javadoc is missed. boolean false
allowMissingPropertyJavadoc Whether to allow missing Javadoc on accessor methods for properties (setters and getters). The setter and getter methods must match exactly the structures below.
public void setNumber(final int number)
{
    mNumber = number;
}

public int getNumber()
{
    return mNumber;
}

public boolean isSomething()
{
    return false;
}
              
boolean false
logLoadErrors This check may need to load exception classes mentioned in the @throws tag to check whether they are RuntimeExceptions. If loading the class fails, this property allows to control checkstyle's error handling. If set to false a classpath configuration problem is assumed and the TreeWalker stops operating on the class completely. If set to true (the default) , checkstyle assumes a typo or refactoring problem in the javadoc and logs the problem in the normal checkstyle report (potentially masking a configuration error). boolean true
suppressLoadErrors When logLoadErrors is set to true, the TreeWalker completely processes a class and displays any problems with loading exceptions as checkstyle violations. When this property is set to true, the violations generated when logLoadErrors is set true are suppressed from being reported as violations in the checkstyle report. boolean false
tokens definitions to check subset of tokens METHOD_DEF, CTOR_DEF METHOD_DEF, CTOR_DEF

To configure the default check:

<module name="JavadocMethod"/>

To configure the check for public scope and to allow documentation of undeclared RuntimeExceptions:

<module name="JavadocMethod"> <property name="scope" value="public"/> <property name="allowUndeclaredRTE" value="true"/> </module>

To configure the check for for public scope, to allow documentation of undeclared RuntimeExceptions, while ignoring any missing param tags is:

<module name="JavadocMethod"> <property name="scope" value="public"/> <property name="allowUndeclaredRTE" value="true"/> <property name="allowMissingParamTags" value="true"/> </module>

To configure the check for methods which are in private , but not in protected scope:

<module name="JavadocMethod"> <property name="scope" value="private"/> <property name="excludeScope" value="protected"/> </module>

com.puppycrawl.tools.checkstyle.checks.javadoc

TreeWalker

Checks that variables have Javadoc comments.

name description type default value
scope visibility scope where Javadoc comments are checked scope private
excludeScope visibility scope where Javadoc comments are not checked scope null

To configure the default check:

<module name="JavadocVariable"/>

To configure the check for public scope:

<module name="JavadocVariable"> <property name="scope" value="public"/> </module>

To configure the check for members which are in private, but not in protected scope:

<module name="JavadocVariable"> <property name="scope" value="private"/> <property name="excludeScope" value="protected"/> </module>

com.puppycrawl.tools.checkstyle.checks.javadoc

TreeWalker

Validates Javadoc comments to help ensure they are well formed. The following checks are performed:

  • Ensures the first sentence ends with proper punctuation (That is a period, question mark, or exclamation mark, by default). Javadoc automatically places the first sentence in the method summary table and index. With out proper punctuation the Javadoc may be malformed. All items eligible for the {@inheritDoc} tag are exempt from this requirement.
  • Check text for Javadoc statements that do not have any description. This includes both completely empty Javadoc, and Javadoc with only tags such as @param and @return.
  • Check text for incomplete HTML tags. Verifies that HTML tags have corresponding end tags and issues an "Unclosed HTML tag found:" error if not. An "Extra HTML tag found:" error is issued if an end tag is found without a previous open tag.
  • Check that a package Javadoc comment is well-formed (as described above) and NOT missing from any package-info.java files.
  • Check for allowed HTML tags. The list of allowed HTML tags is "a", "abbr", "acronym", "address", "area", "b", "bdo", "big", "blockquote", "br", "caption", "cite", "code", "colgroup", "del", "div", "dfn", "dl", "em", "fieldset", "h1" to "h6", "hr", "i", "img", "ins", "kbd", "li", "ol", "p", "pre", "q", "samp", "small", "span", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thread", "tr", "tt", "ul".

These checks were patterned after the checks made by the DocCheck doclet available from Sun.

name description type default value
scope visibility scope where Javadoc comments are checked scope private
excludeScope visibility scope where Javadoc comments are not checked scope null
checkFirstSentence Whether to check the first sentence for proper end of sentence. boolean true
endOfSentenceFormat Format for matching the end of a sentence. regular expression ([.?!][ \t\n\r\f<])|([.?!]$)
checkEmptyJavadoc Whether to check if the Javadoc is missing a describing text. boolean false
checkHtml Whether to check for incomplete html tags. boolean true
tokens definitions to check subset of tokens INTERFACE_DEF, CLASS_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF INTERFACE_DEF, CLASS_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF

To configure the default check:

<module name="JavadocStyle"/>

To configure the check for public scope:

<module name="JavadocStyle"> <property name="scope" value="public"/> </module>

To configure the check for javadoc which is in private, but not in package scope:

<module name="JavadocStyle"> <property name="scope" value="private"/> <property name="excludeScope" value="package"/> </module>

To configure the check to turn off first sentence checking:

<module name="JavadocStyle"> <property name="checkFirstSentence" value="false"/> </module>

com.puppycrawl.tools.checkstyle.checks

TreeWalker

Outputs a JavaDoc tag as information. Can be used e.g. with the stylesheets that sort the report by author name. To define the format for a tag, set property tagFormat to a regular expression. This check uses two different severity levels. The normal one is used for reporting when the tag is missing. The additional one (tagSeverity) is used for the level of reporting when the tag exists.

name description type default value
tag Name of tag String null
tagFormat Format of tag regular expression null
tagSeverity Severity level when tag is found and printed severity info

An example of how to configure the check for printing author name is:

<module name="WriteTag"> <property name="tag" value="@author"/> <property name="tagFormat" value="\S"/> </module>

An example of how to configure the check to print warnings if an "@incomplete" tag is found, and not print anything if it is not found:

<module name="WriteTag"> <property name="tag" value="@incomplete"/> <property name="tagFormat" value="\S"/> <property name="severity" value="ignore"/> <property name="tagSeverity" value="warning"/> </module>

com.puppycrawl.tools.checkstyle.checks

TreeWalker

checkstyle-5.6/src/xdocs/config_metrics.xml100644 0 0 35556 11451071615 16334 0ustar 0 0 Metrics Checkstyle Development Team

Restrict the number of number of &&, ||, &, | and ^ in an expression.

Rationale: Too many conditions leads to code that is difficult to read and hence debug and maintain.

Note that the operators & and | are not only integer bitwise operators, they are also the non-shortcut versions of the boolean operators && and ||.

name description type default value
max the maximum allowed number of boolean operations in one expression. integer 3
tokens tokens to check subset of tokens LAND, BAND, LOR, BOR, BXOR LAND, BAND, LOR, BOR, BXOR

To configure the check:

<module name="BooleanExpressionComplexity"/>

To configure the check with 7 allowed operation in boolean expression:

<module name="BooleanExpressionComplexity"> <property name="max" value="7"/> </module>

To configure the check to ignore & and |:

<module name="BooleanExpressionComplexity"> <property name="tokens" value="BXOR,LAND,LOR"/> </module>

com.puppycrawl.tools.checkstyle.checks.metrics

TreeWalker

This metric measures the number of instantiations of other classes within the given class. This type of coupling is not caused by inheritance or the object oriented paradigm. Generally speaking, any abstract data type with other abstract data types as members has data abstraction coupling; therefore, if a class has a local variable that is an instantiation (object) of another class, there is data abstraction coupling. The higher the DAC, the more complex the data structure (classes) of the system.

name description type default value
max the maximum threshold allowed integer 7

To configure the check:

<module name="ClassDataAbstractionCoupling"/>

To configure the check with a threshold of 5:

<module name="ClassDataAbstractionCoupling"> <property name="max" value="5"/> </module>

com.puppycrawl.tools.checkstyle.checks.metrics

TreeWalker

The number of other classes a given class relies on. Also the square of this has been shown to indicate the amount of maintenence required in functional programs (on a file basis) at least.

name description type default value
max the maximum threshold allowed integer 20

To configure the check:

<module name="ClassFanOutComplexity"/>

To configure the check with a threshold of 10:

<module name="ClassFanOutComplexity"> <property name="max" value="10"/> </module>

com.puppycrawl.tools.checkstyle.checks.metrics

TreeWalker

Checks cyclomatic complexity against a specified limit. The complexity is measured by the number of if, while, do, for, ?:, catch, switch, case statements, and operators && and || (plus one) in the body of a constructor, method, static initializer, or instance initializer. It is a measure of the minimum number of possible paths through the source and therefore the number of required tests. Generally 1-4 is considered good, 5-7 ok, 8-10 consider re-factoring, and 11+ re-factor now!

name description type default value
max the maximum threshold allowed integer 10

To configure the check:

<module name="CyclomaticComplexity"/>

To configure the check with a threshold of 7:

<module name="CyclomaticComplexity"> <property name="max" value="7"/> </module>

com.puppycrawl.tools.checkstyle.checks.metrics

TreeWalker

The NPATH metric computes the number of possible execution paths through a function. It takes into account the nesting of conditional statements and multi-part boolean expressions (e.g., A && B, C || D, etc.).

Rationale: Nejmeh says that his group had an informal NPATH limit of 200 on individual routines; functions that exceeded this value were candidates for further decomposition - or at least a closer look.

name description type default value
max the maximum threshold allowed integer 200

To configure the check:

<module name="NPathComplexity"/>

To configure the check with a threshold of 20:

<module name="NPathComplexity"> <property name="max" value="20"/> </module>

com.puppycrawl.tools.checkstyle.checks.metrics

TreeWalker

Determines complexity of methods, classes and files by counting the Non Commenting Source Statements (NCSS). This check adheres to the specification for the JavaNCSS-Tool written by Chr. Clemens Lee.
Rougly said the NCSS metric is calculated by counting the source lines which are not comments, (nearly) equivalent to counting the semicolons and opening curly braces.
The NCSS for a class is summarized from the NCSS of all its methods, the NCSS of its nested classes and the number of member variable declarations.
The NCSS for a file is summarized from the ncss of all its top level classes, the number of imports and the package declaration.

Rationale: Too large methods and classes are hard to read and costly to maintain. A large NCSS number often means that a method or class has too many responsabilities and/or functionalities which should be decomposed into smaller units.

name description type default value
methodMaximum the maximum allowed number of non commenting lines in a method. integer 50
classMaximum the maximum allowed number of non commenting lines in a class. integer 1500
fileMaximum the maximum allowed number of non commenting lines in a file including all top level and nested classes. integer 2000

To configure the check:

<module name="JavaNCSS"/>

To configure the check with 40 allowed non commenting lines for a method:

<module name="JavaNCSS"> <property name="methodMaximum" value="40"/> </module>

com.puppycrawl.tools.checkstyle.checks.metrics

TreeWalker

checkstyle-5.6/src/xdocs/config_misc.xml100644 0 0 142436 11451071615 15635 0ustar 0 0 Miscellaneous Checkstyle Development Team

Checks whether files end with a new line.

Rationale: Any source files and text files in general should end with a newline character, especially when using SCM systems such as CVS. CVS will even print a warning when it encounters a file that doesn't end with a newline.

name description type default value
lineSeparator type of line separator One of "system" (system default), "crlf" (Windows-style), "cr" (Mac-style) and "lf" (Unix-style) system default
fileExtensions file type extension of the files to check. String Set all files

To configure the check:

<module name="NewlineAtEndOfFile"/>

To configure the check to always use Unix-style line separators:

<module name="NewlineAtEndOfFile"> <property name="lineSeparator" value="lf"/> </module>

To configure the check to work only on java, xml and python files:

<module name="NewlineAtEndOfFile"> <property name="fileExtensions" value="java, xml, py"/> </module>

com.puppycrawl.tools.checkstyle.checks

Checker

A check for TODO: comments. Actually it is a generic regular expression matcher on Java comments. To check for other patterns in Java comments, set property format.

name description type default value
format pattern to check regular expression TODO:

Using TODO: comments is a great way to keep track of tasks that need to be done. Having them reported by Checkstyle makes it very hard to forget about them.

To configure the check:

<module name="TodoComment"/>

To configure the check for comments that contain WARNING:

<module name="TodoComment"> <property name="format" value="WARNING"/> </module>

com.puppycrawl.tools.checkstyle.checks

TreeWalker

A FileSetCheck that ensures the correct translation of code by checking property files for consistency regarding their keys. Two property files describing one and the same context are consistent if they contain the same keys.

Consider the following properties file in the same directory:

#messages.properties hello=Hello cancel=Cancel #messages_de.properties hell=Hallo ok=OK

The Translation check will find the typo in the german hello key, the missing ok key in the default resource file and the missing cancel key in the german resource file:

messages_de.properties: Key 'hello' missing. messages_de.properties: Key 'cancel' missing. messages.properties: Key 'hell' missing. messages.properties: Key 'ok' missing.
name description type default value
fileExtensions file type extension to identify translation files. Setting this property is typically only required if your translation files are preprocessed and the original files do not have the extension .properties String Set properties

To configure the check:

<module name="Translation"/>

com.puppycrawl.tools.checkstyle.checks

Checker

Checks for uncommented main() methods (debugging leftovers).

Rationale: A main() method is often used for debug puposes. When debugging is finished, developers often forget to remove the method, which changes the API and increases the size of the resulting class/jar file. With the exception of the real program entry points, all main() methods should be removed/commented out of the sources.

name description type default value
excludedClasses pattern for qualified names of classes which are allowed to have a main method. regular expression ^$

To configure the check:

<module name="UncommentedMain"/>

To configure the check to allow main method for all classes with "Main" name:

<module name="UncommentedMain"> <property name="excludedClasses" value="\.Main$"/> </module>

com.puppycrawl.tools.checkstyle.checks

TreeWalker

Checks that long constants are defined with an upper ell. That is ' L' and not 'l'. This is in accordance to the Java Language Specification, Section 3.10.1.

looks a lot like 1.

To configure the check:

<module name="UpperEll"/>

com.puppycrawl.tools.checkstyle.checks

TreeWalker

Checks the style of array type definitions. Some like Java-style: public static void main(String[] args) and some like C-style: public static void main(String args[])

name description type default value
javaStyle Controls whether to enforce Java style (true) or C style (false). Boolean true

To configure the check to enforce Java style:

<module name="ArrayTypeStyle"/>

To configure the check to enforce C style:

<module name="ArrayTypeStyle"> <property name="javaStyle" value="false"/> </module>

com.puppycrawl.tools.checkstyle.checks

TreeWalker

Check that method/constructor/catch block parameters are final. Interface and abstract methods are not checked - the final keyword does not make sense for interface and abstract method parameters as there is no code that could modify the parameter.

Rationale: Changing the value of parameters during the execution of the method's algorithm can be confusing and should be avoided. A great way to let the Java compiler prevent this coding style is to declare parameters final.

name description type default value
tokens blocks to check subset of tokens METHOD_DEF, CTOR_DEF, LITERAL_CATCH METHOD_DEF, CTOR_DEF

To configure the check to enforce final parameters for methods and constructors:

<module name="FinalParameters"/>

To configure the check to enforce final parameters only for constructors:

<module name="FinalParameters"> <property name="tokens" value="CTOR_DEF"/> </module>

com.puppycrawl.tools.checkstyle.checks

TreeWalker

Checks for restricted tokens beneath other tokens.

WARNING: This is a very powerful and flexible check, but, at the same time, it is low level and very implementation dependent because its results depend on the grammar we use to build abstract syntax trees. Thus we recomend using other checks when they provide the desired funcionality. All in all, this check just works on the level of an abstract tree and knows nothing about language structures.

name description type default value
tokens token types to check subset of tokens declared in TokenTypes empty set
limitedTokens set of tokens with limited occurances as descendants subset of tokens declared in TokenTypes empty set
minimumDepth the mimimum depth for descendant counts Integer 0
maximumDepth the maximum depth for descendant counts Integer java.lang.Integer.MAX_VALUE
minimumNumber a minimum count for descendants Integer 0
maximumNumber a maximum count for descendants Integer java.lang.Integer.MAX_VALUE
sumTokenCounts whether the number of tokens found should be calculated from the sum of the individual token counts Boolean false
minimumMessage error message when minimum count not reached String "descendant.token.min"
maximumMessage error message when maximum count exceeded String "descendant.token.max"

Comparing this with null (i.e. this == null and this != null):

<module name="DescendantToken"> <property name="tokens" value="EQUAL,NOT_EQUAL"/> <property name="limitedTokens" value="LITERAL_THIS,LITERAL_NULL"/> <property name="maximumNumber" value="1"/> <property name="maximumDepth" value="1"/> <property name="sumTokenCounts" value="true"/> </module>

String literal equality check:

<module name="DescendantToken"> <property name="tokens" value="EQUAL,NOT_EQUAL"/> <property name="limitedTokens" value="STRING_LITERAL"/> <property name="maximumNumber" value="0"/> <property name="maximumDepth" value="1"/> </module>

Switch with no default:

<module name="DescendantToken"> <property name="tokens" value="LITERAL_SWITCH"/> <property name="maximumDepth" value="2"/> <property name="limitedTokens" value="LITERAL_DEFAULT"/> <property name="minimumNumber" value="1"/> </module>

Assert statement may have side effects (formatted for browser display):

<module name="DescendantToken"> <property name="tokens" value="LITERAL_ASSERT"/> <property name="limitedTokens" value="ASSIGN,DEC,INC,POST_DEC, POST_INC,PLUS_ASSIGN,MINUS_ASSIGN,STAR_ASSIGN,DIV_ASSIGN,MOD_ASSIGN, BSR_ASSIGN,SR_ASSIGN,SL_ASSIGN,BAND_ASSIGN,BXOR_ASSIGN,BOR_ASSIGN, METHOD_CALL"/> <property name="maximumNumber" value="0"/> </module>

Initialiser in for performs no setup (use while instead?):

<module name="DescendantToken"> <property name="tokens" value="FOR_INIT"/> <property name="limitedTokens" value="EXPR"/> <property name="minimumNumber" value="1"/> </module>

Condition in for performs no check:

<module name="DescendantToken"> <property name="tokens" value="FOR_CONDITION"/> <property name="limitedTokens" value="EXPR"/> <property name="minimumNumber" value="1"/> </module>

Switch within switch:

<module name="DescendantToken"> <property name="tokens" value="LITERAL_SWITCH"/> <property name="limitedTokens" value="LITERAL_SWITCH"/> <property name="maximumNumber" value="0"/> <property name="minimumDepth" value="1"/> </module>

Return from within a catch or finally block:

<module name="DescendantToken"> <property name="tokens" value="LITERAL_FINALLY,LITERAL_CATCH"/> <property name="limitedTokens" value="LITERAL_RETURN"/> <property name="maximumNumber" value="0"/> </module>

Try within catch or finally block:

<module name="DescendantToken"> <property name="tokens" value="LITERAL_CATCH,LITERAL_FINALLY"/> <property name="limitedTokens" value="LITERAL_TRY"/> <property name="maximumNumber" value="0"/> </module>

Too many cases within a switch:

<module name="DescendantToken"> <property name="tokens" value="LITERAL_SWITCH"/> <property name="limitedTokens" value="LITERAL_CASE"/> <property name="maximumDepth" value="2"/> <property name="maximumNumber" value="10"/> </module>

Too many local variables within a method:

<module name="DescendantToken"> <property name="tokens" value="METHOD_DEF"/> <property name="limitedTokens" value="VARIABLE_DEF"/> <property name="maximumDepth" value="2"/> <property name="maximumNumber" value="10"/> </module>

Too many returns from within a method:

<module name="DescendantToken"> <property name="tokens" value="METHOD_DEF"/> <property name="limitedTokens" value="LITERAL_RETURN"/> <property name="maximumNumber" value="3"/> </module>

Too many fields within an interface:

<module name="DescendantToken"> <property name="tokens" value="INTERFACE_DEF"/> <property name="limitedTokens" value="VARIABLE_DEF"/> <property name="maximumDepth" value="2"/> <property name="maximumNumber" value="0"/> </module>

Limit the number of exceptions a method can throw:

<module name="DescendantToken"> <property name="tokens" value="LITERAL_THROWS"/> <property name="limitedTokens" value="IDENT"/> <property name="maximumNumber" value="1"/> </module>

Limit the number of expressions in a method:

<module name="DescendantToken"> <property name="tokens" value="METHOD_DEF"/> <property name="limitedTokens" value="EXPR"/> <property name="maximumNumber" value="200"/> </module>

Disallow empty statements:

<module name="DescendantToken"> <property name="tokens" value="EMPTY_STAT"/> <property name="limitedTokens" value="EMPTY_STAT"/> <property name="maximumNumber" value="0"/> <property name="maximumDepth" value="0"/> <property name="maximumMessage" value="Empty statement is not allowed."/> </module>

Too many fields within a class:

<module name="DescendantToken"> <property name="tokens" value="CLASS_DEF"/> <property name="limitedTokens" value="VARIABLE_DEF"/> <property name="maximumDepth" value="2"/> <property name="maximumNumber" value="10"/> </module>

com.puppycrawl.tools.checkstyle.checks

TreeWalker

Checks correct indentation of Java Code.

The basic idea behind this is that while pretty printers are sometimes convienent for bulk reformats of legacy code, they often either aren't configurable enough or just can't anticipate how format should be done. Sometimes this is personal preference, other times it is practical experience. In any case, this check should just ensure that a minimal set of indentation rules are followed.

name description type default value
basicOffset how many spaces to use for new indentation level Integer 4
braceAdjustment how far brace should be indented when on next line Integer 0
caseIndent how much to indent a case label Integer 4

To configure the check:

<module name="Indentation"/>

To configure the check to enforce indentation style recommended by Sun:

<module name="Indentation"> <property name="caseIndent" value="0"/> </module>

com.puppycrawl.tools.checkstyle.checks.indentation

TreeWalker

The check to ensure that requires that comments be the only thing on a line. For the case of // comments that means that the only thing that should precede it is whitespace. It doesn't check comments if they do not end line, i.e. it accept the following: Thread.sleep( 10 <some comment here> ); Format property is intended to deal with the "} // while" example.

Rationale: Steve McConnel in "Code Complete" suggests that endline comments are a bad practice. An end line comment would be one that is on the same line as actual code. For example:

a = b + c; // Some insightful comment d = e / f; // Another comment for this line

Quoting "Code Complete" for the justfication:

  • "The comments have to be aligned so that they do not interfere with the visual structure of the code. If you don't align them neatly, they'll make your listing look like it's been through a washing machine."
  • "Endline comments tend to be hard to format...It takes time to align them. Such time is not spent learning more about the code; it's dedicated solely to the tedious task of pressing the spacebar or tab key."
  • "Endline comments are also hard to maintain. If the code on any line containing an endline comment grows, it bumps the comment farther out, and all the other endline comments will have to bumped out to match. Styles that are hard to maintain aren't maintained...."
  • "Endline comments also tend to be cryptic. The right side of the line doesn't offer much room and the desire to keep the comment on one line means the comment must be short. Work then goes into making the line as short as possible instead of as clear as possible. The comment usually ends up as cryptic as possible...."
  • "A systemic problem with endline comments is that it's hard to write a meaningful comment for one line of code. Most endline comments just repeat the line of code, which hurts more than it helps."

His comments on being hard to maintain when the size of the line changes are even more important in the age of automated refactorings.

name description type default value
format pattern for string allowed before comment. regular expression ^[\\s\\}\\);]*$
legalComment pattern for text of trailing comment which is allowed. (this patter will not be applied to multiline comments and text of comment will be trimmed before matching) regular expression (not set)

To configure the check:

<module name="TrailingComment"/>

To configure the check so it enforces only comment on a line:

<module name="TrailingComment"> <property name="format" value="^\\s*$"/> </module>

com.puppycrawl.tools.checkstyle.checks.indentation

TreeWalker

A check that makes sure that a specified pattern exists, exists less than a set number of times, or does not exist in the file.

This check combines all the functionality provided by RegexpHeader, GenericIllegalRegexp and RequiredRegexp, except supplying the regular expression from a file.

It differs from them in that it works in multiline mode. It's regular expression can span multiple lines and it checks this against the whole file at once. The others work in singleline mode. Their single or multiple regular expressions can only span one line. They check each of these against each line in the file in turn.

Note: Because of the different mode of operation there may be some changes in the regular expressions used to achieve a particular end.

In multiline mode...

  • ^ means beginning of a line, as oposed to beginning of input.
  • For beginning of input use \A.
  • $ means end of a line, as oposed to end of input.
  • For end of input use \Z.
  • Each line in the file is terminated with a newline character.

Note: Not all regexp engines are created equal. Some provide extra functions that others do not and some elements of the syntax may vary. This check makes use of the java.util.regex package, please check its documentation for details of how to construct a regular expression to achive a particular goal.

Note: When entering a regular expression as a parameter in the xml config file you must also take into account the xml rules. e.g. if you want to match a < symbol you need to enter &lt;. The regular expression should be entered on one line.

name description type default value
format pattern regular expression $^ (empty)
message message which is used to notify about violations, if empty then default(hard-coded) message is used. String ""(empty)
illegalPattern Controls whether the pattern is required or illegal. Boolean false
duplicateLimit Controls whether to check for duplicates of a required pattern, any negative value means no checking for duplicates, any positive value is used as the maximum number of allowed duplicates, if the limit is exceeded errors will be logged. Integer -1
errorLimit Controls the maximum number of errors before the check will abort. Integer 100
ignoreComments Controls whether to ignore matches found within comments. Boolean false

The following examples are mainly copied from the other 3 checks mentioned above, to show how the same results can be acheived using this check in place of them.

To use like RequiredRegexp :

An example of how to configure the check to make sure a copyright statement is included in the file:

The statement.

// This code is copyrighted

The check.

<module name="Regexp"> <property name="format" value="// This code is copyrighted"/> </module>

Your statement may be multiline.

// This code is copyrighted // (c) MyCompany

Then the check would be.

<module name="Regexp"> <property name="format" value="// This code is copyrighted\n// \(c\) MyCompany"/> </module>

Note: To search for parentheses () in a regular expression you must escape them like \(\). This is required by the regexp engine, otherwise it will think they are special instruction characters.

And to make sure it appears only once:

<module name="Regexp"> <property name="format" value="// This code is copyrighted\n// \(c\) MyCompany"/> <property name="duplicateLimit" value="0"/> </module>

It can also be useful to attach a meaningful message to the check:

<module name="Regexp"> <property name="format" value="// This code is copyrighted\n// \(c\) MyCompany"/> <property name="message" value="Copyright"/> </module>

To use like GenericIllegalRegexp :

An example of how to configure the check to make sure there are no calls to System.out.println:

<module name="Regexp"> <!-- . matches any character, so we need to escape it and use \. to match dots. --> <property name="format" value="System\.out\.println"/> <property name="illegalPattern" value="true"/> </module>

You may want to make the above check ignore comments, like this:

<module name="Regexp"> <property name="format" value="System\.out\.println"/> <property name="illegalPattern" value="true"/> <property name="ignoreComments" value="true"/> </module>

An example of how to configure the check to find trailing whitespace at the end of a line:

<module name="Regexp"> <property name="format" value="[ \t]+$"/> <property name="illegalPattern" value="true"/> <property name="message" value="Trailing whitespace"/> </module>

Note: The difference between this and the example given for GenericIllegalRegexp is necessary because \s and $ both match the newline character ("\n").

An example of how to configure the check to find case-insensitive occurrences of "debug":

<module name="Regexp"> <property name="format" value="(?i)debug"/> <property name="illegalPattern" value="true"/> </module>

Note: The (?i) at the beginning of the regular expression tells the regexp engine to ignore the case.

There is also a feature to limit the number of errors reported. When the limit is reached the check aborts with a message reporting that the limit has been reached. The default limit setting is 100, but this can be change as shown in the following example.

<module name="Regexp"> <property name="format" value="(?i)debug"/> <property name="illegalPattern" value="true"/> <property name="errorLimit" value="1000"/> </module>

To use like RegexpHeader :

To configure the check to verify that each file starts with the following multiline header.

Note the following:

  • \A means the start of the file.
  • The date can be any 4 digit number.
// Copyright (C) 2004 MyCompany // All rights reserved <module name="Regexp"> <property name="format" value="\A// Copyright \(C\) \d\d\d\d MyCompany\n// All rights reserved"/> </module>

A more complex example. Note how the import and javadoc multilines are handled, there can be any number of them.

/////////////////////////////////////////////////////////////////////// // checkstyle: // Checks Java source code for adherence to a set of rules. // Copyright (C) 2004 Oliver Burn // Last modification by $Author A.N.Other$ /////////////////////////////////////////////////////////////////////// package com.puppycrawl.checkstyle; import java.util.thing1; import java.util.thing2; import java.util.thing3; /** * javadoc line 1 * javadoc line 2 * javadoc line 3 */ <module name="Regexp"> <property name="format" value="\A/{71}\n// checkstyle:\n// Checks Java source code for adherence to a set of rules\.\n// Copyright \(C\) \d\d\d\d Oliver Burn\n // Last modification by \$Author.*\$\n/{71}\n\npackage [\w\.]*;\n\n (import [\w\.]*;\n)*\n/\*\*\n( \*[^/]*\n)* \*/"/> </module>

More examples:

The next 2 examples deal with the following example java source file:

/* * PID.java * * Copyright (c) 2001 ACME * 123 Some St. * Somewhere. * * This software is the confidential and proprietary information of ACME. * ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with * the terms of the license agreement you entered into with ACME. * * $Log: config_misc.xml,v $ * Revision 1.7 2007/01/16 12:16:35 oburn * Removing all reference to mailing lists * * Revision 1.6 2005/12/25 16:13:10 o_sukhodolsky * Fix for rfe 1248106 (TYPECAST is now accepted by NoWhitespaceAfter) * * Fix for rfe 953266 (thanks to Paul Guyot (pguyot) for submitting patch) * IllegalType can be configured to accept some abstract classes which * matches to regexp of illegal type names (property legalAbstractClassNames) * * TrailingComment now can be configured to accept some trailing comments * (such as NOI18N) (property legalComment, rfe 1385344). * * Revision 1.5 2005/11/06 11:54:12 oburn * Incorporate excellent patch [ 1344344 ] Consolidation of regexp checks. * * Revision 1.3.8.1 2005/10/11 14:26:32 someone * Fix for bug 251. The broken bit is fixed */ package com.acme.tools; import com.acme.thing1; import com.acme.thing2; import com.acme.thing3; /** * * <P> * <I>This software is the confidential and proprietary information of * ACME (<B>"Confidential Information"</B>). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with ACME.</I> * </P> * * &#169; copyright 2002 ACME * * @author Some Body */ public class PID extends StateMachine implements WebObject.Constants { /** javadoc. */ public static final int A_SETPOINT = 1; . . . } // class PID

This checks for the presence of the header, the first 16 lines.

Note the following:

  • Line 2 and 13 contain the file name. These are checked to make sure they are the same, and that they match the class name.
  • The date can be any 4 digit number.
<module name="Regexp"> <property name="format" value="\A/\*\n \* (\w*)\.java\n \*\n \* Copyright \(c\) \d\d\d\d ACME\n \* 123 Some St\.\n \* Somewhere\.\n \*\n \* This software is the confidential and proprietary information of ACME\.\n \* \("Confidential Information"\)\. You shall not disclose such\n \* Confidential Information and shall use it only in accordance with\n \* the terms of the license agreement you entered into with ACME\.\n \*\n \* \$Log: config_misc.xml,v $ \* \Revision 1.7 2007/01/16 12:16:35 oburn \* \Removing all reference to mailing lists \* \ \* \Revision 1.6 2005/12/25 16:13:10 o_sukhodolsky \* \Fix for rfe 1248106 (TYPECAST is now accepted by NoWhitespaceAfter) \* \ \* \Fix for rfe 953266 (thanks to Paul Guyot (pguyot) for submitting patch) \* \IllegalType can be configured to accept some abstract classes which \* \matches to regexp of illegal type names (property legalAbstractClassNames) \* \ \* \TrailingComment now can be configured to accept some trailing comments \* \(such as NOI18N) (property legalComment, rfe 1385344). \* \ \* \Revision 1.5 2005/11/06 11:54:12 oburn \* \Incorporate excellent patch [ 1344344 ] Consolidation of regexp checks. \* \\n(.*\n)*([\w|\s]*( class | interface )\1)"/> <property name="message" value="Correct header not found"/> </module>

This checks for the presence of a copyright notice within the class javadoc, lines 24 to 37.

<module name="Regexp"> <property name="format" value="(/\*\*\n)( \*.*\n)*( \* &lt;P&gt;\n \* &lt;I&gt; This software is the confidential and proprietary information of\n \* ACME \(&lt;B&gt;&quot;Confidential Information&quot;&lt;/B&gt; \)\. You shall not\n \* disclose such Confidential Information and shall use it only in\n \* accordance with the terms of the license agreement you entered into\n \* with ACME\.&lt;/I&gt;\n \* &lt;/P&gt;\n \*\n \* &#169; copyright \d\d\d\d ACME\n \*\n \* @author .*)(\n\s\*.*)*/\n[\w|\s]*( class | interface )"/> <property name="message" value="Copyright in class/interface Javadoc"/> <property name="duplicateLimit" value="0"/> </module>

Note: To search for things that mean something in xml, like < you need to escape them like &lt;. This is required so the xml parser does not act on them, but instead passes the correct character to the regexp engine.

com.puppycrawl.tools.checkstyle.checks

TreeWalker

Checks that the outer type name and the file name match. For example, the class Foo must be in a file named Foo.java.

None.

To configure the check:

<module name="OuterTypeFilename"/>

com.puppycrawl.tools.checkstyle.checks

TreeWalker

checkstyle-5.6/src/xdocs/config_modifier.xml100644 0 0 13025 11545733667 16467 0ustar 0 0 Modifiers Checkstyle Development Team

Checks that the order of modifiers conforms to the suggestions in the Java Language specification, sections 8.1.1, 8.3.1 and 8.4.3. The correct order is:

  1. public
  2. protected
  3. private
  4. abstract
  5. static
  6. final
  7. transient
  8. volatile
  9. synchronized
  10. native
  11. strictfp

To configure the check:

<module name="ModifierOrder"/>

com.puppycrawl.tools.checkstyle.checks.modifier

TreeWalker

Checks for redundant modifiers in:

  1. interface and annotation definitions,
  2. the final modifier on methods of final classes, and
  3. inner interface declarations that are declared as static

Rationale: The Java Language Specification strongly discourages the usage of "public" and "abstract" for method declarations in interface definitions as a matter of style.

Variables in interfaces and annotations are automatically public, static and final, so these modifiers are redundant as well.

As annotations are a form of interface, their fields are also automatically public, static and final just as their annotation fields are automatically public and abstract.

Final classes by definition can not be extended so the final modifier on the method of a final class is redundant.

name description type default value
tokens tokens to check subset of tokens METHOD_DEF, VARIABLE_DEF, ANNOTATION_FIELD_DEF, INTERFACE_DEF METHOD_DEF, VARIABLE_DEF, ANNOTATION_FIELD_DEF, INTERFACE_DEF

To configure the check:

<module name="RedundantModifier"/>

To configure the check to check only methods and not variables:

<module name="RedundantModifier"> <property name="tokens" value="METHOD_DEF"/> </module>

com.puppycrawl.tools.checkstyle.checks.modifier

TreeWalker

checkstyle-5.6/src/xdocs/config_naming.xml100644 0 0 25263 11452563037 16136 0ustar 0 0 Naming Conventions Checkstyle Development Team

Each of these naming modules validates identifiers for particular code elements. Valid identifiers for a naming module are specified by its format property. The value of format is a regular expression for valid identifiers. This is an example of a configuration of the MemberName module to ensure that member identifiers begin with 'm', followed by an upper case letter, and then letters and digits:

<module name="MemberName"> <property name="format" value="^m[A-Z][a-zA-Z0-9]*$"/> </module>

All naming modules belong to package com.puppycrawl.tools.checkstyle.checks.naming and are submodules of TreeWalker.

module validates identifiers for default value of format
AbstractClassName abstract classes ^Abstract.*$|^.*Factory$
ClassTypeParameterName class type parameters ^[A-Z]$
ConstantName constants (static, final fields) ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$
LocalFinalVariableName local, final variables, including catch parameters ^[a-z][a-zA-Z0-9]*$
LocalVariableName local, non-final variables, including catch parameters ^[a-z][a-zA-Z0-9]*$
MemberName non-static fields ^[a-z][a-zA-Z0-9]*$
MethodName methods ^[a-z][a-zA-Z0-9]*$
MethodTypeParameterName method type parameters ^[A-Z]$
PackageName packages ^[a-z]+(\.[a-zA-Z_][a-zA-Z0-9_]*)*$
ParameterName parameters ^[a-z][a-zA-Z0-9]*$
StaticVariableName static, non-final fields ^[a-z][a-zA-Z0-9]*$
TypeName classes and interfaces ^[A-Z][a-zA-Z0-9]*$

Module LocalVariableName also has property tokens which can be used to control whether the check applies to variable declarations or catch clause parameters through tokens VARIABLE_DEF and PARAMETER_DEF. For example, the following configuration element ensures that catch clause parameters begin with "e", followed by letters and digits:

<module name="LocalVariableName"> <property name="format" value="^e[a-zA-Z0-9]*$"/> <property name="tokens" value="PARAMETER_DEF"/> </module>

Module TypeName also has property tokens which can be used to control whether the check applies to classes or interfaces through tokens CLASS_DEF and INTERFACE_DEF. For example, the following configuration element ensures that interface names begin with "I_", followed by letters and digits:

<module name="TypeName"> <property name="format" value="^I_[a-zA-Z0-9]*$"/> <property name="tokens" value="INTERFACE_DEF"/> </module>

Module MethodName also has the following properties:

name description type default value
allowClassName Controls whether to allow a method name to have the same name as the residing class name. This is not to be confused with a constructor. An easy mistake is to place a return type on a constructor declaration which turns it into a method. For example:
class MyClass {
    public void MyClass() {} //this is a method
    public MyClass() {} //this is a constructor
}
              
Boolean false

Module AbstractClassName also has the following properties:

name description type default value
ignoreModifier Controls whether to ignore checking for the abstract modifier on classes that match the name. Boolean false
ignoreName Controls whether to ignore checking the name. Realistically only useful if using the check to identify that match name and do not have the abstract modifier. name. Boolean false

The following example shows how to configure the AbstractClassName to checks names, but ignore missing abstract modifiers:

<module name="AbstractClassName"> <property name="ignoreModifier" value="true"/> </module>

The modules ConstantName, MemberName, StaticVariableName and TypeName also have the following properties:

name description type default value
applyToPublic Controls whether to apply the check to public member. Boolean true
applyToProtected Controls whether to apply the check to protected member. Boolean true
applyToPackage Controls whether to apply the check to package-private member. Boolean true
applyToPrivate Controls whether to apply the check to private member. Boolean true

The default value of format for module PackageName has been chosen to match the requirements in the Java Language specification and the Sun coding conventions. However both underscores and uppercase letters are rather uncommon, so most configurations should probably assign value ^[a-z]+(\.[a-z][a-z0-9]*)*$ to format for module PackageName, as in

<module name="PackageName"> <property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/> </module>
checkstyle-5.6/src/xdocs/config_regexp.xml100644 0 0 25075 11451011233 16141 0ustar 0 0 Regexp Checkstyle Development Team

A check for detecting single lines that match a supplied regular expression. Works with any file type.

Rationale: This check can be used to prototype checks and to find common bad practice such as calling ex.printStacktrace(), System.out.println(), System.exit(), etc.

name description type default value
format illegal pattern regular expression ^$ (empty)
message message which is used to notify about violations, if empty then default(hard-coded) message is used. String ""(empty)
ignoreCase Controls whether to ignore case when searching. Boolean false
minimum The minimum number of matches required in each file. Integer 0
maximum The maximum number of matches required in each file. Integer 0
fileExtensions file type extension of files to process String Set {}

To configure the check to find trailing whitespace at the end of a line:

<module name="RegexpSingleline"> <!-- \s matches whitespace character, $ matches end of line. --> <property name="format" value="\s+$"/> </module>

To configure the check to find trailing whitespace at the end of a line, with some slack of allowing two occurances per file:

<module name="RegexpSingleline"> <property name="format" value="\s+$"/> <!-- next line not required as 0 is the default --> <property name="minimum" value="0"/> <property name="maximum" value="2"/> </module>

An example of how to configure the check to make sure a copyright statement is included in the file:

<module name="RegexpSingleline"> <property name="format" value="This file is copyrighted"/> <property name="minimum" value="1"/> <!-- Need to specify a maximum, so 10 times is more than enough. --> <property name="maximum" value="10"/> </module>

com.puppycrawl.tools.checkstyle.checks

Checker

A check for detecting that matches across multiple lines. Works with any file type.

Rationale: This check can be used to when the regular expression can be span multiple lines.

name description type default value
format illegal pattern regular expression ^$ (empty)
message message which is used to notify about violations, if empty then default(hard-coded) message is used. String ""(empty)
ignoreCase Controls whether to ignore case when searching. Boolean false
minimum The minimum number of matches required in each file. Integer 0
maximum The maximum number of matches required in each file. Integer 0
fileExtensions file type extension of files to process String Set {}

To configure the check to find calls to print to the console:

<module name="RegexpMultiline"> <property name="format" value="System\.(out)|(err)\.print(ln)?\("/> </module>

com.puppycrawl.tools.checkstyle.checks

Checker

This class is variation on RegexpSingleline for detecting single lines that match a supplied regular expression in Java files. It supports suppressing matches in Java comments.

name description type default value
format illegal pattern regular expression ^$ (empty)
message message which is used to notify about violations, if empty then default(hard-coded) message is used. String ""(empty)
ignoreCase Controls whether to ignore case when searching. Boolean false
minimum The minimum number of matches required in each file. Integer 0
maximum The maximum number of matches required in each file. Integer 0
ignoreComments Controls whether to ignore text in comments when searching. Boolean false

To configure the check for calls to System.out.println, except in comments:

<module name="RegexpSinglelineJava"> <!-- . matches any character, so we need to escape it and use \. to match dots. --> <property name="format" value="System\.out\.println"/> <property name="ignoreComments" value="true"/> </module>

To configure the check to find case-insensitive occurrences of "debug":

<module name="RegexpSinglelineJava"> <property name="format" value="debug"/> <property name="ignoreCase" value="true"/> </module>

com.puppycrawl.tools.checkstyle.checks

TreeWalker

checkstyle-5.6/src/xdocs/config_reporting.xml100644 0 0 4652 11451071615 16650 0ustar 0 0 Reporting Configuration Checkstyle Development Team

The property checkstyle.cache.file specifies the name of a file that can be used to cache details of files that pass Checkstyle. This can significantly increase the speed of checkstyle on successive runs. The property type is string and defaults to an empty string (which means do not cache).

Checkstyle supports a mechanism for localising the output messages. If your language is not supported, please consider translating the messages in the messages.properties file. Please let us know if you translate the file.

The property checkstyle.locale.language specifies the language to use in localising the output messages. The property type is string and defaults to the default system locale language.

The property checkstyle.locale.country specifies the country to use in localising the output messages. The property type is string and defaults to the default system locale country.

The property checkstyle.basedir specifies a base directory which files are then reported relative to. For example, if a base directory is specified as c:\projects\checkstyle, then an error in the file c:\projects\checkstyle\src\dir\subdir\File.java will be reported as src\dir\subdir\File.java. The property type is string and defaults to an empty string.

checkstyle-5.6/src/xdocs/config_sizes.xml100644 0 0 44265 11451330227 16015 0ustar 0 0 Size Violations Checkstyle Development Team

Restricts the number of executable statements to a specified limit.

name description type default value
max the maximum threshold allowed integer 30
tokens members to check subset of tokens CTOR_DEF, METHOD_DEF, INSTANCE_INIT, STATIC_INIT all tokens

To configure the check:

<module name="ExecutableStatementCount"/>

To configure the check with a threshold of 20 for constructor and method definitions:

<module name="ExecutableStatementCount"> <property name="max" value="20"/> <property name="tokens" value="CTOR_DEF,METHOD_DEF"/> </module>

com.puppycrawl.tools.checkstyle.checks.sizes

TreeWalker

Checks for long source files.

Rationale: If a source file becomes very long it is hard to understand. Therefore long classes should usually be refactored into several individual classes that focus on a specific task.

name description type default value
max maximum allowable number of lines integer 2000
fileExtensions file type extension of files to process String Set {}

To configure the check to accept files with up to 1500 lines:

<module name="FileLength"> <property name="max" value="1500"/> </module>

com.puppycrawl.tools.checkstyle.checks.sizes

Checker

Checks for long lines.

Rationale: Long lines are hard to read in printouts or if developers have limited screen space for the source code, e.g. if the IDE displays additional information like project tree, class hierarchy, etc.

name description type default value
ignorePattern pattern for lines to ignore regular expression ^$
max maximum allowable line length integer 80

To configure the check to accept lines up to 120 characters long:

<module name="LineLength"> <property name="max" value="120"/> </module>

To configure the check to ignore lines that begin with " * ", followed by just one word, such as within a Javadoc comment:

<module name="LineLength"> <property name="ignorePattern" value="^ *\* *[^ ]+$"/> </module>
  • The calculation of the length of a line takes into account the number of expanded spaces for a tab character ('\t'). The default number of spaces is 8. To specify a different number of spaces, the user can set TreeWalker property tabWidth which applies to all Checks, including LineLength; or can set property tabWidth for LineLength alone.
  • Support for the special handling of imports in CheckStyle Version 2 has been dropped as it is a special case of regexp: The user can set property ignorePattern to ^import and achieve the same effect.

com.puppycrawl.tools.checkstyle.checks.sizes

TreeWalker

Checks for long methods and constructors.

Rationale: If a method becomes very long it is hard to understand. Therefore long methods should usually be refactored into several individual methods that focus on a specific task.

name description type default value
max maximum allowable number of lines integer 150
countEmpty whether to count empty lines and single line comments of the form // boolean true
tokens blocks to check subset of tokens METHOD_DEF, CTOR_DEF METHOD_DEF, CTOR_DEF

To configure the check:

<module name="MethodLength"/>

To configure the check so that it accepts methods with at most 60 lines:

<module name="MethodLength"> <property name="tokens" value="METHOD_DEF"/> <property name="max" value="60"/> </module>

To configure the check so that it accepts methods with at most 60 lines, not counting empty lines and single line comments:

<module name="MethodLength"> <property name="tokens" value="METHOD_DEF"/> <property name="max" value="60"/> <property name="countEmpty" value="false"/> </module>

com.puppycrawl.tools.checkstyle.checks.sizes

TreeWalker

Checks for long anonymous inner classes.

Rationale: If an anonymous inner class becomes very long it is hard to understand and to see the flow of the method where the class is defined. Therefore long anonymous inner classes should usually be refactored into a named inner class. See also Bloch, Effective Java, p. 93.

name description type default value
max maximum allowable number of lines integer 20

To configure the check to accept files with up to 60 lines:

<module name="AnonInnerLength"> <property name="max" value="60"/> </module>

com.puppycrawl.tools.checkstyle.checks.sizes

TreeWalker

Checks the number of parameters of a method or constructor.

name description type default value
max maximum allowable number of parameters integer 7
tokens declarations to check subset of tokens METHOD_DEF, CTOR_DEF METHOD_DEF, CTOR_DEF

To configure the check:

<module name="ParameterNumber"/>

To configure the check to allow 10 parameters for a method:

<module name="ParameterNumber"> <property name="max" value="10"/> <property name="tokens" value="METHOD_DEF"/> </module>

com.puppycrawl.tools.checkstyle.checks.sizes

TreeWalker

Checks for the number of types declared at the outer (or root) level in a file.

Rationale: It is considered good practice to only define one outer type per file.

name description type default value
max maximum allowable number of outer types integer 1

To configure the check to accept 1 outer type per file:

<module name="OuterTypeNumber"/>

To configure the check to accept 2 outer types per file:

<module name="OuterTypeNumber"> <property name="max" value="2"/> </module>

com.puppycrawl.tools.checkstyle.checks.sizes

TreeWalker

Checks the number of methods declared in each type. This includes the number of each scope (private, package, protected and public) as well as an overall total.

name description type default value
maxTotal maximum allowable number of methods at all scope levels integer 100
maxPrivate maximum allowable number of private methods integer 100
maxPackage maximum allowable number of package methods integer 100
maxProtected maximum allowable number of protected methods integer 100
maxPublic maximum allowable number of public methods integer 100

To configure the check with defaults:

<module name="MethodCount"/>

To configure the check to allow at most 30 methods per type:

<module name="MethodCount"> <property name="maxTotal" value="30"/> </module>

com.puppycrawl.tools.checkstyle.checks.sizes

TreeWalker

checkstyle-5.6/src/xdocs/config_whitespace.xml100644 0 0 130025 11646533001 17023 0ustar 0 0 Whitespace Checkstyle Development Team

Checks that the whitespace around the Generic tokens < and > is correct to the typical convention. The convention is not configurable.

For example the following is legal:

List<Integer> x = new ArrayList<Integer>(); List<List<Integer>> y = new ArrayList<List<Integer>>();

But the following example is not:

List < Integer > x = new ArrayList < Integer > (); List < List < Integer > > y = new ArrayList < List < Integer > > ();

None.

To configure the check:

<module name="GenericWhitespace"/>

com.puppycrawl.tools.checkstyle.checks.whitespace

TreeWalker

Checks the padding of an empty for initializer; that is whether white space is required at an empty for initializer, or such white space is forbidden. No check occurs if there is a line wrap at the initializer, as in

for ( ; i < j; i++, j--)
name description type default value
option policy on how to pad an empty for iterator pad policy nospace

To configure the check:

<module name="EmptyForInitializerPad"/>

To configure the check to require white space at an empty for iterator:

<module name="EmptyForInitializerPad"> <property name="option" value="space"/> </module>

com.puppycrawl.tools.checkstyle.checks.whitespace

TreeWalker

Checks the padding of an empty for iterator; that is whether white space is required at an empty for iterator, or such white space is forbidden. No check occurs if there is a line wrap at the iterator, as in

for (Iterator foo = very.long.line.iterator(); foo.hasNext(); )
name description type default value
option policy on how to pad an empty for iterator pad policy nospace

To configure the check:

<module name="EmptyForIteratorPad"/>

To configure the check to require white space at an empty for iterator:

<module name="EmptyForIteratorPad"> <property name="option" value="space"/> </module>

com.puppycrawl.tools.checkstyle.checks.whitespace

TreeWalker

Checks the padding between the identifier of a method definition, constructor definition, method call, or constructor invocation; and the left parenthesis of the parameter list. That is, if the identifier and left parenthesis are on the same line, checks whether a space is required immediately after the identifier or such a space is forbidden. If they are not on the same line, reports an error, unless configured to allow line breaks. To allow linebreaks after the identifier, set property allowLineBreaks to true.

name description type default value
allowLineBreaks whether a line break between the identifier and left parenthesis is allowed boolean false
option policy on how to pad method parameter pad policy nospace
tokens tokens to check subset of tokens CTOR_DEF, LITERAL_NEW, METHOD_CALL, METHOD_DEF, SUPER_CTOR_CALL CTOR_DEF, LITERAL_NEW, METHOD_CALL, METHOD_DEF, SUPER_CTOR_CALL

To configure the check:

<module name="MethodParamPad"/>

To configure the check to require a space after the identifier of a method definition, except if the left parenthesis occurs on a new line:

<module name="MethodParamPad"> <property name="tokens" value="METHOD_DEF"/> <property name="option" value="space"/> <property name="allowLineBreaks" value="true"/> </module>

com.puppycrawl.tools.checkstyle.checks.whitespace

TreeWalker

Checks that there is no whitespace after a token. More specifically, it checks that it is not followed by whitespace, or (if linebreaks are allowed) all characters on the line after are whitespace. To forbid linebreaks after a token, set property allowLineBreaks to false.

name description type default value
allowLineBreaks whether whitespace is allowed if the token is at a linebreak boolean true
tokens tokens to check subset of tokens ARRAY_INIT, BNOT, DEC, DOT, INC, LNOT, UNARY_MINUS, UNARY_PLUS, TYPECAST ARRAY_INIT, BNOT, DEC, DOT, INC, LNOT, UNARY_MINUS, UNARY_PLUS

To configure the check:

<module name="NoWhitespaceAfter"/>

To configure the check to forbid linebreaks after a DOT token:

<module name="NoWhitespaceAfter"> <property name="tokens" value="DOT"/> <property name="allowLineBreaks" value="false"/> </module>

com.puppycrawl.tools.checkstyle.checks.whitespace

TreeWalker

Checks that there is no whitespace before a token. More specifically, it checks that it is not preceded with whitespace, or (if linebreaks are allowed) all characters on the line before are whitespace. To allow linebreaks before a token, set property allowLineBreaks to true.

name description type default value
allowLineBreaks whether whitespace is allowed if the token is at a linebreak boolean false
tokens tokens to check subset of tokens SEMI, DOT, POST_DEC, POST_INC SEMI, POST_DEC, POST_INC

To configure the check:

<module name="NoWhitespaceBefore"/>

To configure the check to allow linebreaks before a DOT token:

<module name="NoWhitespaceBefore"> <property name="tokens" value="DOT"/> <property name="allowLineBreaks" value="true"/> </module>

com.puppycrawl.tools.checkstyle.checks.whitespace

TreeWalker

Checks the policy on how to wrap lines on operators.

name description type default value
option policy on how to wrap lines wrap operator policy nl
tokens tokens to check subset of tokens ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, SL, SL_ASSIGN, SR, SR_ASSIGN, STAR, STAR_ASSIGN BAND, BOR, BSR, BXOR, COLON, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR (all tokens except assignment operators)

To configure the check:

<module name="OperatorWrap"/>

To configure the check for the assignment operator, =, at the end of a line:

<module name="OperatorWrap"> <property name="tokens" value="ASSIGN"/> <property name="option" value="eol"/> </module>

com.puppycrawl.tools.checkstyle.checks.whitespace

TreeWalker

Checks the policy on the padding of parentheses; i.e. whether a space is required after a left parenthesis and before a right parenthesis, or such spaces are forbidden.

name description type default value
option policy on how to pad parentheses pad policy nospace
tokens tokens to check subset of tokens CTOR_CALL, LPAREN, METHOD_CALL, RPAREN, SUPER_CTOR_CALL CTOR_CALL, LPAREN, METHOD_CALL, RPAREN, SUPER_CTOR_CALL

To configure the check:

<module name="ParenPad"/>

To configure the check to require spaces for the parentheses of constructor, method, and super constructor calls:

<module name="ParenPad"> <property name="tokens" value="CTOR_CALL, METHOD_CALL, SUPER_CTOR_CALL"/> <property name="option" value="space"/> </module>

com.puppycrawl.tools.checkstyle.checks.whitespace

TreeWalker

Checks the policy on the padding of parentheses for typecasts. That is, whether a space is required after a left parenthesis and before a right parenthesis, or such spaces are forbidden.

name description type default value
option policy on how to pad parentheses pad policy nospace
tokens tokens to check Must have tokens TYPECAST, RPAREN TYPECAST, RPAREN

To configure the check:

<module name="TypecastParenPad"/>

To configure the check to require spaces:

<module name="TypecastParenPad"> <property name="option" value="space"/> </module>

com.puppycrawl.tools.checkstyle.checks.whitespace

TreeWalker

Checks that there are no tab characters ('\t') in the source code.

Rationale:

  • Developers should not need to configure the tab width of their text editors in order to be able to read source code.
  • From the Apache jakarta coding standards: In a distributed development environment, when the commit messages get sent to a mailing list, they are almost impossible to read if you use tabs.
name description type default value
eachLine whether to report on each line containing a tab, or just the first instance boolean false
fileExtensions file type extension of files to process String Set {}

To configure the check to report on the first instance in each file:

<module name="FileTabCharacter"/>

To configure the check to report on each line in each file:

<module name="FileTabCharacter"> <property name="eachLine" value="true"/> </module>

com.puppycrawl.tools.checkstyle.checks.whitespace

Checker

Checks that a token is followed by whitespace.

name description type default value
tokens tokens to check subset of tokens COMMA, SEMI, TYPECAST COMMA, SEMI, TYPECAST

To configure the check:

<module name="WhitespaceAfter"/>

To configure the check for whitespace only after COMMA and SEMI tokens:

<module name="WhitespaceAfter"> <property name="tokens" value="COMMA, SEMI"/> </module>

com.puppycrawl.tools.checkstyle.checks.whitespace

TreeWalker

Checks that a token is surrounded by whitespace. Empty constructor and method bodies (blocks) of the form

public MyClass() {} // empty constructor public void func() {} // empty method

may optionally be exempted from the policy using the allowEmptyMethods and allowEmptyConstructors properties.

name description type default value
tokens tokens to check subset of tokens ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, EQUAL, GE, GT, LAND, LCURLY, LE, LITERAL_ASSERT, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY, SL, SLIST, SL_ASSIGN, SR, SR_ASSIGN, STAR, STAR_ASSIGN TYPE_EXTENSION_AND all tokens
allowEmptyConstructors allow empty constructor bodies boolean false
allowEmptyMethods allow empty method bodies boolean false

To configure the check:

<module name="WhitespaceAround"/>

To configure the check for whitespace around the assignment operator, =:

<module name="WhitespaceAround"> <property name="tokens" value="ASSIGN"/> </module>

com.puppycrawl.tools.checkstyle.checks.whitespace

TreeWalker

checkstyle-5.6/src/xdocs/contributing.xml100644 0 0 10053 12022077301 16022 0ustar 0 0 Contributing Checkstyle Development Team

Hey, good to see you on this page. It means that you are considering a contribution of your own work to the Checkstyle project. We welcome anything: bugfixes, new check modules, unit tests, documentation improvements, build process simplification, etc.

This document assumes you are working with the SVN version of checkstyle and that you are familiar with some standard development tools ( SVN, Maven, JUnit).

The developer team of checkstyle is really a lazy bunch of people. We try to avoid work as best as we can, but most of all we try to avoid working on bugs that are reported by end users.

To that end, we use a set of development tools that ensure that the quality of our code is kept at a fairly high level. Like most projects today, we use JUnit to test our code. However we do take this one step further and measure the coverage of our unit tests using Cobertura. This means it is not sufficient to pass all tests, but the tests should ideally execute each line in the code. To generate the Cobertura report, run the Maven command mvn cobertura:cobertura.

Besides using unit testing, we obviously also use checkstyle to check it's own code.

The Maven command mvn clean package must pass without any errors.

If you add new end user features, remember to document them.

Once you have made sure that your changes pass the Maven command mvn clean package, the code coverage is of high standard and everthing is documented, then you are ready to submit your work.

If you have created new files, put them in a tgz file (or zip if you are on Windows). If you have changed existing files, create a unified diff using SVN. To do that, open a command line, cd to the home directory of checkstyle (where build.xml is located) and execute svn diff > mychanges.patch.

Create a new item in our patch tracker and add the tgz/zip/patch files you created. Make sure the text in the tracker explains the purpose of your contribution. When you create a tracker entry, a notification email about your contribution will automatically be sent to the developer mailing list. Be prepared to answer questions and do some polishing work.

We are not only lazy but at times we are also busy with our day jobs. This means that you might not always get an immediate answer. You are not being ignored, and we value your work - we might just be too busy to review your code, especially if it is a bit complex. If you don't get a response within two weeks, feel free to send a reminder email about your tracker item.

checkstyle-5.6/src/xdocs/extending.xml100644 0 0 1174 11451071615 15273 0ustar 0 0 Extending Checkstyle Checkstyle Development Team

This section covers the ways that Checkstyle's behaviour can be extended, including writing your own checks.

checkstyle-5.6/src/xdocs/index.xml.vm100644 0 0 22550 11714704773 15071 0ustar 0 0 Checkstyle ${projectVersion} Checkstyle Development Team

Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard. It automates the process of checking Java code to spare humans of this boring (but important) task. This makes it ideal for projects that want to enforce a coding standard.

Checkstyle is highly configurable and can be made to support almost any coding standard. An example configuration file is supplied supporting the Sun Code Conventions. As well, other sample configuration files are supplied for other well known conventions.

A good example of a report that can be produced using Checkstyle and Maven can be seen here.

Checkstyle can check many aspects of your source code. Historically its main functionality has been to check code layout issues, but since the internal architecture was changed in version 3, more and more checks for other purposes have been added. Now Checkstyle provides checks that find class design problems, duplicate code, or bug patterns like double checked locking.

For a detailed list of available checks please refer to the Standard Checks page.

The latest release of Checkstyle can be downloaded from the SourceForge download page.

If you want to live on the bleeding edge, you can checkout the current development code from Mercurial and compile yourself. Note, you will need to have the Mercurial EOL Extension enabled to ensure there are no issues with the line endings (this extension will make the files match the local operating system).

Checkstyle is most useful if you integrate it in your build process or your development environment. The distribution includes:

  • An Ant task.
  • A command line tool.

Additionally plug-ins are written by third-parties. Some of them are still based on the Checkstyle 2.4 release, although there have been many improvements since then. The known plug-ins are:

IDE / Build tool Main/Initial Author Available from Remarks
Sonar Freddy Mallet (initial author) Sonar Home Page Demo site
Eclipse/RAD/RDz David Schneider Eclipse-CS Home Page In 2007 was awarded Best Open Source Eclipse-based Developer tool .
Eclipse/RAD/RDz Roman Ivanov Project Page Extension for Eclipse-CS plugin and also an incubator for Checkstyle checks that are not present in main stream of Checkstyle. See the Wiki and Blog .
Eclipse/RAD/RDz Marco van Meegen Checklipse Home Page
IntelliJ IDEA Jakub Slawinski QAPlug Provides quality assurance features.
IntelliJ IDEA James Shiell Checkstyle-idea Project Page Provides real-time and on-demand scanning.
IntelliJ IDEA Mark Lussier JetStyle Project Page
NetBeans Petr Hejl Checkstyle Beans Problems with source code are displayed as annotations of the source
NetBeans Paul Goulbourn nbCheckStyle
NetBeans Software Quality Environment (SQE)
jCoderZ fawkeZ Combines multiple tools (CheckStyle, findbugs, PMD, Cobertura, etc.)
BlueJ Rick Giles bluejcheckstyle home page
tIDE Built in
Emacs JDE Markus Mohnen Part of the standard JDEE distribution
jEdit Todd Papaioannou JEdit CheckStylePlugin
Vim editor Xandy Johnson Plugin Homepage Vim file-type plug-in
Maven Vincent Massol Checkstyle supported out of the box example report
QALab Benoit Xhenseval QALab Home Page Supports tracking Checkstyle statistics over time.

If you have written a plugin for other IDEs, please let us know, so we can provide a link here.

checkstyle-5.6/src/xdocs/property_types.xml100644 0 0 34764 11453047637 16462 0ustar 0 0 Property Types Oliver Burn

Checkstyle is configured using properties, which are string representations. This document describes how these string representations are mapped to typed properties.

This property represents an integer. The string representation is parsed using the java.lang.Integer class.

This property represents a string. The literal string representation is used.

This property represents a boolean. The default value is false. The following string representations will map to true:

  • yes
  • true
  • on

Anything else will map to false.

This property represents a set of strings. The string representation is parsed as a set of comma (',') separated strings.

Alternatively, this property can be supplied multiple times which is equivalent to a set of comma separated strings. For example, the following:

<property name="tokens" value="DIV_ASSIGN,PLUS_ASSIGN"/>

can instead be expressed as:

<property name="tokens" value="DIV_ASSIGN"/> <property name="tokens" value="PLUS_ASSIGN"/>

This property represents a set of integers. The string representation is parsed as a set of comma (',') separated integers that are parsed using the java.lang.Integer class.

Alternatively, this property can be supplied multiple times which is equivalent to a set of comma separated integers. For example, the following:

<property name="tokens" value="42,666"/>

can instead be expressed as:

<property name="tokens" value="42"/> <property name="tokens" value="666"/>

This property represents a regular expression. The string representation is parsed using java.util.regex package.

This property represents the policy for padding with white space. The following table describes the valid options:

Option Definition
nospace Do not pad. For example, method(a, b);
space Ensure padding. For example, method( a, b );

This property represents the policy for wrapping lines on operators. The following table describes the valid options:

Option Definition
nl The operator must be on a new line. For example:
    someVariable = aBigVariableNameToMakeThings + "this may work"
                   + lookVeryInteresting;
            
eol The operator must be at the end of the line. For example:
    someVariable = aBigVariableNameToMakeThings + "this may work" +
                   lookVeryInteresting;
            

This property represents the policy for checking block statements. The following table describes the valid options:

Option Definition
text Require that there is some text in the block. For example:
    catch (Exception ex) {
        // This is a bad coding practice
    }
            
stmt Require that there is a statement in the block. For example:
    finally {
        lock.release();
    }
            

This property represents the policy for checking the placement of a left curly brace ('{'). The following table describes the valid options:

Option Definition
eol The brace must always be on the end of the line. For example:
    if (condition) {
        ...
            
nl The brace must always be on a new line. For example:
    if (condition)
    {
        ...
            
nlow If the brace will fit on the first line of the statement, taking into account maximum line length, then apply eol rule. Otherwise apply the nl rule. nlow is a mnemonic for "new line on wrap". For the example above Checkstyle will enforce:
    if (condition) {
        ...
            
But for a statement spanning multiple lines, Checkstyle will enforce:
    if (condition1 && condition2 &&
        condition3 && condition4)
    {
        ...
            

This property represents the policy for checking the placement of a right curly brace ('}'). The following table describes the valid options:

Option Definition
same The brace must be on the same line as the next statement. For example:
    try {
        ...
    } finally {
            
alone The brace must be alone on the line. For example:
    try {
        ...
    }
    finally {
            

This property represents a Java scope. The scope is treated inclusevly (as javadoc does): 'package' means all 'package', 'protected' and 'public' methods/fields/classes. The valid options are:

  • nothing
  • public
  • protected
  • package
  • private
  • anoninner

This property represents the severity level of a check violation. The valid options are:

  • ignore
  • info
  • warning
  • error

This property represents the policy for checking imports order. The following table describes the valid options:

Option Definition
top All static imports are at the top. For example:
    import static a.b.C.*;
    import static x.y.Z.*;

    import a.b.D;
    import x.y.Z;
above All static imports are above the local group. For example:
    import static a.b.C.*;
    import a.b.D;

    import static x.y.Z.*;
    import x.y.Z;
inflow All static imports are processed like non static imports. For example:
    import static a.b.C.*;
    import a.b.D;

    import x.y.Z;
    import static x.y.Z.*;
under All static imports are under the local group. For example:
    import a.b.D;
    import static a.b.C.*;

    import x.y.Z;
    import static x.y.Z.*;
bottom All static imports are at the bottom. For example:
    import a.b.D;
    import x.y.Z;

    import static a.b.C.*;
    import static x.y.Z.*;

This property represents the policy for the styles for defining elements in an annotation. The following table describes the valid options:

Option Definition
expanded The expanded version is sometimes referred to as "named parameters" in other languages. Example:
@SuppressWarnings(value={"unchecked","unused",})
compact This style can only be used when there is an element called 'value' which is either the sole element or all other elements have default values. Examples:
@SuppressWarnings({"unchecked","unused",})
and:
@SuppressWarnings("unchecked")
compact_no_array It is similar to the compact style but single value arrays are flagged. With annotations a single value array does not need to be placed in an array initializer. This style can only be used when there is an element called 'value' which is either the sole element or all other elements have default values. Example:
@SuppressWarnings("unchecked")
ignore Anything goes.

This property represents the policy for the styles for the ending parenthesis. The following table describes the valid options:

Option Definition
always Example:
@Deprecated()
never Example:
@Deprecated
ignore Anything goes.

This property represents the policy for the styles for the trailing array comma. The following table describes the valid options:

Option Definition
always Example:
@SuppressWarnings(value={"unchecked","unused",})
never Example:
@SuppressWarnings(value={"unchecked","unused"})
ignore Anything goes.
checkstyle-5.6/src/xdocs/releasenotes.xml100644 0 0 263435 12022116617 16046 0ustar 0 0 Release Notes Checkstyle Development Team

New features:

  • SuppressionFilter now supports loading a configuration from a URL reference. Thanks to Stephen for patch #3485185.

Bug fixes:

  • Fixed bug in the grammer for an edge case (bug #1667137). Thanks to Lukas Platinsky for patch #3393810.
  • DeclarationOrder handles ignoreModifiers correctly (all fields should be before ctors and methods)(bug #3429775)
  • Inner assignment is now allowed in try-with-resources (bug #3441097)
  • Fixed bug in the grammer when builtin types are used in a generic declaration (bug #3553541).

Notes:

  • Removed the DoubleCheckedLocking check, as in Java 5 (and beyond), using the volatile keyword addresses the issue. See here for more details.
  • Added Turkish message translations. Thanks to poyrazus for patch #3460908.

New features:

  • Added Java 7 support to the grammar. Thanks to Dinesh Bolkensteyn for patch #3403265.

Bug fixes:

  • Fix parsing error unexpected char: 0xFFFF which was triggered when a comment line is on a line with out newline character. Thanks to Evgeny Mandrikov for patch #3367782.
  • Fixed UnusedImports to consider @linkplain, @throws and @exception tags when the option processJavadoc is turned on.
  • RequireThis now ignores static members (bug #1155921).
  • HiddenField now treats setxYz() as a setter for xYz, and setXYz() as a setter for XYz property to comply JavaBeans specification (bug #3370946).
  • Fixed parsing errors for Unicode escape sequences. Thanks to Dinesh Bolkensteyn for patch #3412812.
  • ignoreEnhancedForColon property added to WhitespaceAround. Thanks to Travis Schneeberger for patch #1921815 (bug #1649038).

New features:

  • Enhanced UnusedImports to have the option processJavadoc to detect whether imports are used. Thanks to Lyle Hanson for patch #3267984.
  • Enhanced MagicNumber to support ignoring numbers in annotation declarations. Thanks to Julio Cesar Cabral for patch #3132984.
  • Enhanced EqualsAvoidNull to process String.equalsIgnoreCase() invocations (which can be suppressed).
  • Enhanced IllegalThrows to support ignoring methods with specified names. Thanks to Amit Shah for patch #3115439.
  • Enhanced RedundantModifier to support detecting inner interface declarations that are declared as static. Raised in bug #3222810.
  • Enhanced the ANT task, Command Line and Suppression Filter to be able to load their configuration file from either the filesystem or the classpath as a resource. Thanks to Tracy Snell for patch #3307526.

Bug fixes:

  • Fix MultipleVariableDeclarations to properly handle when multiple variable declarations are inside a for loop initializer. Thanks to Amit Shah for patch #3121071.
  • Fix memory leak in FileContentsHolder. Thanks to Evgeny Mandrikov for patch #3323517.

New features:

  • Added OuterTypeFilename that checks that the outer type name and the file name match. For example, the class Foo must be in a file named Foo.java.
  • Enhanced PackageDeclaration to optionally check that the package name matches the name of the directory containing the file.
  • Added NestedForDepth that restricts nested for blocks to a specified depth (default = 1). Thanks to Alexander Jesse for patch #1151673.
  • Added MethodCount that checks the number of methods declared in each type. This includes the number of each scope (private, package, protected and public) as well as an overall total. Thanks to Alexander Jesse for patch #1151669, which was the inspiration.
  • Added OneStatementPerLine that checks there is only one statement per line. Thanks to Alexander Jesse for patch #1144994, which was the inspiration.
  • Enhanced MagicNumber to support the parameter ignoreHashCodeMethod to ignore magic numbers in hashCode() methods. Thanks to Daniel Solano Gómez for patch #3050788.
  • Enhanced AbstractClassName to support checking that matching classes have the abstract modifier. Thanks to Danil Lopatin for patch #3043752.
  • Enhanced the property types stringSet and intSet to support being supplied multiple times to construct the equivalent of a comma separated list.
  • Enhanced AvoidStarImport to support the properties allowClassImports and allowStaticMemberImports for finer control over what is allowed. Thanks to Travis Schneeberger for patch #1939775.

Bug fixes:

  • Fix JavadocMethod checking of @throws tags for methods that throw multiple non-runtime exceptions. Thanks to Daan Kets for patch #3039869.
  • Fix HideUtilityClassConstructor to handle empty and inner classes. Thanks to Roman Ivanov for patch #3045720.

Notes:

  • Changed the default value of the property logLoadErrors to be true for the checks RedundantThrows and JavadocMethod to ensure consistent behaviour.

New features:

  • Enhanced DeclarationOrder to support properties to ignore constructors, methods and modifiers. Thanks to Steve McKay for patch #2953941.
  • Enhanced WriteTag to support empty tags, and constructor declarations. Thanks to Rolf Wojtech for patch #2724894.
  • Added InnerTypeLast to check nested (internal) classes/interfaces are declared at the bottom of the class after all method and field declarations. Thanks to Ruslan Dyachenko for patch #3027391.
  • Enhanced ImportOrder to support using regular expressions for defining groups. Thanks to Martin von Gagern for patch #2782118.

Bug fixes:

  • Fixed ImportOrder to have the sort behaviour as in release 5.0. (bug #2952881). Thanks to Steve McKay for patch #2953936.
  • Fixed JavadocStyle not handling package declarations that have annotations. (bug #2911363)

Notes:

  • Converted the build system to Maven. The directory structure has been maintained for now, rather than adopting Maven's standard directory layout . This will change once Maven has been proven.
  • The Maven <groupId> changed to be com.puppycrawl.tools (from checkstyle).
  • Introduced FileText to provide more flexibitily on how the contents of a file are represented. This allows for Checkers that wish to operate on a single character sequence instead of a list of lines. Thanks to Martin von Gagern for patch #2783226.
  • Updated third party dependencies to the latest versions. See Project Dependencies for details.
  • Made the method EmptyBlockCheck.hasText(DetailAST) protected so that it is accessible to subclasses. Requested by Steve McKay.

New features:

  • Enhanced ImportOrder check to support wildcard ('*') groups. Thanks to Steve McKay for patch #2891032.
  • Enhanced the naming checks ConstantName, MemberName, MethodName and StaticVariableName to utilise the access control tuning features of AbstractAccessControlNameCheck. Thanks to Steve McKay for patch #2893581.
  • Improve ConfigurationLoader to use a InputSource. Thanks to Martin von Gagern for patch #2782627.
  • Enhanced the ImportControl check to support regular expressions. Thanks to lbaeumer for patch #2937442.

Bug fixes:

  • Corrected build errors on javadoc generation. Thanks to Martin von Gagern for providing a patch (patch #2782630).
  • Corrected javadoc in TokenTypes class for UNARY_PLUS and UNARY_MINUS members (bug #2745145).
  • Corrected broken link in WhiteSpaceAround documentation (bug #2745287).
  • Corrected pad policy documentation for MethodParamPad (bug #2775402).
  • Added correct license information for referenced source files (bug #2778850).
  • Updated documentation for writing checks (bug #2783451).
  • Report unused Javadoc tags with no trailing whitespace(bug #2506962). Thanks to Ashlesha Patil for patch #2781021.
  • Enhanced JavadocType check to handle and report on unknown Javadoc tags. The property allowUnknownTags can be set to ignore errors. (bug #2882261)

Notes:

  • Updated dependencies: Updated google collections to version 1.0.
  • Updated documentation: Added links for 3rd party tools.

Release 5.0 is not 100% backwardly compatible with release 4.4. Most likely you will need to update your configuration file.

The following checks were added since release 4.4:

Since release 4.4 the following checks were changed from a Check to a FileSetCheck:

This means that the checks above must not be declared under the TreeWalker module anymore. For example, the following Checkstyle 4.4 configuration file:

<module name="Checker"> <module name="TreeWalker"> <module name="Header"> <property name="headerFile" value="${checkstyle.header.file}"/> </module> </module> </module>

becomes the following Checkstyle 5.0 configuration file:

<module name="Checker"> <module name="Header"> <property name="headerFile" value="${checkstyle.header.file}"/> <property name="fileExtensions" value="java"/> </module> </module>

The following checks were removed since release 4.4:

New Features since release 5.0 Beta 2:

Fixed Bugs since release 5.0 Beta 2:

  • RequireThis reported a violation when using an annotation with a member name that is the same as a member name in the enclosing class the annotation was used in (bug #2123003).

Major change to FileSetCheck architecture to move the functionality of open/reporting of files into Checker. The advantages are:

  • Reduces the logic required in each implementation of FileSetCheck
  • Reduces, but not eliminates, the number of times a file is reported as being audited.
  • Reduces the amount of times a file needs to be read in from the file system.

The motivation for this change is to convert checks that are language neutral in nature, to be based on FileSetCheck. This allows the checks to be used for other languages apart from Java. As a practical example, it is possible to ensure that JSP and XML files do not contain tabs.

New Features:

  • Added the option charset to the header checks to allow controlling the encoding of the header file (rfe 1952641).
  • New check OuterTypeNumber for enforcing the maximum number of outer types per file. Inspired by patch #1145023 from Alexander Jesse.
  • Added the option sumTokenCounts to the DescendantToken to allow for even more powerful checks. For example, detect statements like this == null.
  • Add new options to the ImportOrderCheck to make it more flexible. Thanks to David Didier for providing patch #1854213.
  • New check FileTabCharacter for ensuring that any files does not contain a tab character. It replaces TabCharacterCheck which was restricted to Java files.
  • Changed FileLength check to be a FileSetCheck.
  • Changed RegexpHeader and Header to be a FileSetCheck. Removed CrossLanguageRegexpHeader as a result.
  • Enhanced JavadocStyle to check for allowed HTML tags. Thanks to Nicolas Dordet for providing patch #2214251.
  • Enhanced JavadocMethod to be more restrictive on where {@inheritDoc} can be used. Also enhanced JavadocPackage to ensure a package-info.java file contains a comment. Thanks to Travis Schneeberger for providing patch #2294029.
  • Added the SuppressWithNearbyCommentFilter filter that uses nearby comments to suppress audit events. Thanks to Mick Killianey for providing patch #2354424.
  • Added the new checks RegexpMultiline RegexpSingleline RegexpSinglelineJava.

Fixed Bugs:

  • The NCSS complexity checker reported an incorrect fileMax value (bug #2161419).
  • Checkstyle command-line no longer reports a usage error if the user specifies a directory with the -r option that does not contain any files. Thanks to Florian for patch #2151706.
  • Fixed the LeftCurly check to ignore leading annotations. Thanks to Tim Carpenter for patch #2506439.

The 5.x release is developed using Java 5 and requires a Java 5 platform to run. If you need run a Java 1.4 or earlier, then use a Checkstyle 4.x release. As such, features for earlier versions of Java will be dropped over time.

New Features:

  • New check NoFinalizer for ensuring that a class does not define a finalize() method. Thanks to Feng Qian and Steve McKay for providing patch #1892273.
  • New check GenericWhitespace for ensuring the whitespace around the Generic tokens < and > are correct to the typical convention.
  • New check JavadocPackage for ensuring that each Java package has a Javadoc comment. Replaces the check PackageHtml which has been removed. (Bug 1228207)
  • Enhanced the JavadocMethod check to not require Javadoc if the method is tagged with the @Override annotation.
  • New check EqualsAvoidNull for ensuring that String literals is on the left side of an equals() comparison. Thanks to Travis Schneeberger for providing patch #1895152.
  • Overhaul of how the package names to be prefixed to module names are determined. See the documentation for full details. This has meant removing a supported parameter to the ANT task and the Command line. Thanks to Lars Koedderitzsch for patch #1914806.
  • New check AvoidStaticImport for ensuring there are no static import statements. Thanks to Travis Schneeberger for providing patch #1940611.
  • Enhanced the MethodName check to detect when a method name is the same as the residing class name. Thanks to Travis Schneeberger for providing patch #1892364.
  • New check NoClone for ensuring a class does not override the clone method from the Object class. Thanks to Travis Schneeberger for providing patch #1947417.
  • New checks ClassTypeParameterName and MethodTypeParameterName for type name formats. Thanks to Travis Schneeberger for providing patch #1956561.
  • Overhaul of how AbstractOptionCheck works. It now requires that the option type is a Java 5 Enum and hence the AbstractOption class has been removed.
  • Provide support in the module configuration to allow for custom messages that override the default message. This allows for messages to be easily overridden. See Custom Messages for more information. Thanks to Lars Koedderitzsch for providing patch #1917420.

Fixed Bugs:

  • Stop the WhitespaceAroundCheck from checking the Generic tokens < and >.
  • Fixed bug with incorrectly flagging an import as being unused. Bug 1860424, but as a consequence reintroduced bug 1098126. It is a catch-22 that both bugs can be solved with the current architecture.
  • Fixed bug #1649020 where generic parameters for methods recognized as HTML tags. Used patch #1936389 from Travis Schneeberger.

Notes:

  • Retired the J2EE Checks. If you are using Java 5, then you really should be using Java EE. If you need these checks, then use a Checkstyle 4.x release.
  • Applied patch #1892253 to expand access controls to other naming checks.
  • Applied patch #1993103 to make the format of end of sentence configurable in the JavadocStyle check.
  • Updated dependencies: Removed commons-collections; added google collections (google-collect-snapshot-20080321.jar); upgraded commons-cli to version 1.1.
  • Changed the classes Scope and SeverityLevel to be based on the Java 5 Enum class. Used patch #2004776 from Travis Schneeberger.

Fixed Bugs:

  • checkstyle-all.jar contained some classes from jakarta commons-collections twice. (bug 1630361)
  • Multiple string literal check now ignores annotations by default (bug 1560940). It is possible to retain the old behaviour by setting the new check property ignoreOccurrenceContext to an empty value.
  • The calculated value of NPath complexity was subject to integer overflow, so complex code was not always flagged (bug 1654769).
  • Fixed misleading documentation for BooleanExpressionComplexity check (bug 1579227).
  • Fixed Java parser error for array brackets in wildcard generic types (bug 1394014). Thanks to Paul Constantinides for submitting the fix (patch 1422247).
  • Fixed false alarm in HideUtilityClassConstructor check when class has only static methods but contains non static fields (bug 1762702).

New features:

  • Allow to control the operator token types in BooleanExpressionComplexity check (in response to bug 1579227).
  • Added an entry for Checkstyle-IDEA on the home page.
  • Set the failureProperty with a meaningful message (feature request 1725475).
  • Add a url option for ImportControl check. Thanks to Benjamin Lerman for the patch 1724683.
  • Moved source control over to Subversion.

Fixed Bugs:

  • The StrictDuplicateCode check didn't report correct results when multiple duplicate code regions were overlapping. (bug 1564465)
  • Fixed NPE in FallThrough check (bug 1472228)
  • Fixed typo in Command Line example (bug 1464595)
  • RegexpHeader check now correctly report problematic line in file with regexps for header (bug 1455575)
  • Fixed small problem in usage checks (patch 1498920). Thanks to Chris Povirk (cpovirk) for submitting the patch.
  • Fixed incorrect french translation (bug 1611403). Thanks to Fabien Bergeret for providing the correct value.

New features:

  • Major performance improvements in the StrictDuplicateCode check, especially for large projects. Also, false alarms are no longer possible.
  • New CrossLanguageRegexpHeader check that allows checking file headers for other languages than Java.
  • Applied patch 1586411 from Dennis Lundberg (dennislundberg) to add Maven POM files to the build.

New features:

  • NoWhitespaceAfter check now accepts TYPECAST token to check is there is no whitespace after typecast. (rfe 1248106).
  • IllegalType can be configured to accept some abstract classes which matches to regexp of illegal type names (property legalAbstractClassNames, rfe 953266). Thanks to Paul Guyot (pguyot) for submitting patch.
  • TrailingComment now can be configured to accept some trailing comments (such as NOI18N) (property legalComment, rfe 1385344).
  • Added WriteTag check which outputs a JavaDoc tag as information (patch 902110) Thanks to Daniel Grenner (dgrenner) for contribution.
  • Support for suppressing audit events based on an identifier that is assigned to individual modules/checks. This allows for suppressing at a finer level than the check class name. See SuppressionFilter documentation for more.
  • Added the style sheet checkstyle-frames.xsl, thanks to Paul King. (Bug 1385095).
  • Applied patch (1505376) by Clint Stotesbery to support the suppressLoadErrors property for AbstractTypeAwareCheck (RFE 1491630).
  • Upgraded to ANTLR 2.7.6.
  • GUI now displays a TextArea with the contents of the file parsed. Based on patch from sermojohn (RFE 1499180).

Fixed Bugs:

  • First attempt to fix 1000092 (RightCurlyCheck misbehaves for LIT_CATCH). The check has been rewritten to check rcurly after finally and else. Current behavior is incompatible with previous one.
  • Fixed problem in type aware checks with loading inner-classes which were referenced as <outer_class_name>.<inner_class_name> (bug 1379666, modules JavadocMethod and RedundantThrows).
  • Fix UTF-8 encoding error in XMLLogger. (bug 1369589).
  • The new property logLoadErrors of the JavaDocMethod check now allows controlling the behaviour when checkstyle cannot load a class that is referenced in javadoc (bug 1422462).
  • Tighten up the allowed use of the {@inheritDoc} tag.
  • Stop creating duplicate regular expression patterns.

Fixed Bugs:

  • Documentation for JavadocMethod check corrected to indicate that after fix for 1290379 javadoc which contains only @see tag is not valid any more (bug 1369615)
  • Fixed StackOverflowError in GenericIllegalRegexp check which may occur if ignoreComments is true and there is an illegal match in comment at the end of line. (bug 1371588)
  • InnerAssignment now ignores assignments in annotations. (bug 1369425)
  • Applied patch from Ralf (rakus) to remove javadoc's complainings. (patch 1352862)
  • Fixed StringIndexOutOfBoundsException which MethodParamPad may throws if someone tries to create object of generic class (with any params) (bug 1374792).
  • Added information to the manifest file. (bug 1380322).

New features:

  • Applied patch 1344344 by sjq to provide the new Regexp check that can provide the functionality of the following checks: RegexpHeader, GenericIllegalRegexp and RequiredRegexp.
  • Added support for property ignoreStringsRegexp to MultipleStringLiterals check. Patch 1254918 from taab.
  • Added Spanish translation of messages. Thanks to Ricardo Mones (patch 1250329).
  • Made the Class Loader used to load infrastructure classes and resources come from Thread.currentThread() .getContextClassLoader(). Done as a result of patch 1273903 from Lars Koedderitzsch.
  • Added patch The LocalizedMessage already gets the Class of the check that triggers the message (to output the name of the check). Instead of storing just the name of this class, store the class itself. With this the name can be retrieved and the classloader of this class can be used to load the correct resource bundle. Patch 1309516 from Ralf (rakus).
  • FallThrough check now can check last case group (property checkLastCaseGroup, bug 1245942).
  • Applied patch 906531 (WhitespaceAround allows empty method/ctor bodies.) Thanks to Eric Roe (module WhitespaceAround, properties allowEmptyCtors and allowEmptyMethods).
  • FallThrough check can be configured to ignore fall-thoughs if there is a relief comment, thanks to Ralf (aka rakus) for a great patch (rfe 1345691, patch 1348873)

Fixed Bugs:

  • Fixed encoding problems when parsing XML because was using FileReader instead of FileInputStream. Bug 1320132.
  • The InnerAssignment check didn't find all instances of inner assignments. Bug 1195047.
  • Fixed typo in grammar (bug 1335088)
  • Fixed ParenPad check problem which was caused by one of recent grammar change (one which was about (SUPER_)CTOR_CALL) (bug 1322879).
  • Fixed bug in logic JavadocStyle check uses to get main-section of javadoc (bug 1291847).
  • Three more fixes for Indentation check (bugs 1251988, 1260079, 1336737).
  • Fixed problem in Comment.hasIntersectionWithComment() (patch 1339523 from Richard Schulte).
  • Now javadoc method should not contain only @see tag (but could contain only {@ingeritDoc} tag) (bug 1290379, module JavadocMethod)

Other improvements:

  • Applied patch 1292684 from Maarten Coene to fix the generated HTML reports that are not correct if you include the TreeWalker and the StrictDuplicateCode modules in the same configuration. Patch effects checkstyle-noframes-sorted.xsl.
  • Applied patch 1340300 from David Dodini to update bcel checks to be compilable with current Checkstyle's API.
  • Added antlib.xml to support new cool feature of Ant.
  • Applied patch 1386388 to enable ConfigurationLoader to load from InputStream.

New features:

  • One more change for grammar: now CTOR_CALL and SUPER_CTOR_CALL nodes represents "this" and "super" keywords from these statements.

Fixed Bugs:

  • Removed all reference to the usage checks (bug 1256662).
  • RequireThis now handles inner enums better (bug 1257599)
  • Fixed package name for modifiers checks in documentation (bug 1275988)
  • MagicNumber allows use numeric constants in enum constant definition (bug 1284682)
  • Fixed i18n problems in ArrayTypeStyle, HideUtilityClassConstructor and AvoidInlineConditionals(bug 1262825)

Other improvements:

  • TBD

New features:

  • Added useFile property of ant task (patch 916971)
  • Documented new tokens which is checked by WhitespaceAround (bug 1233425)
  • Added patch (id 1193251) to suppress processing of checks with 'ignore' severity. From Lars Koedderitzsch.
  • Added IllegalThrowsCheck to detect illegal throw declarations.
  • Added ImportControlCheck to controls what packages can be imported in each package. Useful for ensuring that application layering is not violated.

Fixed Bugs:

  • HiddenField can be configured to ignore parameters of abstract methods (property ignoreAbstractMethods, bug 1084512)
  • Applied patch 1079192 (thanks to Dave Brosius)
  • Two more bugs fixed in type aware checks (RedundantThrows and JavadocMethod checks) (bug 1168408 and 1220726)
  • Applied patch 1045127 (thanks to Paul Constantinides)
  • TypecastParenPad and ParenPad are now smarter in detecting if paren is part of typecast (bug 1217798)
  • LocalFinalVariable now also checks catch parameters (bug 1223290)
  • Applied patch 1061458, hope this helps users who use checkstyle with JRokit (thank to Ville Skytta for contribution)
  • Changed way how to IndentationCheck handles fields in classes and operator new (bug 1193848, 1232822)
  • Fixed problem with cache file (patch 1012389) thanks to Dave Wood.
  • Fixed example for FinalLocalVariable snf the check itself (bug 1241722)
  • Fixed implementation of DetailAST so getPreviousSibling() works for all nodes in AST tree (bug 1244994)
  • Now type-aware check know more about generics (bug 1249707, modules: RedundantThrows and JavadocMethodCheck)

Other improvements:

  • Introduced the EMMA code coverage tool. A report is produced as a result of running the unit tests.
  • Retired the usage checks to the contrib directory. If there is interest in the future they may be promoted back into the optional set of checks.

Fixed Bugs:

  • Fix critical bug in the grammar (bug 1216844)

Fixed Bugs:

  • DesignForExtension check skips enums now (they are final :). (bug# 1194470)
  • Indentation check now works better with enums and for-each statements (bugs 1193850 and 1193855)
  • Corrected calculation of Cyclomatic complexity metric (bug 1203536, module CyclomaticComplexity)
  • SuppressionCommentFilter now silently does nothing if there is no FileContentsHolder (bug 1183749)
  • Java Parser now understands Java 5 hex float syntax (bug 1195818)

Other improvements:

  • Improved performance of reading Java files (patch 1214386, contributed by Lars Koedderitzsch)

Dependencies:

  • Since Checkstyle now requires Java 1.4, it does not need Jakarta Regexp library any more and uses java.util.regex package from J2SE instead. The regular expression specifications of these libraries use a slightly different syntax in some corner cases, e.g. for posix character classes. We expect that these differences are not relevant for the majority of checkstyle users, but please check your configuration.

Dependencies:

  • Checkstyle now requires Java 1.4, running Checkstyle inside a Java 1.3 VM is no longer supported.

Fixed Bugs:

  • The Ant task now always prints a summary line like 'Running Checkstyle 4.0 on 339 files' (bug 1099573).
  • Added missing documentation for the fileExtensions property of the NewlineAtEndOfFile check (bug 1174751).
  • Fixed bug #1098126 in UnusedImport check.
  • Fixed bug #1185722 (DeclarationCollector.leaveToken unbalanced with visitToken)
  • Fixed NPE in AbstractUsageCheck when we process an empty file (bug 1165855)

New features:

  • Introduced preliminary support (beta quality) for the Java 5 language. Previous versions of Java are still supported so this release should be a drop in replacement for the 3.5 release. The reason for the beta release is to solicit feedback on the Java 5 support.
  • Documentation contains an alphabetically sorted list of all available checks.
  • Checker.getBasedir() is public now (rfe 1023004)
  • JavadocMethod check now can be configured to skip missed javadoc (rfe 1060634)
  • Some clarifications on scope property of javadoc checks added (rfe 1009201)
  • UnusedPrivateMethod check now can be configured to ignore serializaition-related methods (readObject(), writeObject(), readResolve() and writeReplace()) (rfe 1036387)
  • Added support for the property allowMissingPropertyJavadoc on the JavadocMethod check.

Resolved bugs:

  • Fix bug with suppression filtering. (bug 1080343).
  • Improved french message translations (patch 1097980 by Olivier Parent).
  • Fixed typo in SuppressionCommentFilter which caused bug 1084654
  • Fixed 1048226 (Runtime problems of Checks are logged to checkstyle audit), now checkstyle will fail if it can not load class for exception from throws clause of javadoc (modules RedundantThrows and JavadocMethod)
  • Fixed French translation, patch from Paul Guyot (bugs 1090381 and 1100946)
  • Fixed problem with exception's javadoc checks(bug 1100193, module JavadocMethod)
  • Fixed two more problems in Indentation check (bug 1089128)
  • ConstantName check now exclude serialPersistentFields from the check (bug 1097285)
  • One more problem with SuppressionCommentFilter fixed (bug 1061459)
  • format property of IllegalType check documented (bug 1047449)
  • ModifiedControlVariable check changed to work with for-each correctly (1101851)
  • Annotations and enums are classes too and should be treated so by ClassFanOutComplexity checks (bug 1109205)
  • Two more annotation-related problems (module Indentation, bug 1109214 and module UnnecessaryParentheses, bug 1109238)

Other changes:

  • Added new check packages and moved check implementations. Users who maintain their own packagelist must adapt to these changes.

New features:

  • Added attributes maxErrors and maxWarnings to Ant task to allow finetuning of failure behaviour (request 783538).
  • Added check that checks for a required regexp, contributed by Daniel Grenner (module RequiredRegexp, request 606115, patch 902189).
  • Added check for the ncss metric. (module JavaNCSS, patch 920820)
  • Added check that checks for multiple string literals, contributed by Daniel Grenner (module MultipleStringLiterals, patch 929882).
  • Added check that checks for a modified control variable in a for loop, contributed by Daniel Grenner (module ModifiedControlVariable, patch 927680).
  • Added example of how to configure the XML parser factory for Checkstyle, and how to support XInclude processing (contrib/examples/XInclude, request 905169).
  • Added example of an ant build file and stylesheet for generation of an HTML error report with links to source code. (contrib/examples/linkErrors2Source, discussed on sourceforge.net: checkstyle-user).
  • Added filter that suppresses audit events according to source file comments, contributed by Mike McMahon (module SuppressionCommentFilter, requests 732196 and 931327).
  • Better information for unexpected char (request 666188).
  • Added charset property to TreeWalker and StrictDuplicateCode check (addresses bug 975346).
  • French message translations, contributed by Pierre Dittgen (request 978916).
  • DataAbstractionCoupling reports coupling classes, contributed by Benoit Xhenseval (request 990055).
  • FinalLocalVariable ignores parameters of interface methods and abstract methods. (request 993922 and bug 1002849).
  • Header and RegexpHeader checks allow header specification directly in the checkstyle configuration file, not only in an external file (request 1041590).
  • com.puppycrawl.tools.checkstyle.gui.Main accepts an optional file name in the command line. (request 1000102).

Resolved bugs:

  • False alarms from UnusedPrivateMethodCheck for anonymous inner class parameter. (bug 950548).
  • Fixed bug in handling imports in RequireThis(bug 952508)
  • JUnitTestCaseCheck erroneously mentions tearDown instead of setUp. (bug 955925, patch by Paul Guyot)
  • JavadocTypeCheck does not find a tag on the first comment line. (patch 959995, patch by Michael Tamm)
  • StrictDuplicateCodeCheck did not find duplicates within the same file.
  • Unexpected char (bug 975346).
  • MagicNumber check overly aggressive (reported on user mailing list).
  • Documentation error for naming convention checks (bug 987503).
  • FinalParametersCheck checks parameters of abstract methods. (bug 1002849).
  • Bug in ClassResolver where it was mismatching imports - example would match SecurityDataException when looking for DataException. Bug was visible in RedundantThrows check (no known bug).
  • Fixed HiddenFieldCheck to correctly handle static inner classes (bug 1032426).
  • Fixed misspelling of variable (patch 1032618 contibuted by Paul Wagland).
  • Fixed ClassResolver to handle exceptions which are inner for current class (bug 945149).
  • Fixed ClassResolver to handle fully-qualified inner classes (bug 1037667).
  • Fixed 1033166 (Indent module specifies two indent levels for one line)
  • Fixed false alarms in RequireThis check (bug 952508)

API changes:

  • Added new class SeverityLevelCounter.

New features:

  • Added a 'version' attribute to the 'checkstyle' element in the XML output document (request 853128).
  • FinalParameter can be applied to catch blocks (request 848820).
  • Improved german translation, contributed by Oliver Fischer (patch 862911).
  • Added stylesheet to translate xml output into comma separated valuaes format (contrib/checkstyle-csv.xsl, request 764153).
  • Added BooleanExpressionComplexity check from Simon Harris (request 750760)
  • Added ClassDataAbstractionCoupling check from Simon Harris (request 750758)
  • Added ClassFanOutComplexity check from Simon Harris (request 750759)
  • Added NPathComplexity check from Simon Harris (request 750757)
  • Added several more log() methods to AbstractViolationReporter. (request 843551)
  • Added check to ensure that default is a last label in the switch statement.(module DefaultComesLast, request 754486 )
  • Added check to ensure that all classes define constructor. (module MissingCtor, request 696129)
  • Added check to warn on fall-through in case with code not followed by break. (module FallThrough, request 754438)
  • Added check to ensure that every variable is declared in its own statement and on its own line (module MultipleVariableDeclarations, requests 639233, 753858, 844705)
  • Added check to ensure that references to non-static fields and methods should be quailified. (module RequireThis, contributed by Stephen Bloch, requests 755550, 696295).
  • Added multiLines property to regexpCheck (request 597676)
  • Added check for the padding between the identifier of a method definition, constructor definition, method call, or constructor invocation; and the left parenthesis of the parameter list. (module MethodParamPad, request 843254)
  • Added check to forbid endline comments. (module TrailingComment, request 744970)
  • Added applyTo(Public|Protected|Package|Private) properties to check MemberName. (request 695935)
  • Added check to verify padding in empty for loop initializers. (module EmptyForInitializerPad, part of fix for bug 895072)
  • Added checkEmptyJavadoc property to JavadocStyle check, contributed by Daniel Grenner (request 849056, patch 903597)
  • Added format property to ReturnCount check to configure ignored method names (request 904437)
  • Added attribute 'default' to configuration <property> tags, improves usability for centralized configuration files. This change triggered a new version of the configuration DTD. Your old configuration files will still work, but if you want to use the new 'default' attribute you need to upgrade your configuration file to DTD version 1.2.
  • Ignore comments in GenericIllegalRegexp check, contributed by Daniel Grenner (request 680988, patch 902109).
  • UnnecessaryParentheses check contributed by Eric Roe (patch 911086, request 634834)
  • Added ignoreNonLocal property to UnusedParameter check to check only private and static methods (request 787683)
  • Added excludeScope property to Javadoc(Method|Variable|Type|Style) checks (request 846108)

Resolved bugs:

  • Incorrect documentation of cmdline options (bug 865610).
  • FinalParameter now reports column of start of parameter declaration. (bug 864900)
  • Fixed inconsistent handling of NLOW (new line on wrap) option by LeftCurly check. (bug 866501)
  • JDK 1.4 classes used by usage checks. (bug 876570)
  • Error in reporting UnusedLocalVariable for multi-dimensional array index. (bug 878608)
  • MagicNumberCheck throws NumberFormatException with negative octal and hex ints and longs.
  • JavadocStyleCheck throws StringIndexOutOfBoundsException when open tag character, <, is the last character on a line.
  • UnusedPrivateMethod false positive (ternary call). (bug 880954)
  • Cast causes MagicNumberCheck error. (bug 890706)
  • Conflict between ParenPad and NoWhiteSpaceBefore when code uses empty for loop initializers. (bug 895072)
  • Fixed JavadocStyleCheck to handle inline javadoc tags correctly (bug 897749)
  • Updated documentation for ReturnCount check to reflect that it doesn't check equals() method (bug 904443)
  • Erroneous UnusedPrivateField error when the left operand is enclosed in parentheses and the field is in the right operand (bug 908339)
  • ExplicitInitialization shouldn't report about explicitly initialized member of interface (bug 909619)
  • DesignForExtension fires for private inner classes (bug 884035).
  • Entity resolver for configuration files now handles all previous versions of the configuration DTD locally, without accessing the internet (bug 909987).
  • Fixed handling of imports for inner classes in RedundantThrows (bug 925263)

Removed features:

  • Removed ignoreLines property of RegexpHeader check. To make some line optional use "^.*$" regexp for this line.
  • Fixing bug 895072 required changing the logic of the NoWhiteSpaceBefore and ParenPad checks. When a for loop has an empty initializer (like for (; i < j; i++)) both checks will not check whitespace between the opening parenthesis and the first semicolon any more. To enforce your coding rules for such code, you need to use the EmptyForInitializerPad check.

API changes:

  • Added programmatic access to token type documentation (request 724871)
  • All comments are wrapped in TextBlocks (request 885993).

Distribution:

  • Renamed checkstyle-version-optional.jar to checktyle-optional-version.jar to make the distribution Maven friendly.

New features:

  • Fixed grammar build process (request 827781).
  • Added caseSensitive property to ImportOrder check (bug 842604).
  • Added classpathref property to ant task (patch 835896, from Ville Skytta (scop)).

Resolved bugs:

  • Removed MutableException dependency from 1.4 API.(bug 842756)
  • j2ee.EntityBean check for constructor is incorrect (bug 846110).
  • Fixed ArrayIndexOutOfBounds in JavaStyle (bug 841942).
  • Fixed 8433887 - XHTML not handled correctly in JavadocStyle.
  • Fixed ArrayTypeStyle error when type declaration and variable/method name are placed on different lines (bug 848750).
  • Fixed several typos in documentation (patch 848483 from Ville Skytta (scop)).
  • xmllogger.dtd is out-of-date (bug 847974).
  • ArrayTypeStyle shouldn't check method definition (bug 849450).
  • Added link to summary page in checkstyle-frames.xsl (bug 852397).
  • Fixed bug #791245: checkstyle-frames.xsl cannot handle multiple leafs.
  • Fixed handling of inheritDoc in JavadocMethod check (bug 855839).
  • Fixed bug #853225 - Indentation gives false errors.
  • Wrong documentation for FinalLocalVariable (bug 860990).

Distribution:

  • Checks that are designed to be used for a special class of applications (like J2EE) or that require external libraries are now distributed in a separate jar file. This is similar to the way the Ant distribution is organized. See the documentation of optional checks for details.
  • Updated Jakarta Regexp library to version 1.3.

New features:

  • Added ability for user to incorporate custom listeners (requests 738205, 738388). Example listeners perform verbose and Commons Logging audits (request 737584).
  • Added JavadocStyle check to ensure they are stylistically well formed. Nice patch from Chris Stillwell.
  • Added check for trailing comma in array initialization (module ArrayTrailingComma, request 696301).
  • MagicNumberCheck now checks array initializers (request 745949).
  • Added check for uncommented main methods (debugging leftovers). (module UncommentedMain, request 732257)
  • Added check to enforce that anonymous inner classes do not exceed a certain length (module AnonInnerLength, request 715709, contributed by Rob Worth).
  • Added TypecastParenPadCheck to check the padding of typecasts (bug 750348).
  • Added ignoreFormat property to HiddenFieldCheck (request 748830).
  • Nice patch from Matt Quail to DetailAST to replace all the repeated int[] array construction with a BitSet.
  • Patch from Matt Quail to stop the ugly hack of having hard coded constants in TokenTypes. The big risk was that when the grammar changed, the generated constants could change (patch 757846).
  • Added excludes property to AvoidStarImport, contributed by Bill Schneider (request 744955).
  • Added CyclomaticComplexityCheck from Simon Harris.
  • Added check to catch equality comparison with string literals using the == operator (module StringLiteralEquality, request 754835).
  • Added check for definition of covariant equals() method without overriding method equals(comp.lang.Object) (module coding.CovariantEquals).
  • Added NestedTryDepthCheck and NestedIfDepthCheck from Simon Harris (requests 750736 and 750744).
  • Added IllegalTokenCheck from Simon Harris (request 750755).
  • Added allowInSwitchCase property to AvoidNestedBlocksCheck to allow limiting the scope of variables to one case of a switch statement.
  • Added checks for J2EE requirements.
  • Added a check that an overriding clone() method invokes super.clone().
  • Added a check that an overriding finalize() method invokes super.finalize().
  • Added usage checks OneMethodPrivateFieldCheck, UnusedLocalVariableCheck, UnusedParameterCheck, UnusedPrivateFieldCheck, UnusedPrivateMethodCheck.
  • Added filters for audit events (partially fulfills request 559103). A SuppressionFilter denies events according to a suppressions file (request 756416).
  • Made basedir property of Checker OS agnostic (request 663149).
  • Enhanced RedundantModifier to check that all private methods and all methods in a final class do not contain modifier final (discussed in request 775011).
  • Added MethodLengthCheck option for counting empty and comment lines (requests 589358 and 654039).
  • Added a check for illegal token text (requests 740694 and 750633).
  • Added property to HiddenFieldCheck to ignore the parameter of property setter methods (request 790456).
  • Added DescendantToken check (request 755021).
  • Added IllegalCatch check from Simon Harris (request 750746).
  • Added PackageDeclaration check from Simon Harris (request 750753).
  • Added JUnitTestCase check from Simon Harris (request 750761).
  • Added MutableException check from Simon Harris (request 750750).
  • Added AbstractClassName check from Simon Harris (request 750749).
  • Added ThrowsCount check from Simon Harris (request 750742).
  • Added ReturnCount check from Simon Harris (request 750745).
  • Added CyclomaticComplexity check from Simon Harris (request 750756).
  • Added ExecutableStatementCount check from Simon Harris (request 750751).
  • Added property to HiddenFieldCheck to ignore constructor parameters (request 798240).
  • Added check for illegal type of variable, parameters and return value of methods contributed by Simon Harris (request 750739, module IllegalType)
  • Added check for correct declarations order contributed by Roland Auckenthaler (module DeclarationOrder)
  • Added ParameterAssignment check contributed by Simon Harris (request 750748).
  • Added FinalLocalVariable check from Roland Auckenthaler and Kevin Gibbs.
  • Added check for correct grouping/order of imports from Bill Schneider (module ImportOrder, request 745548)
  • Added Indentation check from John Richardson (request 493366)
  • Added check for explicit initialization class and object variable to value which is default for variable's type (module ExplicitInitialization, request 614387).
  • Added check to find duplicate code (module StrictDuplicateCode, request 650710).

Resolved bugs:

  • Fixed NPE when running ArrayTypeStyle check (bug 744573)
  • Typo in HideUtilityClassConstructor description (bug 743973)
  • False MagicNumberCheck errors for interfaces (bug 745941)
  • Docs for severity (bug 745937)
  • EmptyBlock does not accept stmt option (bug 747400)
  • Inner class fields interpreted as local variables (bug 747530)
  • Fixed typo in documentation for PackageName (bug 7480028)
  • NumberFormatException in MagicNumberCheck (bug 748913)
  • Removed broken support for checking typecasts from ParenPadCheck (bug 750348)
  • Fixed grammar problems with unclosed string literals and multiple-lines comments (bug 694111)
  • Fixed grammar definition for identifiers to handle all Unicode symbols (bug 755744)
  • Corrected misspelling of "precede" (bug 744342)
  • EmptyForIteratorPadCheck errors when for statement wraps at the iterator (bug 777471)
  • False alarms from IllegalInstantiation for user defined classes with the same names as those in java.lang (bug 772832)
  • NoSuchElementException in JavadocStyleCheck (bug 785514)
  • RedundantModifierCheck error for public modifier of a method defined in an inner implementation (bug 784814)
  • MagicNumberCheck does not permits negative constants (bug 788106)
  • NullPointerException in Unused... checks (bug 787672)
  • NoSuchMethodError when line wrapped at dot operator (bug 790209)
  • Removed finder restrictions of LocalHomeInterfaceCheck and RemoteHomeInterfaceCheck (bug 791591)
  • Fixed NoSuchMethodError when line wrapped at dot operator (bugid 790209)
  • Incorrect usage checks documentation (bug 790457)
  • CyclomaticComplexityCheck not documented in docs (bug 783800)
  • Changed configuration documentation example from checkstyle_checks.xml to sun_checks.xml (see bug 750169)
  • JavadocStyleCheck doesn't accept {@inheritDoc} javadoc (bug 798405)
  • Unused local variables are not always detected (bug 798111)
  • Fixed allowThrowsTagsForSubclasses/allowMissingThrowsTag interfere (bug 803577)
  • Unused... checks don't work together (bug 805954)
  • NoWhitespaceBeforeCheck error with an interface (bug 806242)
  • NoWhitespaceBeforeCheck error for anonymous inner class (bug 806243)
  • Usage of optional checks should be documented (bug 806961)
  • Changed default format for ConstantName to ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$ to please regexp library (see bug 807571)
  • HiddenFieldCheck error for a local variable of a static method with same name as an instance field (bug 827713)
  • Changed HideUtilityClassConstructorCheck behaviour for classes that do not extend java.lang.Object directly (partial fix for bug 824754)
  • False alarms for abstract classes from FinalClass (bug 837012)
  • Added Checker.removeListener() (fix for 834367)

API changes (only relevant for IDE plugin authors):

  • AuditListener and AuditEvent have been moved from package com.puppycrawl.tools.checkstyle to package com.puppycrawl.tools.checkstyle.api.

New features:

  • Patch from David Schneider to have severity levels for each check (request 597683).
  • Added check to avoid inline conditionals like "b ? x : y" (module AvoidInlineConditionals, request 597790).
  • Added check that blocks are not introduced at arbitrary places but only for if, while, etc. (module AvoidNestedBlocks, request 632442).
  • Added check to enforce that utility classes (classes that have only static methods) cannot be instantiated (module HideUtilityClassConstructor, request 634838).
  • Added check to enforce an API design that shields classes against bugs in derived classes (module DesignForExtension, request 659715).
  • Added check to enforce that Interfaces do not contain only constants (module InterfaceIsType, request 659717, see [Bloch, Effective Java], Item 17 "Use interfaces only to define types").
  • Added check to detect the double-checked locking idiom (module DoubleCheckedLocking, request 709333).
  • Added check to enforce C style (char c[]) or Java style (char[] c) for array type declaration (module ArrayTypeStyle, request 493380).
  • Added check to enforce that method parameters are final (module FinalParameters, request 528196).
  • Added module to enforce that files end with a newline character, contributed by Christopher Lenz (module NewLineAtEndOfFile, request 662544).
  • Many documentation improvements, contributed by Peter Dobratz.
  • Patch from Simon Kitching to allow more configuration control over the JavadocMethodCheck.
  • Checkstyle ant task outputs version info in verbose and debug mode (request 550483).
  • Patch from Oleg Sukhodolsky to add FinalCheck to check that classes are declared final if they only contain private constructors (request 696290).
  • Patch from Oleg Sukhodolsky to add MissingSwitchDefaultCheck to check that a switch statement has a default clause (request 564199).
  • Patch from Oleg Sukhodolsky to fix TranslationCheck Test bug. (bug 720925).
  • Patch from Oleg Sukhodolsky to fix documentation. (bug 727896).
  • Added check to find empty statements (module EmptyStatement, request 724573).
  • Added check to find magic numbers (module MagicNumber, request 564206).
  • One more option for JavadocMethodCheck (allowThrowsTagsForSubclasses, request 540383)
  • Added sourceName property to AuditEvent and LocalizedMessage; and "source" attribute to "error" element of XMLLogger output (request 686336).
  • Added line and column numbers to configuration parse exceptions (request 714962).
  • Added check for redundant exceptions in throws clause (module RedundantThrows, request 579056)
  • Added property for GenericIllegalRegexp to customize reported message (module GenericIllegalRegexp, property message, request 738567)
  • Moved the location of the file checkstyle_packages.xml to be in the directory com/puppycrawl/tools/checkstyle. This is to work around a bug in NetBeans (request 739881).
  • Patch from Dale King to enhance the GUI with a Reload Java File button and storage of the current directory of the last opened file (request 740545).
  • Patch from Bill Schneider to add GenericIllegalRegexpCheck property to perform case-insensitive matches (request 740112).

Resolved bugs:

  • False alarms from RightCurly module for code that does not have braces in if-then-else (bug 689836).
  • Grammar incorrectly defaulting unqualified floating point literals to be float, when they should be double (bug 713716).
  • "threadsafe" was treated as a Java keyword, resulting in parser errors for sources that use it as an identifier (bug 710319).
  • ConfigurationLoader was not public (only relevant for IDE plugin authors).
  • HTML syntax errors in documentation (bug 721458).
  • Error when writing a DOS file name from checkstyle-frames.xsl (bug 713845).
  • Files were not being closed by Utils.getLines().
  • Missing documentation for the EmptyForIterator check (bug 740038).

Development Team:

  • Oleg Sukhodolsky has joined the team.

New features:

  • Completely new architecture based around pluggable modules. This means that users can now write their own checks without changing the sourcecode of checkstyle itself (request 578712).
  • Users can specify the Java token types for which a check must be performed. For example users can now control that there should be whitespace after 'synchronized' but not after 'if' (request 536385).
  • Detect classes that override 'equals()' but not 'hashCode()' (request 554373).
  • Detect inner assignments, e.g. 'this.add(label = new JLabel("yes, I'm a C hacker"));' (request 521325).
  • Detect matches of generic regular expressions (requests 595254, 621247, 630536).
  • Find empty blocks (not only empty catch blocks, request 609523).
  • Check spaces at empty for iterators (requests 565666, 583725).
  • Detect missing property file keys in internationalized applications (request 634966).
  • Check content of @author and @version tag against a regular expression.
  • Detect hiding of fields by parameters or local variables with the same name (request 471897).
  • Detect obsolete final modifier in interfaces (request 651121).
  • Detect whitespace before ';' (request 521323).
  • Added DTD for XML output (request 622157).
  • Added an XSL stylesheet to convert XML output to plain text, contributed by Jon Scott Stevens.
  • Added portuguese localization, contributed by Pedro Morais.
  • Added finnish localization, contributed by Ville Skytt¤.
  • Added french localization, contributed by Pierre Dittgen.

Resolved bugs:

  • Fully-qualified @throws claimed unused (bug 658805).
  • Expected @return tag when one is there (bug 579190).
  • Package name reported incorrectly (bug 622290).
  • Empty header filename silently ignored (bug 629139).
  • Array instantiation incorrectly flagged (bug 626875).
  • Tests fail with non-english locale (bug 594469).
  • Cachefile streams were not closed (bug 665016).
  • Ant Task: NullPointerException when type was not specified in formatter (bug 670321).

Removed features:

  • Removed support for japanese localization until we find a new maintainer.

API changes (only relevant for IDE plugin authors):

  • Configuration is not based on Properties any more. Instead a Configuration interface is used, IDE plugins can define their own way of creating Configurations or they can reuse the provided ConfigurationLoader to read checkstyle's standard XML config files.

Development Team:

  • Rick Giles has joined the team.

New features:

  • Major refactoring on the way Checkstyle is configured. It is now completely based around properties. Big thanks to Vincent Massol for the suggestion on how to refactor the ANT task (bug 605141).
  • Check the package name against a pattern (request 597787). Patch provided by Simon Langford.
  • Detect the number of parameters in a declaration exceeding a specified amount (request 582144).
  • Inspired by patch 580410 from Shinya Ohnuma, now the error messages are localised.
  • Support checking to determine if an unused @throws exception is a subclass of java.lang.Error (request 583719).
  • Incorporate patch 555878 from Rick Giles to allow pattern for local final variables to be specified.
  • Incorporate patch 566855 from Rob Worth to optionally check that parenthesis are padded with spaces.
  • Incorporate patch 590931 from Vijay Aravamudhan to improve documentation of the build.xml file.
  • Incorporate patch from Vijay Aravamudhan to enforce requiring @version tag (request 543964).
  • Incorporate patch 607481 from Ville Skytt¤ to enforce wrap on operator at EOL.

Resolved bugs:

  • Incorporate a patch from Ronald Hastings (Boeing) to correctly handle C++ style comments being between Javadoc comments and declarations.

API changes (only relevant for IDE plugin authors):

  • Many changes to the Configuration object.

New features:

  • Support checking to determine if an unused @throws exception is a subclass of java.lang.RuntimeException (request 540382).
  • Detect instantiations of classes that should not be instantiated (e.g. java.lang.Boolean) (request 550205).
  • Added ability to specify the base directory for reporting file names (request 571161).
  • Check for line wrapping on operators (request 553160).
  • Detect empty try blocks.
  • Detect empty catch blocks (request 516255).
  • Detect empty finally blocks.
  • Detect to-do comments (request 504275).
  • Detect use of lowercase l ("ell") in long integer literals.
  • Include column number in the XML output (request 555262).
  • Added ability to specify a properties file on the command line (request 557544).
  • Check for whitespace around "{" and "}" (request 557544).
  • Fix Javadoc errors under JDK 1.4 (request 568553).
  • Detect redundant abstract modifier in interfaces (request 573485).
  • Support running Checkstyle using the -jar option.

Resolved bugs:

  • Better error reporting for missing properties files (bug 576165).
  • Ant task now logs style violations as errors (bug 561616).

API changes (only relevant for IDE plugin authors):

  • The get/setOutputStream methods have been removed from the AuditListener interface. The XMLLogger and DefaultLogger implementations now expect OutputStreams to be provided as a constructor argument.
  • The DefaultLogger now differentiates between info messages ("started checking file ...", etc.) and error messages (style errors found by checkstyle).

Resolved bugs:

  • The cache was not invalidated upon parameter change (Bug 522282).
  • Tabs were not counted correctly in line length checks (Bug 524671).
  • Problem when a Checker could not be created (Bug 528358).
  • The documentation of the command line property names did not list the property checkstyle.allow.tabs (Bug 529975).
  • The default regular expression for constant names allowed consecutive '_' characters to occur (Bug 540358).
  • Checkstyle reported unused @throws tag for multiple declarations of the same Exception. According to the Java BugParade this is incorrect, multiple @throws tags for the same exception are OK (Bug 540384).

New features:

  • added check for whitespace around '()'
  • added support for JDK 1.4 assert statements
  • added column number to error messages for better Emacs integration
  • added possibility to disable line-length checking by means of regular expressions
  • added possibility to disallow import of package hierarchies, e.g. sun.*
  • added failureProperty to ANT task
  • added check for 'public' modifier in interface method declarations, following the recommendation in chapter 9.4 of the Java Language Specification
  • added -r "dir" option to the commandline frontend, checkstyle will find all Java files contained in the specified directory
  • incorporated patch from Warner Onstine to configure the ANT task by means of a property file
  • added 'contrib' directory, contains XSL stylesheets for formating checkstyle's XML output (contributions by Ingmar Stein, Stephane Bailliez, Scott McCrory and Gray Herter)

New features:

  • added check for package.html
  • added flag allowPackage which acts similar as allowProtected
  • added support for ignoring multiple lines in the file header
  • added support for specifying the file header by means of regular expressions
  • added whitespace checks around '.', e.g. System . out . println()
  • added check for names of methods and local variables
  • check the order of modifiers (public, static, etc.) against the recommendation in the Java Language specification
  • added checks for curly braces placement
  • incorporated patch from Andrew Lang for more robust Javadoc parsing

Changes:

  • Now released under the GNU Lesser General Public License (LGPL).
  • Fix bug #508010, documentation and code are inconsistent.
  • Changes to make it build "out of the box".
checkstyle-5.6/src/xdocs/running.xml100644 0 0 1527 11451071615 14770 0ustar 0 0 Running Oliver Burn

This section documents the out-of-box supported methods for running Checkstyle.

Note that there are loads of plug-ins for all the IDE's out there.

checkstyle-5.6/src/xdocs/writingchecks.xml.vm100644 0 0 55306 11451011233 16607 0ustar 0 0 Writing Checks Lars Kühne

OK, so you have finally decided to write your own Check. Welcome aboard, this is really a fun thing to do. There are actually two kinds of Checks, so before you can start, you have to find out which kind of Check you want to implement.

The functionality of Checkstyle is implemented in modules that can be plugged into Checkstyle. Modules can be containers for other modules, i.e. they form a tree structure. The toplevel modules that are known directly to the Checkstyle kernel (which is also a module and forms the root of the tree) implement the FileSetCheck interface. These are pretty simple to grasp: they take a set of input files and fire error messages.

Checkstyle provides a few FileSetCheck implementations by default and one of them happens to be the TreeWalker. A TreeWalker supports submodules that are derived from the Check class. The TreeWalker operates by separately transforming each of the Java input files into an abstract syntax tree and then handing the result over to each of the Check submodules which in turn have a look at a certain aspect of the tree.

Most of the functionality of Checkstyle is implemented as Checks. If you know how to write your own Checks, you can extend Checkstyle according to your needs without having to wait for the Checkstyle development team. You are about to become a Checkstyle Expert.

Suppose you have a convention that the number of methods in a class should not exceed a certain limit, say 30. This rule makes sense, a class should only do one thing and do it well. With a zillion methods chances are that the class does more than one thing. The only problem you have is that your convention is not checked by Checkstyle, so you'll have to write your own Check and plug it into the Checkstyle framework.

This chapter is organized as a tour that takes you through the process step by step and explains both the theoretical foundations and the Checkstyle API along the way.

Every Java Program is structured into files, and each of these files has a certain structure. For example, if there is a package statement then it is the first line of the file that is not comment or whitespace. After the package statement comes a list of import statements, which is followed by a class or interface definition, and so on.

If you have ever read an introductory level Java book you probably knew all of the above. And if you have studied computer science, you probably also know that the rules that specify the Java language can be formally specified using a grammar (statement is simplified for didactic purposes).

Tools exist which read a grammar definition and produce a parser for the language that is specified in the grammar. In other words, the output of the tool is a program that can transform a stream of characters (a Java file) into a tree representation that reflects the structure of the file. Checkstyle uses the parser generator ANTLR but that is an implementation detail you do not need to worry about when writing Checks. Several other parser generators exist and they all work well.

Still with us? Great, you have mastered the basic theory so here is your reward - a GUI that displays the structure of a Java source file. To run it type

java -classpath checkstyle-${projectVersion}-all.jar \ com.puppycrawl.tools.checkstyle.gui.Main

on the command line. Click the button at the bottom of the frame and select a syntactically correct Java source file. The frame will be populated with a tree that corresponds to the structure of the Java source code.

screenshot

In the leftmost column you can open and close branches of the tree, the remaining columns display information about each node in the tree. The second column displays a token type for each node. As you navigate from the root of the tree to one of the leafs, you'll notice that the token type denotes smaller and smaller units of your source file, i.e. close to the root you might see the token type CLASS_DEF (a node that represents a class definition) while you will see token types like IDENT (an identifier) near the leaves of the tree.

We'll get back to the details in the other columns later, they are important for implementing Checks but not for understanding the basic concepts. For now it is sufficient to know that the gui is a tool that lets you look at the structure of a Java file, i.e. you can see the Java grammar 'in action'.

Ready for a bit more theory? The last bit that is missing before you can start writing Checks is understanding the Visitor pattern.

When working with ASTs, a simple approach to define check operations on them would be to add a check() method to the Class that defines the AST nodes. For example, our AST type could have a method checkNumberOfMethods(). Such an approach would suffer from a few serious drawbacks. Most importantly, it does not provide an extensible design, i.e. the Checks have to be known at compile time; there is no way to write plugins.

Hence Checkstyle's AST classes do not have any methods that implement checking functionality. Instead, Checkstyle's TreeWalker takes a set of objects that conform to a Check interface. OK, you're right - actually it's not an interface but an abstract class to provide some helper methods. A Check provides methods that take an AST as an argument and perform the checking process for that AST, most prominently visitToken().

It is important to understand that the individual Checks do no drive the AST traversal. Instead, the TreeWalker initiates a recursive descend from the root of the AST to the leaf nodes and calls the Check methods. The traversal is done using a depth-first algorithm.

Before any visitor method is called, the TreeWalker will call beginTree() to give the Check a chance to do some initialization. Then, when performing the recursive descend from the root to the leaf nodes, the visitToken() method is called. Unlike the basic examples in the pattern book, there is a visitToken() counterpart called leaveToken(). The TreeWalker will call that method to signal that the subtree below the node has been processed and the TreeWalker is backtracking from the node. After the root node has been left, the TreeWalker will call finishTree().

If you'd like to learn more about the Visitor pattern you should grab a copy of the Gof Design Patterns book.

Let's get back to our example and start writing code - that's why you came here, right? When you fire up the Checkstyle GUI and look at a few source files you'll figure out pretty quickly that you are mainly interested in the number of tree nodes of type METHOD_DEF. The number of such tokens should be counted separately for each CLASS_DEF / INTERFACE_DEF.

Hence we need to register the Check for the token types CLASS_DEF and INTERFACE_DEF. The TreeWalker will only call visitToken for these token types. Because the requirements of our tasks are so simple, there is no need to implement the other fancy methods, like finishTree(), etc., so here is our first shot at our Check implementation:

package com.mycompany.checks; import com.puppycrawl.tools.checkstyle.api.*; public class MethodLimitCheck extends Check { private static final int DEFAULT_MAX = 30; private int max = DEFAULT_MAX; @Override public int[] getDefaultTokens() { return new int[]{TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF}; } @Override public void visitToken(DetailAST ast) { // find the OBJBLOCK node below the CLASS_DEF/INTERFACE_DEF DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK); // count the number of direct children of the OBJBLOCK // that are METHOD_DEFS int methodDefs = objBlock.getChildCount(TokenTypes.METHOD_DEF); // report error if limit is reached if (methodDefs > this.max) { log(ast.getLineNo(), "too many methods, only " + this.max + " are allowed"); } } }

In the example above you already saw that the DetailsAST class provides utility methods to extract information from the tree, like getChildCount(). By now you have probably consulted the api documentation and found that DetailsAST additionally provides methods for navigating around in the syntax tree, like finding the next sibling of a node, the children of a node, the parent of a node, etc.

These methods provide great power for developing complex Checks. Most of the Checks that Checkstyle provides by default use these methods to analyze the environment of the ASTs that are visited by the TreeWalker. Don't abuse that feature for exploring the whole tree, though. Let the TreeWalker drive the tree traversal and limit the visitor to the neighbours of a single AST.

Ok Mr. Checkstyle, that's all very nice but in my company we have several projects, and each has another number of allowed methods. I need to control my Check through properties, so where is the API to do that?

Well, the short answer is, there is no API. It's magic. Really!

If you need to make something configurable, just add a setter method to the Check:

public class MethodLimitCheck extends Check { // code from above omitted for brevity public void setMax(int limit) { max = limit; } }

With this code added, you can set the property max for the MethodLimitCheck module in the configuration file. It doesn't get any simpler than that. The secret is that Checkstyle uses JavaBean introspection to set the JavaBean properties. That works for all primitive types like boolean, int, long, etc., plus Strings, plus arrays of these types.

Detecting errors is one thing, presenting them to the user is another. To do that, the Check base class provides several log methods, the simplest of them being Check.log(String). In your Check you can simply use a verbatim error string like in log("Too many methods, only " + mMax + " are allowed"); as the argument. That will work, but it's not the best possible solution if your Check is intended for a wider audience.

If you are not living in a country where people speak English, you may have noticed that Checkstyle writes internationalized error messages, for example if you live in Germany the error messages are German. The individual Checks don't have to do anything fancy to achieve this, it's actually quite easy and the Checkstyle framework does most of the work.

To support internationalized error messages, you need to create a messages.properties file alongside your Check class, i.e. the Java file and the properties files should be in the same directory. Add a symbolic error code and an English representation to the messages.properties. The file should contain the following line: too.many.methods=Too many methods, only {0} are allowed. Then replace the verbatim error message with the symbolic representation and use one of the log helper methods to provide the dynamic part of the message (mMax in this case): log("too.many.methods", mMax);. Please consult the documentation of Java's MessageFormat to learn about the syntax of format strings (especially about those funny numbers in the translated text).

Supporting a new language is very easy now, simply create a new messages file for the language, e.g. messages_fr.properties to provide french error messages. The correct file will be chosen automatically, based on the language settings of the user's operating system.

The great final moment has arrived, you are about to run your Check. To integrate your Check, add a new subentry under the TreeWalker module of your configuration file. Use the full classname of your Check class as the name of the module. Your configuration file should look something like this:

<?xml version="1.0"?> <!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://www.puppycrawl.com/dtds/configuration_1_3.dtd"> <module name="Checker"> <module name="TreeWalker"> <!-- your standard Checks that come with Checkstyle --> <module name="UpperEll"/> <module name="MethodLength"/> <!-- your Check goes here --> <module name="com.mycompany.checks.MethodLimitCheck"> <property name="max" value="45"/> </module> </module> </module>

To run the new Check on the command line compile your Check, create a jar that contains the classes and property files, e.g. mycompanychecks.jar. Then run (with the path separator adjusted to your platform):

java -classpath mycompanychecks.jar:checkstyle-${projectVersion}-all.jar \ com.puppycrawl.tools.checkstyle.Main \ -c config.xml -r .

Did you see all those errors about "too many methods" flying over your screen? Congratulations. You can now consider yourself a Checkstyle expert. Go to your fridge. Have a beer.

Please consult the Checkstyle configuration manual to learn how to integrate your Checks into the package configuration so that you can use MethodLimit instead of the full class name.

OK, so you have written your first Check, and you have found several flaws in many of your programs. You now know that your boss does not follow the coding conventions he wrote. And you know that you are the king of the world. To become a programming god, you want to write your second Check - now wait, first you should know what your limits are.

There are basically only two of them:

  • You cannot determine the type of an expression.
  • You cannot see the content of other files. (although you can save processed files for use later)

This means that you cannot implement some of the code inspection features that are available in advanced IDEs like IntelliJ IDEA. For example you will not be able to implement a Check that finds redundant type casts or unused public methods.

Writing a FileSetCheck is pretty straightforward: Just inherit from AbstractFileSetCheck and override the abstract processFiltered(java.io.File, java.util.List) method and you're done. A very simple example could fire an error if the number of files exceeds a certain limit. Here is a FileSetCheck that does just that:

package com.mycompany.checks; import java.io.File; import java.util.List; import com.puppycrawl.tools.checkstyle.api.*; public class LimitImplementationFiles extends AbstractFileSetCheck { private static final int DEFAULT_MAX = 100; private int fileCount; private int max = DEFAULT_MAX; public void setMax(int aMax) { this.max = aMax; } @Override public void beginProcessing(String aCharset) { super.beginProcessing(aCharset); //reset the file count this.fileCount = 0; } @Override public void processFiltered(File file, List<String> aLines) { this.fileCount++; if (this.fileCount > this.max) { // log the message log(0, "max.files.exceeded", Integer.valueOf(this.max)); // you can call log() multiple times to flag multiple // errors in the same file } } }

Note that the configuration via bean introspection also applies here. By implementing the setMax() method the FileSetCheck automatically makes "max" a legal configuration parameter that you can use in the Checkstyle configuration file.

There are virtually no limits what you can do in FileSetChecks. The craziest ideas we've had so far are:

  • to find global code problems like unused public methods.
  • to find duplicate code.
  • to port the TreeWalker solution to check C# instead of Java.

That's probably our fault, and it means that we have to provide better documentation. Please do not hesitate to ask questions on the user mailing list, this will help us to improve this document. Please ask your questions as precisely as possible. We will not be able to answer questions like "I want to write a Check but I don't know how, can you help me?". Tell us what you are trying to do (the purpose of the Check), what you have understood so far, and what exactly you are getting stuck on.

We need your help to keep improving Checkstyle. Whenever you write a Check or FileSetCheck that you think is generally useful, please consider contributing it to the Checkstyle community and submit it for inclusion in the next release of Checkstyle.

checkstyle-5.6/src/xdocs/writingfilters.xml100644 0 0 12131 11451071615 16375 0ustar 0 0 Writing Filters Lars Kühne

A Checker has a set of Filters that decide which audit events the Checker reports through its listeners. Interface Filter and class FilterSet are intended to support general AuditEvent filtering using a set of Filters.

A Filter has boolean method accept(AuditEvent) that returns true if the Filter accepts the AuditEvent parameter and returns false if the Filter rejects it.

A FilterSet is a particular Filter that contains a set of Filters. A FilterSet accepts an AuditEvent if and only if all Filters in the set accept the AuditEvent.

Here is a UML diagram for interface Filter and class FilterSet.

Filter UML diagram

The Filter that we demonstrate here rejects audit events for files whose name matches a regular expression. In order to enable the specification of the file name pattern as a property in a configuration file, the Filter is an AutomaticBean with mutator method setFiles(String) that receives the file name pattern. An AutomaticBean uses JavaBean introspection to set JavaBean properties such as files.

package com.mycompany.filters; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.Filter; import com.puppycrawl.tools.checkstyle.api.Utils; public class FilesFilter extends AutomaticBean implements Filter { private Pattern mFileRegexp; public FilesFilter() throws PatternSyntaxException { setFiles("^$"); } public boolean accept(AuditEvent aEvent) { final String fileName = aEvent.getFileName(); return ((fileName == null) || !mFileRegexp.matcher(fileName).find()); } public void setFiles(String aFilesPattern) throws PatternSyntaxException { mFileRegexp = Utils.getPattern(aFilesPattern); } }

To incorporate a Filter in the filter set for a Checker, include a module element for the Filter in the configuration file. For example, to configure a Checker so that it uses custom filter FilesFilter to prevent reporting of audit events for files whose name contains "Generated", include the following module in the configuration file:

<module name="com.mycompany.filters.FilesFilter"> <property name="files" value="Generated"/> </module>

That's probably our fault, and it means that we have to provide better documentation. Please do not hesitate to ask questions on the user mailing list, this will help us to improve this document. Please ask your questions as precisely as possible. We will not be able to answer questions like "I want to write a filter but I don't know how, can you help me?". Tell us what you are trying to do (the purpose of the filter), what you have understood so far, and what exactly you are getting stuck on.

We need your help to keep improving Checkstyle. Whenever you write a filter that you think is generally useful, please consider contributing it to the Checkstyle community and submit it for inclusion in the next release of Checkstyle.

checkstyle-5.6/src/xdocs/writinglisteners.xml.vm100644 0 0 35720 11451071615 17367 0ustar 0 0 Writing Listeners Lars Kühne

A Checkstyle listener monitors the progress of a Checker during the audit of files. The Checker notifies its attached listeners of significant events such as the start of the audit of a file and the logging of a Check error, and the listeners respond appropriately. Any number of listeners can be attached to a Checker. An audit always adds one of the distribution listeners, DefaultLogger or XMLLogger, to report events. A DefaultLogger produces simple text output for the events it receives, and a XMLLogger produces an XML document for its events.

Listeners DefaultLogger and XMLLogger are sufficient for most Checkstyle users, but you may find a need for a custom listener. For example, a user has requested verbose output of progress information during a Checkstyle run. Another user would like to filter error events. This document explains how to write listeners for such tasks and how to integrate them in a Checker module. It also describes two custom listeners that are inspired by ANT listeners: a listener that is a wrapper for the Jakarta Commons Logging API, and a listener that sends its results via email.

A listener is an implementation of the AuditListener interface. During an audit, a Checker informs its attached AuditListeners of six kinds of events: audit started/ended, file started/ended, and logging of an error/exception.

An audit passes an event to a listener as an AuditEvent. A file-related AuditEvent contains the name of that file. An AuditEvent for error logging has a message, a severity level, a message source such as the name of a Check, and file line and column numbers that may be relevant to the error. The notification of an exception to a AuditListener includes an error AuditEvent and the details of the exception. Here is a UML diagram for classes AuditListener and AuditEvent.

AuditListener UML diagram

A custom listener is an implementation of the AuditListener interface. If the listener has properties that can be set from a configuration, the listener must extend AutomaticBean. An AutomaticBean uses JavaBean introspection to set JavaBean properties.

The custom listener that we demonstrate here is a verbose listener that simply prints each event notification to an output stream, and reports the number of errors per audited file and the total number of errors. The default output stream is System.out. In order to enable the specification of output to a file through property file, the class extends AutomaticBean and defines method setFile(String).

package com.mycompany.listeners; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AuditListener; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; public class VerboseListener extends AutomaticBean implements AuditListener { private PrintWriter mWriter = new PrintWriter(System.out); private boolean mCloseOut = false; private int mTotalErrors; private int mErrors; public void setFile(String aFileName) throws FileNotFoundException { final OutputStream out = new FileOutputStream(aFileName); mWriter = new PrintWriter(out); mCloseOut = true; } public void auditStarted(AuditEvent aEvt) { mTotalErrors = 0; mWriter.println("Audit started."); } public void auditFinished(AuditEvent aEvt) { mWriter.println("Audit finished. Total errors: " + mTotalErrors); mWriter.flush(); if (mCloseOut) { mWriter.close(); } } public void fileStarted(AuditEvent aEvt) { mErrors = 0; mWriter.println( "Started checking file '" + aEvt.getFileName() + "'."); } public void fileFinished(AuditEvent aEvt) { mWriter.println("Finished checking file '" + aEvt.getFileName() + "'. Errors: " + mErrors); } public void addError(AuditEvent aEvt) { printEvent(aEvt); if (SeverityLevel.ERROR.equals(aEvt.getSeverityLevel())) { mErrors++; mTotalErrors++; } } public void addException(AuditEvent aEvt, Throwable aThrowable) { printEvent(aEvt); aThrowable.printStackTrace(System.out); mErrors++; mTotalErrors++; } private void printEvent(AuditEvent aEvt) { mWriter.println("Logging error -" + " file: '" + aEvt.getFileName() + "'" + " line: " + aEvt.getLine() + " column: " + aEvt.getColumn() + " severity: " + aEvt.getSeverityLevel() + " message: " + aEvt.getMessage() + " source: " + aEvt.getSourceName()); } }

A listener that filters error events could perform the filtering in methods addError and addException. As further examples of listeners, CommonsLoggingListener reports its events through the Commons Logging API, and MailLogger e-mails the audit report of a DefaultLogger.

To incorporate a custom listener in the set of listeners for a Checker, include a module element for the listener in the configuration file. For example, to configure a Checker so that it uses custom listener VerboseListener to print audit messages to a file named "audit.txt", include the following module in the configuration file:

<module name="com.mycompany.listeners.VerboseListener"> <property name="file" value="audit.txt"/> </module>

Here is a truncated example of audit output from a VerboseListener:

Audit started. Started checking file 'CommonsLoggingListener.java'. Finished checking file 'CommonsLoggingListener.java'. Errors: 0 Started checking file 'MailLogger.java'. Finished checking file 'MailLogger.java'. Errors: 0 Started checking file 'VerboseListener.java'. Logging error - file: 'VerboseListener.java' line: 23 ... Finished checking file 'VerboseListener.java'. Errors: 1 Audit finished. Total errors: 1

This section describes two examples based on ANT listeners. The first listener, CommonsLoggingListener, hands off events to the Jakarata Commons Logging facade and the second, MailLogger, sends a report of an audit via e-mail. The discussion of these examples and how to use them is derived from material in "Java Development with Ant" by Eric Hatcher and Steve Loughran, an excellent ANT book.

CommonsLoggingListener

Jakarata Commons Logging provides a facade for logging tools log4j, Avalon LogKit, J2SE 1.4, and others. Checkstyle listener CommonsLoggingListener responds to an AuditEvent by handing it off to the current Commons Logging Log.

The source code for CommonsLoggingListener is in distribution directory contrib/examples/listeners. Notice that each AuditListener method that receives an AuditEvent calls a method for the Commons Logging log level corresponding to the Checkstyle SeverityLevel of the AuditEvent.

The easiest way to use CommonsLoggingListener is to include checkstyle-${projectVersion}-all.jar in the classpath because that jar file contains all the Commons Logging classes. The default Log under J2SE 1.4 is wrapper class Jdk14Logger. Under earlier Java versions, the default Log is a simple wrapper class, SimpleLog. Both default logging tools can be used directly from Commons Logging; if you need to use other tools such as log4j, then you must include the appropriate jar file(s) in the classpath.

Logging configuration details for Jakarta Commons Logging are in the documentation. As a simple example, assume that log4j.jar is in the classpath and the following log4j.properties file is in the current directory:

# Set root logger level to INFO and its only appender to A1. log4j.rootLogger=INFO, A1 # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender # A1 uses PatternLayout. log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-5p %c %x- %m%n

Running a Checkstyle audit with a CommonsLoggingListener yields this (abbreviated) output:

INFO com.puppycrawl...Checker - Audit started. INFO com.puppycrawl...Checker - File "CommonsLoggingListener.java" started. INFO com.puppycrawl...Checker - File "CommonsLoggingListener.java" finished. INFO com.puppycrawl...Checker - File "MailLogger.java" started. INFO com.puppycrawl...Checker - File "MailLogger.java" finished. INFO com.puppycrawl...Checker - File "VerboseListener.java" started. ERROR com.puppycrawl...ParenPadCheck - Line: 23 Column: 28 ... INFO com.puppycrawl...Checker - File "VerboseListener.java" finished. INFO com.puppycrawl...Checker - Audit finished.

MailLogger

MailLogger sends an audit report in an email message. The listener uses a DefaultLogger to prepare the text of the message. The listener obtains other message parameters such as to and subject from environment properties that can be read from a properties file.

The source code for CommonsLoggingListener is in distribution directory contrib/examples/listeners. This implementation uses the JavaMail API as the mail system, and you must include appropriate jar files in the classpath.

As an example of using MailLogger, set system property -DMailLogger.properties.file=MailLogger.properties, so that MailLogger reads message parameters from file MailLogger.properties of the current directory:

MailLogger.from=user@example.org MailLogger.failure.to=user@example.org MailLogger.success.to=user@example.org MailLogger.mailhost=localhost

That's probably our fault, and it means that we have to provide better documentation. Please do not hesitate to ask questions on the user mailing list, this will help us to improve this document. Please ask your questions as precisely as possible. We will not be able to answer questions like "I want to write a listener but I don't know how, can you help me?". Tell us what you are trying to do (the purpose of the listener), what you have understood so far, and what exactly you are getting stuck on.

We need your help to keep improving Checkstyle. Whenever you write a listener that you think is generally useful, please consider contributing it to the Checkstyle community and submit it for inclusion in the next release of Checkstyle.

checkstyle-5.6/sun_checks.xml100644 0 0 15315 12022120465 13537 0ustar 0 0 checkstyle-5.6/suppressions.xml100644 0 0 4114 11456553043 14156 0ustar 0 0 odule name="Checker"> checkstyle-5.6/suppressions.xml100644 0 0 4114 11456553043 14156 0ustar 0 0