xref(3erl)
πΈ NAME πΈ
okay bestie, welcome to xref(3erl) β the Erlang Module Definition page for the cross reference tool, aka the thing that analyzes dependencies between functions, modules, applications and releases. It's giving detective energy for your codebase ππ
β¨ DESCRIPTION β¨
So Xref is a cross reference tool that you can use to find dependencies between functions, modules, applications and releases. Literally its whole vibe.
Calls between functions are either local calls like f(), or external calls like m:f(). Module data β which gets extracted from BEAM files β includes local functions, exported functions, local calls and external calls. By default, calls to built-in functions (BIF) are ignored, but if the option builtins β accepted by some of this module's functions β is set to true, calls to BIFs are included too. It's the analyzing OTP version that decides what functions are BIFs. Functional objects are assumed to be called where they are created (and nowhere else). Unresolved calls are calls to apply or spawn with variable module, variable function, or variable arguments. Examples are M:F(a), apply(M, f, [a]), and spawn(m, f(), Args). Unresolved calls are represented by calls where variable modules have been replaced with the atom '$M_EXPR', variable functions have been replaced with the atom '$F_EXPR', and variable number of arguments have been replaced with the number -1. The above mentioned examples are represented by calls to '$M_EXPR':'$F_EXPR'/1, '$M_EXPR':f/1, and m:'$F_EXPR'/-1. The unresolved calls are a subset of the external calls.
β οΈ Warning β οΈ
Unresolved calls make module data incomplete, which implies that the results of analyses may be invalid. not me finding out my analysis was invalid because of unresolved calls π
Applications are collections of modules. The modules' BEAM files are located in the ebin subdirectory of the application directory. The name of the application directory determines the name and version of the application. Releases are collections of applications located in the lib subdirectory of the release directory. There is more to read about applications and releases in the Design Principles book.
Xref servers are identified by names, supplied when creating new servers. Each Xref server holds a set of releases, a set of applications, and a set of modules with module data. Xref servers are independent of each other, and all analyses are evaluated in the context of one single Xref server β exceptions are the functions m/1 and d/1, which do not use servers at all. The mode of an Xref server determines what module data are extracted from BEAM files as modules are added to the server. Starting with R7, BEAM files compiled with the option debug_info contain so called debug information, which is an abstract representation of the code. In functions mode, which is the default mode, function calls and line numbers are extracted from debug information. In modules mode, debug information is ignored if present, but dependencies between modules are extracted from other parts of the BEAM files. The modules mode is significantly less time and space consuming than the functions mode, but the analyses that can be done are limited. tradeoffs, bestie, tradeoffs π
An analyzed module is a module that has been added to an Xref server together with its module data. A library module is a module located in some directory mentioned in the library path. A library module is said to be used if some of its exported functions are used by some analyzed module. An unknown module is a module that is neither an analyzed module nor a library module, but whose exported functions are used by some analyzed module. An unknown function is a used function that is neither local or exported by any analyzed module nor exported by any library module. An undefined function is an externally used function that is not exported by any analyzed module or library module. With this notion, a local function can be an undefined function, namely if it is externally used from some module. All unknown functions are also undefined functions; there is a figure in the User's Guide that illustrates this relationship. iykyk π
Starting with R9C, the module attribute tag deprecated can be used to inform Xref about deprecated functions and optionally when functions are planned to be removed. A few examples show the idea:
-deprecated({f,1}).:β The exported functionf/1is deprecated. Nothing is said whetherf/1will be removed or not.-deprecated({f,1,"Use g/1 instead"}).:β As above but with a descriptive string. The string is currently unused by xref but other tools can make use of it.-deprecated({f,'_'}).:β All exported functionsf/0,f/1and so on are deprecated.-deprecated(module).:β All exported functions in the module are deprecated. Equivalent to-deprecated({'_','_'})..-deprecated([{g,1,next_version}]).:β The functiong/1is deprecated and will be removed in next version.-deprecated([{g,2,next_major_release}]).:β The functiong/2is deprecated and will be removed in next major release.-deprecated([{g,3,eventually}]).:β The functiong/3is deprecated and will eventually be removed.-deprecated({'_','_',eventually}).:β All exported functions in the module are deprecated and will eventually be removed.
Before any analysis can take place, module data must be set up. For instance, the cross reference and the unknown functions are computed when all module data are known. The functions that need complete data (analyze, q, variables) take care of setting up data automatically. Module data need to be set up (again) after calls to any of the add, replace, remove, set_library_path or update functions. don't forget the rebuild, bestie, or your data is gonna be giving stale π
The result of setting up module data is the Call Graph. A (directed) graph consists of a set of vertices and a set of (directed) edges. The edges represent calls (From, To) between functions, modules, applications or releases. From is said to call To, and To is said to be used by From. The vertices of the Call Graph are the functions of all module data: local and exported functions of analyzed modules; used BIFs; used exported functions of library modules; and unknown functions. The functions module_info/0,1 added by the compiler are included among the exported functions, but only when called from some module. The edges are the function calls of all module data. A consequence of the edges being a set is that there is only one edge if a function is locally or externally used several times on one and the same line of code.
The Call Graph is represented by Erlang terms β the sets are lists β which is suitable for many analyses. But for analyses that look at chains of calls, a list representation is much too slow. Instead the representation offered by the digraph module is used. The translation of the list representation of the Call Graph β or a subgraph thereof β to the digraph representation does not come for free, so the language used for expressing queries to be described below has a special operator for this task and a possibility to save the digraph representation for subsequent analyses. premium feature energy β¨
In addition to the Call Graph there is a graph called the Inter Call Graph. This is a graph of calls (From, To) such that there is a chain of calls from From to To in the Call Graph, and every From and To is an exported function or an unused local function. The vertices are the same as for the Call Graph.
Calls between modules, applications and releases are also directed graphs. The types of the vertices and edges of these graphs are, ranging from the most special to the most general: Fun for functions; Mod for modules; App for applications; and Rel for releases. The following paragraphs will describe the different constructs of the language used for selecting and analyzing parts of the graphs, beginning with the constants:
Expression ::= Constants
Constants ::= Consts | Consts : Type | RegExpr
Consts ::= Constant | [Constant, ...] | {Constant, ...}
Constant ::= Call | Const
Call ::= FunSpec -> FunSpec | {MFA, MFA} | AtomConst -> AtomConst | {AtomConst, AtomConst}
Const ::= AtomConst | FunSpec | MFA
AtomConst ::= Application | Module | Release
FunSpec ::= Module : Function / Arity
MFA ::= {Module, Function, Arity}
RegExpr ::= RegString : Type | RegFunc | RegFunc : Type
RegFunc ::= RegModule : RegFunction / RegArity
RegModule ::= RegAtom
RegFunction ::= RegAtom
RegArity ::= RegString | Number | _ | -1
RegAtom ::= RegString | Atom | _
RegString ::= - a regular expression, as described in the re module, enclosed in double quotes -
Type ::= Fun | Mod | App | Rel
Function ::= Atom
Application ::= Atom
Module ::= Atom
Release ::= Atom
Arity ::= Number | -1
Atom ::= - same as Erlang atoms -
Number ::= - same as non-negative Erlang integers -
Examples of constants are: kernel, kernel->stdlib, [kernel, sasl], [pg -> mnesia, {tv, mnesia}] : Mod. It is an error if an instance of Const does not match any vertex of any graph. If there are more than one vertex matching an untyped instance of AtomConst, then the one of the most general type is chosen. A list of constants is interpreted as a set of constants, all of the same type. A tuple of constants constitute a chain of calls β which may, but does not have to, correspond to an actual chain of calls of some graph. Assigning a type to a list or tuple of Constant is equivalent to assigning the type to each Constant. <butterfly>so many little syntax crumbs, and we ate every one π¦</butterfly>
Regular expressions are used as a means to select some of the vertices of a graph. A RegExpr consisting of a RegString and a type β an example is "xref_.*" : Mod β is interpreted as those modules (or applications or releases, depending on the type) that match the expression. Similarly, a RegFunc is interpreted as those vertices of the Call Graph that match the expression. An example is "xref_.*":"add_.*"/"(2|3)", which matches all add functions of arity two or three of any of the xref modules. Another example, one that matches all functions of arity 10 or more: _:_/"[1-9].+". Here _ is an abbreviation for ".*", that is, the regular expression that matches anything.
The syntax of variables is simple:
Expression ::= Variable
Variable ::= - same as Erlang variables -
There are two kinds of variables: predefined variables and user variables. Predefined variables hold set up module data, and cannot be assigned to but only used in queries. User variables on the other hand can be assigned to, and are typically used for temporary results while evaluating a query, and for keeping results of queries for use in subsequent queries. The predefined variables are β variables marked with (*) are available in functions mode only:
Eβ Call Graph Edges(*).Vβ Call Graph Vertices(*).
Okay bestie, hereβs the variable squad youβre gonna see everywhere β no cap, every single one matters: π
Mβ Modules. All modules: analyzed modules, used library modules, and unknown modules. (The whole friend group, basically.)Aβ Applications. πRβ Releases. π¦MEβ Module Edges. All module calls.AEβ Application Edges. All application calls.REβ Release Edges. All release calls.Lβ Local Functions(*). All local functions of analyzed modules.Xβ Exported Functions. All exported functions of analyzed modules and all used exported functions of library modules.Fβ Functions(*).Bβ Used BIFs.Bis empty ifbuiltinsis false for all analyzed modules.Uβ Unknown Functions.UUβ Unused Functions(*). All local and exported functions of analyzed modules that have not been used.XUβ Externally Used Functions. Functions of all modules β including local functions β that have been used in some external call.LUβ Locally Used Functions(*). Functions of all modules that have been used in some local call.OLβ Functions with an attribute tagon_load(*).LCβ Local Calls(*).XCβ External Calls(*).AMβ Analyzed Modules.UMβ Unknown Modules.LMβ Used Library Modules.UCβ Unresolved Calls. Empty in modules mode.EEβ Inter Call Graph Edges(*).DFβ Deprecated Functions. All deprecated exported functions and all used deprecated BIFs.DF_1β Deprecated Functions. All deprecated functions to be removed in next version.DF_2β Deprecated Functions. All deprecated functions to be removed in next version or next major release.DF_3β Deprecated Functions. All deprecated functions to be removed in next version, next major release, or later.
Okay, now some facts about the predefined variables β and yes, the set operators + (union) and - (difference) plus the cast operator (Type) are described below. Lowkey important:
Fis equal toL + X. β¨Vis equal toX + L + B + U, whereX,L,BandUare pairwise disjoint (that is, have no elements in common).UUis equal toV - (XU + LU), whereLUandXUmay have elements in common. Put in another way:Vis equal toUU + XU + LU.OLis a subset ofF.Eis equal toLC + XC. Note thatLCandXCmay have elements in common, namely if some function is locally and externally used from one and the same function.Uis a subset ofXU.Bis a subset ofXU.LUis equal torange LC.XUis equal torange XC.LUis a subset ofF.UUis a subset ofF.range UCis a subset ofU.Mis equal toAM + LM + UM, whereAM,LMandUMare pairwise disjoint.MEis equal to(Mod) E.AEis equal to(App) E.REis equal to(Rel) E.(Mod) Vis a subset ofM. Equality holds if all analyzed modules have some local, exported, or unknown function.(App) Mis a subset ofA. Equality holds if all applications have some module.(Rel) Ais a subset ofR. Equality holds if all releases have some application.DF_1is a subset ofDF_2.DF_2is a subset ofDF_3.DF_3is a subset ofDF.DFis a subset ofX + B.
An important notion is conversion of expressions. The syntax of a cast expression is:
Expression ::= ( Type ) Expression
The interpretation of the cast operator depends on the named type Type, the type of Expression, and the structure of the elements of the interpretation of Expression. If the named type is equal to the expression type, no conversion is done. Otherwise, the conversion is done one step at a time; (Fun) (App) RE, for instance, is equivalent to (Fun) (Mod) (App) RE. Now assume that the interpretation of Expression is a set of constants (functions, modules, applications or releases). If the named type is more general than the expression type, say Mod and Fun respectively, then the interpretation of the cast expression is the set of modules that have at least one of their functions mentioned in the interpretation of the expression. If the named type is more special than the expression type, say Fun and Mod, then the interpretation is the set of all the functions of the modules (in modules mode, the conversion is partial since the local functions are not known). The conversions to and from applications and releases work analogously. For instance, (App) "xref_.*" : Mod returns all applications containing at least one module such that xref_ is a prefix of the module name.
Now assume that the interpretation of Expression is a set of calls. If the named type is more general than the expression type, say Mod and Fun respectively, then the interpretation of the cast expression is the set of calls (M1, M2) such that the interpretation of the expression contains a call from some function of M1 to some function of M2. If the named type is more special than the expression type, say Fun and Mod, then the interpretation is the set of all function calls (F1, F2) such that the interpretation of the expression contains a call (M1, M2) and F1 is a function of M1 and F2 is a function of M2 (in modules mode, there are no function calls, so a cast to Fun always yields an empty set). Again, the conversions to and from applications and releases work analogously.
The interpretation of constants and variables are sets, and those sets can be used as the basis for forming new sets by the application of set operators. The syntax:
Expression ::= Expression BinarySetOp ExpressionBinarySetOp ::= + | * | -
+, * and - are interpreted as union, intersection and difference respectively: the union of two sets contains the elements of both sets; the intersection of two sets contains the elements common to both sets; and the difference of two sets contains the elements of the first set that are not members of the second set. The elements of the two sets must be of the same structure; for instance, a function call cannot be combined with a function. But if a cast operator can make the elements compatible, then the more general elements are converted to the less general element type. For instance, M + F is equivalent to (Fun) M + F, and E - AE is equivalent to E - (Fun) AE. One more example: X * xref : Mod is interpreted as the set of functions exported by the module xref; xref : Mod is converted to the more special type of X (Fun, that is) yielding all functions of xref, and the intersection with X (all functions exported by analyzed modules and library modules) is interpreted as those functions that are exported by some module and functions of xref.
There are also unary set operators:
Expression ::= UnarySetOp ExpressionUnarySetOp ::= domain | range | strict
Recall that a call is a pair (From, To). domain applied to a set of calls is interpreted as the set of all vertices From, and range as the set of all vertices To. The interpretation of the strict operator is the operand with all calls on the form (A, A) removed.
The interpretation of the restriction operators is a subset of the first operand, a set of calls. The second operand, a set of vertices, is converted to the type of the first operand. The syntax of the restriction operators:
Expression ::= Expression RestrOp ExpressionRestrOp ::= |RestrOp ::= ||RestrOp ::= |||
The interpretation in some detail for the three operators:
|β The subset of calls from any of the vertices.||β The subset of calls to any of the vertices.|||β The subset of calls to and from any of the vertices. For all sets of callsCSand all sets of verticesVS,CS ||| VSis equivalent toCS | VS * CS || VS.
Two functions (modules, applications, releases) belong to the same strongly connected component if they call each other (in)directly. The interpretation of the components operator is the set of strongly connected components of a set of calls. The condensation of a set of calls is a new set of calls between the strongly connected components such that there is an edge between two components if there is some constant of the first component that calls some constant of the second component.
The interpretation of the of operator is a chain of calls of the second operand (a set of calls) that passes through all of the vertices of the first operand (a tuple of constants), in the given order. The second operand is converted to the type of the first operand. For instance, the of operator can be used for finding out whether a function calls another function indirectly, and the chain of calls demonstrates how. The syntax of the graph analyzing operators:
Expression ::= Expression BinaryGraphOp ExpressionExpression ::= UnaryGraphOp ExpressionUnaryGraphOp ::= components | condensationBinaryGraphOp ::= of
As was mentioned before, the graph analyses operate on the digraph representation of graphs. By default, the digraph representation is created when needed (and deleted when no longer used), but it can also be created explicitly by use of the closure operator:
Expression ::= ClosureOp ExpressionClosureOp ::= closure
The interpretation of the closure operator is the transitive closure of the operand.
The restriction operators are defined for closures as well; closure E | xref : Mod is interpreted as the direct or indirect function calls from the xref module, while the interpretation of E | xref : Mod is the set of direct calls from xref. If some graph is to be used in several graph analyses, it saves time to assign the digraph representation of the graph to a user variable, and then make sure that every graph analysis operates on that variable instead of the list representation of the graph.
The lines where functions are defined (more precisely: where the first clause begins) and the lines where functions are used are available in functions mode. The line numbers refer to the files where the functions are defined. This holds also for files included with the -include and -include_lib directives, which may result in functions defined apparently in the same line. The line operators are used for assigning line numbers to functions and for assigning sets of line numbers to function calls. The syntax is similar to the one of the cast operator:
Expression ::= ( LineOp) ExpressionExpression ::= ( XLineOp) ExpressionLineOp ::= Lin | ELin | LLin | XLinXLineOp ::= XXL
okay so the Lin operator applied to a set of functions? It assigns each function the line number where that function is defined. Unknown functions and functions of library modules get the number 0 β like, theyβre not in the group chat. π
When you apply some LineOp operator to a set of function calls, each call gets the set of line numbers where the first function calls the second function. Not all calls are assigned line numbers by all operators β hereβs the compatibility tea:
Linis defined for Call Graph Edges;LLinis defined for Local Calls.XLinis defined for External Calls.ELinis defined for Inter Call Graph Edges.
The Lin (LLin, XLin) operator assigns the lines where calls (local calls, external calls) are made. The ELin operator assigns to each call (From, To), for which it is defined, every line L such that there is a chain of calls from From to To beginning with a call on line L.
The XXL operator is defined for the interpretation of any of the LineOp operators applied to a set of function calls. The result is that of replacing the function call with a line numbered function call β that is, each of the two functions of the call is replaced by a pair of the function and the line where the function is defined. The effect of the XXL operator can be undone by the LineOp operators. For instance, (Lin) (XXL) (Lin) E is equivalent to (Lin) E.
The +, -, * and # operators are defined for line number expressions, provided the operands are compatible. The LineOp operators are also defined for modules, applications, and releases; the operand is implicitly converted to functions. Similarly, the cast operator is defined for the interpretation of the LineOp operators.
The interpretation of the counting operator is the number of elements of a set. The operator is undefined for closures. The +, - and * operators are interpreted as the obvious arithmetical operators when applied to numbers. The syntax of the counting operator:
Expression ::= CountOp ExpressionCountOp ::= #
All binary operators are left associative; for instance, A | B || C is equivalent to (A | B) || C. The following is a list of all operators, in increasing order of precedence:
+,-*#|,||,|||of(Type)closure,components,condensation,domain,range,strict
Parentheses are used for grouping, either to make an expression more readable or to override the default precedence of operators:
Expression ::= ( Expression )
A query is a non-empty sequence of statements. A statement is either an assignment of a user variable or an expression. The value of an assignment is the value of the right hand side expression. It makes no sense to put a plain expression anywhere else but last in queries. The syntax of queries is summarized by these productions:
Query ::= Statement, ...Statement ::= Assignment | ExpressionAssignment ::= Variable := Expression | Variable = Expression
A variable cannot be assigned a new value unless first removed. Variables assigned to by the = operator are removed at the end of the query, while variables assigned to by the := operator can only be removed by calls to forget. There are no user variables when module data need to be set up again; if any of the functions that make it necessary to set up module data again is called, all user variables are forgotten.
π DATA TYPES π
bestie, hereβs the whole type menu β no skips, no cap:
application() = atom()
call() = {atom(), atom()} | funcall()
constant() = xmfa() | module() | application() | release()
directory() = atom() | file:filename()
file() = file:filename()
file_error() = atom()
funcall() = {xmfa(), xmfa()}
function_name() = atom()
library() = atom()
library_path() = path() | code_path
mode() = functions | modules
path() = [file()]
release() = atom()
string_position() = integer() >= 1
variable() = atom()
xarity() = arity() | -1
xmfa() = {module(), function_name(), xarity()}
xref() = atom() | pid()
π EXPORTS π
okay so this is the export list, fr fr β every signature, every option, every reason type, all right here. π«Ά
π add_application
add_application(XrefServer, Directory) ->
{ok, application()} | {error, module(), Reason}
add_application(XrefServer, Directory, Options) ->
{ok, application()} | {error, module(), Reason}
Types:
XrefServer = xref()
Directory = directory()
Options = Option | [Option]
Option =
{builtins, boolean()} |
{name, application()} |
{verbose, boolean()} |
{warnings, boolean()} |
builtins | verbose | warnings
Reason =
{application_clash, {application(), directory(),
directory()}} |
add_dir_rsn()
add_dir_rsn() =
{file_error, file(), file_error()} |
{invalid_filename, term()} |
{invalid_options, term()} |
{unrecognized_file, file()} |
beam_lib:chnk_rsn()
Adds an application, the modules of the application and module data of the modules to an Xref server. The modules will be members of the application. Default app name? The base name of the directory with the version removed β unless you pass the name option, which overrides it. Returns the name of the application. πΈ
If the given directory has a subdirectory named ebin, modules (BEAM files) are searched for in that directory, otherwise modules are searched for in the given directory.
If the mode of the Xref server is functions, BEAM files that contain no debug information are ignored. π
π¦ add_directory
add_directory(XrefServer, Directory) ->
{ok, Modules} | {error, module(), Reason}
add_directory(XrefServer, Directory, Options) ->
{ok, Modules} | {error, module(), Reason}
Types:
XrefServer = xref()
Directory = directory()
Options = Option | [Option]
Option =
{builtins, boolean()} |
{recurse, boolean()} |
{verbose, boolean()} |
{warnings, boolean()} |
builtins | recurse | verbose | warnings
Modules = [module()]
Reason = add_dir_rsn()
add_dir_rsn() =
{file_error, file(), file_error()} |
{invalid_filename, term()} |
{invalid_options, term()} |
{unrecognized_file, file()} |
beam_lib:chnk_rsn()
Adds the modules found in the given directory and the modulesβ data to an Xref server. Default is not to examine subdirectories, but if the option recurse has the value true, modules are searched for in subdirectories on all levels as well as in the given directory. Returns a sorted list of the names of the added modules. β¨
The modules added will not be members of any applications.
If the mode of the Xref server is functions, BEAM files that contain no debug information are ignored. π
π§ add_module
add_module(XrefServer, File) ->
{ok, module()} | {error, module(), Reason}
add_module(XrefServer, File, Options) ->
{ok, module()} | {error, module(), Reason}
Types:
XrefServer = xref()
File = file:filename()
Options = Option | [Option]
Option =
{builtins, boolean()} |
{verbose, boolean()} |
{warnings, boolean()} |
builtins | verbose | warnings
Reason = add_mod_rsn()
add_mod_rsn() =
{file_error, file(), file_error()} |
{invalid_filename, term()} |
{invalid_options, term()} |
{module_clash, {module(), file(), file()}} |
{no_debug_info, file()} |
beam_lib:chnk_rsn()
Adds a module and its module data to an Xref server. The module will not be member of any application. Returns the name of the module. π
If the mode of the Xref server is functions, and the BEAM file contains no debug information, the error message no_debug_info is returned. π
π add_release
add_release(XrefServer, Directory) ->
{ok, release()} | {error, module(), Reason}
add_release(XrefServer, Directory, Options) ->
{ok, release()} | {error, module(), Reason}
Types:
XrefServer = xref()
Directory = directory()
Options = Option | [Option]
Option =
{builtins, boolean()} |
{name, release()} |
{verbose, boolean()} |
{warnings, boolean()} |
builtins | verbose | warnings
Reason =
{application_clash, {application(), directory(),
directory()}} |
{release_clash, {release(), directory(), directory()}} |
add_dir_rsn()
add_dir_rsn() =
{file_error, file(), file_error()} |
{invalid_filename, term()} |
{invalid_options, term()} |
{unrecognized_file, file()} |
beam_lib:chnk_rsn()
Adds a release, the applications of the release, the modules of the applications, and module data of the modules to an Xref server. The applications will be members of the release, and the modules will be members of the applications. Default release name is the base name of the directory, but this can be overridden by the name option. Returns the name of the release. π
If the given directory has a subdirectory named lib, the directories in that directory are assumed to be application directories, otherwise all subdirectories of the given directory are assumed to be application directories. If there are several versions of some application, the one with the highest version is chosen. π₯
If the mode of the Xref server is functions, BEAM files that contain no debug information are ignored. π
πΈ analyze
analyze(XrefServer, Analysis) ->
{ok, Answer} | {error, module(), Reason}
analyze(XrefServer, Analysis, Options) ->
{ok, Answer} | {error, module(), Reason}
Types:
XrefServer = xref()
Analysis = analysis()
Options = Option | [Option]
Option = {verbose, boolean()} | verbose
Answer = [term()]
Reason = analyze_rsn()
analysis() =
undefined_function_calls | undefined_functions |
locals_not_used | exports_not_used |
deprecated_function_calls |
{deprecated_function_calls, DeprFlag :: depr_flag()} |
deprecated_functions |
{deprecated_functions, DeprFlag :: depr_flag()} |
{call, FuncSpec :: func_spec()} |
{use, FuncSpec :: func_spec()} |
{module_call, ModSpec :: mod_spec()} |
{module_use, ModSpec :: mod_spec()} |
{application_call, AppSpec :: app_spec()} |
{application_use, AppSpec :: app_spec()} |
{release_call, RelSpec :: rel_spec()} |
{release_use, RelSpec :: rel_spec()}
app_spec() = application() | [application()]
depr_flag() = next_version | next_major_release | eventually
func_spec() = xmfa() | [xmfa()]
mod_spec() = module() | [module()]
rel_spec() = release() | [release()]
analyze_rsn() =
{invalid_options, term()} |
{parse_error, string_position(), term()} |
{unavailable_analysis, term()} |
{unknown_analysis, term()} |
{unknown_constant, string()} |
{unknown_variable, variable()}
Okay so this bad boy evaluates one of the predefined analyses for you π. It hands back a sorted list with no duplicates of either call() or constant() β which one you get depends on which analysis you picked, iykyk.
The predefined analyses all operate on every analyzed module, and the ones with a little (*) next to them are lowkey functions mode only β so don't come for them in modules mode, they're simply not available there π«Ά.
undefined_function_calls(*)β returns a list of calls that go absolutely nowhere, i.e. calls to undefined functions π»undefined_functionsβ returns a list of the undefined functions themselves (the actual missing icons, not the calls to them)locals_not_used(*)β returns a list of local functions that nobody locally ever used. sitting there. unused. tragic πexports_not_usedβ returns a list of exported functions that were never used externally. β οΈ note that in modules mode,M:behaviour_info/1is never reported as unused β she has immunity, periodtdeprecated_function_calls(*)β returns a list of external calls to deprecated functions. the drama π{deprecated_function_calls, DeprFlag}(*)β same idea, but now with vibes-based filtering viaDeprFlag:- if
DeprFlagisnext_version, you get calls to functions to be removed in next version; - if
DeprFlagisnext_major_release, you get calls to functions to be removed in next major release as well as calls to functions to be removed in next version; - and if
DeprFlagiseventually, you get all calls to functions to be removed β including the next-version and next-major-release ones. the full collection, no crumbs left π
- if
deprecated_functionsβ returns a list of externally used deprecated functions{deprecated_functions, DeprFlag}β returns a list of externally used deprecated functions, filtered byDeprFlag:next_versionβ functions to be removed in next version;next_major_releaseβ functions to be removed in next major release plus functions to be removed in next version;eventuallyβ all functions to be removed, including next-version and next-major-release ones β¨
{call, FuncSpec}(*)β returns a list of functions called by some of the functions you specified{use, FuncSpec}(*)β returns a list of functions that use some of the functions you specified (the reverse bestie π ){module_call, ModSpec}β returns a list of modules called by some of the given modules{module_use, ModSpec}β returns a list of modules that use some of the given modules{application_call, AppSpec}β returns a list of applications called by some of the given applications{application_use, AppSpec}β returns a list of applications that use some of the given applications{release_call, RelSpec}β returns a list of releases called by some of the given releases{release_use, RelSpec}β returns a list of releases that use some of the given releases
d(Directory)
d(Directory) ->
[DebugInfoResult] |
[NoDebugInfoResult] |
{error, module(), Reason}
Types:
Directory = directory()
DebugInfoResult =
{deprecated, [funcall()]} |
{undefined, [funcall()]} |
{unused, [mfa()]}
NoDebugInfoResult =
{deprecated, [xmfa()]} | {undefined, [xmfa()]}
Reason =
{file_error, file(), file_error()} |
{invalid_filename, term()} |
{unrecognized_file, file()} |
beam_lib:chnk_rsn()
okay so this one looks at all the modules chillin' in the given Directory and checks them for three things: calls to deprecated functions, calls to undefined functions, and unused local functions π΅οΈββοΈ. The code path? Yeah, that's used as the library path, bestie.
Now here's the tea β if some of the BEAM files it finds actually contain debug information, then those modules get checked and you get back a list of tuples. First element of each tuple is one of these:
deprecatedβ and the second element is a sorted list of calls to deprecated functions πundefinedβ and the second element is a sorted list of calls to undefined functions π»unusedβ and the second element is a sorted list of unused local functions π«
And if no BEAM file contains debug information, you get a list of tuples where the first element is one of:
deprecatedβ and the second element is a sorted list of externally used deprecated functionsundefinedβ and the second element is a sorted list of undefined functions
forget(XrefServer) -> ok
forget(XrefServer, Variables) -> ok | {error, module(), Reason}
Types:
XrefServer = xref()
Variables = variable() | [variable()]
Reason = {not_user_variable, term()}
forget/1 and forget/2 remove all or some of the user variables of an Xref server β¨. Like a little memory wipe, but make it consensual. (If you pass something that isn't a user variable you get {not_user_variable, term()} back β that's the Reason, fyi.)
format_error(Error) -> io_lib:chars()
Types:
Error = {error, module(), Reason :: term()}
Give this function the error returned by any function of this module and it hands you back a descriptive string of that error β in English, bestie π«Ά. And for file errors specifically, it calls file:format_error/1 under the hood. iconic delegation behavior honestly.
get_default(XrefServer) -> [{Option, Value}]
get_default(XrefServer, Option) -> {ok, Value} | {error, module(), Reason}
Types:
XrefServer = xref()
Option = builtins | recurse | verbose | warnings
Value = boolean()
Reason = {invalid_options, term()}
Returns the default values of one or more options. that's it, that's the function π
(yes, Value is a boolean() β no surprises here)
get_library_path(XrefServer) -> {ok, LibraryPath}
Types:
XrefServer = xref()
LibraryPath = library_path()
Returns the library path β¨. Straight to the point, we love a no-notes queen.
info(XrefServer) -> [Info]
info(XrefServer, Category) -> [{Item, [Info]}] | {error, module(), {no_such_info, Category}}
info(XrefServer, Category, Items) -> [{Item, [Info]}] | {error, module(), Reason}
Types:
XrefServer = xref()
Category = modules | applications | releases | libraries
Items = Item | [Item]
Item = module() | application() | release() | library()
Info = info()
Reason =
{no_such_application, Item} |
{no_such_info, Category} |
{no_such_library, Item} |
{no_such_module, Item} |
{no_such_release, Item}
info() =
{application, Application :: [application()]} |
{builtins, boolean()} |
{directory, directory()} |
{library_path, library_path()} |
{mode, mode()} |
{no_analyzed_modules, integer() >= 0} |
{no_applications, integer() >= 0} |
{no_calls,
{NoResolved :: integer() >= 0,
NoUnresolved :: integer() >= 0}} |
{no_function_calls,
{NoLocal :: integer() >= 0,
NoResolvedExternal :: integer() >= 0,
NoUnresolved :: integer() >= 0}} |
{no_functions,
{NoLocal :: integer() >= 0,
NoExternal :: integer() >= 0}} |
{no_inter_function_calls, integer() >= 0} |
{no_releases, integer() >= 0} |
{release, Release :: [release()]} |
{version, Version :: [integer() >= 0]}
The info functions return information as a list of pairs {Tag, term()} β in some order, so don't come for the ordering, it's not that kind of function π β about the state and the module data of an Xref server.
info/1 returns information with these tags (and yeah, the (*) ones are functions mode only again):
library_pathβ the library path β¨modeβ the modeno_releasesβ number of releasesno_applicationsβ total number of applications (of all releases, bestie, don't forget)no_analyzed_modulesβ total number of analyzed modulesno_calls (*)β total number of calls (in all modules), and yes, it counts instances of one function call on different lines as separate calls. little pedantic icon behavior, honestly πno_function_calls (*)β total number of local calls, resolved external calls and unresolved callsno_functions (*)β total number of local and exported functionsno_inter_function_calls (*)β total number of calls of the Inter Call Graph π₯
okay bestie, so info/2 and info/3 are literally the β¨ gossip β¨ functions β they spill the tea on all (or just some) of the analyzed modules, applications, releases or library modules chillin' inside an Xref server. here's everything you get back, no crumbs:
for every analyzed module π«Ά
applicationβ an empty list[]if the module doesn't belong to any application, otherwise a list of the application namebuiltinsβ whether calls to BIFs are included in the module's datadirectoryβ the directory where the module's BEAM file is locatedno_calls(*) β number of calls, regarding instances of one function call in different lines as separate callsno_function_calls(*) β number of local calls, resolved external calls and unresolved callsno_functions(*) β number of local and exported functionsno_inter_function_calls(*) β number of calls of the Inter Call Graph
for every application π
directoryβ the directory where the modules' BEAM files are locatedno_analyzed_modulesβ number of analyzed modulesno_calls(*) β number of calls of the application's modules, regarding instances of one function call in different lines as separate callsno_function_calls(*) β number of local calls, resolved external calls and unresolved calls of the application's modulesno_functions(*) β number of local and exported functions of the application's modulesno_inter_function_calls(*) β number of calls of the Inter Call Graph of the application's modulesreleaseβ an empty list[]if the application doesn't belong to any release, otherwise a list of the release nameversionβ the application's version as a list of numbers. for instance, the directory"kernel-2.6"results in the application namekerneland the application version[2,6];"kernel"yields the namekerneland the version[]
for every release π
directoryβ the release directoryno_analyzed_modulesβ number of analyzed modulesno_applicationsβ number of applicationsno_calls(*) β number of calls of the release's modules, regarding instances of one function call in different lines as separate callsno_function_calls(*) β number of local calls, resolved external calls and unresolved calls of the release's modulesno_functions(*) β number of local and exported functions of the release's modulesno_inter_function_calls(*) β number of calls of the Inter Call Graph of the release's modules
for every library module π¦
directoryβ the directory where the library module's BEAM file is located
ngl, for every single number of calls / functions / etc. that comes back under theno_tags, there's a query that hands you the exact same number. the examples below show those queries β some of them return the sum of two or more of theno_tag numbers. also,mod(app,rel) refers to any module (application, release). iykyk.
no_analyzed_modules"# AM"(info/1)"# (Mod) app:App"(application)"# (Mod) rel:Rel"(release)
no_applications"# A"(info/1)
no_callsβ the sum of the number of resolved and unresolved calls:"# (XLin) E + # (LLin) E"(info/1)"T = E | mod:Mod, # (LLin) T + # (XLin) T"(module)"T = E | app:App, # (LLin) T + # (XLin) T"(application)"T = E | rel:Rel, # (LLin) T + # (XLin) T"(release)
no_functionsβ functions in library modules and the functionsmodule_info/0,1are not counted byinfo. assuming that"Extra := _:module_info/\"(0|1)\" + LM"has been evaluated, the sum of the number of local and exported functions are:"# (F - Extra)"(info/1)"# (F * mod:Mod - Extra)"(module)"# (F * app:App - Extra)"(application)"# (F * rel:Rel - Extra)"(release)
no_function_callsβ the sum of the number of local calls, resolved external calls and unresolved calls:"# LC + # XC"(info/1)"# LC | mod:Mod + # XC | mod:Mod"(module)"# LC | app:App + # XC | app:App"(application)"# LC | rel:Rel + # XC | mod:Rel"(release)
no_inter_function_calls"# EE"(info/1)"# EE | mod:Mod"(module)"# EE | app:App"(application)"# EE | rel:Rel"(release)
no_releases"# R"(info/1)
π m/1 β the code path detective
m(FileOrModule) ->
[DebugInfoResult] |
[NoDebugInfoResult] |
{error, module(), Reason}
Types:
FileOrModule = file:filename() | module()
DebugInfoResult =
{deprecated, [funcall()]} |
{undefined, [funcall()]} |
{unused, [mfa()]}
NoDebugInfoResult =
{deprecated, [xmfa()]} | {undefined, [xmfa()]}
Reason =
{cover_compiled, Module} |
{file_error, file(), file_error()} |
{interpreted, Module} |
{invalid_filename, term()} |
{no_such_module, Module} |
beam_lib:chnk_rsn()
so the BEAM file you hand over (with or without the .beam extension β she's flexible like that) β or the file found by calling code:which(Module) β gets checked for calls to deprecated functions, calls to undefined functions, and for unused local functions. the code path is used as the library path, periodt.
if the BEAM file contains debug information, then you get a list of tuples back. the first element of each tuple is one of:
deprecatedβ the second element is a sorted list of calls to deprecated functionsundefinedβ the second element is a sorted list of calls to undefined functionsunusedβ the second element is a sorted list of unused local functions
if the BEAM file does not contain debug information, then you get a list of tuples back. the first element of each tuple is one of:
deprecatedβ the second element is a sorted list of externally used deprecated functions- `undefined β the second element is a sorted list of undefined functions
π₯ q/2 and q/3 β the query era
q(XrefServer, Query) -> {ok, Answer} | {error, module(), Reason}
q(XrefServer, Query, Options) ->
{ok, Answer} | {error, module(), Reason}
Types:
XrefServer = xref()
Query = string() | atom()
Options = Option | [Option]
Option = {verbose, boolean()} | verbose
Answer = answer()
Reason = q_rsn()
answer() =
false |
[constant()] |
[(Call :: call()) |
(ComponentCall :: {component(), component()})] |
[Component :: component()] |
integer() >= 0 |
[DefineAt :: define_at()] |
[CallAt :: {funcall(), LineNumbers :: [integer() >= 0]}] |
[AllLines ::
{{define_at(), define_at()},
LineNumbers :: [integer() >= 0]}]
define_at() = {xmfa(), LineNumber :: integer() >= 0}
component() = [constant()]
q_rsn() =
{invalid_options, term()} |
{parse_error, string_position(), term()} |
{type_error, string()} |
{type_mismatch, string(), string()} |
{unknown_analysis, term()} |
{unknown_constant, string()} |
{unknown_variable, variable()} |
{variable_reassigned, string()}
this one evaluates a query in the context of an Xref server and returns the value of the last statement. the syntax of that value depends on the expression, and here's the whole vibe check:
- a set of calls is represented by a sorted list without duplicates of
call() - a set of constants is represented by a sorted list without duplicates of
constant() - a set of strongly connected components is a sorted list without duplicates of
Component - a set of calls between strongly connected components is a sorted list without duplicates of
ComponentCall - a chain of calls is represented by a list of
constant(). the list contains theFromvertex of every call and theTovertex of the last call - the
ofoperator returnsfalseif no chain of calls between the given constants can be found - the value of the closure operator (the digraph representation) is represented by the atom
'closure()' - a set of line numbered functions is represented by a sorted list without duplicates of
DefineAt - a set of line numbered function calls is represented by a sorted list without duplicates of
CallAt - a set of line numbered functions and function calls is represented by a sorted list without duplicates of
AllLines
and for both CallAt and AllLines it holds that for no list element is LineNumbers an empty list β those elements have been removed, bye. the constants of component and the integers of LineNumbers are sorted and without duplicates π
π§Ή remove_application/2 β the cleanup crew
remove_application(XrefServer, Applications) ->
ok | {error, module(), Reason}
Types:
XrefServer = xref()
Applications = application() | [application()]
Reason = {no_such_application, application()}
removes applications and their modules and module data from an Xref server.
π§Ή remove_module/2
remove_module(XrefServer, Modules) ->
ok | {error, module(), Reason}
Types:
XrefServer = xref()
Modules = module() | [module()]
Reason = {no_such_module, module()}
removes analyzed modules and module data from an Xref server.
π§Ή remove_release/2
remove_release(XrefServer, Releases) ->
ok | {error, module(), Reason}
Types:
okay so we were literally mid type-spec and I refuse to leave you hanging, bestie:
XrefServer = xref()
Releases = release() | [release()]
Reason = {no_such_release, release()}
and the vibe? It removes releases and their applications, modules and module data from an Xref server. Clean sweep, no cap. π§Ήβ¨
π
replace_application/3 and replace_application/4
XrefServer = xref()
Application = application()
Directory = directory()
Options = Option | [Option]
Option =
{builtins, boolean()} |
{verbose, boolean()} |
{warnings, boolean()} |
builtins | verbose | warnings
Reason =
{application_clash, {application(), directory(),
directory()}} |
{no_such_application, Application} |
add_dir_rsn()
add_dir_rsn() =
{file_error, file(), file_error()} |
{invalid_filename, term()} |
{invalid_options, term()} |
{unrecognized_file, file()} |
beam_lib:chnk_rsn()
This one replaces the modules of an application with other modules read from an application directory. Release membership of the application is retained. And listen: the name of the application is kept; the name of the given directory is not used. That part is important, iykyk. π«Ά
π¦ replace_module/3 and replace_module/4
XrefServer = xref()
Module = module()
File = file()
Options = Option | [Option]
Option =
{verbose, boolean()} |
{warnings, boolean()} |
verbose | warnings
Reason =
{module_mismatch, Module, ReadModule :: module()} |
{no_such_module, Module} |
add_mod_rsn()
add_mod_rsn() =
{file_error, file(), file_error()} |
{invalid_filename, term()} |
{invalid_options, term()} |
{module_clash, {module(), file(), file()}} |
{no_debug_info, file()} |
beam_lib:chnk_rsn()
Replaces module data of an analyzed module with data read from a BEAM file. Application membership of the module is retained, and so is the value of the builtins option of the module. An error is returned if the name of the read module differs from the given module. The update function is an alternative for updating module data of recompiled modules. Literally so handy. π
πΈ set_default/3 and set_default/2
XrefServer = xref()
OptionValues = OptionValue | [OptionValue]
OptionValue = {Option, Value}
Option = builtins | recurse | verbose | warnings
Value = boolean()
Reason = {invalid_options, term()}
Sets the default value of one or more options. The options that can be set this way are:
builtins, with initial default valuefalse;recurse, with initial default valuefalse;verbose, with initial default valuefalse;warnings, with initial default valuetrue.
The initial default values are set when creating an Xref server. So cute, so organized. π
β set_library_path/2 and set_library_path/3
XrefServer = xref()
LibraryPath = library_path()
Options = Option | [Option]
Option = {verbose, boolean()} | verbose
Reason = {invalid_options, term()} | {invalid_path, term()}
Sets the library path. If the given path is a list of directories, the set of library modules is determined by choosing the first module encountered while traversing the directories in the given order, for those modules that occur in more than one directory. By default, the library path is an empty list.
The library path code_path is used by the functions m/1 and d/1, but can also be set explicitly. Note however that the code path will be traversed once for each used library module while setting up module data. On the other hand, if there are only a few modules that are used but not analyzed, using code_path may be faster than setting the library path to code:get_path().
If the library path is set to code_path, the set of library modules is not determined, and the info functions will return empty lists of library modules. Big βread the fine printβ energy, but make it slay. π
π start/1
NameOrOptions = Name | Options
Name = atom()
Options = Option | [Option]
Option = {xref_mode, mode()} | term()
Creates an Xref server. The process may optionally be given a name. The default mode is functions. Options that are not recognized by Xref are passed on to gen_server:start/4. Periodt. π
π start/2
Name = atom()
Options = Option | [Option]
Option = {xref_mode, mode()} | term()
Creates an Xref server with a given name. The default mode is functions. Options that are not recognized by Xref are passed on to gen_server:start/4. Same energy, now with a name. β¨
π§ stop/1
XrefServer = xref()
Stops an Xref server. Thatβs it. Thatβs the whole function. Goodbye, icon. ππ«Ά
π₯ update/1 and update/2
XrefServer = xref()
Options = Option | [Option]
Option =
{verbose, boolean()} |
{warnings, boolean()} |
verbose | warnings
Modules = [module()]
Reason =
{module_mismatch, module(), ReadModule :: module()} |
add_mod_rsn()
add_mod_rsn() =
{file_error, file(), file_error()} |
{invalid_filename, term()} |
{invalid_options, term()} |
{module_clash, {module(), file(), file()}} |
{no_debug_info, file()} |
beam_lib:chnk_rsn()
Replaces the module data of all analyzed modules the BEAM files of which have been modified since last read by an add function or update. Application membership of the modules is retained, and so is the value of the builtins option. Returns a sorted list of the names of the replaced modules. Main character refresh moment, fr fr. π
π variables/1 and variables/2
XrefServer = xref()
Options = Option | [Option]
Option = predefined | user | {verbose, boolean()} | verbose
VariableInfo =
{predefined, [variable()]} | {user, [variable()]}
Returns a sorted lists of the names of the variables of an Xref server. The default is to return the user variables only. Predefined girlies stay optional unless you ask. ππ
π SEE ALSO π
beam_lib(3erl)digraph(3erl)digraph_utils(3erl)re(3erl)- TOOLS User's Guide
xoxo, your local Unix bestie π β footer shoutout: source/version is Ericsson AB + tools 3.5.3 for xref(3erl), and the date is the one printed in the actual footer on the page β¨
π¦ where this page comes from
- debian bookworm: erlang-manpages 1:25.2.3+dfsg-1+deb12u1 Β· Apache-2.0
- debian bookworm: erlang-manpages 1:25.2.3+dfsg-1+deb12u4 Β· Apache-2.0
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4 Β· Apache-2.0
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4.8 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms