Why doesn't the Erlang compiler detect undefined functions in compile time.
If I write test.erl:
-module(test).
-export([start/0]).
start() ->
erlang:foo().
It compiles fine.
Eshell V5.6.5 (abort with ^G)
1> c(test).
{ok,test}
2>
But crashes runtime.
2> test:start().
** exception error: undefined function erlang:foo/0
Why doesn't the compiler issue an error or a warning about this during compilation? It should know about exported functions, shouldn't it?
Erlang is a dynamic language. It is good practice however to do type checking and static analysis post-compilation .
The tool Dialyzer is used to check for this sort of error condition.
The reason the compiler doesn't know about it at compile time is because functions can be searched for and dynamically loaded from the code path at run time (and also from a remote node). The Dialyzer will check the code against the code path at the time it is run.
The ability to load code from a remote node means that basic 'systems' can be installed on a device and the device can then bootstrap itself from the network.
You should also remember another characteristic of Erlang that you can generate function calls on the fly using constructs like:
erlang:apply(ModuleName, FunctionName, ArgList)
so in that case it is simply not possible to know if the function exists at compile time or not.
And although the module and function might exist now at compile time, you can hot swap modules out and unload code, so it may not be there at run time.
You may use the xref
application to check the usage of deprecated, undefined and unused functions (and more!).
Compile the module with debug_info
:
Eshell V6.2 (abort with ^G)
1> c(test, debug_info).
{ok,test}
Check the module with xref:m/1
:
2> xref:m(test).
[{deprecated,[]},
{undefined,[{{test,start,0},{erlang,foo,0}}]},
{unused,[]}]
You may want to check out more about xref
here:
Erlang -- Xref - The Cross Reference Tool (Tools User's Guide)
I think that this is an implementation question as the Erlang developers decided to to runtime linking rather than build-time linking. Part of the reason may have something to do versioning and/or dynamic code loading.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.