diff --git a/.github/workflows/checkstyle-linux.yml b/.github/workflows/checkstyle-linux.yml index b7e07bf1..746284f1 100644 --- a/.github/workflows/checkstyle-linux.yml +++ b/.github/workflows/checkstyle-linux.yml @@ -15,33 +15,30 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - haxe-version: ['3.4.7', '4.0.5', 'nightly'] + haxe-version: ['4.3.6', 'nightly'] env: - CC_TEST_REPORTER_ID: 1dff6f89d7179dff5db635c6b4fe64acdd5694c9ed44d7da5f12f0f7d3d163b7 - CODECOV_TOKEN: ${{secrets.CODECOV_TOKEN}} + CC_TEST_REPORTER_ID: c4eda639526d39fbcab7ab9fc68c4046d4e597df56dbcb552b42d27b3580b758 + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} steps: - - uses: actions/checkout@v1 - - name: Use Node.js 10 - uses: actions/setup-node@v1 + - uses: actions/checkout@v4 + - name: Use Node.js 18 + uses: actions/setup-node@v4 with: - node-version: 10 + node-version: 18 - name: Installing codeclimate client - if: matrix.haxe-version == '4.0.5' + if: matrix.haxe-version == 'nightly' run: | curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter chmod +x ./cc-test-reporter ./cc-test-reporter before-build - name: Run npm install - run: npm ci + run: | + npm ci + npm i -g lix - name: Install Haxe version ${{ matrix.haxe-version }} run: | npx lix download haxe ${{ matrix.haxe-version }} npx lix use haxe ${{ matrix.haxe-version }} - - name: Prepare Haxe 3 dependencies - if: matrix.haxe-version == '3.4.7' - run: | - mv haxe_libraries haxe4_libraries - mv haxe3_libraries haxe_libraries - name: Run lix download run: npx lix download - name: Print versions @@ -49,32 +46,28 @@ jobs: npx haxe -version npx neko -version npx haxelib list + - name: Build hxcpp binary + run: | + cd ~/haxe/haxe_libraries/hxcpp/4.2.0/github/96f5f9a69744e5fd07717e5af9d5b45bd3a8890a/ + npx haxelib dev hxcpp . + cd tools/hxcpp + npx haxe compile.hxml - name: Build neko versions run: | npx haxe build.hxml npx haxe buildDebug.hxml - name: Build NodeJs version - run: npx haxe buildJS.hxml + run: | + npx haxe buildJS.hxml + bash uglifyCheckstyle.sh - name: Build C++ version - run: npx haxe buildCpp.hxml + run: echo "y" | npx haxe buildCpp.hxml - name: Build JSON schema run: npx haxe buildSchema.hxml - - name: Run neko tests - if: matrix.haxe-version == '3.4.7' - run: npx haxe -D codecov_json buildTest.hxml - name: Run eval tests - if: matrix.haxe-version != '3.4.7' - run: npx haxe -D codecov_json buildTest.hxml - - name: Run Java tests + run: npx haxe testAndResources.hxml + - name: Run JVM tests run: npx haxe testJava.hxml - - name: Format and upload codeclimate coverage - if: success() && matrix.haxe-version == '4.0.5' - run: | - ( \ - cd src; \ - ../cc-test-reporter format-coverage -t lcov ../lcov.info; \ - ../cc-test-reporter upload-coverage; \ - ) - name: Upload results to codecov - if: success() && matrix.haxe-version == '4.0.5' + if: success() && (matrix.haxe-version == 'nightly') run: bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports" diff --git a/.gitignore b/.gitignore index 6f35743b..6a88ffb0 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,6 @@ .DS_Store *.n *.zip -.haxelib/ out/ node_modules .DS_Store diff --git a/.haxerc b/.haxerc index 8b6b442c..ef431268 100644 --- a/.haxerc +++ b/.haxerc @@ -1,4 +1,4 @@ { - "version": "4.0.5", + "version": "4.3.6", "resolveLibs": "scoped" } \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 3fdccedf..00000000 --- a/.travis.yml +++ /dev/null @@ -1,44 +0,0 @@ -language: node_js -node_js: - - "10" -sudo: false -dist: xenial - -env: - global: - - CC_TEST_REPORTER_ID=1dff6f89d7179dff5db635c6b4fe64acdd5694c9ed44d7da5f12f0f7d3d163b7 - matrix: - - HAXE_VERSION=haxe347 - - HAXE_VERSION=haxe4 - - HAXE_VERSION=nightly - -install: - - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter; chmod +x ./cc-test-reporter - - npm install - - if [[ "$HAXE_VERSION" == "haxe347" ]]; then mv haxe_libraries haxe4_libraries; mv haxe3_libraries haxe_libraries; fi - - if [[ "$HAXE_VERSION" == "haxe347" ]]; then npx lix download haxe 3.4.7; npx lix use haxe 3.4.7; fi - - if [[ "$HAXE_VERSION" == "haxe4" ]]; then npx lix download haxe 4.0.5; npx lix use haxe 4.0.5; fi - - if [[ "$HAXE_VERSION" == "nightly" ]]; then npx lix download haxe nightly; npx lix use haxe nightly; fi - - npx lix download - - npx haxe -version - - npx neko -version - - npx haxelib list - -before_script: - - ./cc-test-reporter before-build - -script: - - npx haxe build.hxml - - npx haxe buildDebug.hxml - - npx haxe buildJS.hxml - - npx haxe buildCpp.hxml - - npx haxe buildSchema.hxml - - npx haxe -D codecov_json buildTest.hxml - - npx haxe testJava.hxml - - (cd src; ../cc-test-reporter format-coverage -t lcov ../lcov.info) - -after_script: - - if [[ "$HAXE_VERSION" == "haxe4" ]]; then (cd src; ../cc-test-reporter upload-coverage); fi - -after_success: - - bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports" diff --git a/CHANGELOG.md b/CHANGELOG.md index 51910d14..0c1af148 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,58 @@ ## dev branch / next version (2.x.x) +- Added -v / --verbose command line switch +- Fixed null pointer exception with module level fields on static targets +- Moved from munit+mcover to utest+instrument + +## version 2.9.0 (2024-06-10) + +- New check `FileNameCase` to check file names match module names ([#527](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/527)) +- Fixed XMLReporter to no longer escape `/` to `/` ([#527](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/527)) + +## version 2.8.5 (2023-02-15) + +- Fixed inner assignement check to allow assignment in arrow functions, fixes [#259](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/259) +- Updated tokentree lib + +## version 2.8.4 (2023-01-05) + +- Fixed null pointer reference in BaseReporter, fixes [#517](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/517) ([#518](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/518)) +- Fixed null pointer reference in JSONReporter ([#516](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/516)) +- Fixed C++ compilation on nightly + +## version 2.8.3 (2022-09-21) + +- Fixed MagicNumber check to support numeric separators and suffixes ([#515](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/515)) + +## version 2.8.2 (2022-09-14) + +- Updated haxeparser and tokentree libs to support latest Haxe nightly syntax ([#514](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/514)) + +## version 2.8.1 (2022-09-07) + +- Added support for inline markup ([#513](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/513)) +- Retired Haxe 4.1.5 compile support ([#513](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/513)) + +## version 2.8.0 (2022-08-24) + +- New check `CommentedOutCode` to check comments for commented out code fragments ([#512](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/512)) +- Fixed Haxe nightly compilation ([#505](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/505)) +- Added related messages to reporters for `CodeSimilarity` check ([#506](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/506)) +- Fixed null pointer exception in `UnusedImport` check ([#507](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/507)) +- Updated to Haxe 4.2.4 ([#512](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/512)) +- Retired Haxe 4.0.5 compile support ([#512](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/512)) + +## version 2.7.0 (2020-12-23) + +- **Breaking Change** replaced `EnforceVarTypeHint` with `VarTypeHint` check ([#500](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/500)) +- Added support for final in `MagicNumber`, fixes [#494](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/494) ([#495](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/495)) +- Fixed handling `OBJECT_DECL` token in `RightCurly`, fixes [#496](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/496) ([#497](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/497)) +- Reorganised build files ([#498](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/498)) +- Refactored for tokentree API change ([#500](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/500) + [#501](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/501)) +- Updated haxeparser lib with latest syntax changes ([#502](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/502)) +- Retired Haxe 3.4.7 compile support ([#502](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/502)) + ## version 2.6.1 (2019-12-17) - Added `allowFinal` setting to `VariableInitialisation`, fixes [#491](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/491) ([#492](https://github.com/HaxeCheckstyle/haxe-checkstyle/issues/492)) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index e2f9928d..00000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at adiinteractive@gmail.com. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/README.md b/README.md index f033c98d..0eaf6892 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,11 @@ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT) [![Release](https://img.shields.io/github/release/HaxeCheckstyle/haxe-checkstyle.svg)](http://lib.haxe.org/p/checkstyle/) -[![Build Status](https://travis-ci.org/HaxeCheckstyle/haxe-checkstyle.svg)](https://travis-ci.org/HaxeCheckstyle/haxe-checkstyle) [![Haxe-Checkstyle Linux](https://github.com/HaxeCheckstyle/haxe-checkstyle/workflows/Haxe-Checkstyle%20Linux/badge.svg)](https://github.com/HaxeCheckstyle/haxe-checkstyle/actions) [![Codecov](https://img.shields.io/codecov/c/github/HaxeCheckstyle/haxe-checkstyle.svg)](https://codecov.io/github/HaxeCheckstyle/haxe-checkstyle?branch=dev) -[![Gitter chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/HaxeCheckstyle/haxe-checkstyle) **Haxe Checkstyle** is a static analysis tool to help developers write Haxe code that adheres to a coding standard. diff --git a/build.hxml b/build.hxml index ca1e13fb..08ee19dc 100644 --- a/build.hxml +++ b/build.hxml @@ -1,3 +1,3 @@ -buildGlobal.hxml +build/common.hxml -main checkstyle.Main -neko run.n \ No newline at end of file diff --git a/build/Build.hx b/build/Build.hx index 73227ce3..b7206d87 100644 --- a/build/Build.hx +++ b/build/Build.hx @@ -4,6 +4,8 @@ import haxe.Timer; helper class to build everything, avoids `--next` **/ class Build { + static var exitCode:Int = 0; + /** run all build files **/ @@ -12,7 +14,9 @@ class Build { callLix("buildDebug.hxml", "runD.n"); callLix("buildJS.hxml", "run.js"); callLix("buildSchema.hxml", "Json schema"); - callLix("buildTest.hxml", "Unittests"); + callLix("testAndResources.hxml", "Unittests neko / eval + generate resoucres"); + callLix("testJava.hxml", "Unittests Java"); + Sys.exit(exitCode); } /** @@ -23,7 +27,10 @@ class Build { **/ public static function callLix(buildFile:String, title:String) { var startTime = Timer.stamp(); - Sys.command("npx", ["haxe", buildFile]); - Sys.println('building $title (${Timer.stamp() - startTime})'); + var result:Int = Sys.command("npx", ["haxe", buildFile]); + Sys.println('building $title (took ${Timer.stamp() - startTime})'); + if (result != 0) { + exitCode = result; + } } } \ No newline at end of file diff --git a/build/common.hxml b/build/common.hxml new file mode 100644 index 00000000..eb71cca0 --- /dev/null +++ b/build/common.hxml @@ -0,0 +1,6 @@ +-cp src +-lib haxeparser +-lib compiletime +-lib hxargs +-lib tokentree +--macro CompileTime.importPackage("checkstyle.checks") diff --git a/build/commonCoverage.hxml b/build/commonCoverage.hxml new file mode 100644 index 00000000..644f9921 --- /dev/null +++ b/build/commonCoverage.hxml @@ -0,0 +1,13 @@ +-lib instrument + +-D coverage-console-summary-reporter +-D coverage-console-file-summary-reporter +-D coverage-console-package-summary-reporter +-D coverage-lcov-reporter +-D coverage-codecov-reporter + +-lib instrument +--macro instrument.Instrumentation.coverage(['checkstyle'], ['src'], []) +# --macro instrument.Instrumentation.coverage(['checkstyle'], ['src'], ['checkstyle.reporter', 'checkstyle.Main']) + +#--macro mcover.MCover.coverage(['checkstyle'], ['src'], ['checkstyle.reporter', 'checkstyle.Main']) diff --git a/build/commonTest.hxml b/build/commonTest.hxml new file mode 100644 index 00000000..c0be8d85 --- /dev/null +++ b/build/commonTest.hxml @@ -0,0 +1,12 @@ +build/common.hxml +-cp test +-lib utest +-lib test-adapter +-D unittest +-D UTEST_PRINT_TESTS +# -D UTEST_FAILURE_THROW + +# -debug + +--macro CompileTime.importPackage("checkstyle.checks") +--macro CompileTime.importPackage("misc") diff --git a/buildCpp.hxml b/buildCpp.hxml index 7ed55374..0f892ae5 100644 --- a/buildCpp.hxml +++ b/buildCpp.hxml @@ -1,4 +1,4 @@ -buildGlobal.hxml +build/common.hxml # -lib hxcpp-debugger # -D HXCPP_DEBUGGER diff --git a/buildDebug.hxml b/buildDebug.hxml index 4c753af9..2cc8cf61 100644 --- a/buildDebug.hxml +++ b/buildDebug.hxml @@ -1,4 +1,4 @@ -buildGlobal.hxml +build/common.hxml -main checkstyle.Main -debug -neko runD.n \ No newline at end of file diff --git a/buildGlobal.hxml b/buildGlobal.hxml deleted file mode 100644 index 065171a3..00000000 --- a/buildGlobal.hxml +++ /dev/null @@ -1,5 +0,0 @@ --cp src --lib haxeparser --lib compiletime --lib hxargs --lib tokentree \ No newline at end of file diff --git a/buildJS.hxml b/buildJS.hxml index 398a7f4b..9703ab40 100644 --- a/buildJS.hxml +++ b/buildJS.hxml @@ -1,4 +1,4 @@ -buildGlobal.hxml +build/common.hxml -lib hxnodejs -main checkstyle.Main --js haxecheckstyle.js \ No newline at end of file +-js haxecheckstyle.js diff --git a/buildSchema.hxml b/buildSchema.hxml index b2b1029f..9c18b67a 100644 --- a/buildSchema.hxml +++ b/buildSchema.hxml @@ -1,3 +1,3 @@ -buildGlobal.hxml +build/common.hxml -cp schema -x SchemaGenerator diff --git a/buildTelemetry.hxml b/buildTelemetry.hxml index 842ccfc6..2dfb7bfa 100644 --- a/buildTelemetry.hxml +++ b/buildTelemetry.hxml @@ -1,4 +1,4 @@ -buildGlobal.hxml +build/common.hxml -lib hxtelemetry -D HXCPP_STACK_TRACE diff --git a/buildTest.hxml b/buildTest.hxml deleted file mode 100644 index 6f0878c2..00000000 --- a/buildTest.hxml +++ /dev/null @@ -1,12 +0,0 @@ -buildGlobal.hxml --cp test --lib mcover --lib munit --lib test-adapter --D unittest --x TestMain ---macro mcover.MCover.coverage(['checkstyle'], ['src'], ['checkstyle.reporter', 'checkstyle.Main']) - --cmd neko run -s src -s test -s schema -s build -p resources/static-analysis.txt --cmd neko run --default-config resources/default-config.json --cmd neko run -c resources/default-config.json \ No newline at end of file diff --git a/checkstyle.json b/checkstyle.json index df14663f..f854447b 100644 --- a/checkstyle.json +++ b/checkstyle.json @@ -28,7 +28,10 @@ { "props": { "ignoreExtern": true, - "format": "^[A-Z][A-Z0-9]*(_[A-Z0-9_]+)*$" + "format": "^[A-Z][A-Z0-9]*(_[A-Z0-9_]+)*$", + "tokens": [ + "INLINE" + ] }, "type": "ConstantName" }, @@ -50,6 +53,9 @@ { "type": "DefaultComesLast" }, + { + "type": "CommentedOutCode" + }, { "type": "DocCommentStyle" }, @@ -136,6 +142,9 @@ { "type": "FileLength" }, + { + "type": "FileNameCase" + }, { "props": { "option": "upperCase" @@ -150,15 +159,6 @@ }, "type": "HiddenField" }, - { - "type": "Indentation" - }, - { - "props": { - "character": "tab" - }, - "type": "IndentationCharacter" - }, { "type": "InnerAssignment" }, diff --git a/haxe3_libraries/compiletime.hxml b/haxe3_libraries/compiletime.hxml deleted file mode 100644 index 921e164a..00000000 --- a/haxe3_libraries/compiletime.hxml +++ /dev/null @@ -1,3 +0,0 @@ --D compiletime=2.8.0 -# @install: lix --silent download "haxelib:/compiletime#2.8.0" into compiletime/2.8.0/haxelib --cp ${HAXE_LIBCACHE}/compiletime/2.8.0/haxelib/src/ diff --git a/haxe3_libraries/haxeparser.hxml b/haxe3_libraries/haxeparser.hxml deleted file mode 100644 index 7a80b5f7..00000000 --- a/haxe3_libraries/haxeparser.hxml +++ /dev/null @@ -1,4 +0,0 @@ --D haxeparser=3.3.0 -# @install: lix --silent download "haxelib:/haxeparser#3.3.0" into haxeparser/3.3.0/haxelib --lib hxparse --cp ${HAXE_LIBCACHE}/haxeparser/3.3.0/haxelib/src diff --git a/haxe3_libraries/hxargs.hxml b/haxe3_libraries/hxargs.hxml deleted file mode 100644 index 646e484a..00000000 --- a/haxe3_libraries/hxargs.hxml +++ /dev/null @@ -1,3 +0,0 @@ --D hxargs=3.0.2 -# @install: lix --silent download "gh://github.com/Simn/hxargs#27eb1114ebcc82fe02abf2cfa3738ae6f43b0e24" into hxargs/3.0.2/github/27eb1114ebcc82fe02abf2cfa3738ae6f43b0e24 --cp ${HAXE_LIBCACHE}/hxargs/3.0.2/github/27eb1114ebcc82fe02abf2cfa3738ae6f43b0e24/ diff --git a/haxe3_libraries/hxcpp.hxml b/haxe3_libraries/hxcpp.hxml deleted file mode 100644 index a1f3d7a3..00000000 --- a/haxe3_libraries/hxcpp.hxml +++ /dev/null @@ -1,4 +0,0 @@ --D hxcpp=4.0.52 -# @install: lix --silent download "haxelib:/hxcpp#4.0.52" into hxcpp/4.0.52/haxelib -# @run: haxelib run-dir hxcpp ${HAXE_LIBCACHE}/hxcpp/4.0.52/haxelib --cp ${HAXE_LIBCACHE}/hxcpp/4.0.52/haxelib/ diff --git a/haxe3_libraries/hxjava.hxml b/haxe3_libraries/hxjava.hxml deleted file mode 100644 index 0942a5aa..00000000 --- a/haxe3_libraries/hxjava.hxml +++ /dev/null @@ -1,5 +0,0 @@ --D hxjava=3.2.0 -# @install: lix --silent download "haxelib:/hxjava#3.2.0" into hxjava/3.2.0/haxelib -# @run: haxelib run-dir hxjava ${HAXE_LIBCACHE}/hxjava/3.2.0/haxelib --cp ${HAXE_LIBCACHE}/hxjava/3.2.0/haxelib/ --java-lib lib/hxjava-std.jar diff --git a/haxe3_libraries/hxjsonast.hxml b/haxe3_libraries/hxjsonast.hxml deleted file mode 100644 index b7480867..00000000 --- a/haxe3_libraries/hxjsonast.hxml +++ /dev/null @@ -1,3 +0,0 @@ --D hxjsonast=1.0.1 -# @install: lix --silent download "haxelib:/hxjsonast#1.0.1" into hxjsonast/1.0.1/haxelib --cp ${HAXE_LIBCACHE}/hxjsonast/1.0.1/haxelib/src diff --git a/haxe3_libraries/hxnodejs.hxml b/haxe3_libraries/hxnodejs.hxml deleted file mode 100644 index 1bfe8128..00000000 --- a/haxe3_libraries/hxnodejs.hxml +++ /dev/null @@ -1,6 +0,0 @@ --D hxnodejs=10.0.0 -# @install: lix --silent download "gh://github.com/HaxeFoundation/hxnodejs#462c800e16aa0b91df5a7c5d54782b313c3f8730" into hxnodejs/10.0.0/github/462c800e16aa0b91df5a7c5d54782b313c3f8730 --cp ${HAXE_LIBCACHE}/hxnodejs/10.0.0/github/462c800e16aa0b91df5a7c5d54782b313c3f8730/src ---macro allowPackage('sys') -# should behave like other target defines and not be defined in macro context ---macro define('nodejs') diff --git a/haxe3_libraries/hxparse.hxml b/haxe3_libraries/hxparse.hxml deleted file mode 100644 index 2201ba72..00000000 --- a/haxe3_libraries/hxparse.hxml +++ /dev/null @@ -1,3 +0,0 @@ --D hxparse=4.0.0 -# @install: lix --silent download "haxelib:/hxparse#4.0.0" into hxparse/4.0.0/haxelib --cp ${HAXE_LIBCACHE}/hxparse/4.0.0/haxelib/src diff --git a/haxe3_libraries/json2object.hxml b/haxe3_libraries/json2object.hxml deleted file mode 100644 index 416bed19..00000000 --- a/haxe3_libraries/json2object.hxml +++ /dev/null @@ -1,4 +0,0 @@ --D json2object=3.6.4 -# @install: lix --silent download "gh://github.com/elnabo/json2object#bd00ad1713bf6bda06d8a7c9ddc90888e8a6094c" into json2object/3.6.4/github/bd00ad1713bf6bda06d8a7c9ddc90888e8a6094c --lib hxjsonast --cp ${HAXE_LIBCACHE}/json2object/3.6.4/github/bd00ad1713bf6bda06d8a7c9ddc90888e8a6094c/src diff --git a/haxe3_libraries/mconsole.hxml b/haxe3_libraries/mconsole.hxml deleted file mode 100644 index 71425849..00000000 --- a/haxe3_libraries/mconsole.hxml +++ /dev/null @@ -1,3 +0,0 @@ --D mconsole=1.6.0 -# @install: lix --silent download "haxelib:/mconsole#1.6.0" into mconsole/1.6.0/haxelib --cp ${HAXE_LIBCACHE}/mconsole/1.6.0/haxelib/ diff --git a/haxe3_libraries/mcover.hxml b/haxe3_libraries/mcover.hxml deleted file mode 100644 index 3ec60840..00000000 --- a/haxe3_libraries/mcover.hxml +++ /dev/null @@ -1,5 +0,0 @@ --D mcover=2.2.1 -# @install: lix --silent download "haxelib:/mcover#2.2.1" into mcover/2.2.1/haxelib --lib mconsole --lib munit --cp ${HAXE_LIBCACHE}/mcover/2.2.1/haxelib/ diff --git a/haxe3_libraries/mlib.hxml b/haxe3_libraries/mlib.hxml deleted file mode 100644 index 49230501..00000000 --- a/haxe3_libraries/mlib.hxml +++ /dev/null @@ -1,4 +0,0 @@ --D mlib=2.0.3 -# @install: lix --silent download "haxelib:/mlib#2.0.3" into mlib/2.0.3/haxelib -# @run: haxelib run-dir mlib ${HAXE_LIBCACHE}/mlib/2.0.3/haxelib --cp ${HAXE_LIBCACHE}/mlib/2.0.3/haxelib/ diff --git a/haxe3_libraries/munit.hxml b/haxe3_libraries/munit.hxml deleted file mode 100644 index 8e364c38..00000000 --- a/haxe3_libraries/munit.hxml +++ /dev/null @@ -1,6 +0,0 @@ --D munit=2.3.4 -# @install: lix --silent download "haxelib:/munit#2.3.4" into munit/2.3.4/haxelib -# @run: haxelib run-dir munit ${HAXE_LIBCACHE}/munit/2.3.4/haxelib --lib mcover --lib mlib --cp ${HAXE_LIBCACHE}/munit/2.3.4/haxelib/ diff --git a/haxe3_libraries/test-adapter.hxml b/haxe3_libraries/test-adapter.hxml deleted file mode 100644 index a47a7c88..00000000 --- a/haxe3_libraries/test-adapter.hxml +++ /dev/null @@ -1,5 +0,0 @@ --D test-adapter=1.2.6 -# @install: lix --silent download "haxelib:/test-adapter#1.2.6" into test-adapter/1.2.6/haxelib --lib json2object --cp ${HAXE_LIBCACHE}/test-adapter/1.2.6/haxelib/ ---macro _testadapter.Macro.init() \ No newline at end of file diff --git a/haxe3_libraries/tokentree.hxml b/haxe3_libraries/tokentree.hxml deleted file mode 100644 index 88b49c61..00000000 --- a/haxe3_libraries/tokentree.hxml +++ /dev/null @@ -1,3 +0,0 @@ --D tokentree=1.0.24 -# @install: lix --silent download "haxelib:/tokentree#1.0.24" into tokentree/1.0.24/haxelib --cp ${HAXE_LIBCACHE}/tokentree/1.0.24/haxelib/src diff --git a/haxe_libraries/haxeparser.hxml b/haxe_libraries/haxeparser.hxml index 4756bf0d..dab39131 100644 --- a/haxe_libraries/haxeparser.hxml +++ b/haxe_libraries/haxeparser.hxml @@ -1,4 +1,4 @@ --D haxeparser=3.3.0 -# @install: lix --silent download "gh://github.com/Simn/haxeparser#e5746bfc55c09a3694db42738ff575b91441971a" into haxeparser/3.3.0/github/e5746bfc55c09a3694db42738ff575b91441971a +# @install: lix --silent download "gh://github.com/HaxeCheckstyle/haxeparser#49db59c303242c7e6ef1293e35ac5983f31f654d" into haxeparser/4.3.0-rc.1/github/49db59c303242c7e6ef1293e35ac5983f31f654d -lib hxparse --cp ${HAXE_LIBCACHE}/haxeparser/3.3.0/github/e5746bfc55c09a3694db42738ff575b91441971a/src +-cp ${HAXE_LIBCACHE}/haxeparser/4.3.0-rc.1/github/49db59c303242c7e6ef1293e35ac5983f31f654d/src +-D haxeparser=4.3.0-rc.1 \ No newline at end of file diff --git a/haxe_libraries/hxargs.hxml b/haxe_libraries/hxargs.hxml index 646e484a..aa3b58ee 100644 --- a/haxe_libraries/hxargs.hxml +++ b/haxe_libraries/hxargs.hxml @@ -1,3 +1,3 @@ --D hxargs=3.0.2 -# @install: lix --silent download "gh://github.com/Simn/hxargs#27eb1114ebcc82fe02abf2cfa3738ae6f43b0e24" into hxargs/3.0.2/github/27eb1114ebcc82fe02abf2cfa3738ae6f43b0e24 --cp ${HAXE_LIBCACHE}/hxargs/3.0.2/github/27eb1114ebcc82fe02abf2cfa3738ae6f43b0e24/ +# @install: lix --silent download "gh://github.com/simn/hxargs#1d8ec84f641833edd6f0cb2e4290b7524fd27219" into hxargs/3.0.2/github/1d8ec84f641833edd6f0cb2e4290b7524fd27219 +-cp ${HAXE_LIBCACHE}/hxargs/3.0.2/github/1d8ec84f641833edd6f0cb2e4290b7524fd27219/ +-D hxargs=3.0.2 \ No newline at end of file diff --git a/haxe_libraries/hxcpp.hxml b/haxe_libraries/hxcpp.hxml index a1f3d7a3..b857afba 100644 --- a/haxe_libraries/hxcpp.hxml +++ b/haxe_libraries/hxcpp.hxml @@ -1,4 +1,4 @@ --D hxcpp=4.0.52 -# @install: lix --silent download "haxelib:/hxcpp#4.0.52" into hxcpp/4.0.52/haxelib -# @run: haxelib run-dir hxcpp ${HAXE_LIBCACHE}/hxcpp/4.0.52/haxelib --cp ${HAXE_LIBCACHE}/hxcpp/4.0.52/haxelib/ +# @install: lix --silent download "gh://github.com/HaxeFoundation/hxcpp#9d9b920a42ecd073a5efaea8c7ad184acec6f479" into hxcpp/4.3.0/github/9d9b920a42ecd073a5efaea8c7ad184acec6f479 +# @run: haxelib run-dir hxcpp "${HAXE_LIBCACHE}/hxcpp/4.3.0/github/9d9b920a42ecd073a5efaea8c7ad184acec6f479" +-cp ${HAXE_LIBCACHE}/hxcpp/4.3.0/github/9d9b920a42ecd073a5efaea8c7ad184acec6f479/ +-D hxcpp=4.3.0 \ No newline at end of file diff --git a/haxe_libraries/hxjsonast.hxml b/haxe_libraries/hxjsonast.hxml index b7480867..841e786a 100644 --- a/haxe_libraries/hxjsonast.hxml +++ b/haxe_libraries/hxjsonast.hxml @@ -1,3 +1,3 @@ --D hxjsonast=1.0.1 -# @install: lix --silent download "haxelib:/hxjsonast#1.0.1" into hxjsonast/1.0.1/haxelib --cp ${HAXE_LIBCACHE}/hxjsonast/1.0.1/haxelib/src +# @install: lix --silent download "haxelib:/hxjsonast#1.1.0" into hxjsonast/1.1.0/haxelib +-cp ${HAXE_LIBCACHE}/hxjsonast/1.1.0/haxelib/src +-D hxjsonast=1.1.0 \ No newline at end of file diff --git a/haxe_libraries/hxnodejs.hxml b/haxe_libraries/hxnodejs.hxml index 1bfe8128..b4982046 100644 --- a/haxe_libraries/hxnodejs.hxml +++ b/haxe_libraries/hxnodejs.hxml @@ -1,6 +1,7 @@ --D hxnodejs=10.0.0 -# @install: lix --silent download "gh://github.com/HaxeFoundation/hxnodejs#462c800e16aa0b91df5a7c5d54782b313c3f8730" into hxnodejs/10.0.0/github/462c800e16aa0b91df5a7c5d54782b313c3f8730 --cp ${HAXE_LIBCACHE}/hxnodejs/10.0.0/github/462c800e16aa0b91df5a7c5d54782b313c3f8730/src +# @install: lix --silent download "haxelib:/hxnodejs#12.2.0" into hxnodejs/12.2.0/haxelib +-cp ${HAXE_LIBCACHE}/hxnodejs/12.2.0/haxelib/src +-D hxnodejs=12.1.0 --macro allowPackage('sys') # should behave like other target defines and not be defined in macro context --macro define('nodejs') +--macro _internal.SuppressDeprecated.run() diff --git a/haxe_libraries/hxparse.hxml b/haxe_libraries/hxparse.hxml index 48696312..9394da37 100644 --- a/haxe_libraries/hxparse.hxml +++ b/haxe_libraries/hxparse.hxml @@ -1,3 +1,3 @@ --D hxparse=4.0.0 -# @install: lix --silent download "gh://github.com/Simn/hxparse#f61faa2021f2abb85360f997ff72c4156c891adc" into hxparse/4.0.0/github/f61faa2021f2abb85360f997ff72c4156c891adc --cp ${HAXE_LIBCACHE}/hxparse/4.0.0/github/f61faa2021f2abb85360f997ff72c4156c891adc/src +# @install: lix --silent download "gh://github.com/simn/hxparse#876070ec62a4869de60081f87763e23457a3bda8" into hxparse/4.3.0/github/876070ec62a4869de60081f87763e23457a3bda8 +-cp ${HAXE_LIBCACHE}/hxparse/4.3.0/github/876070ec62a4869de60081f87763e23457a3bda8/src +-D hxparse=4.3.0 \ No newline at end of file diff --git a/haxe_libraries/instrument.hxml b/haxe_libraries/instrument.hxml new file mode 100644 index 00000000..ea7cc93f --- /dev/null +++ b/haxe_libraries/instrument.hxml @@ -0,0 +1,4 @@ +# @install: lix --silent download "haxelib:/instrument#1.2.0" into instrument/1.2.0/haxelib +-lib safety +-cp ${HAXE_LIBCACHE}/instrument/1.2.0/haxelib/src +-D instrument=1.2.0 \ No newline at end of file diff --git a/haxe_libraries/json2object.hxml b/haxe_libraries/json2object.hxml index 8e7a7317..5ed25d9c 100644 --- a/haxe_libraries/json2object.hxml +++ b/haxe_libraries/json2object.hxml @@ -1,4 +1,4 @@ --D json2object=3.6.4 -# @install: lix --silent download "haxelib:/json2object#3.6.4" into json2object/3.6.4/haxelib +# @install: lix --silent download "gh://github.com/elnabo/json2object#a75859de1e966c09e73591b6c9186086c143fe60" into json2object/3.11.0/github/a75859de1e966c09e73591b6c9186086c143fe60 -lib hxjsonast --cp ${HAXE_LIBCACHE}/json2object/3.6.4/haxelib/src +-cp ${HAXE_LIBCACHE}/json2object/3.11.0/github/a75859de1e966c09e73591b6c9186086c143fe60/src +-D json2object=3.11.0 \ No newline at end of file diff --git a/haxe_libraries/mconsole.hxml b/haxe_libraries/mconsole.hxml index 71425849..993fd0f5 100644 --- a/haxe_libraries/mconsole.hxml +++ b/haxe_libraries/mconsole.hxml @@ -1,3 +1,3 @@ --D mconsole=1.6.0 # @install: lix --silent download "haxelib:/mconsole#1.6.0" into mconsole/1.6.0/haxelib -cp ${HAXE_LIBCACHE}/mconsole/1.6.0/haxelib/ +-D mconsole=1.6.0 \ No newline at end of file diff --git a/haxe_libraries/mcover.hxml b/haxe_libraries/mcover.hxml index 3ec60840..6aafeec2 100644 --- a/haxe_libraries/mcover.hxml +++ b/haxe_libraries/mcover.hxml @@ -1,5 +1,3 @@ --D mcover=2.2.1 -# @install: lix --silent download "haxelib:/mcover#2.2.1" into mcover/2.2.1/haxelib --lib mconsole --lib munit --cp ${HAXE_LIBCACHE}/mcover/2.2.1/haxelib/ +# @install: lix --silent download "gh://github.com/massive-oss/mcover#c3c47cd682b0b202a41caee95321989391b617ef" into mcover/0.0.0/github/c3c47cd682b0b202a41caee95321989391b617ef +-cp ${HAXE_LIBCACHE}/mcover/0.0.0/github/c3c47cd682b0b202a41caee95321989391b617ef/src +-D mcover=0.0.0 \ No newline at end of file diff --git a/haxe_libraries/mlib.hxml b/haxe_libraries/mlib.hxml index 49230501..a6d19592 100644 --- a/haxe_libraries/mlib.hxml +++ b/haxe_libraries/mlib.hxml @@ -1,4 +1,4 @@ --D mlib=2.0.3 # @install: lix --silent download "haxelib:/mlib#2.0.3" into mlib/2.0.3/haxelib # @run: haxelib run-dir mlib ${HAXE_LIBCACHE}/mlib/2.0.3/haxelib -cp ${HAXE_LIBCACHE}/mlib/2.0.3/haxelib/ +-D mlib=2.0.3 \ No newline at end of file diff --git a/haxe_libraries/munit.hxml b/haxe_libraries/munit.hxml index 8e364c38..350abf02 100644 --- a/haxe_libraries/munit.hxml +++ b/haxe_libraries/munit.hxml @@ -1,6 +1,4 @@ --D munit=2.3.4 -# @install: lix --silent download "haxelib:/munit#2.3.4" into munit/2.3.4/haxelib -# @run: haxelib run-dir munit ${HAXE_LIBCACHE}/munit/2.3.4/haxelib --lib mcover +# @install: lix --silent download "gh://github.com/AlexHaxe/MassiveUnit#645952947a10d27f2460321eb9c6c9e2a93b997d" into MassiveUnit/0.0.0/github/645952947a10d27f2460321eb9c6c9e2a93b997d -lib mlib --cp ${HAXE_LIBCACHE}/munit/2.3.4/haxelib/ +-cp ${HAXE_LIBCACHE}/MassiveUnit/0.0.0/github/645952947a10d27f2460321eb9c6c9e2a93b997d/src +-D munit=2.3.5 \ No newline at end of file diff --git a/haxe_libraries/safety.hxml b/haxe_libraries/safety.hxml new file mode 100644 index 00000000..973dc8b9 --- /dev/null +++ b/haxe_libraries/safety.hxml @@ -0,0 +1,3 @@ +# @install: lix --silent download "haxelib:/safety#1.1.2" into safety/1.1.2/haxelib +-cp ${HAXE_LIBCACHE}/safety/1.1.2/haxelib/src +-D safety=1.1.2 \ No newline at end of file diff --git a/haxe_libraries/test-adapter.hxml b/haxe_libraries/test-adapter.hxml index a47a7c88..2551a21a 100644 --- a/haxe_libraries/test-adapter.hxml +++ b/haxe_libraries/test-adapter.hxml @@ -1,5 +1,5 @@ --D test-adapter=1.2.6 -# @install: lix --silent download "haxelib:/test-adapter#1.2.6" into test-adapter/1.2.6/haxelib +# @install: lix --silent download "haxelib:/test-adapter#2.0.7" into test-adapter/2.0.7/haxelib -lib json2object --cp ${HAXE_LIBCACHE}/test-adapter/1.2.6/haxelib/ +-cp ${HAXE_LIBCACHE}/test-adapter/2.0.7/haxelib/ +-D test-adapter=2.0.7 --macro _testadapter.Macro.init() \ No newline at end of file diff --git a/haxe_libraries/tokentree.hxml b/haxe_libraries/tokentree.hxml index 88b49c61..57aa000a 100644 --- a/haxe_libraries/tokentree.hxml +++ b/haxe_libraries/tokentree.hxml @@ -1,3 +1,3 @@ --D tokentree=1.0.24 -# @install: lix --silent download "haxelib:/tokentree#1.0.24" into tokentree/1.0.24/haxelib --cp ${HAXE_LIBCACHE}/tokentree/1.0.24/haxelib/src +# @install: lix --silent download "haxelib:/tokentree#1.2.17" into tokentree/1.2.17/haxelib +-cp ${HAXE_LIBCACHE}/tokentree/1.2.17/haxelib/src +-D tokentree=1.2.17 \ No newline at end of file diff --git a/haxe_libraries/utest.hxml b/haxe_libraries/utest.hxml new file mode 100644 index 00000000..02ee1cad --- /dev/null +++ b/haxe_libraries/utest.hxml @@ -0,0 +1,4 @@ +# @install: lix --silent download "gh://github.com/haxe-utest/utest#f759c0aa257aa723b3dd607cf7cb53d16194d13f" into utest/2.0.0-alpha/github/f759c0aa257aa723b3dd607cf7cb53d16194d13f +-cp ${HAXE_LIBCACHE}/utest/2.0.0-alpha/github/f759c0aa257aa723b3dd607cf7cb53d16194d13f/src +-D utest=2.0.0-alpha +--macro utest.utils.Macro.importEnvSettings() diff --git a/haxelib.json b/haxelib.json index c65e0116..a951386e 100644 --- a/haxelib.json +++ b/haxelib.json @@ -18,8 +18,8 @@ "adireddy", "Gama11" ], - "releasenote": "breaking changes: MethodLength settings changed, new checks CodeSimilarity, EnforceVarTypeHint, AvoidIdentifier, ArrowFunction and NestedControlFlow, some Haxe 4 fixes and a few bugfixes - see CHANGELOG", - "version": "2.6.1", + "releasenote": "added FileNameCase check - see CHANGELOG", + "version": "2.9.0", "url": "https://github.com/HaxeCheckstyle/haxe-checkstyle", "dependencies": {} } \ No newline at end of file diff --git a/makeReleaseZip.sh b/makeReleaseZip.sh index 88f4cc00..96490556 100755 --- a/makeReleaseZip.sh +++ b/makeReleaseZip.sh @@ -2,7 +2,7 @@ npm install npx lix download -npx lix use haxe 4.0.5 +npx lix use haxe nightly npx haxe buildAll.hxml diff --git a/package-lock.json b/package-lock.json index 43609562..e3ac7b4f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,14 +1,349 @@ { - "name": "haxe-checkstyle", - "version": "2.6.1", - "lockfileVersion": 1, + "name": "@haxecheckstyle/haxe-checkstyle", + "version": "2.9.0", + "lockfileVersion": 2, "requires": true, + "packages": { + "": { + "name": "@haxecheckstyle/haxe-checkstyle", + "version": "2.9.0", + "license": "MIT", + "bin": { + "haxe-checkstyle": "bin/checkstyle.js" + }, + "devDependencies": { + "lix": "^15.12.0", + "uglify-js-es6": "^2.8.9" + } + }, + "node_modules/align-text": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/align-text/-/align-text-0.1.4.tgz", + "integrity": "sha512-GrTZLRpmp6wIC2ztrWW9MjjTgSKccffgFagbNDOX95/dcjEcYZibYTeaOntySQLcdw1ztBoFkviiUvTMbb9MYg==", + "dev": true, + "dependencies": { + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/camelcase": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz", + "integrity": "sha512-wzLkDa4K/mzI1OSITC+DUyjgIl/ETNHE9QvYgy6J6Jvqyyz4C0Xfd+lQhb19sX2jMpZV4IssUn0VDVmglV+s4g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/center-align": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/center-align/-/center-align-0.1.3.tgz", + "integrity": "sha512-Baz3aNe2gd2LP2qk5U+sDk/m4oSuwSDcBfayTCTBoWpfIGO5XFxPmjILQII4NGiZjD6DoDI6kf7gKaxkf7s3VQ==", + "dev": true, + "dependencies": { + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/cliui": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz", + "integrity": "sha512-GIOYRizG+TGoc7Wgc1LiOTLare95R3mzKgoln+Q/lE4ceiYH19gUpl0l0Ffq4lJDEf3FxujMe6IBfOCs7pfqNA==", + "dev": true, + "dependencies": { + "center-align": "^0.1.1", + "right-align": "^0.1.1", + "wordwrap": "0.0.2" + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true + }, + "node_modules/kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha512-NOW9QQXMoZGg/oqnVNoNTTIFEIid1627WCffUBJEdMxYApq7mNE7CpzucIPc+ZQg25Phej7IJSmX3hO+oblOtQ==", + "dev": true, + "dependencies": { + "is-buffer": "^1.1.5" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/lazy-cache": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz", + "integrity": "sha512-RE2g0b5VGZsOCFOCgP7omTRYFqydmZkBwl5oNnQ1lDYC57uyO9KqNnNVxT7COSHTxrRCWVcAVOcbjk+tvh/rgQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/lix": { + "version": "15.12.0", + "resolved": "https://registry.npmjs.org/lix/-/lix-15.12.0.tgz", + "integrity": "sha512-FA36oCl+M+3Of8L4eErXw7tAHGOjqEC4IgEvH6oPDsiYd4yN6XpzZGcbLuIyu4PiztjOrr1TKJnpwi32qb2ddw==", + "dev": true, + "hasInstallScript": true, + "bin": { + "haxe": "bin/haxeshim.js", + "haxelib": "bin/haxelibshim.js", + "lix": "bin/lix.js", + "neko": "bin/nekoshim.js" + } + }, + "node_modules/longest": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz", + "integrity": "sha512-k+yt5n3l48JU4k8ftnKG6V7u32wyH2NfKzeMto9F/QRE0amxy/LayxwlvjjkZEIzqR+19IrtFO8p5kB9QaYUFg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==", + "dev": true, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/right-align": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/right-align/-/right-align-0.1.3.tgz", + "integrity": "sha512-yqINtL/G7vs2v+dFIZmFUDbnVyFUJFKd6gK22Kgo6R4jfJGFtisKyncWDDULgjfqf4ASQuIQyjJ7XZ+3aWpsAg==", + "dev": true, + "dependencies": { + "align-text": "^0.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/uglify-js-es6": { + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/uglify-js-es6/-/uglify-js-es6-2.8.9.tgz", + "integrity": "sha512-U+0UdDT77MSsO4Bz78y55UtXq/z6XvoZgHhohfu0oaDNs+Vq087kyARn1nR35QggwPfLfI7NFWFBihaU1+90Cg==", + "dev": true, + "dependencies": { + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" + }, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/uglify-to-browserify": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz", + "integrity": "sha512-vb2s1lYx2xBtUgy+ta+b2J/GLVUR+wmpINwHePmPRhOsIVCG2wDzKJ0n14GslH1BifsqVzSOwQhRaCAsZ/nI4Q==", + "dev": true + }, + "node_modules/window-size": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.0.tgz", + "integrity": "sha512-1pTPQDKTdd61ozlKGNCjhNRd+KPmgLSGa3mZTHoOliaGcESD8G1PXhh7c1fgiPjVbNVfgy2Faw4BI8/m0cC8Mg==", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/wordwrap": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz", + "integrity": "sha512-xSBsCeh+g+dinoBv3GAOWM4LcVVO68wLXRanibtBSdUvkGWQRGeE9P7IwU9EmDDi4jA6L44lz15CGMwdw9N5+Q==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/yargs": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz", + "integrity": "sha512-QFzUah88GAGy9lyDKGBqZdkYApt63rCXYBGYnEP4xDJPXNqXXnBDACnbrXnViV6jRSqAePwrATi2i8mfYm4L1A==", + "dev": true, + "dependencies": { + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", + "window-size": "0.1.0" + } + } + }, "dependencies": { + "align-text": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/align-text/-/align-text-0.1.4.tgz", + "integrity": "sha512-GrTZLRpmp6wIC2ztrWW9MjjTgSKccffgFagbNDOX95/dcjEcYZibYTeaOntySQLcdw1ztBoFkviiUvTMbb9MYg==", + "dev": true, + "requires": { + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" + } + }, + "camelcase": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-1.2.1.tgz", + "integrity": "sha512-wzLkDa4K/mzI1OSITC+DUyjgIl/ETNHE9QvYgy6J6Jvqyyz4C0Xfd+lQhb19sX2jMpZV4IssUn0VDVmglV+s4g==", + "dev": true + }, + "center-align": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/center-align/-/center-align-0.1.3.tgz", + "integrity": "sha512-Baz3aNe2gd2LP2qk5U+sDk/m4oSuwSDcBfayTCTBoWpfIGO5XFxPmjILQII4NGiZjD6DoDI6kf7gKaxkf7s3VQ==", + "dev": true, + "requires": { + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" + } + }, + "cliui": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz", + "integrity": "sha512-GIOYRizG+TGoc7Wgc1LiOTLare95R3mzKgoln+Q/lE4ceiYH19gUpl0l0Ffq4lJDEf3FxujMe6IBfOCs7pfqNA==", + "dev": true, + "requires": { + "center-align": "^0.1.1", + "right-align": "^0.1.1", + "wordwrap": "0.0.2" + } + }, + "decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "dev": true + }, + "is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha512-NOW9QQXMoZGg/oqnVNoNTTIFEIid1627WCffUBJEdMxYApq7mNE7CpzucIPc+ZQg25Phej7IJSmX3hO+oblOtQ==", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + }, + "lazy-cache": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/lazy-cache/-/lazy-cache-1.0.4.tgz", + "integrity": "sha512-RE2g0b5VGZsOCFOCgP7omTRYFqydmZkBwl5oNnQ1lDYC57uyO9KqNnNVxT7COSHTxrRCWVcAVOcbjk+tvh/rgQ==", + "dev": true + }, "lix": { - "version": "15.5.4", - "resolved": "https://registry.npmjs.org/lix/-/lix-15.5.4.tgz", - "integrity": "sha512-abOUxMKCcdoR5WUA8Sos5nE/AuXG02/aHkIwzZ7D3uckBcyvhgGOo0NLlMoZEHCLngtvvJ3QvS2KqQa/o+8Upg==", + "version": "15.12.0", + "resolved": "https://registry.npmjs.org/lix/-/lix-15.12.0.tgz", + "integrity": "sha512-FA36oCl+M+3Of8L4eErXw7tAHGOjqEC4IgEvH6oPDsiYd4yN6XpzZGcbLuIyu4PiztjOrr1TKJnpwi32qb2ddw==", + "dev": true + }, + "longest": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/longest/-/longest-1.0.1.tgz", + "integrity": "sha512-k+yt5n3l48JU4k8ftnKG6V7u32wyH2NfKzeMto9F/QRE0amxy/LayxwlvjjkZEIzqR+19IrtFO8p5kB9QaYUFg==", + "dev": true + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==", + "dev": true + }, + "right-align": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/right-align/-/right-align-0.1.3.tgz", + "integrity": "sha512-yqINtL/G7vs2v+dFIZmFUDbnVyFUJFKd6gK22Kgo6R4jfJGFtisKyncWDDULgjfqf4ASQuIQyjJ7XZ+3aWpsAg==", + "dev": true, + "requires": { + "align-text": "^0.1.1" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==", + "dev": true + }, + "uglify-js-es6": { + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/uglify-js-es6/-/uglify-js-es6-2.8.9.tgz", + "integrity": "sha512-U+0UdDT77MSsO4Bz78y55UtXq/z6XvoZgHhohfu0oaDNs+Vq087kyARn1nR35QggwPfLfI7NFWFBihaU1+90Cg==", + "dev": true, + "requires": { + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" + } + }, + "uglify-to-browserify": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz", + "integrity": "sha512-vb2s1lYx2xBtUgy+ta+b2J/GLVUR+wmpINwHePmPRhOsIVCG2wDzKJ0n14GslH1BifsqVzSOwQhRaCAsZ/nI4Q==", + "dev": true + }, + "window-size": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.1.0.tgz", + "integrity": "sha512-1pTPQDKTdd61ozlKGNCjhNRd+KPmgLSGa3mZTHoOliaGcESD8G1PXhh7c1fgiPjVbNVfgy2Faw4BI8/m0cC8Mg==", + "dev": true + }, + "wordwrap": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.2.tgz", + "integrity": "sha512-xSBsCeh+g+dinoBv3GAOWM4LcVVO68wLXRanibtBSdUvkGWQRGeE9P7IwU9EmDDi4jA6L44lz15CGMwdw9N5+Q==", "dev": true + }, + "yargs": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz", + "integrity": "sha512-QFzUah88GAGy9lyDKGBqZdkYApt63rCXYBGYnEP4xDJPXNqXXnBDACnbrXnViV6jRSqAePwrATi2i8mfYm4L1A==", + "dev": true, + "requires": { + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", + "window-size": "0.1.0" + } } } } diff --git a/package.json b/package.json index df2e15fb..770413e5 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,10 @@ { - "name": "haxe-checkstyle", - "version": "2.6.1", + "name": "@haxecheckstyle/haxe-checkstyle", + "version": "2.9.0", "description": "Automated code analysis ideal for projects that want to enforce a coding standard.", "repository": { "type": "git", - "url": "https://github.com/HaxeCheckstyle/haxe-checkstyle" + "url": "git+https://github.com/HaxeCheckstyle/haxe-checkstyle.git" }, "keywords": [ "checkstyle", @@ -29,8 +29,21 @@ } ], "devDependencies": { - "lix": "^15.5.4" + "lix": "^15.12.0", + "uglify-js-es6": "^2.8.9" }, "bugs": "https://github.com/HaxeCheckstyle/haxe-checkstyle/issues", - "license": "MIT" + "license": "MIT", + "bin": { + "haxe-checkstyle": "bin/checkstyle.js" + }, + "files": [ + "bin" + ], + "publishConfig": { + "registry": "https://npm.pkg.github.com/" + }, + "scripts": { + "build": "haxe buildJS.hxml && ./uglifyCheckstyle.sh" + } } diff --git a/resources/checkstyle-excludes-schema.json b/resources/checkstyle-excludes-schema.json index 6f212a10..4a1e2d8c 100644 --- a/resources/checkstyle-excludes-schema.json +++ b/resources/checkstyle-excludes-schema.json @@ -18,42 +18,38 @@ }, "UnusedImport": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 78 + "propertyOrder": 79 }, "Dynamic": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 19 + "propertyOrder": 20 }, "Final": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 28 + "propertyOrder": 29 }, "MultipleStringLiterals": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 45 - }, - "EnforceVarTypeHint": { - "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 24 + "propertyOrder": 46 }, "NeedBraces": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 47 + "propertyOrder": 48 }, "SeparatorWhitespace": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 64 + "propertyOrder": 65 }, "all": { "$ref": "#/definitions/ExcludeFilterList" }, "LocalVariableName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 38 + "propertyOrder": 39 }, "NestedForDepth": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 49 + "propertyOrder": 50 }, "Anonymous": { "$ref": "#/definitions/ExcludeFilterList", @@ -61,11 +57,11 @@ }, "MultipleVariableDeclarations": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 46 + "propertyOrder": 47 }, "NestedTryDepth": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 51 + "propertyOrder": 52 }, "BlockBreakingConditional": { "$ref": "#/definitions/ExcludeFilterList", @@ -77,7 +73,7 @@ }, "EmptyBlock": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 21 + "propertyOrder": 22 }, "ExtendedEmptyLines": { "$ref": "#/definitions/ExcludeFilterList", @@ -85,47 +81,47 @@ }, "ReturnCount": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 62 + "propertyOrder": 63 }, "DefaultComesLast": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 17 + "propertyOrder": 18 }, "HexadecimalLiteral": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 29 + "propertyOrder": 30 }, "WhitespaceAfter": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 81 + "propertyOrder": 83 }, "ConstantName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 15 + "propertyOrder": 16 }, "EmptyPackage": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 23 + "propertyOrder": 24 }, "Interface": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 34 + "propertyOrder": 35 }, "WhitespaceAround": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 82 + "propertyOrder": 84 }, "NestedIfDepth": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 50 + "propertyOrder": 51 }, "ParameterName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 55 + "propertyOrder": 56 }, "NullableParameter": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 52 + "propertyOrder": 53 }, "AvoidStarImport": { "$ref": "#/definitions/ExcludeFilterList", @@ -133,7 +129,7 @@ }, "SeparatorWrap": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 65 + "propertyOrder": 66 }, "AvoidIdentifier": { "$ref": "#/definitions/ExcludeFilterList", @@ -141,19 +137,19 @@ }, "RedundantAllowMeta": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 59 + "propertyOrder": 60 }, "HiddenField": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 30 + "propertyOrder": 31 }, "UnnecessaryConstructor": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 77 + "propertyOrder": 78 }, "SimplifyBooleanExpression": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 66 + "propertyOrder": 67 }, "path": { "description": "filters excludes relative to\n\t- RELATIVE_TO_PROJECT = use project root\n\t- RELATIVE_TO_SOURCE = use path(s) specified via \"-s \" command line switches", @@ -165,23 +161,23 @@ }, "MethodCount": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 41 + "propertyOrder": 42 }, "UnusedLocalVar": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 79 + "propertyOrder": 80 }, "TabForAligning": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 71 + "propertyOrder": 72 }, "MethodName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 43 + "propertyOrder": 44 }, "RightCurly": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 63 + "propertyOrder": 64 }, "AvoidTernaryOperator": { "$ref": "#/definitions/ExcludeFilterList", @@ -189,7 +185,7 @@ }, "ParameterNumber": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 56 + "propertyOrder": 57 }, "ArrowFunction": { "$ref": "#/definitions/ExcludeFilterList", @@ -197,39 +193,47 @@ }, "MethodLength": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 42 + "propertyOrder": 43 }, "ConditionalCompilation": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 14 + "propertyOrder": 15 }, "EmptyLines": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 22 + "propertyOrder": 23 }, "MemberName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 40 + "propertyOrder": 41 }, "ERegLiteral": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 20 + "propertyOrder": 21 }, "RedundantModifier": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 60 + "propertyOrder": 61 }, "Type": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 74 + "propertyOrder": 75 }, "TypeName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 76 + "propertyOrder": 77 }, "Indentation": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 31 + "propertyOrder": 32 + }, + "FileNameCase": { + "$ref": "#/definitions/ExcludeFilterList", + "propertyOrder": 28 + }, + "CommentedOutCode": { + "$ref": "#/definitions/ExcludeFilterList", + "propertyOrder": 14 }, "version": { "maximum": 1, @@ -238,35 +242,39 @@ }, "Return": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 61 + "propertyOrder": 62 }, "SimplifyBooleanReturn": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 67 + "propertyOrder": 68 }, "TODOComment": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 70 + "propertyOrder": 71 + }, + "VarTypeHint": { + "$ref": "#/definitions/ExcludeFilterList", + "propertyOrder": 81 }, "NestedControlFlow": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 48 + "propertyOrder": 49 }, "OperatorWhitespace": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 53 + "propertyOrder": 54 }, "Spacing": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 68 + "propertyOrder": 69 }, "IndentationCharacter": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 32 + "propertyOrder": 33 }, "MagicNumber": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 39 + "propertyOrder": 40 }, "ArrayLiteral": { "$ref": "#/definitions/ExcludeFilterList", @@ -274,19 +282,19 @@ }, "TrailingWhitespace": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 73 + "propertyOrder": 74 }, "VariableInitialisation": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 80 + "propertyOrder": 82 }, "LineLength": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 36 + "propertyOrder": 37 }, "ListenerName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 37 + "propertyOrder": 38 }, "FileLength": { "$ref": "#/definitions/ExcludeFilterList", @@ -294,15 +302,15 @@ }, "CyclomaticComplexity": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 16 + "propertyOrder": 17 }, "StringLiteral": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 69 + "propertyOrder": 70 }, "Trace": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 72 + "propertyOrder": 73 }, "ArrayAccess": { "$ref": "#/definitions/ExcludeFilterList", @@ -310,19 +318,19 @@ }, "PublicAccessor": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 57 + "propertyOrder": 58 }, "DocCommentStyle": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 18 + "propertyOrder": 19 }, "InnerAssignment": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 33 + "propertyOrder": 34 }, "RedundantAccessMeta": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 58 + "propertyOrder": 59 }, "CodeSimilarity": { "$ref": "#/definitions/ExcludeFilterList", @@ -330,19 +338,19 @@ }, "OperatorWrap": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 54 + "propertyOrder": 55 }, "TypeDocComment": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 75 + "propertyOrder": 76 }, "LeftCurly": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 35 + "propertyOrder": 36 }, "ModifierOrder": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 44 + "propertyOrder": 45 }, "FieldDocComment": { "$ref": "#/definitions/ExcludeFilterList", diff --git a/resources/checkstyle-schema.json b/resources/checkstyle-schema.json index 77b6bb00..0cfe233f 100644 --- a/resources/checkstyle-schema.json +++ b/resources/checkstyle-schema.json @@ -335,7 +335,9 @@ "MACRO", "DYNAMIC", "EXTERN", - "FINAL" + "FINAL", + "ABSTRACT", + "OVERLOAD" ] }, "type": "array", @@ -1746,43 +1748,6 @@ }, "type": "object" }, - "EnforceVarTypeHintCheck": { - "description": "Checks if all variables have type hint.", - "additionalProperties": false, - "properties": { - "type": { - "description": "Checks if all variables have type hint.", - "type": "string", - "enum": [ - "EnforceVarTypeHint" - ] - }, - "props": { - "description": "Checks if all variables have type hint.", - "additionalProperties": false, - "properties": { - "ignoreEnumAbstractValues": { - "description": "ignores fields inside abstract enums", - "type": "boolean", - "propertyOrder": 0 - }, - "severity": { - "description": "sets gravity of reported violations:\n\t- IGNORE = do not report violations, violations do not appear anywhere in output\n\t- INFO = all violations have info / lowest priority\n\t- WARNING = all violations have warning / medium priority\n\t- ERROR = all violations have error / highest priority", - "type": "string", - "enum": [ - "INFO", - "WARNING", - "ERROR", - "IGNORE" - ], - "propertyOrder": 1 - } - }, - "type": "object" - } - }, - "type": "object" - }, "SimplifyBooleanReturnCheck": { "description": "Checks for over-complicated boolean return statements.", "additionalProperties": false, @@ -2159,6 +2124,38 @@ }, "type": "object" }, + "FileNameCaseCheck": { + "description": "Checks that file names match the case of their module name.", + "additionalProperties": false, + "properties": { + "type": { + "description": "Checks that file names match the case of their module name.", + "type": "string", + "enum": [ + "FileNameCase" + ] + }, + "props": { + "description": "Checks that file names match the case of their module name.", + "additionalProperties": false, + "properties": { + "severity": { + "description": "sets gravity of reported violations:\n\t- IGNORE = do not report violations, violations do not appear anywhere in output\n\t- INFO = all violations have info / lowest priority\n\t- WARNING = all violations have warning / medium priority\n\t- ERROR = all violations have error / highest priority", + "type": "string", + "enum": [ + "INFO", + "WARNING", + "ERROR", + "IGNORE" + ], + "propertyOrder": 0 + } + }, + "type": "object" + } + }, + "type": "object" + }, "ListenerNameCheck": { "description": "Checks the naming conventions of event listener functions specified using `listeners` property.", "additionalProperties": false, @@ -2241,6 +2238,38 @@ }, "type": "object" }, + "CommentedOutCodeCheck": { + "description": "Checks sections of commented out code", + "additionalProperties": false, + "properties": { + "type": { + "description": "Checks sections of commented out code", + "type": "string", + "enum": [ + "CommentedOutCode" + ] + }, + "props": { + "description": "Checks sections of commented out code", + "additionalProperties": false, + "properties": { + "severity": { + "description": "sets gravity of reported violations:\n\t- IGNORE = do not report violations, violations do not appear anywhere in output\n\t- INFO = all violations have info / lowest priority\n\t- WARNING = all violations have warning / medium priority\n\t- ERROR = all violations have error / highest priority", + "type": "string", + "enum": [ + "INFO", + "WARNING", + "ERROR", + "IGNORE" + ], + "propertyOrder": 0 + } + }, + "type": "object" + } + }, + "type": "object" + }, "MultipleVariableDeclarationsCheck": { "description": "Checks that each variable declaration is in its own statement and on its own line.", "additionalProperties": false, @@ -3021,42 +3050,38 @@ }, "UnusedImport": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 78 + "propertyOrder": 79 }, "Dynamic": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 19 + "propertyOrder": 20 }, "Final": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 28 + "propertyOrder": 29 }, "MultipleStringLiterals": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 45 - }, - "EnforceVarTypeHint": { - "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 24 + "propertyOrder": 46 }, "NeedBraces": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 47 + "propertyOrder": 48 }, "SeparatorWhitespace": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 64 + "propertyOrder": 65 }, "all": { "$ref": "#/definitions/ExcludeFilterList" }, "LocalVariableName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 38 + "propertyOrder": 39 }, "NestedForDepth": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 49 + "propertyOrder": 50 }, "Anonymous": { "$ref": "#/definitions/ExcludeFilterList", @@ -3064,11 +3089,11 @@ }, "MultipleVariableDeclarations": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 46 + "propertyOrder": 47 }, "NestedTryDepth": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 51 + "propertyOrder": 52 }, "BlockBreakingConditional": { "$ref": "#/definitions/ExcludeFilterList", @@ -3080,7 +3105,7 @@ }, "EmptyBlock": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 21 + "propertyOrder": 22 }, "ExtendedEmptyLines": { "$ref": "#/definitions/ExcludeFilterList", @@ -3088,47 +3113,47 @@ }, "ReturnCount": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 62 + "propertyOrder": 63 }, "DefaultComesLast": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 17 + "propertyOrder": 18 }, "HexadecimalLiteral": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 29 + "propertyOrder": 30 }, "WhitespaceAfter": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 81 + "propertyOrder": 83 }, "ConstantName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 15 + "propertyOrder": 16 }, "EmptyPackage": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 23 + "propertyOrder": 24 }, "Interface": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 34 + "propertyOrder": 35 }, "WhitespaceAround": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 82 + "propertyOrder": 84 }, "NestedIfDepth": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 50 + "propertyOrder": 51 }, "ParameterName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 55 + "propertyOrder": 56 }, "NullableParameter": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 52 + "propertyOrder": 53 }, "AvoidStarImport": { "$ref": "#/definitions/ExcludeFilterList", @@ -3136,7 +3161,7 @@ }, "SeparatorWrap": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 65 + "propertyOrder": 66 }, "AvoidIdentifier": { "$ref": "#/definitions/ExcludeFilterList", @@ -3144,19 +3169,19 @@ }, "RedundantAllowMeta": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 59 + "propertyOrder": 60 }, "HiddenField": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 30 + "propertyOrder": 31 }, "UnnecessaryConstructor": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 77 + "propertyOrder": 78 }, "SimplifyBooleanExpression": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 66 + "propertyOrder": 67 }, "path": { "description": "filters excludes relative to\n\t- RELATIVE_TO_PROJECT = use project root\n\t- RELATIVE_TO_SOURCE = use path(s) specified via \"-s \" command line switches", @@ -3168,23 +3193,23 @@ }, "MethodCount": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 41 + "propertyOrder": 42 }, "UnusedLocalVar": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 79 + "propertyOrder": 80 }, "TabForAligning": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 71 + "propertyOrder": 72 }, "MethodName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 43 + "propertyOrder": 44 }, "RightCurly": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 63 + "propertyOrder": 64 }, "AvoidTernaryOperator": { "$ref": "#/definitions/ExcludeFilterList", @@ -3192,7 +3217,7 @@ }, "ParameterNumber": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 56 + "propertyOrder": 57 }, "ArrowFunction": { "$ref": "#/definitions/ExcludeFilterList", @@ -3200,39 +3225,47 @@ }, "MethodLength": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 42 + "propertyOrder": 43 }, "ConditionalCompilation": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 14 + "propertyOrder": 15 }, "EmptyLines": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 22 + "propertyOrder": 23 }, "MemberName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 40 + "propertyOrder": 41 }, "ERegLiteral": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 20 + "propertyOrder": 21 }, "RedundantModifier": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 60 + "propertyOrder": 61 }, "Type": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 74 + "propertyOrder": 75 }, "TypeName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 76 + "propertyOrder": 77 }, "Indentation": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 31 + "propertyOrder": 32 + }, + "FileNameCase": { + "$ref": "#/definitions/ExcludeFilterList", + "propertyOrder": 28 + }, + "CommentedOutCode": { + "$ref": "#/definitions/ExcludeFilterList", + "propertyOrder": 14 }, "version": { "maximum": 1, @@ -3241,35 +3274,39 @@ }, "Return": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 61 + "propertyOrder": 62 }, "SimplifyBooleanReturn": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 67 + "propertyOrder": 68 }, "TODOComment": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 70 + "propertyOrder": 71 + }, + "VarTypeHint": { + "$ref": "#/definitions/ExcludeFilterList", + "propertyOrder": 81 }, "NestedControlFlow": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 48 + "propertyOrder": 49 }, "OperatorWhitespace": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 53 + "propertyOrder": 54 }, "Spacing": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 68 + "propertyOrder": 69 }, "IndentationCharacter": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 32 + "propertyOrder": 33 }, "MagicNumber": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 39 + "propertyOrder": 40 }, "ArrayLiteral": { "$ref": "#/definitions/ExcludeFilterList", @@ -3277,19 +3314,19 @@ }, "TrailingWhitespace": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 73 + "propertyOrder": 74 }, "VariableInitialisation": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 80 + "propertyOrder": 82 }, "LineLength": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 36 + "propertyOrder": 37 }, "ListenerName": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 37 + "propertyOrder": 38 }, "FileLength": { "$ref": "#/definitions/ExcludeFilterList", @@ -3297,15 +3334,15 @@ }, "CyclomaticComplexity": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 16 + "propertyOrder": 17 }, "StringLiteral": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 69 + "propertyOrder": 70 }, "Trace": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 72 + "propertyOrder": 73 }, "ArrayAccess": { "$ref": "#/definitions/ExcludeFilterList", @@ -3313,19 +3350,19 @@ }, "PublicAccessor": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 57 + "propertyOrder": 58 }, "DocCommentStyle": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 18 + "propertyOrder": 19 }, "InnerAssignment": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 33 + "propertyOrder": 34 }, "RedundantAccessMeta": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 58 + "propertyOrder": 59 }, "CodeSimilarity": { "$ref": "#/definitions/ExcludeFilterList", @@ -3333,19 +3370,19 @@ }, "OperatorWrap": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 54 + "propertyOrder": 55 }, "TypeDocComment": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 75 + "propertyOrder": 76 }, "LeftCurly": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 35 + "propertyOrder": 36 }, "ModifierOrder": { "$ref": "#/definitions/ExcludeFilterList", - "propertyOrder": 44 + "propertyOrder": 45 }, "FieldDocComment": { "$ref": "#/definitions/ExcludeFilterList", @@ -3470,6 +3507,53 @@ }, "type": "object" }, + "VarTypeHintCheck": { + "description": "Checks type hints of variables.", + "additionalProperties": false, + "properties": { + "type": { + "description": "Checks type hints of variables.", + "type": "string", + "enum": [ + "VarTypeHint" + ] + }, + "props": { + "description": "Checks type hints of variables.", + "additionalProperties": false, + "properties": { + "ignoreEnumAbstractValues": { + "description": "ignores fields inside abstract enums", + "type": "boolean", + "propertyOrder": 1 + }, + "typeHintPolicy": { + "description": "policy for type hints on var and final", + "type": "string", + "enum": [ + "enforce_all", + "infer_new_or_const", + "infer_all" + ], + "propertyOrder": 0 + }, + "severity": { + "description": "sets gravity of reported violations:\n\t- IGNORE = do not report violations, violations do not appear anywhere in output\n\t- INFO = all violations have info / lowest priority\n\t- WARNING = all violations have warning / medium priority\n\t- ERROR = all violations have error / highest priority", + "type": "string", + "enum": [ + "INFO", + "WARNING", + "ERROR", + "IGNORE" + ], + "propertyOrder": 2 + } + }, + "type": "object" + } + }, + "type": "object" + }, "CodeSimilarityCheck": { "description": "Checks for identical or similar code.", "additionalProperties": false, @@ -4262,6 +4346,9 @@ { "$ref": "#/definitions/CodeSimilarityCheck" }, + { + "$ref": "#/definitions/CommentedOutCodeCheck" + }, { "$ref": "#/definitions/ConditionalCompilationCheck" }, @@ -4292,9 +4379,6 @@ { "$ref": "#/definitions/EmptyPackageCheck" }, - { - "$ref": "#/definitions/EnforceVarTypeHintCheck" - }, { "$ref": "#/definitions/ExtendedEmptyLinesCheck" }, @@ -4304,6 +4388,9 @@ { "$ref": "#/definitions/FileLengthCheck" }, + { + "$ref": "#/definitions/FileNameCaseCheck" + }, { "$ref": "#/definitions/FinalCheck" }, @@ -4460,6 +4547,9 @@ { "$ref": "#/definitions/UnusedLocalVarCheck" }, + { + "$ref": "#/definitions/VarTypeHintCheck" + }, { "$ref": "#/definitions/VariableInitialisationCheck" }, diff --git a/resources/default-config.json b/resources/default-config.json index ed234eb3..2a18ca4f 100644 --- a/resources/default-config.json +++ b/resources/default-config.json @@ -61,6 +61,10 @@ "thresholdSimilar": 120 } }, + { + "type": "CommentedOutCode", + "props": {} + }, { "type": "ConditionalCompilation", "props": { @@ -149,12 +153,6 @@ "enforceEmptyPackage": false } }, - { - "type": "EnforceVarTypeHint", - "props": { - "ignoreEnumAbstractValues": true - } - }, { "type": "ExtendedEmptyLines", "props": { @@ -182,11 +180,11 @@ "modifier": "PUBLIC", "requireParams": true, "requireReturn": true, + "ignoreOverride": true, "excludeNames": [ "new", "toString" - ], - "ignoreOverride": true + ] } }, { @@ -196,6 +194,10 @@ "ignoreEmptyLines": true } }, + { + "type": "FileNameCase", + "props": {} + }, { "type": "Final", "props": {} @@ -219,9 +221,9 @@ "props": { "character": "tab", "ignoreConditionals": false, + "conditionalPolicy": "aligned", "ignoreComments": true, - "wrapPolicy": "larger", - "conditionalPolicy": "aligned" + "wrapPolicy": "larger" } }, { @@ -352,9 +354,9 @@ { "type": "MultipleStringLiterals", "props": { - "ignore": "^\\s+$", "allowDuplicates": 2, - "minLength": 2 + "minLength": 2, + "ignore": "^\\s+$" } }, { @@ -424,7 +426,6 @@ { "type": "OperatorWrap", "props": { - "option": "eol", "tokens": [ "=", "+", @@ -461,7 +462,8 @@ "=>", "++", "--" - ] + ], + "option": "eol" } }, { @@ -544,17 +546,17 @@ "props": { "dotPolicy": "none", "commaPolicy": "after", - "semicolonPolicy": "after", - "allowTrailingComma": false + "allowTrailingComma": false, + "semicolonPolicy": "after" } }, { "type": "SeparatorWrap", "props": { - "option": "eol", "tokens": [ "," - ] + ], + "option": "eol" } }, { @@ -568,13 +570,13 @@ { "type": "Spacing", "props": { + "spaceAroundBinop": true, + "noSpaceAroundUnop": true, "spaceIfCondition": "should", "spaceForLoop": "should", "spaceWhileLoop": "should", "spaceSwitchCase": "should", "spaceCatch": "should", - "spaceAroundBinop": true, - "noSpaceAroundUnop": true, "ignoreRangeOperator": true } }, @@ -646,6 +648,13 @@ "type": "UnusedLocalVar", "props": {} }, + { + "type": "VarTypeHint", + "props": { + "typeHintPolicy": "infer_new_or_const", + "ignoreEnumAbstractValues": true + } + }, { "type": "VariableInitialisation", "props": { diff --git a/schema/CheckstyleSchemaGenerator.hx b/schema/CheckstyleSchemaGenerator.hx index 1a9b2f79..777533c1 100644 --- a/schema/CheckstyleSchemaGenerator.hx +++ b/schema/CheckstyleSchemaGenerator.hx @@ -1,11 +1,11 @@ #if macro import haxe.DynamicAccess; +import haxe.ds.ArraySort; +import haxe.io.Path; import haxe.macro.Context; import haxe.macro.Expr; import haxe.macro.Type; import sys.FileSystem; -import haxe.io.Path; -import haxe.ds.ArraySort; using StringTools; @@ -131,14 +131,15 @@ class CheckstyleSchemaGenerator { var doc:StructInfo = {name: name, doc: getDescMeta(cl.meta)}; var props = SchemaUtils.makeObject(SchemaUtils.makeObjectDecl(classFields, null, -1, pos), doc, [], -1, pos); - var checkName:Array = [macro '$typeName']; + var checkName:Array = [macro $v{typeName}]; var typeExpr:Expr = macro $a{checkName}; var type = SchemaUtils.makeEnum(typeExpr, doc, -1, pos); var checkFields:Array = [{field: "type", expr: type}, {field: "props", expr: props}]; var classExpr:Expr = SchemaUtils.makeObject(SchemaUtils.makeObjectDecl(checkFields, null, -1, pos), doc, [], -1, pos); refs[name] = classExpr; } - return SchemaUtils.makeObjectDecl([{field: DollarName.DollarRef, expr: macro '#/definitions/${name}'}], null, order, pos); + var defName:String = '#/definitions/${name}'; + return SchemaUtils.makeObjectDecl([{field: DollarName.DollarRef, expr: macro $v{defName}}], null, order, pos); default: } default: diff --git a/schema/DollarName.hx b/schema/DollarName.hx index 97321a90..22e96547 100644 --- a/schema/DollarName.hx +++ b/schema/DollarName.hx @@ -1,11 +1,4 @@ -#if haxe4 enum abstract DollarName(String) to String { var DollarSchema = "$schema"; var DollarRef = "$ref"; -} -#else -@:enum abstract DollarName(String) to String { - var DollarSchema = "@$__hx__$schema"; - var DollarRef = "@$__hx__$ref"; -} -#end \ No newline at end of file +} \ No newline at end of file diff --git a/schema/JsonSchemaGenerator.hx b/schema/JsonSchemaGenerator.hx index 8ff3dde7..dd2cef97 100644 --- a/schema/JsonSchemaGenerator.hx +++ b/schema/JsonSchemaGenerator.hx @@ -4,8 +4,8 @@ import haxe.macro.Context; import haxe.macro.Expr; import haxe.macro.Type; -using haxe.macro.Tools; using StringTools; +using haxe.macro.Tools; typedef ExtendedFieldsCB = Array -> String -> Position -> DynamicAccess -> Void; #end @@ -33,7 +33,7 @@ class JsonSchemaGenerator { fields.push({field: "definitions", expr: definitions}); fields.push({field: DollarName.DollarSchema, expr: macro "http://json-schema.org/schema#"}); if (id != null) { - fields.push({field: "id", expr: macro '$id'}); + fields.push({field: "id", expr: macro $v{id}}); } default: } @@ -84,7 +84,8 @@ class JsonSchemaGenerator { var schema = genSchema(dt.type.applyTypeParameters(dt.params, params), dt.name, dt.pos, doc, refs, -1, extendCB); refs[dt.name] = schema; } - return SchemaUtils.makeObjectDecl([{field: DollarName.DollarRef, expr: macro '#/definitions/${dt.name}'}], structInfo, order, pos); + var name:String = '#/definitions/${dt.name}'; + return SchemaUtils.makeObjectDecl([{field: DollarName.DollarRef, expr: macro $v{name}}], structInfo, order, pos); } case TInst(_.get() => cl, params): diff --git a/schema/ObjectDeclField.hx b/schema/ObjectDeclField.hx index 141bbbb4..4a037e83 100644 --- a/schema/ObjectDeclField.hx +++ b/schema/ObjectDeclField.hx @@ -7,6 +7,6 @@ typedef ObjectDeclField = { var expr:Expr; } #else -typedef ObjectDeclField = haxe.macro.ObjectField; +typedef ObjectDeclField = haxe.macro.Expr.ObjectField; #end #end \ No newline at end of file diff --git a/src/checkstyle/CheckMessage.hx b/src/checkstyle/CheckMessage.hx deleted file mode 100644 index ff4549e5..00000000 --- a/src/checkstyle/CheckMessage.hx +++ /dev/null @@ -1,18 +0,0 @@ -package checkstyle; - -import checkstyle.checks.Category; - -typedef CheckMessage = { - var fileName:String; - var message:String; - var code:String; - var desc:String; - var startLine:Int; - var endLine:Int; - var startColumn:Int; - var endColumn:Int; - var severity:SeverityLevel; - var moduleName:String; - var categories:Array; - var points:Int; -} \ No newline at end of file diff --git a/src/checkstyle/Checker.hx b/src/checkstyle/Checker.hx index 6ec1be3d..87cb65ac 100644 --- a/src/checkstyle/Checker.hx +++ b/src/checkstyle/Checker.hx @@ -1,6 +1,7 @@ package checkstyle; import checkstyle.checks.Check; +import checkstyle.checks.coding.CodeSimilarityCheck; import checkstyle.config.ExcludeManager; import checkstyle.config.ExcludeRange; import checkstyle.reporter.ReporterManager; @@ -21,6 +22,7 @@ class Checker { public var defineCombinations:Array>; public var linesIdx:Array; public var lineSeparator:String; + public var verbose:Bool; var tokenTree:TokenTree; var allowFailingAST:Bool; @@ -33,6 +35,7 @@ class Checker { baseDefines = []; defineCombinations = []; linesIdx = []; + verbose = false; this.allowFailingAST = allowFailingAST; } @@ -175,6 +178,7 @@ class Checker { advanceFrame = function() hxt.advance_frame(); #end + ReporterManager.INSTANCE.addDelayedMessageCallback(CodeSimilarityCheck.delayedMessagesCallback); ReporterManager.INSTANCE.start(); for (checkFile in files) { loadFileContent(checkFile); @@ -199,14 +203,13 @@ class Checker { public function createContext(checkFile:CheckFile):Bool { file = checkFile; - ReporterManager.INSTANCE.fileStart(file); + ReporterManager.INSTANCE.addFile(file); try { findLineSeparator(); makeLines(); makePosIndices(); makeTokens(); makeASTs(); - // if (asts.length <= 0) return false; getTokenTree(); excludesRanges = ExcludeManager.INSTANCE.getPosExcludes(this); } @@ -234,10 +237,9 @@ class Checker { } ReporterManager.INSTANCE.addMessages(messages); } - ReporterManager.INSTANCE.fileFinish(file); } - function runCheck(check:Check):Array { + function runCheck(check:Check):Array { try { if (ExcludeManager.isExcludedFromCheck(file.name, check.getModuleName())) return []; return check.run(this); diff --git a/src/checkstyle/CheckerThread.hx b/src/checkstyle/CheckerThread.hx index 30bffe73..8b06c633 100644 --- a/src/checkstyle/CheckerThread.hx +++ b/src/checkstyle/CheckerThread.hx @@ -1,19 +1,9 @@ package checkstyle; -#if ((haxe_ver >= 4.0) && (neko || macro || eval || cpp || hl || java)) -import sys.thread.Thread; -#elseif neko -import neko.vm.Thread; -#elseif cpp -import cpp.vm.Thread; -#elseif java -import java.vm.Thread; -#else -import checkstyle.utils.Thread; -#end import checkstyle.checks.Check; import checkstyle.config.ExcludeManager; import checkstyle.reporter.ReporterManager; +import checkstyle.utils.Thread; class CheckerThread { static inline var SLEEP_TIME:Float = 0.1; @@ -101,10 +91,9 @@ class CheckerThread { } ReporterManager.INSTANCE.addMessages(messages); } - ReporterManager.INSTANCE.fileFinish(checker.file); } - function runCheck(check:Check, checker:Checker):Array { + function runCheck(check:Check, checker:Checker):Array { try { if (ExcludeManager.isExcludedFromCheck(checker.file.name, check.getModuleName())) return []; return check.run(checker); diff --git a/src/checkstyle/ChecksInfo.hx b/src/checkstyle/ChecksInfo.hx index 395bc632..f2b61251 100644 --- a/src/checkstyle/ChecksInfo.hx +++ b/src/checkstyle/ChecksInfo.hx @@ -8,7 +8,6 @@ class ChecksInfo { public function new() { checkInfos = new Map(); - CompileTime.importPackage("checkstyle.checks"); var checksClasses = CompileTime.getAllClasses(Check); for (cl in checksClasses) { diff --git a/src/checkstyle/Main.hx b/src/checkstyle/Main.hx index 541b0a2a..ca863c2f 100644 --- a/src/checkstyle/Main.hx +++ b/src/checkstyle/Main.hx @@ -71,6 +71,8 @@ class Main { }, @doc("Set reporter style (XSLT)") ["-x", "--xslt"] => function(style:String) STYLE = style, + @doc("verbose logging") + ["-v", "--verbose"] => function() checker.verbose = true, @doc("Sets the number of checker threads") ["--checkerthreads"] => function(num:Int) configParser.overrideCheckerThreads = num, @doc("Generate a default config and exit") diff --git a/src/checkstyle/Message.hx b/src/checkstyle/Message.hx new file mode 100644 index 00000000..133e4278 --- /dev/null +++ b/src/checkstyle/Message.hx @@ -0,0 +1,29 @@ +package checkstyle; + +import checkstyle.checks.Category; + +typedef Message = MessageLocation & { + var message:String; + @:optional var code:String; + var desc:String; + var severity:SeverityLevel; + var moduleName:String; + var categories:Array; + var points:Int; + var related:Array; +}; + +typedef MessageLocation = { + var fileName:String; + var range:MessageRange; +}; + +typedef MessageRange = { + var start:MessagePosition; + var end:MessagePosition; +}; + +typedef MessagePosition = { + var line:Int; + var column:Int; +}; \ No newline at end of file diff --git a/src/checkstyle/ParserQueue.hx b/src/checkstyle/ParserQueue.hx index 1b84edd4..3e52ec99 100644 --- a/src/checkstyle/ParserQueue.hx +++ b/src/checkstyle/ParserQueue.hx @@ -1,21 +1,7 @@ package checkstyle; -#if ((haxe_ver >= 4.0) && (neko || macro || eval || cpp || hl || java)) -import sys.thread.Mutex; -import sys.thread.Thread; -#elseif neko -import neko.vm.Mutex; -import neko.vm.Thread; -#elseif cpp -import cpp.vm.Mutex; -import cpp.vm.Thread; -#elseif java -import java.vm.Mutex; -import java.vm.Thread; -#else import checkstyle.utils.Mutex; import checkstyle.utils.Thread; -#end class ParserQueue { static inline var SLEEP_TIME:Float = 0.1; @@ -51,6 +37,7 @@ class ParserQueue { var checker:Checker = new Checker(); checker.baseDefines = templateChecker.baseDefines; checker.defineCombinations = templateChecker.defineCombinations; + checker.verbose = templateChecker.verbose; checker.loadFileContent(file); if (!checker.createContext(file)) { checker.unloadFileContent(file); diff --git a/src/checkstyle/SeverityLevel.hx b/src/checkstyle/SeverityLevel.hx index 72a15a00..6502b1f9 100644 --- a/src/checkstyle/SeverityLevel.hx +++ b/src/checkstyle/SeverityLevel.hx @@ -7,8 +7,7 @@ package checkstyle; - WARNING = all violations have warning / medium priority - ERROR = all violations have error / highest priority **/ -@:enum -abstract SeverityLevel(String) from String { +enum abstract SeverityLevel(String) from String { var INFO = "INFO"; var WARNING = "WARNING"; var ERROR = "ERROR"; diff --git a/src/checkstyle/checks/Category.hx b/src/checkstyle/checks/Category.hx index 856a29a7..ee366d27 100644 --- a/src/checkstyle/checks/Category.hx +++ b/src/checkstyle/checks/Category.hx @@ -1,7 +1,6 @@ package checkstyle.checks; -@:enum -abstract Category(String) { +enum abstract Category(String) { var BUG_RISK = "Bug Risk"; var CLARITY = "Clarity"; var COMPLEXITY = "Complexity"; diff --git a/src/checkstyle/checks/Check.hx b/src/checkstyle/checks/Check.hx index 782e5f6e..334e8eb5 100644 --- a/src/checkstyle/checks/Check.hx +++ b/src/checkstyle/checks/Check.hx @@ -1,6 +1,7 @@ package checkstyle.checks; import checkstyle.config.ExcludeRange; +import haxe.Timer; class Check { public var severity:SeverityLevel; @@ -9,7 +10,7 @@ class Check { public var points:Int; public var desc:String; - var messages:Array; + var messages:Array; var moduleName:String; var checker:Checker; @@ -30,34 +31,40 @@ class Check { Reflect.setField(this, name, value); } - public function run(checker:Checker):Array { + public function run(checker:Checker):Array { + var startTime = Timer.stamp(); + if (checker.verbose) { + Sys.println('${checker.file.name} - [${getModuleName()}] start'); + } reset(); this.checker = checker; if (severity != SeverityLevel.IGNORE) { try { actualRun(); } - catch (e:String) { + catch (e:Exception) { ErrorUtils.handleException(e, checker.file, getModuleName()); } } + var endTime = Timer.stamp(); + if (checker.verbose) { + Sys.println('${checker.file.name} - [${getModuleName()}] done. (${(endTime - startTime) * 1000}ms)'); + } return messages; } function actualRun() { - throw "Unimplemented"; + throw new Exception("Unimplemented"); } - public function logPos(msg:String, pos:Position, ?code:String, ?sev:SeverityLevel) { - logRange(msg, pos.min, pos.max, code, sev); + public function logPos(msg:String, pos:Position, ?code:String, ?sev:SeverityLevel):Message { + return logRange(msg, pos.min, pos.max, code, sev); } - public function logRange(msg:String, startPos:Int, endPos:Int, ?code:String, ?sev:SeverityLevel) { - var lpStart = checker.getLinePos(startPos); - var lpEnd = checker.getLinePos(endPos); - var startColumn:Int = offsetToColumn(lpStart); - var endColumn:Int = offsetToColumn(lpEnd); - log(msg, lpStart.line + 1, startColumn, lpEnd.line + 1, endColumn, code, sev); + public function logRange(msg:String, startPos:Int, endPos:Int, ?code:String, ?sev:SeverityLevel):Message { + var message:Message = createRangeMessage(msg, startPos, endPos, code, sev); + messages.push(message); + return message; } function offsetToColumn(lp:LinePos):Int { @@ -66,21 +73,66 @@ class Check { return line.getString(0, lp.ofs).length; } - public function log(msg:String, startLine:Int, startColumn:Int, endLine:Int, endColumn:Int, ?code:String, ?sev:SeverityLevel) { + public function log(msg:String, startLine:Int, startColumn:Int, endLine:Int, endColumn:Int, ?code:String, ?sev:SeverityLevel):Message { + var message:Message = createMessage(msg, startLine, startColumn, endLine, endColumn, code, sev); + messages.push(message); + return message; + } + + public function createRangeMessage(msg:String, startPos:Int, endPos:Int, ?code:String, ?sev:SeverityLevel):Message { + var lpStart = checker.getLinePos(startPos); + var lpEnd = checker.getLinePos(endPos); + var startColumn:Int = offsetToColumn(lpStart); + var endColumn:Int = offsetToColumn(lpEnd); + return createMessage(msg, lpStart.line + 1, startColumn, lpEnd.line + 1, endColumn, code, sev); + } + + function createMessage(msg:String, startLine:Int, startColumn:Int, endLine:Int, endColumn:Int, ?code:String, ?sev:SeverityLevel):Message { if (sev == null) sev = severity; - messages.push({ + return { fileName: checker.file.name, message: msg, code: code, desc: desc, - startLine: startLine, - endLine: endLine, - startColumn: startColumn, - endColumn: endColumn, severity: sev, moduleName: getModuleName(), categories: categories, - points: points + points: points, + range: { + start: { + line: startLine, + column: startColumn + }, + end: { + line: endLine, + column: endColumn + } + }, + related: [] + } + } + + public function addRelatedRange(message:Message, msg:String, startPos:Int, endPos:Int) { + var lpStart = checker.getLinePos(startPos); + var lpEnd = checker.getLinePos(endPos); + var startColumn:Int = offsetToColumn(lpStart); + var endColumn:Int = offsetToColumn(lpEnd); + addRelatedMessage(message, lpStart.line + 1, startColumn, lpEnd.line + 1, endColumn); + } + + public function addRelatedMessage(message:Message, startLine:Int, startColumn:Int, endLine:Int, endColumn:Int) { + message.related.push({ + fileName: checker.file.name, + range: { + start: { + line: startLine, + column: startColumn + }, + end: { + line: endLine, + column: endColumn + } + } }); } @@ -145,13 +197,13 @@ class Check { case EEnum(d): if ((pos <= td.pos.max) && (pos >= td.pos.min)) return d.flags.contains(EExtern); case ETypedef(d): - if ((pos <= td.pos.max) && (pos >= td.pos.min)) return d.flags.contains(EExtern); + if ((pos <= td.pos.max) && (pos >= td.pos.min)) return d.flags.contains(TDExtern); switch (d.data) { case TAnonymous(fields): for (field in fields) { if (pos > field.pos.max) continue; if (pos < field.pos.min) continue; - return d.flags.contains(EExtern); + return d.flags.contains(TDExtern); } default: } diff --git a/src/checkstyle/checks/block/BlockBreakingConditionalCheck.hx b/src/checkstyle/checks/block/BlockBreakingConditionalCheck.hx index c24a0979..f835c1e3 100644 --- a/src/checkstyle/checks/block/BlockBreakingConditionalCheck.hx +++ b/src/checkstyle/checks/block/BlockBreakingConditionalCheck.hx @@ -12,7 +12,14 @@ class BlockBreakingConditionalCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var allBrs:Array = root.filter([BrOpen, BrClose], ALL); + var allBrs:Array = root.filterCallback(function(token:TokenTree, index:Int):FilterResult { + return switch (token.tok) { + case BrOpen | BrClose: + FoundGoDeeper; + default: + GoDeeper; + } + }); for (br in allBrs) { if (isPosSuppressed(br.pos)) continue; @@ -21,7 +28,7 @@ class BlockBreakingConditionalCheck extends Check { if (br.access().firstOf(BrClose).exists()) continue; logPos("Left curly has no matching right curly", br.pos); case BrClose: - if (br.access().parent().is(BrOpen).exists()) continue; + if (br.access().parent().matches(BrOpen).exists()) continue; logPos("Right curly has no matching left curly", br.pos); default: continue; diff --git a/src/checkstyle/checks/block/ConditionalCompilationCheck.hx b/src/checkstyle/checks/block/ConditionalCompilationCheck.hx index 44769880..8e5f49b1 100644 --- a/src/checkstyle/checks/block/ConditionalCompilationCheck.hx +++ b/src/checkstyle/checks/block/ConditionalCompilationCheck.hx @@ -29,7 +29,14 @@ class ConditionalCompilationCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - checkSharpIf(root.filter([Sharp("if")], ALL)); + checkSharpIf(root.filterCallback(function(token:TokenTree, index:Int):FilterResult { + return switch (token.tok) { + case Sharp("if"): + FoundGoDeeper; + default: + GoDeeper; + } + })); } function checkSharpIf(tokens:Array) { @@ -169,8 +176,7 @@ class ConditionalCompilationCheck extends Check { - startOfLine = #if, #else, #elseif and #end must start at beginning of line - aligned = indentation of #if, #else, #elseif and #end must match surrounding code **/ -@:enum -abstract ConditionalCompilationPolicy(String) { +enum abstract ConditionalCompilationPolicy(String) { var START_OF_LINE = "startOfLine"; var ALIGNED = "aligned"; } \ No newline at end of file diff --git a/src/checkstyle/checks/block/EmptyBlockCheck.hx b/src/checkstyle/checks/block/EmptyBlockCheck.hx index f1b823af..487bf397 100644 --- a/src/checkstyle/checks/block/EmptyBlockCheck.hx +++ b/src/checkstyle/checks/block/EmptyBlockCheck.hx @@ -59,7 +59,14 @@ class EmptyBlockCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var allBrOpen:Array = root.filter([BrOpen], ALL); + var allBrOpen:Array = root.filterCallback(function(token:TokenTree, index:Int):FilterResult { + return switch (token.tok) { + case BrOpen: + FoundGoDeeper; + default: + GoDeeper; + } + }); for (brOpen in allBrOpen) { if (isPosSuppressed(brOpen.pos)) continue; @@ -78,7 +85,7 @@ class EmptyBlockCheck extends Check { } function filterParentToken(token:TokenTree):Bool { - if ((token == null) || (token.tok == null)) return false; + if ((token == null) || (token.tok == Root)) return false; switch (token.tok) { case Kwd(KwdClass): return !hasToken(CLASS_DEF); @@ -128,7 +135,7 @@ class EmptyBlockCheck extends Check { return; } var lastChild:TokenTree = brOpen.getLastChild(); - if ((brOpen.children.length == 2) && lastChild.is(Semicolon)) { + if ((brOpen.children.length == 2) && lastChild.matches(Semicolon)) { logPos("Empty block should contain a comment or a statement", brOpen.getPos()); return; } @@ -140,7 +147,7 @@ class EmptyBlockCheck extends Check { return; } var lastChild:TokenTree = brOpen.getLastChild(); - if ((brOpen.children.length == 2) && lastChild.is(Semicolon)) { + if ((brOpen.children.length == 2) && lastChild.matches(Semicolon)) { logPos("Empty block should contain a statement", brOpen.getPos()); return; } @@ -163,21 +170,20 @@ class EmptyBlockCheck extends Check { if (brOpen.children.length <= 0) return; var lastChild:TokenTree = brOpen.getLastChild(); - if (brOpen.access().lastChild().is(Semicolon).exists()) { + if (brOpen.access().lastChild().matches(Semicolon).exists()) { if (brOpen.children.length > 2) return; } else { if (brOpen.children.length > 1) return; } - var brClose:TokenTree = brOpen.access().firstChild().is(BrClose).token; + var brClose:TokenTree = brOpen.access().firstChild().matches(BrClose).token; if (brClose == null) return; if (brOpen.pos.max != brClose.pos.min) logPos('Empty block should be written as "{}"', brOpen.getPos()); } } -@:enum -abstract EmptyBlockCheckToken(String) { +enum abstract EmptyBlockCheckToken(String) { var CLASS_DEF = "CLASS_DEF"; var ENUM_DEF = "ENUM_DEF"; var ABSTRACT_DEF = "ABSTRACT_DEF"; @@ -194,8 +200,7 @@ abstract EmptyBlockCheckToken(String) { var REIFICATION = "REIFICATION"; } -@:enum -abstract EmptyBlockCheckOption(String) { +enum abstract EmptyBlockCheckOption(String) { // allow empty blocks but enforce "{}" notation var EMPTY = "empty"; // empty blocks must contain something apart from whitespace (comment or statement) diff --git a/src/checkstyle/checks/block/LeftCurlyCheck.hx b/src/checkstyle/checks/block/LeftCurlyCheck.hx index 0318fb2a..da7bae32 100644 --- a/src/checkstyle/checks/block/LeftCurlyCheck.hx +++ b/src/checkstyle/checks/block/LeftCurlyCheck.hx @@ -72,21 +72,28 @@ class LeftCurlyCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var allBrOpen:Array = root.filter([BrOpen], ALL); + var allBrOpen:Array = root.filterCallback(function(token:TokenTree, index:Int):FilterResult { + return switch (token.tok) { + case BrOpen: + FoundGoDeeper; + default: + GoDeeper; + } + }); for (brOpen in allBrOpen) { if (isPosSuppressed(brOpen.pos)) continue; if (skipSingleLine(brOpen)) continue; var type:BrOpenType = TokenTreeCheckUtils.getBrOpenType(brOpen); switch (type) { - case BLOCK: - case TYPEDEFDECL: + case Block: + case TypedefDecl: if (!hasToken(TYPEDEF_DEF)) continue; - case OBJECTDECL: + case ObjectDecl: if (!hasToken(OBJECT_DECL)) continue; - case ANONTYPE: + case AnonType: if (!hasToken(ANON_TYPE)) continue; - case UNKNOWN: + case Unknown: } var parent:ParentToken = findParentToken(brOpen.parent); if (!parent.hasToken) continue; @@ -108,7 +115,7 @@ class LeftCurlyCheck extends Check { find effective parent token and check against configured tokens **/ function findParentToken(token:TokenTree):ParentToken { - if ((token == null) || (token.tok == null)) return {token: token, hasToken: false}; + if ((token == null) || (token.tok == Root)) return {token: token, hasToken: false}; switch (token.tok) { case Kwd(KwdClass): return {token: token, hasToken: hasToken(CLASS_DEF)}; @@ -159,22 +166,22 @@ class LeftCurlyCheck extends Check { } function findParentTokenDblDot(token:TokenTree):ParentToken { - if ((token == null) || (token.tok == null)) return {token: token, hasToken: false}; + if ((token == null) || (token.tok == Root)) return {token: token, hasToken: false}; var type:ColonType = TokenTreeCheckUtils.getColonType(token); switch (type) { - case SWITCH_CASE: + case SwitchCase: return {token: token, hasToken: hasToken(SWITCH)}; - case TYPE_HINT: + case TypeHint: return {token: token, hasToken: hasToken(TYPEDEF_DEF)}; - case TYPE_CHECK: + case TypeCheck: return {token: token, hasToken: hasToken(TYPEDEF_DEF)}; - case TERNARY: + case Ternary: return {token: token, hasToken: false}; - case OBJECT_LITERAL: + case ObjectLiteral: return {token: token, hasToken: hasToken(OBJECT_DECL)}; - case AT: + case At: return {token: token, hasToken: false}; - case UNKNOWN: + case Unknown: return {token: token, hasToken: false}; } } @@ -234,7 +241,7 @@ class LeftCurlyCheck extends Check { logErrorIf((option == NLOW) && !wrapped, "Left curly should be at EOL (previous expression is not split over multiple lines)", pos); logErrorIf((option != NL) && (option != NLOW), "Left curly unknown option ${option}", pos); } - catch (e:String) { + catch (e:Exception) { // one of the error messages fired -> do nothing } } @@ -242,7 +249,7 @@ class LeftCurlyCheck extends Check { function logErrorIf(condition:Bool, msg:String, pos:Position) { if (condition) { logPos(msg, pos); - throw "exit"; + throw new Exception("exit"); } } @@ -298,8 +305,7 @@ typedef ParentToken = { var hasToken:Bool; } -@:enum -abstract LeftCurlyCheckToken(String) { +enum abstract LeftCurlyCheckToken(String) { var CLASS_DEF = "CLASS_DEF"; var ENUM_DEF = "ENUM_DEF"; var ABSTRACT_DEF = "ABSTRACT_DEF"; @@ -318,8 +324,7 @@ abstract LeftCurlyCheckToken(String) { var ARRAY_COMPREHENSION = "ARRAY_COMPREHENSION"; } -@:enum -abstract LeftCurlyCheckOption(String) { +enum abstract LeftCurlyCheckOption(String) { var EOL = "eol"; var NL = "nl"; var NLOW = "nlow"; diff --git a/src/checkstyle/checks/block/NeedBracesCheck.hx b/src/checkstyle/checks/block/NeedBracesCheck.hx index 4300eadd..b3544d93 100644 --- a/src/checkstyle/checks/block/NeedBracesCheck.hx +++ b/src/checkstyle/checks/block/NeedBracesCheck.hx @@ -36,22 +36,34 @@ class NeedBracesCheck extends Check { } override function actualRun() { - var tokenList:Array = []; + var wantFunction = hasToken(FUNCTION); + var wantFor = hasToken(FOR); + var wantIf = hasToken(IF); + var wantWhile = hasToken(WHILE); + var wantDoWhile = hasToken(DO_WHILE); + var wantCatch = hasToken(CATCH); - if (hasToken(FUNCTION)) tokenList.push(Kwd(KwdFunction)); - if (hasToken(FOR)) tokenList.push(Kwd(KwdFor)); - if (hasToken(IF)) { - tokenList.push(Kwd(KwdIf)); - tokenList.push(Kwd(KwdElse)); - } - if (hasToken(WHILE)) tokenList.push(Kwd(KwdWhile)); - if (hasToken(DO_WHILE)) tokenList.push(Kwd(KwdDo)); - if (hasToken(CATCH)) tokenList.push(Kwd(KwdCatch)); - - if (tokenList.length <= 0) return; + if (!(wantFunction || wantFor || wantIf || wantWhile || wantDoWhile || wantCatch)) return; var root:TokenTree = checker.getTokenTree(); - var allTokens:Array = root.filter(tokenList, ALL); + var allTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdFunction) if (wantFunction): + FoundGoDeeper; + case Kwd(KwdFor) if (wantFor): + FoundGoDeeper; + case Kwd(KwdIf) | Kwd(KwdElse) if (wantIf): + FoundGoDeeper; + case Kwd(KwdWhile) if (wantWhile): + FoundGoDeeper; + case Kwd(KwdDo) if (wantDoWhile): + FoundGoDeeper; + case Kwd(KwdCatch) if (wantCatch): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (tok in allTokens) { if (isPosSuppressed(tok.pos)) continue; @@ -61,7 +73,7 @@ class NeedBracesCheck extends Check { case Kwd(KwdElse): var firstChild = tok.getFirstChild(); if (firstChild == null) continue; - if (firstChild.is(Kwd(KwdIf))) checkIfChild(firstChild); + if (firstChild.matches(Kwd(KwdIf))) checkIfChild(firstChild); else checkLastChild(tok); case Kwd(KwdFunction): checkFunctionChild(tok); @@ -102,14 +114,14 @@ class NeedBracesCheck extends Check { return; } body = body.nextSibling; - if (body.is(DblDot)) { + if (body.matches(DblDot)) { var lastChild:TokenTree = TokenTreeCheckUtils.getLastToken(token); - if (lastChild.is(Semicolon)) { + if (lastChild.matches(Semicolon)) { return; } body = body.nextSibling; } - if ((body == null) || (body.is(BrOpen))) { + if ((body == null) || (body.matches(BrOpen))) { return; } checkNoBraces(token, body); @@ -165,8 +177,7 @@ class NeedBracesCheck extends Check { } } -@:enum -abstract NeedBracesCheckToken(String) { +enum abstract NeedBracesCheckToken(String) { var FUNCTION = "FUNCTION"; var FOR = "FOR"; var IF = "IF"; diff --git a/src/checkstyle/checks/block/RightCurlyCheck.hx b/src/checkstyle/checks/block/RightCurlyCheck.hx index 689d2269..043bda21 100644 --- a/src/checkstyle/checks/block/RightCurlyCheck.hx +++ b/src/checkstyle/checks/block/RightCurlyCheck.hx @@ -60,7 +60,14 @@ class RightCurlyCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var allBrClose:Array = root.filter([BrClose], ALL); + var allBrClose:Array = root.filterCallback(function(token:TokenTree, index:Int):FilterResult { + return switch (token.tok) { + case BrClose: + FoundGoDeeper; + default: + GoDeeper; + } + }); for (brClose in allBrClose) { if (isPosSuppressed(brClose.pos)) continue; @@ -68,14 +75,13 @@ class RightCurlyCheck extends Check { if ((brOpen == null) || (brOpen.pos == null)) continue; var type:BrOpenType = TokenTreeCheckUtils.getBrOpenType(brOpen); switch (type) { - case BLOCK: - case TYPEDEFDECL: - if (!hasToken(TYPEDEF_DEF)) { - continue; - } - case OBJECTDECL: - case ANONTYPE: - case UNKNOWN: + case Block: + case TypedefDecl: + if (!hasToken(TYPEDEF_DEF)) continue; + case ObjectDecl: + if (!hasToken(OBJECT_DECL)) continue; + case AnonType: + case Unknown: } if (filterParentToken(brOpen.parent)) continue; check(brClose, type, isSingleLine(brOpen.pos.min, brClose.pos.max)); @@ -83,7 +89,7 @@ class RightCurlyCheck extends Check { } function filterParentToken(token:TokenTree):Bool { - if ((token == null) || (token.tok == null)) return false; + if ((token == null) || (token.tok == Root)) return false; switch (token.tok) { case Kwd(KwdClass): return !hasToken(CLASS_DEF); @@ -177,9 +183,9 @@ class RightCurlyCheck extends Check { var curlyAlone:Bool = false; switch (type) { - case BLOCK, TYPEDEFDECL, UNKNOWN: + case Block | TypedefDecl | Unknown: curlyAlone = ~/^\s*\}(|\..*|\).*|\].*|,\s*|;\s*)(|\/\/.*)$/.match(line); - case OBJECTDECL, ANONTYPE: + case ObjectDecl | AnonType: curlyAlone = ~/^\s*\}(|\..*|\).*|\].*|,.*|;\s*)(|\/\/.*)$/.match(line); } logErrorIf(!curlyAlone @@ -189,7 +195,7 @@ class RightCurlyCheck extends Check { logErrorIf(shouldHaveSameOption && (option == SAME), 'Right curly should be on same line as following block (e.g. "} else" or "} catch")', curlyPos); } - catch (e:String) { + catch (e:Exception) { // one of the error messages fired -> do nothing } } @@ -197,7 +203,7 @@ class RightCurlyCheck extends Check { function logErrorIf(condition:Bool, msg:String, pos:Position) { if (condition) { logPos(msg, pos); - throw "exit"; + throw new Exception("exit"); } } @@ -246,8 +252,7 @@ class RightCurlyCheck extends Check { } } -@:enum -abstract RightCurlyCheckToken(String) { +enum abstract RightCurlyCheckToken(String) { var CLASS_DEF = "CLASS_DEF"; var ENUM_DEF = "ENUM_DEF"; var ABSTRACT_DEF = "ABSTRACT_DEF"; @@ -265,8 +270,7 @@ abstract RightCurlyCheckToken(String) { var ARRAY_COMPREHENSION = "ARRAY_COMPREHENSION"; } -@:enum -abstract RightCurlyCheckOption(String) { +enum abstract RightCurlyCheckOption(String) { var SAME = "same"; var ALONE = "alone"; var ALONE_OR_SINGLELINE = "aloneorsingle"; diff --git a/src/checkstyle/checks/coding/ArrowFunctionCheck.hx b/src/checkstyle/checks/coding/ArrowFunctionCheck.hx index 8c328990..33bcc98d 100644 --- a/src/checkstyle/checks/coding/ArrowFunctionCheck.hx +++ b/src/checkstyle/checks/coding/ArrowFunctionCheck.hx @@ -40,19 +40,19 @@ class ArrowFunctionCheck extends Check { var arrowTokens:Array = root.filterCallback(function(token:TokenTree, index:Int):FilterResult { return switch (token.tok) { case Arrow: - if (isPosSuppressed(token.pos)) SKIP_SUBTREE; - FOUND_GO_DEEPER; + if (isPosSuppressed(token.pos)) SkipSubtree; + FoundGoDeeper; default: - GO_DEEPER; + GoDeeper; } }); for (token in arrowTokens) { var type:ArrowType = TokenTreeCheckUtils.determineArrowType(token); switch (type) { - case ARROW_FUNCTION: + case ArrowFunction: checkArrowFunction(token); - case FUNCTION_TYPE_HAXE3, FUNCTION_TYPE_HAXE4: + case OldFunctionType | NewFunctionType: continue; } } @@ -66,8 +66,8 @@ class ArrowFunctionCheck extends Check { case BrOpen: var type:BrOpenType = TokenTreeCheckUtils.getBrOpenType(body); switch (type) { - case OBJECTDECL: - case BLOCK, TYPEDEFDECL, ANONTYPE, UNKNOWN: + case ObjectDecl: + case Block | TypedefDecl | AnonType | Unknown: logPos("Arrow function should not have curlies", body.getPos()); } default: @@ -76,24 +76,24 @@ class ArrowFunctionCheck extends Check { arrow.filterCallback(function(token:TokenTree, index:Int):FilterResult { switch (token.tok) { case Arrow: - if (token.index == arrow.index) return GO_DEEPER; - return SKIP_SUBTREE; + if (token.index == arrow.index) return GoDeeper; + return SkipSubtree; case Kwd(KwdFunction): - if (allowFunction) return SKIP_SUBTREE; + if (allowFunction) return SkipSubtree; logPos("Arrow function should not include nested functions", token.pos); - return SKIP_SUBTREE; + return SkipSubtree; case Kwd(KwdReturn): - if (allowReturn) return GO_DEEPER; + if (allowReturn) return GoDeeper; logPos("Arrow function should not have explicit returns", token.pos); - return SKIP_SUBTREE; + return SkipSubtree; default: - return GO_DEEPER; + return GoDeeper; } }); if (allowSingleArgParens) return; var parent:Null = arrow.parent; - if ((parent == null) || (parent.tok == null)) return; - if (!parent.is(POpen)) return; + if ((parent == null) || (parent.tok == Root)) return; + if (!parent.matches(POpen)) return; var count:Int = 0; for (child in parent.children) { switch (child.tok) { diff --git a/src/checkstyle/checks/coding/CodeSimilarityCheck.hx b/src/checkstyle/checks/coding/CodeSimilarityCheck.hx index 11ea8400..039a5659 100644 --- a/src/checkstyle/checks/coding/CodeSimilarityCheck.hx +++ b/src/checkstyle/checks/coding/CodeSimilarityCheck.hx @@ -1,16 +1,6 @@ package checkstyle.checks.coding; -#if ((haxe_ver >= 4.0) && (neko || macro || eval || cpp || hl || java)) -import sys.thread.Mutex; -#elseif neko -import neko.vm.Mutex; -#elseif cpp -import cpp.vm.Mutex; -#elseif java -import java.vm.Mutex; -#else import checkstyle.utils.Mutex; -#end /** Checks for identical or similar code. @@ -20,6 +10,10 @@ import checkstyle.utils.Mutex; class CodeSimilarityCheck extends Check { static var SIMILAR_HASHES:Map = new Map(); static var IDENTICAL_HASHES:Map = new Map(); + + static var SIMILAR_MESSAGES:Map = new Map(); + static var IDENTICAL_MESSAGES:Map = new Map(); + static var LOCK:Mutex = new Mutex(); #if use_similarity_ringbuffer static var FILE_RINGBUFFER:Array = []; @@ -63,7 +57,7 @@ class CodeSimilarityCheck extends Check { case Kwd(KwdDo): skipSubTree = checkFunctionSimilarity(token); case Kwd(KwdWhile): - if ((token.parent != null) && (token.parent.is(Kwd(KwdDo)))) return SKIP_SUBTREE; + if ((token.parent != null) && (token.parent.matches(Kwd(KwdDo)))) return SkipSubtree; skipSubTree = checkFunctionSimilarity(token); case Kwd(KwdTry): skipSubTree = checkFunctionSimilarity(token); @@ -74,9 +68,9 @@ class CodeSimilarityCheck extends Check { default: } if (skipSubTree) { - return SKIP_SUBTREE; + return SkipSubtree; } - return GO_DEEPER; + return GoDeeper; }); } @@ -103,7 +97,7 @@ class CodeSimilarityCheck extends Check { if (hashes.tokenCount > thresholdIdentical) { var existing:Null = checkOrAddHash(hashes.identicalHash, codeBlock, IDENTICAL_HASHES); if (existing != null) { - logRange("Found identical code block - " + formatFirstFound(existing), pos.min, pos.max, SIMILAR_BLOCK, severityIdentical); + logCodeBlock(hashes.identicalHash, existing, pos, IDENTICAL_MESSAGES, "identical code blocks"); return true; } } @@ -111,12 +105,22 @@ class CodeSimilarityCheck extends Check { if (hashes.tokenCount > thresholdSimilar) { var existing:Null = checkOrAddHash(hashes.similarHash, codeBlock, SIMILAR_HASHES); if (existing == null) return false; - logRange("Found similar code block - " + formatFirstFound(existing), pos.min, pos.max, SIMILAR_BLOCK); + logCodeBlock(hashes.similarHash, existing, pos, SIMILAR_MESSAGES, "similar code blocks"); return true; } return false; } + function logCodeBlock(hash:String, existing:HashedCodeBlock, pos:Position, messages:Map, msg:String) { + var message:Null = messages.get(hash); + if (message == null) { + message = createMessage(msg, existing.lineStart.line + 1, existing.startColumn, existing.lineEnd.line + 1, existing.endColumn); + message.fileName = existing.fileName; + messages.set(hash, message); + } + addRelatedRange(message, msg, pos.min, pos.max); + } + function formatFirstFound(existing:HashedCodeBlock):String { return 'first seen in ${existing.fileName}:${existing.lineStart.line + 1}'; } @@ -154,7 +158,9 @@ class CodeSimilarityCheck extends Check { } for (hash in fileHashes) { SIMILAR_HASHES.remove(hash.similarHash); + SIMILAR_MESSAGES.remove(hash.similarHash); IDENTICAL_HASHES.remove(hash.identicalHash); + IDENTICAL_MESSAGES.remove(hash.identicalHash); } FILE_HASHES.remove(fileName); } @@ -168,7 +174,9 @@ class CodeSimilarityCheck extends Check { if (fileHashes != null) { for (hash in fileHashes) { SIMILAR_HASHES.remove(hash.similarHash); + SIMILAR_MESSAGES.remove(hash.similarHash); IDENTICAL_HASHES.remove(hash.identicalHash); + IDENTICAL_MESSAGES.remove(hash.identicalHash); } FILE_HASHES.remove(fileName); } @@ -246,32 +254,50 @@ class CodeSimilarityCheck extends Check { } function identicalTokenText(token:TokenTree):Null { - switch (token.tok) { + return switch (token.tok) { case Const(CFloat(f)): - return '$f'; + '$f'; case Const(CString(s)): - return '"$s"'; + '"$s"'; case Const(CIdent(i)): - return '$i'; + '$i'; case Const(CRegexp(r, op)): - return '$r,$op'; + '$r,$op'; case Const(CInt(i)): - return '$i'; + '$i'; case Dollar(n): - return '$n'; + '$n'; case Unop(op): - return '$op'; + '$op'; case Binop(op): - return '$op'; + '$op'; case Comment(_): - return null; + null; case CommentLine(_): - return null; + null; case IntInterval(i): - return '...$i'; + '...$i'; default: - return '${token.tok}'; + '${token.tok}'; + } + } + + /** + similar or identical code blocks can occur in just one file or distríbuted over the + full code base, so we need to collect all locations before emitting a checkstyle message + @return Array list of checkstyle message findings + **/ + public static function delayedMessagesCallback():Array { + var delayedMessages:Array = []; + for (_ => message in SIMILAR_MESSAGES) { + delayedMessages.push(message); + } + SIMILAR_MESSAGES.clear(); + for (_ => message in IDENTICAL_MESSAGES) { + delayedMessages.push(message); } + IDENTICAL_MESSAGES.clear(); + return delayedMessages; } override public function detectableInstances():DetectableInstances { @@ -285,8 +311,7 @@ class CodeSimilarityCheck extends Check { } } -@:enum -abstract CodeSimilarityCode(String) to String { +enum abstract CodeSimilarityCode(String) to String { var SIMILAR_BLOCK = "SimilarBlock"; var IDENTICAL_BLOCK = "IdenticalBlock"; } diff --git a/src/checkstyle/checks/coding/DefaultComesLastCheck.hx b/src/checkstyle/checks/coding/DefaultComesLastCheck.hx index 0608d805..616be2b7 100644 --- a/src/checkstyle/checks/coding/DefaultComesLastCheck.hx +++ b/src/checkstyle/checks/coding/DefaultComesLastCheck.hx @@ -15,15 +15,29 @@ class DefaultComesLastCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var acceptableTokens:Array = root.filter([Kwd(KwdSwitch)], ALL); + var acceptableTokens:Array = root.filterCallback(function(token:TokenTree, index:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdSwitch): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (token in acceptableTokens) { - var tokens:Array = token.filter([Kwd(KwdCase), Kwd(KwdDefault)], FIRST); + var tokens:Array = token.filterCallback(function(token:TokenTree, index:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdCase) | Kwd(KwdDefault): + FoundSkipSubtree; + default: + GoDeeper; + } + }); if (tokens.length <= 0) continue; - if (tokens[tokens.length - 1].is(Kwd(KwdDefault))) continue; + if (tokens[tokens.length - 1].matches(Kwd(KwdDefault))) continue; for (i in 0...tokens.length) { - if (tokens[i].is(Kwd(KwdDefault)) && i < tokens.length - 1) { + if (tokens[i].matches(Kwd(KwdDefault)) && i < tokens.length - 1) { logPos('Default should be last label in the "switch"', token.pos); continue; } diff --git a/src/checkstyle/checks/coding/HiddenFieldCheck.hx b/src/checkstyle/checks/coding/HiddenFieldCheck.hx index d660670d..9f980313 100644 --- a/src/checkstyle/checks/coding/HiddenFieldCheck.hx +++ b/src/checkstyle/checks/coding/HiddenFieldCheck.hx @@ -35,14 +35,28 @@ class HiddenFieldCheck extends Check { override function actualRun() { var ignoreFormatRE:EReg = new EReg(ignoreFormat, ""); var root:TokenTree = checker.getTokenTree(); - checkClasses(root.filter([Kwd(KwdClass)], ALL), ignoreFormatRE); + checkClasses(root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdClass): + FoundSkipSubtree; + default: + GoDeeper; + } + }), ignoreFormatRE); } function checkClasses(classes:Array, ignoreFormatRE:EReg) { for (clazz in classes) { if (isPosSuppressed(clazz.pos)) continue; var memberNames:Array = collectMemberNames(clazz); - var methods:Array = clazz.filter([Kwd(KwdFunction)], FIRST); + var methods:Array = clazz.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdFunction): + FoundSkipSubtree; + default: + GoDeeper; + } + }); for (method in methods) { if (isPosSuppressed(method.pos)) continue; checkMethod(method, memberNames, ignoreFormatRE); @@ -51,11 +65,11 @@ class HiddenFieldCheck extends Check { } function checkMethod(method:TokenTree, memberNames:Array, ignoreFormatRE:EReg) { - if (!method.hasChildren()) throw "function has invalid structure!"; + if (!method.hasChildren()) throw new Exception("function has invalid structure!"); // handle constructor and setters var methodName:TokenTree = method.children[0]; - if (methodName.is(Kwd(KwdNew)) && ignoreConstructorParameter) return; + if (methodName.matches(Kwd(KwdNew)) && ignoreConstructorParameter) return; if (ignoreSetter && isSetterFunction(methodName, memberNames)) return; switch (methodName.tok) { case Const(CIdent(name)): @@ -90,26 +104,57 @@ class HiddenFieldCheck extends Check { // |- POpen // |- parameters // |- PClose - var paramDef:Array = method.filter([POpen], FIRST, 2); + var paramDef:Array = method.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + if (depth > 2) return SkipSubtree; + return switch (token.tok) { + case POpen: + FoundSkipSubtree; + default: + GoDeeper; + } + }); + if ((paramDef == null) || (paramDef.length != 1)) { - throw "function parameters have invalid structure!"; + throw new Exception("function parameters have invalid structure!"); } var paramList:Array = paramDef[0].children; for (param in paramList) checkName(param, memberNames, "Parameter definition"); } function checkVars(method:TokenTree, memberNames:Array) { - var vars:Array = method.filter([Kwd(KwdVar)], ALL); + var vars:Array = method.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdVar): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (v in vars) { - if (!v.hasChildren()) throw "var has invalid structure!"; + if (!v.hasChildren()) throw new Exception("var has invalid structure!"); checkName(v.children[0], memberNames, "Variable definition"); } } function checkForLoops(method:TokenTree, memberNames:Array) { - var fors:Array = method.filter([Kwd(KwdFor)], ALL); + var fors:Array = method.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdFor): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (f in fors) { - var popens:Array = f.filter([POpen], FIRST, 2); + var popens:Array = f.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + if (depth > 2) return SkipSubtree; + return switch (token.tok) { + case POpen: + FoundSkipSubtree; + default: + GoDeeper; + } + }); if (popens.length <= 0) continue; var pOpen:TokenTree = popens[0]; if (!pOpen.hasChildren()) continue; @@ -135,7 +180,15 @@ class HiddenFieldCheck extends Check { // |- Kwd(KwdVar) // |- Kwd(KwdVar) // |- Kwd(KwdFunction) - var varFields:Array = clazz.filter([Kwd(KwdVar)], FIRST, MAX_FIELD_LEVEL); + var varFields:Array = clazz.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + if (depth > MAX_FIELD_LEVEL) return SkipSubtree; + return switch (token.tok) { + case Kwd(KwdVar): + FoundSkipSubtree; + default: + GoDeeper; + } + }); for (member in varFields) { if (!member.hasChildren()) continue; switch (member.children[0].tok) { diff --git a/src/checkstyle/checks/coding/InnerAssignmentCheck.hx b/src/checkstyle/checks/coding/InnerAssignmentCheck.hx index 8dba6b23..ba153afb 100644 --- a/src/checkstyle/checks/coding/InnerAssignmentCheck.hx +++ b/src/checkstyle/checks/coding/InnerAssignmentCheck.hx @@ -20,19 +20,16 @@ class InnerAssignmentCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var allAssignments:Array = root.filter([ - Binop(OpAssign), - Binop(OpAssignOp(OpAdd)), - Binop(OpAssignOp(OpSub)), - Binop(OpAssignOp(OpDiv)), - Binop(OpAssignOp(OpMult)), - Binop(OpAssignOp(OpShl)), - Binop(OpAssignOp(OpShr)), - Binop(OpAssignOp(OpUShr)), - Binop(OpAssignOp(OpAnd)), - Binop(OpAssignOp(OpOr)), - Binop(OpAssignOp(OpXor)) - ], ALL); + var allAssignments:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Binop(OpAssign) | Binop(OpAssignOp(OpAdd)) | Binop(OpAssignOp(OpSub)) | Binop(OpAssignOp(OpDiv)) | Binop(OpAssignOp(OpMult)) | + Binop(OpAssignOp(OpShl)) | Binop(OpAssignOp(OpShr)) | Binop(OpAssignOp(OpUShr)) | Binop(OpAssignOp(OpAnd)) | Binop(OpAssignOp(OpOr)) | + Binop(OpAssignOp(OpXor)): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (assignToken in allAssignments) { if (isPosSuppressed(assignToken.pos) || !filterAssignment(assignToken)) continue; logPos("Inner assignment detected", assignToken.pos); @@ -40,11 +37,11 @@ class InnerAssignmentCheck extends Check { } function filterAssignment(token:TokenTree):Bool { - if ((token == null) || (token.tok == null)) return false; + if ((token == null) || (token.tok == Root)) return false; if (token.previousSibling != null) { // tokenizer does not treat >= as OpGte // creates OpGt and OpAssign instead - if (token.previousSibling.is(Binop(OpGt))) return false; + if (token.previousSibling.matches(Binop(OpGt))) return false; } return switch (token.tok) { case Kwd(KwdVar): false; @@ -52,13 +49,14 @@ class InnerAssignmentCheck extends Check { case Kwd(KwdSwitch): true; case Kwd(KwdReturn): filterReturn(token); case BrOpen, DblDot: false; + case Arrow: false; case POpen: filterPOpen(token.parent); default: filterAssignment(token.parent); } } function filterPOpen(token:TokenTree):Bool { - if ((token == null) || (token.tok == null)) return false; + if ((token == null) || (token.tok == Root)) return false; return switch (token.tok) { case Kwd(KwdFunction): false; case Kwd(KwdVar): false; @@ -78,12 +76,11 @@ class InnerAssignmentCheck extends Check { // - return is only statement inside block // - it is inside of setter function var allBinops:Array = token.filterCallback(function(token:TokenTree, depth:Int):FilterResult { - if (token.tok == null) return GO_DEEPER; return switch (token.tok) { - case Binop(_): FOUND_GO_DEEPER; - case Unop(_): FOUND_GO_DEEPER; - case POpen, BkOpen, BrOpen: FOUND_GO_DEEPER; - default: GO_DEEPER; + case Binop(_): FoundGoDeeper; + case Unop(_): FoundGoDeeper; + case POpen, BkOpen, BrOpen: FoundGoDeeper; + default: GoDeeper; } }); diff --git a/src/checkstyle/checks/coding/MagicNumberCheck.hx b/src/checkstyle/checks/coding/MagicNumberCheck.hx index 0ff59f72..d5d1d050 100644 --- a/src/checkstyle/checks/coding/MagicNumberCheck.hx +++ b/src/checkstyle/checks/coding/MagicNumberCheck.hx @@ -20,13 +20,14 @@ class MagicNumberCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var allTypes:Array = root.filter([ - Kwd(KwdAbstract), - Kwd(KwdClass), - Kwd(KwdEnum), - Kwd(KwdInterface), - Kwd(KwdTypedef) - ], FIRST); + var allTypes:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdAbstract) | Kwd(KwdClass) | Kwd(KwdEnum) | Kwd(KwdInterface) | Kwd(KwdTypedef): + FoundSkipSubtree; + default: + GoDeeper; + } + }); for (type in allTypes) { if (TokenTreeCheckUtils.isTypeEnumAbstract(type)) continue; checkForNumbers(type); @@ -35,36 +36,51 @@ class MagicNumberCheck extends Check { function checkForNumbers(parent:TokenTree) { var allNumbers:Array = parent.filterCallback(function(token:TokenTree, depth:Int):FilterResult { - if (token.tok == null) return GO_DEEPER; return switch (token.tok) { - case Const(CInt(_)): FOUND_GO_DEEPER; - case Const(CFloat(_)): FOUND_GO_DEEPER; - default: GO_DEEPER; + case Const(CInt(_)): FoundGoDeeper; + case Const(CFloat(_)): FoundGoDeeper; + default: GoDeeper; } }); for (numberToken in allNumbers) { if (isPosSuppressed(numberToken.pos)) continue; - if (!filterNumber(numberToken)) continue; + if (filterNumber(numberToken)) continue; switch (numberToken.tok) { - case Const(CInt(n)): - var number:Int = Std.parseInt(n); + case Const(CInt(n, s)): + var number:Int = Std.parseInt(n.replace("_", "")); if (ignoreNumbers.contains(number)) continue; - logPos('"$n" is a magic number', numberToken.pos); - case Const(CFloat(n)): - var number:Float = Std.parseFloat(n); + if (s == null) s = ""; + logPos('"$n$s" is a magic number', numberToken.pos); + case Const(CFloat(n, s)): + var number:Float = Std.parseFloat(n.replace("_", "")); if (ignoreNumbers.contains(number)) continue; - logPos('"$n" is a magic number', numberToken.pos); + if (s == null) s = ""; + logPos('"$n$s" is a magic number', numberToken.pos); default: } } } function filterNumber(token:TokenTree):Bool { - if ((token == null) || (token.tok == null)) return true; + if ((token == null) || (token.tok == Root)) return false; return switch (token.tok) { - case At: false; - case Kwd(KwdVar): if (token.filter([Kwd(KwdStatic)], FIRST).length > 0) false; else true; + case At: true; + case Kwd(KwdFinal): true; + case BrOpen: false; + case Kwd(KwdVar): if (token.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdStatic): + FoundSkipSubtree; + default: + GoDeeper; + } + }).length > 0) { + true; + } + else { + false; + } default: filterNumber(token.parent); } } diff --git a/src/checkstyle/checks/coding/MultipleVariableDeclarationsCheck.hx b/src/checkstyle/checks/coding/MultipleVariableDeclarationsCheck.hx index 73b3f956..abf64b63 100644 --- a/src/checkstyle/checks/coding/MultipleVariableDeclarationsCheck.hx +++ b/src/checkstyle/checks/coding/MultipleVariableDeclarationsCheck.hx @@ -14,7 +14,14 @@ class MultipleVariableDeclarationsCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var acceptableTokens:Array = root.filter([Kwd(KwdVar)], ALL); + var acceptableTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdVar): + FoundGoDeeper; + default: + GoDeeper; + } + }); var lastVarLineNo = -1; for (v in acceptableTokens) { diff --git a/src/checkstyle/checks/coding/NestedControlFlowCheck.hx b/src/checkstyle/checks/coding/NestedControlFlowCheck.hx index f33e154f..1b5f0805 100644 --- a/src/checkstyle/checks/coding/NestedControlFlowCheck.hx +++ b/src/checkstyle/checks/coding/NestedControlFlowCheck.hx @@ -23,19 +23,19 @@ class NestedControlFlowCheck extends Check { var controlFlowTokens:Array = root.filterCallback(function(token:TokenTree, index:Int):FilterResult { return switch (token.tok) { case Kwd(KwdFor): - FOUND_GO_DEEPER; + FoundGoDeeper; case Kwd(KwdIf): - FOUND_GO_DEEPER; + FoundGoDeeper; case Kwd(KwdSwitch): - FOUND_GO_DEEPER; + FoundGoDeeper; case Kwd(KwdDo): - FOUND_GO_DEEPER; + FoundGoDeeper; case Kwd(KwdWhile): - if ((token.parent != null) && (token.parent.is(Kwd(KwdDo)))) GO_DEEPER; else FOUND_GO_DEEPER; + if ((token.parent != null) && (token.parent.matches(Kwd(KwdDo)))) GoDeeper; else FoundGoDeeper; case Kwd(KwdTry): - FOUND_GO_DEEPER; + FoundGoDeeper; default: - GO_DEEPER; + GoDeeper; } }); for (token in controlFlowTokens) { @@ -52,7 +52,7 @@ class NestedControlFlowCheck extends Check { function calcDepth(token:TokenTree):Int { var parent:TokenTree = token.parent; var count:Int = 1; - while ((parent != null) && (parent.tok != null)) { + while ((parent != null) && (parent.tok != Root)) { switch (parent.tok) { case Kwd(KwdFor): count++; @@ -63,7 +63,7 @@ class NestedControlFlowCheck extends Check { case Kwd(KwdDo): count++; case Kwd(KwdWhile): - if ((parent.parent == null) || (!parent.parent.is(Kwd(KwdDo)))) count++; + if ((parent.parent == null) || (!parent.parent.matches(Kwd(KwdDo)))) count++; case Kwd(KwdTry): count++; default: diff --git a/src/checkstyle/checks/coding/NullableParameterCheck.hx b/src/checkstyle/checks/coding/NullableParameterCheck.hx index e0a6f6b8..830f5be1 100644 --- a/src/checkstyle/checks/coding/NullableParameterCheck.hx +++ b/src/checkstyle/checks/coding/NullableParameterCheck.hx @@ -62,8 +62,7 @@ class NullableParameterCheck extends Check { - questionMark = nullable parameters should use "?name:Type" - nullDefault = nullable parameters should use "name:Type = null" **/ -@:enum -abstract NullableParameterCheckOption(String) { +enum abstract NullableParameterCheckOption(String) { var QUESTION_MARK = "questionMark"; var NULL_DEFAULT = "nullDefault"; } \ No newline at end of file diff --git a/src/checkstyle/checks/coding/ReturnCountCheck.hx b/src/checkstyle/checks/coding/ReturnCountCheck.hx index ba3588d1..1d8cf2e0 100644 --- a/src/checkstyle/checks/coding/ReturnCountCheck.hx +++ b/src/checkstyle/checks/coding/ReturnCountCheck.hx @@ -29,7 +29,14 @@ class ReturnCountCheck extends Check { override function actualRun() { var ignoreFormatRE:EReg = new EReg(ignoreFormat, ""); var root:TokenTree = checker.getTokenTree(); - var functions = root.filter([Kwd(KwdFunction)], ALL); + var functions = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdFunction): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (fn in functions) { if (fn.children == null) continue; switch (fn.getFirstChild().tok) { @@ -50,9 +57,9 @@ class ReturnCountCheck extends Check { return switch (token.tok) { case Kwd(KwdFunction): // top node is always a function node - if (depth == 0) GO_DEEPER; else SKIP_SUBTREE; - case Kwd(KwdReturn): FOUND_SKIP_SUBTREE; - default: GO_DEEPER; + if (depth == 0) GoDeeper; else SkipSubtree; + case Kwd(KwdReturn): FoundSkipSubtree; + default: GoDeeper; } } diff --git a/src/checkstyle/checks/coding/SimplifyBooleanExpressionCheck.hx b/src/checkstyle/checks/coding/SimplifyBooleanExpressionCheck.hx index b8e30912..fa645076 100644 --- a/src/checkstyle/checks/coding/SimplifyBooleanExpressionCheck.hx +++ b/src/checkstyle/checks/coding/SimplifyBooleanExpressionCheck.hx @@ -14,21 +14,19 @@ class SimplifyBooleanExpressionCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var acceptableTokens:Array = root.filter([ - Kwd(KwdTrue), - Kwd(KwdFalse), - Binop(OpEq), - Binop(OpNotEq), - Unop(OpNot), - Binop(OpOr), - Binop(OpAnd), - Binop(OpBoolOr), - Binop(OpBoolAnd) - ], ALL); + var acceptableTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdTrue) | Kwd(KwdFalse) | Binop(OpEq) | Binop(OpNotEq) | Unop(OpNot) | Binop(OpOr) | Binop(OpAnd) | Binop(OpBoolOr) | + Binop(OpBoolAnd): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (token in acceptableTokens) { if (isPosSuppressed(token.pos)) continue; - if (token.is(Kwd(KwdTrue)) || token.is(Kwd(KwdFalse))) checkToken(token); + if (token.matches(Kwd(KwdTrue)) || token.matches(Kwd(KwdFalse))) checkToken(token); } } diff --git a/src/checkstyle/checks/coding/SimplifyBooleanReturnCheck.hx b/src/checkstyle/checks/coding/SimplifyBooleanReturnCheck.hx index 90d258bd..b0e22a57 100644 --- a/src/checkstyle/checks/coding/SimplifyBooleanReturnCheck.hx +++ b/src/checkstyle/checks/coding/SimplifyBooleanReturnCheck.hx @@ -14,10 +14,24 @@ class SimplifyBooleanReturnCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var acceptableTokens:Array = root.filter([Kwd(KwdIf)], ALL); + var acceptableTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdIf): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (token in acceptableTokens) { - var elseLiteral = token.filter([Kwd(KwdElse)], FIRST)[0]; + var elseLiteral = token.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdElse): + FoundSkipSubtree; + default: + GoDeeper; + } + })[0]; if (elseLiteral == null) continue; var elseStatement = elseLiteral.getFirstChild(); @@ -36,7 +50,7 @@ class SimplifyBooleanReturnCheck extends Check { function isBooleanLiteralReturnStatement(tkn:TokenTree):Bool { var booleanReturnStatement = false; - if (tkn != null && tkn.is(Kwd(KwdReturn))) { + if (tkn != null && tkn.matches(Kwd(KwdReturn))) { var expr = tkn.getFirstChild(); booleanReturnStatement = isBooleanLiteralType(expr); } @@ -44,6 +58,6 @@ class SimplifyBooleanReturnCheck extends Check { } function isBooleanLiteralType(tkn:TokenTree):Bool { - return tkn.is(Kwd(KwdTrue)) || tkn.is(Kwd(KwdFalse)); + return tkn.matches(Kwd(KwdTrue)) || tkn.matches(Kwd(KwdFalse)); } } \ No newline at end of file diff --git a/src/checkstyle/checks/coding/TraceCheck.hx b/src/checkstyle/checks/coding/TraceCheck.hx index 00aeacee..2f78764b 100644 --- a/src/checkstyle/checks/coding/TraceCheck.hx +++ b/src/checkstyle/checks/coding/TraceCheck.hx @@ -13,7 +13,14 @@ class TraceCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var traces = root.filter([Const(CIdent("trace"))], ALL); + var traces = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Const(CIdent("trace")): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (tr in traces) { if (!tr.getFirstChild().tok.match(POpen)) continue; if (filterTrace(tr.parent)) continue; diff --git a/src/checkstyle/checks/coding/UnusedLocalVarCheck.hx b/src/checkstyle/checks/coding/UnusedLocalVarCheck.hx index 42e7e9b1..fe7dbd95 100644 --- a/src/checkstyle/checks/coding/UnusedLocalVarCheck.hx +++ b/src/checkstyle/checks/coding/UnusedLocalVarCheck.hx @@ -14,21 +14,28 @@ class UnusedLocalVarCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var functions:Array = root.filter([Kwd(KwdFunction)], ALL); + var functions:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdFunction): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (f in functions) { if (isPosSuppressed(f.pos)) continue; var skipFirstFunction:Bool = true; var localVars:Array = f.filterCallback(function(tok:TokenTree, depth:Int):FilterResult { return switch (tok.tok) { - case Kwd(KwdVar): FOUND_SKIP_SUBTREE; + case Kwd(KwdVar): FoundSkipSubtree; case Kwd(KwdFunction): if (skipFirstFunction) { skipFirstFunction = false; - GO_DEEPER; + GoDeeper; } - else SKIP_SUBTREE; - default: GO_DEEPER; + else SkipSubtree; + default: GoDeeper; } }); checkLocalVars(f, localVars); @@ -53,26 +60,26 @@ class UnusedLocalVarCheck extends Check { if (ignoreFunctionSignature) { switch (tok.tok) { case Kwd(KwdPublic), Kwd(KwdPrivate): - return SKIP_SUBTREE; + return SkipSubtree; case At: - return SKIP_SUBTREE; + return SkipSubtree; case Comment(_), CommentLine(_): - return SKIP_SUBTREE; + return SkipSubtree; case POpen: ignoreFunctionSignature = false; - return SKIP_SUBTREE; + return SkipSubtree; default: - return GO_DEEPER; + return GoDeeper; } } return switch (tok.tok) { case Dollar(n): - if (n == name) FOUND_GO_DEEPER; else GO_DEEPER; + if (n == name) FoundGoDeeper; else GoDeeper; case Const(CIdent(n)): - if (n == name) FOUND_GO_DEEPER; else GO_DEEPER; + if (n == name) FoundGoDeeper; else GoDeeper; case Const(CString(s)): checkStringInterpolation(tok, name, s); - default: GO_DEEPER; + default: GoDeeper; } }); if (nameList.length > 1) return; @@ -82,23 +89,23 @@ class UnusedLocalVarCheck extends Check { function checkStringInterpolation(tok:TokenTree, name:String, s:String):FilterResult { if (!StringUtils.isStringInterpolation(s, checker.file.content, tok.pos)) { - return GO_DEEPER; + return GoDeeper; } // $name var format:String = "\\$" + name + "([^_0-9a-zA-Z]|$)"; var r:EReg = new EReg(format, ""); if (r.match(s)) { - return FOUND_GO_DEEPER; + return FoundGoDeeper; } // '${name.doSomething()} or ${doSomething(name)} or ${name} format = "\\$\\{(|.*[^_0-9a-zA-Z])" + name + "([^_0-9a-zA-Z].*|)\\}"; r = new EReg(format, ""); if (r.match(s)) { - return FOUND_GO_DEEPER; + return FoundGoDeeper; } - return GO_DEEPER; + return GoDeeper; } override public function detectableInstances():DetectableInstances { diff --git a/src/checkstyle/checks/coding/VariableInitialisationCheck.hx b/src/checkstyle/checks/coding/VariableInitialisationCheck.hx index ad013310..37c9bb1c 100644 --- a/src/checkstyle/checks/coding/VariableInitialisationCheck.hx +++ b/src/checkstyle/checks/coding/VariableInitialisationCheck.hx @@ -37,9 +37,7 @@ class VariableInitialisationCheck extends Check { if (f.access.contains(APublic)) isPublic = true; else isPrivate = true; - #if haxe4 if (f.access.contains(AFinal)) isFinal = true; - #end if (allowFinal && isFinal) return; if (isPrivate || isPublic) { diff --git a/src/checkstyle/checks/comments/CommentedOutCodeCheck.hx b/src/checkstyle/checks/comments/CommentedOutCodeCheck.hx new file mode 100644 index 00000000..5728dbf6 --- /dev/null +++ b/src/checkstyle/checks/comments/CommentedOutCodeCheck.hx @@ -0,0 +1,134 @@ +package checkstyle.checks.comments; + +import byte.ByteData; +import haxe.Exception; +import haxeparser.HaxeParser; + +/** + Checks sections of commented out code +**/ +@name("CommentedOutCode") +@desc("Checks sections of commented out code") +class CommentedOutCodeCheck extends Check { + static inline final COMMENTED_OUT_CODE:String = "This block of commented-out lines of code should be removed"; + + public function new() { + super(TOKEN); + } + + override function actualRun() { + var root:TokenTree = checker.getTokenTree(); + var comments = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case CommentLine(_): + FoundSkipSubtree; + case Comment(_): + FoundSkipSubtree; + default: + GoDeeper; + } + }); + + var currentRun:Array = []; + var lastIndex:Int = -1; + for (token in comments) { + if (isPosSuppressed(token.pos)) continue; + + switch (token.tok) { + case Comment(text): + while (text.startsWith("*")) { + text = text.substr(1); + } + while (text.endsWith("*")) { + text = text.substr(0, text.length - 1); + } + checkForCommentedCode(text, token.pos); + case CommentLine(_): + if ((lastIndex == -1) || (lastIndex + 1 == token.index)) { + currentRun.push(token); + lastIndex = token.index; + continue; + } + checkTokenRunIterations(currentRun); + currentRun = [token]; + lastIndex = token.index; + default: + } + } + if (currentRun.length > 0) { + checkTokenRunIterations(currentRun); + } + } + + function checkTokenRunIterations(run:Array) { + if (run.length <= 0) return; + var runCopy:Array = run.copy(); + var removedTokens:Array = []; + + while (runCopy.length > 0) { + if (checkTokenRun(runCopy)) { + checkTokenRunIterations(removedTokens); + return; + } + var lastToken:TokenTree = runCopy.pop(); + if (runCopy.length > 1) { + removedTokens.unshift(lastToken); + } + } + checkTokenRunIterations(removedTokens); + } + + function checkTokenRun(run:Array):Bool { + if (run.length <= 0) return false; + var text:String = run.map(token -> switch (token.tok) { + case CommentLine(text): + text; + default: + ""; + }).join("\n"); + var first:TokenTree = run[0]; + var last:TokenTree = run[run.length - 1]; + var pos:Position = { + file: first.pos.file, + min: first.pos.min, + max: last.pos.max + }; + return checkForCommentedCode(text, pos); + } + + function checkForCommentedCode(text:String, pos:Position):Bool { + if (text.trim().length <= 0) return false; + try { + var parser = new HaxeParser(ByteData.ofString(text), checker.file.name); + parser.parse(); + logPos(COMMENTED_OUT_CODE, pos, "CommentedOutCode"); + return true; + } + catch (e:Exception) {} + try { + var parser = new HaxeParser(ByteData.ofString("function code () {" + text + "}"), checker.file.name); + parser.parse(); + logPos(COMMENTED_OUT_CODE, pos, "CommentedOutCode"); + return true; + } + catch (e:Exception) {} + try { + var parser = new HaxeParser(ByteData.ofString("class Code {" + text + "}"), checker.file.name); + parser.parse(); + logPos(COMMENTED_OUT_CODE, pos, "CommentedOutCode"); + return true; + } + catch (e:Exception) {} + return false; + } + + override public function detectableInstances():DetectableInstances { + return [{ + fixed: [], + properties: [{ + propertyName: "severity", + values: [SeverityLevel.INFO] + }] + }]; + } +} \ No newline at end of file diff --git a/src/checkstyle/checks/comments/DocCommentStyleCheck.hx b/src/checkstyle/checks/comments/DocCommentStyleCheck.hx index 0decd553..8fd0cd5b 100644 --- a/src/checkstyle/checks/comments/DocCommentStyleCheck.hx +++ b/src/checkstyle/checks/comments/DocCommentStyleCheck.hx @@ -31,16 +31,16 @@ class DocCommentStyleCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var docTokens = root.filter([ - Kwd(KwdAbstract), - Kwd(KwdClass), - Kwd(KwdEnum), - Kwd(KwdInterface), - Kwd(KwdTypedef), - Kwd(KwdVar), - #if haxe4 Kwd(KwdFinal) #else Const(CIdent("final")) #end, - Kwd(KwdFunction) - ], ALL); + var docTokens = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdAbstract) | Kwd(KwdClass) | Kwd(KwdEnum) | Kwd(KwdInterface) | Kwd(KwdTypedef) | Kwd(KwdVar) | Kwd(KwdFunction): + FoundGoDeeper; + case Kwd(KwdFinal): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (token in docTokens) { if (isPosSuppressed(token.pos)) continue; @@ -107,16 +107,14 @@ class DocCommentStyleCheck extends Check { - onestar = * - twostar = ** **/ -@:enum -abstract DocCommentStyle(String) { +enum abstract DocCommentStyle(String) { var IGNORE = "ignore"; var NONE = "none"; var ONE_STAR = "onestar"; var TWO_STARS = "twostars"; } -@:enum -abstract DocCommentStyleCode(String) to String { +enum abstract DocCommentStyleCode(String) to String { var ONE_STAR_START = "OneStarStart"; var TWO_STARS_START = "TwoStarsStart"; var NO_STARS_LINES = "NoStarsLine"; diff --git a/src/checkstyle/checks/comments/FieldDocCommentCheck.hx b/src/checkstyle/checks/comments/FieldDocCommentCheck.hx index 018960e8..0f05df8f 100644 --- a/src/checkstyle/checks/comments/FieldDocCommentCheck.hx +++ b/src/checkstyle/checks/comments/FieldDocCommentCheck.hx @@ -71,29 +71,37 @@ class FieldDocCommentCheck extends Check { } override function actualRun() { - var root:TokenTree = checker.getTokenTree(); - var typeTokenDefs:Array = []; - if (hasToken(ABSTRACT_DEF)) typeTokenDefs.push(Kwd(KwdAbstract)); - if (hasToken(CLASS_DEF)) typeTokenDefs.push(Kwd(KwdClass)); - if (hasToken(ENUM_DEF)) typeTokenDefs.push(Kwd(KwdEnum)); - if (hasToken(INTERFACE_DEF)) typeTokenDefs.push(Kwd(KwdInterface)); - if (hasToken(TYPEDEF_DEF)) typeTokenDefs.push(Kwd(KwdTypedef)); - var typeTokens = root.filter(typeTokenDefs, ALL); - - var fieldTokenDefs:Array = []; - if ((fieldType == VARS) || (fieldType == BOTH)) { - fieldTokenDefs.push(Kwd(KwdVar)); - #if haxe4 - fieldTokenDefs.push(Kwd(KwdFinal)); - #else - fieldTokenDefs.push(Const(CIdent("final"))); - #end - } - if ((fieldType == FUNCTIONS) || (fieldType == BOTH)) fieldTokenDefs.push(Kwd(KwdFunction)); + var typeTokens:Array = checker.getTokenTree().filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdAbstract) if (hasToken(ABSTRACT_DEF)): + FoundSkipSubtree; + case Kwd(KwdClass) if (hasToken(CLASS_DEF)): + FoundSkipSubtree; + case Kwd(KwdEnum) if (hasToken(ENUM_DEF)): + FoundSkipSubtree; + case Kwd(KwdInterface) if (hasToken(INTERFACE_DEF)): + FoundSkipSubtree; + case Kwd(KwdTypedef) if (hasToken(TYPEDEF_DEF)): + FoundSkipSubtree; + default: + GoDeeper; + } + }); for (typeToken in typeTokens) { if (isPosSuppressed(typeToken.pos)) continue; - var fieldTokens:Array = typeToken.filter(fieldTokenDefs, FIRST); + var fieldTokens:Array = typeToken.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdVar) if ((fieldType == VARS) || (fieldType == BOTH)): + FoundSkipSubtree; + case Kwd(KwdFinal) if ((fieldType == VARS) || (fieldType == BOTH)): + FoundSkipSubtree; + case Kwd(KwdFunction) if ((fieldType == FUNCTIONS) || (fieldType == BOTH)): + FoundSkipSubtree; + default: + GoDeeper; + } + }); for (token in fieldTokens) { checkField(token, isDefaultPublic(typeToken)); } @@ -134,14 +142,28 @@ class FieldDocCommentCheck extends Check { function checkIgnoreOverride(token:TokenTree):Bool { if (!ignoreOverride) return false; - var ignoreTokens:Array = token.filter([Kwd(KwdOverride)], FIRST); + var ignoreTokens:Array = token.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdOverride): + FoundSkipSubtree; + default: + GoDeeper; + } + }); return (ignoreTokens.length > 0); } function matchesModifier(token:TokenTree, defaultPublic:Bool):Bool { if (modifier == BOTH) return true; - var modifierList:Array = token.filter([Kwd(KwdPublic), Kwd(KwdPrivate)], FIRST); + var modifierList:Array = token.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdPublic) | Kwd(KwdPrivate): + FoundSkipSubtree; + default: + GoDeeper; + } + }); var isPublic:Bool = defaultPublic; for (modToken in modifierList) { switch (modToken.tok) { @@ -198,7 +220,7 @@ class FieldDocCommentCheck extends Check { if (dblDotToken == null) { return; } - var identToken:TokenTree = access.firstChild().is(Const(CIdent("Void"))).token; + var identToken:TokenTree = access.firstChild().matches(Const(CIdent("Void"))).token; if (identToken != null) return; checkReturn(name, docToken, text); } @@ -313,8 +335,7 @@ class FieldDocCommentCheck extends Check { - FUNCTIONS = only functions; - BOTH = both vars and functions; **/ -@:enum -abstract FieldDocCommentType(String) { +enum abstract FieldDocCommentType(String) { var VARS = "VARS"; var FUNCTIONS = "FUNCTIONS"; var BOTH = "BOTH"; @@ -326,8 +347,7 @@ abstract FieldDocCommentType(String) { - PRIVATE = only private fields - BOTH = public and private fields **/ -@:enum -abstract FieldDocCommentModifier(String) { +enum abstract FieldDocCommentModifier(String) { var PUBLIC = "PUBLIC"; var PRIVATE = "PRIVATE"; var BOTH = "BOTH"; diff --git a/src/checkstyle/checks/comments/TypeDocCommentCheck.hx b/src/checkstyle/checks/comments/TypeDocCommentCheck.hx index 8afb09d1..07fc26ea 100644 --- a/src/checkstyle/checks/comments/TypeDocCommentCheck.hx +++ b/src/checkstyle/checks/comments/TypeDocCommentCheck.hx @@ -27,13 +27,23 @@ class TypeDocCommentCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var tokenList:Array = []; - if (hasToken(ABSTRACT_DEF)) tokenList.push(Kwd(KwdAbstract)); - if (hasToken(CLASS_DEF)) tokenList.push(Kwd(KwdClass)); - if (hasToken(ENUM_DEF)) tokenList.push(Kwd(KwdEnum)); - if (hasToken(INTERFACE_DEF)) tokenList.push(Kwd(KwdInterface)); - if (hasToken(TYPEDEF_DEF)) tokenList.push(Kwd(KwdTypedef)); - var docTokens = root.filter(tokenList, ALL); + + var docTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdAbstract) if (hasToken(ABSTRACT_DEF)): + FoundSkipSubtree; + case Kwd(KwdClass) if (hasToken(CLASS_DEF)): + FoundSkipSubtree; + case Kwd(KwdEnum) if (hasToken(ENUM_DEF)): + FoundSkipSubtree; + case Kwd(KwdInterface) if (hasToken(INTERFACE_DEF)): + FoundSkipSubtree; + case Kwd(KwdTypedef) if (hasToken(TYPEDEF_DEF)): + FoundSkipSubtree; + case _: + GoDeeper; + } + }); for (token in docTokens) { if (isPosSuppressed(token.pos)) continue; var name:String = getTypeName(token); @@ -69,15 +79,15 @@ class TypeDocCommentCheck extends Check { while (docToken != null) { switch (docToken.tok) { case Sharp(s): - var notAllowed:Array = docToken.filter([ - Kwd(KwdAbstract), - Kwd(KwdClass), - Kwd(KwdEnum), - Kwd(KwdInterface), - Kwd(KwdTypedef), - Kwd(KwdImport), - Kwd(KwdUsing) - ], FIRST); + var notAllowed:Array = docToken.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdAbstract) | Kwd(KwdClass) | Kwd(KwdEnum) | Kwd(KwdInterface) | Kwd(KwdTypedef) | Kwd(KwdImport) | Kwd(KwdUsing): + FoundSkipSubtree; + default: + GoDeeper; + } + }); + if (notAllowed.length > 0) { return null; } @@ -116,8 +126,7 @@ class TypeDocCommentCheck extends Check { } } -@:enum -abstract TypeDocCommentToken(String) { +enum abstract TypeDocCommentToken(String) { var ABSTRACT_DEF = "ABSTRACT_DEF"; var CLASS_DEF = "CLASS_DEF"; var ENUM_DEF = "ENUM_DEF"; diff --git a/src/checkstyle/checks/design/EmptyPackageCheck.hx b/src/checkstyle/checks/design/EmptyPackageCheck.hx index d63e1b97..84988d49 100644 --- a/src/checkstyle/checks/design/EmptyPackageCheck.hx +++ b/src/checkstyle/checks/design/EmptyPackageCheck.hx @@ -18,7 +18,16 @@ class EmptyPackageCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var packageTokens = root.filter([Kwd(KwdPackage)], ALL); + var packageTokens = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdPackage): + FoundSkipSubtree; + case Kwd(_): + SkipSubtree; + default: + GoDeeper; + } + }); if (enforceEmptyPackage) { if (packageTokens.length == 0) log("Missing package declaration", 1, 0, 1, 0, MISSING_PACKAGE); } @@ -28,7 +37,7 @@ class EmptyPackageCheck extends Check { function checkPackageNames(entries:Array) { for (entry in entries) { var firstChild = entry.getFirstChild(); - if (firstChild.is(Semicolon)) logRange("Found empty package", entry.pos.min, firstChild.pos.max, REDUNDANT_PACKAGE); + if (firstChild.matches(Semicolon)) logRange("Found empty package", entry.pos.min, firstChild.pos.max, REDUNDANT_PACKAGE); } } @@ -43,8 +52,7 @@ class EmptyPackageCheck extends Check { } } -@:enum -abstract EmptyPackageCode(String) to String { +enum abstract EmptyPackageCode(String) to String { var MISSING_PACKAGE = "MissingPackage"; var REDUNDANT_PACKAGE = "RedundantPackage"; } \ No newline at end of file diff --git a/src/checkstyle/checks/design/InterfaceCheck.hx b/src/checkstyle/checks/design/InterfaceCheck.hx index 1513f3d7..c10420bf 100644 --- a/src/checkstyle/checks/design/InterfaceCheck.hx +++ b/src/checkstyle/checks/design/InterfaceCheck.hx @@ -26,10 +26,31 @@ class InterfaceCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var interfaces:Array = root.filter([Kwd(KwdInterface)], ALL); + var interfaces:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdInterface): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (intr in interfaces) { - var functions:Array = intr.filter([Kwd(KwdFunction)], ALL); - var vars:Array = intr.filter([Kwd(KwdVar)], ALL); + var functions:Array = intr.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdFunction): + FoundGoDeeper; + default: + GoDeeper; + } + }); + var vars:Array = intr.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdVar): + FoundGoDeeper; + default: + GoDeeper; + } + }); if (functions.length == 0 && vars.length == 0) { if (allowMarkerInterfaces) continue; diff --git a/src/checkstyle/checks/design/UnnecessaryConstructorCheck.hx b/src/checkstyle/checks/design/UnnecessaryConstructorCheck.hx index f3a9dae7..7c50bace 100644 --- a/src/checkstyle/checks/design/UnnecessaryConstructorCheck.hx +++ b/src/checkstyle/checks/design/UnnecessaryConstructorCheck.hx @@ -13,27 +13,47 @@ class UnnecessaryConstructorCheck extends Check { } override function actualRun() { - var root:TokenTree = checker.getTokenTree(); - var classes:Array = root.filter([Kwd(KwdClass)], ALL); + var classes:Array = findClasses(); for (cls in classes) { - if (extendsBaseClass(cls)) { - continue; - } + if (extendsBaseClass(cls)) continue; if (isPosSuppressed(cls.pos)) continue; - var acceptableTokens:Array = cls.filter([Kwd(KwdFunction), Kwd(KwdVar)], FIRST); + var acceptableTokens:Array = cls.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdFunction) | Kwd(KwdVar): + FoundSkipSubtree; + default: + GoDeeper; + } + }); var haveConstructor:Bool = false; var staticTokens:Int = 0; var constructorPos = null; for (token in acceptableTokens) { - if (token.filter([Kwd(KwdNew)], FIRST, 2).length > 0) { + if (token.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + if (depth > 2) return SkipSubtree; + return switch (token.tok) { + case Kwd(KwdNew): + FoundSkipSubtree; + default: + GoDeeper; + } + }).length > 0) { haveConstructor = true; constructorPos = token.getPos(); continue; } - if (token.filter([Kwd(KwdStatic)], FIRST, 2).length > 0) { + if (token.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + if (depth > 2) return SkipSubtree; + return switch (token.tok) { + case Kwd(KwdStatic): + FoundSkipSubtree; + default: + GoDeeper; + } + }).length > 0) { staticTokens++; continue; } @@ -45,10 +65,21 @@ class UnnecessaryConstructorCheck extends Check { } } + function findClasses():Array { + return checker.getTokenTree().filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdClass): + FoundGoDeeper; + default: + GoDeeper; + } + }); + } + function extendsBaseClass(cls:TokenTree):Bool { var clsName:TokenTree = cls.getFirstChild(); for (child in clsName.children) { - if (child.is(Kwd(KwdExtends))) { + if (child.matches(Kwd(KwdExtends))) { return true; } } diff --git a/src/checkstyle/checks/import.hx b/src/checkstyle/checks/import.hx new file mode 100644 index 00000000..30322b3a --- /dev/null +++ b/src/checkstyle/checks/import.hx @@ -0,0 +1,3 @@ +package checkstyle.checks; + +import checkstyle.SeverityLevel; \ No newline at end of file diff --git a/src/checkstyle/checks/imports/AvoidStarImportCheck.hx b/src/checkstyle/checks/imports/AvoidStarImportCheck.hx index 1b31c493..49ad5db9 100644 --- a/src/checkstyle/checks/imports/AvoidStarImportCheck.hx +++ b/src/checkstyle/checks/imports/AvoidStarImportCheck.hx @@ -14,12 +14,29 @@ class AvoidStarImportCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - checkImports(root.filter([Kwd(KwdImport)], ALL)); + checkImports(root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdImport): + FoundSkipSubtree; + case Kwd(_): + SkipSubtree; + default: + GoDeeper; + } + })); } function checkImports(importEntries:Array) { for (entry in importEntries) { - var stars:Array = entry.filter([Binop(OpMult)], ALL); + var stars:Array = entry.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Binop(OpMult): + FoundGoDeeper; + default: + GoDeeper; + } + }); + if (stars.length <= 0) continue; logPos('Using the ".*" form of import should be avoided', entry.getPos()); } diff --git a/src/checkstyle/checks/imports/UnusedImportCheck.hx b/src/checkstyle/checks/imports/UnusedImportCheck.hx index 7cac6f0f..9251931d 100644 --- a/src/checkstyle/checks/imports/UnusedImportCheck.hx +++ b/src/checkstyle/checks/imports/UnusedImportCheck.hx @@ -1,7 +1,7 @@ package checkstyle.checks.imports; -import tokentree.utils.TokenTreeCheckUtils; import haxe.io.Path; +import tokentree.utils.TokenTreeCheckUtils; /** Checks for unused or duplicate imports. @@ -33,24 +33,24 @@ class UnusedImportCheck extends Check { if (isImportHx()) return; var root:TokenTree = checker.getTokenTree(); var packageName:String = detectPackageName(root); - var imports:Array = root.filter([Kwd(KwdImport)], ALL); + var imports:Array = findImports(root); var idents:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { switch (token.tok) { case Const(CIdent(_)): - if (TokenTreeCheckUtils.isImport(token)) return GO_DEEPER; - return FOUND_GO_DEEPER; + if (TokenTreeCheckUtils.isImport(token)) return GoDeeper; + return FoundGoDeeper; default: } - return GO_DEEPER; + return GoDeeper; }); var stringLiterals:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { switch (token.tok) { case Const(CString(text)): - if (checker.getString(token.pos.min, token.pos.min + 1) != "'") return GO_DEEPER; - if (~/\$\{[^\}]+\.[^\}]+\}/.match(text)) return FOUND_GO_DEEPER; + if (checker.getString(token.pos.min, token.pos.min + 1) != "'") return GoDeeper; + if (~/\$\{[^\}]+\.[^\}]+\}/.match(text)) return FoundGoDeeper; default: } - return GO_DEEPER; + return GoDeeper; }); for (imp in imports) { var typeName:String = detectTypeName(imp); @@ -77,13 +77,34 @@ class UnusedImportCheck extends Check { } } + function findImports(root:TokenTree):Array { + return root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdImport): + if (TokenTreeCheckUtils.isMetadata(token)) { + return SkipSubtree; + } + FoundGoDeeper; + default: + GoDeeper; + } + }); + } + function isImportHx():Bool { var fileName:String = Path.withoutDirectory(checker.file.name); return fileName == "import.hx"; } function detectPackageName(root:TokenTree):String { - var packageToken:Array = root.filter([Kwd(KwdPackage)], ALL); + var packageToken:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdPackage): + FoundGoDeeper; + default: + GoDeeper; + } + }); if ((packageToken == null) || (packageToken.length <= 0)) return null; var packageName:String = detectModuleName(packageToken[0]); @@ -98,6 +119,7 @@ class UnusedImportCheck extends Check { var moduleName:StringBuf = new StringBuf(); while (true) { + if (token == null) return moduleName.toString(); switch (token.tok) { case Binop(OpMult): return null; @@ -105,15 +127,9 @@ class UnusedImportCheck extends Check { case Kwd(KwdPackage): case Semicolon: return moduleName.toString(); - #if (haxe_ver < 4.0) - case Kwd(KwdIn): - if (token.parent.tok.match(Dot)) moduleName.add(token.toString()); - else moduleName.add(" in "); - #else - case Binop(OpIn): + case Kwd(KwdIn) | Binop(OpIn): if (token.parent.tok.match(Dot)) moduleName.add(token.toString()); else moduleName.add(" in "); - #end case Const(CIdent("as")): if (token.parent.tok.match(Dot)) moduleName.add(token.toString()); else moduleName.add(" as "); @@ -128,6 +144,7 @@ class UnusedImportCheck extends Check { function detectTypeName(token:TokenTree):String { var lastName:String = null; while (true) { + if (token == null) return lastName; switch (token.tok) { case Binop(OpMult): return null; @@ -211,8 +228,7 @@ class UnusedImportCheck extends Check { } } -@:enum -abstract UnusedImportCode(String) to String { +enum abstract UnusedImportCode(String) to String { var UNUSED_IMPORT = "UnusedImport"; var TOPLEVEL_IMPORT = "ToplevelImport"; var SAME_PACKAGE = "SamePackage"; diff --git a/src/checkstyle/checks/literal/HexadecimalLiteralCheck.hx b/src/checkstyle/checks/literal/HexadecimalLiteralCheck.hx index f029357c..02d44f77 100644 --- a/src/checkstyle/checks/literal/HexadecimalLiteralCheck.hx +++ b/src/checkstyle/checks/literal/HexadecimalLiteralCheck.hx @@ -48,8 +48,7 @@ class HexadecimalLiteralCheck extends Check { - upperCase = use uppercase for all letters - lowerCase = use lowercase for all letters **/ -@:enum -abstract HexadecimalLiteralPolicy(String) { +enum abstract HexadecimalLiteralPolicy(String) { var UPPER_CASE = "upperCase"; var LOWER_CASE = "lowerCase"; } \ No newline at end of file diff --git a/src/checkstyle/checks/literal/MultipleStringLiteralsCheck.hx b/src/checkstyle/checks/literal/MultipleStringLiteralsCheck.hx index 2748e8ff..478d4b57 100644 --- a/src/checkstyle/checks/literal/MultipleStringLiteralsCheck.hx +++ b/src/checkstyle/checks/literal/MultipleStringLiteralsCheck.hx @@ -41,10 +41,9 @@ class MultipleStringLiteralsCheck extends Check { var allLiterals:Map = new Map(); var allStringLiterals:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { - if (token.tok == null) return GO_DEEPER; return switch (token.tok) { - case Const(CString(_)): FOUND_GO_DEEPER; - default: GO_DEEPER; + case Const(CString(_)): FoundGoDeeper; + default: GoDeeper; } }); @@ -74,10 +73,18 @@ class MultipleStringLiteralsCheck extends Check { } function filterLiteral(token:TokenTree):Bool { - if ((token == null) || (token.tok == null)) return true; + if ((token == null) || (token.tok == Root)) return true; return switch (token.tok) { case At: false; - case Kwd(KwdVar): !(token.filter([Kwd(KwdStatic)], FIRST).length > 0); + case Kwd(KwdVar): !(token.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdStatic): + FoundSkipSubtree; + default: + GoDeeper; + } + }).length > 0); + default: filterLiteral(token.parent); } } diff --git a/src/checkstyle/checks/literal/StringLiteralCheck.hx b/src/checkstyle/checks/literal/StringLiteralCheck.hx index c0b0065f..d273fa01 100644 --- a/src/checkstyle/checks/literal/StringLiteralCheck.hx +++ b/src/checkstyle/checks/literal/StringLiteralCheck.hx @@ -33,10 +33,9 @@ class StringLiteralCheck extends Check { var root:TokenTree = checker.getTokenTree(); var allStringLiterals:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { - if (token.tok == null) return GO_DEEPER; return switch (token.tok) { - case Const(CString(_)): FOUND_GO_DEEPER; - default: GO_DEEPER; + case Const(CString(_)): FoundGoDeeper; + default: GoDeeper; } }); @@ -84,15 +83,13 @@ class StringLiteralCheck extends Check { } } -@:enum -abstract StringLiteralPolicy(String) { +enum abstract StringLiteralPolicy(String) { var ONLY_SINGLE = "onlySingle"; var ONLY_DOUBLE = "onlyDouble"; var DOUBLE_AND_INTERPOLATION = "doubleAndInterpolation"; } -@:enum -abstract StringLiteralCode(String) to String { +enum abstract StringLiteralCode(String) to String { var USE_DOUBLE_QUOTES = "UseDoubleQuotes"; var USE_SINGLE_QUOTES = "UseSingleQuotes"; } \ No newline at end of file diff --git a/src/checkstyle/checks/meta/RedundantAccessMetaBase.hx b/src/checkstyle/checks/meta/RedundantAccessMetaBase.hx index fdbeb503..697ba992 100644 --- a/src/checkstyle/checks/meta/RedundantAccessMetaBase.hx +++ b/src/checkstyle/checks/meta/RedundantAccessMetaBase.hx @@ -22,7 +22,14 @@ class RedundantAccessMetaBase extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var docTokens = root.filter([At], ALL); + var docTokens = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case At: + FoundGoDeeper; + default: + GoDeeper; + } + }); var infos:Array = []; @@ -30,11 +37,11 @@ class RedundantAccessMetaBase extends Check { if (isPosSuppressed(token.pos)) continue; var target:TokenTree = TokenTreeAccessHelper.access(token) .firstChild() - .is(DblDot) + .matches(DblDot) .firstChild() - .is(Const(CIdent(metaName))) + .matches(Const(CIdent(metaName))) .firstChild() - .is(POpen) + .matches(POpen) .firstChild() .token; diff --git a/src/checkstyle/checks/metrics/CyclomaticComplexityCheck.hx b/src/checkstyle/checks/metrics/CyclomaticComplexityCheck.hx index 01ce1867..7638a911 100644 --- a/src/checkstyle/checks/metrics/CyclomaticComplexityCheck.hx +++ b/src/checkstyle/checks/metrics/CyclomaticComplexityCheck.hx @@ -75,9 +75,6 @@ class CyclomaticComplexityCheck extends Check { return total + evaluateExpr(e); }, 0); case ExprDef.EFor(it, e): 1 + evaluateExpr(it) + evaluateExpr(e); - #if (haxe_ver < 4.0) - case ExprDef.EIn(e1, e2): evaluateExpr(e1) + evaluateExpr(e2); - #end case ExprDef.EIf(econd, eif, eelse): 1 + evaluateExpr(econd) + evaluateExpr(eif) + evaluateExpr(eelse); case ExprDef.EWhile(econd, e, _): 1 + evaluateExpr(econd) + evaluateExpr(e); case ExprDef.ESwitch(e, cases, def): diff --git a/src/checkstyle/checks/modifier/FinalCheck.hx b/src/checkstyle/checks/modifier/FinalCheck.hx index 416e6b6a..1dba897f 100644 --- a/src/checkstyle/checks/modifier/FinalCheck.hx +++ b/src/checkstyle/checks/modifier/FinalCheck.hx @@ -56,8 +56,7 @@ class FinalCheck extends Check { } } -@:enum -abstract FinalCode(String) to String { +enum abstract FinalCode(String) to String { var USE_INLINE_FINAL = "UseInlineFinal"; var SHOULD_BE_PUBLIC_FINAL = "ShouldBePublicFinal"; } diff --git a/src/checkstyle/checks/modifier/ModifierOrderCheck.hx b/src/checkstyle/checks/modifier/ModifierOrderCheck.hx index e4581f3d..781791ef 100644 --- a/src/checkstyle/checks/modifier/ModifierOrderCheck.hx +++ b/src/checkstyle/checks/modifier/ModifierOrderCheck.hx @@ -15,10 +15,7 @@ class ModifierOrderCheck extends Check { public function new() { super(AST); - modifiers = [MACRO, OVERRIDE, PUBLIC_PRIVATE, STATIC, INLINE, DYNAMIC]; - #if haxe4 - modifiers.push(FINAL); - #end + modifiers = [MACRO, OVERRIDE, PUBLIC_PRIVATE, STATIC, INLINE, DYNAMIC, FINAL]; categories = [Category.STYLE, Category.CLARITY]; } @@ -32,11 +29,7 @@ class ModifierOrderCheck extends Check { var actual:Array = []; var expected:Array = []; - #if haxe4 expected.resize(modifiers.length); - #else - for (mod in modifiers) expected.push(null); - #end var compliant:Bool = true; @@ -85,17 +78,19 @@ class ModifierOrderCheck extends Check { - EXTERN = extern modifier - FINAL = final modifier **/ -@:enum -abstract ModifierOrderCheckModifier(String) { +enum abstract ModifierOrderCheckModifier(String) { var PUBLIC_PRIVATE = "PUBLIC_PRIVATE"; var INLINE = "INLINE"; var STATIC = "STATIC"; var OVERRIDE = "OVERRIDE"; var MACRO = "MACRO"; var DYNAMIC = "DYNAMIC"; - #if haxe4 var EXTERN = "EXTERN"; var FINAL = "FINAL"; + var ABSTRACT = "ABSTRACT"; + var OVERLOAD = "OVERLOAD"; + #if (haxe >= version("5.0.0-alpha")) + var ENUM = "ENUM"; #end @:from @@ -107,9 +102,12 @@ abstract ModifierOrderCheckModifier(String) { case AOverride: OVERRIDE; case AMacro: MACRO; case ADynamic: DYNAMIC; - #if haxe4 case AExtern: EXTERN; case AFinal: FINAL; + case AAbstract: ABSTRACT; + case AOverload: OVERLOAD; + #if (haxe >= version("5.0.0-alpha")) + case AEnum: ENUM; #end } } @@ -123,9 +121,12 @@ abstract ModifierOrderCheckModifier(String) { case AOverride: "override"; case AMacro: "macro"; case ADynamic: "dynamic"; - #if haxe4 case AExtern: "extern"; case AFinal: "final"; + case AAbstract: "abstract"; + case AOverload: "overload"; + #if (haxe >= version("5.0.0-alpha")) + case AEnum: "enum"; #end } } diff --git a/src/checkstyle/checks/modifier/RedundantModifierCheck.hx b/src/checkstyle/checks/modifier/RedundantModifierCheck.hx index 8f0ece20..39c9afa4 100644 --- a/src/checkstyle/checks/modifier/RedundantModifierCheck.hx +++ b/src/checkstyle/checks/modifier/RedundantModifierCheck.hx @@ -80,8 +80,7 @@ class RedundantModifierCheck extends Check { } } -@:enum -abstract RedundantModifierCode(String) to String { +enum abstract RedundantModifierCode(String) to String { var MISSING_PUBLIC = "MissingPublic"; var MISSING_PRIVATE = "MissingPrivate"; var REDUNDANT_PUBLIC = "RedundantPublic"; diff --git a/src/checkstyle/checks/naming/CatchParameterNameCheck.hx b/src/checkstyle/checks/naming/CatchParameterNameCheck.hx index 3f2b3b85..86ceb6f8 100644 --- a/src/checkstyle/checks/naming/CatchParameterNameCheck.hx +++ b/src/checkstyle/checks/naming/CatchParameterNameCheck.hx @@ -19,7 +19,14 @@ class CatchParameterNameCheck extends Check { override function actualRun() { var formatRE = new EReg(format, ""); var root:TokenTree = checker.getTokenTree(); - var catchTokens = root.filter([Kwd(KwdCatch)], ALL); + var catchTokens = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdCatch): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (tkn in catchTokens) { for (item in tkn.children) { @@ -27,7 +34,7 @@ class CatchParameterNameCheck extends Check { if (child == null) continue; switch (child.tok) { case Const(CIdent(name)): - if (item.is(POpen)) { + if (item.matches(POpen)) { if (!formatRE.match(name)) logPos('"$name" must match pattern "~/${format}/"', item.pos); continue; } diff --git a/src/checkstyle/checks/naming/ConstantNameCheck.hx b/src/checkstyle/checks/naming/ConstantNameCheck.hx index 0e942f45..33606ed1 100644 --- a/src/checkstyle/checks/naming/ConstantNameCheck.hx +++ b/src/checkstyle/checks/naming/ConstantNameCheck.hx @@ -24,7 +24,7 @@ class ConstantNameCheck extends NameCheckBase { checkFields(d.data, decl.toParentType()); } - override function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) {} + override function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) {} function checkFields(d:Array, p:ParentType) { for (field in d) { @@ -81,14 +81,12 @@ class ConstantNameCheck extends NameCheckBase { - INLINE = "static inline var" - NOTINLINE = "static var" **/ -@:enum -abstract ConstantNameCheckToken(String) { +enum abstract ConstantNameCheckToken(String) { var INLINE = "INLINE"; var NOTINLINE = "NOTINLINE"; } -@:enum -abstract ConstantNameCheckFormt(String) to String { +enum abstract ConstantNameCheckFormt(String) to String { var UPPER_CASE = "^[A-Z][A-Z0-9]*(_[A-Z0-9_]+)*$"; var CAMEL_CASE = "^[A-Z]+[a-zA-Z0-9]*$"; var LOWER_CASE = "^[a-z][a-zA-Z0-9]*$"; diff --git a/src/checkstyle/checks/naming/FileNameCaseCheck.hx b/src/checkstyle/checks/naming/FileNameCaseCheck.hx new file mode 100644 index 00000000..022b229b --- /dev/null +++ b/src/checkstyle/checks/naming/FileNameCaseCheck.hx @@ -0,0 +1,86 @@ +package checkstyle.checks.naming; + +import haxe.io.Path; + +/** + Checks that file names match the case of their module name. +**/ +@name("FileNameCase") +@desc("Checks that file names match the case of their module name.") +class FileNameCaseCheck extends Check { + public function new() { + super(TOKEN); + } + + override function actualRun() { + var fileName:String = Path.withoutDirectory(checker.file.name); + fileName = Path.withoutExtension(fileName); + checkFile(fileName, checker); + } + + function checkFile(fileName:String, checker:Checker) { + var types:Array = getTypes(checker.getTokenTree()); + var lowerFileName:String = fileName.toLowerCase(); + if (fileName == "import") { + if (types.length <= 0) { + return; + } + log('"import.hx" contains types', 0, 0, 0, 0); + return; + } + if ((lowerFileName == "import") && (types.length == 0)) { + // ImPort.hx with types + log('"$fileName.hx" contains no types - consider renaming to "import.hx"', 0, 0, 0, 0); + return; + } + if (!types.contains(fileName)) { + for (type in types) { + var lowerType:String = type.toLowerCase(); + if (lowerType == lowerFileName) { + log('"$fileName.hx" defines type "$type" using different case', 0, 0, 0, 0); + } + } + log('"$fileName.hx" defines no type with name "$fileName"', 0, 0, 0, 0); + return; + } + } + + function getTypes(token:TokenTree):Array { + var types:Array = checker.getTokenTree().filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdAbstract) | Kwd(KwdClass) | Kwd(KwdEnum) | Kwd(KwdInterface) | Kwd(KwdTypedef): + FoundSkipSubtree; + default: + GoDeeper; + } + }); + var typeNames:Array = []; + for (type in types) { + switch (type.tok) { + case Kwd(KwdAbstract) | Kwd(KwdClass) | Kwd(KwdEnum) | Kwd(KwdInterface) | Kwd(KwdTypedef): + var child:Null = type.getFirstChild(); + if (child == null) { + continue; + } + switch (child.tok) { + case Const(CIdent(s)): + typeNames.push(s); + default: + } + default: + } + } + + return typeNames; + } + + override public function detectableInstances():DetectableInstances { + return [{ + fixed: [], + properties: [{ + propertyName: "severity", + values: [SeverityLevel.WARNING] + }] + }]; + } +} \ No newline at end of file diff --git a/src/checkstyle/checks/naming/MemberNameCheck.hx b/src/checkstyle/checks/naming/MemberNameCheck.hx index 9d31c7b6..a5c92d87 100644 --- a/src/checkstyle/checks/naming/MemberNameCheck.hx +++ b/src/checkstyle/checks/naming/MemberNameCheck.hx @@ -37,9 +37,9 @@ class MemberNameCheck extends NameCheckBase { checkFields(d.data, decl.toParentType()); } - override function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) { + override function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) { if (!hasToken(TYPEDEF)) return; - if (ignoreExtern && d.flags.contains(EExtern)) return; + if (ignoreExtern && d.flags.contains(TDExtern)) return; switch (d.data) { case TAnonymous(f): @@ -101,8 +101,7 @@ class MemberNameCheck extends NameCheckBase { - ABSTRACT = all abstract fields, use in combination with PUBLIC and PRIVATE to only match public/private abstract fields - TYPEDEF = all typedef fields **/ -@:enum -abstract MemberNameCheckToken(String) { +enum abstract MemberNameCheckToken(String) { var PUBLIC = "PUBLIC"; var PRIVATE = "PRIVATE"; var ENUM = "ENUM"; diff --git a/src/checkstyle/checks/naming/MethodNameCheck.hx b/src/checkstyle/checks/naming/MethodNameCheck.hx index fb0e03fa..b993e733 100644 --- a/src/checkstyle/checks/naming/MethodNameCheck.hx +++ b/src/checkstyle/checks/naming/MethodNameCheck.hx @@ -21,8 +21,8 @@ class MethodNameCheck extends NameCheckBase { checkFields(d.data, decl.toParentType()); } - override function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) { - if (ignoreExtern && d.flags.contains(EExtern)) return; + override function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) { + if (ignoreExtern && d.flags.contains(TDExtern)) return; var p = decl.toParentType(); switch (d.data) { @@ -65,8 +65,7 @@ class MethodNameCheck extends NameCheckBase { - INLINE = all inline methods - NOTINLINE = all non-inline methods **/ -@:enum -abstract MethodNameCheckToken(String) { +enum abstract MethodNameCheckToken(String) { var PUBLIC = "PUBLIC"; var PRIVATE = "PRIVATE"; var STATIC = "STATIC"; diff --git a/src/checkstyle/checks/naming/NameCheckBase.hx b/src/checkstyle/checks/naming/NameCheckBase.hx index c39868e8..2b27f756 100644 --- a/src/checkstyle/checks/naming/NameCheckBase.hx +++ b/src/checkstyle/checks/naming/NameCheckBase.hx @@ -62,7 +62,7 @@ class NameCheckBase extends Check { function checkAbstractType(decl:TypeDef, d:Definition>, pos:Position) {} - function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) {} + function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) {} function matchTypeName(type:String, name:String, pos:Position) { if (!formatRE.match(name)) { diff --git a/src/checkstyle/checks/naming/ParameterNameCheck.hx b/src/checkstyle/checks/naming/ParameterNameCheck.hx index 43851530..0d7bf0f5 100644 --- a/src/checkstyle/checks/naming/ParameterNameCheck.hx +++ b/src/checkstyle/checks/naming/ParameterNameCheck.hx @@ -25,8 +25,8 @@ class ParameterNameCheck extends NameCheckBase { checkFields(d.data); } - override function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) { - if (ignoreExtern && d.flags.contains(EExtern)) return; + override function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) { + if (ignoreExtern && d.flags.contains(TDExtern)) return; switch (d.data) { case TAnonymous(f): checkFields(f); diff --git a/src/checkstyle/checks/naming/TypeNameCheck.hx b/src/checkstyle/checks/naming/TypeNameCheck.hx index b964a1f5..8e21edfa 100644 --- a/src/checkstyle/checks/naming/TypeNameCheck.hx +++ b/src/checkstyle/checks/naming/TypeNameCheck.hx @@ -38,9 +38,9 @@ class TypeNameCheck extends NameCheckBase { matchTypeName("abstract", d.name, pos); } - override function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) { + override function checkTypedefType(decl:TypeDef, d:Definition, pos:Position) { if (!hasToken(TYPEDEF)) return; - if (ignoreExtern && d.flags.contains(EExtern)) return; + if (ignoreExtern && d.flags.contains(TDExtern)) return; matchTypeName("typedef", d.name, pos); } @@ -54,8 +54,7 @@ class TypeNameCheck extends NameCheckBase { - ABSTRACT = all abstract types - TYPEDEF = all typedef types **/ -@:enum -abstract TypeNameCheckToken(String) { +enum abstract TypeNameCheckToken(String) { var INTERFACE = "INTERFACE"; var CLASS = "CLASS"; var ENUM = "ENUM"; diff --git a/src/checkstyle/checks/size/MethodCountCheck.hx b/src/checkstyle/checks/size/MethodCountCheck.hx index 5b4033af..4a9c7759 100644 --- a/src/checkstyle/checks/size/MethodCountCheck.hx +++ b/src/checkstyle/checks/size/MethodCountCheck.hx @@ -34,7 +34,14 @@ class MethodCountCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var acceptableTokens:Array = root.filter([Kwd(KwdFunction)], FIRST); + var acceptableTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdFunction): + FoundSkipSubtree; + default: + GoDeeper; + } + }); if (acceptableTokens.length > maxTotal) { logPos('Total number of methods is ${acceptableTokens.length} (max allowed is $maxTotal)', acceptableTokens[maxTotal].pos); @@ -44,8 +51,19 @@ class MethodCountCheck extends Check { var privateTokens = []; var publicTokens = []; for (token in acceptableTokens) { - if (token.filter([Kwd(KwdPublic)], FIRST).length > 0) publicTokens.push(token); - else privateTokens.push(token); + if (token.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdPublic): + FoundSkipSubtree; + default: + GoDeeper; + } + }).length > 0) { + publicTokens.push(token); + } + else { + privateTokens.push(token); + } } if (privateTokens.length > maxPrivate) { diff --git a/src/checkstyle/checks/size/MethodLengthCheck.hx b/src/checkstyle/checks/size/MethodLengthCheck.hx index e22d4566..8be89f45 100755 --- a/src/checkstyle/checks/size/MethodLengthCheck.hx +++ b/src/checkstyle/checks/size/MethodLengthCheck.hx @@ -32,7 +32,14 @@ class MethodLengthCheck extends Check { override public function actualRun() { var root:TokenTree = checker.getTokenTree(); - var functions:Array = root.filter([Kwd(KwdFunction)], FIRST); + var functions:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdFunction): + FoundSkipSubtree; + default: + GoDeeper; + } + }); var emptyLines:ListOfEmptyLines = ListOfEmptyLines.detectEmptyLines(checker); for (func in functions) { diff --git a/src/checkstyle/checks/type/AvoidIdentifierCheck.hx b/src/checkstyle/checks/type/AvoidIdentifierCheck.hx index 00608b40..bf8e5872 100644 --- a/src/checkstyle/checks/type/AvoidIdentifierCheck.hx +++ b/src/checkstyle/checks/type/AvoidIdentifierCheck.hx @@ -24,7 +24,7 @@ class AvoidIdentifierCheck extends Check { checkIdent(ident, token); default: } - return GO_DEEPER; + return GoDeeper; }); } diff --git a/src/checkstyle/checks/type/DynamicCheck.hx b/src/checkstyle/checks/type/DynamicCheck.hx index 02ff2603..4f295bc1 100644 --- a/src/checkstyle/checks/type/DynamicCheck.hx +++ b/src/checkstyle/checks/type/DynamicCheck.hx @@ -17,11 +17,11 @@ class DynamicCheck extends Check { root.filterCallback(function(token:TokenTree, index:Int):FilterResult { switch token.tok { case Const(CIdent("Dynamic")): - if (isPosSuppressed(token.pos)) return SKIP_SUBTREE; + if (isPosSuppressed(token.pos)) return SkipSubtree; logPos('Avoid using "Dynamic" as type', token.pos); - return SKIP_SUBTREE; + return SkipSubtree; default: - return GO_DEEPER; + return GoDeeper; } }); } diff --git a/src/checkstyle/checks/type/EnforceVarTypeHintCheck.hx b/src/checkstyle/checks/type/EnforceVarTypeHintCheck.hx deleted file mode 100644 index 93b7dfd0..00000000 --- a/src/checkstyle/checks/type/EnforceVarTypeHintCheck.hx +++ /dev/null @@ -1,76 +0,0 @@ -package checkstyle.checks.type; - -/** - Checks if type is specified or not for member variables. -**/ -@name("EnforceVarTypeHint") -@desc("Checks if all variables have type hint.") -class EnforceVarTypeHintCheck extends Check { - /** - ignores fields inside abstract enums - **/ - public var ignoreEnumAbstractValues:Bool; - - public function new() { - super(TOKEN); - ignoreEnumAbstractValues = true; - categories = [CLARITY, BUG_RISK]; - } - - override function actualRun() { - var root:TokenTree = checker.getTokenTree(); - root.filterCallback(function(token:TokenTree, index:Int):FilterResult { - switch (token.tok) { - #if haxe4 - case Kwd(KwdFinal): - checkVar(token); - return SKIP_SUBTREE; - #else - case Const(CIdent("final")): - checkVar(token); - return SKIP_SUBTREE; - #end - case Kwd(KwdVar): - checkVar(token); - return SKIP_SUBTREE; - default: - return GO_DEEPER; - } - }); - } - - function checkVar(token:TokenTree) { - if (isPosSuppressed(token.pos)) return; - var name:Null = token.access().firstChild().token; - if (name == null) return; - var colon:Null = name.access().firstOf(DblDot).token; - if (colon != null) return; - if (ignoreEnumAbstractValues && isEnumAbstractValue(token)) return; - error(name.toString(), name.pos); - } - - function isEnumAbstractValue(token:TokenTree):Bool { - var parent:Null = token.parent; - while ((parent != null) && (parent.tok != null)) { - switch (parent.tok) { - case Kwd(KwdAbstract): - return TokenTreeCheckUtils.isTypeEnumAbstract(parent); - case Kwd(KwdInterface): - return false; - case Kwd(KwdClass): - return false; - case Kwd(KwdEnum): - return false; - case Kwd(KwdTypedef): - return false; - default: - } - parent = parent.parent; - } - return false; - } - - function error(name:String, pos:Position) { - logPos('Variable "${name}" has no type hint', pos); - } -} \ No newline at end of file diff --git a/src/checkstyle/checks/type/ReturnCheck.hx b/src/checkstyle/checks/type/ReturnCheck.hx index b343a901..ee6655d6 100644 --- a/src/checkstyle/checks/type/ReturnCheck.hx +++ b/src/checkstyle/checks/type/ReturnCheck.hx @@ -32,12 +32,12 @@ class ReturnCheck extends Check { override function actualRun() { forEachField(function(field, parent) { - if (!field.isConstructor() && parent.kind != INTERFACE) checkField(field); + if (!field.isConstructor() && parent.kind != INTERFACE) checkField(field, parent); }); checkInlineFunctions(); } - function checkField(f:Field) { + function checkField(f:Field, p:ParentType) { if (isPosExtern(f.pos)) return; var noReturn = false; switch (f.kind) { @@ -51,7 +51,7 @@ class ReturnCheck extends Check { if (!noReturn) { switch (fun.ret) { case TPath(val): - if (!enforceReturnType && Std.string(val.name) == "Void") warnVoid(f.name, f.pos); + if (!enforceReturnType && Std.string(val.name) == "Void" && !f.isAbstract(p)) warnVoid(f.name, f.pos); default: } } @@ -65,11 +65,6 @@ class ReturnCheck extends Check { if (checker.ast == null) return; checker.ast.walkFile(function(e) { switch (e.expr) { - #if (haxe_ver < 4.0) - case EFunction(fname, f): - var funNoReturn:Bool = (f.ret == null); - walkExpr(f.expr, funNoReturn, fname, e.pos); - #else case EFunction(kind, f): var name:Null = switch (kind) { case null: null; @@ -79,7 +74,6 @@ class ReturnCheck extends Check { } var funNoReturn:Bool = (f.ret == null); walkExpr(f.expr, funNoReturn, name, e.pos); - #end default: } }); diff --git a/src/checkstyle/checks/type/VarTypeHintCheck.hx b/src/checkstyle/checks/type/VarTypeHintCheck.hx new file mode 100644 index 00000000..1dd1b177 --- /dev/null +++ b/src/checkstyle/checks/type/VarTypeHintCheck.hx @@ -0,0 +1,144 @@ +package checkstyle.checks.type; + +/** + Checks if type is specified or not for member variables. +**/ +@name("VarTypeHint", "EnforceVarTypeHint") +@desc("Checks type hints of variables.") +class VarTypeHintCheck extends Check { + /** + policy for type hints on var and final + **/ + public var typeHintPolicy:VarTypeHintPolicy; + + /** + ignores fields inside abstract enums + **/ + public var ignoreEnumAbstractValues:Bool; + + public function new() { + super(TOKEN); + typeHintPolicy = INFER_NEW_OR_CONST; + ignoreEnumAbstractValues = true; + categories = [CLARITY, BUG_RISK]; + } + + override function actualRun() { + var root:TokenTree = checker.getTokenTree(); + var varList:Array = root.filterCallback(function(token:TokenTree, index:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdFinal): + FoundSkipSubtree; + case Kwd(KwdVar): + FoundSkipSubtree; + default: + return GoDeeper; + } + }); + for (v in varList) { + checkVar(v); + } + } + + function checkVar(token:TokenTree) { + if (isPosSuppressed(token.pos)) return; + if (!token.hasChildren()) return; + + for (child in token.children) { + checkVarName(child); + } + } + + function checkVarName(name:TokenTree) { + if (ignoreEnumAbstractValues && isEnumAbstractValue(name)) return; + switch (name.tok) { + case Root: + return; + case Question: + checkVarName(name.getFirstChild()); + return; + default: + } + var colon:Null = name.access().firstOf(DblDot).token; + var opAssign:Null = name.access().firstOf(Binop(OpAssign)).token; + var hasNewOrConst:Bool = detectNewOrConst(opAssign); + switch (typeHintPolicy) { + case ENFORCE_ALL: + if (colon == null) needsTypeHint(name.toString(), name.pos); + + case INFER_NEW_OR_CONST if (opAssign == null): + if (colon != null) return; + needsTypeHint(name.toString(), name.pos); + case INFER_NEW_OR_CONST if (colon == null): + if (hasNewOrConst) return; + needsTypeHint(name.toString(), name.pos); + case INFER_NEW_OR_CONST: + if (!hasNewOrConst) return; + noTypeHintNeeded(name.toString(), name.pos); + + case INFER_ALL if (opAssign == null): + if (colon != null) return; + needsTypeHint(name.toString(), name.pos); + case INFER_ALL: + if (colon != null) noTypeHintNeeded(name.toString(), name.pos); + } + } + + function detectNewOrConst(token:TokenTree):Bool { + if (token == null) return false; + for (child in token.children) { + switch (child.tok) { + case Const(CString(_)) | Const(CInt(_)) | Const(CFloat(_)) | Const(CRegexp(_)): + return true; + case Kwd(KwdTrue) | Kwd(KwdFalse): + return true; + case Kwd(KwdNew): + return true; + case Semicolon: + return false; + default: + } + } + return false; + } + + function isEnumAbstractValue(token:TokenTree):Bool { + var parent:Null = token.parent; + while ((parent != null) && (parent.tok != Root)) { + switch (parent.tok) { + case Kwd(KwdAbstract): + return TokenTreeCheckUtils.isTypeEnumAbstract(parent); + case Kwd(KwdInterface): + return false; + case Kwd(KwdClass): + return false; + case Kwd(KwdEnum): + return false; + case Kwd(KwdTypedef): + return false; + default: + } + parent = parent.parent; + } + return false; + } + + function needsTypeHint(name:String, pos:Position) { + logPos('"${name}" should have a type hint', pos); + } + + function noTypeHintNeeded(name:String, pos:Position) { + logPos('"${name}" type hint not needed', pos); + } +} + +/** + enforce_all = var / final require a type hint + infer_new_or_const = var / final require a type hint unless you assign a number, a string or new + infer_all = var / final only require a type hint if you do not assign anything +**/ +enum abstract VarTypeHintPolicy(String) { + var ENFORCE_ALL = "enforce_all"; + var INFER_NEW_OR_CONST = "infer_new_or_const"; + var INFER_ALL = "infer_all"; +} \ No newline at end of file diff --git a/src/checkstyle/checks/whitespace/ExtendedEmptyLinesCheck.hx b/src/checkstyle/checks/whitespace/ExtendedEmptyLinesCheck.hx index b3386e8a..1acd3ec9 100644 --- a/src/checkstyle/checks/whitespace/ExtendedEmptyLinesCheck.hx +++ b/src/checkstyle/checks/whitespace/ExtendedEmptyLinesCheck.hx @@ -4,8 +4,7 @@ import checkstyle.checks.whitespace.ListOfEmptyLines.EmptyLineRange; /** Checks for consecutive empty lines. -**/ -@name("ExtendedEmptyLines") +**/ @name("ExtendedEmptyLines") @desc("Checks for consecutive empty lines.") class ExtendedEmptyLinesCheck extends Check { /** @@ -103,7 +102,16 @@ class ExtendedEmptyLinesCheck extends Check { if (isIgnored([BEFORE_PACKAGE, AFTER_PACKAGE])) return; var root:TokenTree = checker.getTokenTree(); - var packages:Array = root.filter([Kwd(KwdPackage)], ALL); + var packages:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdPackage): + FoundSkipSubtree; + case Kwd(_): + SkipSubtree; + default: + GoDeeper; + } + }); for (pack in packages) { checkBetweenToken(emptyLines, null, pack, getPolicy(BEFORE_PACKAGE), "before package"); @@ -115,7 +123,14 @@ class ExtendedEmptyLinesCheck extends Check { if (isIgnored([AFTER_IMPORTS, BEFORE_USING, BETWEEN_IMPORTS])) return; var root:TokenTree = checker.getTokenTree(); - var imports:Array = root.filter([Kwd(KwdImport), Kwd(KwdUsing)], ALL); + var imports:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdImport) | Kwd(KwdUsing): + FoundSkipSubtree; + default: + GoDeeper; + } + }); if (imports.length <= 0) return; @@ -132,14 +147,14 @@ class ExtendedEmptyLinesCheck extends Check { var imp:TokenTree = imports[index]; var prev:TokenTree = imp.previousSibling; if (prev == null) continue; - if (imp.is(Kwd(KwdUsing))) { - if (prev.is(Kwd(KwdImport))) { + if (imp.matches(Kwd(KwdUsing))) { + if (prev.matches(Kwd(KwdImport))) { checkBetweenToken(emptyLines, prev, imp, getPolicy(BEFORE_USING), "between import and using"); continue; } } else { - if (prev.is(Kwd(KwdUsing))) { + if (prev.matches(Kwd(KwdUsing))) { checkBetweenToken(emptyLines, prev, imp, getPolicy(BEFORE_USING), "between import and using"); continue; } @@ -154,13 +169,14 @@ class ExtendedEmptyLinesCheck extends Check { function checkTypes(emptyLines:ListOfEmptyLines) { var root:TokenTree = checker.getTokenTree(); - var types:Array = root.filter([ - Kwd(KwdAbstract), - Kwd(KwdClass), - Kwd(KwdEnum), - Kwd(KwdInterface), - Kwd(KwdTypedef) - ], FIRST); + var types:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdAbstract) | Kwd(KwdClass) | Kwd(KwdEnum) | Kwd(KwdInterface) | Kwd(KwdTypedef): + FoundSkipSubtree; + default: + GoDeeper; + } + }); if (types.length <= 0) return; @@ -251,8 +267,8 @@ class ExtendedEmptyLinesCheck extends Check { if (hasDocComment(child)) { return makePolicyAndWhat(getPolicy(AFTER_DOC_COMMENT_FIELD), "between type fields"); } - var isFuncChild:Bool = child.is(Kwd(KwdFunction)); - var isVarChild:Bool = child.is(Kwd(KwdVar)); + var isFuncChild:Bool = child.matches(Kwd(KwdFunction)); + var isVarChild:Bool = child.matches(Kwd(KwdVar)); if (!isVarChild && !isFuncChild) return null; var type:EmptyLinesFieldType = detectNextFieldType(next); if (type == OTHER) return null; @@ -286,8 +302,8 @@ class ExtendedEmptyLinesCheck extends Check { } if (next == null) return null; - var isFuncChild:Bool = child.is(Kwd(KwdFunction)); - var isVarChild:Bool = child.is(Kwd(KwdVar)); + var isFuncChild:Bool = child.matches(Kwd(KwdFunction)); + var isVarChild:Bool = child.matches(Kwd(KwdVar)); if (!isVarChild && !isFuncChild) return null; var type:EmptyLinesFieldType = detectNextFieldType(next); if (type == OTHER) return null; @@ -295,8 +311,22 @@ class ExtendedEmptyLinesCheck extends Check { if (isVarChild && (type == FUNCTION)) return makePolicyAndWhat(getPolicy(AFTER_CLASS_VARS), "after class vars"); if (isFuncChild && (type == VAR)) return makePolicyAndWhat(getPolicy(AFTER_CLASS_VARS), "after class vars"); - var isStaticChild:Bool = (child.filter([Kwd(KwdStatic)], FIRST).length > 0); - var isStaticNext:Bool = (next.filter([Kwd(KwdStatic)], FIRST).length > 0); + var isStaticChild:Bool = (child.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdStatic): + FoundSkipSubtree; + default: + GoDeeper; + } + }).length > 0); + var isStaticNext:Bool = (next.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdStatic): + FoundSkipSubtree; + default: + GoDeeper; + } + }).length > 0); if (isStaticChild && isStaticNext) return makePolicyAndWhat(getPolicy(BETWEEN_CLASS_STATIC_VARS), "between class static vars"); if (!isStaticChild && !isStaticNext) return makePolicyAndWhat(getPolicy(BETWEEN_CLASS_VARS), "between class vars"); @@ -305,14 +335,14 @@ class ExtendedEmptyLinesCheck extends Check { } function detectNextFieldType(field:TokenTree):EmptyLinesFieldType { - if (field.is(Kwd(KwdFunction))) return FUNCTION; - if (field.is(Kwd(KwdVar))) return VAR; + if (field.matches(Kwd(KwdFunction))) return FUNCTION; + if (field.matches(Kwd(KwdVar))) return VAR; if (!field.isComment()) return OTHER; var after:TokenTree = field.nextSibling; while (after != null) { - if (after.is(Kwd(KwdFunction))) return FUNCTION; - if (after.is(Kwd(KwdVar))) return VAR; + if (after.matches(Kwd(KwdFunction))) return FUNCTION; + if (after.matches(Kwd(KwdVar))) return VAR; if (after.isComment()) { after = after.nextSibling; continue; @@ -362,8 +392,8 @@ class ExtendedEmptyLinesCheck extends Check { if (parent == null) return null; var brOpens:Array = parent.filterCallback(function(tok:TokenTree, depth:Int):FilterResult { return switch (tok.tok) { - case BrOpen: FOUND_SKIP_SUBTREE; - default: GO_DEEPER; + case BrOpen: FoundSkipSubtree; + default: GoDeeper; } }); if (brOpens.length <= 0) return null; @@ -406,7 +436,14 @@ class ExtendedEmptyLinesCheck extends Check { if (isIgnored([IN_FUNCTION, AFTER_LEFT_CURLY, BEFORE_RIGHT_CURLY])) return; var root:TokenTree = checker.getTokenTree(); - var funcs:Array = root.filter([Kwd(KwdFunction)], ALL); + var funcs:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdFunction): + FoundGoDeeper; + default: + GoDeeper; + } + }); if (funcs.length <= 0) return; @@ -416,7 +453,14 @@ class ExtendedEmptyLinesCheck extends Check { var end:Int = checker.getLinePos(pos.max).line; checkLines(emptyLines, getPolicy(IN_FUNCTION), start, end, "inside functions", true); - var brOpen:Array = func.filter([BrOpen], ALL); + var brOpen:Array = func.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case BrOpen: + FoundGoDeeper; + default: + GoDeeper; + } + }); for (open in brOpen) { var close:TokenTree = open.getLastChild(); if (close == null) continue; @@ -442,9 +486,9 @@ class ExtendedEmptyLinesCheck extends Check { var root:TokenTree = checker.getTokenTree(); var comments:Array = root.filterCallback(function(tok:TokenTree, depth:Int):FilterResult { return switch (tok.tok) { - case Comment(_): FOUND_SKIP_SUBTREE; - case CommentLine(_): FOUND_SKIP_SUBTREE; - default: GO_DEEPER; + case Comment(_): FoundSkipSubtree; + case CommentLine(_): FoundSkipSubtree; + default: GoDeeper; } }); for (comment in comments) { @@ -474,7 +518,7 @@ class ExtendedEmptyLinesCheck extends Check { } function checkPreviousSiblingComment(token:TokenTree):Bool { - if ((token == null) || (token.tok == null)) { + if ((token == null) || (token.tok == Root)) { return false; } switch (token.tok) { @@ -484,7 +528,7 @@ class ExtendedEmptyLinesCheck extends Check { return false; case POpen, Const(CIdent(_)): var parent:Null = token.parent; - if ((parent != null) && (parent.tok != null)) { + if (parent != null) { switch (parent.tok) { case Sharp(_): return false; @@ -611,8 +655,7 @@ typedef PolicyAndWhat = { - upto = up to "max" empty line(s) allowed (0 - "max") - atleast = at least "max" empty lines required **/ -@:enum -abstract EmptyLinesPolicy(String) { +enum abstract EmptyLinesPolicy(String) { var IGNORE = "ignore"; var NONE = "none"; var EXACT = "exact"; @@ -664,8 +707,7 @@ enum EmptyLinesFieldType { - inFunction = anywhere inside function body - typeDefinition = between type and left curly **/ -@:enum -abstract EmptyLinesPlace(String) { +enum abstract EmptyLinesPlace(String) to String { var BEFORE_PACKAGE = "beforePackage"; var AFTER_PACKAGE = "afterPackage"; var BETWEEN_IMPORTS = "betweenImports"; diff --git a/src/checkstyle/checks/whitespace/IndentationCharacterCheck.hx b/src/checkstyle/checks/whitespace/IndentationCharacterCheck.hx index fac472c7..a4baacae 100644 --- a/src/checkstyle/checks/whitespace/IndentationCharacterCheck.hx +++ b/src/checkstyle/checks/whitespace/IndentationCharacterCheck.hx @@ -56,8 +56,7 @@ class IndentationCharacterCheck extends LineCheckBase { - tab = tabs - space = space **/ -@:enum -abstract IndentationCharacterCheckCharacter(String) { +enum abstract IndentationCharacterCheckCharacter(String) { var TAB = "tab"; var SPACE = "space"; } \ No newline at end of file diff --git a/src/checkstyle/checks/whitespace/IndentationCheck.hx b/src/checkstyle/checks/whitespace/IndentationCheck.hx index bdbf580f..ac8b7d13 100644 --- a/src/checkstyle/checks/whitespace/IndentationCheck.hx +++ b/src/checkstyle/checks/whitespace/IndentationCheck.hx @@ -127,24 +127,15 @@ class IndentationCheck extends Check { function calcLineIndentation():Array { var lineIndentation:Array = [for (i in 0...checker.lines.length) 0]; - var searchFor:Array = [ - BrOpen, - BkOpen, - Sharp("if"), - Sharp("else"), - Sharp("elseif"), - Sharp("end"), - Sharp("error"), - Kwd(KwdFunction), - Kwd(KwdIf), - Kwd(KwdElse), - Kwd(KwdFor), - Kwd(KwdDo), - Kwd(KwdWhile), - Kwd(KwdCase), - Kwd(KwdDefault) - ]; - var tokenList:Array = checker.getTokenTree().filter(searchFor, ALL); + var tokenList:Array = checker.getTokenTree().filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case BrOpen | BkOpen | Sharp("if") | Sharp("else") | Sharp("elseif") | Sharp("end") | Sharp("error") | Kwd(KwdFunction) | Kwd(KwdIf) | + Kwd(KwdElse) | Kwd(KwdFor) | Kwd(KwdDo) | Kwd(KwdWhile) | Kwd(KwdCase) | Kwd(KwdDefault): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (token in tokenList) { switch (token.tok) { case BkOpen: @@ -157,14 +148,6 @@ class IndentationCheck extends Check { continue; default: } - // var type:BrOpenType = TokenTreeCheckUtils.getBrOpenType(token); - // switch (type) { - // case BLOCK: - // case TYPEDEFDECL: - // case OBJECTDECL: - // case ANONTYPE: - // case UNKNOWN: - // } case Kwd(KwdFunction): calcLineIndentationFunction(token, lineIndentation); case Kwd(KwdIf), Kwd(KwdElse): @@ -191,7 +174,7 @@ class IndentationCheck extends Check { function calcLineIndentationBkOpen(token:TokenTree, lineIndentation:Array) { var child:TokenTree = token.getFirstChild(); if (child == null) return; - if ((child.is(BrOpen)) || (child.is(BkOpen))) { + if ((child.matches(BrOpen)) || (child.matches(BkOpen))) { // only indent once, if directly next to each other `[{` if (token.pos.min + 1 == child.pos.min) return; } @@ -202,7 +185,7 @@ class IndentationCheck extends Check { function calcLineIndentationFunction(token:TokenTree, lineIndentation:Array) { var body:TokenTree = TokenTreeAccessHelper.access(token).firstChild().lastChild().token; if (body == null) return; - if (body.is(BrOpen)) return; + if (body.matches(BrOpen)) return; increaseIndentIfNextLine(token, body, lineIndentation); } @@ -211,15 +194,15 @@ class IndentationCheck extends Check { case Kwd(KwdIf): var child:TokenTree = token.getLastChild(); if (child == null) return; - if (child.is(Kwd(KwdElse))) { + if (child.matches(Kwd(KwdElse))) { child = token.children[token.children.length - 2]; } - if (child.is(BrOpen)) return; + if (child.matches(BrOpen)) return; increaseIndentIfNextLine(token, child, lineIndentation); case Kwd(KwdElse): var child:TokenTree = token.getFirstChild(); if (child == null) return; - if (child.is(BrOpen)) return; + if (child.matches(BrOpen)) return; increaseIndentIfNextLine(token, child, lineIndentation); default: } @@ -264,8 +247,8 @@ class IndentationCheck extends Check { case Kwd(KwdFor): var child:TokenTree = token.getLastChild(); if (child == null) return; - if (child.is(BrOpen)) return; - if (child.is(BkOpen)) return; + if (child.matches(BrOpen)) return; + if (child.matches(BkOpen)) return; while (child.getLastChild() != null) { child = child.getLastChild(); } @@ -275,12 +258,12 @@ class IndentationCheck extends Check { case Kwd(KwdDo): var child:TokenTree = token.getFirstChild(); if (child == null) return; - if (child.is(BrOpen)) return; + if (child.matches(BrOpen)) return; increaseIndentIfNextLine(token, child, lineIndentation); case Kwd(KwdWhile): var child:TokenTree = token.getLastChild(); if (child == null) return; - if (child.is(BrOpen)) return; + if (child.matches(BrOpen)) return; increaseIndentIfNextLine(token, child, lineIndentation); default: } @@ -289,27 +272,16 @@ class IndentationCheck extends Check { function calcWrapStatements():Array { var wrapped:Array = [for (i in 0...checker.lines.length) false]; - var searchFor:Array = [ - POpen, - Dot, - Kwd(KwdReturn), - Kwd(KwdCase), - Binop(OpAssign), - Binop(OpArrow), - Binop(OpAssignOp(OpShr)), - Binop(OpAssignOp(OpAdd)), - Binop(OpAssignOp(OpSub)), - Binop(OpAssignOp(OpMult)), - Binop(OpAssignOp(OpDiv)), - Binop(OpAssignOp(OpMod)), - Binop(OpAssignOp(OpShl)), - Binop(OpAssignOp(OpShr)), - Binop(OpAssignOp(OpUShr)), - Binop(OpAssignOp(OpOr)), - Binop(OpAssignOp(OpAnd)), - Binop(OpAssignOp(OpXor)) - ]; - var tokenList:Array = checker.getTokenTree().filter(searchFor, ALL); + var tokenList:Array = checker.getTokenTree().filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case POpen | Dot | Kwd(KwdReturn) | Kwd(KwdCase) | Binop(OpAssign) | Binop(OpArrow) | Binop(OpAssignOp(OpAdd)) | Binop(OpAssignOp(OpSub)) | + Binop(OpAssignOp(OpMult)) | Binop(OpAssignOp(OpDiv)) | Binop(OpAssignOp(OpMod)) | Binop(OpAssignOp(OpShl)) | Binop(OpAssignOp(OpShr)) | + Binop(OpAssignOp(OpUShr)) | Binop(OpAssignOp(OpOr)) | Binop(OpAssignOp(OpAnd)) | Binop(OpAssignOp(OpXor)): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (token in tokenList) { var pos = token.getPos(); var child:TokenTree = token.getFirstChild(); @@ -351,12 +323,11 @@ class IndentationCheck extends Check { var ignoreIndentation:Array = [for (i in 0...checker.lines.length) false]; var tokenList:Array = checker.getTokenTree().filterCallback(function(token:TokenTree, depth:Int):FilterResult { - if (token.tok == null) return GO_DEEPER; return switch (token.tok) { - case Comment(_): FOUND_SKIP_SUBTREE; - case CommentLine(_): FOUND_SKIP_SUBTREE; - case Const(CString(_)): FOUND_SKIP_SUBTREE; - default: GO_DEEPER; + case Comment(_): FoundSkipSubtree; + case CommentLine(_): FoundSkipSubtree; + case Const(CString(_)): FoundSkipSubtree; + default: GoDeeper; } }); for (token in tokenList) { @@ -456,23 +427,20 @@ class IndentationCheck extends Check { } } -@:enum -abstract WrappedIndentationPolicy(String) { +enum abstract WrappedIndentationPolicy(String) { var NONE = "none"; var EXACT = "exact"; var LARGER = "larger"; } -@:enum -abstract ConditionalIndentationPolicy(String) { +enum abstract ConditionalIndentationPolicy(String) { var IGNORE = "ignore"; var FIXED_ZERO = "fixed_zero"; var ALIGNED = "aligned"; var ALIGNED_INCREASE = "aligned_increase"; } -@:enum -abstract IndentationCheckCharacter(String) to String { +enum abstract IndentationCheckCharacter(String) to String { var TAB = "tab"; var ONE_SPACE = " "; var TWO_SPACES = " "; diff --git a/src/checkstyle/checks/whitespace/ListOfEmptyLines.hx b/src/checkstyle/checks/whitespace/ListOfEmptyLines.hx index 4263ae47..3d6eed65 100644 --- a/src/checkstyle/checks/whitespace/ListOfEmptyLines.hx +++ b/src/checkstyle/checks/whitespace/ListOfEmptyLines.hx @@ -110,7 +110,7 @@ class ListOfEmptyLines { @return EmptyLineRange matching range or NONE **/ public function checkPolicySingleRange(policy:EmptyLinesPolicy, max:Int, start:Int, end:Int):EmptyLineRange { - if (start > end) throw "*** wrong order!! *** " + start + " " + end; + if (start > end) throw new Exception("*** wrong order!! *** " + start + " " + end); var range:Array = getRanges(start, end); switch (policy) { diff --git a/src/checkstyle/checks/whitespace/OperatorWhitespaceCheck.hx b/src/checkstyle/checks/whitespace/OperatorWhitespaceCheck.hx index 824fb978..a5b6138d 100644 --- a/src/checkstyle/checks/whitespace/OperatorWhitespaceCheck.hx +++ b/src/checkstyle/checks/whitespace/OperatorWhitespaceCheck.hx @@ -1,13 +1,12 @@ package checkstyle.checks.whitespace; -import tokentree.utils.TokenTreeCheckUtils; import checkstyle.checks.whitespace.WhitespaceCheckBase.WhitespacePolicy; import checkstyle.checks.whitespace.WhitespaceCheckBase.WhitespaceUnaryPolicy; +import tokentree.utils.TokenTreeCheckUtils; /** Checks that whitespace is present or absent around a operators. -**/ -@name("OperatorWhitespace") +**/ @name("OperatorWhitespace") @desc("Checks that whitespace is present or absent around a operators.") class OperatorWhitespaceCheck extends WhitespaceCheckBase { /** @@ -178,7 +177,14 @@ class OperatorWhitespaceCheck extends WhitespaceCheckBase { function checkUnaryOps(root:TokenTree) { if ((unaryOpPolicy == null) || (unaryOpPolicy == IGNORE)) return; - var tokens:Array = root.filter([Unop(OpNegBits), Unop(OpNot), Unop(OpIncrement), Unop(OpDecrement)], ALL); + var tokens:Array = root.filterCallback(function(token:TokenTree, index:Int):FilterResult { + return switch (token.tok) { + case Unop(OpNegBits) | Unop(OpNot) | Unop(OpIncrement) | Unop(OpDecrement): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (token in tokens) { if (isPosSuppressed(token.pos)) continue; @@ -188,7 +194,14 @@ class OperatorWhitespaceCheck extends WhitespaceCheckBase { function checkTernaryOps(root:TokenTree) { if ((ternaryOpPolicy == null) || (ternaryOpPolicy == IGNORE)) return; - var tokens:Array = root.filter([Question], ALL); + var tokens:Array = root.filterCallback(function(token:TokenTree, index:Int):FilterResult { + return switch (token.tok) { + case Question: + FoundGoDeeper; + default: + GoDeeper; + } + }); for (token in tokens) { if (isPosSuppressed(token.pos)) continue; @@ -233,11 +246,18 @@ class OperatorWhitespaceCheck extends WhitespaceCheckBase { function checkIntervalOps(root:TokenTree) { if ((intervalOpPolicy == null) || (intervalOpPolicy == IGNORE)) return; var tokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { - if (token.tok == null) return GO_DEEPER; return switch (token.tok) { - case Binop(OpInterval): FOUND_SKIP_SUBTREE; - case IntInterval(_): FOUND_SKIP_SUBTREE; - default: GO_DEEPER; + case Binop(OpInterval): FoundSkipSubtree; + case IntInterval(_): FoundSkipSubtree; + case Spread: + if (token.parent == null) return GoDeeper; + switch (token.parent.tok) { + case POpen: + return GoDeeper; + default: + FoundSkipSubtree; + } + default: GoDeeper; } }); checkTokenList(tokens, intervalOpPolicy); @@ -245,7 +265,14 @@ class OperatorWhitespaceCheck extends WhitespaceCheckBase { function checkArrowOps(root:TokenTree) { if ((arrowPolicy == null) || (arrowPolicy == IGNORE)) return; - var tokens:Array = root.filter([Binop(OpArrow)], ALL); + var tokens:Array = root.filterCallback(function(token:TokenTree, index:Int):FilterResult { + return switch (token.tok) { + case Binop(OpArrow): + FoundGoDeeper; + default: + GoDeeper; + } + }); checkTokenList(tokens, arrowPolicy); } @@ -255,16 +282,23 @@ class OperatorWhitespaceCheck extends WhitespaceCheckBase { && ((newFunctionTypePolicy == null) || (newFunctionTypePolicy == IGNORE))) { return; } - var tokens:Array = root.filter([Arrow], ALL); + var tokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Arrow: + FoundGoDeeper; + default: + GoDeeper; + } + }); for (token in tokens) { if (isPosSuppressed(token.pos)) continue; var type:ArrowType = TokenTreeCheckUtils.getArrowType(token); switch (type) { - case ARROW_FUNCTION: + case ArrowFunction: checkWhitespace(token, arrowFunctionPolicy); - case FUNCTION_TYPE_HAXE3: + case OldFunctionType: checkWhitespace(token, oldFunctionTypePolicy); - case FUNCTION_TYPE_HAXE4: + case NewFunctionType: checkWhitespace(token, newFunctionTypePolicy); } } diff --git a/src/checkstyle/checks/whitespace/OperatorWrapCheck.hx b/src/checkstyle/checks/whitespace/OperatorWrapCheck.hx index d460d98f..2f09f517 100644 --- a/src/checkstyle/checks/whitespace/OperatorWrapCheck.hx +++ b/src/checkstyle/checks/whitespace/OperatorWrapCheck.hx @@ -50,7 +50,7 @@ class OperatorWrapCheck extends WrapCheckBase { } override function actualRun() { - var tokenList:Array = []; + var tokenList:Array = []; if (hasToken("=")) tokenList.push(Binop(OpAssign)); if (hasToken("+")) tokenList.push(Binop(OpAdd)); diff --git a/src/checkstyle/checks/whitespace/SeparatorWrapCheck.hx b/src/checkstyle/checks/whitespace/SeparatorWrapCheck.hx index de7bee7f..9dc76280 100644 --- a/src/checkstyle/checks/whitespace/SeparatorWrapCheck.hx +++ b/src/checkstyle/checks/whitespace/SeparatorWrapCheck.hx @@ -14,7 +14,7 @@ class SeparatorWrapCheck extends WrapCheckBase { } override function actualRun() { - var tokenList:Array = []; + var tokenList:Array = []; if (hasToken(",")) tokenList.push(Comma); if (hasToken(".")) tokenList.push(Dot); diff --git a/src/checkstyle/checks/whitespace/SpacingCheck.hx b/src/checkstyle/checks/whitespace/SpacingCheck.hx index 43540fbf..5eba6e29 100644 --- a/src/checkstyle/checks/whitespace/SpacingCheck.hx +++ b/src/checkstyle/checks/whitespace/SpacingCheck.hx @@ -78,7 +78,14 @@ class SpacingCheck extends Check { override function actualRun() { var root:TokenTree = checker.getTokenTree(); - var acceptableTokens:Array = root.filter([Kwd(KwdIf), Kwd(KwdFor), Kwd(KwdWhile), Kwd(KwdSwitch), Kwd(KwdCatch)], ALL); + var acceptableTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case Kwd(KwdIf), Kwd(KwdFor), Kwd(KwdWhile), Kwd(KwdSwitch), Kwd(KwdCatch): + FoundGoDeeper; + default: + GoDeeper; + } + }); for (token in acceptableTokens) { var firstChild:TokenTree = token.getFirstChild(); @@ -189,8 +196,7 @@ class SpacingCheck extends Check { - shouldNot = no space should between statement and condition - any = ignored by space check **/ -@:enum -abstract SpacingPolicy(String) { +enum abstract SpacingPolicy(String) { var SHOULD = "should"; var SHOULD_NOT = "should_not"; var ANY = "any"; diff --git a/src/checkstyle/checks/whitespace/WhitespaceAfterCheck.hx b/src/checkstyle/checks/whitespace/WhitespaceAfterCheck.hx index 501849c7..6d1c083a 100644 --- a/src/checkstyle/checks/whitespace/WhitespaceAfterCheck.hx +++ b/src/checkstyle/checks/whitespace/WhitespaceAfterCheck.hx @@ -32,7 +32,7 @@ class WhitespaceAfterCheck extends Check { } override function actualRun() { - var tokenList:Array = []; + var tokenList:Array = []; if (hasToken(",")) tokenList.push(Comma); if (hasToken(";")) tokenList.push(Semicolon); @@ -90,9 +90,15 @@ class WhitespaceAfterCheck extends Check { checkTokens(tokenList); } - function checkTokens(tokenList:Array) { + @:access(tokentree.TokenTree) + function checkTokens(tokenList:Array) { var root:TokenTree = checker.getTokenTree(); - var allTokens:Array = root.filter(tokenList, ALL); + var allTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + if (token.matchesAny(tokenList)) { + return FoundGoDeeper; + } + return GoDeeper; + }); for (tok in allTokens) { if (isPosSuppressed(tok.pos)) continue; diff --git a/src/checkstyle/checks/whitespace/WhitespaceAroundCheck.hx b/src/checkstyle/checks/whitespace/WhitespaceAroundCheck.hx index bb2050cf..8b645595 100644 --- a/src/checkstyle/checks/whitespace/WhitespaceAroundCheck.hx +++ b/src/checkstyle/checks/whitespace/WhitespaceAroundCheck.hx @@ -61,7 +61,7 @@ class WhitespaceAroundCheck extends Check { } override function actualRun() { - var tokenList:Array = []; + var tokenList:Array = []; if (hasToken(",")) tokenList.push(Comma); if (hasToken(";")) tokenList.push(Semicolon); @@ -122,9 +122,15 @@ class WhitespaceAroundCheck extends Check { checkTokens(tokenList); } - function checkTokens(tokenList:Array) { + @:access(tokentree.TokenTree) + function checkTokens(tokenList:Array) { var root:TokenTree = checker.getTokenTree(); - var allTokens:Array = root.filter(tokenList, ALL); + var allTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + if (token.matchesAny(tokenList)) { + return FoundGoDeeper; + } + return GoDeeper; + }); for (tok in allTokens) { if (isPosSuppressed(tok.pos)) continue; diff --git a/src/checkstyle/checks/whitespace/WhitespaceCheckBase.hx b/src/checkstyle/checks/whitespace/WhitespaceCheckBase.hx index 6e3c9c24..679c8014 100644 --- a/src/checkstyle/checks/whitespace/WhitespaceCheckBase.hx +++ b/src/checkstyle/checks/whitespace/WhitespaceCheckBase.hx @@ -13,9 +13,15 @@ class WhitespaceCheckBase extends Check { categories = [Category.STYLE, Category.CLARITY]; } - function checkTokens(root:TokenTree, tokens:Array, policy:WhitespacePolicy) { + @:access(tokentree.TokenTree) + function checkTokens(root:TokenTree, tokens:Array, policy:WhitespacePolicy) { if ((policy == null) || (policy == IGNORE)) return; - var tokenList:Array = root.filter(tokens, ALL); + var tokenList:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + if (token.matchesAny(tokens)) { + return FoundGoDeeper; + } + return GoDeeper; + }); checkTokenList(tokenList, policy); } @@ -99,8 +105,7 @@ typedef WhitespacePolicyCheck = Bool -> Bool -> Void; - none = enforce no whitespace before and after operator - ignore = skip checks **/ -@:enum -abstract WhitespacePolicy(String) { +enum abstract WhitespacePolicy(String) { var BEFORE = "before"; var AFTER = "after"; var AROUND = "around"; @@ -114,8 +119,7 @@ abstract WhitespacePolicy(String) { - none = enforce no whitespace between unary operator and operand - ignore = skip checks **/ -@:enum -abstract WhitespaceUnaryPolicy(String) { +enum abstract WhitespaceUnaryPolicy(String) { var INNER = "inner"; var NONE = "none"; var IGNORE = "ignore"; diff --git a/src/checkstyle/checks/whitespace/WrapCheckBase.hx b/src/checkstyle/checks/whitespace/WrapCheckBase.hx index 704e2f7f..b66015da 100644 --- a/src/checkstyle/checks/whitespace/WrapCheckBase.hx +++ b/src/checkstyle/checks/whitespace/WrapCheckBase.hx @@ -29,9 +29,15 @@ class WrapCheckBase extends Check { return (tokens.length == 0 || tokens.contains(token)); } - function checkTokens(tokenList:Array) { + @:access(tokentree.TokenTree) + function checkTokens(tokenList:Array) { var root:TokenTree = checker.getTokenTree(); - var allTokens:Array = root.filter(tokenList, ALL); + var allTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + if (token.matchesAny(tokenList)) { + return FoundGoDeeper; + } + return GoDeeper; + }); for (tok in allTokens) { if (isPosSuppressed(tok.pos)) continue; @@ -67,8 +73,7 @@ class WrapCheckBase extends Check { - eol = wrapping token should be at end of line - nl = wrapping token should start a new line **/ -@:enum -abstract WrapCheckBaseOption(String) { +enum abstract WrapCheckBaseOption(String) { var EOL = "eol"; var NL = "nl"; } \ No newline at end of file diff --git a/src/checkstyle/config/ConfigParser.hx b/src/checkstyle/config/ConfigParser.hx index fe066e19..da00787c 100644 --- a/src/checkstyle/config/ConfigParser.hx +++ b/src/checkstyle/config/ConfigParser.hx @@ -1,14 +1,15 @@ package checkstyle.config; -import checkstyle.ChecksInfo; +import Std.isOfType as isOfType; import checkstyle.Checker; +import checkstyle.ChecksInfo; import checkstyle.checks.Check; import checkstyle.errors.Error; import checkstyle.utils.ConfigUtils; import haxe.Json; +import haxe.io.Path; import sys.FileSystem; import sys.io.File; -import haxe.io.Path; class ConfigParser { public var paths:Array; @@ -179,7 +180,7 @@ class ConfigParser { } catch (e:Any) { var message = 'Failed to configure $prop setting for ${check.getModuleName()}: '; - message += (Std.is(e, Error) ? (e : Error).message : Std.string(e)); + message += (isOfType(e, Error) ? (e : Error).message : Std.string(e)); failWith(message); } } diff --git a/src/checkstyle/config/ExcludeManager.hx b/src/checkstyle/config/ExcludeManager.hx index 11a94726..4e3b326e 100644 --- a/src/checkstyle/config/ExcludeManager.hx +++ b/src/checkstyle/config/ExcludeManager.hx @@ -27,13 +27,13 @@ class ExcludeManager { } static function createExcludeDefinition(filter:String, range:String):ExcludeDefinition { - if ((range == null) || (range == "")) return FULL(filter); - if (~/^[1-9][0-9]*$/.match(range)) return LINE(filter, Std.parseInt(range)); + if ((range == null) || (range == "")) return ExcludeDefinition.FULL(filter); + if (~/^[1-9][0-9]*$/.match(range)) return ExcludeDefinition.LINE(filter, Std.parseInt(range)); if (~/^[1-9][0-9]*-[1-9][0-9]*$/.match(range)) { var parts = range.split("-"); - return RANGE(filter, Std.parseInt(parts[0]), Std.parseInt(parts[1])); + return ExcludeDefinition.RANGE(filter, Std.parseInt(parts[0]), Std.parseInt(parts[1])); } - return IDENTIFIER(filter, range); + return ExcludeDefinition.IDENTIFIER(filter, range); } public static function isExcludedFromAll(fileName:String):Bool { @@ -133,24 +133,31 @@ class ExcludeManager { function getInlineExcludes(checker:Checker):Array { var inlineExcludes:Array = []; var root:TokenTree = checker.getTokenTree(); - var allAtTokens:Array = root.filter([At], ALL); + var allAtTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + return switch (token.tok) { + case At: + FoundGoDeeper; + default: + GoDeeper; + } + }); for (atToken in allAtTokens) { var child:TokenTree = atToken.getFirstChild(); if (child == null) continue; - if (!child.is(Const(CIdent("SuppressWarnings")))) continue; + if (!child.matches(Const(CIdent("SuppressWarnings")))) continue; var pOpen:TokenTree = child.getFirstChild(); if (pOpen == null) continue; - if (!pOpen.is(POpen)) continue; + if (!pOpen.matches(POpen)) continue; var checkNames:Array = []; pOpen.filterCallback(function(token:TokenTree, depth:Int):FilterResult { switch (token.tok) { case Const(CString(name)): - if (!StringTools.startsWith(name, "checkstyle:")) return SKIP_SUBTREE; + if (!StringTools.startsWith(name, "checkstyle:")) return SkipSubtree; checkNames.push(name.substr(11)); - return SKIP_SUBTREE; + return SkipSubtree; default: - return GO_DEEPER; + return GoDeeper; } }); for (name in checkNames) { @@ -173,14 +180,20 @@ class ExcludeManager { return map; } + @:access(tokentree.TokenTree) function makeIdentifierRange(checker:Checker, checkName:String, name:String):Array { var identifierExcludes:Array = []; var root:TokenTree = checker.getTokenTree(); - var filterTokens:Array = [Const(CIdent(name))]; + var filterTokens:Array = [Const(CIdent(name))]; if (name == "new") { filterTokens.push(Kwd(KwdNew)); } - var allTokens:Array = root.filter(filterTokens, ALL); + var allTokens:Array = root.filterCallback(function(token:TokenTree, depth:Int):FilterResult { + if (token.matchesAny(filterTokens)) { + return FoundGoDeeper; + } + return GoDeeper; + }); for (token in allTokens) { identifierExcludes.push(makeTokenExcludeRange(checker, checkName, token)); } diff --git a/src/checkstyle/config/ExcludePath.hx b/src/checkstyle/config/ExcludePath.hx index 2b4c52c7..ae7ca766 100644 --- a/src/checkstyle/config/ExcludePath.hx +++ b/src/checkstyle/config/ExcludePath.hx @@ -5,8 +5,7 @@ package checkstyle.config; - RELATIVE_TO_PROJECT = use project root - RELATIVE_TO_SOURCE = use path(s) specified via "-s " command line switches **/ -@:enum -abstract ExcludePath(String) { +enum abstract ExcludePath(String) { var RELATIVE_TO_PROJECT = "RELATIVE_TO_PROJECT"; var RELATIVE_TO_SOURCE = "RELATIVE_TO_SOURCE"; } \ No newline at end of file diff --git a/src/checkstyle/detect/DetectCodingStyle.hx b/src/checkstyle/detect/DetectCodingStyle.hx index fc14ad45..96ec79c3 100644 --- a/src/checkstyle/detect/DetectCodingStyle.hx +++ b/src/checkstyle/detect/DetectCodingStyle.hx @@ -1,10 +1,10 @@ package checkstyle.detect; -import checkstyle.config.CheckConfig; import checkstyle.Checker; import checkstyle.checks.Check; -import checkstyle.utils.ConfigUtils; +import checkstyle.config.CheckConfig; import checkstyle.reporter.ReporterManager; +import checkstyle.utils.ConfigUtils; import haxe.ds.ArraySort; class DetectCodingStyle { @@ -70,16 +70,16 @@ class DetectCodingStyle { static function iterateProperty(check:Check, property:DetectablePropertyList, file:CheckFile):DetectionResult { if (property.values.length <= 0) { - return NO_CHANGE; + return DetectionResult.NO_CHANGE; } if (property.values.length == 1) { - return CHANGE_DETECTED(property.values[0]); + return DetectionResult.CHANGE_DETECTED(property.values[0]); } var checker:Checker = new Checker(); checker.addCheck(check); checker.loadFileContent(file); - if (!checker.createContext(file)) return NO_CHANGE; + if (!checker.createContext(file)) return DetectionResult.NO_CHANGE; var lastCount:Int = -1; var lowestCountValue:Any = null; @@ -102,14 +102,14 @@ class DetectCodingStyle { } if (changed) { var index:Int = property.values.indexOf(lowestCountValue); - if (index <= 0) return CHANGE_DETECTED(lowestCountValue); + if (index <= 0) return DetectionResult.CHANGE_DETECTED(lowestCountValue); property.values = property.values.slice(index); if (property.values.length > 2) { - return REDUCED_VALUE_LIST(lowestCountValue); + return DetectionResult.REDUCED_VALUE_LIST(lowestCountValue); } - return CHANGE_DETECTED(lowestCountValue); + return DetectionResult.CHANGE_DETECTED(lowestCountValue); } - return NO_CHANGE; + return DetectionResult.NO_CHANGE; } static function runCheck(checker:Checker, fileList:Array):Int { diff --git a/src/checkstyle/detect/DetectionReporter.hx b/src/checkstyle/detect/DetectionReporter.hx index 79510e02..bae73bf4 100644 --- a/src/checkstyle/detect/DetectionReporter.hx +++ b/src/checkstyle/detect/DetectionReporter.hx @@ -13,11 +13,9 @@ class DetectionReporter implements IReporter { public function finish() {} - public function fileStart(f:CheckFile) {} + public function addFile(f:CheckFile) {} - public function fileFinish(f:CheckFile) {} - - public function addMessage(m:CheckMessage) { + public function addMessage(m:Message) { messageCount++; } } \ No newline at end of file diff --git a/src/checkstyle/import.hx b/src/checkstyle/import.hx index 8b94a048..60d18d4b 100644 --- a/src/checkstyle/import.hx +++ b/src/checkstyle/import.hx @@ -1,14 +1,15 @@ package checkstyle; import checkstyle.Checker.LinePos; -import checkstyle.SeverityLevel; import checkstyle.detect.DetectableInstances; import checkstyle.utils.ErrorUtils; +import haxe.Exception; import haxe.io.Bytes; import haxe.macro.Expr; import haxeparser.Data; import tokentree.TokenTree; import tokentree.TokenTreeAccessHelper; +import tokentree.TokenTreeDef; import tokentree.utils.TokenTreeCheckUtils; using StringTools; @@ -16,4 +17,8 @@ using checkstyle.utils.ArrayUtils; using checkstyle.utils.ExprUtils; using checkstyle.utils.FieldUtils; using checkstyle.utils.StringUtils; -using tokentree.TokenTreeAccessHelper; \ No newline at end of file +using tokentree.TokenTreeAccessHelper; + +#if !macro +import checkstyle.SeverityLevel; +#end \ No newline at end of file diff --git a/src/checkstyle/reporter/BaseReporter.hx b/src/checkstyle/reporter/BaseReporter.hx index 0dba347a..d6e5a09c 100644 --- a/src/checkstyle/reporter/BaseReporter.hx +++ b/src/checkstyle/reporter/BaseReporter.hx @@ -16,12 +16,14 @@ class BaseReporter implements IReporter { var numChecks:Int; var numUsedChecks:Int; var noStyle:Bool; + var messages:Array; public function new(fileCount:Int, checkCount:Int, usedCheckCount:Int, path:String, ns:Bool) { numFiles = fileCount; numChecks = checkCount; numUsedChecks = usedCheckCount; noStyle = ns; + messages = []; if (path != null) { var folder = Path.directory(path); if (folder.length > 0 && !FileSystem.exists(folder)) FileSystem.createDirectory(folder); @@ -67,11 +69,11 @@ class BaseReporter implements IReporter { else Sys.println(styleText("No issues found.", Style.BOLD)); } - public function fileStart(f:CheckFile) {} + public function addFile(f:CheckFile) {} - public function fileFinish(f:CheckFile) {} - - public function addMessage(m:CheckMessage) {} + public function addMessage(m:Message) { + messages.push(m); + } function styleText(s:String, style:Style):String { if (Sys.systemName() == "Windows" || noStyle) return s; @@ -87,28 +89,42 @@ class BaseReporter implements IReporter { } } - function getMessage(m:CheckMessage):StringBuf { + function getMessage(message:Message):StringBuf { var sb:StringBuf = new StringBuf(); - sb.add(m.fileName); + sb.add(message.fileName); sb.add(":"); - sb.add(m.startLine); - if (m.startColumn >= 0) { - var isRange = m.startColumn != m.endColumn; + sb.add(message.range.start.line); + if (message.range.start.column >= 0) { + var isRange = message.range.start.column != message.range.end.column; sb.add(': character${isRange ? "s" : ""} '); - sb.add(m.startColumn); + sb.add(message.range.start.column); if (isRange) { sb.add("-"); - sb.add(m.endColumn); + sb.add(message.range.end.column); } sb.add(" "); } sb.add(": "); - sb.add(m.moduleName); + sb.add(message.moduleName); sb.add(" - "); - sb.add(BaseReporter.severityString(m.severity)); + sb.add(BaseReporter.severityString(message.severity)); sb.add(": "); - sb.add(m.message); + sb.add(message.message); sb.add("\n"); + for (related in message.related) { + sb.add(' - see also: ${related.fileName}:${related.range.start.line}'); + if (related.range.start.column >= 0) { + var isRange = related.range.start.column != related.range.end.column; + sb.add(': character${isRange ? "s" : ""} '); + sb.add(related.range.start.column); + if (isRange) { + sb.add("-"); + sb.add(related.range.end.column); + } + sb.add(" "); + } + sb.add("\n"); + } return sb; } @@ -123,8 +139,7 @@ class BaseReporter implements IReporter { } } -@:enum -abstract Style(Int) { +enum abstract Style(Int) { var BOLD = 1; var RED = 91; var BLUE = 94; diff --git a/src/checkstyle/reporter/CodeClimateReporter.hx b/src/checkstyle/reporter/CodeClimateReporter.hx index f0d3b5d7..eab2009d 100644 --- a/src/checkstyle/reporter/CodeClimateReporter.hx +++ b/src/checkstyle/reporter/CodeClimateReporter.hx @@ -1,5 +1,6 @@ package checkstyle.reporter; +import checkstyle.Message.MessageLocation; import haxe.Json; using StringTools; @@ -14,37 +15,45 @@ class CodeClimateReporter extends BaseReporter { override public function finish() {} - override public function addMessage(m:CheckMessage) { - var file = ~/^\/code\//.replace(m.fileName, ""); + override public function addMessage(message:Message) { + Sys.print(Json.stringify(createIssue(message, message))); + Sys.stdout().writeByte(0); + for (related in message.related) { + Sys.print(Json.stringify(createIssue(message, related))); + Sys.stdout().writeByte(0); + } + } + + function createIssue(message:Message, location:MessageLocation):Any { + var file = ~/^\/code\//.replace(location.fileName, ""); file = ~/\/\//.replace(file, "/"); var issue = { type: "issue", - check_name: m.moduleName, - description: m.message.replace("\"", "`"), + check_name: message.moduleName, + description: message.message.replace("\"", "`"), content: { - body: m.desc + body: message.desc }, - severity: getSeverity(m.severity), - categories: m.categories, - remediation_points: m.points * REMEDIATION_BASE, + severity: getSeverity(message.severity), + categories: message.categories, + remediation_points: message.points * REMEDIATION_BASE, location: { path: file, positions: { begin: { - line: m.startLine, - column: m.startColumn + line: location.range.start.line, + column: location.range.start.column }, end: { - line: m.endLine, - column: m.endColumn + line: location.range.end.line, + column: location.range.end.column } } } }; - Sys.print(Json.stringify(issue)); - Sys.stdout().writeByte(0); + return issue; } function getSeverity(severity:SeverityLevel):String { diff --git a/src/checkstyle/reporter/ExitCodeReporter.hx b/src/checkstyle/reporter/ExitCodeReporter.hx index b3055bcd..3ad7a569 100644 --- a/src/checkstyle/reporter/ExitCodeReporter.hx +++ b/src/checkstyle/reporter/ExitCodeReporter.hx @@ -13,11 +13,9 @@ class ExitCodeReporter implements IReporter { Main.setExitCode(failCheckCount); } - public function fileStart(f:CheckFile) {} + public function addFile(file:CheckFile) {} - public function fileFinish(f:CheckFile) {} - - public function addMessage(m:CheckMessage) { - if (m.severity == ERROR) failCheckCount++; + public function addMessage(message:Message) { + if (message.severity == ERROR) failCheckCount++; } } \ No newline at end of file diff --git a/src/checkstyle/reporter/IReporter.hx b/src/checkstyle/reporter/IReporter.hx index d5ef56ae..73005f3e 100644 --- a/src/checkstyle/reporter/IReporter.hx +++ b/src/checkstyle/reporter/IReporter.hx @@ -6,9 +6,7 @@ interface IReporter { // After all files checked function finish():Void; // Before file checked - function fileStart(f:CheckFile):Void; - // After file checked - function fileFinish(f:CheckFile):Void; + function addFile(file:CheckFile):Void; // When issue found - function addMessage(m:CheckMessage):Void; + function addMessage(message:Message):Void; } \ No newline at end of file diff --git a/src/checkstyle/reporter/JSONReporter.hx b/src/checkstyle/reporter/JSONReporter.hx index 03cee904..f631883c 100644 --- a/src/checkstyle/reporter/JSONReporter.hx +++ b/src/checkstyle/reporter/JSONReporter.hx @@ -1,39 +1,67 @@ package checkstyle.reporter; +import checkstyle.Message.MessageLocation; import haxe.Json; class JSONReporter extends BaseReporter { - var jsonReport:GlobalReport; - var fileReport:FileReport; + var files:Array; + + public function new(fileCount:Int, checkCount:Int, usedCheckCount:Int, path:String, ns:Bool) { + super(fileCount, checkCount, usedCheckCount, path, ns); + files = []; + } override public function start() { - jsonReport = []; super.start(); } - override public function fileStart(f:CheckFile) { - fileReport = { - fileName: f.name, - messages: [] - }; - jsonReport.push(fileReport); + override public function addFile(f:CheckFile) { + files.push(f.name); } override public function finish() { + var jsonReport:GlobalReport = []; + for (file in files) { + var fileReport:FileReport = makeFileReport(file); + jsonReport.push(fileReport); + } + if (file != null) report.add(Json.stringify(jsonReport)); super.finish(); } - override public function addMessage(m:CheckMessage) { - var reportMessage:ReportMessage = { - line: m.startLine, - column: m.startColumn, - severity: BaseReporter.severityString(m.severity), - message: m.message + function makeFileReport(file:String):FileReport { + var fileReport:FileReport = { + fileName: file, + messages: [] + }; + for (message in messages) { + if (file == message.fileName) { + fileReport.messages.push(makeReportMessage(message, message)); + continue; + } + for (related in message.related) { + if (related.fileName != file) { + continue; + } + fileReport.messages.push(makeReportMessage(message, related)); + } + } + return fileReport; + } + + function makeReportMessage(message:Message, location:MessageLocation):ReportMessage { + return { + line: location.range.start.line, + column: location.range.start.column, + severity: BaseReporter.severityString(message.severity), + message: message.message }; - fileReport.messages.push(reportMessage); + } - switch (m.severity) { + override public function addMessage(message:Message) { + super.addMessage(message); + switch (message.severity) { case ERROR: errors++; case WARNING: @@ -43,7 +71,7 @@ class JSONReporter extends BaseReporter { default: } - Sys.print(applyColour(getMessage(m).toString(), m.severity)); + Sys.print(applyColour(getMessage(message).toString(), message.severity)); } } diff --git a/src/checkstyle/reporter/ProgressReporter.hx b/src/checkstyle/reporter/ProgressReporter.hx index 4ed7c490..0acf7e59 100644 --- a/src/checkstyle/reporter/ProgressReporter.hx +++ b/src/checkstyle/reporter/ProgressReporter.hx @@ -14,7 +14,7 @@ class ProgressReporter implements IReporter { clear(); } - public function fileStart(f:CheckFile) { + public function addFile(f:CheckFile) { clear(); var percentage = Math.floor((f.index + 1) / numFiles * 100); var line = '${percentage}% - ${f.name}'; @@ -30,7 +30,5 @@ class ProgressReporter implements IReporter { Sys.print("\r"); } - public function fileFinish(f:CheckFile) {} - - public function addMessage(m:CheckMessage) {} + public function addMessage(m:Message) {} } \ No newline at end of file diff --git a/src/checkstyle/reporter/ReporterManager.hx b/src/checkstyle/reporter/ReporterManager.hx index 15e8bb1b..58d7418f 100644 --- a/src/checkstyle/reporter/ReporterManager.hx +++ b/src/checkstyle/reporter/ReporterManager.hx @@ -1,24 +1,15 @@ package checkstyle.reporter; -#if ((haxe_ver >= 4.0) && (neko || macro || eval || cpp || hl || java)) -import sys.thread.Mutex; -#elseif neko -import neko.vm.Mutex; -#elseif cpp -import cpp.vm.Mutex; -#elseif java -import java.vm.Mutex; -#else -import checkstyle.utils.Mutex; -#end -import checkstyle.CheckMessage; +import checkstyle.Message; import checkstyle.checks.Category; +import checkstyle.utils.Mutex; class ReporterManager { public static var INSTANCE:ReporterManager = new ReporterManager(); public static var SHOW_PARSE_ERRORS:Bool = false; var reporters:Array; + var delayedMessageCallbacks:Array; var lock:Mutex; function new() { @@ -31,6 +22,11 @@ class ReporterManager { public function clear() { reporters = []; + delayedMessageCallbacks = []; + } + + public function addDelayedMessageCallback(callback:DelayedMessageCallback) { + delayedMessageCallbacks.push(callback); } public function addReporter(r:IReporter) { @@ -42,18 +38,15 @@ class ReporterManager { } public function finish() { + for (delayedMessage in delayedMessageCallbacks) { + addMessages(delayedMessage()); + } for (reporter in reporters) reporter.finish(); } - public function fileStart(f:CheckFile) { + public function addFile(f:CheckFile) { lock.acquire(); - for (reporter in reporters) reporter.fileStart(f); - lock.release(); - } - - public function fileFinish(f:CheckFile) { - lock.acquire(); - for (reporter in reporters) reporter.fileFinish(f); + for (reporter in reporters) reporter.addFile(f); lock.release(); } @@ -64,7 +57,7 @@ class ReporterManager { lock.release(); } - public function addMessages(messages:Array) { + public function addMessages(messages:Array) { if ((messages == null) || (messages.length <= 0)) return; lock.acquire(); messages = filterDuplicateMessages(messages); @@ -72,7 +65,7 @@ class ReporterManager { lock.release(); } - function filterDuplicateMessages(messages:Array):Array { + function filterDuplicateMessages(messages:Array):Array { var filteredMessages = []; for (message in messages) { var anyDuplicates = false; @@ -87,32 +80,61 @@ class ReporterManager { return filteredMessages; } - function areMessagesSame(message1:CheckMessage, message2:CheckMessage):Bool { - return (message1.fileName == message2.fileName - && message1.message == message2.message - && message1.code == message2.code - && message1.startLine == message2.startLine - && message1.startColumn == message2.startColumn - && message1.endLine == message2.endLine - && message1.endColumn == message2.endColumn - && message1.severity == message2.severity - && message1.moduleName == message2.moduleName); + function areMessagesSame(a:Message, b:Message):Bool { + if (a.message != b.message || a.severity != b.severity || a.moduleName != b.moduleName || !messageLocationSame(a, b)) { + return false; + } + if ((a.code == null && b.code != null) || (a.code != null && b.code == null) || (a.code != b.code)) { + return false; + } + if (a.related == null && b.related == null) { + return true; + } + if (a.related == null || b.related == null) { + return false; + } + if (a.related.length != b.related.length) { + return false; + } + for (index in 0...a.related.length) { + if (!messageLocationSame(a.related[index], b.related[index])) { + return false; + } + } + return true; + } + + function messageLocationSame(a:MessageLocation, b:MessageLocation):Bool { + return (a.fileName == b.fileName && messageRangeSame(a.range, b.range)); + } + + function messageRangeSame(a:MessageRange, b:MessageRange):Bool { + return ((a.start.line == b.start.line) && (a.start.column == b.start.column) && (a.end.line == b.end.line) && (a.end.column == b.end.column)); } - function getErrorMessage(e:Any, fileName:String, step:String):CheckMessage { + function getErrorMessage(e:Any, fileName:String, step:String):Message { return { fileName: fileName, - startLine: 1, - endLine: 1, - startColumn: 0, - endColumn: 0, + range: { + start: { + line: 1, + column: 0 + }, + end: { + line: 1, + column: 0 + } + }, severity: ERROR, moduleName: "Checker", categories: [Category.STYLE], points: 1, desc: "", code: '$e', - message: '$step failed: $e\nPlease file a github issue at https://github.com/HaxeCheckstyle/haxe-checkstyle/issues' + message: '$step failed: $e\nPlease file a github issue at https://github.com/HaxeCheckstyle/haxe-checkstyle/issues', + related: [] }; } -} \ No newline at end of file +} + +typedef DelayedMessageCallback = () -> Array; \ No newline at end of file diff --git a/src/checkstyle/reporter/TextReporter.hx b/src/checkstyle/reporter/TextReporter.hx index 09119a56..edbd1c32 100644 --- a/src/checkstyle/reporter/TextReporter.hx +++ b/src/checkstyle/reporter/TextReporter.hx @@ -3,11 +3,11 @@ package checkstyle.reporter; import haxe.io.Output; class TextReporter extends BaseReporter { - override public function addMessage(m:CheckMessage) { - var sb:StringBuf = getMessage(m); + override public function addMessage(message:Message) { + var sb:StringBuf = getMessage(message); var output:Output = Sys.stderr(); - switch (m.severity) { + switch (message.severity) { case ERROR: errors++; case WARNING: @@ -20,7 +20,7 @@ class TextReporter extends BaseReporter { var line = sb.toString(); if (Sys.systemName() == "Windows") output.writeString(line); - else Sys.print(applyColour(line, m.severity)); + else Sys.print(applyColour(line, message.severity)); if (file != null) report.add(line); } } \ No newline at end of file diff --git a/src/checkstyle/reporter/XMLReporter.hx b/src/checkstyle/reporter/XMLReporter.hx index bade7fa8..e86d301c 100644 --- a/src/checkstyle/reporter/XMLReporter.hx +++ b/src/checkstyle/reporter/XMLReporter.hx @@ -1,28 +1,23 @@ package checkstyle.reporter; +import checkstyle.Message.MessageLocation; + class XMLReporter extends BaseReporter { var style:String; - var messageCache:Map>; + var files:Array; /** Solution from mustache.js https://github.com/janl/mustache.js/blob/master/mustache.js#L49 **/ - static var ENTITY_MAP:Map = [ - "&" => "&", - "<" => "<", - ">" => ">", - '"' => """, - "'" => "'", - "/" => "/" - ]; + static var ENTITY_MAP:Map = ["&" => "&", "<" => "<", ">" => ">", '"' => """, "'" => "'"]; - static var ENTITY_RE:EReg = ~/[&<>"'\/]/g; + static var ENTITY_RE:EReg = ~/[&<>"']/g; public function new(numFiles:Int, checkCount:Int, usedCheckCount:Int, path:String, s:String, ns:Bool) { super(numFiles, checkCount, usedCheckCount, path, ns); - messageCache = new Map>(); style = s; + files = []; } override public function start() { @@ -39,30 +34,39 @@ class XMLReporter extends BaseReporter { override public function finish() { var sb = new StringBuf(); + for (file in files) { + makeFileTag(sb, file); + } + sb.add("\n"); if (file != null) report.add(sb.toString()); super.finish(); } - function encode(s:String):String { - return escapeXML(s); + function makeFileTag(sb:StringBuf, file:String) { + sb.add('\t\n'); + for (message in messages) { + if (file == message.fileName) { + sb.add(formatMessage(message, message)); + continue; + } + for (related in message.related) { + if (related.fileName != file) { + continue; + } + sb.add(formatMessage(message, related)); + } + } + sb.add("\t\n"); } - override public function fileStart(f:CheckFile) { - messageCache.set(f.name, []); + function encode(s:String):String { + return escapeXML(s); } - override public function fileFinish(f:CheckFile) { - var sb = new StringBuf(); - sb.add("\t\n"); - var messages:Array = messageCache.get(f.name); - for (m in messages) sb.add(formatMessage(m)); - messageCache.remove(f.name); - sb.add("\t\n"); - if (file != null) report.add(sb.toString()); + override public function addFile(f:CheckFile) { + files.push(f.name); } static function replace(str:String, re:EReg):String { @@ -75,33 +79,28 @@ class XMLReporter extends BaseReporter { return replace(string, ENTITY_RE); } - override public function addMessage(m:CheckMessage) { - if (!messageCache.exists(m.fileName)) messageCache.set(m.fileName, [m]); - else messageCache.get(m.fileName).push(m); - } - - function formatMessage(m:CheckMessage):String { + function formatMessage(message:Message, location:MessageLocation):String { var sb:StringBuf = new StringBuf(); sb.add("\t\t= 0) { + if (location.range.start.column >= 0) { sb.add(" column=\""); - sb.add(m.startColumn); + sb.add(location.range.start.column); sb.add("\""); } sb.add(" severity=\""); - sb.add(BaseReporter.severityString(m.severity)); + sb.add(BaseReporter.severityString(message.severity)); sb.add("\""); sb.add(" message=\""); - sb.add(encode(m.moduleName) + " - " + encode(m.message)); + sb.add(encode(message.moduleName) + " - " + encode(message.message)); sb.add("\""); sb.add(" source=\""); - sb.add(encode(m.fileName)); + sb.add(encode(location.fileName)); sb.add("\"/>\n"); - switch (m.severity) { + switch (message.severity) { case ERROR: errors++; case WARNING: @@ -111,7 +110,7 @@ class XMLReporter extends BaseReporter { default: } - Sys.print(applyColour(getMessage(m).toString(), m.severity)); + Sys.print(applyColour(getMessage(message).toString(), message.severity)); return sb.toString(); } diff --git a/src/checkstyle/utils/ComplexTypeUtils.hx b/src/checkstyle/utils/ComplexTypeUtils.hx index ebb6cd51..6b7543dd 100644 --- a/src/checkstyle/utils/ComplexTypeUtils.hx +++ b/src/checkstyle/utils/ComplexTypeUtils.hx @@ -19,6 +19,8 @@ class ComplexTypeUtils { walkTypedef(d, td.pos, cb); case EUsing(path): walkTypePath(path, path.name, td.pos, cb); + case EStatic(s): + walkStatic(s, td.pos, cb); } } @@ -57,7 +59,7 @@ class ComplexTypeUtils { walkCommonDefinition(d, pos, cb); for (f in d.flags) { switch (f) { - case AFromType(ct) | AToType(ct) | AIsType(ct): + case AbFrom(ct) | AbTo(ct) | AbOver(ct): walkComplexType(ct, f.getName(), pos, cb); default: } @@ -67,7 +69,7 @@ class ComplexTypeUtils { public static function walkImport(sl, mode, cb:ComplexTypeCallback) {} - public static function walkTypedef(d:Definition, pos:Position, cb:ComplexTypeCallback) { + public static function walkTypedef(d:Definition, pos:Position, cb:ComplexTypeCallback) { walkCommonDefinition(d, pos, cb); walkComplexType(d.data, d.name, pos, cb); } @@ -85,6 +87,12 @@ class ComplexTypeUtils { } } + public static function walkStatic(s:Definition, pos:Position, cb:ComplexTypeCallback) { + var field:Field = cast s; + field.kind = s.data; + walkField(field, cb); + } + public static function walkVar(v:Var, pos:Position, cb:ComplexTypeCallback) { if (v.type != null) walkComplexType(v.type, v.name, pos, cb); if (v.expr != null) walkExpr(v.expr, cb); @@ -147,12 +155,10 @@ class ComplexTypeUtils { for (f in fields) walkField(f, cb); case TOptional(t): walkComplexType(t, name, pos, cb); - #if (haxe_ver >= 4.0) case TNamed(n, t): walkComplexType(t, n, pos, cb); case TIntersection(types): for (t in types) walkComplexType(t, name, pos, cb); - #end } } @@ -183,10 +189,6 @@ class ComplexTypeUtils { walkExpr(e, cb); case EVars(vars): for (v in vars) walkVar(v, e.pos, cb); - #if (haxe_ver < 4.0) - case EFunction(name, f): - walkFunction(f, name, e.pos, cb); - #else case EFunction(kind, f): var name:Null = switch (kind) { case null: null; @@ -195,17 +197,11 @@ class ComplexTypeUtils { case FArrow: null; } walkFunction(f, name, e.pos, cb); - #end case EBlock(exprs): for (e in exprs) walkExpr(e, cb); case EFor(it, expr): walkExpr(it, cb); walkExpr(expr, cb); - #if (haxe_ver < 4.0) - case EIn(e1, e2): - walkExpr(e1, cb); - walkExpr(e2, cb); - #end case EIf(econd, eif, eelse): walkExpr(econd, cb); walkExpr(eif, cb); @@ -233,8 +229,10 @@ class ComplexTypeUtils { if (t != null) walkComplexType(t, "", e.pos, cb); case EDisplay(e, displayKind): walkExpr(e, cb); + #if (haxe < version("4.3.0-rc.1")) case EDisplayNew(t): walkTypePath(t, t.name, e.pos, cb); + #end case ETernary(econd, eif, eelse): walkExpr(econd, cb); walkExpr(eif, cb); @@ -245,6 +243,9 @@ class ComplexTypeUtils { case EMeta(s, e): if (s.params != null) for (mp in s.params) walkExpr(mp, cb); walkExpr(e, cb); + case EIs(e, t): + walkExpr(e, cb); + walkComplexType(t, "", e.pos, cb); } } } diff --git a/src/checkstyle/utils/ConfigUtils.hx b/src/checkstyle/utils/ConfigUtils.hx index 5702f337..64315825 100644 --- a/src/checkstyle/utils/ConfigUtils.hx +++ b/src/checkstyle/utils/ConfigUtils.hx @@ -2,9 +2,9 @@ package checkstyle.utils; import checkstyle.Checker; import checkstyle.ChecksInfo.CheckInfo; -import checkstyle.config.Config; -import checkstyle.config.CheckConfig; import checkstyle.checks.Check; +import checkstyle.config.CheckConfig; +import checkstyle.config.Config; import haxe.Json; import haxe.ds.ArraySort; import sys.io.File; @@ -86,15 +86,19 @@ class ConfigUtils { "messages", "checker", "placemap", - "metaName" + "metaName", + "ignoreRE" ]; var checkConfig:CheckConfig = { type: check.getModuleName(), props: {} }; - for (prop in Reflect.fields(check)) { + for (prop in Type.getInstanceFields(Type.getClass(check))) { if (propsNotAllowed.contains(prop)) continue; - Reflect.setField(checkConfig.props, prop, Reflect.field(check, prop)); + + var value = Reflect.field(check, prop); + if (Reflect.isFunction(value)) continue; + Reflect.setField(checkConfig.props, prop, value); } return checkConfig; } diff --git a/src/checkstyle/utils/DummyMutex.hx b/src/checkstyle/utils/DummyMutex.hx new file mode 100644 index 00000000..d62b61e3 --- /dev/null +++ b/src/checkstyle/utils/DummyMutex.hx @@ -0,0 +1,9 @@ +package checkstyle.utils; + +class DummyMutex { + public function new() {} + + public function acquire() {} + + public function release() {} +} \ No newline at end of file diff --git a/src/checkstyle/utils/DummyThread.hx b/src/checkstyle/utils/DummyThread.hx new file mode 100644 index 00000000..039e418a --- /dev/null +++ b/src/checkstyle/utils/DummyThread.hx @@ -0,0 +1,7 @@ +package checkstyle.utils; + +class DummyThread { + public static function create(f:Void -> Void) { + f(); + } +} \ No newline at end of file diff --git a/src/checkstyle/utils/ExprUtils.hx b/src/checkstyle/utils/ExprUtils.hx index c818af17..d36cb819 100644 --- a/src/checkstyle/utils/ExprUtils.hx +++ b/src/checkstyle/utils/ExprUtils.hx @@ -19,6 +19,8 @@ class ExprUtils { walkTypedef(d, cb); case EUsing(path): walkTypePath(path, cb); + case EStatic(s): + walkStatic(s, td.pos, cb); } } @@ -57,7 +59,7 @@ class ExprUtils { walkCommonDefinition(d, cb); for (f in d.flags) { switch (f) { - case AFromType(ct) | AToType(ct) | AIsType(ct): + case AbFrom(ct) | AbTo(ct) | AbOver(ct): walkComplexType(ct, cb); default: } @@ -67,7 +69,7 @@ class ExprUtils { public static function walkImport(sl, mode, cb:Expr -> Void) {} - public static function walkTypedef(d:Definition, cb:Expr -> Void) { + public static function walkTypedef(d:Definition, cb:Expr -> Void) { walkCommonDefinition(d, cb); walkComplexType(d.data, cb); } @@ -85,6 +87,12 @@ class ExprUtils { } } + public static function walkStatic(s:Definition, pos:Position, cb:Expr -> Void) { + var field:Field = cast s; + field.kind = s.data; + walkField(field, cb); + } + public static function walkVar(v:Var, cb:Expr -> Void) { if (v.type != null) walkComplexType(v.type, cb); if (v.expr != null) walkExpr(v.expr, cb); @@ -146,12 +154,10 @@ class ExprUtils { for (f in fields) walkField(f, cb); case TOptional(t): walkComplexType(t, cb); - #if (haxe_ver >= 4.0) case TNamed(n, t): walkComplexType(t, cb); case TIntersection(types): for (t in types) walkComplexType(t, cb); - #end } } @@ -190,11 +196,6 @@ class ExprUtils { case EFor(it, expr): walkExpr(it, cb); walkExpr(expr, cb); - #if (haxe_ver < 4.0) - case EIn(e1, e2): - walkExpr(e1, cb); - walkExpr(e2, cb); - #end case EIf(econd, eif, eelse): walkExpr(econd, cb); walkExpr(eif, cb); @@ -222,8 +223,10 @@ class ExprUtils { if (t != null) walkComplexType(t, cb); case EDisplay(e, displayKind): walkExpr(e, cb); + #if (haxe < version("4.3.0-rc.1")) case EDisplayNew(t): walkTypePath(t, cb); + #end case ETernary(econd, eif, eelse): walkExpr(econd, cb); walkExpr(eif, cb); @@ -234,6 +237,9 @@ class ExprUtils { case EMeta(s, e): if (s.params != null) for (mp in s.params) walkExpr(mp, cb); walkExpr(e, cb); + case EIs(e, t): + walkExpr(e, cb); + walkComplexType(t, cb); } } diff --git a/src/checkstyle/utils/FieldUtils.hx b/src/checkstyle/utils/FieldUtils.hx index bf255c8b..7de85944 100644 --- a/src/checkstyle/utils/FieldUtils.hx +++ b/src/checkstyle/utils/FieldUtils.hx @@ -21,6 +21,10 @@ class FieldUtils { return f.access.contains(AStatic); } + public static function isAbstract(f:Field, p:ParentType):Bool { + return f.access.contains(AAbstract); + } + public static function isDefaultPrivate(f:Field, p:ParentType):Bool { if (p.kind == INTERFACE) return false; if (p.kind == ENUM_ABSTRACT && !f.access.contains(AStatic) && f.kind.match(FVar(_, _))) return false; @@ -52,9 +56,16 @@ class FieldUtils { case EAbstract(a): var metaName = #if (haxeparser > "3.2.0") ":enum" #else ":kwdenum" #end; var kind = a.meta.hasMeta(metaName) ? ENUM_ABSTRACT : ABSTRACT; + for (flag in a.flags) { + switch (flag) { + case AbEnum: + kind = ENUM_ABSTRACT; + default: + } + } return {decl: decl, kind: kind}; case ETypedef(d): - return return {decl: decl, kind: TYPEDEF}; + return {decl: decl, kind: TYPEDEF}; default: return null; } @@ -70,6 +81,6 @@ enum FieldParentKind { } typedef ParentType = { - var decl:TypeDef; + var decl:haxeparser.Data.TypeDef; var kind:FieldParentKind; } \ No newline at end of file diff --git a/src/checkstyle/utils/Mutex.hx b/src/checkstyle/utils/Mutex.hx index 7d1f01ae..a9075eac 100644 --- a/src/checkstyle/utils/Mutex.hx +++ b/src/checkstyle/utils/Mutex.hx @@ -1,11 +1,7 @@ package checkstyle.utils; -#if (!neko && !cpp && !hl && !java) -class Mutex { - public function new() {} - - public function acquire() {} - - public function release() {} -} +#if (neko || macro || eval || cpp || hl || java) +typedef Mutex = sys.thread.Mutex; +#else +typedef Mutex = DummyMutex; #end \ No newline at end of file diff --git a/src/checkstyle/utils/Thread.hx b/src/checkstyle/utils/Thread.hx index e4352019..94a70f37 100644 --- a/src/checkstyle/utils/Thread.hx +++ b/src/checkstyle/utils/Thread.hx @@ -1,9 +1,7 @@ package checkstyle.utils; -#if (!neko && !cpp && !hl) -class Thread { - public static function create(f:Void -> Void) { - f(); - } -} +#if (neko || macro || eval || cpp || hl || java) +typedef Thread = sys.thread.Thread; +#else +typedef Thread = DummyThread; #end \ No newline at end of file diff --git a/test.hxml b/test.hxml index 74246c24..13c01013 100644 --- a/test.hxml +++ b/test.hxml @@ -1,9 +1,2 @@ -buildGlobal.hxml --cp test --lib mcover --lib munit --lib test-adapter --D unittest -# -debug ---macro mcover.MCover.coverage(['checkstyle'], ['src'], ['checkstyle.reporter', 'checkstyle.Main']) +build/commonTest.hxml -x TestMain diff --git a/test/TestMain.hx b/test/TestMain.hx index fb7d9fd3..26027f0e 100644 --- a/test/TestMain.hx +++ b/test/TestMain.hx @@ -1,43 +1,45 @@ -import massive.munit.TestRunner; -import mcover.coverage.MCoverage; -import mcover.coverage.munit.client.MCoverPrintClient; -#if (neko || cpp || hl) -import haxe.EntryPoint; -#end -#if codecov_json -import mcover.coverage.client.CodecovJsonPrintClient; -#else -import mcover.coverage.client.LcovPrintClient; -#end +import checkstyle.checks.CheckTestCase; +import checkstyle.config.ConfigParserTest; +import checkstyle.config.ExcludeManagerTest; +import checkstyle.detect.DetectCodingStyleTest; +import misc.CheckerTest; +import misc.ThreadTest; +import sys.io.File; +import utest.Runner; +import utest.ui.text.DiagnosticsReport; class TestMain { public function new() { - var suites:Array> = [TestSuite]; + var runner:Runner = new Runner(); - var client:MCoverPrintClient = new MCoverPrintClient(); - #if codecov_json - MCoverage.getLogger().addClient(new CodecovJsonPrintClient()); - #else - MCoverage.getLogger().addClient(new LcovPrintClient("Checkstyle Unittests")); - #end - var runner:TestRunner = new TestRunner(client); - runner.completionHandler = completionHandler; - #if (neko || cpp || hl) - EntryPoint.addThread(function() { - while (true) Sys.sleep(1.0); + var failed = false; + runner.onProgress.add(r -> { + if (!r.result.allOk()) { + failed = true; + } }); - #end - runner.run(suites); + runner.onComplete.add(_ -> { + completionHandler(!failed); + }); + + new DiagnosticsReport(runner); + + var testClasses = CompileTime.getAllClasses(CheckTestCase); + for (test in testClasses) { + runner.addCase(Type.createInstance(test, [])); + } + + runner.addCase(new CheckerTest()); + runner.addCase(new ConfigParserTest()); + runner.addCase(new DetectCodingStyleTest()); + runner.addCase(new ThreadTest()); + + runner.run(); } function completionHandler(success:Bool) { - // setupCoverageReport(); - #if eval - if (!success) { - Sys.exit(1); - } - #else - Sys.exit(success ? 0 : 1); + #if instrument + instrument.coverage.Coverage.endCoverage(); #end } diff --git a/test/TestSuite.hx b/test/TestSuite.hx deleted file mode 100644 index 28d9fb62..00000000 --- a/test/TestSuite.hx +++ /dev/null @@ -1,24 +0,0 @@ -import checkstyle.checks.CheckTestCase; -import checkstyle.config.ConfigParserTest; -import checkstyle.config.ExcludeManagerTest; -import checkstyle.detect.DetectCodingStyleTest; -import misc.CheckerTest; -import misc.ThreadTest; - -class TestSuite extends massive.munit.TestSuite { - public function new() { - super(); - - CompileTime.importPackage("checkstyle.checks"); - CompileTime.importPackage("misc"); - - add(CheckerTest); - add(ConfigParserTest); - add(ExcludeManagerTest); - add(DetectCodingStyleTest); - add(ThreadTest); - - var tests = CompileTime.getAllClasses(CheckTestCase); - for (testClass in tests) add(testClass); - } -} \ No newline at end of file diff --git a/test/checkstyle/checks/CheckTestCase.hx b/test/checkstyle/checks/CheckTestCase.hx index 262499ce..0c50325d 100644 --- a/test/checkstyle/checks/CheckTestCase.hx +++ b/test/checkstyle/checks/CheckTestCase.hx @@ -2,21 +2,30 @@ package checkstyle.checks; import byte.ByteData; import checkstyle.CheckFile; -import checkstyle.CheckMessage; import checkstyle.Checker; +import checkstyle.Message; +import checkstyle.config.ExcludeManager; import checkstyle.reporter.IReporter; import checkstyle.reporter.ReporterManager; -class CheckTestCase { +class CheckTestCase implements ITest { static inline var FILE_NAME:String = "Test.hx"; var checker:Checker; var reporter:TestReporter; + public function new() {} + @Before - public function setup() {} + public function setup() { + ExcludeManager.INSTANCE.clear(); + } + + function assertMsg(check:Check, testCase:T, expected:String, ?defines:Array>, ?fileName:String, allowFailingAST:Bool = false, ?pos:PosInfos) { + assertMessages(check, testCase, [expected], defines, fileName, allowFailingAST, pos); + } - function assertMsg(check:Check, testCase:T, expected:String, ?defines:Array>, ?fileName:String, allowFailingAST:Bool = false, + function assertMessages(check:Check, testCase:T, expected:Array, ?defines:Array>, ?fileName:String, allowFailingAST:Bool = false, ?pos:PosInfos) { var re = ~/abstractAndClass ([a-zA-Z0-9]*)/g; if (re.match(testCase)) { @@ -27,17 +36,25 @@ class CheckTestCase { } function assertNoMsg(check:Check, testCase:T, ?fileName:String, allowFailingAST:Bool = false, ?pos:PosInfos) { - assertMsg(check, testCase, "", null, fileName, allowFailingAST, pos); + assertMessages(check, testCase, [], null, fileName, allowFailingAST, pos); } - function actualAssertMsg(check:Check, testCase:String, expected:String, ?defines:Array>, ?fileName:String, allowFailingAST:Bool = false, - ?pos:PosInfos) { - var msg = checkMessage(testCase, check, defines, fileName, allowFailingAST, pos); - Assert.areEqual(expected, msg, pos); + function actualAssertMsg(check:Check, testCase:String, expected:Array, ?defines:Array>, ?fileName:String, + allowFailingAST:Bool = false, ?pos:PosInfos) { + var messages:Array = checkMessages(testCase, check, defines, fileName, allowFailingAST, pos); + if ((expected.length == 1) && (expected.length != messages.length)) { + for (i in 0...messages.length) { + Assert.equals(expected[0], messages[i]?.message, pos); + } + } + Assert.equals(expected.length, messages.length, pos); + for (i in 0...expected.length) { + Assert.equals(expected[i], messages[i]?.message, pos); + } } - function checkMessage(src:String, check:Check, defines:Array>, fileName:String = FILE_NAME, allowFailingAST:Bool = false, - ?pos:PosInfos):String { + function checkMessages(src:String, check:Check, defines:Array>, fileName:String = FILE_NAME, allowFailingAST:Bool = false, + ?pos:PosInfos):Array { // a fresh Checker and Reporter for every checkMessage // to allow multiple independent checkMessage calls in a single test checker = new Checker(allowFailingAST); @@ -49,32 +66,30 @@ class CheckTestCase { ReporterManager.INSTANCE.clear(); ReporterManager.INSTANCE.addReporter(reporter); checker.process([{name: fileName, content: ByteData.ofString(src), index: 0}]); - return reporter.message; + return reporter.messages; } @After - public function tearDown() { + public function teardown() { checker = null; reporter = null; } } class TestReporter implements IReporter { - public var message:String; + public var messages:Array; public function new() { - message = ""; + messages = []; } public function start() {} public function finish() {} - public function fileStart(f:CheckFile) {} - - public function fileFinish(f:CheckFile) {} + public function addFile(f:CheckFile) {} - public function addMessage(m:CheckMessage) { - message = m.message; + public function addMessage(m:Message) { + messages.push(m); } } \ No newline at end of file diff --git a/test/checkstyle/checks/block/BlockBreakingConditionalCheckTest.hx b/test/checkstyle/checks/block/BlockBreakingConditionalCheckTest.hx index bf823051..15a842e0 100644 --- a/test/checkstyle/checks/block/BlockBreakingConditionalCheckTest.hx +++ b/test/checkstyle/checks/block/BlockBreakingConditionalCheckTest.hx @@ -1,6 +1,7 @@ package checkstyle.checks.block; class BlockBreakingConditionalCheckTest extends CheckTestCase { + static inline var MSG_LEFT_CURLY:String = "Left curly has no matching right curly"; static inline var MSG_RIGHT_CURLY:String = "Right curly has no matching left curly"; @Test @@ -14,16 +15,25 @@ class BlockBreakingConditionalCheckTest extends CheckTestCase { assertMsg(check, TEST5, MSG_EOL); assertMsg(check, TEST7, MSG_EOL); assertMsg(check, TEST10, MSG_EOL); - assertMsg(check, NL_CASEBLOCK, MSG_EOL); + assertMessages(check, NL_CASEBLOCK, [MSG_EOL, MSG_EOL, MSG_EOL]); assertMsg(check, NLOW_CASEBLOCK, MSG_EOL); } @@ -44,16 +44,16 @@ class LeftCurlyCheckTest extends CheckTestCase { var check = new LeftCurlyCheck(); check.option = NL; - assertMsg(check, TEST, MSG_NL); + assertMessages(check, TEST, [MSG_NL, MSG_NL, MSG_NL, MSG_NL, MSG_NL, MSG_NL, MSG_NL, MSG_NL]); assertNoMsg(check, TEST13); check.tokens = [OBJECT_DECL]; assertMsg(check, TEST4, MSG_NL); assertNoMsg(check, TEST14); - assertMsg(check, NESTED_OBJECT_LITERAL, MSG_NL); + assertMessages(check, NESTED_OBJECT_LITERAL, [MSG_NL, MSG_NL]); check.tokens = [TYPEDEF_DEF]; - assertMsg(check, TEST14, MSG_NL); + assertMessages(check, TEST14, [MSG_NL, MSG_NL]); check.tokens = [IF]; assertNoMsg(check, TEST1); @@ -73,8 +73,8 @@ class LeftCurlyCheckTest extends CheckTestCase { check.option = NL; assertNoMsg(check, TEST15); assertNoMsg(check, NL_CASEBLOCK); - assertMsg(check, EOL_CASEBLOCK, MSG_NL); - assertMsg(check, NLOW_CASEBLOCK, MSG_NL); + assertMessages(check, EOL_CASEBLOCK, [MSG_NL, MSG_NL, MSG_NL]); + assertMessages(check, NLOW_CASEBLOCK, [MSG_NL, MSG_NL]); } @Test @@ -85,7 +85,7 @@ class LeftCurlyCheckTest extends CheckTestCase { assertNoMsg(check, TEST12); assertNoMsg(check, TEST16); assertNoMsg(check, NLOW_CASEBLOCK); - assertMsg(check, TEST17, MSG_NLOW); + assertMessages(check, TEST17, [MSG_NLOW, MSG_NLOW]); assertMsg(check, TEST18, MSG_NL_SPLIT); assertMsg(check, TEST19, MSG_NL_SPLIT); assertMsg(check, WRAPPED_FUNCTION, MSG_NL_SPLIT); @@ -95,7 +95,7 @@ class LeftCurlyCheckTest extends CheckTestCase { public function testReification() { var check = new LeftCurlyCheck(); check.tokens = [REIFICATION]; - assertMsg(check, MACRO_REIFICATION, MSG_EOL); + assertMessages(check, MACRO_REIFICATION, [MSG_EOL, MSG_EOL]); } @Test @@ -116,21 +116,20 @@ class LeftCurlyCheckTest extends CheckTestCase { var check = new LeftCurlyCheck(); check.tokens = [ARRAY_COMPREHENSION, OBJECT_DECL]; assertNoMsg(check, ARRAY_COMPREHENSION_2_ISSUE_114); - assertMsg(check, ARRAY_COMPREHENSION_ISSUE_114, MSG_EOL); + assertMessages(check, ARRAY_COMPREHENSION_ISSUE_114, [MSG_EOL, MSG_EOL]); check.option = NLOW; assertNoMsg(check, ARRAY_COMPREHENSION_2_ISSUE_114); assertNoMsg(check, ARRAY_COMPREHENSION_NLOW_ISSUE_114); - assertMsg(check, ARRAY_COMPREHENSION_ISSUE_114, MSG_NL); + assertMessages(check, ARRAY_COMPREHENSION_ISSUE_114, [MSG_NL, MSG_NL]); check.option = NL; - assertMsg(check, ARRAY_COMPREHENSION_2_ISSUE_114, MSG_NL); - assertMsg(check, ARRAY_COMPREHENSION_ISSUE_114, MSG_NL); + assertMessages(check, ARRAY_COMPREHENSION_2_ISSUE_114, [MSG_NL, MSG_NL]); + assertMessages(check, ARRAY_COMPREHENSION_ISSUE_114, [MSG_NL, MSG_NL]); } } -@:enum -abstract LeftCurlyCheckTests(String) to String { +enum abstract LeftCurlyCheckTests(String) to String { var TEST = " class Test { function test() { diff --git a/test/checkstyle/checks/block/NeedBracesCheckTest.hx b/test/checkstyle/checks/block/NeedBracesCheckTest.hx index 90ae8b49..5d6ec4fc 100644 --- a/test/checkstyle/checks/block/NeedBracesCheckTest.hx +++ b/test/checkstyle/checks/block/NeedBracesCheckTest.hx @@ -46,9 +46,17 @@ class NeedBracesCheckTest extends CheckTestCase { var check = new NeedBracesCheck(); check.allowSingleLineStatement = false; - assertMsg(check, TEST, MSG_SAME_LINE_WHILE); + assertMessages(check, TEST, [ + MSG_SAME_LINE_IF, + MSG_SAME_LINE_IF, + MSG_SAME_LINE_ELSE, + MSG_SAME_LINE_IF, + MSG_SAME_LINE_IF, + MSG_SAME_LINE_FOR, + MSG_SAME_LINE_WHILE + ]); assertMsg(check, TEST1, MSG_IF); - assertMsg(check, TEST2, MSG_ELSE); + assertMessages(check, TEST2, [MSG_SAME_LINE_IF, MSG_ELSE]); assertNoMsg(check, TEST3); assertMsg(check, TEST4, MSG_IF); assertNoMsg(check, TEST5); @@ -57,7 +65,7 @@ class NeedBracesCheckTest extends CheckTestCase { assertNoMsg(check, TEST8); assertMsg(check, TEST9, MSG_SAME_LINE_FOR); assertMsg(check, TEST10, MSG_SAME_LINE_IF); - assertMsg(check, TEST11, MSG_SAME_LINE_ELSE); + assertMessages(check, TEST11, [MSG_IF, MSG_SAME_LINE_ELSE]); assertMsg(check, TEST12, MSG_SAME_LINE_IF); assertMsg(check, TEST13, MSG_SAME_LINE_IF); assertNoMsg(check, TEST14); @@ -113,9 +121,15 @@ class NeedBracesCheckTest extends CheckTestCase { assertNoMsg(check, TEST14); check.allowSingleLineStatement = false; - assertMsg(check, TEST, MSG_SAME_LINE_IF); + assertMessages(check, TEST, [ + MSG_SAME_LINE_IF, + MSG_SAME_LINE_IF, + MSG_SAME_LINE_ELSE, + MSG_SAME_LINE_IF, + MSG_SAME_LINE_IF + ]); assertMsg(check, TEST10, MSG_SAME_LINE_IF); - assertMsg(check, TEST11, MSG_SAME_LINE_ELSE); + assertMessages(check, TEST11, [MSG_IF, MSG_SAME_LINE_ELSE]); assertMsg(check, TEST13, MSG_SAME_LINE_IF); assertNoMsg(check, TEST14); assertMsg(check, TEST16, MSG_SAME_LINE_ELSE); @@ -143,9 +157,15 @@ class NeedBracesCheckTest extends CheckTestCase { assertNoMsg(check, TEST14); check.allowSingleLineStatement = false; - assertMsg(check, TEST, MSG_SAME_LINE_IF); + assertMessages(check, TEST, [ + MSG_SAME_LINE_IF, + MSG_SAME_LINE_IF, + MSG_SAME_LINE_ELSE, + MSG_SAME_LINE_IF, + MSG_SAME_LINE_IF + ]); assertMsg(check, TEST10, MSG_SAME_LINE_IF); - assertMsg(check, TEST11, MSG_SAME_LINE_ELSE); + assertMessages(check, TEST11, [MSG_IF, MSG_SAME_LINE_ELSE]); assertMsg(check, TEST12, MSG_SAME_LINE_IF); assertMsg(check, TEST13, MSG_SAME_LINE_IF); assertNoMsg(check, TEST14); @@ -235,8 +255,7 @@ class NeedBracesCheckTest extends CheckTestCase { } } -@:enum -abstract NeedBracesCheckTests(String) to String { +enum abstract NeedBracesCheckTests(String) to String { var TEST = " class Test { function test() { diff --git a/test/checkstyle/checks/block/RightCurlyCheckTest.hx b/test/checkstyle/checks/block/RightCurlyCheckTest.hx index c1f2a0f3..ff9d3fbb 100644 --- a/test/checkstyle/checks/block/RightCurlyCheckTest.hx +++ b/test/checkstyle/checks/block/RightCurlyCheckTest.hx @@ -53,7 +53,7 @@ class RightCurlyCheckTest extends CheckTestCase { var check = new RightCurlyCheck(); assertMsg(check, SAMELINE_IF, MSG_ALONE); assertMsg(check, SAMELINE_TRY_CATCH, MSG_ALONE); - assertMsg(check, SAMELINE_NESTED_OBJECT, MSG_ALONE); + assertMessages(check, SAMELINE_NESTED_OBJECT, [MSG_ALONE, MSG_ALONE]); } @Test @@ -84,19 +84,19 @@ class RightCurlyCheckTest extends CheckTestCase { public function testIncorrectSame() { var check = new RightCurlyCheck(); check.option = SAME; - assertMsg(check, SINGLELINE_IF, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_IF, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, SINGLELINE_FOR, MSG_NOT_SAME_LINE); assertMsg(check, SINGLELINE_WHILE, MSG_NOT_SAME_LINE); - assertMsg(check, SINGLELINE_TRY_CATCH, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_TRY_CATCH, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, SINGLELINE_INTERFACE, MSG_NOT_SAME_LINE); - assertMsg(check, SINGLELINE_CLASS, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_CLASS, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, SINGLELINE_TYPEDEF, MSG_NOT_SAME_LINE); assertMsg(check, SINGLELINE_SWITCH, MSG_NOT_SAME_LINE); - assertMsg(check, SINGLELINE_CASE, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_CASE, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, SINGLELINE_OBJECT, MSG_NOT_SAME_LINE); - assertMsg(check, SINGLELINE_ABSTRACT, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_ABSTRACT, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, SINGLELINE_ENUM, MSG_NOT_SAME_LINE); - assertMsg(check, SINGLELINE_NESTED_OBJECT, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_NESTED_OBJECT, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, ALONE_IF, MSG_SAME_LINE); assertMsg(check, ALONE_TRY_CATCH, MSG_SAME_LINE); @@ -127,24 +127,24 @@ class RightCurlyCheckTest extends CheckTestCase { public function testIncorrectAlone() { var check = new RightCurlyCheck(); check.option = ALONE; - assertMsg(check, SINGLELINE_IF, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_IF, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, SINGLELINE_FUNCTION, MSG_NOT_SAME_LINE); assertMsg(check, SINGLELINE_FOR, MSG_NOT_SAME_LINE); assertMsg(check, SINGLELINE_WHILE, MSG_NOT_SAME_LINE); - assertMsg(check, SINGLELINE_TRY_CATCH, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_TRY_CATCH, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, SINGLELINE_INTERFACE, MSG_NOT_SAME_LINE); - assertMsg(check, SINGLELINE_CLASS, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_CLASS, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, SINGLELINE_TYPEDEF, MSG_NOT_SAME_LINE); assertMsg(check, SINGLELINE_SWITCH, MSG_NOT_SAME_LINE); - assertMsg(check, SINGLELINE_CASE, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_CASE, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, SINGLELINE_OBJECT, MSG_NOT_SAME_LINE); - assertMsg(check, SINGLELINE_ABSTRACT, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_ABSTRACT, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, SINGLELINE_ENUM, MSG_NOT_SAME_LINE); - assertMsg(check, SINGLELINE_NESTED_OBJECT, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_NESTED_OBJECT, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertMsg(check, SAMELINE_IF, MSG_ALONE); assertMsg(check, SAMELINE_TRY_CATCH, MSG_ALONE); - assertMsg(check, SAMELINE_NESTED_OBJECT, MSG_ALONE); + assertMessages(check, SAMELINE_NESTED_OBJECT, [MSG_ALONE, MSG_ALONE]); } @Test @@ -159,7 +159,7 @@ class RightCurlyCheckTest extends CheckTestCase { assertNoMsg(check, ALONE_FOR); check.option = SAME; - assertMsg(check, SINGLELINE_IF, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_IF, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertNoMsg(check, SINGLELINE_FOR); assertNoMsg(check, SAMELINE_IF); assertNoMsg(check, SAMELINE_TRY_CATCH); @@ -167,7 +167,7 @@ class RightCurlyCheckTest extends CheckTestCase { assertNoMsg(check, ALONE_FOR); check.option = ALONE; - assertMsg(check, SINGLELINE_IF, MSG_NOT_SAME_LINE); + assertMessages(check, SINGLELINE_IF, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); assertNoMsg(check, SINGLELINE_FOR); assertMsg(check, SAMELINE_IF, MSG_ALONE); assertNoMsg(check, SAMELINE_TRY_CATCH); @@ -182,31 +182,69 @@ class RightCurlyCheckTest extends CheckTestCase { assertNoMsg(check, MACRO_REIFICATION); check.option = SAME; - assertMsg(check, MACRO_REIFICATION, MSG_NOT_SAME_LINE); + assertMessages(check, MACRO_REIFICATION, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); check.option = ALONE; - assertMsg(check, MACRO_REIFICATION, MSG_NOT_SAME_LINE); + assertMessages(check, MACRO_REIFICATION, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); } @Test public function testArrayComprehension() { var check = new RightCurlyCheck(); + check.tokens = [ARRAY_COMPREHENSION, OBJECT_DECL]; + assertNoMsg(check, ARRAY_COMPREHENSION_ISSUE_114); + assertNoMsg(check, ARRAY_COMPREHENSION_2_ISSUE_114); + + check.option = SAME; + assertMessages(check, ARRAY_COMPREHENSION_ISSUE_114, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); + assertNoMsg(check, ARRAY_COMPREHENSION_2_ISSUE_114); + + check.option = ALONE; + assertMessages(check, ARRAY_COMPREHENSION_ISSUE_114, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); + assertNoMsg(check, ARRAY_COMPREHENSION_2_ISSUE_114); + check.tokens = [ARRAY_COMPREHENSION]; + check.option = ALONE_OR_SINGLELINE; assertNoMsg(check, ARRAY_COMPREHENSION_ISSUE_114); assertNoMsg(check, ARRAY_COMPREHENSION_2_ISSUE_114); check.option = SAME; - assertMsg(check, ARRAY_COMPREHENSION_ISSUE_114, MSG_NOT_SAME_LINE); + assertNoMsg(check, ARRAY_COMPREHENSION_ISSUE_114); assertNoMsg(check, ARRAY_COMPREHENSION_2_ISSUE_114); check.option = ALONE; - assertMsg(check, ARRAY_COMPREHENSION_ISSUE_114, MSG_NOT_SAME_LINE); + assertNoMsg(check, ARRAY_COMPREHENSION_ISSUE_114); assertNoMsg(check, ARRAY_COMPREHENSION_2_ISSUE_114); } + + @Test + public function testTokenIfNoObjectDecl() { + var check = new RightCurlyCheck(); + check.tokens = [IF]; + check.option = ALONE; + + assertMessages(check, SINGLELINE_IF, [MSG_NOT_SAME_LINE, MSG_NOT_SAME_LINE]); + + assertNoMsg(check, SINGLELINE_FUNCTION); + assertNoMsg(check, SINGLELINE_FOR); + assertNoMsg(check, SINGLELINE_WHILE); + assertNoMsg(check, SINGLELINE_TRY_CATCH); + assertNoMsg(check, SINGLELINE_INTERFACE); + assertNoMsg(check, SINGLELINE_CLASS); + assertNoMsg(check, SINGLELINE_TYPEDEF); + assertNoMsg(check, SINGLELINE_SWITCH); + assertNoMsg(check, SINGLELINE_CASE); + assertNoMsg(check, SINGLELINE_OBJECT); + assertNoMsg(check, SINGLELINE_ABSTRACT); + assertNoMsg(check, SINGLELINE_ENUM); + assertNoMsg(check, SINGLELINE_NESTED_OBJECT); + + assertNoMsg(check, CONSTRUCTOR_OBJECT_DECL_ISSUE_152); + assertNoMsg(check, SINGLELINE_PATTERN_OBJECT); + } } -@:enum -abstract RightCurlyCheckTests(String) to String { +enum abstract RightCurlyCheckTests(String) to String { var ALONE_OR_SINGLELINE_CORRECT = " class Test { function test() { @@ -547,4 +585,13 @@ abstract RightCurlyCheckTests(String) to String { class Test { var field = new Object({x:0}); }"; + var SINGLELINE_PATTERN_OBJECT = " + class Test { + public function foo() { + var obj = {x: 1, y: 2}; + switch (obj) { + case {x: 2, y: b}: + } + } + }"; } \ No newline at end of file diff --git a/test/checkstyle/checks/coding/ArrowFunctionCheckTest.hx b/test/checkstyle/checks/coding/ArrowFunctionCheckTest.hx index 0ecec333..8a8038ef 100644 --- a/test/checkstyle/checks/coding/ArrowFunctionCheckTest.hx +++ b/test/checkstyle/checks/coding/ArrowFunctionCheckTest.hx @@ -3,7 +3,6 @@ package checkstyle.checks.coding; class ArrowFunctionCheckTest extends CheckTestCase { @Test public function testArrowFunction() { - #if haxe4 var check = new ArrowFunctionCheck(); assertNoMsg(check, CORRECT_ARROW_FUNCTION); @@ -11,12 +10,10 @@ class ArrowFunctionCheckTest extends CheckTestCase { assertMsg(check, ARROW_FUNCTION_WITH_RETURN, "Arrow function should not have explicit returns"); assertMsg(check, ARROW_FUNCTION_WITH_NESTED_FUNCTION, "Arrow function should not include nested functions"); assertMsg(check, ARROW_FUNCTION_WITH_SINGLE_ARGUMENT, "Arrow function should not use parens for single argument invocation"); - #end } @Test public function testAllowReturn() { - #if haxe4 var check = new ArrowFunctionCheck(); check.allowReturn = true; assertNoMsg(check, CORRECT_ARROW_FUNCTION); @@ -25,12 +22,10 @@ class ArrowFunctionCheckTest extends CheckTestCase { assertMsg(check, ARROW_FUNCTION_WITH_CURLY, "Arrow function should not have curlies"); assertMsg(check, ARROW_FUNCTION_WITH_NESTED_FUNCTION, "Arrow function should not include nested functions"); assertMsg(check, ARROW_FUNCTION_WITH_SINGLE_ARGUMENT, "Arrow function should not use parens for single argument invocation"); - #end } @Test public function testAllowFunction() { - #if haxe4 var check = new ArrowFunctionCheck(); check.allowFunction = true; assertNoMsg(check, CORRECT_ARROW_FUNCTION); @@ -39,12 +34,10 @@ class ArrowFunctionCheckTest extends CheckTestCase { assertMsg(check, ARROW_FUNCTION_WITH_RETURN, "Arrow function should not have explicit returns"); assertMsg(check, ARROW_FUNCTION_WITH_CURLY, "Arrow function should not have curlies"); assertMsg(check, ARROW_FUNCTION_WITH_SINGLE_ARGUMENT, "Arrow function should not use parens for single argument invocation"); - #end } @Test public function testAllowCurly() { - #if haxe4 var check = new ArrowFunctionCheck(); check.allowCurlyBody = true; assertNoMsg(check, CORRECT_ARROW_FUNCTION); @@ -53,12 +46,10 @@ class ArrowFunctionCheckTest extends CheckTestCase { assertMsg(check, ARROW_FUNCTION_WITH_RETURN, "Arrow function should not have explicit returns"); assertMsg(check, ARROW_FUNCTION_WITH_NESTED_FUNCTION, "Arrow function should not include nested functions"); assertMsg(check, ARROW_FUNCTION_WITH_SINGLE_ARGUMENT, "Arrow function should not use parens for single argument invocation"); - #end } @Test public function testAllowSingleArg() { - #if haxe4 var check = new ArrowFunctionCheck(); check.allowSingleArgParens = true; assertNoMsg(check, CORRECT_ARROW_FUNCTION); @@ -67,12 +58,10 @@ class ArrowFunctionCheckTest extends CheckTestCase { assertMsg(check, ARROW_FUNCTION_WITH_RETURN, "Arrow function should not have explicit returns"); assertMsg(check, ARROW_FUNCTION_WITH_CURLY, "Arrow function should not have curlies"); assertMsg(check, ARROW_FUNCTION_WITH_NESTED_FUNCTION, "Arrow function should not include nested functions"); - #end } } -@:enum -abstract ArrowFunctionCheckTests(String) to String { +enum abstract ArrowFunctionCheckTests(String) to String { var CORRECT_ARROW_FUNCTION = " abstractAndClass Test { function main() { diff --git a/test/checkstyle/checks/coding/AvoidTernaryOperatorCheckTest.hx b/test/checkstyle/checks/coding/AvoidTernaryOperatorCheckTest.hx index 1727ee0f..9c5419e8 100644 --- a/test/checkstyle/checks/coding/AvoidTernaryOperatorCheckTest.hx +++ b/test/checkstyle/checks/coding/AvoidTernaryOperatorCheckTest.hx @@ -11,8 +11,7 @@ class AvoidTernaryOperatorCheckTest extends CheckTestCase { } } -@:enum -abstract CodeSimilarityCheckTests(String) to String { +enum abstract CodeSimilarityCheckTests(String) to String { var SIMILAR_CODE = " class Test { function a(param1:String, param2:Int):Int { @@ -406,4 +412,77 @@ abstract CodeSimilarityCheckTests(String) to String { return Std.parseInt(paramA); } }"; + var MULTIPLE_SIMILAR_CODES = " + class Test { + function a(param1:String, param2:Int):Int { + var regex = ~/.*/; + switch (param2) { + case 1: + param1 = '111'; + case 2: + param1 = 1.0; + case 3: // test + param1 = '111'; + case 4: + case 5: /* test 2 */ + return param1 && param2; + case 6: + param1 += param2; + case 7: + param1 = param2 + 100; + case 8: + return param1 & param2; + case 9: + param1 = --param2; + } + return Std.parseInt(param1); + } + + function b(paramA:String, paramB:Int):Int { + var regex = ~/[a-z]+/; + switch (paramB) { + case 10: + paramA = '222222'; + case 20: + paramA = 100.0; + case 30: + paramA = '111'; + case 40: + case 50: + return param1 || param2; + case 60: + param1 *= param2; + case 70: + param1 = param2 - 50; + case 80: // comment + return param1 | param2; + case 90: + paramA = ++paramB; + } + return Std.parseInt(paramA); + } + function c(paramA:String, paramB:Int):Int { + var regex = ~/[a-z]+/; + switch (paramB) { + case 10: + paramA = '3333'; + case 20: + paramA = 100.0; + case 30: + paramA = '111'; + case 40: + case 50: + return param1 || param2; + case 60: + param1 *= param2; + case 70: + param1 = param2 - 50; + case 80: // comment + return param1 | param2; + case 90: + paramA = ++paramB; + } + return Std.parseInt(paramA); + } + }"; } \ No newline at end of file diff --git a/test/checkstyle/checks/coding/DefaultComesLastCheckTest.hx b/test/checkstyle/checks/coding/DefaultComesLastCheckTest.hx index 8559a447..4e95deec 100644 --- a/test/checkstyle/checks/coding/DefaultComesLastCheckTest.hx +++ b/test/checkstyle/checks/coding/DefaultComesLastCheckTest.hx @@ -19,8 +19,7 @@ class DefaultComesLastCheckTest extends CheckTestCase { assertNoMsg(check, HIDDEN_FIELDS_CONSTRUCTOR); assertNoMsg(check, HIDDEN_FIELDS_CONSTRUCTOR_VAR); assertNoMsg(check, HIDDEN_FIELDS_CONSTRUCTOR_VAR_WITH_COMMENT); - assertMsg(check, HIDDEN_FIELDS_SETTER, 'Parameter definition of "field2" masks member of same name'); + assertMessages(check, HIDDEN_FIELDS_SETTER, [ + 'Parameter definition of "field1" masks member of same name', + 'Parameter definition of "field2" masks member of same name' + ]); assertMsg(check, HIDDEN_FIELDS_FUNC, 'Parameter definition of "field1" masks member of same name'); assertMsg(check, HIDDEN_FIELDS_FUNC_WITH_COMMENT, 'Parameter definition of "field1" masks member of same name'); } @@ -63,8 +69,7 @@ class HiddenFieldCheckTest extends CheckTestCase { } } -@:enum -abstract HiddenFieldCheckTests(String) to String { +enum abstract HiddenFieldCheckTests(String) to String { var NO_HIDDEN_FIELDS = " class Test { var field1:Int; diff --git a/test/checkstyle/checks/coding/InnerAssignmentCheckTest.hx b/test/checkstyle/checks/coding/InnerAssignmentCheckTest.hx index 688e8325..b6d722e3 100644 --- a/test/checkstyle/checks/coding/InnerAssignmentCheckTest.hx +++ b/test/checkstyle/checks/coding/InnerAssignmentCheckTest.hx @@ -11,6 +11,7 @@ class InnerAssignmentCheckTest extends CheckTestCase assertNoMsg(check, MEMBER_DEF); assertNoMsg(check, METHOD_DEF); assertNoMsg(check, BRACELESS_ANON_FUNC_ISSUE_113); + assertNoMsg(check, ARROW_FUNCTION); } @Test @@ -20,7 +21,7 @@ class InnerAssignmentCheckTest extends CheckTestCase assertMsg(check, IF_RETURN_EXPR, MSG_INNER_ASSIGNMENT); assertMsg(check, WHILE_COND_RETURN, MSG_INNER_ASSIGNMENT); assertMsg(check, SWITCH, MSG_INNER_ASSIGNMENT); - assertMsg(check, SETTER_GETTER_ISSUE_259, MSG_INNER_ASSIGNMENT); + assertMessages(check, SETTER_GETTER_ISSUE_259, [MSG_INNER_ASSIGNMENT, MSG_INNER_ASSIGNMENT]); } @Test @@ -33,6 +34,7 @@ class InnerAssignmentCheckTest extends CheckTestCase assertNoMsg(check, METHOD_DEF); assertNoMsg(check, BRACELESS_ANON_FUNC_ISSUE_113); assertNoMsg(check, SETTER_GETTER_ISSUE_259); + assertNoMsg(check, ARROW_FUNCTION); assertMsg(check, IF_COND, MSG_INNER_ASSIGNMENT); assertMsg(check, IF_RETURN_EXPR, MSG_INNER_ASSIGNMENT); @@ -46,8 +48,7 @@ class InnerAssignmentCheckTest extends CheckTestCase } } -@:enum -abstract InnerAssignmentCheckTests(String) to String { +enum abstract InnerAssignmentCheckTests(String) to String { var IF_COND = " abstractAndClass Test { public function new() { @@ -142,4 +143,10 @@ abstract InnerAssignmentCheckTests(String) to String { class Test { private function set_value(value : String) : String { return this.value = StringTools.trim(value); } }"; + var ARROW_FUNCTION = " + class Test { + public function foo() { + Lamba.iter(sounds, s -> s.volume = 0.75); + } + }"; } \ No newline at end of file diff --git a/test/checkstyle/checks/coding/MagicNumberCheckTest.hx b/test/checkstyle/checks/coding/MagicNumberCheckTest.hx index 9c84c8d4..807aa7e8 100644 --- a/test/checkstyle/checks/coding/MagicNumberCheckTest.hx +++ b/test/checkstyle/checks/coding/MagicNumberCheckTest.hx @@ -6,6 +6,7 @@ class MagicNumberCheckTest extends CheckTestCase { var check = new MagicNumberCheck(); assertNoMsg(check, STANDARD_MAGIC_NUMBERS); assertNoMsg(check, ALLOWED_MAGIC_NUMBER); + assertNoMsg(check, META_NUMBER); } @Test @@ -43,10 +44,36 @@ class MagicNumberCheckTest extends CheckTestCase { assertNoMsg(check, ENUM_ABSTRACT_WITH_CLASS); assertNoMsg(check, HAXE4_ENUM_ABSTRACT); } + + @Test + public function testFinal() { + var check = new MagicNumberCheck(); + assertNoMsg(check, HAXE4_FINAL_VAR); + assertMsg(check, HAXE4_FINAL_FUNCTION, '"7" is a magic number'); + } + + #if (haxe >= version("4.3.0-rc.1")) + @Test + public function testNumberSeparatorAndSuffixes() { + var check = new MagicNumberCheck(); + assertMessages(check, NUMBER_SEPARATOR_AND_SUFFIX, [ + '"1_000.1e2f64" is a magic number', + '"1_000i64" is a magic number', + '"0xabcdei32" is a magic number', + '"0xabcdeu32" is a magic number', + '"1.1E+3f64" is a magic number', + '"1.E+3f64" is a magic number', + '"1E+3f64" is a magic number', + '"1.1f64" is a magic number', + '"5f64" is a magic number', + '".1f64" is a magic number', + '"5i64" is a magic number', + ]); + } + #end } -@:enum -abstract MagicNumberCheckTests(String) to String { +enum abstract MagicNumberCheckTests(String) to String { var STANDARD_MAGIC_NUMBERS = " abstractAndClass Test { public function new() { @@ -93,14 +120,14 @@ abstract MagicNumberCheckTests(String) to String { } }"; var ENUM_ABSTRACT = " - @:enum abstract Style(Int) { + enum abstract Style(Int) { var BOLD = 1; var RED = 91; var BLUE = 94; var MAGENTA = 95; }"; var ENUM_ABSTRACT_WITH_CLASS = " - @:enum abstract Style(Int) { + enum abstract Style(Int) { var BOLD = 1; var RED = 91; var BLUE = 94; @@ -118,4 +145,36 @@ abstract MagicNumberCheckTests(String) to String { var BLUE = 94; var MAGENTA = 95; }"; + var HAXE4_FINAL_VAR = " + abstractAndClass Test { + static inline final VAL1 = 5; + static final VAL2 = 6; + final VAL3 = 7; + }"; + var HAXE4_FINAL_FUNCTION = " + abstractAndClass Test { + final function test() { + val = 7; + } + }"; + var META_NUMBER = " + abstractAndClass Test { + @meta(100) + function test() { + } + }"; + var NUMBER_SEPARATOR_AND_SUFFIX = " + abstractAndClass Test { + var x = 1_000.1e2f64; + var y = 1_000i64; + var z = 0xabcdei32; + var x0 = 0xabcdeu32; + var x1 = 1.1E+3f64; + var x2 = 1.E+3f64; + var x3 = 1E+3f64; + var x4 = 1.1f64; + var x5 = 5f64; + var x6 = .1f64; + var x7 = 5i64; + }"; } \ No newline at end of file diff --git a/test/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.hx b/test/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.hx index b12aa30a..16cb07ca 100644 --- a/test/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.hx +++ b/test/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.hx @@ -12,7 +12,7 @@ class MultipleVariableDeclarationsCheckTest extends CheckTestCase):Void { diff --git a/test/checkstyle/checks/coding/NestedIfDepthCheckTest.hx b/test/checkstyle/checks/coding/NestedIfDepthCheckTest.hx index a56aa075..832c648e 100644 --- a/test/checkstyle/checks/coding/NestedIfDepthCheckTest.hx +++ b/test/checkstyle/checks/coding/NestedIfDepthCheckTest.hx @@ -27,8 +27,7 @@ class NestedIfDepthCheckTest extends CheckTestCase { } } -@:enum -abstract NestedIfDepthCheckTests(String) to String { +enum abstract NestedIfDepthCheckTests(String) to String { var TEST1 = " abstractAndClass Test { public function test(param:Int):Void { diff --git a/test/checkstyle/checks/coding/NestedTryDepthCheckTest.hx b/test/checkstyle/checks/coding/NestedTryDepthCheckTest.hx index 5acfa2d6..aefcab3e 100644 --- a/test/checkstyle/checks/coding/NestedTryDepthCheckTest.hx +++ b/test/checkstyle/checks/coding/NestedTryDepthCheckTest.hx @@ -1,6 +1,9 @@ package checkstyle.checks.coding; class NestedTryDepthCheckTest extends CheckTestCase { + static inline var NESTED_TRY_DEPTH_IS_2_MAX_ALLOWED_IS_1:String = "Nested try depth is 2 (max allowed is 1)"; + static inline var NESTED_TRY_DEPTH_IS_1_MAX_ALLOWED_IS_0:String = "Nested try depth is 1 (max allowed is 0)"; + @Test public function testDefault() { var check = new NestedTryDepthCheck(); @@ -10,7 +13,7 @@ class NestedTryDepthCheckTest extends CheckTestCase { @Test public function testDefaultTooMany() { var check = new NestedTryDepthCheck(); - assertMsg(check, TEST2, "Nested try depth is 2 (max allowed is 1)"); + assertMessages(check, TEST2, [NESTED_TRY_DEPTH_IS_2_MAX_ALLOWED_IS_1, NESTED_TRY_DEPTH_IS_2_MAX_ALLOWED_IS_1]); } @Test @@ -23,12 +26,18 @@ class NestedTryDepthCheckTest extends CheckTestCase { check.max = 0; assertNoMsg(check, TEST1); - assertMsg(check, TEST2, "Nested try depth is 1 (max allowed is 0)"); + assertMessages(check, TEST2, [ + NESTED_TRY_DEPTH_IS_1_MAX_ALLOWED_IS_0, + NESTED_TRY_DEPTH_IS_1_MAX_ALLOWED_IS_0, + NESTED_TRY_DEPTH_IS_1_MAX_ALLOWED_IS_0, + NESTED_TRY_DEPTH_IS_1_MAX_ALLOWED_IS_0, + NESTED_TRY_DEPTH_IS_1_MAX_ALLOWED_IS_0, + NESTED_TRY_DEPTH_IS_1_MAX_ALLOWED_IS_0 + ]); } } -@:enum -abstract NestedTryDepthCheckTests(String) to String { +enum abstract NestedTryDepthCheckTests(String) to String { var TEST1 = " abstractAndClass Test { public function test() { diff --git a/test/checkstyle/checks/coding/NullableParameterCheckTest.hx b/test/checkstyle/checks/coding/NullableParameterCheckTest.hx index 0e431aa1..fc09d770 100644 --- a/test/checkstyle/checks/coding/NullableParameterCheckTest.hx +++ b/test/checkstyle/checks/coding/NullableParameterCheckTest.hx @@ -30,8 +30,7 @@ class NullableParameterCheckTest extends CheckTestCase { } } -@:enum -abstract ReturnCountCheckTests(String) to String { +enum abstract ReturnCountCheckTests(String) to String { var TEST1 = " abstractAndClass Test { function a() { diff --git a/test/checkstyle/checks/coding/SimplifyBooleanExpressionCheckTest.hx b/test/checkstyle/checks/coding/SimplifyBooleanExpressionCheckTest.hx index 0dd05d97..11edb25b 100644 --- a/test/checkstyle/checks/coding/SimplifyBooleanExpressionCheckTest.hx +++ b/test/checkstyle/checks/coding/SimplifyBooleanExpressionCheckTest.hx @@ -23,8 +23,7 @@ class SimplifyBooleanExpressionCheckTest extends CheckTestCase { } } -@:enum -abstract TraceCheckTests(String) to String { +enum abstract TraceCheckTests(String) to String { var TRACE_TEXT = " abstractAndClass Test { function a() { diff --git a/test/checkstyle/checks/coding/UnusedLocalVarCheckTest.hx b/test/checkstyle/checks/coding/UnusedLocalVarCheckTest.hx index 5d68dc0c..f83d0929 100644 --- a/test/checkstyle/checks/coding/UnusedLocalVarCheckTest.hx +++ b/test/checkstyle/checks/coding/UnusedLocalVarCheckTest.hx @@ -21,8 +21,7 @@ class UnusedLocalVarCheckTest extends CheckTestCase { } } -@:enum -abstract UnusedLocalVarCheckTests(String) to String { +enum abstract UnusedLocalVarCheckTests(String) to String { var USED_INDEX = " abstractAndClass Test { function a() { diff --git a/test/checkstyle/checks/coding/VariableInitialisationCheckTest.hx b/test/checkstyle/checks/coding/VariableInitialisationCheckTest.hx index b888ca9a..f8f1bd3f 100644 --- a/test/checkstyle/checks/coding/VariableInitialisationCheckTest.hx +++ b/test/checkstyle/checks/coding/VariableInitialisationCheckTest.hx @@ -16,7 +16,6 @@ class VariableInitialisationCheckTest extends CheckTestCase { + static inline var MSG_REMOVE_COMMENTED_CODE:String = "This block of commented-out lines of code should be removed"; + + @Test + public function testComments() { + var check = new CommentedOutCodeCheck(); + assertMsg(check, BLOCK_COMMENT_VAR, MSG_REMOVE_COMMENTED_CODE); + assertMsg(check, BLOCK_COMMENT_STAR_VAR, MSG_REMOVE_COMMENTED_CODE); + assertMsg(check, BLOCK_COMMENT_MULTI_STAR_VAR, MSG_REMOVE_COMMENTED_CODE); + assertMsg(check, LINE_COMMENT_VAR, MSG_REMOVE_COMMENTED_CODE); + assertMsg(check, LINE_COMMENT_VAR2, MSG_REMOVE_COMMENTED_CODE); + assertMsg(check, LINE_COMMENT_SWITCH, MSG_REMOVE_COMMENTED_CODE); + assertMsg(check, LINE_COMMENT_SWITCH2, MSG_REMOVE_COMMENTED_CODE); + assertNoMsg(check, LINE_COMMENT_EMPTY); + assertNoMsg(check, LINE_COMMENT_SUPRESSED); + // xx assertMessages(check, ONE_STAR_ONE_STAR_ONE_STAR, [MSG_SHOULD_USE_TWO_STARS, MSG_SHOULD_NOT_START_WITH_STAR]); + } +} + +enum abstract CommentedOutCodeCheckTests(String) to String { + var BLOCK_COMMENT_VAR = " + /* + var test:String = ''; + */ + class Test {} + "; + var BLOCK_COMMENT_STAR_VAR = " + /** + var test:String = ''; + **/ + class Test {} + "; + var BLOCK_COMMENT_MULTI_STAR_VAR = " + /********************************************** + var test:String = ''; + **********************************************/ + class Test {} + "; + var LINE_COMMENT_VAR = " + // var test:String = ''; + class Test {} + "; + var LINE_COMMENT_VAR2 = " + // var test:String = ''; + // var test2:String = ''; + // var test3:String = ''; + class Test {} + "; + var LINE_COMMENT_SWITCH = " + // switch(test) { + // case ValueA: + // var a = ''; + // call(a); + // case ValueB: + // case ValueC: + // default: + // } + class Test {} + "; + var LINE_COMMENT_SWITCH2 = " + // text comment + // switch(test) { + // case ValueA: + // var a = ''; + // call(a); + // case ValueB: + // case ValueC: + // default: + // } + class Test {} + "; + var LINE_COMMENT_EMPTY = " + // text comment + // + /* */ + class Test {} + "; + var LINE_COMMENT_SUPRESSED = " + @SuppressWarnings('checkstyle:CommentedOutCode') + class Test { + // var test:String = ''; + } + "; +} \ No newline at end of file diff --git a/test/checkstyle/checks/comments/DocCommentStyleCheckTest.hx b/test/checkstyle/checks/comments/DocCommentStyleCheckTest.hx index 20e0b4b5..75f9856c 100644 --- a/test/checkstyle/checks/comments/DocCommentStyleCheckTest.hx +++ b/test/checkstyle/checks/comments/DocCommentStyleCheckTest.hx @@ -12,7 +12,7 @@ class DocCommentStyleCheckTest extends CheckTestCase assertNoMsg(check, TWO_STAR_NO_STAR_TWO_STAR); assertNoMsg(check, MANY_STARS_NO_STAR_MANY_STARS); assertMsg(check, ONE_STAR_NO_STAR_ONE_STAR, MSG_SHOULD_USE_TWO_STARS); - assertMsg(check, ONE_STAR_ONE_STAR_ONE_STAR, MSG_SHOULD_NOT_START_WITH_STAR); + assertMessages(check, ONE_STAR_ONE_STAR_ONE_STAR, [MSG_SHOULD_USE_TWO_STARS, MSG_SHOULD_NOT_START_WITH_STAR]); assertMsg(check, TWO_STAR_ONE_STAR_TWO_STAR, MSG_SHOULD_NOT_START_WITH_STAR); assertMsg(check, TWO_STAR_TWO_STARS_TWO_STAR, MSG_SHOULD_NOT_START_WITH_STAR); } @@ -46,8 +46,7 @@ class DocCommentStyleCheckTest extends CheckTestCase } } -@:enum -abstract DocCommentStyleCheckTests(String) to String { +enum abstract DocCommentStyleCheckTests(String) to String { var TWO_STAR_NO_STAR_TWO_STAR = " /** comment diff --git a/test/checkstyle/checks/comments/FieldDocCommentCheckTest.hx b/test/checkstyle/checks/comments/FieldDocCommentCheckTest.hx index f52e29a1..9c4de392 100644 --- a/test/checkstyle/checks/comments/FieldDocCommentCheckTest.hx +++ b/test/checkstyle/checks/comments/FieldDocCommentCheckTest.hx @@ -1,8 +1,14 @@ package checkstyle.checks.comments; class FieldDocCommentCheckTest extends CheckTestCase { - static inline var MSG_DOC_FUNC8:String = 'Field "func8" should have documentation'; + static inline var MSG_DOC_FIELD1:String = 'Field "field1" should have documentation'; + static inline var MSG_DOC_FIELD2:String = 'Field "field2" should have documentation'; static inline var MSG_DOC_FUNC4:String = 'Field "func4" should have documentation'; + static inline var MSG_DOC_FUNC5:String = 'Field "func5" should have documentation'; + static inline var MSG_DOC_FUNC5A:String = 'Field "func5a" should have documentation'; + static inline var MSG_DOC_FUNC6:String = 'Field "func6" should have documentation'; + static inline var MSG_DOC_FUNC7:String = 'Field "func7" should have documentation'; + static inline var MSG_DOC_FUNC8:String = 'Field "func8" should have documentation'; static inline var MSG_DOC_PARAM1_FUNC8:String = 'Documentation for parameter "param1" of field "func8" missing'; static inline var MSG_DOC_RETURN_FUNC8:String = 'Documentation for return value of field "func8" missing'; @@ -16,8 +22,15 @@ class FieldDocCommentCheckTest extends CheckTestCase assertNoMsg(check, INTERFACE); assertNoMsg(check, TYPEDEF); - assertMsg(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, MSG_DOC_FUNC8); - assertMsg(check, NO_CLASS_FIELDS_COMMENTED, MSG_DOC_FUNC8); + assertMessages(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, [MSG_DOC_FIELD2, MSG_DOC_FUNC8]); + assertMessages(check, NO_CLASS_FIELDS_COMMENTED, [ + MSG_DOC_FIELD2, + MSG_DOC_FUNC5, + MSG_DOC_FUNC5A, + MSG_DOC_FUNC6, + MSG_DOC_FUNC7, + MSG_DOC_FUNC8 + ]); assertMsg(check, MISSING_PARAM, MSG_DOC_PARAM1_FUNC8); assertMsg(check, MISSING_RETURN, MSG_DOC_RETURN_FUNC8); @@ -38,8 +51,15 @@ class FieldDocCommentCheckTest extends CheckTestCase assertNoMsg(check, INTERFACE); assertNoMsg(check, TYPEDEF); - assertMsg(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, MSG_DOC_FUNC8); - assertMsg(check, NO_CLASS_FIELDS_COMMENTED, MSG_DOC_FUNC8); + assertMessages(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, [MSG_DOC_FIELD2, MSG_DOC_FUNC8]); + assertMessages(check, NO_CLASS_FIELDS_COMMENTED, [ + MSG_DOC_FIELD2, + MSG_DOC_FUNC5, + MSG_DOC_FUNC5A, + MSG_DOC_FUNC6, + MSG_DOC_FUNC7, + MSG_DOC_FUNC8 + ]); assertMsg(check, MISSING_PARAM, MSG_DOC_PARAM1_FUNC8); assertMsg(check, MISSING_RETURN, MSG_DOC_RETURN_FUNC8); @@ -63,21 +83,21 @@ class FieldDocCommentCheckTest extends CheckTestCase check.modifier = PUBLIC; assertNoMsg(check, ALL_CLASS_FIELDS_COMMENTED); assertNoMsg(check, ONLY_PUBLIC_CLASS_FIELDS_COMMENTED); - assertMsg(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, MSG_DOC_FUNC8); + assertMessages(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, [MSG_DOC_FIELD2, MSG_DOC_FUNC8]); assertMsg(check, MISSING_PARAM, MSG_DOC_PARAM1_FUNC8); assertMsg(check, MISSING_RETURN, MSG_DOC_RETURN_FUNC8); check.modifier = PRIVATE; assertNoMsg(check, ALL_CLASS_FIELDS_COMMENTED); - assertMsg(check, ONLY_PUBLIC_CLASS_FIELDS_COMMENTED, MSG_DOC_FUNC4); + assertMessages(check, ONLY_PUBLIC_CLASS_FIELDS_COMMENTED, [MSG_DOC_FIELD1, MSG_DOC_FUNC4]); assertNoMsg(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED); assertNoMsg(check, MISSING_PARAM); assertNoMsg(check, MISSING_RETURN); check.modifier = BOTH; assertNoMsg(check, ALL_CLASS_FIELDS_COMMENTED); - assertMsg(check, ONLY_PUBLIC_CLASS_FIELDS_COMMENTED, MSG_DOC_FUNC4); - assertMsg(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, MSG_DOC_FUNC8); + assertMessages(check, ONLY_PUBLIC_CLASS_FIELDS_COMMENTED, [MSG_DOC_FIELD1, MSG_DOC_FUNC4]); + assertMessages(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, [MSG_DOC_FIELD2, MSG_DOC_FUNC8]); assertMsg(check, MISSING_PARAM, MSG_DOC_PARAM1_FUNC8); assertMsg(check, MISSING_RETURN, MSG_DOC_RETURN_FUNC8); } @@ -88,7 +108,7 @@ class FieldDocCommentCheckTest extends CheckTestCase check.fieldType = VARS; assertNoMsg(check, ALL_CLASS_FIELDS_COMMENTED); assertNoMsg(check, ONLY_PUBLIC_CLASS_FIELDS_COMMENTED); - assertMsg(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, 'Field "field2" should have documentation'); + assertMsg(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, MSG_DOC_FIELD2); assertNoMsg(check, MISSING_PARAM); assertNoMsg(check, MISSING_RETURN); @@ -102,7 +122,7 @@ class FieldDocCommentCheckTest extends CheckTestCase check.fieldType = BOTH; assertNoMsg(check, ALL_CLASS_FIELDS_COMMENTED); assertNoMsg(check, ONLY_PUBLIC_CLASS_FIELDS_COMMENTED); - assertMsg(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, MSG_DOC_FUNC8); + assertMessages(check, ONLY_PRIVATE_CLASS_FIELDS_COMMENTED, [MSG_DOC_FIELD2, MSG_DOC_FUNC8]); assertMsg(check, MISSING_PARAM, MSG_DOC_PARAM1_FUNC8); assertMsg(check, MISSING_RETURN, MSG_DOC_RETURN_FUNC8); } @@ -164,8 +184,7 @@ class FieldDocCommentCheckTest extends CheckTestCase } } -@:enum -abstract FieldDocCommentCheckTests(String) to String { +enum abstract FieldDocCommentCheckTests(String) to String { var ALL_CLASS_FIELDS_COMMENTED = " class Test1 {} class Test2 { diff --git a/test/checkstyle/checks/comments/TODOCommentCheckTest.hx b/test/checkstyle/checks/comments/TODOCommentCheckTest.hx index 06b42ff9..d7deefe8 100644 --- a/test/checkstyle/checks/comments/TODOCommentCheckTest.hx +++ b/test/checkstyle/checks/comments/TODOCommentCheckTest.hx @@ -53,8 +53,7 @@ class TODOCommentCheckTest extends CheckTestCase { } } -@:enum -abstract TODOCommentCheckTests(String) to String { +enum abstract TODOCommentCheckTests(String) to String { var TEST1 = " class Test { // TODO: remove test diff --git a/test/checkstyle/checks/comments/TypeDocCommentCheckTest.hx b/test/checkstyle/checks/comments/TypeDocCommentCheckTest.hx index 7eca7737..bcda047d 100644 --- a/test/checkstyle/checks/comments/TypeDocCommentCheckTest.hx +++ b/test/checkstyle/checks/comments/TypeDocCommentCheckTest.hx @@ -4,7 +4,22 @@ class TypeDocCommentCheckTest extends CheckTestCase { @Test public function testDefault() { var check = new TypeDocCommentCheck(); - checkComments(check, "TTest"); + + var shouldHaveExtra:Array = [ + for (t in ["ATest", "CTest", "ETest", "ITest", "TTest"]) 'Documentation for type "$t" should have at least one extra line of text' + ]; + var shouldContain:Array = [ + for (t in ["ATest", "CTest", "ETest", "ITest", "TTest"]) 'Documentation for type "$t" should contain text' + ]; + var shouldHave:Array = [ + for (t in ["ATest", "CTest", "ETest", "ITest", "TTest"]) 'Type "$t" should have documentation' + ]; + + assertNoMsg(check, ALL_TYPES_COMMENTED); + assertMessages(check, EMPTY_COMMENTS, shouldHaveExtra); + assertMessages(check, EMPTY_COMMENTS_2, shouldHaveExtra); + assertMessages(check, EMPTY_COMMENTS_3, shouldContain); + assertMessages(check, NO_COMMENTS, shouldHave); } @Test @@ -52,8 +67,7 @@ class TypeDocCommentCheckTest extends CheckTestCase { } } -@:enum -abstract TypeDocCommentCheckTests(String) to String { +enum abstract TypeDocCommentCheckTests(String) to String { var ALL_TYPES_COMMENTED = " /** comment @@ -168,7 +182,7 @@ abstract TypeDocCommentCheckTests(String) to String { @:fileXml('file.xml') @:noDebug #end - @:enum abstract Main(Null) + enum abstract Main(Null) { /** text diff --git a/test/checkstyle/checks/design/EmptyPackageCheckTest.hx b/test/checkstyle/checks/design/EmptyPackageCheckTest.hx index 197e2f9e..dc78669a 100644 --- a/test/checkstyle/checks/design/EmptyPackageCheckTest.hx +++ b/test/checkstyle/checks/design/EmptyPackageCheckTest.hx @@ -23,8 +23,7 @@ class EmptyPackageCheckTest extends CheckTestCase { } } -@:enum -abstract EmptyPackageCheckTests(String) to String { +enum abstract EmptyPackageCheckTests(String) to String { var TEST1 = " package; diff --git a/test/checkstyle/checks/design/InterfaceCheckTest.hx b/test/checkstyle/checks/design/InterfaceCheckTest.hx index 5f06b7c6..8c09eb15 100644 --- a/test/checkstyle/checks/design/InterfaceCheckTest.hx +++ b/test/checkstyle/checks/design/InterfaceCheckTest.hx @@ -34,8 +34,7 @@ class InterfaceCheckTest extends CheckTestCase { } } -@:enum -abstract InterfaceCheckTests(String) to String { +enum abstract InterfaceCheckTests(String) to String { var TEST1 = " interface IComponentController { var a:Int = 1; diff --git a/test/checkstyle/checks/design/UnnecessaryConstructorCheckTest.hx b/test/checkstyle/checks/design/UnnecessaryConstructorCheckTest.hx index 21fdbd3c..5296955f 100644 --- a/test/checkstyle/checks/design/UnnecessaryConstructorCheckTest.hx +++ b/test/checkstyle/checks/design/UnnecessaryConstructorCheckTest.hx @@ -48,8 +48,7 @@ class UnnecessaryConstructorCheckTest extends CheckTestCase { assertNoMsg(check, IMPORT_BASE_CLASS); assertNoMsg(check, IMPORT_AS); assertNoMsg(check, IMPORT_IN_STATIC_FUNC); + assertNoMsg(check, METADATA_IMPORT); } @Test @@ -76,8 +77,7 @@ class UnusedImportCheckTest extends CheckTestCase { } } -@:enum -abstract UnusedImportCheckTests(String) to String { +enum abstract UnusedImportCheckTests(String) to String { var ALL_IMPORTS_USED = " package checkstyle.test; @@ -259,4 +259,11 @@ abstract UnusedImportCheckTests(String) to String { trace ('${Check3}'); } }"; + var METADATA_IMPORT = " + abstractAndClass Test { + private static var SRC = + { + @:import h3d.shader.BaseMesh; + }; + }"; } \ No newline at end of file diff --git a/test/checkstyle/checks/literal/ArrayLiteralCheckTest.hx b/test/checkstyle/checks/literal/ArrayLiteralCheckTest.hx index c3061ad7..872eaf23 100644 --- a/test/checkstyle/checks/literal/ArrayLiteralCheckTest.hx +++ b/test/checkstyle/checks/literal/ArrayLiteralCheckTest.hx @@ -12,8 +12,7 @@ class ArrayLiteralCheckTest extends CheckTestCase { } } -@:enum -abstract ArrayLiteralCheckTests(String) to String { +enum abstract ArrayLiteralCheckTests(String) to String { var TEST1 = " abstractAndClass Test { var _arr:Array = new Array(); diff --git a/test/checkstyle/checks/literal/ERegLiteralCheckTest.hx b/test/checkstyle/checks/literal/ERegLiteralCheckTest.hx index 24da8083..6f503617 100644 --- a/test/checkstyle/checks/literal/ERegLiteralCheckTest.hx +++ b/test/checkstyle/checks/literal/ERegLiteralCheckTest.hx @@ -22,8 +22,7 @@ class ERegLiteralCheckTest extends CheckTestCase { } } -@:enum -abstract ERegLiteralCheckTests(String) to String { +enum abstract ERegLiteralCheckTests(String) to String { var TEST1 = " abstractAndClass Test { var _reg:EReg = new EReg('test', 'i'); diff --git a/test/checkstyle/checks/literal/HexadecimalLiteralCheckTest.hx b/test/checkstyle/checks/literal/HexadecimalLiteralCheckTest.hx index 23edd9ca..73429331 100644 --- a/test/checkstyle/checks/literal/HexadecimalLiteralCheckTest.hx +++ b/test/checkstyle/checks/literal/HexadecimalLiteralCheckTest.hx @@ -19,8 +19,7 @@ class HexadecimalLiteralCheckTest extends CheckTestCase { assertNoMsg(check, INTERPOLATION); assertNoMsg(check, NO_INTERPOLATION); assertNoMsg(check, SINGLE_QUOTE_WITH_EXCEPTION); - assertMsg(check, DOUBLE_QUOTE, 'String "test" uses double quotes instead of single quotes'); + assertMessages(check, DOUBLE_QUOTE, [ + 'String "check" uses double quotes instead of single quotes', + 'String "test" uses double quotes instead of single quotes', + 'String "xml" uses double quotes instead of single quotes', + 'String "test" uses double quotes instead of single quotes' + ]); } @Test @@ -31,8 +41,28 @@ class StringLiteralCheckTest extends CheckTestCase { check.policy = ONLY_DOUBLE; check.allowException = false; assertNoMsg(check, DOUBLE_QUOTE); - assertMsg(check, SINGLE_QUOTE, 'String "test" uses single quotes instead of double quotes'); - assertMsg(check, INTERPOLATION, 'String "$$value is $${i++} $$i" uses single quotes instead of double quotes'); + assertMessages(check, SINGLE_QUOTE, [ + 'String "check" uses single quotes instead of double quotes', + 'String "test" uses single quotes instead of double quotes', + 'String "xml" uses single quotes instead of double quotes', + 'String "test" uses single quotes instead of double quotes' + ]); + assertMessages(check, INTERPOLATION, [ + 'String "Value is $$i" uses single quotes instead of double quotes', + 'String "Value is $$i" uses single quotes instead of double quotes', + 'String "$$value is i" uses single quotes instead of double quotes', + 'String "$$value is i" uses single quotes instead of double quotes', + 'String "$$value" uses single quotes instead of double quotes', + 'String "$$value" uses single quotes instead of double quotes', + 'String "Value is $${i++}" uses single quotes instead of double quotes', + 'String "Value is $${i++}" uses single quotes instead of double quotes', + 'String "Value is $${i++}$$" uses single quotes instead of double quotes', + 'String "Value is $${i++}$$" uses single quotes instead of double quotes', + 'String "Value is $${i++} $$i" uses single quotes instead of double quotes', + 'String "Value is $${i++} $$i" uses single quotes instead of double quotes', + 'String "$$value is $${i++} $$i" uses single quotes instead of double quotes', + 'String "$$value is $${i++} $$i" uses single quotes instead of double quotes' + ]); #if (haxeparser < "3.3.0") assertMsg(check, NO_INTERPOLATION, 'String "value $$$$is i" uses single quotes instead of double quotes'); #end @@ -46,8 +76,28 @@ class StringLiteralCheckTest extends CheckTestCase { check.allowException = true; assertNoMsg(check, DOUBLE_QUOTE); assertNoMsg(check, DOUBLE_QUOTE_WITH_EXCEPTION); - assertMsg(check, SINGLE_QUOTE, 'String "test" uses single quotes instead of double quotes'); - assertMsg(check, INTERPOLATION, 'String "$$value is $${i++} $$i" uses single quotes instead of double quotes'); + assertMessages(check, SINGLE_QUOTE, [ + 'String "check" uses single quotes instead of double quotes', + 'String "test" uses single quotes instead of double quotes', + 'String "xml" uses single quotes instead of double quotes', + 'String "test" uses single quotes instead of double quotes' + ]); + assertMessages(check, INTERPOLATION, [ + 'String "Value is $$i" uses single quotes instead of double quotes', + 'String "Value is $$i" uses single quotes instead of double quotes', + 'String "$$value is i" uses single quotes instead of double quotes', + 'String "$$value is i" uses single quotes instead of double quotes', + 'String "$$value" uses single quotes instead of double quotes', + 'String "$$value" uses single quotes instead of double quotes', + 'String "Value is $${i++}" uses single quotes instead of double quotes', + 'String "Value is $${i++}" uses single quotes instead of double quotes', + 'String "Value is $${i++}$$" uses single quotes instead of double quotes', + 'String "Value is $${i++}$$" uses single quotes instead of double quotes', + 'String "Value is $${i++} $$i" uses single quotes instead of double quotes', + 'String "Value is $${i++} $$i" uses single quotes instead of double quotes', + 'String "$$value is $${i++} $$i" uses single quotes instead of double quotes', + 'String "$$value is $${i++} $$i" uses single quotes instead of double quotes' + ]); #if (haxeparser < "3.3.0") assertMsg(check, NO_INTERPOLATION, 'String "value $$$$is i" uses single quotes instead of double quotes'); #end @@ -59,7 +109,12 @@ class StringLiteralCheckTest extends CheckTestCase { check.allowException = false; assertNoMsg(check, DOUBLE_QUOTE); assertNoMsg(check, INTERPOLATION); - assertMsg(check, SINGLE_QUOTE, 'String "test" uses single quotes instead of double quotes'); + assertMessages(check, SINGLE_QUOTE, [ + 'String "check" uses single quotes instead of double quotes', + 'String "test" uses single quotes instead of double quotes', + 'String "xml" uses single quotes instead of double quotes', + 'String "test" uses single quotes instead of double quotes' + ]); #if (haxeparser < "3.3.0") assertMsg(check, NO_INTERPOLATION, 'String "value $$$$is i" uses single quotes instead of double quotes'); #end @@ -73,15 +128,19 @@ class StringLiteralCheckTest extends CheckTestCase { assertNoMsg(check, DOUBLE_QUOTE); assertNoMsg(check, INTERPOLATION); assertNoMsg(check, DOUBLE_QUOTE_WITH_EXCEPTION); - assertMsg(check, SINGLE_QUOTE, 'String "test" uses single quotes instead of double quotes'); + assertMessages(check, SINGLE_QUOTE, [ + 'String "check" uses single quotes instead of double quotes', + 'String "test" uses single quotes instead of double quotes', + 'String "xml" uses single quotes instead of double quotes', + 'String "test" uses single quotes instead of double quotes' + ]); #if (haxeparser < "3.3.0") assertMsg(check, NO_INTERPOLATION, 'String "value $$$$is i" uses single quotes instead of double quotes'); #end } } -@:enum -abstract StringLiteralCheckTests(String) to String { +enum abstract StringLiteralCheckTests(String) to String { var SINGLE_QUOTE = " class Test { static var a:String = 'check'; diff --git a/test/checkstyle/checks/meta/RedundantAccessMetaCheckTest.hx b/test/checkstyle/checks/meta/RedundantAccessMetaCheckTest.hx index 68f461a2..300f7a10 100644 --- a/test/checkstyle/checks/meta/RedundantAccessMetaCheckTest.hx +++ b/test/checkstyle/checks/meta/RedundantAccessMetaCheckTest.hx @@ -13,9 +13,19 @@ class RedundantAccessMetaCheckTest extends CheckTestCase { static inline var ERROR_INLINE_VAR:String = 'Consider using "inline final" for field "test"'; static inline var ERROR_PUBLIC_STATIC:String = 'Consider making public static field "test" "final" or "private"'; @@ -18,10 +17,8 @@ class FinalCheckTest extends CheckTestCase { assertMsg(check, TEST_PUBLIC_STATIC_VAR, ERROR_PUBLIC_STATIC); } } -#end -@:enum -abstract FinalCheckTests(String) to String { +enum abstract FinalCheckTests(String) to String { var TEST_INLINE_FINAL = " abstractAndClass Test { public inline final test:String = '0'; diff --git a/test/checkstyle/checks/modifier/ModifierOrderCheckTest.hx b/test/checkstyle/checks/modifier/ModifierOrderCheckTest.hx index aa0df528..dff77e1e 100644 --- a/test/checkstyle/checks/modifier/ModifierOrderCheckTest.hx +++ b/test/checkstyle/checks/modifier/ModifierOrderCheckTest.hx @@ -5,9 +5,7 @@ class ModifierOrderCheckTest extends CheckTestCase { public function testCorrectOrder() { var check = new ModifierOrderCheck(); assertNoMsg(check, TEST1); - #if haxe4 assertNoMsg(check, TEST_FINAL); - #end } @Test @@ -25,7 +23,11 @@ class ModifierOrderCheckTest extends CheckTestCase { public function testModifiers() { var check = new ModifierOrderCheck(); check.modifiers = [DYNAMIC, PUBLIC_PRIVATE, OVERRIDE, INLINE, STATIC, MACRO]; - assertMsg(check, TEST1, 'modifier order for field "test6" is "public static inline" but should be "public inline static"'); + assertMessages(check, TEST1, [ + 'modifier order for field "test1" is "override public" but should be "public override"', + 'modifier order for field "test2" is "override private" but should be "private override"', + 'modifier order for field "test6" is "public static inline" but should be "public inline static"' + ]); assertNoMsg(check, TEST2); assertNoMsg(check, TEST3); assertNoMsg(check, TEST4); @@ -41,8 +43,7 @@ class ModifierOrderCheckTest extends CheckTestCase { } } -@:enum -abstract ModifierOrderCheckTests(String) to String { +enum abstract ModifierOrderCheckTests(String) to String { var TEST1 = " abstractAndClass Test { override public function test1() {} diff --git a/test/checkstyle/checks/modifier/PublicAccessorCheckTest.hx b/test/checkstyle/checks/modifier/PublicAccessorCheckTest.hx index 60b3756d..9a0a8f2d 100644 --- a/test/checkstyle/checks/modifier/PublicAccessorCheckTest.hx +++ b/test/checkstyle/checks/modifier/PublicAccessorCheckTest.hx @@ -20,8 +20,7 @@ class PublicAccessorCheckTest extends CheckTestCase { } } -@:enum -abstract PublicAccessorCheckTests(String) to String { +enum abstract PublicAccessorCheckTests(String) to String { var NON_ACCESSOR = " abstractAndClass Test { public function _set_test() {} diff --git a/test/checkstyle/checks/modifier/RedundantModifierCheckTest.hx b/test/checkstyle/checks/modifier/RedundantModifierCheckTest.hx index da494f18..2e16a222 100644 --- a/test/checkstyle/checks/modifier/RedundantModifierCheckTest.hx +++ b/test/checkstyle/checks/modifier/RedundantModifierCheckTest.hx @@ -28,7 +28,7 @@ class RedundantModifierCheckTest extends CheckTestCase { } } -@:enum -abstract ConstantNameCheckTests(String) to String { +enum abstract ConstantNameCheckTests(String) to String { var TEST = " abstractAndClass Test { static var COUNT:Int = 1; diff --git a/test/checkstyle/checks/naming/FileNameCaseCheckTest.hx b/test/checkstyle/checks/naming/FileNameCaseCheckTest.hx new file mode 100644 index 00000000..b113da3b --- /dev/null +++ b/test/checkstyle/checks/naming/FileNameCaseCheckTest.hx @@ -0,0 +1,73 @@ +package checkstyle.checks.naming; + +class FileNameCaseCheckTest extends CheckTestCase { + @Test + public function testCorrectNaming() { + var check = new FileNameCaseCheck(); + assertNoMsg(check, IMPORT, "import.hx"); + assertNoMsg(check, TYPES, "Test.hx"); + assertNoMsg(check, TYPES, "ITest.hx"); + assertNoMsg(check, TYPES, "Test2.hx"); + assertNoMsg(check, TYPES, "Test3.hx"); + } + + @Test + public function testIncorrectImport() { + var check = new FileNameCaseCheck(); + assertMsg(check, IMPORT, '"Import.hx" contains no types - consider renaming to "import.hx"', "Import.hx"); + assertMsg(check, TYPES, '"import.hx" contains types', "import.hx"); + } + + @Test + public function testModuleWithNoTypes() { + var check = new FileNameCaseCheck(); + assertMsg(check, IMPORT, '"Main.hx" defines no type with name "Main"', "Main.hx"); + } + + @Test + public function testIncorrectCase() { + var check = new FileNameCaseCheck(); + + assertMessages(check, TYPES, [ + '"TeSt.hx" defines type "Test" using different case', + '"TeSt.hx" defines no type with name "TeSt"' + ], "TeSt.hx"); + + assertMessages(check, TYPES, [ + '"Itest.hx" defines type "ITest" using different case', + '"Itest.hx" defines no type with name "Itest"' + ], "Itest.hx"); + } +} + +enum abstract FileNameCaseCheckTests(String) to String { + var IMPORT = " + import haxe.io.Path; + import checkstyle.checks.Check; + + using StringTools; + "; + + var TYPES = " + class Test { + public var a:Int; + private var b:Int; + static var COUNT:Int = 1; + static inline var COUNT2:Int = 1; + var count5:Int = 1; + } + + interface ITest { + + } + + enum Test2 { + count; + a; + } + + typedef Test3 = { + var count1:Int; + var count2:String; + }"; +} \ No newline at end of file diff --git a/test/checkstyle/checks/naming/ListenerNameCheckTest.hx b/test/checkstyle/checks/naming/ListenerNameCheckTest.hx index dcf259cc..490a0401 100644 --- a/test/checkstyle/checks/naming/ListenerNameCheckTest.hx +++ b/test/checkstyle/checks/naming/ListenerNameCheckTest.hx @@ -14,8 +14,7 @@ class ListenerNameCheckTest extends CheckTestCase { } } -@:enum -abstract ListenerNameCheckTests(String) to String { +enum abstract ListenerNameCheckTests(String) to String { var TEST = " abstractAndClass Test { var a:Stage; diff --git a/test/checkstyle/checks/naming/LocalVariableNameCheckTest.hx b/test/checkstyle/checks/naming/LocalVariableNameCheckTest.hx index fe065e5d..101e215c 100644 --- a/test/checkstyle/checks/naming/LocalVariableNameCheckTest.hx +++ b/test/checkstyle/checks/naming/LocalVariableNameCheckTest.hx @@ -34,15 +34,17 @@ class LocalVariableNameCheckTest extends CheckTestCase { assertMsg(check, TEST2, memberMessage); assertMsg(check, TEST3, 'Invalid typedef member signature: "Count" (name should be "~/${check.format}/")'); assertMsg(check, TEST4, memberMessage); - assertMsg(check, TEST5, 'Invalid enum member signature: "VALUE_TEST" (name should be "~/${check.format}/")'); + assertMessages(check, TEST5, [ + 'Invalid enum member signature: "VALUE_TEST_" (name should be "~/^[a-z][a-zA-Z0-9]*$/")', + 'Invalid enum member signature: "VALUE_TEST" (name should be "~/${check.format}/")' + ]); } @Test @@ -124,8 +134,14 @@ class MemberNameCheckTest extends CheckTestCase { assertNoMsg(check, TEST1); assertNoMsg(check, TEST3); assertNoMsg(check, TEST4); - assertMsg(check, TEST5, 'Invalid enum member signature: "VALUE_TEST" (name should be "~/${check.format}/")'); - assertMsg(check, TEST6, 'Invalid enum member signature: "VALUE" (name should be "~/${check.format}/")'); + assertMessages(check, TEST5, [ + 'Invalid enum member signature: "VALUE_TEST_" (name should be "~/${check.format}/")', + 'Invalid enum member signature: "VALUE_TEST" (name should be "~/${check.format}/")' + ]); + assertMessages(check, TEST6, [ + 'Invalid enum member signature: "VALUE_" (name should be "~/${check.format}/")', + 'Invalid enum member signature: "VALUE" (name should be "~/${check.format}/")' + ]); assertNoMsg(check, ABSTRACT_FIELDS); } @@ -147,14 +163,27 @@ class MemberNameCheckTest extends CheckTestCase { var check = new MemberNameCheck(); check.format = "^[A-Z_]*$"; - assertMsg(check, TEST, 'Invalid typedef member signature: "count2" (name should be "~/${check.format}/")'); + assertMessages(check, TEST, [ + 'Invalid member signature: "a" (name should be "~/${check.format}/")', + 'Invalid member signature: "b" (name should be "~/${check.format}/")', + 'Invalid member signature: "example" (name should be "~/${check.format}/")', + 'Invalid member signature: "count5" (name should be "~/${check.format}/")', + 'Invalid enum member signature: "count" (name should be "~/${check.format}/")', + 'Invalid enum member signature: "a" (name should be "~/${check.format}/")', + 'Invalid typedef member signature: "count1" (name should be "~/${check.format}/")', + 'Invalid typedef member signature: "count2" (name should be "~/${check.format}/")' + ]); assertMsg(check, TEST1, 'Invalid member signature: "Count" (name should be "~/${check.format}/")'); assertMsg(check, TEST2, 'Invalid member signature: "Count" (name should be "~/${check.format}/")'); assertMsg(check, TEST3, 'Invalid typedef member signature: "Count" (name should be "~/${check.format}/")'); assertNoMsg(check, TEST4); assertNoMsg(check, TEST5); assertNoMsg(check, TEST6); - assertMsg(check, ABSTRACT_FIELDS, 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")'); + assertMessages(check, ABSTRACT_FIELDS, [ + 'Invalid member signature: "EnumConstructor1" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor2" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")' + ]); check.format = "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"; assertMsg(check, TEST5, 'Invalid enum member signature: "VALUE_TEST_" (name should be "~/${check.format}/")'); @@ -168,11 +197,19 @@ class MemberNameCheckTest extends CheckTestCase { check.format = "^[A-Z_]*$"; assertNoMsg(check, TEST); - assertMsg(check, ABSTRACT_FIELDS, 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")'); + assertMessages(check, ABSTRACT_FIELDS, [ + 'Invalid member signature: "EnumConstructor1" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor2" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")' + ]); check.tokens = [ABSTRACT]; assertNoMsg(check, TEST); - assertMsg(check, ABSTRACT_FIELDS, 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")'); + assertMessages(check, ABSTRACT_FIELDS, [ + 'Invalid member signature: "EnumConstructor1" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor2" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")' + ]); check.tokens = [ABSTRACT, PRIVATE]; assertNoMsg(check, ABSTRACT_FIELDS); @@ -184,13 +221,25 @@ class MemberNameCheckTest extends CheckTestCase { assertNoMsg(check, ABSTRACT_FIELDS); check.tokens = [ABSTRACT, PUBLIC]; - assertMsg(check, ABSTRACT_FIELDS, 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")'); + assertMessages(check, ABSTRACT_FIELDS, [ + 'Invalid member signature: "EnumConstructor1" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor2" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")' + ]); check.tokens = [PUBLIC]; - assertMsg(check, ABSTRACT_FIELDS, 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")'); + assertMessages(check, ABSTRACT_FIELDS, [ + 'Invalid member signature: "EnumConstructor1" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor2" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")' + ]); check.tokens = [ABSTRACT, CLASS, PUBLIC]; - assertMsg(check, ABSTRACT_FIELDS, 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")'); + assertMessages(check, ABSTRACT_FIELDS, [ + 'Invalid member signature: "EnumConstructor1" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor2" (name should be "~/${check.format}/")', + 'Invalid member signature: "EnumConstructor3" (name should be "~/${check.format}/")' + ]); } @Test @@ -201,8 +250,7 @@ class MemberNameCheckTest extends CheckTestCase { } } -@:enum -abstract MemberNameCheckTests(String) to String { +enum abstract MemberNameCheckTests(String) to String { var TEST = " class Test { public var a:Int; @@ -260,7 +308,7 @@ abstract MemberNameCheckTests(String) to String { VALUE; }"; var ABSTRACT_FIELDS = " - @:enum abstract MyAbstract(Int) from Int to Int + enum abstract MyAbstract(Int) from Int to Int { static public inline var NORMAL_CONST = 'hello, world'; diff --git a/test/checkstyle/checks/naming/MethodNameCheckTest.hx b/test/checkstyle/checks/naming/MethodNameCheckTest.hx index 480d0e0d..df702fef 100644 --- a/test/checkstyle/checks/naming/MethodNameCheckTest.hx +++ b/test/checkstyle/checks/naming/MethodNameCheckTest.hx @@ -6,16 +6,20 @@ class MethodNameCheckTest extends CheckTestCase { var check = new MethodNameCheck(); assertNoMsg(check, TEST); assertNoMsg(check, TEST4); + assertNoMsg(check, TEST_SUPPRESS_CLASS); } @Test public function testWrongNaming() { var check = new MethodNameCheck(); + var testMessage = 'Invalid method name signature: "Test" (name should be "~/${check.format}/")'; + var test1Message = 'Invalid method name signature: "Test1" (name should be "~/${check.format}/")'; + var test2Message = 'Invalid method name signature: "Test2" (name should be "~/${check.format}/")'; var test3Message = 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'; - assertMsg(check, TEST1, test3Message); - assertMsg(check, TEST2, test3Message); + assertMessages(check, TEST1, [testMessage, test2Message, test3Message]); + assertMessages(check, TEST2, [testMessage, test1Message, test2Message, test3Message]); assertMsg(check, TEST3, 'Invalid method name signature: "Test" (name should be "~/${check.format}/")'); - assertMsg(check, TEST5, test3Message); + assertMessages(check, TEST5, [testMessage, test1Message, test3Message]); } @Test @@ -24,23 +28,29 @@ class MethodNameCheckTest extends CheckTestCase { check.ignoreExtern = false; var testMessage = 'Invalid method name signature: "Test" (name should be "~/${check.format}/")'; + var test1Message = 'Invalid method name signature: "Test1" (name should be "~/${check.format}/")'; + var test2Message = 'Invalid method name signature: "Test2" (name should be "~/${check.format}/")'; var test3Message = 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'; assertNoMsg(check, TEST); - assertMsg(check, TEST1, test3Message); - assertMsg(check, TEST2, test3Message); + assertMessages(check, TEST1, [testMessage, test2Message, test3Message]); + assertMessages(check, TEST2, [testMessage, test1Message, test2Message, test3Message]); assertMsg(check, TEST3, testMessage); assertMsg(check, TEST4, testMessage); - assertMsg(check, TEST5, test3Message); + assertMessages(check, TEST5, [testMessage, test1Message, test3Message]); } @Test public function testTokenPUBLIC() { var check = new MethodNameCheck(); check.tokens = [PUBLIC]; + var testMessage = 'Invalid method name signature: "Test" (name should be "~/${check.format}/")'; + var test1Message = 'Invalid method name signature: "Test1" (name should be "~/${check.format}/")'; + var test2Message = 'Invalid method name signature: "Test2" (name should be "~/${check.format}/")'; + var test3Message = 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'; assertNoMsg(check, TEST); - assertMsg(check, TEST1, 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'); - assertMsg(check, TEST2, 'Invalid method name signature: "Test2" (name should be "~/${check.format}/")'); + assertMessages(check, TEST1, [testMessage, test2Message, test3Message]); + assertMessages(check, TEST2, [testMessage, test1Message, test2Message]); assertMsg(check, TEST3, 'Invalid method name signature: "Test" (name should be "~/${check.format}/")'); assertNoMsg(check, TEST4); assertNoMsg(check, TEST5); @@ -51,38 +61,48 @@ class MethodNameCheckTest extends CheckTestCase { var check = new MethodNameCheck(); check.tokens = [PRIVATE]; + var testMessage = 'Invalid method name signature: "Test" (name should be "~/${check.format}/")'; + var test1Message = 'Invalid method name signature: "Test1" (name should be "~/${check.format}/")'; + var test3Message = 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'; assertNoMsg(check, TEST); assertNoMsg(check, TEST1); - assertMsg(check, TEST2, 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'); + assertMsg(check, TEST2, test3Message); assertNoMsg(check, TEST3); assertNoMsg(check, TEST4); - assertMsg(check, TEST5, 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'); + assertMessages(check, TEST5, [testMessage, test1Message, test3Message]); } @Test public function testTokenSTATIC() { var check = new MethodNameCheck(); check.tokens = [STATIC]; + var testMessage = 'Invalid method name signature: "Test" (name should be "~/${check.format}/")'; + var test1Message = 'Invalid method name signature: "Test1" (name should be "~/${check.format}/")'; + var test3Message = 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'; assertNoMsg(check, TEST); - assertMsg(check, TEST1, 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'); - assertMsg(check, TEST2, 'Invalid method name signature: "Test1" (name should be "~/${check.format}/")'); + assertMessages(check, TEST1, [testMessage, test3Message]); + assertMessages(check, TEST2, [testMessage, test1Message]); assertNoMsg(check, TEST3); assertNoMsg(check, TEST4); - assertMsg(check, TEST5, 'Invalid method name signature: "Test1" (name should be "~/${check.format}/")'); + assertMessages(check, TEST5, [testMessage, test1Message]); } @Test public function testTokenNOTSTATIC() { var check = new MethodNameCheck(); check.tokens = [NOTSTATIC]; + var testMessage = 'Invalid method name signature: "Test" (name should be "~/${check.format}/")'; + var test2Message = 'Invalid method name signature: "Test2" (name should be "~/${check.format}/")'; + var test3Message = 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'; assertNoMsg(check, TEST); - assertMsg(check, TEST1, 'Invalid method name signature: "Test2" (name should be "~/${check.format}/")'); - assertMsg(check, TEST2, 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'); - assertMsg(check, TEST3, 'Invalid method name signature: "Test" (name should be "~/${check.format}/")'); + assertMsg(check, TEST1, test2Message); + assertMessages(check, TEST2, [test2Message, test3Message]); + + assertMsg(check, TEST3, testMessage); assertNoMsg(check, TEST4); - assertMsg(check, TEST5, 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'); + assertMsg(check, TEST5, test3Message); } @Test @@ -102,13 +122,16 @@ class MethodNameCheckTest extends CheckTestCase { public function testTokenNOTINLINE() { var check = new MethodNameCheck(); check.tokens = [NOTINLINE]; + var testMessage = 'Invalid method name signature: "Test" (name should be "~/${check.format}/")'; + var test2Message = 'Invalid method name signature: "Test2" (name should be "~/${check.format}/")'; + var test3Message = 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'; assertNoMsg(check, TEST); - assertMsg(check, TEST1, 'Invalid method name signature: "Test2" (name should be "~/${check.format}/")'); - assertMsg(check, TEST2, 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'); - assertMsg(check, TEST3, 'Invalid method name signature: "Test" (name should be "~/${check.format}/")'); + assertMessages(check, TEST1, [testMessage, test2Message]); + assertMessages(check, TEST2, [testMessage, test2Message, test3Message]); + assertMsg(check, TEST3, testMessage); assertNoMsg(check, TEST4); - assertMsg(check, TEST5, 'Invalid method name signature: "Test3" (name should be "~/${check.format}/")'); + assertMessages(check, TEST5, [testMessage, test3Message]); } @Test @@ -116,7 +139,13 @@ class MethodNameCheckTest extends CheckTestCase { var check = new MethodNameCheck(); check.format = "^[A-Z][a-z0-9]*$"; - assertMsg(check, TEST, 'Invalid method name signature: "testName" (name should be "~/${check.format}/")'); + assertMessages(check, TEST, [ + 'Invalid method name signature: "test" (name should be "~/${check.format}/")', + 'Invalid method name signature: "testName" (name should be "~/${check.format}/")', + 'Invalid method name signature: "testValue" (name should be "~/${check.format}/")', + 'Invalid method name signature: "test" (name should be "~/${check.format}/")', + 'Invalid method name signature: "testName" (name should be "~/${check.format}/")' + ]); assertNoMsg(check, TEST1); assertNoMsg(check, TEST2); assertNoMsg(check, TEST3); @@ -125,8 +154,7 @@ class MethodNameCheckTest extends CheckTestCase { } } -@:enum -abstract MethodNameCheckTests(String) to String { +enum abstract MethodNameCheckTests(String) to String { var TEST = " abstractAndClass Test { function test() {} @@ -170,4 +198,12 @@ abstract MethodNameCheckTests(String) to String { static inline function Test1() {} function Test3() {} }"; + var TEST_SUPPRESS_CLASS = " + @SuppressWarnings('checkstyle:MethodName') + abstractAndClass Test { + static public function Test() {} + static inline public function Test1() {} + public function Test2() {} + function Test3() {} + }"; } \ No newline at end of file diff --git a/test/checkstyle/checks/naming/ParameterNameCheckTest.hx b/test/checkstyle/checks/naming/ParameterNameCheckTest.hx index 6e1ae711..a5f53a5a 100644 --- a/test/checkstyle/checks/naming/ParameterNameCheckTest.hx +++ b/test/checkstyle/checks/naming/ParameterNameCheckTest.hx @@ -36,7 +36,13 @@ class ParameterNameCheckTest extends CheckTestCase { var check = new ParameterNameCheck(); check.format = "^[A-Z][a-zA-Z]*$"; - assertMsg(check, TEST, 'Invalid parameter name signature: "paramName" (name should be "~/${check.format}/")'); + assertMessages(check, TEST, [ + 'Invalid parameter name signature: "param1" (name should be "~/${check.format}/")', + 'Invalid parameter name signature: "paramName" (name should be "~/${check.format}/")', + 'Invalid parameter name signature: "param" (name should be "~/${check.format}/")', + 'Invalid parameter name signature: "param1" (name should be "~/${check.format}/")', + 'Invalid parameter name signature: "paramName" (name should be "~/${check.format}/")' + ]); assertNoMsg(check, TEST2); assertNoMsg(check, TEST1); assertMsg(check, TEST3, 'Invalid parameter name signature: "param1" (name should be "~/${check.format}/")'); @@ -45,8 +51,7 @@ class ParameterNameCheckTest extends CheckTestCase { } } -@:enum -abstract ParameterNameCheckTests(String) to String { +enum abstract ParameterNameCheckTests(String) to String { var TEST = " abstractAndClass Test { function test(param1:Int, paramName:String) { diff --git a/test/checkstyle/checks/naming/TypeNameCheckTest.hx b/test/checkstyle/checks/naming/TypeNameCheckTest.hx index bcaca2b2..f290df13 100644 --- a/test/checkstyle/checks/naming/TypeNameCheckTest.hx +++ b/test/checkstyle/checks/naming/TypeNameCheckTest.hx @@ -21,7 +21,12 @@ class TypeNameCheckTest extends CheckTestCase { var check = new TypeNameCheck(); check.format = FORMAT_CLASS; - assertMsg(check, TEST, 'Invalid typedef signature: "Test3" (name should be "~/^C[A-Z][a-z]*$/")'); + assertMessages(check, TEST, [ + 'Invalid class signature: "Test" (name should be "~/^C[A-Z][a-z]*$/")', + 'Invalid interface signature: "ITest" (name should be "~/^C[A-Z][a-z]*$/")', + 'Invalid enum signature: "Test2" (name should be "~/^C[A-Z][a-z]*$/")', + 'Invalid typedef signature: "Test3" (name should be "~/^C[A-Z][a-z]*$/")' + ]); assertNoMsg(check, TEST1); assertMsg(check, TEST2, 'Invalid interface signature: "Test" (name should be "~/^C[A-Z][a-z]*$/")'); assertMsg(check, TEST3, 'Invalid typedef signature: "TTest" (name should be "~/^C[A-Z][a-z]*$/")'); @@ -98,8 +103,7 @@ class TypeNameCheckTest extends CheckTestCase { } } -@:enum -abstract TypeNameCheckTests(String) to String { +enum abstract TypeNameCheckTests(String) to String { var TEST = " class Test { public var a:Int; diff --git a/test/checkstyle/checks/size/FileLengthCheckTest.hx b/test/checkstyle/checks/size/FileLengthCheckTest.hx index 4c229dfe..0aef7fb7 100644 --- a/test/checkstyle/checks/size/FileLengthCheckTest.hx +++ b/test/checkstyle/checks/size/FileLengthCheckTest.hx @@ -39,8 +39,7 @@ class FileLengthCheckTest extends CheckTestCase { } } -@:enum -abstract FileLengthCheckTests(String) to String { +enum abstract FileLengthCheckTests(String) to String { var TEST2001 = "\n class Test { public function new() { diff --git a/test/checkstyle/checks/size/LineLengthCheckTest.hx b/test/checkstyle/checks/size/LineLengthCheckTest.hx index 9cd0e1ed..efb97d47 100644 --- a/test/checkstyle/checks/size/LineLengthCheckTest.hx +++ b/test/checkstyle/checks/size/LineLengthCheckTest.hx @@ -19,8 +19,7 @@ class LineLengthCheckTest extends CheckTestCase { } } -@:enum -abstract LineLengthCheckTests(String) to String { +enum abstract LineLengthCheckTests(String) to String { var TEST1 = " class Test { var _a:Int; diff --git a/test/checkstyle/checks/size/MethodCountCheckTest.hx b/test/checkstyle/checks/size/MethodCountCheckTest.hx index 87a8d52c..12ac602a 100644 --- a/test/checkstyle/checks/size/MethodCountCheckTest.hx +++ b/test/checkstyle/checks/size/MethodCountCheckTest.hx @@ -27,8 +27,7 @@ class MethodCountCheckTest extends CheckTestCase { } } -@:enum -abstract MethodCountCheckTests(String) to String { +enum abstract MethodCountCheckTests(String) to String { var TEST1 = " abstractAndClass Test { public function test1() {} diff --git a/test/checkstyle/checks/size/MethodLengthCheckTest.hx b/test/checkstyle/checks/size/MethodLengthCheckTest.hx index a9b31b7a..5593d5b4 100755 --- a/test/checkstyle/checks/size/MethodLengthCheckTest.hx +++ b/test/checkstyle/checks/size/MethodLengthCheckTest.hx @@ -45,8 +45,7 @@ class MethodLengthCheckTest extends CheckTestCase { } } -@:enum -abstract MethodLengthCheckTests(String) to String { +enum abstract MethodLengthCheckTests(String) to String { var TEST1 = " abstractAndClass Test { public function test() { diff --git a/test/checkstyle/checks/size/ParameterNumberCheckTest.hx b/test/checkstyle/checks/size/ParameterNumberCheckTest.hx index 91fd19e4..007adc95 100644 --- a/test/checkstyle/checks/size/ParameterNumberCheckTest.hx +++ b/test/checkstyle/checks/size/ParameterNumberCheckTest.hx @@ -47,8 +47,7 @@ class ParameterNumberCheckTest extends CheckTestCase } } -@:enum -abstract ParameterNumberCheckTests(String) to String { +enum abstract ParameterNumberCheckTests(String) to String { var TEST1 = " abstractAndClass Test { var testVar1:Int; diff --git a/test/checkstyle/checks/type/AnonymousCheckTest.hx b/test/checkstyle/checks/type/AnonymousCheckTest.hx index 3fdf18e9..0e2ada79 100644 --- a/test/checkstyle/checks/type/AnonymousCheckTest.hx +++ b/test/checkstyle/checks/type/AnonymousCheckTest.hx @@ -12,8 +12,7 @@ class AnonymousCheckTest extends CheckTestCase { } } -@:enum -abstract AnonymousCheckTests(String) to String { +enum abstract AnonymousCheckTests(String) to String { var TEST1 = " abstractAndClass Test { var anonymous:{a:Int, b:Int}; diff --git a/test/checkstyle/checks/type/AvoidIdentifierCheckTest.hx b/test/checkstyle/checks/type/AvoidIdentifierCheckTest.hx index 2bdd679d..2dd7565f 100644 --- a/test/checkstyle/checks/type/AvoidIdentifierCheckTest.hx +++ b/test/checkstyle/checks/type/AvoidIdentifierCheckTest.hx @@ -16,8 +16,7 @@ class AvoidIdentifierCheckTest extends CheckTestCase } } -@:enum -abstract AvoidIdentifierCheckTests(String) to String { +enum abstract AvoidIdentifierCheckTests(String) to String { var TEST = " abstractAndClass Test { var a:Int; diff --git a/test/checkstyle/checks/type/DynamicCheckTest.hx b/test/checkstyle/checks/type/DynamicCheckTest.hx index c5571386..519cbe37 100644 --- a/test/checkstyle/checks/type/DynamicCheckTest.hx +++ b/test/checkstyle/checks/type/DynamicCheckTest.hx @@ -23,8 +23,7 @@ class DynamicCheckTest extends CheckTestCase { } } -@:enum -abstract DynamicCheckTests(String) to String { +enum abstract DynamicCheckTests(String) to String { var TEST = " import checkstyle.check.type.DynamicCheck; diff --git a/test/checkstyle/checks/type/EnforceVarTypeHintCheckTest.hx b/test/checkstyle/checks/type/EnforceVarTypeHintCheckTest.hx deleted file mode 100644 index 313260af..00000000 --- a/test/checkstyle/checks/type/EnforceVarTypeHintCheckTest.hx +++ /dev/null @@ -1,62 +0,0 @@ -package checkstyle.checks.type; - -class EnforceVarTypeHintCheckTest extends CheckTestCase { - @Test - public function testCorrectTypeHints() { - var check = new EnforceVarTypeHintCheck(); - assertNoMsg(check, CORRECT_TYPE_HINTS); - assertNoMsg(check, ABSTRACT_ENUM); - assertNoMsg(check, ABSTRACT_ENUM2); - assertMsg(check, TYPEDEF, 'Variable "risk" has no type hint'); - #if haxe4 - assertNoMsg(check, FINAL_FUNCTION); - assertMsg(check, FINAL_VAR, 'Variable "a" has no type hint'); - - assertNoMsg(check, DOLLAR_VAR_CORRECT); - assertMsg(check, DOLLAR_VAR, 'Variable "$$a" has no type hint'); - #end - - check.ignoreEnumAbstractValues = false; - assertMsg(check, ABSTRACT_ENUM, 'Variable "STYLE" has no type hint'); - assertMsg(check, ABSTRACT_ENUM2, 'Variable "STYLE" has no type hint'); - } -} - -@:enum -abstract EnforceVarTypeHintCheckTests(String) to String { - var CORRECT_TYPE_HINTS = " - abstractAndClass Test { - var a:Int; - - @SuppressWarnings('checkstyle:EnforceVarTypeHint') - var _b; - }"; - var ABSTRACT_ENUM = " - @:enum abstract Category(String) { - var STYLE = 'Style'; - }"; - var ABSTRACT_ENUM2 = " - enum abstract Category(String) { - var STYLE = 'Style'; - }"; - var TYPEDEF = " - typedef Category = { - var risk; - }"; - var FINAL_VAR = " - abstractAndClass Test { - final a; - }"; - var FINAL_FUNCTION = " - abstractAndClass Test { - final function test() {}; - }"; - var DOLLAR_VAR = " - abstractAndClass Test { - var $a; - }"; - var DOLLAR_VAR_CORRECT = " - abstractAndClass Test { - var $a:Int; - }"; -} \ No newline at end of file diff --git a/test/checkstyle/checks/type/ReturnCheckTest.hx b/test/checkstyle/checks/type/ReturnCheckTest.hx index 32734cb4..461e8650 100644 --- a/test/checkstyle/checks/type/ReturnCheckTest.hx +++ b/test/checkstyle/checks/type/ReturnCheckTest.hx @@ -36,6 +36,11 @@ class ReturnCheckTest extends CheckTestCase { assertMsg(new ReturnCheck(), TEST1, MSG_VOID_RETURN); } + @Test + public function testAbstractVoid() { + assertNoMsg(new ReturnCheck(), TEST1A, MSG_VOID_RETURN); + } + @Test public function testNoReturnType() { var check = new ReturnCheck(); @@ -106,12 +111,17 @@ class ReturnCheckTest extends CheckTestCase { } } -@:enum -abstract ReturnCheckTests(String) to String { +enum abstract ReturnCheckTests(String) to String { var TEST1 = " abstractAndClass Test { public function test():Void {} }"; + + var TEST1A = " + abstractAndClass Test { + abstract public function test():Void; + }"; + var TEST2 = " abstractAndClass Test { public function test1() { diff --git a/test/checkstyle/checks/type/TypeCheckTest.hx b/test/checkstyle/checks/type/TypeCheckTest.hx index d050a7c4..0de56645 100644 --- a/test/checkstyle/checks/type/TypeCheckTest.hx +++ b/test/checkstyle/checks/type/TypeCheckTest.hx @@ -22,8 +22,7 @@ class TypeCheckTest extends CheckTestCase { } } -@:enum -abstract TypeCheckTests(String) to String { +enum abstract TypeCheckTests(String) to String { var TEST1 = " class Test { var _a; @@ -36,12 +35,12 @@ abstract TypeCheckTests(String) to String { static inline var A = 1; }"; var TEST3 = " - @:enum + enum abstract Test(Int) { var VALUE = 0; }"; var TEST4 = " - @:enum + enum abstract Test(Int) { static inline var VALUE = 0; }"; diff --git a/test/checkstyle/checks/type/VarTypeHintCheckTest.hx b/test/checkstyle/checks/type/VarTypeHintCheckTest.hx new file mode 100644 index 00000000..8384a3f7 --- /dev/null +++ b/test/checkstyle/checks/type/VarTypeHintCheckTest.hx @@ -0,0 +1,333 @@ +package checkstyle.checks.type; + +class VarTypeHintCheckTest extends CheckTestCase { + @Test + public function testEnforceTypeHints() { + var check = new VarTypeHintCheck(); + check.typeHintPolicy = ENFORCE_ALL; + assertNoMsg(check, SUPPRESSED_LOCAL_VARS); + + var messages:Array = [for (t in [ + "test1", "test2", "test3", "test6", "test9", + "test10", "test11", "test12", "test13", "test14", + "test15", "test26", "test27", "test28", "test31", + "test32", "test33", "test34", "test39", "test41" + ]) { + '"$t" should have a type hint'; + }]; + + assertMessages(check, LOCAL_VARS, messages); + assertMessages(check, LOCAL_FINALS, messages); + + messages = [for (t in ["test1", "test9", "test13", "test26", "test32", "test39"]) { + '"$t" should have a type hint'; + }]; + assertMessages(check, MODULE_LEVEL_VARS, messages); + assertMessages(check, MODULE_LEVEL_FINALS, messages); + assertMessages(check, TYPEDEF, ['"test0" should have a type hint', '"test1" should have a type hint']); + + assertNoMsg(check, ENUM); + assertMessages(check, INTERFACE, ['"test0" should have a type hint']); + } + + @Test + public function testInferConstAndNewTypeHints() { + var check = new VarTypeHintCheck(); + check.typeHintPolicy = INFER_NEW_OR_CONST; + assertNoMsg(check, SUPPRESSED_LOCAL_VARS); + + var messages:Array = [for (t in ["test1", "test2", "test3", "test6", "test12"]) { + '"$t" should have a type hint'; + }]; + messages = messages.concat([ + for (t in ["test16", "test17", "test20", "test21", "test22", "test29", "test30"]) { + '"$t" type hint not needed'; + } + ]); + messages = messages.concat([for (t in ["test32", "test33", "test34"]) { + '"$t" should have a type hint'; + }]); + messages.push('"test40" type hint not needed'); + + assertMessages(check, LOCAL_VARS, messages); + assertMessages(check, LOCAL_FINALS, messages); + + messages = [ + '"test1" should have a type hint', + '"test16" type hint not needed', + '"test29" type hint not needed', + '"test32" should have a type hint' + ]; + assertMessages(check, MODULE_LEVEL_VARS, messages); + assertMessages(check, MODULE_LEVEL_FINALS, messages); + assertMessages(check, TYPEDEF, ['"test0" should have a type hint', '"test1" should have a type hint']); + assertNoMsg(check, ENUM); + assertMessages(check, INTERFACE, ['"test0" should have a type hint']); + } + + @Test + public function testInferAllTypeHints() { + var check = new VarTypeHintCheck(); + check.typeHintPolicy = INFER_ALL; + assertNoMsg(check, SUPPRESSED_LOCAL_VARS); + var messages:Array = [for (t in ["test1", "test2", "test3", "test6", "test12"]) { + '"$t" should have a type hint'; + }]; + messages = messages.concat([for (t in [ + "test16", "test17", "test20", "test21", "test22", "test29", + "test30", "test35", "test36", "test37", "test38", "test40" + ]) { + '"$t" type hint not needed'; + }]); + + assertMessages(check, LOCAL_VARS, messages); + assertMessages(check, LOCAL_FINALS, messages); + + messages = [ + '"test1" should have a type hint', + '"test16" type hint not needed', + '"test29" type hint not needed', + '"test35" type hint not needed', + '"test38" type hint not needed' + ]; + assertMessages(check, MODULE_LEVEL_VARS, messages); + assertMessages(check, MODULE_LEVEL_FINALS, messages); + assertMessages(check, TYPEDEF, ['"test0" should have a type hint', '"test1" should have a type hint']); + assertNoMsg(check, ENUM); + assertMessages(check, INTERFACE, ['"test0" should have a type hint']); + } + + @Test + public function testCorrectTypeHints() { + var check = new VarTypeHintCheck(); + check.typeHintPolicy = ENFORCE_ALL; + + assertNoMsg(check, CORRECT_TYPE_HINTS); + assertNoMsg(check, ABSTRACT_ENUM); + assertNoMsg(check, ABSTRACT_ENUM2); + assertMsg(check, TYPEDEF_OLD, '"risk" should have a type hint'); + assertNoMsg(check, FINAL_FUNCTION); + assertMsg(check, FINAL_VAR, '"a" should have a type hint'); + + assertNoMsg(check, DOLLAR_VAR_CORRECT); + assertMsg(check, DOLLAR_VAR, '"$$a" should have a type hint'); + + check.ignoreEnumAbstractValues = false; + assertMsg(check, ABSTRACT_ENUM, '"STYLE" should have a type hint'); + assertMsg(check, ABSTRACT_ENUM2, '"STYLE" should have a type hint'); + } +} + +enum abstract VarTypeHintCheckTests(String) to String { + var MODULE_LEVEL_VARS = " + var test0:Int; + var test1; + var test9 = 10; + var test13 = '10'; + var test16:Int = 10; + + var test26 = new Test(); + var test29:Test = new Test(); + var test32 = call(); + var test35:Test = call(); + var test38:Test = /** **/ call(); + + var test39 = true; + "; + var MODULE_LEVEL_FINALS = " + final test0:Int; + final test1; + final test9 = 10; + final test13 = '10'; + final test16:Int = 10; + + final test26 = new Test(); + final test29:Test = new Test(); + final test32 = call(); + final test35:Test = call(); + final test38:Test = /** **/ call(); + + final test39 = true; + "; + var LOCAL_VARS = " + abstractAndClass Test { + function test() { + var test0:Int; + var test1, test2; + var test3, test4:Int; + var test5:Int, test6; + var test7:Int, test8:Int; + + var test9 = 10; + var test10 = 10, test11 = '10'; + var test12, test13 = '10'; + var test14 = 10, test15 = '12'; + + var test16:Int = 10; + var test17:Int = 10, test18:String; + var test19:Int, test20:String = '14'; + var test21:Int = 10, test22:String = '14'; + + // var @:meta test23:Int = 10; + // var @:meta test24:Int = 10, @:meta test25:Int = 10; + + var test26 = new Test(); + var test27 = new Test(), test28 = new Test2(); + + var test29:Test = new Test(); + var test30:Test = new Test(), test31 = new Test2(); + + var test32 = call(); + var test33 = call(), test34 = call(); + + var test35:Test = call(); + var test36:Test = call(), test37:Test = call(); + + var test38:Test = /** **/ call(); + + var test39 = true; + var test40:Bool = true, test41 = false; + }; + } + "; + var LOCAL_FINALS = " + abstractAndClass Test { + function test() { + final test0:Int; + final test1, test2; + final test3, test4:Int; + final test5:Int, test6; + final test7:Int, test8:Int; + + final test9 = 10; + final test10 = 10, test11 = '10'; + final test12, test13 = '10'; + final test14 = 10, test15 = '12'; + + final test16:Int = 10; + final test17:Int = 10, test18:String; + final test19:Int, test20:String = '14'; + final test21:Int = 10, test22:String = '14'; + + // final @:meta test23:Int = 10; + // final @:meta test24:Int = 10, @:meta test25:Int = 10; + + final test26 = new Test(); + final test27 = new Test(), test28 = new Test2(); + + final test29:Test = new Test(); + final test30:Test = new Test(), test31 = new Test2(); + + final test32 = call(); + final test33 = call(), test34 = call(); + + final test35:Test = call(); + final test36:Test = call(), test37:Test = call(); + + final test38:Test = /** **/ call(); + + final test39 = true; + final test40:Bool = true, test41 = false; + }; + } + "; + var SUPPRESSED_LOCAL_VARS = " + abstractAndClass Test { + @SuppressWarnings('checkstyle:VarTypeHint') + function test() { + var test0:Int; + var test1, test2; + var test3, test4:Int; + var test5:Int, test6; + var test7:Int, test8:Int; + + var test9 = 10; + var test10 = 10, test11 = '10'; + var test12, test13 = '10'; + var test14 = 10, test15 = '12'; + + var test16:Int = 10; + var test17:Int = 10, test18:String; + var test19:Int, test20:String = '14'; + var test21:Int = 10, test22:String = '14'; + + // var @:meta test23:Int = 10; + // var @:meta test24:Int = 10, @:meta test25:Int = 10; + + var test26 = new Test(); + var test27 = new Test(), test28 = new Test2(); + + var test29:Test = new Test(); + var test30:Test = new Test(), test31 = new Test2(); + + var test32 = call(); + var test33 = call(), test34 = call(); + + var test35:Test = call(); + var test36:Test = call(), test37:Test = call(); + + var test38:Test = /** **/ call(); + }; + } + "; + var ENUM = " + enum abstract Category(String) { + var STYLE = 'Style'; + } + enum abstract Category(String) { + var STYLE = 'Style'; + } + enum Category { + STYLE; + } + "; + var TYPEDEF = " + typedef Category = { + var test0; + var ?test1; + var test2:Int; + var ?test3:Int; + } + "; + var INTERFACE = " + interface Category { + var test0; + var test1:Int; + } + "; + var CORRECT_TYPE_HINTS = " + abstractAndClass Test { + var a:Int; + + @SuppressWarnings('checkstyle:VarTypeHint') + var _b; + }"; + var ABSTRACT_ENUM = " + enum abstract Category(String) { + var STYLE = 'Style'; + }"; + var ABSTRACT_ENUM2 = " + enum abstract Category(String) { + var STYLE = 'Style'; + }"; + var TYPEDEF_OLD = " + typedef Category = { + var risk; + }"; + var FINAL_VAR = " + abstractAndClass Test { + final a; + }"; + var FINAL_FUNCTION = " + abstractAndClass Test { + final function test() {}; + }"; + var DOLLAR_VAR = " + abstractAndClass Test { + var $a; + }"; + var DOLLAR_VAR_CORRECT = " + abstractAndClass Test { + var $a:Int; + }"; +} \ No newline at end of file diff --git a/test/checkstyle/checks/whitespace/ArrayAccessCheckTest.hx b/test/checkstyle/checks/whitespace/ArrayAccessCheckTest.hx index eb3befe0..3cad3625 100644 --- a/test/checkstyle/checks/whitespace/ArrayAccessCheckTest.hx +++ b/test/checkstyle/checks/whitespace/ArrayAccessCheckTest.hx @@ -11,7 +11,7 @@ class ArrayAccessCheckTest extends CheckTestCase { var check = new ArrayAccessCheck(); assertMsg(check, TEST2, "Space between [ and index"); assertMsg(check, TEST3, "Space between index and ]"); - assertMsg(check, TEST4, "Space between index and ]"); + assertMessages(check, TEST4, ["Space between [ and index", "Space between index and ]"]); } @Test @@ -32,8 +32,7 @@ class ArrayAccessCheckTest extends CheckTestCase { } } -@:enum -abstract ArrayAccessCheckTests(String) to String { +enum abstract ArrayAccessCheckTests(String) to String { var TEST1 = " class Test { diff --git a/test/checkstyle/checks/whitespace/EmptyLinesCheckTest.hx b/test/checkstyle/checks/whitespace/EmptyLinesCheckTest.hx index 2f4a1f9f..8839c69c 100644 --- a/test/checkstyle/checks/whitespace/EmptyLinesCheckTest.hx +++ b/test/checkstyle/checks/whitespace/EmptyLinesCheckTest.hx @@ -75,8 +75,7 @@ class EmptyLinesCheckTest extends CheckTestCase { } } -@:enum -abstract EmptyLinesCheckTests(String) to String { +enum abstract EmptyLinesCheckTests(String) to String { var TEST1 = " class Test { diff --git a/test/checkstyle/checks/whitespace/ExtendedEmptyLinesCheckTest.hx b/test/checkstyle/checks/whitespace/ExtendedEmptyLinesCheckTest.hx index a2fe7980..a809c8c3 100644 --- a/test/checkstyle/checks/whitespace/ExtendedEmptyLinesCheckTest.hx +++ b/test/checkstyle/checks/whitespace/ExtendedEmptyLinesCheckTest.hx @@ -1,7 +1,7 @@ package checkstyle.checks.whitespace; -import haxe.PosInfos; import checkstyle.checks.whitespace.ExtendedEmptyLinesCheck.EmptyLinesPlace; +import haxe.PosInfos; class ExtendedEmptyLinesCheckTest extends CheckTestCase { static inline var MSG_NONE:String = "should not have empty line(s)"; @@ -24,12 +24,12 @@ class ExtendedEmptyLinesCheckTest extends CheckTestCase = [for (i in 0...msgCount) MSG_EXACT_1 + postfix]; + assertMessages(check, TEST_EXACT_2, messages); + if (hasFixedPosition) assertMessages(check, TEST_NONE, messages); check.exact = []; check.none = [fieldName]; - assertMsg(check, TEST_EXACT_1, MSG_NONE + postfix); - assertMsg(check, TEST_EXACT_2, MSG_NONE + postfix); + messages = [for (i in 0...msgCount) MSG_NONE + postfix]; + assertMessages(check, TEST_EXACT_1, messages); + assertMessages(check, TEST_EXACT_2, messages); assertNoMsg(check, TEST_NONE); check.none = []; check.upto = [fieldName]; + messages = [for (i in 0...msgCount) MSG_UPTO_1 + postfix]; assertNoMsg(check, TEST_EXACT_1); - assertMsg(check, TEST_EXACT_2, MSG_UPTO_1 + postfix); + assertMessages(check, TEST_EXACT_2, messages); assertNoMsg(check, TEST_NONE); check.upto = []; check.atleast = [fieldName]; assertNoMsg(check, TEST_EXACT_1); assertNoMsg(check, TEST_EXACT_2); - if (hasFixedPosition) assertMsg(check, TEST_NONE, MSG_ATLEAST_1 + postfix); + + messages = [for (i in 0...msgCount) MSG_ATLEAST_1 + postfix]; + if (hasFixedPosition) assertMessages(check, TEST_NONE, messages); } - function runChecksMax2(check:ExtendedEmptyLinesCheck, fieldName:EmptyLinesPlace, postfix:String, hasFixedPosition:Bool = true, ?pos:PosInfos) { + function runChecksMax2(check:ExtendedEmptyLinesCheck, fieldName:EmptyLinesPlace, postfix:String, hasFixedPosition:Bool = true, msgCount:Int = 1, + ?pos:PosInfos) { check.max = 2; check.atleast = []; check.exact = [fieldName]; - assertMsg(check, TEST_EXACT_1, MSG_EXACT_2 + postfix); + var messages:Array = [for (i in 0...msgCount) MSG_EXACT_2 + postfix]; + assertMessages(check, TEST_EXACT_1, messages); assertNoMsg(check, TEST_EXACT_2); - if (hasFixedPosition) assertMsg(check, TEST_NONE, MSG_EXACT_2 + postfix); + if (hasFixedPosition) assertMessages(check, TEST_NONE, messages); check.exact = []; check.none = [fieldName]; - assertMsg(check, TEST_EXACT_1, MSG_NONE + postfix); - assertMsg(check, TEST_EXACT_2, MSG_NONE + postfix); + messages = [for (i in 0...msgCount) MSG_NONE + postfix]; + assertMessages(check, TEST_EXACT_1, messages); + assertMessages(check, TEST_EXACT_2, messages); assertNoMsg(check, TEST_NONE); check.none = []; @@ -255,9 +264,10 @@ class ExtendedEmptyLinesCheckTest extends CheckTestCase { check.character = cast " "; check.severity = SeverityLevel.INFO; assertNoMsg(check, CORRECT_SPACE_INDENT); - assertMsg(check, CORRECT_TAB_INDENT, 'Indentation mismatch: expected: " "[1], actual: no indentation'); + assertMessages(check, CORRECT_TAB_INDENT, [ + 'Indentation mismatch: expected: " "[1], actual: no indentation', + 'Indentation mismatch: expected: " "[1], actual: no indentation', + 'Indentation mismatch: expected: " "[1], actual: no indentation', + 'Indentation mismatch: expected: " "[1], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[4], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[2], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[3], actual: no indentation', + 'Indentation mismatch: expected: " "[1], actual: no indentation' + ]); } @Test @@ -28,7 +156,10 @@ class IndentationCheckTest extends CheckTestCase { var check = new IndentationCheck(); check.severity = SeverityLevel.INFO; - assertMsg(check, WRONG_CONDITIONAL, 'Indentation mismatch: expected: "\\t"[1], actual: no indentation'); + assertMessages(check, WRONG_CONDITIONAL, [ + 'Indentation mismatch: expected: "\\t"[1], actual: no indentation', + 'Indentation mismatch: expected: "\\t"[1], actual: no indentation' + ]); check.ignoreConditionals = true; assertNoMsg(check, WRONG_CONDITIONAL); assertNoMsg(check, CORRECT_TAB_INDENT); @@ -40,16 +171,41 @@ class IndentationCheckTest extends CheckTestCase { check.conditionalPolicy = FIXED_ZERO; assertNoMsg(check, WRONG_CONDITIONAL); - assertMsg(check, CORRECT_TAB_INDENT, 'Indentation mismatch: expected: no indentation, actual: "\\t\\t\\t"[3]'); + assertMessages(check, CORRECT_TAB_INDENT, [ + 'Indentation mismatch: expected: no indentation, actual: "\\t\\t"[2]', + 'Indentation mismatch: expected: no indentation, actual: "\\t\\t"[2]', + 'Indentation mismatch: expected: no indentation, actual: "\\t\\t\\t"[3]', + 'Indentation mismatch: expected: no indentation, actual: "\\t\\t\\t"[3]', + 'Indentation mismatch: expected: no indentation, actual: "\\t\\t\\t"[3]', + 'Indentation mismatch: expected: no indentation, actual: "\\t\\t\\t"[3]' + ]); check.conditionalPolicy = ALIGNED; - assertMsg(check, WRONG_CONDITIONAL, 'Indentation mismatch: expected: "\\t"[1], actual: no indentation'); + assertMessages(check, WRONG_CONDITIONAL, [ + 'Indentation mismatch: expected: "\\t"[1], actual: no indentation', + 'Indentation mismatch: expected: "\\t"[1], actual: no indentation' + ]); assertNoMsg(check, CORRECT_TAB_INDENT); check.conditionalPolicy = ALIGNED_INCREASE; - assertMsg(check, WRONG_CONDITIONAL, 'Indentation mismatch: expected: "\\t"[1], actual: no indentation'); + assertMessages(check, WRONG_CONDITIONAL, [ + 'Indentation mismatch: expected: "\\t"[1], actual: no indentation', + 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t"[1]', + 'Indentation mismatch: expected: "\\t"[1], actual: no indentation' + ]); assertNoMsg(check, CONDITIONAL_INCREASE); - assertMsg(check, CORRECT_TAB_INDENT, 'Indentation mismatch: expected: "\\t\\t\\t\\t\\t"[5], actual: "\\t\\t\\t\\t"[4]'); + assertMessages(check, CORRECT_TAB_INDENT, [ + 'Indentation mismatch: expected: "\\t\\t\\t"[3], actual: "\\t\\t"[2]', + 'Indentation mismatch: expected: "\\t\\t\\t\\t"[4], actual: "\\t\\t\\t"[3]', + 'Indentation mismatch: expected: "\\t\\t\\t\\t"[4], actual: "\\t\\t\\t"[3]', + 'Indentation mismatch: expected: "\\t\\t\\t\\t"[4], actual: "\\t\\t\\t"[3]', + 'Indentation mismatch: expected: "\\t\\t\\t"[3], actual: "\\t\\t"[2]', + 'Indentation mismatch: expected: "\\t\\t\\t\\t"[4], actual: "\\t\\t\\t"[3]', + 'Indentation mismatch: expected: "\\t\\t\\t\\t\\t"[5], actual: "\\t\\t\\t\\t"[4]', + 'Indentation mismatch: expected: "\\t\\t\\t\\t\\t"[5], actual: "\\t\\t\\t\\t"[4]', + 'Indentation mismatch: expected: "\\t\\t\\t\\t"[4], actual: "\\t\\t\\t"[3]', + 'Indentation mismatch: expected: "\\t\\t\\t\\t\\t"[5], actual: "\\t\\t\\t\\t"[4]' + ]); } @Test @@ -58,7 +214,10 @@ class IndentationCheckTest extends CheckTestCase { check.severity = SeverityLevel.INFO; check.ignoreComments = false; assertNoMsg(check, CORRECT_COMMENTS); - assertMsg(check, CORRECT_TAB_INDENT, 'Indentation mismatch: expected: "\\t\\t"[2], actual: no indentation'); + assertMessages(check, CORRECT_TAB_INDENT, [ + 'Indentation mismatch: expected: "\\t\\t"[2], actual: no indentation', + 'Indentation mismatch: expected: "\\t\\t"[2], actual: no indentation' + ]); } @Test @@ -69,22 +228,44 @@ class IndentationCheckTest extends CheckTestCase { assertNoMsg(check, EXACT_WRAPPED_PARAMS); assertNoMsg(check, WRAPPED_STRING); assertNoMsg(check, CORRECT_PCLOSE_WRAPPING_ISSUE_450); - assertMsg(check, NONE_WRAPPED_PARAMS, 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t"[1]'); + assertMessages(check, NONE_WRAPPED_PARAMS, [ + 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t"[1]', + 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t"[1]', + 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t"[1]' + ]); check.wrapPolicy = EXACT; assertNoMsg(check, WRAPPED_STRING); assertNoMsg(check, CORRECT_PCLOSE_WRAPPING_ISSUE_450); - assertMsg(check, LARGER_WRAPPED_PARAMS, 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t\\t\\t\\t\\t\\t"[6]'); - assertMsg(check, NONE_WRAPPED_PARAMS, 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t"[1]'); + assertMessages(check, LARGER_WRAPPED_PARAMS, [ + 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t\\t\\t\\t\\t\\t"[6]', + 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t\\t\\t\\t\\t\\t"[6]', + 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t\\t\\t\\t\\t\\t"[6]' + ]); + assertMessages(check, NONE_WRAPPED_PARAMS, [ + 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t"[1]', + 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t"[1]', + 'Indentation mismatch: expected: "\\t\\t"[2], actual: "\\t"[1]' + ]); check.wrapPolicy = NONE; assertNoMsg(check, NONE_WRAPPED_PARAMS); - assertMsg(check, LARGER_WRAPPED_PARAMS, 'Indentation mismatch: expected: "\\t"[1], actual: "\\t\\t\\t\\t\\t\\t"[6]'); - assertMsg(check, EXACT_WRAPPED_PARAMS, 'Indentation mismatch: expected: "\\t"[1], actual: "\\t\\t"[2]'); + assertMessages(check, LARGER_WRAPPED_PARAMS, [ + 'Indentation mismatch: expected: "\\t"[1], actual: "\\t\\t"[2]', + 'Indentation mismatch: expected: "\\t"[1], actual: "\\t\\t"[2]', + 'Indentation mismatch: expected: "\\t"[1], actual: "\\t\\t"[2]', + 'Indentation mismatch: expected: "\\t"[1], actual: "\\t\\t\\t\\t\\t\\t"[6]', + 'Indentation mismatch: expected: "\\t"[1], actual: "\\t\\t\\t\\t\\t\\t"[6]', + 'Indentation mismatch: expected: "\\t"[1], actual: "\\t\\t\\t\\t\\t\\t"[6]' + ]); + assertMessages(check, EXACT_WRAPPED_PARAMS, [ + 'Indentation mismatch: expected: "\\t"[1], actual: "\\t\\t"[2]', + 'Indentation mismatch: expected: "\\t"[1], actual: "\\t\\t"[2]', + 'Indentation mismatch: expected: "\\t"[1], actual: "\\t\\t"[2]' + ]); } } -@:enum -abstract IndentationCheckTests(String) to String { +enum abstract IndentationCheckTests(String) to String { var CORRECT_TAB_INDENT = " class Test { static inline var INDENTATION_CHARACTER_CHECK_TEST:Int = 100; diff --git a/test/checkstyle/checks/whitespace/OperatorWhitespaceCheckTest.hx b/test/checkstyle/checks/whitespace/OperatorWhitespaceCheckTest.hx index 196692cb..241dbb63 100644 --- a/test/checkstyle/checks/whitespace/OperatorWhitespaceCheckTest.hx +++ b/test/checkstyle/checks/whitespace/OperatorWhitespaceCheckTest.hx @@ -10,12 +10,17 @@ class OperatorWhitespaceCheckTest extends CheckTestCase { assertNoMsg(check, CORRECT_NL_WRAP_GT); assertNoMsg(check, TYPE_PARAM); - assertMsg(check, CORRECT_EOL_WRAP, MSG_GT_NL); + assertMessages(check, CORRECT_EOL_WRAP, [MSG_PLUS_NL, MSG_LT_NL, MSG_GT_NL]); } } -@:enum -abstract OperatorWrapCheckTests(String) to String { +enum abstract OperatorWrapCheckTests(String) to String { var CORRECT_EOL_WRAP = " class Test { function test(param1:String, param2:String) { diff --git a/test/checkstyle/checks/whitespace/SeparatorWhitespaceCheckTest.hx b/test/checkstyle/checks/whitespace/SeparatorWhitespaceCheckTest.hx index 72f07f42..b545cbd0 100644 --- a/test/checkstyle/checks/whitespace/SeparatorWhitespaceCheckTest.hx +++ b/test/checkstyle/checks/whitespace/SeparatorWhitespaceCheckTest.hx @@ -13,8 +13,8 @@ class SeparatorWhitespaceCheckTest extends CheckTestCase { } } -@:enum -abstract TabForAligningCheckTests(String) to String { +enum abstract TabForAligningCheckTests(String) to String { var TEST1 = " class Test { static inline var TAB_FOR_ALIGNING_TEST:Int = 1; diff --git a/test/checkstyle/checks/whitespace/TrailingWhitespaceCheckTest.hx b/test/checkstyle/checks/whitespace/TrailingWhitespaceCheckTest.hx index 0a57d441..494a8057 100644 --- a/test/checkstyle/checks/whitespace/TrailingWhitespaceCheckTest.hx +++ b/test/checkstyle/checks/whitespace/TrailingWhitespaceCheckTest.hx @@ -11,8 +11,7 @@ class TrailingWhitespaceCheckTest extends CheckTestCase } } -@:enum -abstract WhitespaceAfterCheckTests(String) to String { +enum abstract WhitespaceAfterCheckTests(String) to String { var CORRECT_WHITESPACE_AFTER = " class Test { function test(param1:String, param2:String) { diff --git a/test/checkstyle/checks/whitespace/WhitespaceAroundCheckTest.hx b/test/checkstyle/checks/whitespace/WhitespaceAroundCheckTest.hx index a57d69ad..fdcf388b 100644 --- a/test/checkstyle/checks/whitespace/WhitespaceAroundCheckTest.hx +++ b/test/checkstyle/checks/whitespace/WhitespaceAroundCheckTest.hx @@ -60,8 +60,7 @@ class WhitespaceAroundCheckTest extends CheckTestCase 0); Assert.isTrue(configParser.checker.checks.length != configParser.getCheckCount()); } @@ -24,14 +26,14 @@ class ConfigParserTest { public function testExtendsConfigPath() { var configParser:ConfigParser = new ConfigParser(reportConfigParserFailure); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); configParser.parseAndValidateConfig({ extendsConfigPath: "checkstyle.json" }, LOCAL_PATH); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length > 0); } @@ -39,43 +41,35 @@ class ConfigParserTest { public function testValidateParserThread() { var configParser:ConfigParser = new ConfigParser(reportConfigParserFailure); configParser.parseAndValidateConfig({numberOfCheckerThreads: 0}, ""); - Assert.areEqual(5, configParser.numberOfCheckerThreads); + Assert.equals(5, configParser.numberOfCheckerThreads); configParser.parseAndValidateConfig({numberOfCheckerThreads: 10}, ""); - Assert.areEqual(10, configParser.numberOfCheckerThreads); + Assert.equals(10, configParser.numberOfCheckerThreads); configParser.parseAndValidateConfig({numberOfCheckerThreads: 50}, ""); - Assert.areEqual(15, configParser.numberOfCheckerThreads); + Assert.equals(15, configParser.numberOfCheckerThreads); configParser.overrideCheckerThreads = 13; configParser.parseAndValidateConfig({numberOfCheckerThreads: 14}, ""); - Assert.areEqual(13, configParser.numberOfCheckerThreads); + Assert.equals(13, configParser.numberOfCheckerThreads); configParser.overrideCheckerThreads = 18; configParser.parseAndValidateConfig({numberOfCheckerThreads: 14}, ""); - Assert.areEqual(15, configParser.numberOfCheckerThreads); + Assert.equals(15, configParser.numberOfCheckerThreads); } @Test public function testCheckCount() { var configParser:ConfigParser = new ConfigParser(reportConfigParserFailure); - #if haxe4 - Assert.areEqual(TEST_COUNT, configParser.getCheckCount()); - #else - Assert.areEqual(TEST_COUNT - 1, configParser.getCheckCount()); - #end + Assert.equals(TEST_COUNT, configParser.getCheckCount()); } @Test public function testUnusedChecks() { var configParser:ConfigParser = new ConfigParser(reportConfigParserFailure); - Assert.areEqual(0, configParser.getUsedCheckCount()); + Assert.equals(0, configParser.getUsedCheckCount()); configParser.addAllChecks(); - #if haxe4 - Assert.areEqual(TEST_COUNT, configParser.getUsedCheckCount()); - #else - Assert.areEqual(TEST_COUNT - 1, configParser.getUsedCheckCount()); - #end + Assert.equals(TEST_COUNT, configParser.getUsedCheckCount()); } @Test @@ -88,22 +82,22 @@ class ConfigParserTest { configParser = new ConfigParser(reportConfigParserFailure); configParser.parseAndValidateConfig(config, ""); - Assert.areEqual(configParser.getCheckCount(), configParser.getUsedCheckCount()); - Assert.areEqual(11, configParser.numberOfCheckerThreads); + Assert.equals(configParser.getCheckCount(), configParser.getUsedCheckCount()); + Assert.equals(11, configParser.numberOfCheckerThreads); } @Test public function testConfigVersion1() { var configParser:ConfigParser = new ConfigParser(reportConfigParserFailure); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); configParser.parseAndValidateConfig({ version: 1 }, LOCAL_PATH); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); } @@ -114,23 +108,23 @@ class ConfigParserTest { failMessage = message; }); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); configParser.parseAndValidateConfig({ version: 0 }, LOCAL_PATH); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); - Assert.areEqual("configuration file has unknown version: 0", failMessage); + Assert.equals("configuration file has unknown version: 0", failMessage); } @Test public function testExcludeConfigVersion1() { var configParser:ConfigParser = new ConfigParser(reportConfigParserFailure); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); configParser.parseExcludes({ @@ -145,14 +139,14 @@ class ConfigParserTest { failMessage = message; }); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); configParser.parseExcludes({ version: 0 }); - Assert.areEqual("exclude configuration file has unknown version: 0", failMessage); + Assert.equals("exclude configuration file has unknown version: 0", failMessage); } @Test @@ -163,7 +157,7 @@ class ConfigParserTest { }); configParser.validateMode = RELAXED; - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); var config:Config = { @@ -179,11 +173,11 @@ class ConfigParserTest { }; configParser.parseAndValidateConfig(config, LOCAL_PATH); - Assert.areEqual("", failMessage); + Assert.equals("", failMessage); configParser.validateMode = STRICT; configParser.parseAndValidateConfig(config, LOCAL_PATH); - Assert.areEqual("Check Trace has no property named 'non_existing_property'", failMessage); + Assert.equals("Check Trace has no property named 'non_existing_property'", failMessage); } function reportConfigParserFailure(message:String) { diff --git a/test/checkstyle/config/ExcludeManagerTest.hx b/test/checkstyle/config/ExcludeManagerTest.hx index c36a00dc..b2039b88 100644 --- a/test/checkstyle/config/ExcludeManagerTest.hx +++ b/test/checkstyle/config/ExcludeManagerTest.hx @@ -21,7 +21,7 @@ class ExcludeManagerTest extends CheckTestCase { public function testExcludeAllConfig() { var configParser:ConfigParser = new ConfigParser(reportConfigParserFailure); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); configParser.parseExcludes({ @@ -39,7 +39,7 @@ class ExcludeManagerTest extends CheckTestCase { public function testExcludeAllConfig2() { var configParser:ConfigParser = new ConfigParser(reportConfigParserFailure); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); configParser.paths = ["src", "test"]; @@ -59,7 +59,7 @@ class ExcludeManagerTest extends CheckTestCase { public function testExcludeConfigDynamic() { var configParser:ConfigParser = new ConfigParser(reportConfigParserFailure); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); configParser.parseExcludes(cast { @@ -80,7 +80,7 @@ class ExcludeManagerTest extends CheckTestCase { public function testExcludeConfigDynamicRange() { var configParser:ConfigParser = new ConfigParser(reportConfigParserFailure); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); configParser.parseExcludes(cast { @@ -101,7 +101,7 @@ class ExcludeManagerTest extends CheckTestCase { public function testExcludeConfigAllRange() { var configParser:ConfigParser = new ConfigParser(reportConfigParserFailure); - Assert.isNotNull(configParser.checker.checks); + Assert.notNull(configParser.checker.checks); Assert.isTrue(configParser.checker.checks.length == 0); configParser.parseExcludes(cast { @@ -124,8 +124,7 @@ class ExcludeManagerTest extends CheckTestCase { } } -@:enum -abstract ExcludeManagerTests(String) to String { +enum abstract ExcludeManagerTests(String) to String { var CHECKSINFO = "\n class ChecksInfo { public function new() { diff --git a/test/checkstyle/detect/DetectCodingStyleTest.hx b/test/checkstyle/detect/DetectCodingStyleTest.hx index acb5ca94..f5c812d2 100644 --- a/test/checkstyle/detect/DetectCodingStyleTest.hx +++ b/test/checkstyle/detect/DetectCodingStyleTest.hx @@ -19,6 +19,7 @@ import checkstyle.checks.coding.NullableParameterCheck; import checkstyle.checks.coding.ReturnCountCheck; import checkstyle.checks.coding.TraceCheck; import checkstyle.checks.coding.UnusedLocalVarCheck; +import checkstyle.checks.comments.CommentedOutCodeCheck; import checkstyle.checks.comments.DocCommentStyleCheck; import checkstyle.checks.comments.FieldDocCommentCheck; import checkstyle.checks.comments.TODOCommentCheck; @@ -35,6 +36,7 @@ import checkstyle.checks.metrics.CyclomaticComplexityCheck; import checkstyle.checks.modifier.FinalCheck; import checkstyle.checks.modifier.RedundantModifierCheck; import checkstyle.checks.naming.ConstantNameCheck; +import checkstyle.checks.naming.FileNameCaseCheck; import checkstyle.checks.size.FileLengthCheck; import checkstyle.checks.size.LineLengthCheck; import checkstyle.checks.size.MethodCountCheck; @@ -59,83 +61,82 @@ import checkstyle.checks.whitespace.WhitespaceCheckBase.WhitespacePolicy; import checkstyle.checks.whitespace.WrapCheckBase.WrapCheckBaseOption; import checkstyle.config.CheckConfig; -class DetectCodingStyleTest { +class DetectCodingStyleTest implements ITest { + public function new() {} + // checkstyle.checks.block @Test public function testBlockBreakingConditional() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new BlockBreakingConditionalCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("BlockBreakingConditional", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("BlockBreakingConditional", detectedChecks[0].type); } @Test public function testDetectConditionalCompilation() { - var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new ConditionalCompilationCheck()], - [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("ConditionalCompilation", detectedChecks[0].type); + var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new ConditionalCompilationCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); + Assert.equals(1, detectedChecks.length); + Assert.equals("ConditionalCompilation", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual("aligned", props.policy); + Assert.equals("aligned", props.policy); Assert.isTrue(props.allowSingleline); } @Test public function testDetectLeftCurly() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new LeftCurlyCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(2, detectedChecks.length); - Assert.areEqual("LeftCurly", detectedChecks[0].type); + Assert.equals(2, detectedChecks.length); + Assert.equals("LeftCurly", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual("eol", props.option); + Assert.equals("eol", props.option); Assert.isTrue(props.ignoreEmptySingleline); - Assert.areEqual("LeftCurly", detectedChecks[1].type); + Assert.equals("LeftCurly", detectedChecks[1].type); props = cast detectedChecks[1].props; - Assert.areEqual("nl", props.option); + Assert.equals("nl", props.option); Assert.isTrue(props.ignoreEmptySingleline); } @Test public function testDetectRightCurly() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new RightCurlyCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(2, detectedChecks.length); - Assert.areEqual("RightCurly", detectedChecks[0].type); + Assert.equals(2, detectedChecks.length); + Assert.equals("RightCurly", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual("aloneorsingle", props.option); - Assert.areEqual("RightCurly", detectedChecks[1].type); + Assert.equals("aloneorsingle", props.option); + Assert.equals("RightCurly", detectedChecks[1].type); var props = cast detectedChecks[1].props; - Assert.areEqual("same", props.option); + Assert.equals("same", props.option); } // checkstyle.checks.coding @Test public function testDetectArrowFunction() { - #if haxe4 var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new ArrowFunctionCheck()], [buildCheckFile(SAMPLE_CODING_STYLE_HAXE_4)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("ArrowFunction", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("ArrowFunction", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(true, props.allowReturn); - Assert.areEqual(true, props.allowFunction); - Assert.areEqual(true, props.allowCurlyBody); - Assert.areEqual(true, props.allowSingleArgParens); - #end + Assert.equals(true, props.allowReturn); + Assert.equals(true, props.allowFunction); + Assert.equals(true, props.allowCurlyBody); + Assert.equals(true, props.allowSingleArgParens); } @Test public function testDetectCodeSimilarity() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new CodeSimilarityCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("CodeSimilarity", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("CodeSimilarity", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(60, props.thresholdIdentical); - Assert.areEqual(120, props.thresholdSimilar); + Assert.equals(60, props.thresholdIdentical); + Assert.equals(120, props.thresholdSimilar); } @Test public function testDetectHiddenField() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new HiddenFieldCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("HiddenField", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("HiddenField", detectedChecks[0].type); var props = cast detectedChecks[0].props; Assert.isFalse(props.ignoreSetter); Assert.isTrue(props.ignoreConstructorParameter); @@ -145,127 +146,134 @@ class DetectCodingStyleTest { public function testDetectInnerAssignment() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new InnerAssignmentCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); // ignored not enough data points - Assert.areEqual(0, detectedChecks.length); + Assert.equals(0, detectedChecks.length); } @Test public function testDetectNestedControlFlowC() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new NestedControlFlowCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("NestedControlFlow", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("NestedControlFlow", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(3, props.max); + Assert.equals(3, props.max); } @Test public function testDetectNestedForDepth() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new NestedForDepthCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("NestedForDepth", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("NestedForDepth", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(2, props.max); + Assert.equals(2, props.max); } @Test public function testDetectNestedIfDepth() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new NestedIfDepthCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("NestedIfDepth", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("NestedIfDepth", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(2, props.max); + Assert.equals(2, props.max); } @Test public function testDetectNestedTryDepth() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new NestedTryDepthCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("NestedTryDepth", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("NestedTryDepth", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(2, props.max); + Assert.equals(2, props.max); } @Test public function testDetectNullableParameter() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new NullableParameterCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("NullableParameter", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("NullableParameter", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual("questionMark", props.option); + Assert.equals("questionMark", props.option); } @Test public function testDetectReturnCount() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new ReturnCountCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("ReturnCount", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("ReturnCount", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(10, props.max); + Assert.equals(10, props.max); } @Test public function testDetectTrace() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new TraceCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("Trace", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("Trace", detectedChecks[0].type); } @Test public function testDetectUnusedLocalVar() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new UnusedLocalVarCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("UnusedLocalVar", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("UnusedLocalVar", detectedChecks[0].type); } // checkstyle.checks.comments + @Test + public function testCommentedOutCode() { + var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new CommentedOutCodeCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); + Assert.equals(1, detectedChecks.length); + Assert.equals("CommentedOutCode", detectedChecks[0].type); + } + @Test public function testDetectDocCommentStyle() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new DocCommentStyleCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("DocCommentStyle", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("DocCommentStyle", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual("twostars", props.startStyle); - Assert.areEqual("none", props.lineStyle); + Assert.equals("twostars", props.startStyle); + Assert.equals("none", props.lineStyle); } @Test public function testDetectFieldDocComment() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new FieldDocCommentCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("FieldDocComment", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("FieldDocComment", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.isNotNull(props.tokens); - Assert.areEqual(5, props.tokens.length); + Assert.notNull(props.tokens); + Assert.equals(5, untyped props.tokens.length); Assert.isFalse(props.requireParams); Assert.isFalse(props.requireReturn); - Assert.isNotNull(props.excludeNames); - Assert.areEqual(2, props.excludeNames.length); - Assert.areEqual(FUNCTIONS, props.fieldType); - Assert.areEqual(PUBLIC, props.modifier); + Assert.notNull(props.excludeNames); + Assert.equals(2, untyped props.excludeNames.length); + Assert.equals(FUNCTIONS, props.fieldType); + Assert.equals(PUBLIC, props.modifier); } @Test public function testDetectTODOComment() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new TODOCommentCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("TODOComment", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("TODOComment", detectedChecks[0].type); } @Test public function testDetectTypeDocComment() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new TypeDocCommentCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("TypeDocComment", detectedChecks[0].type); - var props = cast detectedChecks[0].props; - Assert.isNotNull(props.tokens); - Assert.areEqual(5, props.tokens.length); + Assert.equals(1, detectedChecks.length); + Assert.equals("TypeDocComment", detectedChecks[0].type); + var props = detectedChecks[0].props; + Assert.notNull(untyped props.tokens); + Assert.equals(5, untyped props.tokens.length); } // checkstyle.checks.design @Test public function testDetectEmptyPackage() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new EmptyPackageCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("EmptyPackage", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("EmptyPackage", detectedChecks[0].type); var props = cast detectedChecks[0].props; Assert.isTrue(props.enforceEmptyPackage); } @@ -273,8 +281,8 @@ class DetectCodingStyleTest { @Test public function testDetectInterface() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new InterfaceCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("Interface", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("Interface", detectedChecks[0].type); var props = cast detectedChecks[0].props; Assert.isFalse(props.allowProperties); Assert.isTrue(props.allowMarkerInterfaces); @@ -282,35 +290,34 @@ class DetectCodingStyleTest { @Test public function testDetectUnnecessaryConstructor() { - var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new UnnecessaryConstructorCheck()], - [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("UnnecessaryConstructor", detectedChecks[0].type); + var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new UnnecessaryConstructorCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); + Assert.equals(1, detectedChecks.length); + Assert.equals("UnnecessaryConstructor", detectedChecks[0].type); } // checkstyle.checks.imports @Test public function testDetectAvoidStarImport() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new AvoidStarImportCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("AvoidStarImport", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("AvoidStarImport", detectedChecks[0].type); } @Test public function testDetectUnusedImport() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new UnusedImportCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("UnusedImport", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("UnusedImport", detectedChecks[0].type); } // checkstyle.checks.literal @Test public function testDetectStringLiteral() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new StringLiteralCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("StringLiteral", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("StringLiteral", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual("onlySingle", props.policy); + Assert.equals("onlySingle", props.policy); Assert.isTrue(props.allowException); } @@ -318,8 +325,8 @@ class DetectCodingStyleTest { @Test public function testDetectRedundantAccessMeta() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new RedundantAccessMetaCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("RedundantAccessMeta", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("RedundantAccessMeta", detectedChecks[0].type); var props = cast detectedChecks[0].props; Assert.isFalse(props.prohibitMeta); } @@ -327,8 +334,8 @@ class DetectCodingStyleTest { @Test public function testDetectRedundantAllowMeta() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new RedundantAllowMetaCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("RedundantAllowMeta", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("RedundantAllowMeta", detectedChecks[0].type); var props = cast detectedChecks[0].props; Assert.isFalse(props.prohibitMeta); } @@ -337,30 +344,28 @@ class DetectCodingStyleTest { @Test public function testDetectCyclomaticComplexity() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new CyclomaticComplexityCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("CyclomaticComplexity", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("CyclomaticComplexity", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(11, props.thresholds[0].complexity); - Assert.areEqual(SeverityLevel.WARNING, props.thresholds[0].severity); - Assert.areEqual(21, props.thresholds[1].complexity); - Assert.areEqual(SeverityLevel.ERROR, props.thresholds[1].severity); + Assert.equals(11, props.thresholds[0].complexity); + Assert.equals(SeverityLevel.WARNING, props.thresholds[0].severity); + Assert.equals(21, props.thresholds[1].complexity); + Assert.equals(SeverityLevel.ERROR, props.thresholds[1].severity); } // checkstyle.checks.modifier - #if haxe4 @Test public function testDetectInlineFinal() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new FinalCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("Final", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("Final", detectedChecks[0].type); } - #end @Test public function testDetectRedundantModifier() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new RedundantModifierCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("RedundantModifier", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("RedundantModifier", detectedChecks[0].type); var props = cast detectedChecks[0].props; Assert.isFalse(props.enforcePublicPrivate); Assert.isTrue(props.enforcePublic); @@ -371,10 +376,17 @@ class DetectCodingStyleTest { @Test public function testDetectConstantName() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new ConstantNameCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("ConstantName", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("ConstantName", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual("^[A-Z][A-Z0-9]*(_[A-Z0-9_]+)*$", props.format); + Assert.equals("^[A-Z][A-Z0-9]*(_[A-Z0-9_]+)*$", props.format); + } + + @Test + public function testDetectFileNameCase() { + var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new FileNameCaseCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); + Assert.equals(1, detectedChecks.length); + Assert.equals("FileNameCase", detectedChecks[0].type); } // checkstyle.checks.size @@ -382,42 +394,42 @@ class DetectCodingStyleTest { public function testDetectFileLength() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new FileLengthCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); // ignored not enough data points - Assert.areEqual(0, detectedChecks.length); + Assert.equals(0, detectedChecks.length); } @Test public function testDetectLineLength() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new LineLengthCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("LineLength", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("LineLength", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(100, props.max); + Assert.equals(100, props.max); } @Test public function testDetectMethodCount() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new MethodCountCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); // ignored not enough data points - Assert.areEqual(0, detectedChecks.length); + Assert.equals(0, detectedChecks.length); } @Test public function testDetectMethodLength() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new MethodLengthCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("MethodLength", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("MethodLength", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(35, props.max); + Assert.equals(35, props.max); Assert.isFalse(props.ignoreEmptyLines); } @Test public function testDetectParameterNumber() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new ParameterNumberCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("ParameterNumber", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("ParameterNumber", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(6, props.max); + Assert.equals(6, props.max); Assert.isFalse(props.ignoreOverriddenMethods); } @@ -425,22 +437,22 @@ class DetectCodingStyleTest { @Test public function testDetectAnonymous() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new AnonymousCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("Anonymous", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("Anonymous", detectedChecks[0].type); } @Test public function testDetectDynamic() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new DynamicCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("Dynamic", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("Dynamic", detectedChecks[0].type); } @Test public function testDetectReturn() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new ReturnCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("Return", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("Return", detectedChecks[0].type); var props = cast detectedChecks[0].props; Assert.isFalse(props.enforceReturnTypeForAnonymous); Assert.isTrue(props.allowEmptyReturn); @@ -450,16 +462,16 @@ class DetectCodingStyleTest { @Test public function testDetectType() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new TypeCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("Type", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("Type", detectedChecks[0].type); } // checkstyle.checks.whitespace @Test public function testDetectArrayAccess() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new ArrayAccessCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("ArrayAccess", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("ArrayAccess", detectedChecks[0].type); var props = cast detectedChecks[0].props; Assert.isTrue(props.spaceBefore); Assert.isTrue(props.spaceInside); @@ -468,14 +480,14 @@ class DetectCodingStyleTest { @Test public function testDetectEmptyLines() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new EmptyLinesCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("EmptyLines", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("EmptyLines", detectedChecks[0].type); var props = cast detectedChecks[0].props; Assert.isFalse(props.requireEmptyLineAfterPackage); Assert.isFalse(props.requireEmptyLineAfterInterface); Assert.isFalse(props.requireEmptyLineAfterAbstract); Assert.isTrue(props.allowEmptyLineAfterSingleLineComment); - Assert.areEqual(1, props.max); + Assert.equals(1, props.max); Assert.isFalse(props.requireEmptyLineAfterClass); Assert.isTrue(props.allowEmptyLineAfterMultiLineComment); } @@ -483,105 +495,105 @@ class DetectCodingStyleTest { @Test public function testDetectExtendedEmptyLines() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new ExtendedEmptyLinesCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("ExtendedEmptyLines", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("ExtendedEmptyLines", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(1, props.max); - Assert.areEqual(true, props.skipSingleLineTypes); - Assert.areEqual(EmptyLinesPolicy.UPTO, props.defaultPolicy); + Assert.equals(1, props.max); + Assert.equals(true, props.skipSingleLineTypes); + Assert.equals(EmptyLinesPolicy.UPTO, props.defaultPolicy); } @Test public function testDetectIndentationCharacter() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new IndentationCharacterCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("IndentationCharacter", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("IndentationCharacter", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual("tab", props.character); + Assert.equals("tab", props.character); } @Test public function testDetectIndentation() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new IndentationCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("Indentation", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("Indentation", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual("tab", props.character); + Assert.equals("tab", props.character); Assert.isFalse(props.ignoreConditionals); Assert.isFalse(props.ignoreComments); - Assert.areEqual("exact", props.wrapPolicy); + Assert.equals("exact", props.wrapPolicy); } @Test public function testDetectOperatorWhitespace() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new OperatorWhitespaceCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("OperatorWhitespace", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("OperatorWhitespace", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(WhitespacePolicy.IGNORE, props.ternaryOpPolicy); - Assert.areEqual(WhitespacePolicy.IGNORE, props.unaryOpPolicy); - Assert.areEqual(WhitespacePolicy.IGNORE, props.boolOpPolicy); - Assert.areEqual(WhitespacePolicy.IGNORE, props.intervalOpPolicy); - Assert.areEqual(WhitespacePolicy.AROUND, props.assignOpPolicy); - Assert.areEqual(WhitespacePolicy.IGNORE, props.oldFunctionTypePolicy); - Assert.areEqual(WhitespacePolicy.IGNORE, props.newFunctionTypePolicy); - Assert.areEqual(WhitespacePolicy.IGNORE, props.arrowFunctionPolicy); - Assert.areEqual(WhitespacePolicy.IGNORE, props.bitwiseOpPolicy); - Assert.areEqual(WhitespacePolicy.AROUND, props.arithmeticOpPolicy); - Assert.areEqual(WhitespacePolicy.AROUND, props.compareOpPolicy); - Assert.areEqual(WhitespacePolicy.IGNORE, props.arrowPolicy); + Assert.equals(WhitespacePolicy.IGNORE, props.ternaryOpPolicy); + Assert.equals(WhitespacePolicy.IGNORE, props.unaryOpPolicy); + Assert.equals(WhitespacePolicy.IGNORE, props.boolOpPolicy); + Assert.equals(WhitespacePolicy.IGNORE, props.intervalOpPolicy); + Assert.equals(WhitespacePolicy.AROUND, props.assignOpPolicy); + Assert.equals(WhitespacePolicy.IGNORE, props.oldFunctionTypePolicy); + Assert.equals(WhitespacePolicy.IGNORE, props.newFunctionTypePolicy); + Assert.equals(WhitespacePolicy.IGNORE, props.arrowFunctionPolicy); + Assert.equals(WhitespacePolicy.IGNORE, props.bitwiseOpPolicy); + Assert.equals(WhitespacePolicy.AROUND, props.arithmeticOpPolicy); + Assert.equals(WhitespacePolicy.AROUND, props.compareOpPolicy); + Assert.equals(WhitespacePolicy.IGNORE, props.arrowPolicy); } @Test public function testDetectOperatorWrap() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new OperatorWrapCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("OperatorWrap", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("OperatorWrap", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(WrapCheckBaseOption.EOL, props.option); + Assert.equals(WrapCheckBaseOption.EOL, props.option); } @Test public function testDetectSeparatorWhitespace() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new SeparatorWhitespaceCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("SeparatorWhitespace", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("SeparatorWhitespace", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual("after", props.commaPolicy); - Assert.areEqual("after", props.semicolonPolicy); - Assert.areEqual("before", props.dotPolicy); + Assert.equals("after", props.commaPolicy); + Assert.equals("after", props.semicolonPolicy); + Assert.equals("before", props.dotPolicy); } @Test public function testDetectSeparatorWrap() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new SeparatorWrapCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("SeparatorWrap", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("SeparatorWrap", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(WrapCheckBaseOption.EOL, props.option); + Assert.equals(WrapCheckBaseOption.EOL, props.option); } @Test public function testDetectSpacing() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new SpacingCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("Spacing", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("Spacing", detectedChecks[0].type); var props = cast detectedChecks[0].props; - Assert.areEqual(SpacingPolicy.SHOULD, props.spaceIfCondition); + Assert.equals(SpacingPolicy.SHOULD, props.spaceIfCondition); Assert.isFalse(props.spaceAroundBinop); - Assert.areEqual(SpacingPolicy.SHOULD, props.spaceForLoop); + Assert.equals(SpacingPolicy.SHOULD, props.spaceForLoop); Assert.isFalse(props.ignoreRangeOperator); - Assert.areEqual(SpacingPolicy.SHOULD, props.spaceWhileLoop); - Assert.areEqual(SpacingPolicy.SHOULD_NOT, props.spaceCatch); - Assert.areEqual(SpacingPolicy.SHOULD, props.spaceSwitchCase); + Assert.equals(SpacingPolicy.SHOULD, props.spaceWhileLoop); + Assert.equals(SpacingPolicy.SHOULD_NOT, props.spaceCatch); + Assert.equals(SpacingPolicy.SHOULD, props.spaceSwitchCase); Assert.isFalse(props.noSpaceAroundUnop); } @Test public function testDetectTrailingWhitespace() { var detectedChecks:Array = DetectCodingStyle.detectCodingStyle([new TrailingWhitespaceCheck()], [buildCheckFile(SAMPLE_CODING_STYLE)]); - Assert.areEqual(1, detectedChecks.length); - Assert.areEqual("TrailingWhitespace", detectedChecks[0].type); + Assert.equals(1, detectedChecks.length); + Assert.equals("TrailingWhitespace", detectedChecks[0].type); } function buildCheckFile(src:String):CheckFile { @@ -589,8 +601,7 @@ class DetectCodingStyleTest { } } -@:enum -abstract DetectCodingStyleTests(String) to String { +enum abstract DetectCodingStyleTests(String) to String { var SAMPLE_CODING_STYLE = " package; diff --git a/test/import.hx b/test/import.hx index 13b351df..d5dac959 100644 --- a/test/import.hx +++ b/test/import.hx @@ -1,2 +1,3 @@ import haxe.PosInfos; -import massive.munit.Assert; \ No newline at end of file +import utest.Assert; +import utest.ITest; \ No newline at end of file diff --git a/test/misc/CheckerTest.hx b/test/misc/CheckerTest.hx index adac7fb6..e16b1b48 100644 --- a/test/misc/CheckerTest.hx +++ b/test/misc/CheckerTest.hx @@ -2,7 +2,9 @@ package misc; import checkstyle.Checker; -class CheckerTest { +class CheckerTest implements ITest { + public function new() {} + @Test public function testEmptyLinesIdx() { var checker:Checker = new Checker(); @@ -53,9 +55,9 @@ class CheckerTest { function checkLinePos(checker:Checker, ofs:Int, expectedLine:Int, expectedOfs:Int, ?pos:PosInfos) { var linePos:LinePos = checker.getLinePos(ofs); - Assert.isNotNull(linePos, pos); - Assert.areEqual(expectedLine, linePos.line, pos); - Assert.areEqual(expectedOfs, linePos.ofs, pos); + Assert.notNull(linePos, pos); + Assert.equals(expectedLine, linePos.line, pos); + Assert.equals(expectedOfs, linePos.ofs, pos); } function throwsBadOffset(checker:Checker, ofs:Int, ?pos:PosInfos) { @@ -64,7 +66,7 @@ class CheckerTest { Assert.fail("line pos calculation should fail", pos); } catch (e:Any) { - Assert.areEqual("Bad offset", '$e', pos); + Assert.equals("Bad offset", '$e', pos); } } } \ No newline at end of file diff --git a/test/misc/ExtensionsTest.hx b/test/misc/ExtensionsTest.hx index 2091b4a7..6811967e 100644 --- a/test/misc/ExtensionsTest.hx +++ b/test/misc/ExtensionsTest.hx @@ -10,8 +10,7 @@ class ExtensionsTest extends CheckTestCase { } } -@:enum -abstract ExtensionsTests(String) to String { +enum abstract ExtensionsTests(String) to String { var TEST1 = " typedef TypedefName = { > OneTypedef, diff --git a/test/misc/ThreadTest.hx b/test/misc/ThreadTest.hx index 7a38a239..2eea2b29 100644 --- a/test/misc/ThreadTest.hx +++ b/test/misc/ThreadTest.hx @@ -2,20 +2,22 @@ package misc; import byte.ByteData; import checkstyle.CheckFile; -import checkstyle.reporter.ReporterManager; import checkstyle.Checker; -import checkstyle.ParserQueue; import checkstyle.CheckerPool; +import checkstyle.ParserQueue; +import checkstyle.checks.CheckTestCase.TestReporter; import checkstyle.checks.whitespace.IndentationCheck; import checkstyle.checks.whitespace.IndentationCheckTest.IndentationCheckTests; -import checkstyle.checks.CheckTestCase.TestReporter; +import checkstyle.reporter.ReporterManager; -class ThreadTest { +class ThreadTest implements ITest { static inline var FILE_NAME:String = "Test.hx"; var checker:Checker; var reporter:TestReporter; + public function new() {} + @Before public function setup() { checker = setupChecker(); @@ -30,9 +32,9 @@ class ThreadTest { var parseQueue = new ParserQueue(files, checker); parseQueue.start(1); + Sys.sleep(1); Assert.isFalse(parseQueue.isFinished()); - Sys.sleep(1); var failCount:Int = 0; var count:Int = 0; Assert.isFalse(parseQueue.isFinished()); @@ -48,7 +50,7 @@ class ThreadTest { if (count == 13) break; } Assert.isTrue(parseQueue.isFinished()); - Assert.areEqual(13, count); + Assert.equals(13, count); Assert.isNull(parseQueue.nextFile()); } @@ -61,10 +63,11 @@ class ThreadTest { var checkerPool = new CheckerPool(parseQueue, checker); checkerPool.start(5); + Sys.sleep(.2); Assert.isFalse(parseQueue.isFinished()); Assert.isFalse(checkerPool.isFinished()); - Sys.sleep(1); + var failCount:Int = 0; while (true) { if (failCount > 5) Assert.fail("parsing failed"); @@ -98,7 +101,7 @@ class ThreadTest { } @After - public function tearDown() { + public function teardown() { checker = null; reporter = null; } diff --git a/testAndResources.hxml b/testAndResources.hxml new file mode 100644 index 00000000..5dc54ba8 --- /dev/null +++ b/testAndResources.hxml @@ -0,0 +1,8 @@ +build/commonTest.hxml +build/commonCoverage.hxml +-x TestMain + +-cmd neko run -s src -s test -s schema -s build -p resources/static-analysis.txt +-cmd neko run -s src -s test -s schema -s build -r xml +-cmd neko run --default-config resources/default-config.json +-cmd neko run -c resources/default-config.json diff --git a/testCoverage.hxml b/testCoverage.hxml new file mode 100644 index 00000000..111034bc --- /dev/null +++ b/testCoverage.hxml @@ -0,0 +1,3 @@ +build/commonTest.hxml +build/commonCoverage.hxml +-x TestMain diff --git a/testJava.hxml b/testJava.hxml index 4647923e..21e18346 100644 --- a/testJava.hxml +++ b/testJava.hxml @@ -1,14 +1,7 @@ -buildGlobal.hxml --cp test --lib mcover --lib munit --lib test-adapter --D unittest -# -D jvm -# -debug ---macro mcover.MCover.coverage(['checkstyle'], ['src'], ['checkstyle.reporter', 'checkstyle.Main']) +build/commonTest.hxml +build/commonCoverage.hxml --java out +--jvm out/TestMain.jar -main TestMain -cmd java -jar out/TestMain.jar diff --git a/uglifyCheckstyle.sh b/uglifyCheckstyle.sh new file mode 100755 index 00000000..467b5580 --- /dev/null +++ b/uglifyCheckstyle.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +mkdir -p bin + +npx uglify-js-es6 haxecheckstyle.js -o bin/checkstyle.uglify.js + +echo '#!/usr/bin/env node' > bin/checkstyle.js +echo "" >> bin/checkstyle.js +cat bin/checkstyle.uglify.js >> bin/checkstyle.js +chmod 755 bin/checkstyle.js + +rm bin/checkstyle.uglify.js