├── test ├── test_helper.exs └── dialyze_test.exs ├── .gitignore ├── mix.exs ├── config └── config.exs ├── README.md ├── LICENSE └── lib └── mix └── tasks └── dialyze.ex /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /_build 2 | /deps 3 | erl_crash.dump 4 | *.ez 5 | -------------------------------------------------------------------------------- /test/dialyze_test.exs: -------------------------------------------------------------------------------- 1 | defmodule DialyzeTest do 2 | use ExUnit.Case 3 | 4 | test "the truth" do 5 | assert 1 + 1 == 2 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Dialyze.Mixfile do 2 | use Mix.Project 3 | 4 | def project do 5 | [app: :dialyze, 6 | version: "0.2.1", 7 | elixir: "~> 0.14.3 or ~> 0.15.0 or ~> 1.0", 8 | description: "Dialyzer Mix task", 9 | deps: [], 10 | aliases: [install: ["compile", "archive.build", "archive.install --force"]], 11 | package: package()] 12 | end 13 | 14 | def application do 15 | [applications: [:mix, :dialyzer]] 16 | end 17 | 18 | defp package() do 19 | [files: ["lib", "mix.exs", "README.md", "LICENSE"], 20 | maintainers: ["James Fish"], 21 | licenses: ["Apache 2.0"], 22 | links: %{"Github" => "https://github.com/fishcakez/dialyze"}] 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | # This file is responsible for configuring your application 2 | # and its dependencies. The Mix.Config module provides functions 3 | # to aid in doing so. 4 | use Mix.Config 5 | 6 | # Note this file is loaded before any dependency and is restricted 7 | # to this project. If another project depends on this project, this 8 | # file won't be loaded nor affect the parent project. 9 | 10 | # Sample configuration: 11 | # 12 | # config :my_dep, 13 | # key: :value, 14 | # limit: 42 15 | 16 | # It is also possible to import configuration files, relative to this 17 | # directory. For example, you can emulate configuration per environment 18 | # by uncommenting the line below and defining dev.exs, test.exs and such. 19 | # Configuration from the imported file will override the ones defined 20 | # here (which is why it is important to import them last). 21 | # 22 | # import_config "#{Mix.env}.exs" 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Mix.Task.Dialyze 2 | ================ 3 | 4 | This project is no longer maintained, please consider using/contributing to https://github.com/Comcast/dialyzex. 5 | 6 | Install 7 | ------- 8 | Add as a dependency: 9 | ```elixir 10 | defp deps() do 11 | [{:dialyze, "~> 0.2.0"}] 12 | end 13 | ``` 14 | Fetch and compile: 15 | ``` 16 | mix do deps.get, deps.compile 17 | ``` 18 | 19 | Or install as archive: 20 | ``` 21 | git clone https://github.com/fishcakez/dialyze.git 22 | cd dialyze 23 | mix install 24 | ``` 25 | 26 | Usage 27 | ----- 28 | Carry out success typing analysis on any mix project: 29 | ``` 30 | mix dialyze 31 | ``` 32 | To just check the PLT and skip success typing analysis: 33 | ``` 34 | mix dialyze --no-analyse 35 | ``` 36 | On subsequent calls for the same project checking the PLT can be 37 | skipped. This should only be done if the build environment's 38 | dependencies have not changed since the PLT were last checked: 39 | ``` 40 | mix dialyze --no-check 41 | ``` 42 | To skip compiling the project: 43 | ``` 44 | mix dialyze --no-compile 45 | ``` 46 | To turn on additional warnings: 47 | ``` 48 | mix dialyze --unmatched-returns --error-handling --race-conditions --underspecs 49 | ``` 50 | All switches are boolean and can be used in any combination, the default 51 | is: 52 | ``` 53 | mix dialyze --compile --check --analyse --no-unmatched-returns --no-error-handling --no-race-conditions --no-underspecs 54 | ``` 55 | 56 | License 57 | ------- 58 | 59 | Copyright 2014 James Fish 60 | 61 | Licensed under the Apache License, Version 2.0 (the "License"); 62 | you may not use this file except in compliance with the License. 63 | You may obtain a copy of the License at 64 | 65 | http://www.apache.org/licenses/LICENSE-2.0 66 | 67 | Unless required by applicable law or agreed to in writing, software 68 | distributed under the License is distributed on an "AS IS" BASIS, 69 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 70 | See the License for the specific language governing permissions and 71 | limitations under the License. 72 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /lib/mix/tasks/dialyze.ex: -------------------------------------------------------------------------------- 1 | defmodule Mix.Tasks.Dialyze do 2 | @moduledoc """ 3 | Analyses the current Mix project using success typing. 4 | 5 | ## Examples 6 | 7 | # Build or check a PLT and use it to analysis a project 8 | mix dialyze 9 | 10 | # Use the existing PLT to analysis a project 11 | mix dialyze --no-check 12 | 13 | # Build or check the PLT for current environment but don't analyse 14 | mix dialyze --no-analyse 15 | 16 | # Skip compiling the project 17 | mix dialyze --no-compile 18 | 19 | # Find extra warnings during analysis 20 | mix dialyze --unmatched-returns --error-handling --race-conditions --underspecs 21 | 22 | The `--no-check` switch should only be used when the PLT for the current 23 | build environment (including Erlang and Elixir) has been checked, and 24 | no changes have been made to dependencies (including Erlang and Elixir). It is 25 | not required to check the PLT even if changes are made to dependencies but the 26 | success typing analysis will be less accurate and may make incorrect warnings. 27 | 28 | Below is a common pattern of use: 29 | 30 | ## Examples 31 | 32 | # Fetch deps 33 | mix deps.get 34 | # Possibly make changes to current application and then compile project 35 | mix compile 36 | # Run Dialyze for the first time to build a PLT and analyse 37 | mix dialyze 38 | # Fix Dialyzer warnings and analyse again (assuming same build 39 | # environment, Elixir version, Erlang version and deps) 40 | mix dialyze --no-check 41 | 42 | This task will automatically find all dependencies for the current build 43 | environment and add them to a PLT. The most common dependencies from 44 | Erlang/OTP and Elixir will be cached for each version of Erlang and Elixir and 45 | re-used between projects. If a PLT exists for the active versions of Erlang 46 | and Elixir, and the current build environment the PLT will be checked for 47 | consistency before analysis. 48 | 49 | This task tries to be as efficient as possible in reusing PLTs. If Erlang or 50 | Elixir is changed (including changing directories) without their versions 51 | changing, the next consistency check for each project and build environment 52 | will take longer as the PLT will need to be updated. 53 | 54 | The default warning flags are: 55 | 56 | --return --unused --improper-lists --fun-app --match --opaque 57 | --fail-call --contracts --behaviours --undefined-callbacks 58 | --no-unmatched-returns --no-error-handling --no-race-conditions 59 | --no-overspecs --no-underspecs, --no-unknown --no-overspecs --no-specdiffs 60 | 61 | For more information on `dialyzer` and success typing see: 62 | `http://www.erlang.org/doc/apps/dialyzer/index.html` 63 | """ 64 | 65 | @shortdoc "Analyses the current Mix project using success typing" 66 | 67 | use Mix.Task 68 | 69 | @no_warnings [:return, :unused, :improper_lists, :fun_app, 70 | :match, :opaque, :fail_call, :contracts, :behaviours, :undefined_callbacks] 71 | @warnings [:unmatched_returns, :error_handling, :race_conditions, :overspecs, 72 | :underspecs, :unknown, :overspecs, :specdiffs] 73 | 74 | @spec run(OptionParser.argv) :: :ok 75 | def run(args) do 76 | {make, prepare, analysis, warnings} = parse_args(args) 77 | info("Finding applications for analysis") 78 | {mods, deps} = get_info(make) 79 | try do 80 | {plt, plt_beams} = ( plts_list(deps) |> prepare.() ) 81 | analysis.(plt, mods, plt_beams, warnings) 82 | else 83 | [] -> :ok 84 | [_|_] = warnings -> 85 | print_warnings(warnings) 86 | Mix.raise "Dialyzer reported #{length(warnings)} warnings" 87 | catch 88 | :throw, {:dialyzer_error, reason} -> 89 | Mix.raise "Dialyzer error: " <> IO.chardata_to_string(reason) 90 | end 91 | end 92 | 93 | defp parse_args(args) do 94 | warn_switches = Enum.map(@no_warnings ++ @warnings, &{&1, :boolean}) 95 | switches = [compile: :boolean, check: :boolean, analyse: :boolean] ++ 96 | warn_switches 97 | {opts, _, _} = OptionParser.parse(args, [strict: switches]) 98 | {make_fun(opts), prepare_fun(opts), analysis_fun(opts), warnings_list(opts)} 99 | end 100 | 101 | defp make_fun(opts) do 102 | case Keyword.get(opts, :compile, true) do 103 | true -> &compile/0 104 | false -> &no_compile/0 105 | end 106 | end 107 | 108 | defp prepare_fun(opts) do 109 | case Keyword.get(opts, :check, true) do 110 | true -> &check/1 111 | false -> &no_check/1 112 | end 113 | end 114 | 115 | defp analysis_fun(opts) do 116 | case Keyword.get(opts, :analyse, true) do 117 | true -> &analyse/4 118 | false -> &no_analyse/4 119 | end 120 | end 121 | 122 | defp warnings_list(opts) do 123 | warnings = Enum.filter(@warnings, &Keyword.get(opts, &1, false)) 124 | no_warnings = Enum.filter_map(@no_warnings, 125 | &(not Keyword.get(opts, &1, true)), &String.to_atom("no_#{&1}")) 126 | warnings ++ no_warnings 127 | end 128 | 129 | defp no_compile(), do: :ok 130 | 131 | defp compile(), do: Mix.Task.run("compile", []) 132 | 133 | defp get_info(make) do 134 | infos = app_info_list(make) 135 | apps = Keyword.keys(infos) 136 | mods = Enum.flat_map(infos, fn({_, {mods, _deps}}) -> mods end) 137 | deps = Enum.flat_map(infos, fn({_, {_mods, deps}}) -> deps end) 138 | # Ensure apps not in deps. 139 | {mods, Enum.uniq(deps) -- apps} 140 | end 141 | 142 | defp app_info_list(make) do 143 | case Mix.Project.umbrella?() do 144 | true -> get_umbrella_info(make) 145 | false -> [get_app_info(make)] 146 | end 147 | end 148 | 149 | defp get_umbrella_info(make) do 150 | config = [build_path: Mix.Project.build_path()] 151 | for %Mix.Dep{app: app, opts: opts} <- Mix.Dep.Umbrella.loaded() do 152 | path = opts[:path] 153 | Mix.Project.in_project(app, path, config, fn(_) -> get_app_info(make) end) 154 | end 155 | end 156 | 157 | defp get_app_info(make) do 158 | make.() 159 | Keyword.fetch!(Mix.Project.config(), :app) 160 | |> app_info() 161 | end 162 | 163 | defp plts_list(deps) do 164 | [{deps_plt(), deps}, {elixir_plt(), [:elixir]}, 165 | {erlang_plt(), [:erts, :kernel, :stdlib, :crypto]}] 166 | end 167 | 168 | defp erlang_plt(), do: global_plt("erlang-" <> otp_vsn()) 169 | 170 | defp otp_vsn() do 171 | major = :erlang.system_info(:otp_release) 172 | vsn_file = Path.join([:code.root_dir(), "releases", major, "OTP_VERSION"]) 173 | try do 174 | {:ok, contents} = File.read(vsn_file) 175 | String.split(contents, "\n", trim: true) 176 | else 177 | [full] -> 178 | full 179 | _ -> 180 | major 181 | catch 182 | :error, _ -> 183 | major 184 | end 185 | end 186 | 187 | defp elixir_plt() do 188 | global_plt("erlang-#{otp_vsn()}_elixir-#{System.version()}") 189 | end 190 | 191 | defp deps_plt do 192 | name = "erlang-#{otp_vsn()}_elixir-#{System.version()}_deps-#{build_env()}" 193 | local_plt(name) 194 | end 195 | 196 | defp build_env() do 197 | config = Mix.Project.config() 198 | case Keyword.fetch!(config, :build_per_environment) do 199 | true -> Atom.to_string(Mix.env()) 200 | false -> "shared" 201 | end 202 | end 203 | 204 | defp global_plt(name) do 205 | Path.join(Mix.Utils.mix_home(), "dialyze_" <> name <> ".plt") 206 | end 207 | 208 | defp local_plt(name) do 209 | Path.join(Mix.Project.build_path(), "dialyze_" <> name <> ".plt") 210 | end 211 | 212 | defp no_analyse(_plts, _mods, _plt_beams, _warnings), do: [] 213 | 214 | defp analyse(plt, mods, plt_beams, warnings) do 215 | info("Finding modules for analysis") 216 | beams = resolve_modules(mods, HashSet.new()) 217 | clashes = HashSet.intersection(beams, plt_beams) 218 | case HashSet.size(clashes) do 219 | 0 -> 220 | plt_analyse(plt, beams, warnings) 221 | _ -> 222 | Mix.raise "Clashes with plt: " <> 223 | inspect(HashSet.to_list(clashes)) 224 | end 225 | end 226 | 227 | defp no_check([{plt, _apps} | _plts]) do 228 | case plt_files(plt) do 229 | nil -> 230 | Mix.raise "Could not open #{plt}: #{:file.format_error(:enoent)}" 231 | beams -> 232 | {plt, beams} 233 | end 234 | end 235 | 236 | defp check(plts) do 237 | info("Finding suitable PLTs") 238 | find_plts(plts, []) 239 | end 240 | 241 | defp find_plts([{plt, apps} | plts], acc) do 242 | case plt_files(plt) do 243 | nil -> 244 | find_plts(plts, [{plt, apps, nil} | acc]) 245 | beams -> 246 | apps_rest = Enum.flat_map(plts, fn({_plt2, apps2}) -> apps2 end) 247 | apps = Enum.uniq(apps ++ apps_rest) 248 | check_plts([{plt, apps, beams} | acc]) 249 | end 250 | end 251 | 252 | defp find_plts([], acc) do 253 | check_plts(acc) 254 | end 255 | 256 | defp check_plts(plts) do 257 | {last_plt, beams, _cache} = Enum.reduce(plts, {nil, HashSet.new(), %{}}, 258 | fn({plt, apps, beams}, acc) -> 259 | check_plt(plt, apps, beams, acc) 260 | end) 261 | {last_plt, beams} 262 | end 263 | 264 | defp check_plt(plt, apps, old_beams, {prev_plt, prev_beams, prev_cache}) do 265 | info("Finding applications for #{Path.basename(plt)}") 266 | cache = resolve_apps(apps, prev_cache) 267 | mods = cache_mod_diff(cache, prev_cache) 268 | info("Finding modules for #{Path.basename(plt)}") 269 | beams = resolve_modules(mods, prev_beams) 270 | check_beams(plt, beams, old_beams, prev_plt) 271 | {plt, beams, cache} 272 | end 273 | 274 | defp cache_mod_diff(new, old) do 275 | Enum.flat_map(new, 276 | fn({app, {mods, _deps}}) -> 277 | case Map.has_key?(old, app) do 278 | true -> [] 279 | false -> mods 280 | end 281 | end) 282 | end 283 | 284 | defp resolve_apps(apps, cache) do 285 | apps 286 | |> Enum.uniq() 287 | |> Enum.filter_map(&(not Map.has_key?(cache, &1)), &app_info/1) 288 | |> Enum.into(cache) 289 | end 290 | 291 | defp app_info(app) do 292 | app_file = Atom.to_char_list(app) ++ '.app' 293 | case :code.where_is_file(app_file) do 294 | :non_existing -> 295 | error("Unknown application #{inspect(app)}") 296 | {app, {[], []}} 297 | app_file -> 298 | Path.expand(app_file) 299 | |> read_app_info(app) 300 | end 301 | end 302 | 303 | defp read_app_info(app_file, app) do 304 | case :file.consult(app_file) do 305 | {:ok, [{:application, ^app, info}]} -> 306 | parse_app_info(info, app) 307 | {:error, reason} -> 308 | Mix.raise "Could not read #{app_file}: #{:file.format_error(reason)}" 309 | end 310 | end 311 | 312 | defp parse_app_info(info, app) do 313 | mods = Keyword.get(info, :modules, []) 314 | apps = Keyword.get(info, :applications, []) 315 | inc_apps = Keyword.get(info, :included_applications, []) 316 | runtime_deps = get_runtime_deps(info) 317 | {app, {mods, runtime_deps ++ inc_apps ++ apps}} 318 | end 319 | 320 | defp get_runtime_deps(info) do 321 | Keyword.get(info, :runtime_dependencies, []) 322 | |> Enum.map(&parse_runtime_dep/1) 323 | end 324 | 325 | defp parse_runtime_dep(runtime_dep) do 326 | runtime_dep = IO.chardata_to_string(runtime_dep) 327 | regex = ~r/^(.+)\-\d+(?|\.\d+)*$/ 328 | [app] = Regex.run(regex, runtime_dep, [capture: :all_but_first]) 329 | String.to_atom(app) 330 | end 331 | 332 | defp resolve_modules(modules, beams) do 333 | Enum.reduce(modules, beams, &resolve_module/2) 334 | end 335 | 336 | defp resolve_module(module, beams) do 337 | beam = Atom.to_char_list(module) ++ '.beam' 338 | case :code.where_is_file(beam) do 339 | path when is_list(path) -> 340 | path = Path.expand(path) 341 | HashSet.put(beams, path) 342 | :non_existing -> 343 | error("Unknown module #{inspect(module)}") 344 | beams 345 | end 346 | end 347 | 348 | defp check_beams(plt, beams, nil, prev_plt) do 349 | plt_ensure(plt, prev_plt) 350 | case plt_files(plt) do 351 | nil -> 352 | Mix.raise("Could not open #{plt}: #{:file.format_error(:enoent)}") 353 | old_beams -> 354 | check_beams(plt, beams, old_beams) 355 | end 356 | end 357 | 358 | defp check_beams(plt, beams, old_beams, _prev_plt) do 359 | check_beams(plt, beams, old_beams) 360 | end 361 | 362 | defp check_beams(plt, beams, old_beams) do 363 | remove = HashSet.difference(old_beams, beams) 364 | plt_remove(plt, remove) 365 | check = HashSet.intersection(beams, old_beams) 366 | plt_check(plt, check) 367 | add = HashSet.difference(beams, old_beams) 368 | plt_add(plt, add) 369 | end 370 | 371 | defp plt_ensure(plt, nil), do: plt_new(plt) 372 | defp plt_ensure(plt, prev_plt), do: plt_copy(prev_plt, plt) 373 | 374 | defp plt_new(plt) do 375 | info("Creating #{Path.basename(plt)}") 376 | plt = erl_path(plt) 377 | _ = plt_run([analysis_type: :plt_build, output_plt: plt, 378 | apps: [:erts]]) 379 | :ok 380 | end 381 | 382 | defp plt_copy(plt, new_plt) do 383 | info("Copying #{Path.basename(plt)} to #{Path.basename(new_plt)}") 384 | File.cp!(plt, new_plt) 385 | end 386 | 387 | defp plt_add(plt, files) do 388 | case HashSet.size(files) do 389 | 0 -> 390 | :ok 391 | n -> 392 | (Mix.shell()).info("Adding #{n} modules to #{Path.basename(plt)}") 393 | plt = erl_path(plt) 394 | files = erl_files(files) 395 | _ = plt_run([analysis_type: :plt_add, init_plt: plt, 396 | files: files]) 397 | :ok 398 | end 399 | end 400 | 401 | defp plt_remove(plt, files) do 402 | case HashSet.size(files) do 403 | 0 -> 404 | :ok 405 | n -> 406 | info("Removing #{n} modules from #{Path.basename(plt)}") 407 | plt = erl_path(plt) 408 | files = erl_files(files) 409 | _ = plt_run([analysis_type: :plt_remove, init_plt: plt, 410 | files: files]) 411 | :ok 412 | end 413 | end 414 | 415 | defp plt_check(plt, files) do 416 | case HashSet.size(files) do 417 | 0 -> 418 | :ok 419 | n -> 420 | (Mix.shell()).info("Checking #{n} modules in #{Path.basename(plt)}") 421 | plt = erl_path(plt) 422 | _ = plt_run([analysis_type: :plt_check, init_plt: plt]) 423 | :ok 424 | end 425 | end 426 | 427 | defp plt_analyse(plt, files, warnings) do 428 | case HashSet.size(files) do 429 | 0 -> 430 | [] 431 | n -> 432 | info("Analysing #{n} modules with #{Path.basename(plt)}") 433 | plt = erl_path(plt) 434 | files = Enum.map(files, &erl_path/1) 435 | plt_run([analysis_type: :succ_typings, plts: [plt], files: files, 436 | warnings: warnings]) 437 | end 438 | end 439 | 440 | defp plt_run(opts) do 441 | :dialyzer.run([check_plt: false] ++ opts) 442 | end 443 | 444 | defp plt_info(plt) do 445 | erl_path(plt) 446 | |> :dialyzer.plt_info() 447 | end 448 | 449 | defp erl_files(files) do 450 | Enum.reduce(files, [], &[erl_path(&1)|&2]) 451 | end 452 | 453 | defp erl_path(path) do 454 | encoding = :file.native_name_encoding() 455 | :unicode.characters_to_list(path, encoding) 456 | end 457 | 458 | defp plt_files(plt) do 459 | info("Looking up modules in #{Path.basename(plt)}") 460 | case plt_info(plt) do 461 | {:ok, info} -> 462 | Keyword.fetch!(info, :files) 463 | |> Enum.reduce(HashSet.new(), &HashSet.put(&2, Path.expand(&1))) 464 | {:error, :no_such_file} -> 465 | nil 466 | {:error, reason} -> 467 | Mix.raise("Could not open #{plt}: #{:file.format_error(reason)}") 468 | end 469 | end 470 | 471 | defp print_warnings(warnings) do 472 | _ = for warning <- warnings do 473 | _ = error(format_warning(warning)) 474 | :ok 475 | end 476 | :ok 477 | end 478 | 479 | defp format_warning(warning) do 480 | :dialyzer.format_warning(warning, :fullpath) 481 | |> IO.chardata_to_string() 482 | end 483 | 484 | defp info(msg), do: apply(Mix.shell(), :info, [msg]) 485 | 486 | defp error(msg), do: apply(Mix.shell(), :error, [msg]) 487 | 488 | end 489 | --------------------------------------------------------------------------------