dmd.dtemplate
Defines TemplateDeclaration, TemplateInstance and a few utilities
Discussion
This modules holds the two main template types:
TemplateDeclaration, which is the user-provided declaration of a template,
and TemplateInstance, which is an instance of a TemplateDeclaration
with specific arguments.
Template Parameter:
Additionally, the classes for template parameters are defined in this module.
The base class, TemplateParameter, is inherited by:
TemplateTypeParameterTemplateThisParameterTemplateValueParameterTemplateAliasParameterTemplateTupleParameter
Templates semantic: The start of the template instantiation process looks like this:
- A
TypeInstanceorTypeIdentifieris encountered.TypeInstancehave a bang (e.g.Foo!(arg)) whileTypeIdentifierdon't. - A
TemplateInstanceis instantiated - Semantic is run on the
TemplateInstance(seedmd.dsymbolsem) - The
TemplateInstancesearch for itsTemplateDeclaration, runs semantic on the template arguments and deduce the best match among the possible overloads. - The
TemplateInstancesearch for existing instances with the same arguments, and uses it if found. - Otherwise, the rest of semantic is run on the
TemplateInstance.
License
Source: dtemplate.d
Documentation: https://dlang.org/phobos/dmd_dtemplate.html
-
Declaration
pure nothrow @nogc inout(Expression)isExpression(inout RootObjecto);These functions substitute for dynamic_cast. dynamic_cast does not work on earlier versions of gcc.
-
Declaration
pure nothrow @nogc boolisError(const RootObjecto);Is this Object an error?
-
Declaration
pure nothrow @nogc boolarrayObjectIsError(const Objects*args);Are any of the Objects an error?
-
Declaration
pure nothrow @nogc inout(Type)getType(inout RootObjecto);Try to get arg as a type.
-
Declaration
classTemplateDeclaration: dmd.dsymbol.ScopeDsymbol;[mixin] template Identifier (parameters) [Constraint] https://dlang.org/spec/template.html https://dlang.org/spec/template-mixin.html
-
Declaration
boolisTrivialAliasSeq;matches pattern
template AliasSeq(T...) { alias AliasSeq = T; } -
Declaration
boolisTrivialAlias;matches pattern
template Alias(T) { alias Alias = qualifiers(T); } -
Declaration
booldeprecated_;this template declaration is deprecated
-
Declaration
intinuse;for recursive expansion detection
-
Declaration
booloverloadInsert(Dsymbols);Overload existing TemplateDeclaration 'this' with the new one '
s'. Returntrueif successful; i.e. no conflict. -
Declaration
const const(char)*toCharsNoConstraints();Similar to
toChars, but does not print the template constraints -
Declaration
boolevaluateConstraint(TemplateInstanceti, Scope*sc, Scope*paramscope, Objects*dedargs, FuncDeclarationfd);Check to see if constraint is satisfied.
-
Declaration
const(char)*getConstraintEvalError(ref const(char)*tip);Destructively get the error message from the last constraint evaluation
Parameters
const(char)*tiptipto show after printing all overloads -
Declaration
Scope*scopeForTemplateParameters(TemplateInstanceti, Scope*sc);Create a scope for the parameters of the TemplateInstance
in the parent scopetiscfrom the ScopeDsymbol paramsym.Discussion
If paramsym is
nulla new ScopeDsymbol is used in place of paramsym.Parameters
TemplateInstancetithe TemplateInstance whose parameters to generate the scope for.
Scope*scthe parent scope of
tiReturn Value
a scope for the parameters of
ti -
Declaration
MATCHmatchWithInstance(Scope*sc, TemplateInstanceti, Objects*dedtypes, Expressions*fargs, intflag);Given that
tiis an instance of this TemplateDeclaration, deduce the types of the parameters to this, and store those deduced types indedtypes[].Input:
flag1: don't do semantic() because of dummy types 2: don't change types in matchArg()Output:
dedtypesdeduced arguments Return match level. -
Declaration
MATCHleastAsSpecialized(Scope*sc, TemplateDeclarationtd2, Expressions*fargs);Determine partial specialization order of 'this' vs
td2.Return Value
match this is at least as specialized as
td20td2is more specialized than this -
Declaration
MATCHdeduceFunctionTemplateMatch(TemplateInstanceti, Scope*sc, ref FuncDeclarationfd, Typetthis, Expressions*fargs);Match function arguments against a specific template function.
Input:
tiscinstantiation scopefdtthis'this' argument if !NULLfargsarguments to functionOutput:
fdPartially instantiated function declarationti.tdtypes Expression/Type deduced template argumentsReturn Value
match level bit 0-3 Match template parameters by inferred template arguments bit 4-7 Match template parameters by initial template arguments
-
Declaration
RootObjectdeclareParameter(Scope*sc, TemplateParametertp, RootObjecto);Declare template parameter
tpwith valueo, and install it in the scopesc. -
Declaration
FuncDeclarationdoHeaderInstantiation(TemplateInstanceti, Scope*sc2, FuncDeclarationfd, Typetthis, Expressions*fargs);Limited function template instantiation for using
fd.leastAsSpecialized() -
Declaration
TemplateInstancefindExistingInstance(TemplateInstancetithis, Expressions*fargs);Given a new instance
tithisof this TemplateDeclaration, see if there already exists an instance. If so, return that existing instance. -
Declaration
TemplateInstanceaddInstance(TemplateInstanceti);Add instance
tito TemplateDeclaration's table of instances. Return a handle we can use to later remove it if it fails instantiation. -
Declaration
voidremoveInstance(TemplateInstanceti);Remove TemplateInstance from table of instances.
Input: handle returned by addInstance()
-
Declaration
TemplateTupleParameterisVariadic();Check if the last template parameter is a tuple one, and returns it if so, else returns
null.Return Value
The last template parameter if it's a
TemplateTupleParameter -
Declaration
const boolisOverloadable();We can overload templates.
-
-
Declaration
voidfunctionResolve(ref MatchAccumulatorm, Dsymboldstart, Locloc, Scope*sc, Objects*tiargs, Typetthis, Expressions*fargs, const(char)**pMessage= null);Given function arguments, figure out which template function to expand, and return matching result.
Parameters
MatchAccumulatormmatching result
Dsymboldstartthe root of overloaded function templates
Loclocinstantiation location
Scope*scinstantiation scope
Objects*tiargsinitial list of template arguments
Typetthisif !NULL, the 'this' pointer argument
Expressions*fargsarguments to function
const(char)**pMessageaddress to store error message, or
null -
Declaration
boolreliesOnTident(Typet, TemplateParameters*tparams, size_tiStart= 0);Check whether the type
trepresentation relies on one or more the template parameters.Parameters
TypetTested type, if
null, returnsfalse.TemplateParameters*tparamsTemplate parameters.
size_tiStartStart index of
tparamsto limit the tested parameters. If it's nonzero,tparams[0..iStart] will be excluded from the test target. -
Declaration
abstract classTemplateParameter: dmd.ast_node.ASTNode; -
Declaration
classTemplateTypeParameter: dmd.dtemplate.TemplateParameter;Syntax: ident : specType = defaultType
-
Declaration
classTemplateThisParameter: dmd.dtemplate.TemplateTypeParameter;Syntax: this ident : specType = defaultType
-
Declaration
classTemplateValueParameter: dmd.dtemplate.TemplateParameter;Syntax: valType ident : specValue = defaultValue
-
Declaration
classTemplateAliasParameter: dmd.dtemplate.TemplateParameter;Syntax: specType ident : specAlias = defaultAlias
-
Declaration
classTemplateTupleParameter: dmd.dtemplate.TemplateParameter;Syntax: ident ...
-
Declaration
classTemplateInstance: dmd.dsymbol.ScopeDsymbol;Given: foo!(args) => name = foo tiargs = args
-
Declaration
final const pure nothrow @nogc @property @safe boolsemantictiargsdone();has semanticTiargs() been done?
-
Declaration
final const pure nothrow @nogc @property @safe boolhavetempdecl();if used second constructor
-
Declaration
final const pure nothrow @nogc @property @safe boolgagged();if the instantiation is done with error gagging
-
Declaration
this(ref const Locloc, TemplateDeclarationtd, Objects*tiargs);This constructor is only called when we figured out which function template to instantiate.
-
Declaration
final voidprintInstantiationTrace(Classificationcl= Classification.error);Given an error instantiating the TemplateInstance, give the nested TemplateInstance instantiations that got us here. Those are a list threaded into the nested scopes.
-
Declaration
final IdentifiergetIdent();Lazily generate identifier for template instance. This is because 75% of the ident's are never needed.
-
Declaration
final boolequalsx(TemplateInstanceti);Compare proposed template instantiation with existing template instantiation. Note that this is not commutative because of the auto ref check.
Parameters
TemplateInstancetiexisting template instantiation
Return Value
truefor match -
Declaration
final boolisDiscardable();Return Value
trueif the instances' innards are discardable.
The idea of this function is to see if the template instantiation can be 100% replaced with its eponymous member. All other members can be discarded, even in the compiler to free memory (for example, the template could be expanded in a region allocator, deemed trivial, the end result copied back out independently and the entire region freed), and can be elided entirely from the binary.
The current implementation affects code that generally looks like:
template foo(args...) { some_basic_type_or_string helper() { .... } enum foo = helper(); }
since it was the easiest starting point of implementation but it can and should be expanded more later. -
Declaration
final boolneedsCodegen();Returns
trueif this is not instantiated in non-root module, and is a part of non-speculative instantiatiation.Note: minst does not stabilize until semantic analysis is completed, so don't call this function during semantic analysis to return precise result.
-
Declaration
final boolfindTempDecl(Scope*sc, WithScopeSymbol*pwithsym);Find template declaration corresponding to template instance.
Return Value
falseif finding fails.Note: This function is reentrant against error occurrence. If returns
false, any members of this object won't be modified, and repetition call will reproduce same error. -
Declaration
final boolupdateTempDecl(Scope*sc, Dsymbols);Confirm
sis a valid template, then store it.Input:
scscandidate symbol of template. It may be: TemplateDeclaration FuncDeclaration with findTemplateDeclRoot() != NULL OverloadSet which contains candidatesReturn Value
trueif updating succeeds. -
Declaration
static boolsemanticTiargs(ref const Locloc, Scope*sc, Objects*tiargs, intflags);Run semantic of
tiargsas arguments of template.Input:
locsctiargsarray of template argumentsflags1: replace const variables with their initializers 2: don't devolve Parameter to TypeReturn Value
falseif one or more arguments have errors. -
Declaration
final boolsemanticTiargs(Scope*sc);Run semantic on the elements of tiargs.
Input:
scReturn Value
falseif one or more arguments have errors.Note: This function is reentrant against error occurrence. If returns
false, all elements of tiargs won't be modified. -
Declaration
final boolfindBestMatch(Scope*sc, Expressions*fargs);Find the TemplateDeclaration that matches this TemplateInstance best.
Parameters
Scope*scthe scope this TemplateInstance resides in
Expressions*fargsfunction arguments in case of a template function,
nullotherwiseReturn Value
trueif a match was found,falseotherwise -
Declaration
final boolneedsTypeInference(Scope*sc, intflag= 0);Determine if template instance is really a template function, and that template function needs to infer types from the function arguments.
Discussion
Like findBestMatch, iterate possible template candidates, but just looks only the necessity of type inference.
-
Declaration
final boolhasNestedArgs(Objects*args, boolisstatic);Determines if a TemplateInstance will need a nested generation of the TemplateDeclaration. Sets enclosing property if so, and returns != 0;
-
Declaration
final Dsymbols*appendToModuleMember();Append 'this' to the specific module members[]
-
Declaration
final voiddeclareParameters(Scope*sc);Declare parameters of template instance, initialize them with the template instance arguments.
-
Declaration
final IdentifiergenIdent(Objects*args);This instance needs an identifier for name mangling purposes. Create one by taking the template declaration name and adding the type signature for it.
-
-
Declaration
voidunSpeculative(Scope*sc, RootObjecto);IsExpression can evaluate the specified type speculatively, and even if it instantiates any symbols, they are normally unnecessary for the final executable. However, if those symbols leak to the actual code, compiler should remark them as non-speculative to generate their code and link to the final executable.
-
Declaration
booldefinitelyValueParameter(Expressione);Return
trueifecould be valid only as a template value parameter. Returnfalseif it might be an alias or tuple. (Note that even in this case, it could still turn out to be a value). -
Declaration
classTemplateMixin: dmd.dtemplate.TemplateInstance;Syntax: mixin MixinTemplateName [TemplateArguments]
Identifier; -
Declaration
structTemplateInstanceBox;This struct is needed for TemplateInstance to be the key in an associative array. Fixing https://issues.dlang.org/show_bug.cgi?id=15812 and https://issues.dlang.org/show_bug.cgi?id=15813 would make it unnecessary.
-
Declaration
MATCHmatchArg(TemplateParametertp, LocinstLoc, Scope*sc, Objects*tiargs, size_ti, TemplateParameters*parameters, Objects*dedtypes, Declaration*psparam);Match to a particular TemplateParameter.
Input:
instLoclocation that the template is instantiated.tiargs[] actual arguments to template instanceii'th argumentparameters[] templateparametersdedtypes[] deduced arguments to template instance *psparamset to symbol declared and initialized todedtypes[i] -
Declaration
structTemplateStats;Collect and print statistics on template instantiations.
-
Declaration
static voidincInstance(const TemplateDeclarationtd, const TemplateInstanceti);Add this instance
-
Declaration
static voidincUnique(const TemplateDeclarationtd, const TemplateInstanceti);Add this unique instance
-