Is there any rule to arrange the order of definitions of variables, functions, types, macros in a module?

I just found that a type or macro should be declared before being called, but a function is not. Is it to say that functions can be placed in an arbitrary order confined by the only requirment that they must be placed after the definition of types and macro they depend on?

1 Like

Define macros, types, structs and assign consts before anything else.
Provide @generated functions after everything else (from @Elrod),

You are free apply methods to arguments that specialize the signature, dispatching over your type[s] as you prefer and before your specialization of the method appears. Allowing define-after-use is a useful way to take more control of your source code [reordering it for clarity, simplicity]. define-after-use also works for functions. So one may place the lower-level, more internal supportive functions near the end of the source file, reducing a distraction.

1 Like

I tried to define several macros, types, structs and consts following a depending function in a module, and it turns out that the structs and consts can successfully be called by the function, but the macros and types can not. If this was true, it would mean that macros and types imported from a package can not be redefined to be used by the imported package. I don’t find any explanation about the definition order in the “Modules” introduction of Julia manual. Could you please share some references on it?

I just wrote what I have been doing – no refs, a teaspoon of experience. You should not be redefining macros and types that you import – this could change behavior for someone else (unless, if by redefine, you mean overload with implementations that are specific to your types – that is ok).

Many thanks for your experience sharing! Looking forward to an official thorough explanation of this issue!

Note that @generated functions must also come after functions being called is you want to support disabling compiled modules.
MPI.jl recommended this for a long time.

2 Likes

Note that @generated functions must also come after functions being called is you want to support disabling compiled modules.

Good suggestion!