dialyzer:erlang代碼分析器

Erlang是一種“動態”語言,這會帶來一個問題,單元測試不足以證明我寫的代碼是否足夠正確。很難發現動態語言類型錯用的問題。靜態類型語言倒是很容易找到此類錯誤,但是Erlang是“動態的”。例如,length/1函數只能處理類型爲列表(list)的參數,如果傳入的不是列表,比如傳入一個atom就會出錯,但是程序中這樣的代碼是能夠通過編譯的,運氣好的話會有一個警告,運氣差的話只能在運行時發現出錯。例如以下代碼能成功的編譯,也不會有警告,但是顯然代碼是有問題的,這個問題只能在運行時(foo函數被調用時)才能發現:
bar(List) ->

abc.

foo() ->

V1 = bar([]),

io:format("length: ~p~n", [length(V1)]).  %% 這裏V1必須是list纔行,但是編譯時是沒法知道的,只有運行時纔會發現這個錯誤

同樣的例子,exit/2函數的第一個參數必須是Pid,如果不是也能順利通過編譯,這樣只能在運行時纔會被發現此外,我自己寫的函數,比如bar函數,可能業務邏輯決定了傳入的參數必須是list,返回的參數也應該是list,如果不是,那調用者肯定錯誤的使用了此函數。在動態語言中很難做到對參數類型和返回類型的限制。也就是說,對庫的接口的錯誤理解和錯誤使用是Erlang這樣的動態語言常見問題。爲此設計了一套合約語言(contract language),有了合約(contract),dialyzer能夠很容易的檢測到誤用的接口有兩種建立合約的方式,一種是在註釋裏使用@spec這樣的annotation,另一種是spec聲明
例如規定bar函數只能接收atom或整數,只能返回atom的list:
-type bar_thing() :: atom() | integer().  %% 類型聲明:定義bar函數能接收的參數類型

-type ret_thing() :: [atom()].  %% 類型聲明:定義bar函數的返回類型

-spec bar(bar_thing()) -> ret_thing(). %% 函數合約:bar函數的參數和返回值


或者
-spec bar(Arg::atom()|integer()) -> [atom()].


另一種是使用annotation的方式,(注意註釋中spec要以點號結束annotation,不然無效):
%% @spec bar(Arg::atom()|integer()) -> [atom()].

正如註釋一樣,annotation不會影響編譯。不過,違反了合約(contact)依然能順利編譯通過,但是我們現在就可以通過dialyzer工具分析源代碼找出所有違反合約的代碼
dialyzer --src -c test1.erl 可以一次分析工程中的所有文件
dialyzer --src -I ./include -c *.erl
但是可能會有太多的警告信息了,也可以一個文件一個文件的分析,處理起來容易一點注1:使用dialyzer工具前需要先構建plt:
dialyzer --build_plt -r $OTP_HOME/lib/kernel-2.12.4/ebin/

$OTP_HOME/lib/stdlib-1.15.4/ebin/

$OTP_HOME/lib/mnesia-4.4.5/ebin (或者其它更多的模塊)

這一過程耗時很長(大概5分多鐘),成功後會在我的home目錄下創建一個叫.dialyzer_plt的文件
注2:有個萬能類型any()可以代表任意的數據類型;
注3:可以將多個文件中用到的類型(比如pos())集中到一個erl文件中(比如m.erl),通過m:pos()使用該類型;或者將該類型集中到頭文件hrl中,使用時包含進來。
注4:typer工具可以列出所有聲明的合約總結:

可以通過確定某種編程規範以及使用Dialyzer這樣的工具分析代碼是否正確,克服動態語言的弱點。聲明和合約一般不影響編譯和運行。所以編譯通過不一定代表合約有效,還需要dialyzer工具分析

以下是鍵入dialyzer --help之後的幫助文檔

Usage: dialyzer [--help] [--version] [--shell] [--quiet] [--verbose]
        [-pa dir]* [--plt plt] [--plts plt*] [-Ddefine]*
                [-I include_dir]* [--output_plt file] [-Wwarn]*
                [--src] [--gui | --wx] [files_or_dirs] [-r dirs]
                [--apps applications] [-o outfile]
        [--build_plt] [--add_to_plt] [--remove_from_plt]
        [--check_plt] [--no_check_plt] [--plt_info] [--get_warnings]
                [--no_native] [--fullpath]
Options:
  files_or_dirs (for backwards compatibility also as: -c files_or_dirs)
      Use Dialyzer from the command line to detect defects in the
      specified files or directories containing .erl or .beam files,
      depending on the type of the analysis.
  -r dirs
      Same as the previous but the specified directories are searched
      recursively for subdirectories containing .erl or .beam files in
      them, depending on the type of analysis.
  --apps applications
      Option typically used when building or modifying a plt as in:
        dialyzer --build_plt --apps erts kernel stdlib mnesia ...
      to conveniently refer to library applications corresponding to the
      Erlang/OTP installation. However, the option is general and can also
      be used during analysis in order to refer to Erlang/OTP applications.
      In addition, file or directory names can also be included, as in:
        dialyzer --apps inets ssl ./ebin ../other_lib/ebin/my_module.beam
  -o outfile (or --output outfile)
      When using Dialyzer from the command line, send the analysis
      results to the specified outfile rather than to stdout.
  --raw
      When using Dialyzer from the command line, output the raw analysis
      results (Erlang terms) instead of the formatted result.
      The raw format is easier to post-process (for instance, to filter
      warnings or to output HTML pages).
  --src
      Override the default, which is to analyze BEAM files, and
      analyze starting from Erlang source code instead.
  -Dname (or -Dname=value)
      When analyzing from source, pass the define to Dialyzer. (**)
  -I include_dir
      When analyzing from source, pass the include_dir to Dialyzer. (**)
  -pa dir
      Include dir in the path for Erlang (useful when analyzing files
      that have '-include_lib()' directives).
  --output_plt file
      Store the plt at the specified file after building it.
  --plt plt
      Use the specified plt as the initial plt (if the plt was built
      during setup the files will be checked for consistency).
  --plts plt*
      Merge the specified plts to create the initial plt -- requires
      that the plts are disjoint (i.e., do not have any module
      appearing in more than one plt).
      The plts are created in the usual way:
        dialyzer --build_plt --output_plt plt_1 files_to_include
        ...
        dialyzer --build_plt --output_plt plt_n files_to_include
      and then can be used in either of the following ways:
        dialyzer files_to_analyze --plts plt_1 ... plt_n
      or:
        dialyzer --plts plt_1 ... plt_n -- files_to_analyze
      (Note the -- delimiter in the second case)
  -Wwarn
      A family of options which selectively turn on/off warnings
      (for help on the names of warnings use dialyzer -Whelp).
  --shell
      Do not disable the Erlang shell while running the GUI.
  --version (or -v)
      Print the Dialyzer version and some more information and exit.
  --help (or -h)
      Print this message and exit.
  --quiet (or -q)
      Make Dialyzer a bit more quiet.
  --verbose
      Make Dialyzer a bit more verbose.
  --build_plt
      The analysis starts from an empty plt and creates a new one from the
      files specified with -c and -r. Only works for beam files.
      Use --plt(s) or --output_plt to override the default plt location.
  --add_to_plt
      The plt is extended to also include the files specified with -c and -r.
      Use --plt(s) to specify which plt to start from, and --output_plt to
      specify where to put the plt. Note that the analysis might include
      files from the plt if they depend on the new files.
      This option only works with beam files.
  --remove_from_plt
      The information from the files specified with -c and -r is removed
      from the plt. Note that this may cause a re-analysis of the remaining
      dependent files.
  --check_plt
      Check the plt for consistency and rebuild it if it is not up-to-date.
      Actually, this option is of rare use as it is on by default.
  --no_check_plt (or -n)
      Skip the plt check when running Dialyzer. Useful when working with
      installed plts that never change.
  --plt_info
      Make Dialyzer print information about the plt and then quit. The plt
      can be specified with --plt(s).
  --get_warnings
      Make Dialyzer emit warnings even when manipulating the plt. Warnings
      are only emitted for files that are actually analyzed.
  --dump_callgraph file
      Dump the call graph into the specified file whose format is determined
      by the file name extension. Supported extensions are: raw, dot, and ps.
      If something else is used as file name extension, default format '.raw'
      will be used.
  --no_native (or -nn)
      Bypass the native code compilation of some key files that Dialyzer
      heuristically performs when dialyzing many files; this avoids the
      compilation time but it may result in (much) longer analysis time.
  --fullpath
      Display the full path names of files for which warnings are emitted.
  --gui
      Use the gs-based GUI.
  --wx
      Use the wx-based GUI.

Note:
  * denotes that multiple occurrences of these options are possible.
 ** options -D and -I work both from command-line and in the Dialyzer GUI;
    the syntax of defines and includes is the same as that used by "erlc".

Warning options:
  -Wno_return
     Suppress warnings for functions that will never return a value.
  -Wno_unused
     Suppress warnings for unused functions.
  -Wno_improper_lists
     Suppress warnings for construction of improper lists.
  -Wno_tuple_as_fun
     Suppress warnings for using tuples instead of funs.
  -Wno_fun_app
     Suppress warnings for fun applications that will fail.
  -Wno_match
     Suppress warnings for patterns that are unused or cannot match.
  -Wno_opaque
     Suppress warnings for violations of opaqueness of data types.
  -Wno_behaviours
     Suppress warnings about behaviour callbacks which drift from the published
     recommended interfaces.
  -Wno_undefined_callbacks
     Suppress warnings about behaviours that have no -callback attributes for
     their callbacks.
  -Wunmatched_returns ***
     Include warnings for function calls which ignore a structured return
     value or do not match against one of many possible return value(s).
  -Werror_handling ***
     Include warnings for functions that only return by means of an exception.
  -Wrace_conditions ***
     Include warnings for possible race conditions.
  -Wunderspecs ***
     Warn about underspecified functions
     (those whose -spec is strictly more allowing than the success typing).

The following options are also available but their use is not recommended:
(they are mostly for Dialyzer developers and internal debugging)
  -Woverspecs ***
     Warn about overspecified functions
     (those whose -spec is strictly less allowing than the success typing).
  -Wspecdiffs ***
     Warn when the -spec is different than the success typing.

*** Identifies options that turn on warnings rather than turning them off.

The exit status of the command line version is:
  0 - No problems were encountered during the analysis and no
      warnings were emitted.
  1 - Problems were encountered during the analysis.
  2 - No problems were encountered, but warnings were emitted.





轉載:http://cryolite.iteye.com/blog/259877

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章