4801 lines
287 KiB
Plaintext
4801 lines
287 KiB
Plaintext
|
|
<!DOCTYPE html>
|
|
<html lang="en-US">
|
|
<!--
|
|
Copyright (c) 1999-2026 by the D Language Foundation
|
|
All Rights Reserved.
|
|
https://dlang.org/foundation_overview.html
|
|
-->
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="keywords" content="D programming language">
|
|
<meta name="description" content="D Programming Language">
|
|
<title>Functions - D Programming Language</title>
|
|
|
|
<link rel="stylesheet" href="../css/codemirror.css">
|
|
<link rel="stylesheet" href="../css/style.css">
|
|
<link rel="stylesheet" href="../css/print.css" media="print">
|
|
<link rel="shortcut icon" href="../favicon.ico">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.1, maximum-scale=10.0">
|
|
|
|
</head>
|
|
<body id='Functions' class='doc'>
|
|
<script type="text/javascript">document.body.className += ' have-javascript'</script>
|
|
<div id="top"><div class="helper"><div class="helper expand-container"> <div class="logo"><a href=".."><img id="logo" alt="D Logo" src="../images/dlogo.svg"></a></div>
|
|
<a href="../menu.html" title="Menu" class="hamburger expand-toggle"><span>Menu</span></a>
|
|
|
|
<div id="cssmenu"><ul> <li><a href='https://tour.dlang.org'><span>Learn</span></a></li>
|
|
<li class='expand-container'><a class='expand-toggle' href='../documentation.html'><span>Documentation</span></a>
|
|
|
|
<ul class='expand-content'> <li><a href='../spec/spec.html'>Language Reference</a></li>
|
|
<li><a href='../phobos/index.html'>Library Reference</a></li>
|
|
<li><a href='../dmd.html'>Command-line Reference</a></li>
|
|
<li class="menu-divider"><a href='../comparison.html'>Feature Overview</a></li>
|
|
<li><a href='../articles.html'>Articles</a></li>
|
|
</ul></li>
|
|
<li><a href='../download.html'><span>Downloads</span></a></li>
|
|
<li><a href='https://code.dlang.org'><span>Packages</span></a></li>
|
|
<li class='expand-container'><a class='expand-toggle' href='../community.html'><span>Community</span></a>
|
|
|
|
<ul class='expand-content'> <li><a href='https://blog.dlang.org'>Blog</a></li>
|
|
<li><a href='../orgs-using-d.html'>Orgs using D</a></li>
|
|
<li><a href='https://twitter.com/search?q=%23dlang'>Twitter</a></li>
|
|
<li class="menu-divider"><a href='https://discord.gg/bMZk9Q4'>Discord (community-run)</a></li>
|
|
<li><a href='https://forum.dlang.org'>Forums</a></li>
|
|
<li><a href='irc://irc.libera.chat/d'>IRC</a></li>
|
|
<li><a href='https://wiki.dlang.org'>Wiki</a></li>
|
|
<li class="menu-divider"><a href='../bugstats.html'>Issues</a></li>
|
|
<li><a href='../contributing.html'>Contributing</a></li>
|
|
<li class="menu-divider"><a href='../foundation/contributors.html'>Contributors</a></li>
|
|
<li><a href='../foundation/index.html'>Foundation</a></li>
|
|
<li><a href='..//security.html'>Security Team</a></li>
|
|
<li class="menu-divider"><a href='https://store.dlang.org/'>Store</a></li>
|
|
<li><a href='../foundation/donate.html'>Donate</a></li>
|
|
<li><a href='../foundation/sponsors.html'>Sponsors</a></li>
|
|
</ul></li>
|
|
<li class='expand-container'><a class='expand-toggle' href='../resources.html'><span>Resources</span></a>
|
|
|
|
<ul class='expand-content'> <li><a href='https://tour.dlang.org'>Tour</a></li>
|
|
<li><a href='https://wiki.dlang.org/Books'>Books</a></li>
|
|
<li><a href='https://wiki.dlang.org/Tutorials'>Tutorials</a></li>
|
|
<li class="menu-divider"><a href='https://wiki.dlang.org/Development_tools'>Tools</a></li>
|
|
<li><a href='https://wiki.dlang.org/Editors'>Editors</a></li>
|
|
<li><a href='https://wiki.dlang.org/IDEs'>IDEs</a></li>
|
|
<li><a href='https://run.dlang.io'>run.dlang.io</a></li>
|
|
<li><a href='http://rainers.github.io/visuald/visuald/StartPage.html'>Visual D</a></li>
|
|
<li class="menu-divider"><a href='../acknowledgements.html'>Acknowledgments</a></li>
|
|
<li><a href='../dstyle.html'>D Style</a></li>
|
|
<li><a href='../spec/glossary.html'>Glossary</a></li>
|
|
<li><a href='../sitemap.html'>Sitemap</a></li>
|
|
</ul></li>
|
|
</ul></div>
|
|
<div class="search-container expand-container"> <a href="../search.html" class="expand-toggle" title="Search"><span>Search</span></a>
|
|
|
|
<div id="search-box"> <form method="get" action="https://google.com/search">
|
|
<input type="hidden" id="domains" name="domains" value="dlang.org">
|
|
<input type="hidden" id="sourceid" name="sourceid" value="google-search">
|
|
<span id="search-query"><input id="q" name="q" placeholder="Google Search"></span><span id="search-dropdown"><span class="helper"> <select id="sitesearch" name="sitesearch" size="1">
|
|
<option value="dlang.org">Entire Site</option>
|
|
<option selected value="dlang.org/spec">Language</option>
|
|
<option value="dlang.org/phobos">Library</option>
|
|
<option value="forum.dlang.org">Forums</option>
|
|
|
|
</select>
|
|
</span></span><span id="search-submit"><button type="submit"><i class="fa fa-search"></i><span>go</span></button></span>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
</div></div></div>
|
|
|
|
<div class="container">
|
|
<div class="subnav-helper"></div> <div class="subnav"> <div class="head"><h2>Language Reference</h2> <p class="subnav-duplicate"><a href="../spec/spec.html">table of contents</a></p></div>
|
|
<ul> <li><a href=' ../spec/intro.html'>Introduction</a></li><li><a href=' ../spec/lex.html'>Lexical</a></li><li><a href=' ../spec/istring.html'>Interpolation Expression Sequence</a></li><li><a href=' ../spec/grammar.html'>Grammar</a></li><li><a href=' ../spec/module.html'>Modules</a></li><li><a href=' ../spec/declaration.html'>Declarations</a></li><li><a href=' ../spec/type.html'>Types</a></li><li><a href=' ../spec/property.html'>Properties</a></li><li><a href=' ../spec/attribute.html'>Attributes</a></li><li><a href=' ../spec/pragma.html'>Pragmas</a></li><li><a href=' ../spec/expression.html'>Expressions</a></li><li><a href=' ../spec/statement.html'>Statements</a></li><li><a href=' ../spec/arrays.html'>Arrays</a></li><li><a href=' ../spec/hash-map.html'>Associative Arrays</a></li><li><a href=' ../spec/struct.html'>Structs and Unions</a></li><li><a href=' ../spec/class.html'>Classes</a></li><li><a href=' ../spec/interface.html'>Interfaces</a></li><li><a href=' ../spec/enum.html'>Enums</a></li><li><a href=' ../spec/const3.html'>Type Qualifiers</a></li><li><a href=' ../spec/function.html'>Functions</a></li><li><a href=' ../spec/operatoroverloading.html'>Operator Overloading</a></li><li><a href=' ../spec/template.html'>Templates</a></li><li><a href=' ../spec/template-mixin.html'>Template Mixins</a></li><li><a href=' ../spec/contracts.html'>Contract Programming</a></li><li><a href=' ../spec/version.html'>Conditional Compilation</a></li><li><a href=' ../spec/traits.html'>Traits</a></li><li><a href=' ../spec/errors.html'>Error Handling</a></li><li><a href=' ../spec/unittest.html'>Unit Tests</a></li><li><a href=' ../spec/garbage.html'>Garbage Collection</a></li><li><a href=' ../spec/float.html'>Floating Point</a></li><li><a href=' ../spec/iasm.html'>D x86 Inline Assembler</a></li><li><a href=' ../spec/ddoc.html'>Embedded Documentation</a></li><li><a href=' ../spec/interfaceToC.html'>Interfacing to C</a></li><li><a href=' ../spec/cpp_interface.html'>Interfacing to C++</a></li><li><a href=' ../spec/objc_interface.html'>Interfacing to Objective-C</a></li><li><a href=' ../spec/portability.html'>Portability Guide</a></li><li><a href=' ../spec/entity.html'>Named Character Entities</a></li><li><a href=' ../spec/memory-safe-d.html'>Memory Safety</a></li><li><a href=' ../spec/abi.html'>Application Binary Interface</a></li><li><a href=' ../spec/simd.html'>Vector Extensions</a></li><li><a href=' ../spec/betterc.html'>Better C</a></li><li><a href=' ../spec/importc.html'>ImportC</a></li><li><a href=' ../spec/ob.html'>Live Functions</a></li><li><a href=' ../spec/windows.html'>Windows Programming</a></li><li><a href=' ../spec/glossary.html'>Glossary</a></li><li><a href=' ../spec/legacy.html'>Legacy Code</a></li><li><a href=' ../spec/editions.html'>Editions
|
|
</a></li>
|
|
</ul>
|
|
</div>
|
|
<div class="hyphenate" id="content">
|
|
<div id="tools"><div > <div class="tip smallprint"> <a href="https://github.com/dlang/dmd/issues/new?title=%5BFunctions%5D%20&label=Severity:Enhancement">Report a bug</a>
|
|
<div > If you spot a problem with this page, click here to create a GitHub issue.
|
|
</div>
|
|
</div>
|
|
<div class="tip smallprint"> <a href="https://github.com/dlang/dmd/edit/master/spec/function.dd">Improve this page</a>
|
|
<div > Quickly fork, edit online, and submit a pull request for this page.
|
|
Requires a signed-in GitHub account. This works well for small changes.
|
|
If you'd like to make larger changes you may want to consider using
|
|
a local clone.
|
|
</div>
|
|
</div>
|
|
</div></div>
|
|
<h1>Functions</h1>
|
|
|
|
<style> body { counter-reset: h1 20; counter-increment: h1 -1; }
|
|
h1 { counter-reset: h2 h3 p; }
|
|
h2 { counter-reset: h3 h4 p; }
|
|
h3 { counter-reset: h4 p; }
|
|
h4 { counter-reset: p; }
|
|
h1::before {
|
|
counter-increment: h1;
|
|
content: counter(h1) ". ";
|
|
}
|
|
.hyphenate h2::before {
|
|
counter-increment: h2;
|
|
content: counter(h1) "." counter(h2) " ";
|
|
}
|
|
h3::before {
|
|
counter-increment: h3;
|
|
content: counter(h1) "." counter(h2) "." counter(h3) " ";
|
|
}
|
|
h4::before {
|
|
counter-increment: h4;
|
|
content: counter(h1) "." counter(h2) "." counter(h3) "." counter(h4) " ";
|
|
}
|
|
p::before, .spec-boxes::before {
|
|
counter-increment: p;
|
|
content: counter(p) ". ";
|
|
}
|
|
h1::before, h2::before, h3::before, h4::before, p::before, .spec-boxes::before
|
|
{
|
|
color: #999;
|
|
font-size: 80%;
|
|
margin-right: 0.25em;
|
|
}
|
|
</style>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<div class="page-contents quickindex"> <div class="page-contents-header"> <b>Contents</b>
|
|
</div>
|
|
<ol> <li><a href="#grammar">Function Declarations</a><ol> <li><a href="#attributes">Function Attributes</a></li>
|
|
<li><a href="#function-bodies">Function Bodies</a></li>
|
|
<li><a href="#function-declarations">Function Prototypes</a></li>
|
|
</ol></li>
|
|
<li><a href="#contracts">Function Contracts</a><ol> <li><a href="#preconditions">Preconditions</a></li>
|
|
<li><a href="#postconditions">Postconditions</a></li>
|
|
<li><a href="#example-contracts">Example</a></li>
|
|
<li><a href="#in_out_inheritance">In, Out and Inheritance</a></li>
|
|
</ol></li>
|
|
<li><a href="#function-return-values">Function Return Values</a></li>
|
|
<li><a href="#pure-functions">Pure Functions</a><ol> <li><a href="#weak-purity">Strong vs Weak Purity</a></li>
|
|
<li><a href="#pure-special-cases">Special Cases</a></li>
|
|
<li><a href="#pure-nested">Nested Functions</a></li>
|
|
<li><a href="#pure-factory-functions">Pure Factory Functions</a></li>
|
|
<li><a href="#pure-optimization">Optimization</a></li>
|
|
</ol></li>
|
|
<li><a href="#nothrow-functions">Nothrow Functions</a></li>
|
|
<li><a href="#ref-functions">Ref Functions</a></li>
|
|
<li><a href="#auto-functions">Auto Functions</a></li>
|
|
<li><a href="#auto-ref-functions">Auto Ref Functions</a></li>
|
|
<li><a href="#inout-functions">Inout Functions</a></li>
|
|
<li><a href="#optional-parenthesis">Optional Parentheses</a></li>
|
|
<li><a href="#property-functions">Property Functions</a></li>
|
|
<li><a href="#virtual-functions">Virtual Functions</a><ol> <li><a href="#covariance">Covariance</a></li>
|
|
<li><a href="#base-methods">Calling Base Class Methods</a></li>
|
|
<li><a href="#function-inheritance">Overload Sets and Overriding</a></li>
|
|
<li><a href="#override-defaults">Default Values</a></li>
|
|
<li><a href="#inheriting-attributes">Inherited Attributes</a></li>
|
|
<li><a href="#override-restrictions">Restrictions</a></li>
|
|
</ol></li>
|
|
<li><a href="#inline-functions">Inline Functions</a></li>
|
|
<li><a href="#function-overloading">Function Overloading</a><ol> <li><a href="#overload-sets">Overload Sets</a></li>
|
|
</ol></li>
|
|
<li><a href="#parameters">Function Parameters</a><ol> <li><a href="#param-storage">Parameter Storage Classes</a></li>
|
|
<li><a href="#in-params">In Parameters</a></li>
|
|
<li><a href="#ref-params">Ref and Out Parameters</a></li>
|
|
<li><a href="#lazy-params">Lazy Parameters</a></li>
|
|
<li><a href="#function-default-args">Default Arguments</a></li>
|
|
<li><a href="#return-ref-parameters">Return Ref Parameters</a></li>
|
|
<li><a href="#scope-parameters">Scope Parameters</a></li>
|
|
<li><a href="#return-scope-parameters">Return Scope Parameters</a></li>
|
|
<li><a href="#ref-return-scope-parameters">Ref Return Scope Parameters</a></li>
|
|
<li><a href="#pure-scope-inference">Inferred <span class="d_inlinecode donthyphenate notranslate">scope</span> parameters in <span class="d_inlinecode donthyphenate notranslate">pure</span> functions</a></li>
|
|
<li><a href="#udas-parameters">User-Defined Attributes for Parameters</a></li>
|
|
<li><a href="#unpacking-parameters">Unpacking Parameters</a></li>
|
|
<li><a href="#variadic">Variadic Functions</a></li>
|
|
<li><a href="#hidden-parameters">Hidden Parameters</a></li>
|
|
</ol></li>
|
|
<li><a href="#refscopereturn">Ref Scope Return Cases</a><ol> <li><a href="#rsr_definitions">Definitions</a></li>
|
|
<li><a href="#rsr_classification">Classification</a></li>
|
|
<li><a href="#rsr_mapping">Mapping Syntax Onto Classification</a></li>
|
|
<li><a href="#rsr_memberfunctions">Member Functions</a></li>
|
|
<li><a href="#rsr_PandRef">P and ref</a></li>
|
|
<li><a href="#rsr_covariance">Contravariance</a></li>
|
|
</ol></li>
|
|
<li><a href="#local-variables">Local Variables</a><ol> <li><a href="#local-static-variables">Local Static Variables</a></li>
|
|
</ol></li>
|
|
<li><a href="#nested">Nested Functions</a><ol> <li><a href="#nested-qualifiers">Nested Functions with Method Attributes</a></li>
|
|
<li><a href="#nested-declaration-order">Declaration Order</a></li>
|
|
</ol></li>
|
|
<li><a href="#function-pointers-delegates">Function Pointers, Delegates and Closures</a><ol> <li><a href="#function-pointers">Function Pointers</a></li>
|
|
<li><a href="#closures">Delegates & Closures</a></li>
|
|
<li><a href="#method-delegates">Method Delegates</a></li>
|
|
<li><a href="#function-pointer-attributes">Attributes</a></li>
|
|
<li><a href="#function-delegate-init">Initialization</a></li>
|
|
<li><a href="#anonymous">Anonymous Functions and Anonymous Delegates</a></li>
|
|
</ol></li>
|
|
<li><a href="#main"><span class="d_inlinecode donthyphenate notranslate">main()</span> Function</a><ol> <li><a href="#betterc-main"><span class="d_inlinecode donthyphenate notranslate">extern(C) main()</span> Function</a></li>
|
|
</ol></li>
|
|
<li><a href="#function-templates">Function Templates</a></li>
|
|
<li><a href="#interpretation">Compile Time Function Execution (CTFE)</a><ol> <li><a href="#string-mixins">Run Time Values during CTFE</a></li>
|
|
</ol></li>
|
|
<li><a href="#nogc-functions">No-GC Functions</a></li>
|
|
<li><a href="#function-safety">Function Safety</a><ol> <li><a href="#safe-functions">Safe Functions</a></li>
|
|
<li><a href="#trusted-functions">Trusted Functions</a></li>
|
|
<li><a href="#system-functions">System Functions</a></li>
|
|
<li><a href="#safe-interfaces">Safe Interfaces</a></li>
|
|
<li><a href="#safe-values">Safe Values</a></li>
|
|
<li><a href="#null-dereferences">Null Dereferences</a></li>
|
|
<li><a href="#safe-aliasing">Safe Aliasing</a></li>
|
|
</ol></li>
|
|
<li><a href="#function-attribute-inference">Function Attribute Inference</a></li>
|
|
<li><a href="#pseudo-member">Uniform Function Call Syntax (UFCS)</a></li>
|
|
</ol>
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="grammar" href="#grammar">Function Declarations</a></h2>
|
|
<div class="blankline"></div>
|
|
<pre class="bnf notranslate"><a id="FuncDeclaration"><span class="gname">FuncDeclaration</span></a>:
|
|
<a href="../spec/declaration.html#StorageClasses"><i>StorageClasses</i></a><sub>opt</sub> <a href="../spec/type.html#BasicType"><i>BasicType</i></a> <a href="#FuncDeclarator"><i>FuncDeclarator</i></a> <a href="#FunctionBody"><i>FunctionBody</i></a>
|
|
<a href="../spec/declaration.html#StorageClasses"><i>StorageClasses</i></a><sub>opt</sub> <a href="../spec/type.html#BasicType"><i>BasicType</i></a> <a href="#FuncDeclarator"><i>FuncDeclarator</i></a> <a href="#MissingFunctionBody"><i>MissingFunctionBody</i></a>
|
|
<a href="#AutoFuncDeclaration"><i>AutoFuncDeclaration</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="AutoFuncDeclaration"><span class="gname">AutoFuncDeclaration</span></a>:
|
|
<a href="../spec/declaration.html#StorageClasses"><i>StorageClasses</i></a> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a> <a href="#FuncDeclaratorSuffix"><i>FuncDeclaratorSuffix</i></a> <a href="#FunctionBody"><i>FunctionBody</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="FuncDeclarator"><span class="gname">FuncDeclarator</span></a>:
|
|
<a href="../spec/type.html#TypeSuffixes"><i>TypeSuffixes</i></a><sub>opt</sub> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a> <a href="#FuncDeclaratorSuffix"><i>FuncDeclaratorSuffix</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="FuncDeclaratorSuffix"><span class="gname">FuncDeclaratorSuffix</span></a>:
|
|
<a href="#Parameters"><i>Parameters</i></a> <a href="#MemberFunctionAttributes"><i>MemberFunctionAttributes</i></a><sub>opt</sub>
|
|
<a href="../spec/template.html#TemplateParameters"><i>TemplateParameters</i></a> <a href="#Parameters"><i>Parameters</i></a> <a href="#MemberFunctionAttributes"><i>MemberFunctionAttributes</i></a><sub>opt</sub> <a href="../spec/template.html#Constraint"><i>Constraint</i></a><sub>opt</sub>
|
|
</pre>
|
|
|
|
<ul><li>A <em>FuncDeclaration</em> with a function body is called a
|
|
<a href="#function-bodies">function definition</a>.</li>
|
|
<li>A <em>FuncDeclaration</em> without a function body is called a
|
|
<a href="#function-declarations">function prototype</a>.</li>
|
|
<li>A <em>FuncDeclaration</em> with <em>TemplateParameters</em> defines a
|
|
<a href="../spec/template.html#function-templates">function template</a>.
|
|
<div class="blankline"></div>
|
|
</li>
|
|
</ul>
|
|
<h3>Function Parameters</h3>
|
|
<div class="blankline"></div>
|
|
<pre class="bnf notranslate"><a id="Parameters"><span class="gname">Parameters</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">(</span> <a href="#ParameterList"><i>ParameterList</i></a><sub>opt</sub> <span class="d_inlinecode donthyphenate notranslate">)</span>
|
|
<div class="blankline"></div>
|
|
<a id="ParameterList"><span class="gname">ParameterList</span></a>:
|
|
<a href="#Parameter"><i>Parameter</i></a>
|
|
<a href="#Parameter"><i>Parameter</i></a> <span class="d_inlinecode donthyphenate notranslate">,</span> <i>ParameterList</i><sub>opt</sub>
|
|
<a href="#VariadicArgumentsAttributes"><i>VariadicArgumentsAttributes</i></a><sub>opt</sub> <span class="d_inlinecode donthyphenate notranslate">...</span>
|
|
<div class="blankline"></div>
|
|
<a id="Parameter"><span class="gname">Parameter</span></a>:
|
|
<a href="#ParameterDeclaration"><i>ParameterDeclaration</i></a>
|
|
<a href="#ParameterDeclaration"><i>ParameterDeclaration</i></a> <span class="d_inlinecode donthyphenate notranslate">...</span>
|
|
<a href="#ParameterDeclaration"><i>ParameterDeclaration</i></a> <span class="d_inlinecode donthyphenate notranslate">=</span> <a href="../spec/expression.html#AssignExpression"><i>AssignExpression</i></a>
|
|
<a href="#ParameterDeclaration"><i>ParameterDeclaration</i></a> <span class="d_inlinecode donthyphenate notranslate">=</span> <a href="../spec/expression.html#AssignExpression"><i>AssignExpression</i></a> <span class="d_inlinecode donthyphenate notranslate">...</span>
|
|
<a href="#ParameterAttributes"><i>ParameterAttributes</i></a><sub>opt</sub> <a href="#ParameterTuplePattern"><i>ParameterTuplePattern</i></a>
|
|
<a href="#ParameterAttributes"><i>ParameterAttributes</i></a><sub>opt</sub> <a href="#ParameterTuplePattern"><i>ParameterTuplePattern</i></a> = <a href="../spec/expression.html#AssignExpression"><i>AssignExpression</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="ParameterDeclaration"><span class="gname">ParameterDeclaration</span></a>:
|
|
<a href="#ParameterAttributes"><i>ParameterAttributes</i></a><sub>opt</sub> <a href="../spec/type.html#BasicType"><i>BasicType</i></a> <a href="../spec/declaration.html#Declarator"><i>Declarator</i></a>
|
|
<a href="#ParameterAttributes"><i>ParameterAttributes</i></a><sub>opt</sub> <a href="../spec/type.html#Type"><i>Type</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="ParameterAttributes"><span class="gname">ParameterAttributes</span></a>:
|
|
<a href="#ParameterStorageClass"><i>ParameterStorageClass</i></a>
|
|
<a href="../spec/attribute.html#UserDefinedAttribute"><i>UserDefinedAttribute</i></a>
|
|
<i>ParameterAttributes</i> <a href="#ParameterStorageClass"><i>ParameterStorageClass</i></a>
|
|
<i>ParameterAttributes</i> <a href="../spec/attribute.html#UserDefinedAttribute"><i>UserDefinedAttribute</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="ParameterStorageClass"><span class="gname">ParameterStorageClass</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">auto</span>
|
|
<a href="../spec/type.html#TypeCtor"><i>TypeCtor</i></a>
|
|
<span class="d_inlinecode donthyphenate notranslate">final</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">in</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">lazy</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">out</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">ref</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">return</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">scope</span>
|
|
<div class="blankline"></div>
|
|
<a id="VariadicArgumentsAttributes"><span class="gname">VariadicArgumentsAttributes</span></a>:
|
|
<a href="#VariadicArgumentsAttribute"><i>VariadicArgumentsAttribute</i></a>
|
|
<a href="#VariadicArgumentsAttribute"><i>VariadicArgumentsAttribute</i></a> <i>VariadicArgumentsAttributes</i>
|
|
<div class="blankline"></div>
|
|
<a id="VariadicArgumentsAttribute"><span class="gname">VariadicArgumentsAttribute</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">const</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">immutable</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">return</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">scope</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">shared</span>
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> In D2, declaring a parameter <span class="d_inlinecode donthyphenate notranslate">final</span> is a semantic error, but not a parse error.</div>
|
|
<div class="blankline"></div>
|
|
<p>See also: <a href="#param-storage">parameter storage classes</a>.</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="attributes" href="#attributes">Function Attributes</a></h3>
|
|
<div class="blankline"></div>
|
|
<pre class="bnf notranslate"><a id="FunctionAttributes"><span class="gname">FunctionAttributes</span></a>:
|
|
<a href="#FunctionAttribute"><i>FunctionAttribute</i></a>
|
|
<a href="#FunctionAttribute"><i>FunctionAttribute</i></a> <i>FunctionAttributes</i>
|
|
<div class="blankline"></div>
|
|
<a id="FunctionAttribute"><span class="gname">FunctionAttribute</span></a>:
|
|
<a href="../spec/attribute.html#FunctionAttributeKwd"><i>FunctionAttributeKwd</i></a>
|
|
<a href="../spec/attribute.html#Property"><i>Property</i></a>
|
|
<a href="../spec/attribute.html#AtAttribute"><i>AtAttribute</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="MemberFunctionAttributes"><span class="gname">MemberFunctionAttributes</span></a>:
|
|
<a href="#MemberFunctionAttribute"><i>MemberFunctionAttribute</i></a>
|
|
<a href="#MemberFunctionAttribute"><i>MemberFunctionAttribute</i></a> <i>MemberFunctionAttributes</i>
|
|
<div class="blankline"></div>
|
|
<a id="MemberFunctionAttribute"><span class="gname">MemberFunctionAttribute</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">const</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">immutable</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">inout</span>
|
|
<a href="#struct-return-methods"><span class="d_inlinecode donthyphenate notranslate">return</span></a> <span class="d_inlinecode donthyphenate notranslate">ref</span><sub>opt</sub>
|
|
<span class="d_inlinecode donthyphenate notranslate">scope</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">shared</span>
|
|
<a href="#FunctionAttribute"><i>FunctionAttribute</i></a>
|
|
</pre>
|
|
<p><em>FunctionAttributes</em> come after function parameters in a <a href="#FuncDeclaration"><i>FuncDeclaration</i></a>
|
|
or <a href="#function-pointer-attributes">function pointer</a>, unlike
|
|
<a href="../spec/attribute.html#Attribute"><i>Attribute</i></a>s which precede a declaration.</p>
|
|
<div class="blankline"></div>
|
|
<p>A <a href="../spec/struct.html#constructor-attributes">constructor</a>,
|
|
<a href="../spec/struct.html#member-functions">member function</a>,
|
|
<a href="../spec/type.html#delegates">delegate</a> or
|
|
<a href="#nested-qualifiers">nested function</a> can have <em>MemberFunctionAttributes</em>,
|
|
which extends <em>FunctionAttributes</em>.</p>
|
|
|
|
<ul><li>Many function/method attributes are valid <a href="../spec/attribute.html#Attribute"> declaration attributes</a>. Note that the different attribute positions have different
|
|
meanings for a <a href="../spec/type.html#TypeCtor"><i>TypeCtor</i></a> attribute - see
|
|
<a href="../spec/declaration.html#methods-returning-qualified"> Methods Returning a Qualified Type</a>.</li>
|
|
<li>Some function attributes <a href="#function-attribute-inference">can be inferred</a>.</li>
|
|
<li>Some function attribute checks are turned off inside a
|
|
<a href="../spec/version.html#DebugStatement"><span class="d_inlinecode donthyphenate notranslate">debug</span> statement</a>.
|
|
</li>
|
|
</ul>
|
|
<p>See also:</p>
|
|
|
|
<ul><li><a href="../spec/attribute.html#function-attributes">Function Attributes</a></li>
|
|
<li><a href="../spec/attribute.html#class-attributes">OOP Attributes</a>
|
|
</li>
|
|
</ul>
|
|
<h3><a class="anchor" title="Permalink to this section" id="function-bodies" href="#function-bodies">Function Bodies</a></h3>
|
|
<div class="blankline"></div>
|
|
<pre class="bnf notranslate"><a id="FunctionBody"><span class="gname">FunctionBody</span></a>:
|
|
<a href="#SpecifiedFunctionBody"><i>SpecifiedFunctionBody</i></a>
|
|
<a href="#ShortenedFunctionBody"><i>ShortenedFunctionBody</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="SpecifiedFunctionBody"><span class="gname">SpecifiedFunctionBody</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">do</span><sub>opt</sub> <a href="../spec/statement.html#BlockStatement"><i>BlockStatement</i></a>
|
|
<a href="#FunctionContracts"><i>FunctionContracts</i></a><sub>opt</sub> <a href="#InOutContractExpression"><i>InOutContractExpression</i></a> <span class="d_inlinecode donthyphenate notranslate">do</span><sub>opt</sub> <a href="../spec/statement.html#BlockStatement"><i>BlockStatement</i></a>
|
|
<a href="#FunctionContracts"><i>FunctionContracts</i></a><sub>opt</sub> <a href="#InOutStatement"><i>InOutStatement</i></a> <span class="d_inlinecode donthyphenate notranslate">do</span> <a href="../spec/statement.html#BlockStatement"><i>BlockStatement</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="ShortenedFunctionBody"><span class="gname">ShortenedFunctionBody</span></a>:
|
|
<a href="#InOutContractExpressions"><i>InOutContractExpressions</i></a><sub>opt</sub> <span class="d_inlinecode donthyphenate notranslate">=></span> <a href="../spec/expression.html#AssignExpression"><i>AssignExpression</i></a> <span class="d_inlinecode donthyphenate notranslate">;</span>
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Examples:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> hasSpecifiedBody() { <span class="d_keyword">return</span> 1; }
|
|
<span class="d_keyword">int</span> hasShortenedBody() => 1; <span class="d_comment">// equivalent
|
|
</span></pre>
|
|
<div class="blankline"></div>
|
|
<span id="FunctionLiteralBody"><a class="anchor" title="Permalink to this section" id="" href="#"></a></span>
|
|
<p>The <em>ShortenedFunctionBody</em> form implies a
|
|
<a href="../spec/statement.html#ReturnStatement">return statement</a>.
|
|
This syntax also applies for <a href="../spec/expression.html#function_literals">function literals</a>.</p>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="function-declarations" href="#function-declarations">Function Prototypes</a></h3>
|
|
<div class="blankline"></div>
|
|
<pre class="bnf notranslate"><a id="MissingFunctionBody"><span class="gname">MissingFunctionBody</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">;</span>
|
|
<a href="#FunctionContracts"><i>FunctionContracts</i></a><sub>opt</sub> <a href="#InOutContractExpression"><i>InOutContractExpression</i></a> <span class="d_inlinecode donthyphenate notranslate">;</span>
|
|
<a href="#FunctionContracts"><i>FunctionContracts</i></a><sub>opt</sub> <a href="#InOutStatement"><i>InOutStatement</i></a>
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Function declarations with a <em>MissingFunctionBody</em>, e.g.:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> foo();
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>that are not declared as <a href="../spec/class.html#abstract"><span class="d_inlinecode donthyphenate notranslate">abstract</span></a>
|
|
are expected to have their implementations
|
|
elsewhere, and that implementation will be provided at the link step.
|
|
This enables an implementation of a function to be completely hidden from the user
|
|
of it, and the implementation may be in another language such as C, assembler, etc.
|
|
Typically a function prototype would have non-<span class="d_inlinecode donthyphenate notranslate">extern(D)</span>
|
|
<a href="../spec/attribute.html#linkage">linkage</a>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>A function prototype can have <span class="d_inlinecode donthyphenate notranslate">extern(D)</span> linkage.
|
|
This is useful for <a href="../dmd.html#interface-files">D interface files</a>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="contracts" href="#contracts">Function Contracts</a></h2>
|
|
<div class="blankline"></div>
|
|
<pre class="bnf notranslate"><a id="FunctionContracts"><span class="gname">FunctionContracts</span></a>:
|
|
<a href="#FunctionContract"><i>FunctionContract</i></a>
|
|
<a href="#FunctionContract"><i>FunctionContract</i></a> <i>FunctionContracts</i>
|
|
<div class="blankline"></div>
|
|
<a id="FunctionContract"><span class="gname">FunctionContract</span></a>:
|
|
<a href="#InOutContractExpression"><i>InOutContractExpression</i></a>
|
|
<a href="#InOutStatement"><i>InOutStatement</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="InOutContractExpressions"><span class="gname">InOutContractExpressions</span></a>:
|
|
<a href="#InOutContractExpression"><i>InOutContractExpression</i></a>
|
|
<a href="#InOutContractExpression"><i>InOutContractExpression</i></a> <i>InOutContractExpressions</i>
|
|
<div class="blankline"></div>
|
|
<a id="InOutContractExpression"><span class="gname">InOutContractExpression</span></a>:
|
|
<a href="#InContractExpression"><i>InContractExpression</i></a>
|
|
<a href="#OutContractExpression"><i>OutContractExpression</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="InOutStatement"><span class="gname">InOutStatement</span></a>:
|
|
<a href="#InStatement"><i>InStatement</i></a>
|
|
<a href="#OutStatement"><i>OutStatement</i></a>
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Function Contracts specify the preconditions and postconditions of a function.
|
|
They are used in <a href="contracts.html">Contract Programming</a>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Preconditions and postconditions do not affect the type of the function.</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="preconditions" href="#preconditions">Preconditions</a></h3>
|
|
<div class="blankline"></div>
|
|
<pre class="bnf notranslate"><a id="InContractExpression"><span class="gname">InContractExpression</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">in (</span> <a href="../spec/expression.html#AssertArguments"><i>AssertArguments</i></a> <span class="d_inlinecode donthyphenate notranslate">)</span>
|
|
<div class="blankline"></div>
|
|
<a id="InStatement"><span class="gname">InStatement</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">in</span> <a href="../spec/statement.html#BlockStatement"><i>BlockStatement</i></a>
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>An <i>InContractExpression</i> is a precondition.</p>
|
|
|
|
<ul><li>The first <a href="../spec/expression.html#AssignExpression"><i>AssignExpression</i></a> of the <i>AssertArguments</i>
|
|
must evaluate to true. If it does not, the precondition has failed.</li>
|
|
</ul>
|
|
|
|
<ul><li>The second <i>AssignExpression</i>, if present, must be implicitly convertible to type <span class="d_inlinecode donthyphenate notranslate">const(char)[]</span>.
|
|
</li>
|
|
</ul>
|
|
<p>An <a href="#InStatement"><i>InStatement</i></a> is also a precondition. Any <a href="../spec/expression.html#AssertExpression"><i>AssertExpression</i></a> appearing
|
|
in an <i>InStatement</i> will be an <i>InContractExpression</i>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Preconditions must semantically be satisfied before the function starts executing.
|
|
If a precondition fails, the program enters an <i>Invalid State</i>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> Whether the preconditions are actually run or not is implementation defined.
|
|
This is usually selectable with a compiler switch.
|
|
Its behavior upon precondition failure is also usually selectable with a compiler switch.
|
|
One option is to throw an <span class="d_inlinecode donthyphenate notranslate">AssertError</span> with a message consisting of the optional second
|
|
<i>AssignExpression</i>.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> Use preconditions to validate that input arguments have values that are
|
|
expected by the function.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> Since preconditions may or may not be actually checked at runtime, avoid
|
|
using preconditions that have side effects.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<p>The expression form is:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">in</span> (expression)
|
|
<span class="d_keyword">in</span> (expression, <span class="d_string">"failure string"</span>)
|
|
{
|
|
...<span class="d_keyword">function</span> body...
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>The block statement form is:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">in</span>
|
|
{
|
|
...contract preconditions...
|
|
}
|
|
<span class="d_keyword">do</span>
|
|
{
|
|
...<span class="d_keyword">function</span> body...
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="postconditions" href="#postconditions">Postconditions</a></h3>
|
|
<div class="blankline"></div>
|
|
<pre class="bnf notranslate"><a id="OutContractExpression"><span class="gname">OutContractExpression</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">out ( ;</span> <a href="../spec/expression.html#AssertArguments"><i>AssertArguments</i></a> <span class="d_inlinecode donthyphenate notranslate">)</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">out (</span> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a> <span class="d_inlinecode donthyphenate notranslate">;</span> <a href="../spec/expression.html#AssertArguments"><i>AssertArguments</i></a> <span class="d_inlinecode donthyphenate notranslate">)</span>
|
|
<div class="blankline"></div>
|
|
<a id="OutStatement"><span class="gname">OutStatement</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">out</span> <a href="../spec/statement.html#BlockStatement"><i>BlockStatement</i></a>
|
|
<span class="d_inlinecode donthyphenate notranslate">out</span> <span class="d_inlinecode donthyphenate notranslate">(</span> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a> <span class="d_inlinecode donthyphenate notranslate">)</span> <a href="../spec/statement.html#BlockStatement"><i>BlockStatement</i></a>
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>An <i>OutContractExpression</i> is a postcondition.</p>
|
|
|
|
<ul><li>The first <a href="../spec/expression.html#AssignExpression"><i>AssignExpression</i></a> of the <i>AssertArguments</i>
|
|
must evaluate to true. If it does not, the postcondition has failed.
|
|
</li>
|
|
<li>The second <i>AssignExpression</i>, if present, must be implicitly convertible to type <span class="d_inlinecode donthyphenate notranslate">const(char)[]</span>.
|
|
</li>
|
|
</ul>
|
|
<p>An <i>OutStatement</i> is also a postcondition. Any <a href="../spec/expression.html#AssertExpression"><i>AssertExpression</i></a> appearing
|
|
in an <i>OutStatement</i> will be an <i>OutContractExpression</i>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Postconditions must semantically be satisfied after the function finishes executing.
|
|
If a postcondition fails, the program enters an <i>Invalid State</i>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> Whether the postconditions are actually run or not is implementation defined.
|
|
This is usually selectable with a compiler switch.
|
|
Its behavior upon postcondition failure is also usually selectable with a compiler switch.
|
|
One option is to throw an <span class="d_inlinecode donthyphenate notranslate">AssertError</span> with a message consisting of the optional second
|
|
<i>AssignExpression</i>.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> Use postconditions to validate that on leaving the function:</div>
|
|
|
|
|
|
<ul><li>Any mutable input arguments each have the expected value/range of values.</li>
|
|
<li>Any return value has a correct value/range of values.
|
|
</li>
|
|
</ul>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> Since postconditions may or may not be actually checked at runtime, avoid
|
|
using postconditions that have side effects.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<p>The expression form is:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">out</span> (identifier; expression)
|
|
<span class="d_keyword">out</span> (identifier; expression, <span class="d_string">"failure string"</span>)
|
|
<span class="d_keyword">out</span> (; expression)
|
|
<span class="d_keyword">out</span> (; expression, <span class="d_string">"failure string"</span>)
|
|
{
|
|
...<span class="d_keyword">function</span> body...
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>The block statement form is:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">out</span>
|
|
{
|
|
...contract postconditions...
|
|
}
|
|
<span class="d_keyword">out</span> (identifier)
|
|
{
|
|
...contract postconditions...
|
|
}
|
|
<span class="d_keyword">do</span>
|
|
{
|
|
...<span class="d_keyword">function</span> body...
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>The optional identifier in either type of postcondition is set to the return value
|
|
of the function, and can be accessed from within the postcondition.
|
|
It is implicitly <span class="d_inlinecode donthyphenate notranslate">const</span>.</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="example-contracts" href="#example-contracts">Example</a></h3>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> fun(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> a, <span class="d_keyword">int</span> b)
|
|
<span class="d_keyword">in</span> (a > 0)
|
|
<span class="d_keyword">in</span> (b >= 0, <span class="d_string">"b cannot be negative!"</span>)
|
|
<span class="d_keyword">out</span> (r; r > 0, <span class="d_string">"return must be positive"</span>)
|
|
<span class="d_keyword">out</span> (; a != 0)
|
|
{
|
|
<span class="d_comment">// function body
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> fun(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> a, <span class="d_keyword">int</span> b)
|
|
<span class="d_keyword">in</span>
|
|
{
|
|
<span class="d_keyword">assert</span>(a > 0);
|
|
<span class="d_keyword">assert</span>(b >= 0, <span class="d_string">"b cannot be negative!"</span>);
|
|
}
|
|
<span class="d_keyword">out</span> (r)
|
|
{
|
|
<span class="d_keyword">assert</span>(r > 0, <span class="d_string">"return must be positive"</span>);
|
|
<span class="d_keyword">assert</span>(a != 0);
|
|
}
|
|
<span class="d_keyword">do</span>
|
|
{
|
|
<span class="d_comment">// function body
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>The two functions are identical semantically.</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="in_out_inheritance" href="#in_out_inheritance">In, Out and Inheritance</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>If a function in a derived class overrides a function from its
|
|
super class, then only the preconditions of one of the
|
|
function and its overridden functions
|
|
must be satisfied.
|
|
Overriding
|
|
functions then becomes a process of <i>loosening</i> the preconditions.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> B
|
|
{
|
|
<span class="d_keyword">int</span> i;
|
|
|
|
<span class="d_keyword">int</span> f() <span class="d_keyword">in</span> (i == 5) => 5;
|
|
}
|
|
<span class="d_keyword">class</span> C : B
|
|
{
|
|
<span class="d_keyword">override</span> <span class="d_keyword">int</span> f() => i; <span class="d_comment">// no `in` contract, `i` can have any value
|
|
</span>}
|
|
|
|
B b = <span class="d_keyword">new</span> B;
|
|
<span class="d_keyword">assert</span>(b.i == 0);
|
|
<span class="d_comment">//b.f(); // AssertError, `i == 5` failed
|
|
</span>
|
|
b = <span class="d_keyword">new</span> C;
|
|
<span class="d_keyword">assert</span>(b.f() == 0); <span class="d_comment">// OK
|
|
</span></pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>A function without preconditions means its precondition is always
|
|
satisfied.
|
|
Therefore if any
|
|
function in an inheritance hierarchy has no preconditions,
|
|
then any preconditions on functions overriding it have no meaningful
|
|
effect.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> C : Object
|
|
{
|
|
<span class="d_keyword">int</span> x;
|
|
|
|
<span class="d_keyword">override</span> string toString()
|
|
<span class="d_keyword">in</span> (x > 0) <span class="d_comment">// Error, Object.toString has no `in` contract
|
|
</span> {
|
|
<span class="d_keyword">return</span> <span class="d_string">""</span>;
|
|
}
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>Conversely, all the postconditions of the function and its
|
|
overridden functions must be satisfied.
|
|
Overriding functions then becomes a process of <i>tightening</i> the
|
|
postconditions.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> B
|
|
{
|
|
<span class="d_keyword">int</span> i;
|
|
|
|
<span class="d_keyword">int</span> f() <span class="d_keyword">out</span> (; i > 5) => i;
|
|
}
|
|
<span class="d_keyword">class</span> C : B
|
|
{
|
|
<span class="d_keyword">override</span> <span class="d_keyword">int</span> f() <span class="d_keyword">out</span> (; i < 10) => i;
|
|
}
|
|
|
|
B b = <span class="d_keyword">new</span> C;
|
|
b.f(); <span class="d_comment">// AssertError, `i > 5` failed
|
|
</span>b.i = 10;
|
|
b.f(); <span class="d_comment">// AssertError, `i < 10` failed
|
|
</span></pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="function-return-values" href="#function-return-values">Function Return Values</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>One <a href="../spec/statement.html#return-statement">return statement</a> per execution path
|
|
is required if the function specifies a return type that is not <span class="d_inlinecode donthyphenate notranslate">void</span>,
|
|
unless:</p>
|
|
<ul> <li>the path executes an infinite loop</li>
|
|
<li>the path evaluates an <a href="../spec/expression.html#assert-ct"> <span class="d_inlinecode donthyphenate notranslate">assert(0)</span> expression</a></li>
|
|
<li>the path evaluates an expression of type
|
|
<a href="../spec/type.html#noreturn"><span class="d_inlinecode donthyphenate notranslate">noreturn</span></a></li>
|
|
<li>the path contains inline assembler code</li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<p>Simple forms of the first 3 cases above can be recognized by the compiler,
|
|
but not all.</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> error(<span class="d_keyword">int</span> i)
|
|
{
|
|
<span class="d_keyword">if</span> (i & 1)
|
|
i++;
|
|
<span class="d_keyword">else</span>
|
|
<span class="d_keyword">return</span> i;
|
|
|
|
<span class="d_comment">// Error: no return statement
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> f(<span class="d_keyword">int</span> i)
|
|
{
|
|
<span class="d_keyword">if</span> (i >= 0)
|
|
<span class="d_keyword">return</span> i;
|
|
|
|
<span class="d_keyword">assert</span>(0);
|
|
<span class="d_comment">// OK, no return needed
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<p>Function return values not marked as <a href="#ref-functions"><span class="d_inlinecode donthyphenate notranslate">ref</span></a>
|
|
are considered to be rvalues by the calling function.
|
|
This means they cannot be passed by reference to other functions.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="pure-functions" href="#pure-functions">Pure Functions</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>Pure functions are annotated with the <span class="d_inlinecode donthyphenate notranslate">pure</span> attribute.
|
|
Pure functions cannot directly access global or static
|
|
mutable state.
|
|
Pure functions can only call pure functions.</p>
|
|
<div class="blankline"></div>
|
|
<p>Pure functions can:</p>
|
|
<ul> <li>Modify the local state of the function.</li>
|
|
<li>Throw exceptions.</li>
|
|
</ul>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> x;
|
|
<span class="d_keyword">immutable</span> <span class="d_keyword">int</span> y;
|
|
|
|
<span class="d_keyword">pure</span> <span class="d_keyword">int</span> foo(<span class="d_keyword">int</span> i)
|
|
{
|
|
i++; <span class="d_comment">// ok, modifying local state
|
|
</span> <span class="d_comment">//x = i; // error, modifying global state
|
|
</span> <span class="d_comment">//i = x; // error, reading mutable global state
|
|
</span> i = y; <span class="d_comment">// ok, reading immutable global state
|
|
</span> <span class="d_keyword">throw</span> <span class="d_keyword">new</span> Exception(<span class="d_string">"failed"</span>); <span class="d_comment">// ok
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>A pure function can override an impure function,
|
|
but cannot be overridden by an impure function.
|
|
I.e. it is <a href="../spec/type.html#covariance">covariant</a> with an impure function.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="weak-purity" href="#weak-purity">Strong vs Weak Purity</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>A <i>weakly pure function</i> has parameters with mutable indirections.
|
|
Program state can be modified transitively through the matching
|
|
argument.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">pure</span> size_t foo(<span class="d_keyword">int</span>[] arr)
|
|
{
|
|
arr[] += 1;
|
|
<span class="d_keyword">return</span> arr.length;
|
|
}
|
|
<span class="d_keyword">int</span>[] a = [1, 2, 3];
|
|
foo(a);
|
|
<span class="d_keyword">assert</span>(a == [2, 3, 4]);
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>A <i>strongly pure function</i> has no parameters with mutable indirections
|
|
and cannot modify any program state external to the function.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> S { <span class="d_keyword">double</span> x; }
|
|
|
|
<span class="d_keyword">pure</span> size_t foo(<span class="d_keyword">immutable</span>(<span class="d_keyword">int</span>)[] arr, <span class="d_keyword">int</span> num, S val)
|
|
{
|
|
<span class="d_comment">//arr[num] = 1; // compile error
|
|
</span> num = 2; <span class="d_comment">// has no side effect on the caller side
|
|
</span> val.x = 3.14; <span class="d_comment">// ditto
|
|
</span> <span class="d_keyword">return</span> arr.length;
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>A strongly pure function can call a weakly pure function.</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="pure-special-cases" href="#pure-special-cases">Special Cases</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>A pure function can:</p>
|
|
<div class="blankline"></div>
|
|
<ul> <li>read and write the floating point exception flags</li>
|
|
<li>read and write the floating point mode flags, as long as those
|
|
flags are restored to their initial state upon function entry</li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes undefined-behavior"><b>Undefined Behavior:</b> occurs if these flags are not restored to their
|
|
initial state upon function exit. It is the programmer's responsibility
|
|
to ensure this. Setting these flags is not allowed in <span class="d_inlinecode donthyphenate notranslate">@safe</span> code.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<h4><a class="anchor" title="Permalink to this section" id="pure-debug" href="#pure-debug">Debugging</a></h4>
|
|
<div class="blankline"></div>
|
|
<p>A pure function can perform impure operations in statements that are in a
|
|
<a href="../spec/version.html#ConditionalStatement"><i>ConditionalStatement</i></a>
|
|
controlled by a <a href="../spec/version.html#DebugCondition"><i>DebugCondition</i></a>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> this relaxation of purity checks in <em>DebugCondition</em>s is
|
|
intended solely to make debugging programs easier.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">pure</span> <span class="d_keyword">int</span> foo(<span class="d_keyword">int</span> i)
|
|
{
|
|
<span class="d_keyword">debug</span> writeln(<span class="d_string">"i = "</span>, i); <span class="d_comment">// ok, impure code allowed in debug statement
|
|
</span> ...
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="pure-nested" href="#pure-nested">Nested Functions</a></h3>
|
|
<div class="blankline"></div>
|
|
<p><a href="#nested">Nested functions</a> inside a pure function are implicitly marked as pure.</p>
|
|
<div class="blankline"></div>
|
|
<p>A non-static pure nested function can access (and sometimes mutate) data
|
|
through its context pointer:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">pure</span> <span class="d_keyword">int</span> foo()
|
|
{
|
|
<span class="d_keyword">int</span> x = 5;
|
|
|
|
<span class="d_keyword">int</span> bar()
|
|
<span class="d_comment">// implicitly marked as pure, to be "weakly pure"
|
|
</span> <span class="d_comment">// since hidden context pointer to foo stack context is mutable
|
|
</span> {
|
|
x = 10; <span class="d_comment">// can access states in enclosing scope
|
|
</span> <span class="d_comment">// through the mutable context pointer
|
|
</span> <span class="d_keyword">return</span> x;
|
|
}
|
|
<span class="d_keyword">pragma</span>(msg, <span class="d_keyword">typeof</span>(&bar)); <span class="d_comment">// int delegate() pure
|
|
</span>
|
|
bar();
|
|
<span class="d_keyword">return</span> x;
|
|
}
|
|
|
|
<span class="d_keyword">static</span> <span class="d_keyword">assert</span>(foo() == 10);
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> <a href="#nested-qualifiers">Qualifying</a> a nested function
|
|
as <span class="d_inlinecode donthyphenate notranslate">immutable</span> prevents access to mutable data through its context pointer.
|
|
An immutable pure nested function is strongly pure.</div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="pure-factory-functions" href="#pure-factory-functions">Pure Factory Functions</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>A <i>pure factory function</i> is a strongly pure function
|
|
that returns a result that has only mutable indirections.
|
|
All mutable
|
|
memory returned by the call cannot be referenced by any other part of the
|
|
program, i.e. it is newly allocated by the function.
|
|
The mutable
|
|
references of the result similarly cannot refer to any object that
|
|
existed before the function call.
|
|
This allows the result to be implicitly cast
|
|
from anything to <span class="d_inlinecode donthyphenate notranslate">immutable</span> or <span class="d_inlinecode donthyphenate notranslate">const shared</span>,
|
|
and from <span class="d_inlinecode donthyphenate notranslate">shared</span> and <span class="d_inlinecode donthyphenate notranslate">const shared</span> to (unshared) <span class="d_inlinecode donthyphenate notranslate">const</span>.
|
|
For example:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> List { <span class="d_keyword">int</span> payload; List* next; }
|
|
|
|
<span class="d_keyword">pure</span> List* make(<span class="d_keyword">int</span> a, <span class="d_keyword">int</span> b)
|
|
{
|
|
<span class="d_keyword">auto</span> result = <span class="d_keyword">new</span> List(a, <span class="d_keyword">null</span>);
|
|
result.next = <span class="d_keyword">new</span> List(b, <span class="d_keyword">null</span>);
|
|
<span class="d_keyword">return</span> result;
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">auto</span> list = make(1, 2);
|
|
<span class="d_keyword">pragma</span>(msg, <span class="d_keyword">typeof</span>(list)); <span class="d_comment">// List*
|
|
</span>
|
|
<span class="d_keyword">immutable</span> ilist = make(1, 2);
|
|
<span class="d_keyword">pragma</span>(msg, <span class="d_keyword">typeof</span>(ilist)); <span class="d_comment">// immutable List*
|
|
</span> <span class="d_keyword">pragma</span>(msg, <span class="d_keyword">typeof</span>(ilist.next)); <span class="d_comment">// immutable List*
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>All references in <span class="d_inlinecode donthyphenate notranslate">make</span>'s result refer to <span class="d_inlinecode donthyphenate notranslate">List</span>
|
|
objects created by <span class="d_inlinecode donthyphenate notranslate">make</span>, and no other part of the program refers to
|
|
any of these objects. Hence the result can initialize an immutable
|
|
variable.</p>
|
|
<div class="blankline"></div>
|
|
<p>This does not affect any <em>Exception</em> or <em>Error</em> thrown from the function.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="pure-optimization" href="#pure-optimization">Optimization</a></h3>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> An implementation may assume that a strongly pure
|
|
function called with arguments that have only immutable indirections (or none)
|
|
that returns a result
|
|
without mutable indirections will have the same effect for all invocations
|
|
with equivalent arguments. It is allowed to memoize the result of the
|
|
function under the assumption that equivalent arguments always produce
|
|
equivalent results.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> a(<span class="d_keyword">int</span>) <span class="d_keyword">pure</span>; <span class="d_comment">// no mutable indirections
|
|
</span><span class="d_keyword">int</span> b(<span class="d_keyword">const</span> Object) <span class="d_keyword">pure</span>; <span class="d_comment">// depends on argument passed
|
|
</span><span class="d_keyword">immutable</span>(Object) c(<span class="d_keyword">immutable</span> Object) <span class="d_keyword">pure</span>; <span class="d_comment">// always memoizable
|
|
</span>
|
|
<span class="d_keyword">void</span> g();
|
|
|
|
<span class="d_keyword">void</span> f(<span class="d_keyword">int</span> n, <span class="d_keyword">const</span> Object co, <span class="d_keyword">immutable</span> Object io)
|
|
{
|
|
<span class="d_keyword">const</span> <span class="d_keyword">int</span> x = a(n);
|
|
g(); <span class="d_comment">// `n` does not change between calls to `a`
|
|
</span> <span class="d_keyword">int</span> i = a(n); <span class="d_comment">// same as `i = x`
|
|
</span>
|
|
<span class="d_keyword">const</span> <span class="d_keyword">int</span> y = b(co);
|
|
<span class="d_comment">// `co` may have mutable indirection
|
|
</span> g(); <span class="d_comment">// may change fields of `co` through another reference
|
|
</span> i = b(co); <span class="d_comment">// call is not memoizable, result may differ
|
|
</span>
|
|
<span class="d_keyword">const</span> <span class="d_keyword">int</span> z = b(io);
|
|
i = b(io); <span class="d_comment">// same as `i = z`
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p> Such a function may still have behavior
|
|
inconsistent with memoization by e.g. using <span class="d_inlinecode donthyphenate notranslate">cast</span>s or by changing behavior
|
|
depending on the address of its parameters. An implementation is currently
|
|
not required to enforce validity of memoization in all cases.
|
|
</p>
|
|
<p> If a function throws an <em>Exception</em> or an <em>Error</em>, the
|
|
assumptions related to memoization do not carry to the thrown
|
|
exception.</p>
|
|
<div class="blankline"></div>
|
|
<p>Pure destructors do not benefit of special elision.</p>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="nothrow-functions" href="#nothrow-functions">Nothrow Functions</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>Nothrow functions can only throw exceptions derived
|
|
from <a href="https://dlang.org/phobos/object.html#.Error"><span class="d_inlinecode donthyphenate notranslate">class Error</span></a>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Nothrow functions are <a href="../spec/type.html#covariance">covariant</a> with throwing ones.</p>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="ref-functions" href="#ref-functions">Ref Functions</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>A <span class="d_inlinecode donthyphenate notranslate">ref</span> function returns by reference (instead of by value).
|
|
The return value of a <span class="d_inlinecode donthyphenate notranslate">ref</span> function must be an lvalue
|
|
(whereas the return value of a non-<span class="d_inlinecode donthyphenate notranslate">ref</span> function can be an rvalue, too).
|
|
An expression formed by calling a <span class="d_inlinecode donthyphenate notranslate">ref</span> function is an lvalue
|
|
(whereas an expression formed by calling a non-<span class="d_inlinecode donthyphenate notranslate">ref</span> function is an rvalue).
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> *p;
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> foo()
|
|
{
|
|
p = <span class="d_keyword">new</span> <span class="d_keyword">int</span>(2);
|
|
<span class="d_keyword">return</span> *p;
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">int</span> i = foo();
|
|
<span class="d_keyword">assert</span>(i == 2);
|
|
|
|
foo() = 3; <span class="d_comment">// reference returns can be lvalues
|
|
</span> <span class="d_keyword">assert</span>(*p == 3);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>Returning a reference to an expired function context is not allowed.
|
|
This includes local variables, temporaries and parameters that are part
|
|
of an expired function context.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">ref</span> <span class="d_keyword">int</span> sun()
|
|
{
|
|
<span class="d_keyword">int</span> i;
|
|
<span class="d_keyword">return</span> i; <span class="d_comment">// error, escaping a reference to local variable i
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>A <span class="d_inlinecode donthyphenate notranslate">ref</span> parameter may not be returned by <span class="d_inlinecode donthyphenate notranslate">ref</span>, unless it is
|
|
<a href="#return-ref-parameters"><span class="d_inlinecode donthyphenate notranslate">return ref</span></a>.</p>
|
|
<pre class="d_code notranslate"><span class="d_keyword">ref</span> <span class="d_keyword">int</span> moon(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> i)
|
|
{
|
|
<span class="d_keyword">return</span> i; <span class="d_comment">// error
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="auto-functions" href="#auto-functions">Auto Functions</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>Auto functions have their return type inferred from any
|
|
<a href="../spec/statement.html#ReturnStatement"><i>ReturnStatement</i></a>s in the function body.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>An auto function is declared without a return type.
|
|
Auto functions can use any valid <a href="../spec/declaration.html#StorageClass"><i>StorageClass</i></a>, not just <span class="d_inlinecode donthyphenate notranslate">auto</span>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>If there are multiple <i>ReturnStatement</i>s, the types
|
|
of them must be implicitly convertible to a common type.
|
|
If there are no <i>ReturnStatement</i>s, the return type is inferred
|
|
to be <span class="d_keyword">void</span>.</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">auto</span> foo(<span class="d_keyword">int</span> x) { <span class="d_keyword">return</span> x + 3; } <span class="d_comment">// inferred to be int
|
|
</span><span class="d_keyword">pure</span> bar(<span class="d_keyword">int</span> x) { <span class="d_keyword">return</span> x; <span class="d_keyword">return</span> 2.5; } <span class="d_comment">// inferred to be double
|
|
</span></pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> Return type inference also triggers
|
|
<a href="#function-attribute-inference">attribute inference</a>.</div>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="auto-ref-functions" href="#auto-ref-functions">Auto Ref Functions</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>Auto ref functions can infer their return type just as
|
|
<a href="#auto-functions">auto functions</a> do.
|
|
In addition, they become <a href="#ref-functions">ref functions</a>
|
|
if all of these apply:</p>
|
|
|
|
<ul><li>All expressions returned from the function are lvalues</li>
|
|
<li>No local variables are returned</li>
|
|
<li>Any parameters returned are reference parameters</li>
|
|
<li>Each returned expression must implicitly convert to an lvalue of the deduced return type
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
|
|
</div>
|
|
</li><pre class="d_code notranslate"><span class="d_keyword">auto</span> <span class="d_keyword">ref</span> f1(<span class="d_keyword">int</span> x) { <span class="d_keyword">return</span> x; } <span class="d_comment">// value return
|
|
</span><span class="d_keyword">auto</span> <span class="d_keyword">ref</span> f2() { <span class="d_keyword">return</span> 3; } <span class="d_comment">// value return
|
|
</span><span class="d_keyword">auto</span> <span class="d_keyword">ref</span> f3(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> x) { <span class="d_keyword">return</span> x; } <span class="d_comment">// ref return
|
|
</span><span class="d_keyword">auto</span> <span class="d_keyword">ref</span> f4(<span class="d_keyword">out</span> <span class="d_keyword">int</span> x) { <span class="d_keyword">return</span> x; } <span class="d_comment">// ref return
|
|
</span><span class="d_keyword">auto</span> <span class="d_keyword">ref</span> f5()
|
|
{
|
|
<span class="d_keyword">static</span> <span class="d_keyword">int</span> x;
|
|
<span class="d_keyword">return</span> x; <span class="d_comment">// ref return
|
|
</span>}
|
|
</pre>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<p>The ref-ness of a function is determined from all
|
|
<a href="../spec/statement.html#ReturnStatement"><i>ReturnStatement</i></a>s in the function body:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">auto</span> <span class="d_keyword">ref</span> f1(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> x) { <span class="d_keyword">return</span> 3; <span class="d_keyword">return</span> x; } <span class="d_comment">// ok, value return
|
|
</span><span class="d_keyword">auto</span> <span class="d_keyword">ref</span> f2(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> x) { <span class="d_keyword">return</span> x; <span class="d_keyword">return</span> 3; } <span class="d_comment">// ok, value return
|
|
</span><span class="d_keyword">auto</span> <span class="d_keyword">ref</span> f3(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> x, <span class="d_keyword">ref</span> <span class="d_keyword">double</span> y)
|
|
{
|
|
<span class="d_keyword">return</span> x; <span class="d_keyword">return</span> y;
|
|
<span class="d_comment">// The return type is deduced to be double, but cast(double)x is not an lvalue,
|
|
</span> <span class="d_comment">// so f3 has a value return.
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>Auto ref functions can have an explicit return type.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">auto</span> <span class="d_keyword">ref</span> <span class="d_keyword">int</span> bar(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> x) { <span class="d_keyword">return</span> x; } <span class="d_comment">// ok, ref return
|
|
</span><span class="d_keyword">auto</span> <span class="d_keyword">ref</span> <span class="d_keyword">int</span> foo(<span class="d_keyword">double</span> x) { <span class="d_keyword">return</span> x; } <span class="d_comment">// error, cannot convert double to int
|
|
</span></pre>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="inout-functions" href="#inout-functions">Inout Functions</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>For extensive information see <a href="../spec/const3.html#inout"><span class="d_inlinecode donthyphenate notranslate">inout</span> type qualifier</a>.</p>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="optional-parenthesis" href="#optional-parenthesis">Optional Parentheses</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>If a function call passes no explicit argument, i.e. it would syntactically use <span class="d_inlinecode donthyphenate notranslate">()</span>, then these parentheses
|
|
may be omitted, similar to a getter invocation of a
|
|
<a href="#property-functions">property function</a>.
|
|
A <a href="#pseudo-member">UFCS</a> call can also omit empty parentheses.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> foo() {} <span class="d_comment">// no arguments
|
|
</span><span class="d_keyword">void</span> fun(<span class="d_keyword">int</span> x = 10) {}
|
|
<span class="d_keyword">void</span> bar(<span class="d_keyword">int</span>[] arr) {}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
foo(); <span class="d_comment">// OK
|
|
</span> foo; <span class="d_comment">// also OK
|
|
</span> fun; <span class="d_comment">// OK
|
|
</span>
|
|
<span class="d_keyword">int</span>[] arr;
|
|
arr.bar(); <span class="d_comment">// UFCS call
|
|
</span> arr.bar; <span class="d_comment">// also OK
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>Due to ambiguity, parentheses are required to call a delegate or a function pointer:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">int</span> <span class="d_keyword">function</span>() fp;
|
|
|
|
<span class="d_keyword">assert</span>(fp == 6); <span class="d_comment">// Error, incompatible types int function() and int
|
|
</span> <span class="d_keyword">assert</span>(*fp == 6); <span class="d_comment">// Error, incompatible types int() and int
|
|
</span>
|
|
<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg;
|
|
<span class="d_keyword">assert</span>(dg == 6); <span class="d_comment">// Error, incompatible types int delegate() and int
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>If a function returns a delegate or a function pointer, any parentheses
|
|
apply first to the function call, not the result. Two sets of parentheses are required
|
|
to call the result directly:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> getNum() { <span class="d_keyword">return</span> 6; }
|
|
<span class="d_keyword">int</span> <span class="d_keyword">function</span>() getFunc() { <span class="d_keyword">return</span> &getNum; }
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">int</span> <span class="d_keyword">function</span>() fp;
|
|
|
|
fp = getFunc; <span class="d_comment">// implicit call
|
|
</span> <span class="d_keyword">assert</span>(fp() == 6);
|
|
|
|
fp = getFunc(); <span class="d_comment">// explicit call
|
|
</span> <span class="d_keyword">assert</span>(fp() == 6);
|
|
|
|
<span class="d_keyword">int</span> x = getFunc()();
|
|
<span class="d_keyword">assert</span>(x == 6);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> S
|
|
{
|
|
<span class="d_keyword">int</span> getNum() { <span class="d_keyword">return</span> 6; }
|
|
<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() getDel() <span class="d_keyword">return</span> { <span class="d_keyword">return</span> &getNum; }
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
S s;
|
|
<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg;
|
|
|
|
dg = s.getDel; <span class="d_comment">// implicit call
|
|
</span> <span class="d_keyword">assert</span>(dg() == 6);
|
|
|
|
dg = s.getDel(); <span class="d_comment">// explicit call
|
|
</span> <span class="d_keyword">assert</span>(dg() == 6);
|
|
|
|
<span class="d_keyword">int</span> y = s.getDel()();
|
|
<span class="d_keyword">assert</span>(y == 6);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="property-functions" href="#property-functions">Property Functions</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>WARNING: The definition and usefulness of property functions is being reviewed, and the implementation
|
|
is currently incomplete. Using property functions is not recommended until the definition is
|
|
more certain and implementation more mature.</p>
|
|
<div class="blankline"></div>
|
|
<p>Properties are functions that can be syntactically treated
|
|
as if they were fields or variables. Properties can be read from or written to.
|
|
A property is read by calling a method or function with no arguments;
|
|
a property is written by calling a method or function with its argument
|
|
being the value it is set to.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Simple getter and setter properties can be written using <a href="#pseudo-member">UFCS</a>.
|
|
These can be enhanced with the additon of the <span class="d_inlinecode donthyphenate notranslate">@property</span> attribute to the function, which
|
|
adds the following behaviors:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<ul> <li><span class="d_inlinecode donthyphenate notranslate">@property</span> functions cannot be overloaded with non-<span class="d_inlinecode donthyphenate notranslate">@property</span> functions with the same name.</li>
|
|
<li><span class="d_inlinecode donthyphenate notranslate">@property</span> functions can only have zero, one or two parameters.</li>
|
|
<li><span class="d_inlinecode donthyphenate notranslate">@property</span> functions cannot have variadic parameters.</li>
|
|
<li>For the expression <span class="d_inlinecode donthyphenate notranslate">typeof(exp)</span> where <span class="d_inlinecode donthyphenate notranslate">exp</span> is an <span class="d_inlinecode donthyphenate notranslate">@property</span> function,
|
|
the type is the return type of the function, rather than the type of the function.</li>
|
|
<li>For the expression <span class="d_inlinecode donthyphenate notranslate">__traits(compiles, exp)</span> where <span class="d_inlinecode donthyphenate notranslate">exp</span> is an <span class="d_inlinecode donthyphenate notranslate">@property</span> function,
|
|
a further check is made to see if the function can be called.</li>
|
|
<li><span class="d_inlinecode donthyphenate notranslate">@property</span> are mangled differently, meaning that <span class="d_inlinecode donthyphenate notranslate">@property</span> must be consistently
|
|
used across different compilation units.</li>
|
|
<li>The ObjectiveC interface recognizes <span class="d_inlinecode donthyphenate notranslate">@property</span> setter functions as special and modifies
|
|
them accordingly.</li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<p>A simple property would be:</p>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> Foo
|
|
{
|
|
@property <span class="d_keyword">int</span> data() { <span class="d_keyword">return</span> m_data; } <span class="d_comment">// read property
|
|
</span>
|
|
@property <span class="d_keyword">int</span> data(<span class="d_keyword">int</span> value) { <span class="d_keyword">return</span> m_data = value; } <span class="d_comment">// write property
|
|
</span>
|
|
<span class="d_keyword">private</span>:
|
|
<span class="d_keyword">int</span> m_data;
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>To use it:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> test()
|
|
{
|
|
Foo f;
|
|
|
|
f.data = 3; <span class="d_comment">// same as f.data(3);
|
|
</span> <span class="d_keyword">return</span> f.data + 3; <span class="d_comment">// same as return f.data() + 3;
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>The absence of a read method means that the property is write-only.
|
|
The absence of a write method means that the property is read-only.
|
|
Multiple write methods can exist; the correct one is selected using
|
|
the usual function overloading rules.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>In all the other respects, these methods are like any other methods.
|
|
They can be static, have different linkages, have their address taken, etc.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>The built in properties <span class="d_inlinecode donthyphenate notranslate">.sizeof</span>, <span class="d_inlinecode donthyphenate notranslate">.alignof</span>, and <span class="d_inlinecode donthyphenate notranslate">.mangleof</span>
|
|
may not be declared as fields or methods in structs, unions, classes or enums.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>If a property function has no parameters, it works as a getter.
|
|
If has exactly one parameter, it works as a setter.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="virtual-functions" href="#virtual-functions">Virtual Functions</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>Virtual functions are class member functions that are called indirectly through a
|
|
function pointer table, called a <span class="d_inlinecode donthyphenate notranslate">vtbl[]</span>, rather than directly.
|
|
Member functions that are virtual can be overridden in a derived class:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> A
|
|
{
|
|
<span class="d_keyword">void</span> foo(<span class="d_keyword">int</span> x) {}
|
|
}
|
|
|
|
<span class="d_keyword">class</span> B : A
|
|
{
|
|
<span class="d_keyword">override</span> <span class="d_keyword">void</span> foo(<span class="d_keyword">int</span> x) {}
|
|
<span class="d_comment">//override void foo() {} // error, no foo() in A
|
|
</span>}
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
A a = <span class="d_keyword">new</span> B();
|
|
a.foo(1); <span class="d_comment">// calls B.foo(int)
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>The <span class="d_inlinecode donthyphenate notranslate">override</span> attribute is required when overriding a function.
|
|
This is useful for catching errors when a base class's member function
|
|
has its parameters changed, and all derived classes need to have
|
|
their overriding functions updated.</p>
|
|
<div class="blankline"></div>
|
|
<p>The <a class="anchor" title="Permalink to this section" id="final" href="#final"><span class="d_inlinecode donthyphenate notranslate">final</span></a> method attribute
|
|
prevents a subclass from overriding the method.</p>
|
|
<div class="blankline"></div>
|
|
<p>The following are not virtual:</p>
|
|
<ul> <li>Struct and union member functions</li>
|
|
<li><span class="d_inlinecode donthyphenate notranslate">final</span> member functions</li>
|
|
<li><a href="../spec/attribute.html#static"><span class="d_inlinecode donthyphenate notranslate">static</span></a> member functions</li>
|
|
<li>Member functions which are <span class="d_inlinecode donthyphenate notranslate">private</span> or <span class="d_inlinecode donthyphenate notranslate">package</span></li>
|
|
<li>Member template functions</li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<p><b>Example:</b></p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> A
|
|
{
|
|
<span class="d_keyword">int</span> def() { ... }
|
|
<span class="d_keyword">final</span> <span class="d_keyword">int</span> foo() { ... }
|
|
<span class="d_keyword">final</span> <span class="d_keyword">private</span> <span class="d_keyword">int</span> bar() { ... }
|
|
<span class="d_keyword">private</span> <span class="d_keyword">int</span> abc() { ... }
|
|
}
|
|
|
|
<span class="d_keyword">class</span> B : A
|
|
{
|
|
<span class="d_keyword">override</span> <span class="d_keyword">int</span> def() { ... } <span class="d_comment">// ok, overrides A.def
|
|
</span> <span class="d_keyword">override</span> <span class="d_keyword">int</span> foo() { ... } <span class="d_comment">// error, A.foo is final
|
|
</span> <span class="d_keyword">int</span> bar() { ... } <span class="d_comment">// ok, A.bar is final private, but not virtual
|
|
</span> <span class="d_keyword">int</span> abc() { ... } <span class="d_comment">// ok, A.abc is not virtual, B.abc is virtual
|
|
</span>}
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
A a = <span class="d_keyword">new</span> B;
|
|
a.def(); <span class="d_comment">// calls B.def
|
|
</span> a.foo(); <span class="d_comment">// calls A.foo
|
|
</span> a.bar(); <span class="d_comment">// calls A.bar
|
|
</span> a.abc(); <span class="d_comment">// calls A.abc
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Member functions with <span class="d_inlinecode donthyphenate notranslate">Objective-C</span> linkage are virtual even if marked
|
|
with <span class="d_inlinecode donthyphenate notranslate">final</span> or <span class="d_inlinecode donthyphenate notranslate">static</span>, and can be overridden.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="covariance" href="#covariance">Covariance</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>An overriding function may be <a href="../spec/type.html#covariance">covariant</a>
|
|
with the overridden function.
|
|
A covariant function has a type that is implicitly convertible to the
|
|
type of the overridden function.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> A { }
|
|
<span class="d_keyword">class</span> B : A { }
|
|
|
|
<span class="d_keyword">class</span> Foo
|
|
{
|
|
A test() { <span class="d_keyword">return</span> <span class="d_keyword">null</span>; }
|
|
}
|
|
|
|
<span class="d_keyword">class</span> Bar : Foo
|
|
{
|
|
<span class="d_comment">// overrides and is covariant with Foo.test()
|
|
</span> <span class="d_keyword">override</span> B test() { <span class="d_keyword">return</span> <span class="d_keyword">null</span>; }
|
|
}
|
|
|
|
<span class="d_keyword">static</span> <span class="d_keyword">assert</span>(<span class="d_keyword">is</span>(<span class="d_keyword">typeof</span>(&Bar.test) : <span class="d_keyword">typeof</span>(&Foo.test)));
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="base-methods" href="#base-methods">Calling Base Class Methods</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>To directly call a member function of a base class <span class="d_inlinecode donthyphenate notranslate">Base</span>,
|
|
write <span class="d_inlinecode donthyphenate notranslate">Base.</span> before the function name.
|
|
This avoids dynamic dispatch through a function pointer. For
|
|
example:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> B
|
|
{
|
|
<span class="d_keyword">int</span> foo() { <span class="d_keyword">return</span> 1; }
|
|
}
|
|
<span class="d_keyword">class</span> C : B
|
|
{
|
|
<span class="d_keyword">override</span> <span class="d_keyword">int</span> foo() { <span class="d_keyword">return</span> 2; }
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
<span class="d_keyword">assert</span>(B.foo() == 1); <span class="d_comment">// translated to this.B.foo(), and
|
|
</span> <span class="d_comment">// calls B.foo statically.
|
|
</span> <span class="d_keyword">assert</span>(C.foo() == 2); <span class="d_comment">// calls C.foo statically, even if
|
|
</span> <span class="d_comment">// the actual instance of 'this' is D.
|
|
</span> }
|
|
}
|
|
<span class="d_keyword">class</span> D : C
|
|
{
|
|
<span class="d_keyword">override</span> <span class="d_keyword">int</span> foo() { <span class="d_keyword">return</span> 3; }
|
|
}
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">auto</span> d = <span class="d_keyword">new</span> D();
|
|
<span class="d_keyword">assert</span>(d.foo() == 3); <span class="d_comment">// calls D.foo
|
|
</span> <span class="d_keyword">assert</span>(d.B.foo() == 1); <span class="d_comment">// calls B.foo
|
|
</span> <span class="d_keyword">assert</span>(d.C.foo() == 2); <span class="d_comment">// calls C.foo
|
|
</span> d.test();
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<p>Base class methods can also be called through the
|
|
<a href="../spec/expression.html#super"><span class="d_inlinecode donthyphenate notranslate">super</span></a> reference.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> Normally calling a virtual function implies getting the
|
|
address of the function at runtime by indexing into the class's <span class="d_inlinecode donthyphenate notranslate">vtbl[]</span>.
|
|
If the implementation can determine that the called virtual function will be statically
|
|
known, such as if it is <span class="d_inlinecode donthyphenate notranslate">final</span>, it can use a direct call instead.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="function-inheritance" href="#function-inheritance">Overload Sets and Overriding</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>When doing overload resolution, the functions in the base
|
|
class are not considered, as they are not in the same
|
|
<a href="#overload-sets">Overload Set</a>:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> A
|
|
{
|
|
<span class="d_keyword">int</span> foo(<span class="d_keyword">int</span> x) { ... }
|
|
<span class="d_keyword">int</span> foo(<span class="d_keyword">long</span> y) { ... }
|
|
}
|
|
|
|
<span class="d_keyword">class</span> B : A
|
|
{
|
|
<span class="d_keyword">override</span> <span class="d_keyword">int</span> foo(<span class="d_keyword">long</span> x) { ... }
|
|
}
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
B b = <span class="d_keyword">new</span> B();
|
|
b.foo(1); <span class="d_comment">// calls B.foo(long), since A.foo(int) is not considered
|
|
</span>
|
|
A a = b;
|
|
a.foo(1); <span class="d_comment">// issues runtime error (instead of calling A.foo(int))
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>To include the base class's functions in the overload resolution
|
|
process, use an <a href="../spec/declaration.html#AliasDeclaration"><i>AliasDeclaration</i></a>:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> A
|
|
{
|
|
<span class="d_keyword">int</span> foo(<span class="d_keyword">int</span> x) { ... }
|
|
<span class="d_keyword">int</span> foo(<span class="d_keyword">long</span> y) { ... }
|
|
}
|
|
|
|
<span class="d_keyword">class</span> B : A
|
|
{
|
|
<b><i><span class="d_keyword">alias</span> foo = A.foo;</i></b>
|
|
<span class="d_keyword">override</span> <span class="d_keyword">int</span> foo(<span class="d_keyword">long</span> x) { ... }
|
|
}
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
A a = <span class="d_keyword">new</span> B();
|
|
a.foo(1); <span class="d_comment">// calls A.foo(int)
|
|
</span> B b = <span class="d_keyword">new</span> B();
|
|
b.foo(1); <span class="d_comment">// calls A.foo(int)
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>If such an <i>AliasDeclaration</i> is not used, the derived
|
|
class's functions completely override all the functions of the
|
|
same name in the base class, even if the types of the parameters
|
|
in the base class functions are different.
|
|
It is illegal if, through
|
|
implicit conversions to the base class, those other functions do
|
|
get called:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> A
|
|
{
|
|
<span class="d_keyword">void</span> <b><i>set</i></b>(<span class="d_keyword">long</span> i) { }
|
|
<span class="d_keyword">void</span> set(<span class="d_keyword">int</span> i) { }
|
|
}
|
|
<span class="d_keyword">class</span> B : A
|
|
{
|
|
<span class="d_keyword">override</span> <span class="d_keyword">void</span> set(<span class="d_keyword">long</span> i) { }
|
|
}
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
A a = <span class="d_keyword">new</span> B;
|
|
a.set(3); <span class="d_comment">// error, use of A.set(int) is hidden by B
|
|
</span> <span class="d_comment">// use 'alias set = A.set;' to introduce base class overload set
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="override-defaults" href="#override-defaults">Default Values</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>A function parameter's default value is not inherited:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> A
|
|
{
|
|
<span class="d_keyword">void</span> <b><i>foo</i></b>(<span class="d_keyword">int</span> x = 5) { ... }
|
|
}
|
|
|
|
<span class="d_keyword">class</span> B : A
|
|
{
|
|
<span class="d_keyword">void</span> foo(<span class="d_keyword">int</span> <b><i>x = 7</i></b>) { ... }
|
|
}
|
|
|
|
<span class="d_keyword">class</span> C : B
|
|
{
|
|
<span class="d_keyword">void</span> foo(<span class="d_keyword">int</span> <b><i>x</i></b>) { ... }
|
|
}
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
A a = <span class="d_keyword">new</span> A();
|
|
a.foo(); <span class="d_comment">// calls A.foo(5)
|
|
</span>
|
|
B b = <span class="d_keyword">new</span> B();
|
|
b.foo(); <span class="d_comment">// calls B.foo(7)
|
|
</span>
|
|
C c = <span class="d_keyword">new</span> C();
|
|
c.foo(); <span class="d_comment">// error, need an argument for C.foo
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="inheriting-attributes" href="#inheriting-attributes">Inherited Attributes</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>An overriding function inherits any unspecified <a href="#FunctionAttributes"><i>FunctionAttributes</i></a>
|
|
from the attributes of the overridden function.</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> B
|
|
{
|
|
<span class="d_keyword">void</span> foo() <span class="d_keyword">pure</span> <span class="d_keyword">nothrow</span> @safe {}
|
|
}
|
|
<span class="d_keyword">class</span> D : B
|
|
{
|
|
<span class="d_keyword">override</span> <span class="d_keyword">void</span> foo() {}
|
|
}
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">auto</span> d = <span class="d_keyword">new</span> D();
|
|
<span class="d_keyword">pragma</span>(msg, <span class="d_keyword">typeof</span>(&d.foo));
|
|
<span class="d_comment">// prints "void delegate() pure nothrow @safe" in compile time
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="override-restrictions" href="#override-restrictions">Restrictions</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>The attributes
|
|
<a href="attribute.html#disable"><span class="d_inlinecode donthyphenate notranslate">@disable</span></a> and
|
|
<a href="attribute.html#deprecated"><span class="d_inlinecode donthyphenate notranslate">deprecated</span></a>
|
|
are not allowed on overriding functions.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes rationale"><b>Rationale:</b> To stop the compilation or to output the deprecation message, the implementation
|
|
must be able to determine the target of the call, which can't be guaranteed
|
|
when it is virtual.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> B
|
|
{
|
|
<span class="d_keyword">void</span> foo() {}
|
|
}
|
|
|
|
<span class="d_keyword">class</span> D : B
|
|
{
|
|
@disable <span class="d_keyword">override</span> <span class="d_keyword">void</span> foo() {} <span class="d_comment">// error, can't apply @disable to overriding function
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="inline-functions" href="#inline-functions">Inline Functions</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>The compiler makes the decision whether to inline a function or not.
|
|
This decision may be controlled by <a href="pragma.html#inline"><span class="d_inlinecode donthyphenate notranslate">pragma(inline)</span></a>.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> Whether a function is inlined or not is implementation defined, though
|
|
any <a href="../spec/expression.html#FunctionLiteral"><i>FunctionLiteral</i></a> should be inlined
|
|
when used in its declaration scope.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="function-overloading" href="#function-overloading">Function Overloading</a></h2>
|
|
<div class="blankline"></div>
|
|
<p><i>Function overloading</i> occurs when two or more functions in the same scope
|
|
have the same name.
|
|
The function selected is the one that is the <i>best match</i> to the arguments.
|
|
The matching levels are:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<ol> <li>No match</li>
|
|
<li>Match with implicit conversions</li>
|
|
<li>Match with qualifier conversion (if the argument type is
|
|
<a href="https://dlang.org/spec/glossary.html#qualifier-convertible">qualifier-convertible</a> to the parameter type)</li>
|
|
<li>Exact match</li>
|
|
</ol>
|
|
<div class="blankline"></div>
|
|
<p>Named arguments are resolved for a candidate according to
|
|
<a href="../spec/expression.html#argument-parameter-matching">Matching Arguments to Parameters</a>.
|
|
If this fails (for example, because the overload does not have a parameter matching a named argument),
|
|
the level is <i>no match</i>. Other than that, named arguments do not affect the matching level.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Each argument (including any <span class="d_inlinecode donthyphenate notranslate">this</span> reference) is
|
|
compared against the function's corresponding parameter to
|
|
determine the match level for that argument. The match level
|
|
for a function is the <i>worst</i> match level of each of its
|
|
arguments.</p>
|
|
<div class="blankline"></div>
|
|
<p>Literals do not match <span class="d_inlinecode donthyphenate notranslate">ref</span> or <span class="d_inlinecode donthyphenate notranslate">out</span> parameters.</p>
|
|
<div class="blankline"></div>
|
|
<p><span class="d_inlinecode donthyphenate notranslate">scope</span> parameter storage class does not affect function overloading.</p>
|
|
<div class="blankline"></div>
|
|
<p>If two or more functions have the same match level,
|
|
then <a class="anchor" title="Permalink to this section" id="partial-ordering" href="#partial-ordering"><i>partial ordering</i></a>
|
|
is used to disambiguate to find the best match.
|
|
Partial ordering finds the most specialized function.
|
|
If neither function is more specialized than the other,
|
|
then it is an ambiguity error.
|
|
Partial ordering is determined for functions <i>f</i>
|
|
and <i>g</i> by taking the parameter types of <i>f</i>,
|
|
constructing a list of arguments by taking the default values
|
|
of those types, and attempting to match them against <i>g</i>.
|
|
If it succeeds, then <i>g</i> is at least as specialized
|
|
as <i>f</i>.
|
|
For example:
|
|
</p>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> A { }
|
|
<span class="d_keyword">class</span> B : A { }
|
|
<span class="d_keyword">class</span> C : B { }
|
|
<span class="d_keyword">void</span> foo(A);
|
|
<span class="d_keyword">void</span> foo(B);
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
C c;
|
|
<span class="d_comment">/* Both foo(A) and foo(B) match with implicit conversions (level 2).
|
|
* Applying partial ordering rules,
|
|
* foo(B) cannot be called with an A, and foo(A) can be called
|
|
* with a B. Therefore, foo(B) is more specialized, and is selected.
|
|
*/</span>
|
|
foo(c); <span class="d_comment">// calls foo(B)
|
|
</span>}
|
|
</pre>
|
|
<p>A function with a variadic argument is considered less
|
|
specialized than a function without.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>A static member function can be overloaded with a member
|
|
function. The struct, class
|
|
or union of the static member function is inferred from the
|
|
type of the <span class="d_inlinecode donthyphenate notranslate">this</span> argument.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> S {
|
|
<span class="d_keyword">void</span> eggs(<span class="d_keyword">int</span>);
|
|
<span class="d_keyword">static</span> <span class="d_keyword">void</span> eggs(<span class="d_keyword">long</span>);
|
|
}
|
|
S s;
|
|
s.eggs(0); <span class="d_comment">// calls void eggs(int);
|
|
</span>S.eggs(0); <span class="d_comment">// error: need `this`
|
|
</span>s.eggs(0L); <span class="d_comment">// calls static void eggs(long);
|
|
</span>S.eggs(0L); <span class="d_comment">// calls static void eggs(long);
|
|
</span>
|
|
<span class="d_keyword">struct</span> T {
|
|
<span class="d_keyword">void</span> bacon(<span class="d_keyword">int</span>);
|
|
<span class="d_keyword">static</span> <span class="d_keyword">void</span> bacon(<span class="d_keyword">int</span>);
|
|
}
|
|
T t;
|
|
t.bacon(0); <span class="d_comment">// error: ambiguous
|
|
</span>T.bacon(0); <span class="d_comment">// error: ambiguous
|
|
</span></pre>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes rationale"><b>Rationale:</b> A static member function that doesn't need
|
|
the <span class="d_inlinecode donthyphenate notranslate">this</span> parameter does not need to pass it.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="overload-sets" href="#overload-sets">Overload Sets</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>An <i>Overload Set</i> is the set of functions with the same name
|
|
declared in the same scope that participate in overload resolution.
|
|
An example of an overload set are functions defined
|
|
at module level:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">module</span> A;
|
|
<span class="d_keyword">void</span> foo() { }
|
|
<span class="d_keyword">void</span> foo(<span class="d_keyword">long</span> i) { }
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p><span class="d_inlinecode donthyphenate notranslate">A.foo()</span> and <span class="d_inlinecode donthyphenate notranslate">A.foo(long)</span> form an overload set.
|
|
A different module can also define another overload set of
|
|
functions with the same name:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">module</span> B;
|
|
<span class="d_keyword">class</span> C { }
|
|
<span class="d_keyword">void</span> foo(C) { }
|
|
<span class="d_keyword">void</span> foo(<span class="d_keyword">int</span> i) { }
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>and A and B can be imported by a third module, C.
|
|
Both overload sets, the <span class="d_inlinecode donthyphenate notranslate">A.foo</span> overload set and the <span class="d_inlinecode donthyphenate notranslate">B.foo</span>
|
|
overload set, are found when searching for symbol <span class="d_inlinecode donthyphenate notranslate">foo</span>.
|
|
An instance of <span class="d_inlinecode donthyphenate notranslate">foo</span> is selected
|
|
based on it matching in exactly one overload set:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">import</span> A;
|
|
<span class="d_keyword">import</span> B;
|
|
|
|
<span class="d_keyword">void</span> bar(C c , <span class="d_keyword">long</span> i)
|
|
{
|
|
foo(); <span class="d_comment">// calls A.foo()
|
|
</span> foo(i); <span class="d_comment">// calls A.foo(long)
|
|
</span> foo(c); <span class="d_comment">// calls B.foo(C)
|
|
</span> foo(1,2); <span class="d_comment">// error, does not match any foo
|
|
</span> foo(1); <span class="d_comment">// error, matches A.foo(long) and B.foo(int)
|
|
</span> A.foo(1); <span class="d_comment">// calls A.foo(long)
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Even though <span class="d_inlinecode donthyphenate notranslate">B.foo(int)</span> is a better match than <span class="d_inlinecode donthyphenate notranslate"> A.foo(long)</span> for <span class="d_inlinecode donthyphenate notranslate">foo(1)</span>,
|
|
it is an error because the two matches are in
|
|
different overload sets.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Overload sets can be merged with an alias declaration:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">import</span> A;
|
|
<span class="d_keyword">import</span> B;
|
|
|
|
<span class="d_keyword">alias</span> foo = A.foo;
|
|
<span class="d_keyword">alias</span> foo = B.foo;
|
|
|
|
<span class="d_keyword">void</span> bar(C c)
|
|
{
|
|
foo(); <span class="d_comment">// calls A.foo()
|
|
</span> foo(1L); <span class="d_comment">// calls A.foo(long)
|
|
</span> foo(c); <span class="d_comment">// calls B.foo(C)
|
|
</span> foo(1,2); <span class="d_comment">// error, does not match any foo
|
|
</span> foo(1); <span class="d_comment">// calls B.foo(int)
|
|
</span> A.foo(1); <span class="d_comment">// calls A.foo(long)
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="parameters" href="#parameters">Function Parameters</a></h2>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="param-storage" href="#param-storage">Parameter Storage Classes</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>Parameter storage classes are <span class="d_inlinecode donthyphenate notranslate">in</span>, <span class="d_inlinecode donthyphenate notranslate">out</span>, <span class="d_inlinecode donthyphenate notranslate">ref</span>, <span class="d_inlinecode donthyphenate notranslate">lazy</span>, <span class="d_inlinecode donthyphenate notranslate">return</span> and <span class="d_inlinecode donthyphenate notranslate">scope</span>.
|
|
Parameters can also take the type constructors <span class="d_inlinecode donthyphenate notranslate">const</span>, <span class="d_inlinecode donthyphenate notranslate">immutable</span>, <span class="d_inlinecode donthyphenate notranslate">shared</span> and <span class="d_inlinecode donthyphenate notranslate">inout</span>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p><span class="d_inlinecode donthyphenate notranslate">in</span>, <span class="d_inlinecode donthyphenate notranslate">out</span>, <span class="d_inlinecode donthyphenate notranslate">ref</span> and <span class="d_inlinecode donthyphenate notranslate">lazy</span> are mutually exclusive. The first three are used to
|
|
denote input, output and input/output parameters, respectively.
|
|
For example:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> read(<span class="d_keyword">in</span> <span class="d_keyword">char</span>[] input, <span class="d_keyword">ref</span> size_t count, <span class="d_keyword">out</span> <span class="d_keyword">int</span> errno);
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
size_t a = 42;
|
|
<span class="d_keyword">int</span> b;
|
|
<span class="d_keyword">int</span> r = read(<span class="d_string">"Hello World"</span>, a, b);
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p><span class="d_inlinecode donthyphenate notranslate">read</span> has three parameters. <span class="d_inlinecode donthyphenate notranslate">input</span> will only be read and no reference to it will be retained.
|
|
<span class="d_inlinecode donthyphenate notranslate">count</span> may be read and written to, and <span class="d_inlinecode donthyphenate notranslate">errno</span> will be set to a value from
|
|
within the function.</p>
|
|
<div class="blankline"></div>
|
|
<p>The argument <span class="d_inlinecode donthyphenate notranslate">"Hello World"</span> gets bound to parameter <span class="d_inlinecode donthyphenate notranslate">input</span>,
|
|
<span class="d_inlinecode donthyphenate notranslate">a</span> gets bound to <span class="d_inlinecode donthyphenate notranslate">count</span> and <span class="d_inlinecode donthyphenate notranslate">b</span> to <span class="d_inlinecode donthyphenate notranslate">errno</span>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<center><table><caption>Parameter Storage Class and Type Constructor Overview</caption> <tr><th class="donthyphenate"><b>Storage Class</b></th><th class="donthyphenate"><b>Description</b></th></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><i>none</i></td><td>The parameter will be a mutable copy of its argument.</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">in</span></td><td>The parameter is an input to the function.</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">out</span></td><td>The argument must be an lvalue, which will be passed by reference and initialized
|
|
upon function entry with the default value (<span class="d_inlinecode donthyphenate notranslate">T.init</span>) of its type.
|
|
</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref</span></td><td>The parameter is an <i>input/output</i> parameter, passed by reference.
|
|
</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">scope</span></td><td> The parameter must not escape the function call
|
|
(e.g. by being assigned to a global variable).
|
|
Ignored for any parameter that is not a reference type.
|
|
</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">return</span></td><td>Parameter may be returned or copied to the first parameter,
|
|
but otherwise does not escape from the function.
|
|
Such copies are required not to outlive the argument(s) they were derived from.
|
|
Ignored for parameters with no references.
|
|
See <a href="../spec/memory-safe-d.html#scope-return-params">Scope Parameters</a>.</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">lazy</span></td><td>argument is evaluated by the called function and not by the caller</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><th class="donthyphenate"><b>Type Constructor</b></th><th class="donthyphenate"><b>Description</b></th></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">const</span></td><td>argument is implicitly converted to a const type</td></tr>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">immutable</span></td><td>argument is implicitly converted to an immutable type</td></tr>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">shared</span></td><td>argument is implicitly converted to a shared type</td></tr>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">inout</span></td><td>argument is implicitly converted to an inout type</td></tr>
|
|
</table></center>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="in-params" href="#in-params">In Parameters</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>The parameter is an input to the function. Input parameters behave as if they have
|
|
the <span class="d_inlinecode donthyphenate notranslate">const</span> storage class.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> The following requires the <span class="d_inlinecode donthyphenate notranslate">-preview=in</span> switch and a compiler compliant with
|
|
<a href="../changelog/2.094.0.html#preview-in">dmd v2.094.0</a> or higher.</div>
|
|
<div class="blankline"></div>
|
|
<p><span class="d_inlinecode donthyphenate notranslate">in</span> parameters also behave like <a href="#scope-parameters"><span class="d_inlinecode donthyphenate notranslate">scope</span></a> parameters.</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">const</span>(<span class="d_keyword">int</span>[]) g(<span class="d_keyword">in</span> <span class="d_keyword">int</span>[] a) @safe
|
|
{
|
|
a[0]++; <span class="d_comment">// Error: cannot modify const expression
|
|
</span> <span class="d_keyword">return</span> a; <span class="d_comment">// Error: scope parameter `a` may not be returned
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>Input parameters may also be passed by reference by the compiler.
|
|
Unlike <span class="d_inlinecode donthyphenate notranslate">ref</span> parameters, <span class="d_inlinecode donthyphenate notranslate">in</span> parameters can bind to both lvalues and rvalues
|
|
(such as literals).</p>
|
|
|
|
<ul><li>Types that would trigger a side effect if passed by value (such as types with
|
|
a copy constructor, postblit, or destructor) will always be passed by reference.</li>
|
|
<li>Types which cannot be copied (e.g. if their copy constructor is marked as
|
|
<span class="d_inlinecode donthyphenate notranslate">@disable</span>) will always be passed by reference.</li>
|
|
<li>Dynamic arrays, classes, associative arrays, function pointers, and delegates
|
|
will always be passed by value.
|
|
</li>
|
|
</ul>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> If the type of the parameter does not fall in one of those categories,
|
|
whether or not it is passed by reference is implementation defined, and the backend is free
|
|
to choose the method that will best fit the ABI of the platform.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="ref-params" href="#ref-params">Ref and Out Parameters</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>By default, parameters take rvalue arguments.
|
|
A <span class="d_inlinecode donthyphenate notranslate">ref</span> parameter takes an lvalue argument, so changes to its value will operate
|
|
on the caller's argument.</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> inc(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> x)
|
|
{
|
|
x += 1;
|
|
}
|
|
|
|
<span class="d_keyword">void</span> seattle()
|
|
{
|
|
<span class="d_keyword">int</span> z = 3;
|
|
inc(z);
|
|
<span class="d_keyword">assert</span>(z == 4);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>A <span class="d_inlinecode donthyphenate notranslate">ref</span> parameter can also be returned by reference, see
|
|
<a href="#return-ref-parameters">Return Ref Parameters.</a></p>
|
|
<div class="blankline"></div>
|
|
<p>An <span class="d_inlinecode donthyphenate notranslate">out</span> parameter is similar to a <span class="d_inlinecode donthyphenate notranslate">ref</span> parameter, except it is
|
|
<a href="../spec/property.html#init-vs-construction">default initialized</a> upon
|
|
function invocation.</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> zero(<span class="d_keyword">out</span> <span class="d_keyword">int</span> x)
|
|
{
|
|
<span class="d_keyword">assert</span>(x == 0);
|
|
}
|
|
|
|
<span class="d_keyword">void</span> two(<span class="d_keyword">out</span> <span class="d_keyword">int</span> x)
|
|
{
|
|
x = 2;
|
|
}
|
|
|
|
<span class="d_keyword">void</span> tacoma()
|
|
{
|
|
<span class="d_keyword">int</span> a = 3;
|
|
zero(a);
|
|
<span class="d_keyword">assert</span>(a == 0);
|
|
|
|
<span class="d_keyword">int</span> y = 3;
|
|
two(y);
|
|
<span class="d_keyword">assert</span>(y == 2);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>For dynamic array and class object parameters, which are always passed
|
|
by reference, <span class="d_inlinecode donthyphenate notranslate">out</span> and <span class="d_inlinecode donthyphenate notranslate">ref</span>
|
|
apply only to the reference and not the contents.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="lazy-params" href="#lazy-params">Lazy Parameters</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>An argument to a <span class="d_inlinecode donthyphenate notranslate">lazy</span> parameter is not evaluated before the function is called.
|
|
The argument is only evaluated if/when the parameter is evaluated within the function. Hence,
|
|
a <span class="d_inlinecode donthyphenate notranslate">lazy</span> argument can be executed 0 or more times. </p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">import</span> std.stdio : writeln;
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">int</span> x;
|
|
3.times(writeln(x++));
|
|
writeln(<span class="d_string">"-"</span>);
|
|
writeln(x);
|
|
}
|
|
|
|
<span class="d_keyword">void</span> times(<span class="d_keyword">int</span> n, <span class="d_keyword">lazy</span> <span class="d_keyword">void</span> exp)
|
|
{
|
|
<span class="d_keyword">while</span> (n--)
|
|
exp();
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>prints to the console:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="console notranslate">0
|
|
1
|
|
2
|
|
−
|
|
3
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>A <span class="d_inlinecode donthyphenate notranslate">lazy</span> parameter cannot be an lvalue.</p>
|
|
<div class="blankline"></div>
|
|
<p>The underlying delegate of the <span class="d_inlinecode donthyphenate notranslate">lazy</span> parameter may be extracted
|
|
by using the <span class="d_inlinecode donthyphenate notranslate">&</span> operator:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> test(<span class="d_keyword">lazy</span> <span class="d_keyword">int</span> dg)
|
|
{
|
|
<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg_ = &dg;
|
|
<span class="d_keyword">assert</span>(dg_() == 7);
|
|
<span class="d_keyword">assert</span>(dg == dg_());
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">int</span> a = 7;
|
|
test(a);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>A <span class="d_inlinecode donthyphenate notranslate">lazy</span> parameter of type <span class="d_inlinecode donthyphenate notranslate">void</span> can accept an argument
|
|
of any type.</p>
|
|
<div class="blankline"></div>
|
|
<p>See Also: <a href="#lazy_variadic_functions">Lazy Variadic Functions</a></p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="function-default-args" href="#function-default-args">Default Arguments</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>Function parameter declarations can have default values:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> foo(<span class="d_keyword">int</span> x, <span class="d_keyword">int</span> y = 3)
|
|
{
|
|
...
|
|
}
|
|
...
|
|
foo(4); <span class="d_comment">// same as foo(4, 3);
|
|
</span></pre>
|
|
<div class="blankline"></div>
|
|
<p>Default parameters are resolved and semantically checked in the context of the
|
|
function declaration.</p>
|
|
<pre class="d_code notranslate"><span class="d_keyword">module</span> m;
|
|
<span class="d_keyword">private</span> <span class="d_keyword">immutable</span> <span class="d_keyword">int</span> b;
|
|
<span class="d_keyword">pure</span> <span class="d_keyword">void</span> g(<span class="d_keyword">int</span> a = b) {}
|
|
</pre>
|
|
<pre class="d_code notranslate"><span class="d_keyword">import</span> m;
|
|
<span class="d_keyword">int</span> b;
|
|
<span class="d_keyword">pure</span> <span class="d_keyword">void</span> f()
|
|
{
|
|
g(); <span class="d_comment">// ok, uses m.b
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>The attributes of the <a href="../spec/expression.html#AssignExpression"><i>AssignExpression</i></a> are applied where the default expression
|
|
is used.</p>
|
|
<pre class="d_code notranslate"><span class="d_keyword">module</span> m;
|
|
<span class="d_keyword">int</span> b;
|
|
<span class="d_keyword">pure</span> <span class="d_keyword">void</span> g(<span class="d_keyword">int</span> a = b) {}
|
|
</pre>
|
|
<pre class="d_code notranslate"><span class="d_keyword">import</span> m;
|
|
<span class="d_keyword">enum</span> <span class="d_keyword">int</span> b = 3;
|
|
<span class="d_keyword">pure</span> <span class="d_keyword">void</span> f()
|
|
{
|
|
g(); <span class="d_comment">// error, cannot access mutable global `m.b` in pure function
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>See also: function type aliases
|
|
<a href="../spec/declaration.html#alias-function">with default values</a>.</p>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="return-ref-parameters" href="#return-ref-parameters">Return Ref Parameters</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>Return ref parameters are used with
|
|
<a href="#ref-functions">ref functions</a> to ensure that the
|
|
returned reference will not outlive the matching argument's lifetime.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">ref</span> <span class="d_keyword">int</span> identity(<span class="d_keyword">return</span> <span class="d_keyword">ref</span> <span class="d_keyword">int</span> x) {
|
|
<span class="d_keyword">return</span> x; <span class="d_comment">// pass-through function that does nothing
|
|
</span>}
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> fun() {
|
|
<span class="d_keyword">int</span> x;
|
|
<span class="d_keyword">return</span> identity(x); <span class="d_comment">// Error: escaping reference to local variable x
|
|
</span>}
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> gun(<span class="d_keyword">return</span> <span class="d_keyword">ref</span> <span class="d_keyword">int</span> x) {
|
|
<span class="d_keyword">return</span> identity(x); <span class="d_comment">// OK
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<p>Returning the address of a <span class="d_inlinecode donthyphenate notranslate">ref</span> variable is also checked in <span class="d_inlinecode donthyphenate notranslate">@safe</span> code.</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span>* pluto(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> i) @safe
|
|
{
|
|
<span class="d_keyword">return</span> &i; <span class="d_comment">// error: returning &i escapes a reference to parameter i
|
|
</span>}
|
|
|
|
<span class="d_keyword">int</span>* mars(<span class="d_keyword">return</span> <span class="d_keyword">ref</span> <span class="d_keyword">int</span> i) @safe
|
|
{
|
|
<span class="d_keyword">return</span> &i; <span class="d_comment">// OK with -preview=dip1000
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="panel">If a function returns <span class="d_inlinecode donthyphenate notranslate">void</span>, and the first parameter is <span class="d_inlinecode donthyphenate notranslate">ref</span> or <span class="d_inlinecode donthyphenate notranslate">out</span>, then
|
|
all subsequent <span class="d_inlinecode donthyphenate notranslate">return ref</span> parameters are considered as being assigned to
|
|
the first parameter for lifetime checking.
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> f(<span class="d_keyword">ref</span> <span class="d_keyword">scope</span> <span class="d_keyword">int</span>* p, <span class="d_keyword">return</span> <span class="d_keyword">ref</span> <span class="d_keyword">int</span> i) @safe
|
|
{
|
|
p = &i; <span class="d_comment">// OK with -preview=dip1000
|
|
</span>}
|
|
|
|
<span class="d_keyword">void</span> main() @safe
|
|
{
|
|
<span class="d_keyword">int</span> i;
|
|
<span class="d_keyword">int</span>* p;
|
|
f(p, i); <span class="d_comment">// OK, lifetime of p is shorter than i
|
|
</span> *p = 5;
|
|
<span class="d_keyword">assert</span>(i == 5);
|
|
|
|
<span class="d_keyword">int</span> j;
|
|
<span class="d_comment">//f(p, j); // error, lifetime of p is longer than j
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
The <span class="d_inlinecode donthyphenate notranslate">this</span> reference parameter to a struct non-static member function is
|
|
considered the first parameter.
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> S
|
|
{
|
|
<span class="d_keyword">private</span> <span class="d_keyword">int</span>* p;
|
|
|
|
<span class="d_keyword">void</span> f(<span class="d_keyword">return</span> <span class="d_keyword">ref</span> <span class="d_keyword">int</span> i) <span class="d_keyword">scope</span> @safe
|
|
{
|
|
p = &i; <span class="d_comment">// OK with -preview=dip1000
|
|
</span> }
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main() @safe
|
|
{
|
|
<span class="d_keyword">int</span> i;
|
|
S s;
|
|
s.f(i); <span class="d_comment">// OK, lifetime of `s` is shorter than `i`
|
|
</span> *s.p = 2;
|
|
<span class="d_keyword">assert</span>(i == 2);
|
|
}
|
|
</pre>
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>If there are multiple <span class="d_inlinecode donthyphenate notranslate">return ref</span> parameters, the lifetime of the return
|
|
value is the smallest lifetime of the corresponding arguments.</p>
|
|
<div class="blankline"></div>
|
|
<p>Neither the type of the <span class="d_inlinecode donthyphenate notranslate">return ref</span> parameter(s) nor the type of the return
|
|
value is considered when determining the lifetime of the return value.</p>
|
|
<div class="blankline"></div>
|
|
<p>It is not an error if the return type does not contain any indirections.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> mercury(<span class="d_keyword">return</span> <span class="d_keyword">ref</span> <span class="d_keyword">int</span> i)
|
|
{
|
|
<span class="d_keyword">return</span> i; <span class="d_comment">// ok
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Template functions, auto functions, nested functions and <a href="../spec/expression.html#function_literals">lambdas</a>
|
|
can deduce the <span class="d_inlinecode donthyphenate notranslate">return</span> attribute.</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate">@safe:
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> templateFunction()(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> i)
|
|
{
|
|
<span class="d_keyword">return</span> i; <span class="d_comment">// ok
|
|
</span>}
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">auto</span> autoFunction(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> i)
|
|
{
|
|
<span class="d_keyword">return</span> i; <span class="d_comment">// ok
|
|
</span>}
|
|
|
|
<span class="d_keyword">void</span> uranus()
|
|
{
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> nestedFunction(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> i)
|
|
{
|
|
<span class="d_keyword">return</span> i; <span class="d_comment">// ok
|
|
</span> }
|
|
<span class="d_keyword">auto</span> lambdaFunction =
|
|
(<span class="d_keyword">ref</span> <span class="d_keyword">int</span> i)
|
|
{
|
|
<span class="d_keyword">return</span> &i; <span class="d_comment">// ok
|
|
</span> };
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h4><a class="anchor" title="Permalink to this section" id="struct-return-methods" href="#struct-return-methods">Struct Return Methods</a></h4>
|
|
<div class="blankline"></div>
|
|
<p>Struct non-static methods can be marked with the <span class="d_inlinecode donthyphenate notranslate">return</span> attribute to ensure a returned
|
|
reference will not outlive the struct instance. This is the same as the
|
|
<span class="d_inlinecode donthyphenate notranslate">return ref</span> method attribute.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> S
|
|
{
|
|
<span class="d_keyword">private</span> <span class="d_keyword">int</span> x;
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> get() <span class="d_keyword">return</span> { <span class="d_keyword">return</span> x; }
|
|
}
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> escape()
|
|
{
|
|
S s;
|
|
<span class="d_keyword">return</span> s.get(); <span class="d_comment">// Error: escaping reference to local variable s
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<p>The hidden <span class="d_inlinecode donthyphenate notranslate">this</span> ref-parameter then becomes <span class="d_inlinecode donthyphenate notranslate">return ref</span>.</p>
|
|
<div class="blankline"></div>
|
|
<p>The <span class="d_inlinecode donthyphenate notranslate">return</span> attribute can also be used to limit
|
|
the lifetime of the returned value, even when the method is not <span class="d_inlinecode donthyphenate notranslate">ref</span>:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> S
|
|
{
|
|
<span class="d_keyword">private</span> <span class="d_keyword">int</span> i;
|
|
<span class="d_keyword">int</span>* get() <span class="d_keyword">return</span> @safe => &i;
|
|
}
|
|
|
|
<span class="d_keyword">void</span> f() @safe
|
|
{
|
|
<span class="d_keyword">int</span>* p;
|
|
{
|
|
S s;
|
|
<span class="d_keyword">int</span> *q = s.get(); <span class="d_comment">// OK, q has shorter lifetime than s
|
|
</span> p = s.get(); <span class="d_comment">// error, p has longer lifetime
|
|
</span> p = (<span class="d_keyword">new</span> S).get(); <span class="d_comment">// OK, heap allocated S
|
|
</span> }
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="scope-parameters" href="#scope-parameters">Scope Parameters</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>A <span class="d_inlinecode donthyphenate notranslate">scope</span> parameter of reference type must not escape the function call
|
|
(e.g. by being assigned to a global variable). It has no effect for non-reference types.
|
|
<span class="d_inlinecode donthyphenate notranslate">scope</span> escape analysis is only done for <span class="d_inlinecode donthyphenate notranslate">@safe</span> functions. For other functions <span class="d_inlinecode donthyphenate notranslate">scope</span>
|
|
semantics must be manually enforced.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> <span class="d_inlinecode donthyphenate notranslate">@safe</span> escape analysis is only done with the <span class="d_inlinecode donthyphenate notranslate">-preview=dip1000</span> switch.</div>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">@safe:
|
|
|
|
<span class="d_keyword">int</span>* gp;
|
|
<span class="d_keyword">void</span> thorin(<span class="d_keyword">scope</span> <span class="d_keyword">int</span>*);
|
|
<span class="d_keyword">void</span> gloin(<span class="d_keyword">int</span>*);
|
|
<span class="d_keyword">int</span>* balin(<span class="d_keyword">scope</span> <span class="d_keyword">int</span>* q, <span class="d_keyword">int</span>* r)
|
|
{
|
|
gp = q; <span class="d_comment">// error, q escapes to global gp
|
|
</span> gp = r; <span class="d_comment">// ok
|
|
</span>
|
|
thorin(q); <span class="d_comment">// ok, q does not escape thorin()
|
|
</span> thorin(r); <span class="d_comment">// ok
|
|
</span>
|
|
gloin(q); <span class="d_comment">// error, gloin() escapes q
|
|
</span> gloin(r); <span class="d_comment">// ok that gloin() escapes r
|
|
</span>
|
|
<span class="d_keyword">return</span> q; <span class="d_comment">// error, cannot return 'scope' q
|
|
</span> <span class="d_keyword">return</span> r; <span class="d_comment">// ok
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> As a <span class="d_inlinecode donthyphenate notranslate">scope</span> parameter must not escape, the compiler can potentially avoid heap-allocating a
|
|
unique argument to a <span class="d_inlinecode donthyphenate notranslate">scope</span> parameter. Due to this, passing an array literal, delegate
|
|
literal or a <a href="../spec/expression.html#NewExpression"><i>NewExpression</i></a> to a scope parameter may be allowed in a
|
|
<span class="d_inlinecode donthyphenate notranslate">@nogc</span> context.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="return-scope-parameters" href="#return-scope-parameters">Return Scope Parameters</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>Parameters marked as <span class="d_inlinecode donthyphenate notranslate">return scope</span> that contain indirections
|
|
can only escape those indirections via the function's return value.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">@safe:
|
|
|
|
<span class="d_keyword">int</span>* gp;
|
|
<span class="d_keyword">void</span> thorin(<span class="d_keyword">scope</span> <span class="d_keyword">int</span>*);
|
|
<span class="d_keyword">void</span> gloin(<span class="d_keyword">int</span>*);
|
|
<span class="d_keyword">int</span>* balin(<span class="d_keyword">return</span> <span class="d_keyword">scope</span> <span class="d_keyword">int</span>* p)
|
|
{
|
|
gp = p; <span class="d_comment">// error, p escapes to global gp
|
|
</span> thorin(p); <span class="d_comment">// ok, p does not escape thorin()
|
|
</span> gloin(p); <span class="d_comment">// error, gloin() escapes p
|
|
</span> <span class="d_keyword">return</span> p; <span class="d_comment">// ok
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Class references are considered pointers that are subject to <span class="d_inlinecode donthyphenate notranslate">scope</span>.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">@safe:
|
|
|
|
<span class="d_keyword">class</span> C { }
|
|
C gp;
|
|
<span class="d_keyword">void</span> thorin(<span class="d_keyword">scope</span> C);
|
|
<span class="d_keyword">void</span> gloin(C);
|
|
C balin(<span class="d_keyword">return</span> <span class="d_keyword">scope</span> C p, <span class="d_keyword">scope</span> C q, C r)
|
|
{
|
|
gp = p; <span class="d_comment">// error, p escapes to global gp
|
|
</span> gp = q; <span class="d_comment">// error, q escapes to global gp
|
|
</span> gp = r; <span class="d_comment">// ok
|
|
</span>
|
|
thorin(p); <span class="d_comment">// ok, p does not escape thorin()
|
|
</span> thorin(q); <span class="d_comment">// ok
|
|
</span> thorin(r); <span class="d_comment">// ok
|
|
</span>
|
|
gloin(p); <span class="d_comment">// error, gloin() escapes p
|
|
</span> gloin(q); <span class="d_comment">// error, gloin() escapes q
|
|
</span> gloin(r); <span class="d_comment">// ok that gloin() escapes r
|
|
</span>
|
|
<span class="d_keyword">return</span> p; <span class="d_comment">// ok
|
|
</span> <span class="d_keyword">return</span> q; <span class="d_comment">// error, cannot return 'scope' q
|
|
</span> <span class="d_keyword">return</span> r; <span class="d_comment">// ok
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p><span class="d_inlinecode donthyphenate notranslate">return scope</span> can be applied to the <span class="d_inlinecode donthyphenate notranslate">this</span> of class and interface member functions.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> C
|
|
{
|
|
C bofur() <span class="d_keyword">return</span> <span class="d_keyword">scope</span> { <span class="d_keyword">return</span> <span class="d_keyword">this</span>; }
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Template functions, auto functions, nested functions and
|
|
<a href="../spec/expression.html#function_literals">lambdas</a> can deduce
|
|
the <span class="d_inlinecode donthyphenate notranslate">return scope</span> attribute.</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="ref-return-scope-parameters" href="#ref-return-scope-parameters">Ref Return Scope Parameters</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>It is not possible to have both <span class="d_inlinecode donthyphenate notranslate">return ref</span> and <span class="d_inlinecode donthyphenate notranslate">return scope</span> semantics
|
|
for the same parameter.
|
|
When a parameter is passed by <span class="d_inlinecode donthyphenate notranslate">ref</span> and has both the <span class="d_inlinecode donthyphenate notranslate">return</span> and <span class="d_inlinecode donthyphenate notranslate">scope</span> storage classes,
|
|
it gets <a href="#return-scope-parameters"><span class="d_inlinecode donthyphenate notranslate">return scope</span></a> semantics if and only if the <span class="d_inlinecode donthyphenate notranslate">return</span> and <span class="d_inlinecode donthyphenate notranslate">scope</span>
|
|
keywords appear adjacent to each other, in that order.
|
|
Specifying a <span class="d_inlinecode donthyphenate notranslate">return ref</span> and <span class="d_inlinecode donthyphenate notranslate">scope</span> parameter enables returning a reference to a scope pointer.
|
|
In all other cases, the parameter has <a href="#return-ref-parameters"><span class="d_inlinecode donthyphenate notranslate">return ref</span></a> semantics
|
|
and regular <a href="#scope-parameters"><span class="d_inlinecode donthyphenate notranslate">scope</span></a> semantics.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">U xerxes( <span class="d_keyword">ref</span> <span class="d_keyword">return</span> <span class="d_keyword">scope</span> V v) <span class="d_comment">// (1) ref and return scope
|
|
</span>U sargon(<span class="d_keyword">return</span> <span class="d_keyword">ref</span> <span class="d_keyword">scope</span> V v) <span class="d_comment">// (2) return ref and scope
|
|
</span>
|
|
<span class="d_keyword">struct</span> S
|
|
{
|
|
<span class="d_comment">// note: in struct member functions, the implicit `this` parameter
|
|
</span> <span class="d_comment">// is passed by `ref`
|
|
</span>
|
|
U xerxes() <span class="d_keyword">return</span> <span class="d_keyword">scope</span>; <span class="d_comment">// return scope
|
|
</span> U sargon() <span class="d_keyword">scope</span> <span class="d_keyword">return</span>; <span class="d_comment">// return ref, `return` comes after `scope`
|
|
</span> U xerxes() <span class="d_keyword">return</span> <span class="d_keyword">const</span> <span class="d_keyword">scope</span>; <span class="d_comment">// return ref, `return` and `scope` are not adjacent
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Example of combinations of <span class="d_inlinecode donthyphenate notranslate">return scope</span>, <span class="d_inlinecode donthyphenate notranslate">return ref</span>, and <span class="d_inlinecode donthyphenate notranslate">scope</span> semantics:</p>
|
|
<pre class="d_code notranslate">@safe:
|
|
|
|
<span class="d_keyword">int</span>* globalPtr;
|
|
|
|
<span class="d_keyword">struct</span> S
|
|
{
|
|
<span class="d_keyword">int</span> val;
|
|
<span class="d_keyword">int</span>* ptr;
|
|
|
|
<span class="d_keyword">this</span>(<span class="d_keyword">return</span> <span class="d_keyword">scope</span> <span class="d_keyword">ref</span> <span class="d_keyword">int</span>* p) { ptr = p; }
|
|
|
|
<span class="d_comment">// note: `this` is passed by `ref` in structs
|
|
</span>
|
|
<span class="d_keyword">int</span>* retRefA() <span class="d_keyword">scope</span> <span class="d_keyword">return</span> <span class="d_comment">// return-ref, scope
|
|
</span> {
|
|
globalPtr = <span class="d_keyword">this</span>.ptr; <span class="d_comment">// disallowed, `this` is `scope`
|
|
</span> <span class="d_keyword">return</span> &<span class="d_keyword">this</span>.val; <span class="d_comment">// allowed, `return` means `return ref`
|
|
</span> }
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> retRefB() <span class="d_keyword">scope</span> <span class="d_keyword">return</span> <span class="d_comment">// return-ref, scope
|
|
</span> {
|
|
globalPtr = <span class="d_keyword">this</span>.ptr; <span class="d_comment">// disallowed, `this` is `scope`
|
|
</span> <span class="d_keyword">return</span> <span class="d_keyword">this</span>.val; <span class="d_comment">// allowed, `return` means `return ref`
|
|
</span> }
|
|
|
|
<span class="d_keyword">int</span>* retScopeA() <span class="d_keyword">return</span> <span class="d_keyword">scope</span> <span class="d_comment">// ref, return-scope
|
|
</span> {
|
|
<span class="d_keyword">return</span> &<span class="d_keyword">this</span>.val; <span class="d_comment">// disallowed, escaping a reference to `this`
|
|
</span> <span class="d_keyword">return</span> <span class="d_keyword">this</span>.ptr; <span class="d_comment">// allowed, returning a `return scope` pointer
|
|
</span> }
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> retScopeB() <span class="d_keyword">return</span> <span class="d_keyword">scope</span> <span class="d_comment">// ref, return-scope
|
|
</span> {
|
|
<span class="d_keyword">return</span> <span class="d_keyword">this</span>.val; <span class="d_comment">// disallowed, escaping a reference to `this`
|
|
</span> <span class="d_keyword">return</span> *<span class="d_keyword">this</span>.ptr; <span class="d_comment">// allowed, returning a `return scope` pointer
|
|
</span> }
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span>* retRefScopeC() <span class="d_keyword">scope</span> <span class="d_keyword">return</span> <span class="d_comment">// return-ref, scope
|
|
</span> {
|
|
<span class="d_keyword">return</span> <span class="d_keyword">this</span>.ptr; <span class="d_comment">// allowed, returning a reference to a scope pointer
|
|
</span> }
|
|
}
|
|
|
|
<span class="d_keyword">int</span>* retRefA(<span class="d_keyword">return</span> <span class="d_keyword">ref</span> <span class="d_keyword">scope</span> S s)
|
|
{
|
|
globalPtr = s.ptr; <span class="d_comment">// disallowed, `s` is `scope`
|
|
</span> <span class="d_keyword">return</span> &s.val; <span class="d_comment">// allowed, returning a reference to `return ref s`
|
|
</span>}
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> retRefB(<span class="d_keyword">return</span> <span class="d_keyword">ref</span> <span class="d_keyword">scope</span> S s)
|
|
{
|
|
globalPtr = s.ptr; <span class="d_comment">// disallowed, `s` is `scope`
|
|
</span> <span class="d_keyword">return</span> s.val;
|
|
}
|
|
|
|
<span class="d_keyword">int</span>* retScopeA(<span class="d_keyword">ref</span> <span class="d_keyword">return</span> <span class="d_keyword">scope</span> S s)
|
|
{
|
|
<span class="d_keyword">return</span> &s.val; <span class="d_comment">// disallowed, escaping a reference to `s`
|
|
</span> <span class="d_keyword">return</span> s.ptr; <span class="d_comment">// allowed, returning a `return scope` pointer
|
|
</span>}
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> retScopeB(<span class="d_keyword">ref</span> <span class="d_keyword">return</span> <span class="d_keyword">scope</span> S s)
|
|
{
|
|
<span class="d_keyword">return</span> s.val; <span class="d_comment">// disallowed, escaping a reference to `s`
|
|
</span> <span class="d_keyword">return</span> *s.ptr; <span class="d_comment">// allowed, returning a `return scope` pointer
|
|
</span>}
|
|
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span>* retRefScopeC(<span class="d_keyword">return</span> <span class="d_keyword">ref</span> <span class="d_keyword">scope</span> <span class="d_keyword">int</span>* p)
|
|
{
|
|
<span class="d_keyword">return</span> p; <span class="d_comment">// allowed, returning a reference to a scope pointer
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="pure-scope-inference" href="#pure-scope-inference">Inferred <span class="d_inlinecode donthyphenate notranslate">scope</span> parameters in <span class="d_inlinecode donthyphenate notranslate">pure</span> functions</a></h3>
|
|
<div class="blankline"></div>
|
|
When a parameter is not marked or inferred <span class="d_inlinecode donthyphenate notranslate">scope</span>, it may still be <span class="d_inlinecode donthyphenate notranslate">@safe</span> to assign it a <span class="d_inlinecode donthyphenate notranslate">scope</span> pointer in a function call.
|
|
The following conditions need to be met:
|
|
<div class="blankline"></div>
|
|
<ul> <li>The function is <a href="#pure-functions"><span class="d_inlinecode donthyphenate notranslate">pure</span></a>, hence the argument cannot be assigned to a global variable</li>
|
|
<li>The function is <a href="#nothrow-functions"><span class="d_inlinecode donthyphenate notranslate">nothrow</span></a>, hence the argument cannot be assigned to a thrown <span class="d_inlinecode donthyphenate notranslate">Exception</span> object</li>
|
|
<li>None of the other parameters have mutable indirections, hence the argument cannot be assigned to a longer-lived variable</li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
Then, the parameter is still treated as <span class="d_inlinecode donthyphenate notranslate">scope</span> or <span class="d_inlinecode donthyphenate notranslate">return scope</span> depending on the return type of the function:
|
|
<ul> <li>If the function returns by <span class="d_inlinecode donthyphenate notranslate">ref</span> or has a return type that contains pointers, the argument could be returned, so it is treated as <span class="d_inlinecode donthyphenate notranslate">return scope</span></li>
|
|
<li>Otherwise, the argument cannot escape the function, so it is treated as <span class="d_inlinecode donthyphenate notranslate">scope</span></li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">@safe:
|
|
|
|
<span class="d_keyword">int</span> dereference(<span class="d_keyword">int</span>* x) <span class="d_keyword">pure</span> <span class="d_keyword">nothrow</span>;
|
|
<span class="d_keyword">int</span>* identity(<span class="d_keyword">int</span>* x) <span class="d_keyword">pure</span> <span class="d_keyword">nothrow</span>;
|
|
<span class="d_keyword">int</span>* identityThrow(<span class="d_keyword">int</span>* x) <span class="d_keyword">pure</span>;
|
|
<span class="d_keyword">void</span> assignToRef(<span class="d_keyword">int</span>* x, <span class="d_keyword">ref</span> <span class="d_keyword">int</span>* escapeHatch) <span class="d_keyword">pure</span> <span class="d_keyword">nothrow</span>;
|
|
<span class="d_keyword">void</span> assignToPtr(<span class="d_keyword">int</span>* x, <span class="d_keyword">int</span>** escapeHatch) <span class="d_keyword">pure</span> <span class="d_keyword">nothrow</span>;
|
|
<span class="d_keyword">void</span> cannotAssignTo(<span class="d_keyword">int</span>* x, <span class="d_keyword">const</span> <span class="d_keyword">ref</span> <span class="d_keyword">int</span>* noEscapeHatch) <span class="d_keyword">pure</span> <span class="d_keyword">nothrow</span>;
|
|
|
|
<span class="d_keyword">int</span>* globalPtr;
|
|
|
|
<span class="d_keyword">int</span>* test(<span class="d_keyword">scope</span> <span class="d_keyword">int</span>* ptr)
|
|
{
|
|
<span class="d_keyword">int</span> result = dereference(ptr); <span class="d_comment">// allowed, treated as `scope`
|
|
</span> <span class="d_keyword">int</span>* ptr2 = identity(ptr); <span class="d_comment">// allowed, treated as `return scope`
|
|
</span> <span class="d_keyword">int</span>* ptr3 = identityThrow(ptr); <span class="d_comment">// not allowed, can throw an `Exception`
|
|
</span> assignToRef(ptr, globalPtr); <span class="d_comment">// not allowed, mutable second parameter
|
|
</span> assignToPtr(ptr, &globalPtr); <span class="d_comment">// not allowed, mutable second parameter
|
|
</span> cannotAssignTo(ptr, globalPtr); <span class="d_comment">// allowed
|
|
</span>
|
|
<span class="d_keyword">return</span> ptr2; <span class="d_comment">// not allowed, ptr2 is inferred `scope` now
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="udas-parameters" href="#udas-parameters">User-Defined Attributes for Parameters</a></h3>
|
|
<div class="blankline"></div>
|
|
See also: <a href="../spec/attribute.html#UserDefinedAttribute"><i>User-Defined Attributes</i></a>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="unpacking-parameters" href="#unpacking-parameters">Unpacking Parameters</a></h3>
|
|
<div class="blankline"></div>
|
|
<pre class="bnf notranslate"><a id="ParameterTuplePattern"><span class="gname">ParameterTuplePattern</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">(</span> <a href="#ParameterTupleComponents"><i>ParameterTupleComponents</i></a> <span class="d_inlinecode donthyphenate notranslate">)</span>
|
|
<div class="blankline"></div>
|
|
<a id="ParameterTupleComponents"><span class="gname">ParameterTupleComponents</span></a>:
|
|
<a href="#ParameterTupleComponent"><i>ParameterTupleComponent</i></a> <span class="d_inlinecode donthyphenate notranslate">,</span>
|
|
<a href="#ParameterTupleComponent"><i>ParameterTupleComponent</i></a> <span class="d_inlinecode donthyphenate notranslate">,</span> <a href="#ParameterTupleComponent"><i>ParameterTupleComponent</i></a>
|
|
<a href="#ParameterTupleComponent"><i>ParameterTupleComponent</i></a> <span class="d_inlinecode donthyphenate notranslate">,</span> <a href="#ParameterTupleComponents"><i>ParameterTupleComponents</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="ParameterTupleComponent"><span class="gname">ParameterTupleComponent</span></a>:
|
|
<a href="#ParameterAttributes"><i>ParameterAttributes</i></a><sub>opt</sub> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a>
|
|
<a href="#ParameterAttributes"><i>ParameterAttributes</i></a><sub>opt</sub> <a href="../spec/type.html#BasicType"><i>BasicType</i></a> <a href="../spec/type.html#TypeSuffixes"><i>TypeSuffixes</i></a><sub>opt</sub> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a>
|
|
<a href="#ParameterAttributes"><i>ParameterAttributes</i></a><sub>opt</sub> <a href="#ParameterTuplePattern"><i>ParameterTuplePattern</i></a>
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>A <a href="../spec/expression.html#function-literal-alias">function literal template</a>
|
|
with untyped <em>ParameterTupleComponents</em> is supported. The corresponding function
|
|
argument will be unpacked into component variables:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">import</span> std.typecons : tuple;
|
|
|
|
<span class="d_keyword">alias</span> dg = ((x, y), z) => writeln(x, <span class="d_string">" "</span>, y, <span class="d_string">" "</span>, z);
|
|
dg(tuple(1, 2), 3); <span class="d_comment">// "1 2 3\n"
|
|
</span></pre>
|
|
<div class="spec-boxes note"><b>Note:</b> A typed <em>ParameterTupleComponent</em> is parsed, but cannot be supported without
|
|
compiler-recognised tuple types.</div>
|
|
<div class="blankline"></div>
|
|
<p><span class="d_inlinecode donthyphenate notranslate">((x, y), z) { ... }</span> is lowered to <span class="d_inlinecode donthyphenate notranslate">(__arg0, z) { auto (x, y) = __arg0; ... }</span>.
|
|
In general, lowering preserves and copies storage classes from
|
|
the parameter to an <a href="../spec/declaration.html#unpacking-declarations"> unpacking declaration</a> in the function body.</p>
|
|
|
|
<ul><li>The <span class="d_inlinecode donthyphenate notranslate">ref</span> storage class is copied outwards, e.g., <span class="d_inlinecode donthyphenate notranslate">((ref a, b), c) { ... }</span> gets lowered to
|
|
<span class="d_inlinecode donthyphenate notranslate">(ref __arg0, c) { (ref a, auto b) = __arg0; ... }</span>.</li>
|
|
<li><span class="d_inlinecode donthyphenate notranslate">out</span> can be applied to the whole parameter, but not to individual components.</li>
|
|
<li><span class="d_inlinecode donthyphenate notranslate">auto ref</span> and <span class="d_inlinecode donthyphenate notranslate">lazy</span> cannot be applied to an unpacking parameter.
|
|
</li>
|
|
</ul>
|
|
<div class="spec-boxes note"><b>Note:</b> <span class="d_inlinecode donthyphenate notranslate">out</span> unpacking parameters are not supported by the current implementation, but may be added at a future date.</div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="variadic" href="#variadic">Variadic Functions</a></h3>
|
|
<div class="blankline"></div>
|
|
<p><i>Variadic Functions</i> take a variable number of arguments.
|
|
There are three forms:</p>
|
|
<div class="blankline"></div>
|
|
<ol> <li><a href="#c_style_variadic_functions">C-style variadic functions</a></li>
|
|
<li><a href="#d_style_variadic_functions">Variadic functions with type info</a></li>
|
|
<li><a href="#typesafe_variadic_functions">Typesafe variadic functions</a></li>
|
|
</ol>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h4><a class="anchor" title="Permalink to this section" id="c_style_variadic_functions" href="#c_style_variadic_functions">C-style Variadic Functions</a></h4>
|
|
<div class="blankline"></div>
|
|
<p>A C-style variadic function is declared with
|
|
a parameter <span class="d_inlinecode donthyphenate notranslate">...</span> as the last function parameter.
|
|
It has non-D linkage, such as <span class="d_inlinecode donthyphenate notranslate">extern (C)</span>.</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">extern</span> (C) <span class="d_keyword">void</span> dry(<span class="d_keyword">int</span> x, <span class="d_keyword">int</span> y, ...); <span class="d_comment">// C-style Variadic Function
|
|
</span>
|
|
<span class="d_keyword">void</span> spin()
|
|
{
|
|
dry(3, 4); <span class="d_comment">// ok, no variadic arguments
|
|
</span> dry(3, 4, 6.8); <span class="d_comment">// ok, one variadic argument
|
|
</span> <span class="d_comment">//dry(2); // error, no argument for parameter y
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>There must be at least one non-variadic parameter declared.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">extern</span> (C) <span class="d_keyword">int</span> def(...); <span class="d_comment">// error, must have at least one parameter
|
|
</span></pre>
|
|
<div class="blankline"></div>
|
|
<p> C-style variadic functions match the C calling convention for
|
|
variadic functions, and can call C Standard library
|
|
functions like <a href="../phobos/core_stdc_stdio.html#.printf"><span class="d_inlinecode donthyphenate notranslate">printf</span></a>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">extern</span> (C) <span class="d_keyword">int</span> printf(<span class="d_keyword">const</span>(<span class="d_keyword">char</span>)*, ...);
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
printf(<span class="d_string">"hello world\n"</span>);
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>C-style variadic functions cannot be marked as <span class="d_inlinecode donthyphenate notranslate">@safe</span>.</p>
|
|
<div class="blankline"></div>
|
|
<p>To access the variadic arguments,
|
|
import the standard library
|
|
module <a href="../phobos/core_stdc_stdarg.html"><span class="d_inlinecode donthyphenate notranslate">core.stdc.stdarg</span></a>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">import</span> core.stdc.stdarg;
|
|
<span class="d_keyword">import</span> std.stdio;
|
|
|
|
<span class="d_keyword">extern</span> (C) <span class="d_keyword">void</span> rinse(<span class="d_keyword">int</span> x, <span class="d_keyword">int</span> y, ...)
|
|
{
|
|
va_list args;
|
|
va_start(args, y); <span class="d_comment">// y is the last named parameter
|
|
</span> <span class="d_keyword">int</span> z;
|
|
va_arg(args, z); <span class="d_comment">// z is set to 5
|
|
</span> va_end(args);
|
|
writeln(z);
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
rinse(3, 4, 5); <span class="d_comment">// first variadic argument is 5
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h4><a class="anchor" title="Permalink to this section" id="d_style_variadic_functions" href="#d_style_variadic_functions">D-style Variadic Functions</a></h4>
|
|
<div class="blankline"></div>
|
|
<p>D-style variadic functions have D linkage and <span class="d_inlinecode donthyphenate notranslate">...</span> as the last
|
|
parameter.</p>
|
|
<div class="blankline"></div>
|
|
<p><span class="d_inlinecode donthyphenate notranslate">...</span> can be the only parameter.</p>
|
|
<div class="blankline"></div>
|
|
<p>If there are parameters preceding the <span class="d_inlinecode donthyphenate notranslate">...</span> parameter, there
|
|
must be a comma separating them from the <span class="d_inlinecode donthyphenate notranslate">...</span>.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> If the comma is omitted, it is a
|
|
<a href="#typesafe_variadic_functions">Typesafe Variadic Function</a>.</div>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> abc(<span class="d_keyword">char</span> c, ...); <span class="d_comment">// one required parameter: c
|
|
</span><span class="d_keyword">int</span> def(...); <span class="d_comment">// no required parameters
|
|
</span><span class="d_keyword">int</span> ghi(<span class="d_keyword">int</span> i ...); <span class="d_comment">// a typesafe variadic function
|
|
</span><span class="d_comment">//int boo(, ...); // error
|
|
</span></pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p><span class="d_inlinecode donthyphenate notranslate">va_list _argptr</span> is declared & initialized as a pointer to the
|
|
first of the variadic arguments. To access the variadic arguments,
|
|
import <a href="../phobos/core_vararg.html"><span class="d_inlinecode donthyphenate notranslate">core.vararg</span></a> and
|
|
use <span class="d_inlinecode donthyphenate notranslate">_argptr</span> in conjunction with <a href="../phobos/core_stdc_stdarg.html#.va_arg"><span class="d_inlinecode donthyphenate notranslate">va_arg</span></a>:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">import</span> core.vararg;
|
|
<span class="d_keyword">import</span> std.stdio;
|
|
|
|
@system <span class="d_keyword">void</span> foo(<span class="d_keyword">int</span> x, <span class="d_keyword">int</span> y, ...)
|
|
{
|
|
<span class="d_keyword">int</span> z = va_arg!<span class="d_keyword">int</span>(_argptr); <span class="d_comment">// z is set to 5 and _argptr is advanced
|
|
</span> <span class="d_comment">// to the next argument
|
|
</span> writeln(z); <span class="d_comment">// 5
|
|
</span>}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
foo(3, 4, 5); <span class="d_comment">// first variadic argument is 5
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<p>A hidden function parameter <span class="d_inlinecode donthyphenate notranslate">TypeInfo[] _arguments</span> gives
|
|
the number of arguments and the <a href="../phobos/object.html#.TypeInfo""><span class="d_inlinecode donthyphenate notranslate">TypeInfo</span></a> of each argument's
|
|
type. This enables type safety to be manually checked at run time by
|
|
comparing each element against a <a href="../spec/expression.html#typeid_expressions"> <span class="d_inlinecode donthyphenate notranslate">typeid(</span><em>Type</em><span class="d_inlinecode donthyphenate notranslate">)</span></a> expression.</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">import</span> std.stdio;
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
Foo f = <span class="d_keyword">new</span> Foo();
|
|
Bar b = <span class="d_keyword">new</span> Bar();
|
|
|
|
writefln(<span class="d_string">"%s"</span>, f);
|
|
printargs(1, 2, 3L, 4.5, f, b);
|
|
}
|
|
|
|
<span class="d_keyword">class</span> Foo { <span class="d_keyword">int</span> x = 3; }
|
|
<span class="d_keyword">class</span> Bar { <span class="d_keyword">long</span> y = 4; }
|
|
|
|
<span class="d_keyword">import</span> core.vararg;
|
|
|
|
@system <span class="d_keyword">void</span> printargs(<span class="d_keyword">int</span> x, ...)
|
|
{
|
|
writefln(<span class="d_string">"%d arguments"</span>, _arguments.length);
|
|
<span class="d_keyword">for</span> (<span class="d_keyword">int</span> i = 0; i < _arguments.length; i++)
|
|
{
|
|
writeln(_arguments[i]);
|
|
|
|
<span class="d_keyword">if</span> (_arguments[i] == <span class="d_keyword">typeid</span>(<span class="d_keyword">int</span>))
|
|
{
|
|
<span class="d_keyword">int</span> j = va_arg!(<span class="d_keyword">int</span>)(_argptr);
|
|
writefln(<span class="d_string">"\t%d"</span>, j);
|
|
}
|
|
<span class="d_keyword">else</span> <span class="d_keyword">if</span> (_arguments[i] == <span class="d_keyword">typeid</span>(<span class="d_keyword">long</span>))
|
|
{
|
|
<span class="d_keyword">long</span> j = va_arg!(<span class="d_keyword">long</span>)(_argptr);
|
|
writefln(<span class="d_string">"\t%d"</span>, j);
|
|
}
|
|
<span class="d_keyword">else</span> <span class="d_keyword">if</span> (_arguments[i] == <span class="d_keyword">typeid</span>(<span class="d_keyword">double</span>))
|
|
{
|
|
<span class="d_keyword">double</span> d = va_arg!(<span class="d_keyword">double</span>)(_argptr);
|
|
writefln(<span class="d_string">"\t%g"</span>, d);
|
|
}
|
|
<span class="d_keyword">else</span> <span class="d_keyword">if</span> (_arguments[i] == <span class="d_keyword">typeid</span>(Foo))
|
|
{
|
|
Foo f = va_arg!(Foo)(_argptr);
|
|
writefln(<span class="d_string">"\t%d"</span>, f.x);
|
|
}
|
|
<span class="d_keyword">else</span> <span class="d_keyword">if</span> (_arguments[i] == <span class="d_keyword">typeid</span>(Bar))
|
|
{
|
|
Bar b = va_arg!(Bar)(_argptr);
|
|
writefln(<span class="d_string">"\t%d"</span>, b.y);
|
|
}
|
|
<span class="d_keyword">else</span>
|
|
<span class="d_keyword">assert</span>(0);
|
|
}
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
which prints:
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">0x00870FE0
|
|
5 arguments
|
|
<span class="d_keyword">int</span>
|
|
2
|
|
<span class="d_keyword">long</span>
|
|
3
|
|
<span class="d_keyword">double</span>
|
|
4.5
|
|
Foo
|
|
3
|
|
Bar
|
|
4
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>D-style variadic functions cannot be marked as <span class="d_inlinecode donthyphenate notranslate">@safe</span> (if
|
|
they call <span class="d_inlinecode donthyphenate notranslate">va_arg</span>).</p>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h4><a class="anchor" title="Permalink to this section" id="typesafe_variadic_functions" href="#typesafe_variadic_functions">Typesafe Variadic Functions</a></h4>
|
|
<div class="blankline"></div>
|
|
<p>A typesafe variadic function has D linkage and a variadic
|
|
parameter, which is typically an array followed by <span class="d_inlinecode donthyphenate notranslate">...</span>.
|
|
The variadic parameter must be the last one. When passing component
|
|
arguments (e.g. array elements), the variadic parameter is
|
|
implicitly constructed from the given arguments.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>A dynamic array variadic parameter accepts either a
|
|
dynamic array argument or any number of arguments, each of
|
|
which must implicitly convert to the array element type:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> sum(<span class="d_keyword">int</span>[] ar ...) <span class="d_comment">// typesafe variadic function
|
|
</span>{
|
|
<span class="d_keyword">int</span> s;
|
|
<span class="d_keyword">foreach</span> (<span class="d_keyword">int</span> x; ar)
|
|
s += x;
|
|
<span class="d_keyword">return</span> s;
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">assert</span>(sum(1, 2, 3) == 6);
|
|
<span class="d_keyword">assert</span>(sum() == 0);
|
|
|
|
<span class="d_keyword">int</span>[3] ii = [4, 5, 6];
|
|
<span class="d_keyword">assert</span>(sum(ii) == 15);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>A static array variadic parameter accepts either a static
|
|
array argument or a fixed number of arguments which matches
|
|
the array dimension:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> sum(<span class="d_keyword">int</span>[3] ar ...) <span class="d_comment">// typesafe variadic function
|
|
</span>{
|
|
<span class="d_keyword">int</span> s;
|
|
<span class="d_keyword">foreach</span> (<span class="d_keyword">int</span> x; ar)
|
|
s += x;
|
|
<span class="d_keyword">return</span> s;
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">int</span> i;
|
|
<span class="d_comment">//i = sum(2, 3); // error, need 3 values for array
|
|
</span> i = sum(1, 2, 3);
|
|
<span class="d_keyword">assert</span>(i == 6);
|
|
|
|
<span class="d_keyword">int</span>[3] ii = [4, 5, 6];
|
|
i = sum(ii);
|
|
<span class="d_keyword">assert</span>(i == 15);
|
|
|
|
<span class="d_keyword">int</span>[] jj = ii;
|
|
<span class="d_comment">//i = sum(jj); // error, type mismatch
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="keyval Deprecated"><span class="key keyDeprecated">Deprecated:</span> <div class="val valDeprecated">For class objects:</div></div>
|
|
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> tesla(<span class="d_keyword">int</span> x, C c ...)
|
|
{
|
|
<span class="d_keyword">return</span> x + c.x;
|
|
}
|
|
|
|
<span class="d_keyword">class</span> C
|
|
{
|
|
<span class="d_keyword">int</span> x;
|
|
string s;
|
|
|
|
<span class="d_keyword">this</span>(<span class="d_keyword">int</span> x, string s)
|
|
{
|
|
<span class="d_keyword">this</span>.x = x;
|
|
<span class="d_keyword">this</span>.s = s;
|
|
}
|
|
}
|
|
|
|
<span class="d_keyword">void</span> edison()
|
|
{
|
|
C g = <span class="d_keyword">new</span> C(3, <span class="d_string">"abc"</span>);
|
|
tesla(1, c); <span class="d_comment">// ok, since c is an instance of C
|
|
</span> tesla(1, 4, <span class="d_string">"def"</span>); <span class="d_comment">// ok
|
|
</span> tesla(1, 5); <span class="d_comment">// error, no matching constructor for C
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>The lifetime of the variadic class object or array
|
|
instance ends at the end of the function.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">C orville(C c ...)
|
|
{
|
|
<span class="d_keyword">return</span> c; <span class="d_comment">// error, c instance contents invalid after return
|
|
</span>}
|
|
|
|
<span class="d_keyword">int</span>[] wilbur(<span class="d_keyword">int</span>[] a ...)
|
|
{
|
|
<span class="d_keyword">return</span> a; <span class="d_comment">// error, array contents invalid after return
|
|
</span> <span class="d_keyword">return</span> a[0..1]; <span class="d_comment">// error, array contents invalid after return
|
|
</span> <span class="d_keyword">return</span> a.dup; <span class="d_comment">// ok, since copy is made
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> the variadic object or array instance
|
|
may be constructed on the stack.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<p>For other types, the variadic parameter matches exactly one
|
|
argument, which is passed by value.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> neil(<span class="d_keyword">int</span> i ...)
|
|
{
|
|
<span class="d_keyword">return</span> i;
|
|
}
|
|
|
|
<span class="d_keyword">void</span> buzz()
|
|
{
|
|
neil(); <span class="d_comment">// error, missing argument
|
|
</span> neil(3); <span class="d_comment">// returns 3
|
|
</span> neil(3, 4); <span class="d_comment">// error, too many arguments
|
|
</span> <span class="d_keyword">int</span>[] x;
|
|
neil(x); <span class="d_comment">// error, type mismatch
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<h4><a class="anchor" title="Permalink to this section" id="lazy_variadic_functions" href="#lazy_variadic_functions">Lazy Variadic Functions</a></h4>
|
|
<div class="blankline"></div>
|
|
<p>If the variadic parameter of a function is an array of delegates
|
|
with no parameters,
|
|
then each of the arguments whose type does not match that
|
|
of the delegate is converted to a delegate of that type.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> hal(<span class="d_keyword">scope</span> <span class="d_keyword">int</span> <span class="d_keyword">delegate</span>()[] dgs ...);
|
|
|
|
<span class="d_keyword">void</span> dave()
|
|
{
|
|
<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg;
|
|
hal(1, 3+x, dg, <span class="d_keyword">cast</span>(<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>())<span class="d_keyword">null</span>); <span class="d_comment">// (1)
|
|
</span> hal( { <span class="d_keyword">return</span> 1; }, { <span class="d_keyword">return</span> 3+x; }, dg, <span class="d_keyword">null</span> ); <span class="d_comment">// same as (1)
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>The variadic delegate array differs from using a lazy
|
|
variadic array. With the latter each array element access
|
|
would evaluate every array element.
|
|
With the former, only the element being accessed would be evaluated.</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">import</span> std.stdio;
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">int</span> x;
|
|
ming(++x, ++x);
|
|
|
|
<span class="d_keyword">int</span> y;
|
|
flash(++y, ++y);
|
|
}
|
|
|
|
<span class="d_comment">// lazy variadic array
|
|
</span><span class="d_keyword">void</span> ming(<span class="d_keyword">lazy</span> <span class="d_keyword">int</span>[] arr...)
|
|
{
|
|
writeln(arr[0]); <span class="d_comment">// 1
|
|
</span> writeln(arr[1]); <span class="d_comment">// 4
|
|
</span>}
|
|
|
|
<span class="d_comment">// variadic delegate array
|
|
</span><span class="d_keyword">void</span> flash(<span class="d_keyword">scope</span> <span class="d_keyword">int</span> <span class="d_keyword">delegate</span>()[] arr ...)
|
|
{
|
|
writeln(arr[0]()); <span class="d_comment">// 1
|
|
</span> writeln(arr[1]()); <span class="d_comment">// 2
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> Use <span class="d_inlinecode donthyphenate notranslate">scope</span> when declaring the array of delegates
|
|
parameter. This will prevent a closure being generated for the delegate,
|
|
as <span class="d_inlinecode donthyphenate notranslate">scope</span> means the delegate will not escape the function.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<span id="this-reference"><a class="anchor" title="Permalink to this section" id="" href="#"></a></span>
|
|
<h3><a class="anchor" title="Permalink to this section" id="hidden-parameters" href="#hidden-parameters">Hidden Parameters</a></h3>
|
|
<div class="blankline"></div>
|
|
<ul> <li> Non-static member functions all have a hidden parameter called the
|
|
<a href="../spec/expression.html#this"><span class="d_inlinecode donthyphenate notranslate">this</span> reference</a>, which refers to the object for which
|
|
the function is called.
|
|
</li>
|
|
<li><a href="#d_style_variadic_functions">D-style variadic functions</a>
|
|
have a hidden <span class="d_inlinecode donthyphenate notranslate">_arguments</span> parameter.</li>
|
|
<li><a href="#nested">Nested functions</a> have a hidden context
|
|
pointer parameter.</li>
|
|
<li>A function <a href="../spec/glossary.html#nrvo">returning a struct type</a> may
|
|
have a hidden pointer parameter.</li>
|
|
<li> <a href="../spec/class.html#objc-member-functions"> Member functions with <span class="d_inlinecode donthyphenate notranslate">Objective-C</span> linkage</a> have a hidden parameter.
|
|
</li>
|
|
</ul>
|
|
<p>See <a href="../spec/abi.html#parameters">ABI</a> for details.</p>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="refscopereturn" href="#refscopereturn">Ref Scope Return Cases</a></h2>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="rsr_definitions" href="#rsr_definitions">Definitions</a></h3>
|
|
<div class="blankline"></div>
|
|
<center><table><caption>Definitions</caption> <tr><th class="donthyphenate"><b>Term</b></th><th class="donthyphenate"><b>Description</b></th></tr>
|
|
<tr><td>I</td><td>type that contains no indirections</td></tr>
|
|
<tr><td>P</td><td>type that contains indirections</td></tr>
|
|
<tr><td>X</td><td>type that may or may not contain indirections</td></tr>
|
|
<tr><td>p</td><td>parameter of type P</td></tr>
|
|
<tr><td>i</td><td>parameter of type I</td></tr>
|
|
<tr><td>ref</td><td><span class="d_inlinecode donthyphenate notranslate">ref</span> or <span class="d_inlinecode donthyphenate notranslate">out</span> parameter</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td>returned</td><td>returned via the <span class="d_inlinecode donthyphenate notranslate">return</span> statement</td></tr>
|
|
<tr><td>escaped</td><td>stored in a global or other memory not in the function’s stack frame</td></tr>
|
|
</table></center>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="rsr_classification" href="#rsr_classification">Classification</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>A parameter must be in one of the following states:</p>
|
|
<div class="blankline"></div>
|
|
<center><table><caption>Classification</caption> <tr><th class="donthyphenate"><b>Term</b></th><th class="donthyphenate"><b>Description</b></th></tr>
|
|
<tr><td>None</td><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be returned or escaped</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td>ReturnScope</td><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be returned but not escaped</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td>Scope</td><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be neither returned nor escaped</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td>Ref</td><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be returned or escaped,
|
|
<span class="d_inlinecode donthyphenate notranslate">ref</span> may not be returned nor escaped</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td>ReturnRef</td><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be returned or escaped,
|
|
<span class="d_inlinecode donthyphenate notranslate">ref</span> may be returned but not escaped</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td>RefScope</td><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be neither returned nor escaped,
|
|
<span class="d_inlinecode donthyphenate notranslate">ref</span> may not be returned nor escaped</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td>ReturnRef-Scope</td><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be neither returned nor escaped,
|
|
<span class="d_inlinecode donthyphenate notranslate">ref</span> may be returned but not escaped</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td>Ref-ReturnScope</td><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be returned but not escaped,
|
|
<span class="d_inlinecode donthyphenate notranslate">ref</span> may not be returned nor escaped</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td>ReturnRef-ReturnScope</td><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be returned but not escaped,
|
|
<span class="d_inlinecode donthyphenate notranslate">ref</span> may be returned but not escaped.
|
|
This isn't expressible with the current syntax
|
|
and so is not allowed.</td></tr>
|
|
</table></center>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="rsr_mapping" href="#rsr_mapping">Mapping Syntax Onto Classification</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>The juxtaposition of <span class="d_inlinecode donthyphenate notranslate">return</span> immediately preceding <span class="d_inlinecode donthyphenate notranslate">scope</span> means ReturnScope.
|
|
Otherwise, <span class="d_inlinecode donthyphenate notranslate">return</span> and <span class="d_inlinecode donthyphenate notranslate">ref</span> in any position means ReturnRef.</p>
|
|
<div class="blankline"></div>
|
|
<center><table><caption>Mapping</caption> <tr><th class="donthyphenate"><b>Example</b></th><th class="donthyphenate"><b>Classification</b></th><th class="donthyphenate"><b>Comments</b></th></tr>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(P p)</span></td><td> None</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(scope P p)</span></td><td> Scope</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(return scope P p)</span></td><td> ReturnScope</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">I foo(return scope P p)</span></td><td> Scope</td><td> The <span class="d_inlinecode donthyphenate notranslate">return</span> is dropped because the return type <span class="d_inlinecode donthyphenate notranslate">I</span> contains no pointers.</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(return P p)</span></td><td> ReturnScope</td><td> Makes no sense to have <span class="d_inlinecode donthyphenate notranslate">return</span> without <span class="d_inlinecode donthyphenate notranslate">scope</span>.</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">I foo(return P p)</span></td><td> Scope</td><td> The <span class="d_inlinecode donthyphenate notranslate">return</span> is dropped because the return type <span class="d_inlinecode donthyphenate notranslate">I</span> contains no pointers.</td></tr>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(ref P p)</span></td><td> Ref</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(ref scope P p)</span></td><td> RefScope</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(ref return scope P p)</span></td><td> Ref-ReturnScope</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(return ref scope P p)</span></td><td> ReturnRef-Scope</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">I foo(ref return scope P p)</span></td><td> RefScope</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(ref return P p)</span></td><td> ReturnRef</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">I foo(ref return P p)</span></td><td> Ref</td></tr>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(P p)</span></td><td> None</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(scope P p)</span></td><td> Scope</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(return scope P p)</span></td><td> ReturnScope</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(return P p)</span></td><td> ReturnScope</td><td> Makes no sense to have <span class="d_inlinecode donthyphenate notranslate">return</span> without <span class="d_inlinecode donthyphenate notranslate">scope</span>.</td></tr>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref P p)</span></td><td> Ref</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref scope P p)</span></td><td> RefScope</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref return scope P p)</span></td><td> Ref-ReturnScope</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(return ref scope P p)</span></td><td> ReturnRef-Scope</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref return P p)</span></td><td> ReturnRef</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(I i)</span></td><td> None</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(scope I i)</span></td><td> None</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(return scope I i)</span></td><td> None</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(return I i)</span></td><td> None</td></tr>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(ref I i)</span></td><td> Ref</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(ref scope I i)</span></td><td> Ref</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(ref return scope I i)</span></td><td> Ref</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(ref return I i)</span></td><td> ReturnRef</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">I foo(ref return I i)</span></td><td> Ref</td></tr>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(I i)</span></td><td> None</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(scope I i)</span></td><td> None</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(return scope I i)</span></td><td> None</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(return I i)</span></td><td> None</td></tr>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref I i)</span></td><td> Ref</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref scope I i)</span></td><td> Ref</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref return scope I i)</span></td><td> ReturnRef</td></tr>
|
|
<div class="blankline"></div>
|
|
<tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref return I i)</span></td><td> ReturnRef</td></tr>
|
|
</table></center>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="rsr_memberfunctions" href="#rsr_memberfunctions">Member Functions</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>Member functions are rewritten as if the <span class="d_inlinecode donthyphenate notranslate">this</span> parameter is the first
|
|
parameter of a non-member function,
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> S {
|
|
X foo();
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>is treated as:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">X foo(<span class="d_keyword">ref</span> S);
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>and:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> C {
|
|
X foo()
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>is treated as:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">X foo(P)
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="rsr_PandRef" href="#rsr_PandRef">P and ref</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>The rules account for switching between <span class="d_inlinecode donthyphenate notranslate">ref</span> and P, such as:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span>* foo(<span class="d_keyword">return</span> <span class="d_keyword">ref</span> <span class="d_keyword">int</span> i) { <span class="d_keyword">return</span> &i; }
|
|
<span class="d_keyword">ref</span> <span class="d_keyword">int</span> foo(<span class="d_keyword">int</span>* p) { <span class="d_keyword">return</span> *p; }
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="rsr_covariance" href="#rsr_covariance">Contravariance</a></h3>
|
|
<div class="blankline"></div>
|
|
<p><a href="../spec/type.html#covariance">Contravariance</a> means a function with a parameter
|
|
restriction can be overridden by a function with a corresponding parameter with fewer
|
|
restrictions. This is deducible from the description of each state.
|
|
The following tables show which of the attributes can be loosened:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> There is no variance between <span class="d_inlinecode donthyphenate notranslate">ref</span> and non-<span class="d_inlinecode donthyphenate notranslate">ref</span> types, so those entries are
|
|
omitted from the table for simplicity.
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<center><table><caption>Non-Ref Contravariance</caption> <tr><th class="donthyphenate"><b>From\To</b></th><th class="donthyphenate"><b> None</b></th><th class="donthyphenate"><b> ReturnScope</b></th><th class="donthyphenate"><b>Scope</b></th></tr>
|
|
<tr><td>None</td><td> ✔</td><td> </td><td> </td></tr>
|
|
<tr><td>ReturnScope</td><td> ✔</td><td>✔ </td><td> </td></tr>
|
|
<tr><td>Scope</td><td> ✔</td><td>✔ </td><td>✔</td></tr>
|
|
</table></center>
|
|
<div class="blankline"></div>
|
|
<center><table><caption>Ref Contravariance</caption> <tr><th class="donthyphenate"><b>From\To</b></th><th class="donthyphenate"><b> Ref </b></th><th class="donthyphenate"><b>ReturnRef</b></th><th class="donthyphenate"><b>RefScope</b></th><th class="donthyphenate"><b>ReturnRef-Scope</b></th><th class="donthyphenate"><b>Ref-ReturnScope</b></th></tr>
|
|
<tr><td>Ref</td><td> ✔</td><td>✔ </td><td> </td><td> </td><td> </td></tr>
|
|
<tr><td>ReturnRef</td><td> </td><td>✔ </td><td> </td><td> </td><td> </td></tr>
|
|
<tr><td>RefScope</td><td> ✔</td><td>✔ </td><td>✔</td><td>✔ </td><td> ✔</td></tr>
|
|
<tr><td>ReturnRef-Scope</td><td> </td><td>✔ </td><td> </td><td>✔ </td><td> </td></tr>
|
|
<tr><td>Ref-ReturnScope</td><td> ✔</td><td>✔ </td><td> </td><td> </td><td> ✔</td></tr>
|
|
</table></center>
|
|
<div class="blankline"></div>
|
|
<p>For example, <span class="d_inlinecode donthyphenate notranslate">scope</span> can be overridden by all non-ref parameters,
|
|
and <span class="d_inlinecode donthyphenate notranslate">ref scope</span> can be overridden by all ref parameters:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_comment">// cannot escape parameter
|
|
</span><span class="d_keyword">void</span> f1(<span class="d_keyword">scope</span> <span class="d_keyword">int</span>*);
|
|
<span class="d_comment">// can escape, but doesn't have to
|
|
</span><span class="d_keyword">void</span> <span class="d_keyword">function</span>(<span class="d_keyword">int</span>*) fp1 = &f1;
|
|
|
|
<span class="d_keyword">void</span> f2(<span class="d_keyword">ref</span> <span class="d_keyword">scope</span> <span class="d_keyword">int</span>*);
|
|
<span class="d_keyword">void</span> <span class="d_keyword">function</span>(<span class="d_keyword">ref</span> <span class="d_keyword">int</span>*) fp2 = &f2;
|
|
|
|
<span class="d_comment">// cannot return parameter
|
|
</span><span class="d_keyword">ref</span> <span class="d_keyword">int</span> f3(<span class="d_keyword">ref</span> <span class="d_keyword">int</span>);
|
|
<span class="d_comment">// can return parameter, but doesn't have to
|
|
</span><span class="d_keyword">ref</span> <span class="d_keyword">int</span> <span class="d_keyword">function</span>(<span class="d_keyword">ref</span> <span class="d_keyword">return</span> <span class="d_keyword">int</span>) fp3 = &f3;
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><span id="Local Variables"><a class="anchor" title="Permalink to this section" id="local-variables" href="#local-variables">Local Variables</a></span></h2>
|
|
<div class="blankline"></div>
|
|
<p>Local variables are declared within the scope of a function.
|
|
Function parameters are included.</p>
|
|
<div class="blankline"></div>
|
|
<p>A local variable cannot be read without first assigning it a
|
|
value.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> The implementation may not always be able
|
|
to detect these cases.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<p>The address of or reference to a
|
|
local non-static variable cannot be returned from the function.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>A local variable and a label in the same function cannot have the same
|
|
name.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>A local variable cannot hide another local
|
|
variable in the same function.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes rationale"><b>Rationale:</b> whenever
|
|
this is done it often is a
|
|
bug or at least looks like a bug.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">ref</span> <span class="d_keyword">double</span> func(<span class="d_keyword">int</span> x)
|
|
{
|
|
<span class="d_keyword">int</span> x; <span class="d_comment">// error, hides previous definition of x
|
|
</span> <span class="d_keyword">double</span> y;
|
|
{
|
|
<span class="d_keyword">char</span> y; <span class="d_comment">// error, hides previous definition of y
|
|
</span> <span class="d_keyword">int</span> z;
|
|
}
|
|
{
|
|
<span class="d_keyword">wchar</span> z; <span class="d_comment">// Ok, previous z is out of scope
|
|
</span> }
|
|
z: <span class="d_comment">// error, z is a local variable and a label
|
|
</span> <span class="d_keyword">return</span> y; <span class="d_comment">// error, returning ref to local
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h3><span id="Local Static Variables"><a class="anchor" title="Permalink to this section" id="local-static-variables" href="#local-static-variables">Local Static Variables</a></span></h3>
|
|
<div class="blankline"></div>
|
|
<p>Local variables declared as <span class="d_inlinecode donthyphenate notranslate">static</span>, <span class="d_inlinecode donthyphenate notranslate">shared static</span>
|
|
or <span class="d_inlinecode donthyphenate notranslate">__gshared</span> are statically allocated
|
|
rather than being allocated on the stack.
|
|
The lifetime of <span class="d_inlinecode donthyphenate notranslate">__gshared</span> and <span class="d_inlinecode donthyphenate notranslate">shared static</span> variables begins
|
|
when the function is first executed and ends when the program ends.
|
|
The lifetime of <span class="d_inlinecode donthyphenate notranslate">static</span> variables begins when the function is first
|
|
executed within the thread and ends when that thread terminates.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">import</span> std.stdio : writeln;
|
|
|
|
<span class="d_keyword">void</span> foo()
|
|
{
|
|
<span class="d_keyword">static</span> <span class="d_keyword">int</span> n;
|
|
<span class="d_keyword">if</span> (++n == 100)
|
|
writeln(<span class="d_string">"called 100 times"</span>);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>The initializer for a static variable must be evaluatable at
|
|
compile time.
|
|
There are no static constructors or static destructors
|
|
for static local variables.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Although static variable name visibility follows the usual scoping
|
|
rules, the names of them must be unique within a particular function.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> main()
|
|
{
|
|
{ <span class="d_keyword">static</span> <span class="d_keyword">int</span> x; }
|
|
{ <span class="d_keyword">static</span> <span class="d_keyword">int</span> x; } <span class="d_comment">// error
|
|
</span> { <span class="d_keyword">int</span> i; }
|
|
{ <span class="d_keyword">int</span> i; } <span class="d_comment">// ok
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="nested" href="#nested">Nested Functions</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>Functions may be nested within other functions:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> bar(<span class="d_keyword">int</span> a)
|
|
{
|
|
<span class="d_keyword">int</span> foo(<span class="d_keyword">int</span> b)
|
|
{
|
|
<span class="d_keyword">int</span> abc() { <span class="d_keyword">return</span> 1; }
|
|
|
|
<span class="d_keyword">return</span> b + abc();
|
|
}
|
|
<span class="d_keyword">return</span> foo(a);
|
|
}
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
<span class="d_keyword">int</span> i = bar(3); <span class="d_comment">// i is assigned 4
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>Nested functions can be accessed only if the name is in scope.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> foo()
|
|
{
|
|
<span class="d_keyword">void</span> A()
|
|
{
|
|
B(); <span class="d_comment">// error, B() is forward referenced
|
|
</span> C(); <span class="d_comment">// error, C undefined
|
|
</span> }
|
|
<span class="d_keyword">void</span> B()
|
|
{
|
|
A(); <span class="d_comment">// ok, in scope
|
|
</span> <span class="d_keyword">void</span> C()
|
|
{
|
|
<span class="d_keyword">void</span> D()
|
|
{
|
|
A(); <span class="d_comment">// ok
|
|
</span> B(); <span class="d_comment">// ok
|
|
</span> C(); <span class="d_comment">// ok
|
|
</span> D(); <span class="d_comment">// ok
|
|
</span> }
|
|
}
|
|
}
|
|
A(); <span class="d_comment">// ok
|
|
</span> B(); <span class="d_comment">// ok
|
|
</span> C(); <span class="d_comment">// error, C undefined
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
and:
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> bar(<span class="d_keyword">int</span> a)
|
|
{
|
|
<span class="d_keyword">int</span> foo(<span class="d_keyword">int</span> b) { <span class="d_keyword">return</span> b + 1; }
|
|
<span class="d_keyword">int</span> abc(<span class="d_keyword">int</span> b) { <span class="d_keyword">return</span> foo(b); } <span class="d_comment">// ok
|
|
</span> <span class="d_keyword">return</span> foo(a);
|
|
}
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
<span class="d_keyword">int</span> i = bar(3); <span class="d_comment">// ok
|
|
</span> <span class="d_keyword">int</span> j = bar.foo(3); <span class="d_comment">// error, bar.foo not visible
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Nested functions have access to the variables and other symbols
|
|
defined by the lexically enclosing function.
|
|
This access includes both the ability to read and write them.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> bar(<span class="d_keyword">int</span> a)
|
|
{
|
|
<span class="d_keyword">int</span> c = 3;
|
|
|
|
<span class="d_keyword">int</span> foo(<span class="d_keyword">int</span> b)
|
|
{
|
|
b += c; <span class="d_comment">// 4 is added to b
|
|
</span> c++; <span class="d_comment">// bar.c is now 5
|
|
</span> <span class="d_keyword">return</span> b + c; <span class="d_comment">// 12 is returned
|
|
</span> }
|
|
c = 4;
|
|
<span class="d_keyword">int</span> i = foo(a); <span class="d_comment">// i is set to 12
|
|
</span> <span class="d_keyword">return</span> i + c; <span class="d_comment">// returns 17
|
|
</span>}
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
<span class="d_keyword">int</span> i = bar(3); <span class="d_comment">// i is assigned 17
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>This access can span multiple nesting levels:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> bar(<span class="d_keyword">int</span> a)
|
|
{
|
|
<span class="d_keyword">int</span> c = 3;
|
|
|
|
<span class="d_keyword">int</span> foo(<span class="d_keyword">int</span> b)
|
|
{
|
|
<span class="d_keyword">int</span> abc()
|
|
{
|
|
<span class="d_keyword">return</span> c; <span class="d_comment">// access bar.c
|
|
</span> }
|
|
<span class="d_keyword">return</span> b + c + abc();
|
|
}
|
|
<span class="d_keyword">return</span> foo(3);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>Static nested functions cannot access any stack variables of
|
|
any lexically enclosing function, but can access static variables.
|
|
This is analogous to how static member functions behave.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> bar(<span class="d_keyword">int</span> a)
|
|
{
|
|
<span class="d_keyword">int</span> c;
|
|
<span class="d_keyword">static</span> <span class="d_keyword">int</span> d;
|
|
|
|
<span class="d_keyword">static</span> <span class="d_keyword">int</span> foo(<span class="d_keyword">int</span> b)
|
|
{
|
|
b = d; <span class="d_comment">// ok
|
|
</span> b = c; <span class="d_comment">// error, foo() cannot access frame of bar()
|
|
</span> <span class="d_keyword">return</span> b + 1;
|
|
}
|
|
<span class="d_keyword">return</span> foo(a);
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Functions can be nested within member functions:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> Foo
|
|
{
|
|
<span class="d_keyword">int</span> a;
|
|
|
|
<span class="d_keyword">int</span> bar()
|
|
{
|
|
<span class="d_keyword">int</span> c;
|
|
|
|
<span class="d_keyword">int</span> foo()
|
|
{
|
|
<span class="d_keyword">return</span> c + a;
|
|
}
|
|
<span class="d_keyword">return</span> 0;
|
|
}
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>Nested functions always have the D function linkage type.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="nested-qualifiers" href="#nested-qualifiers">Nested Functions with Method Attributes</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>A non-static nested function can have <a href="#MemberFunctionAttributes"><i>MemberFunctionAttributes</i></a>.
|
|
Method attributes (other than the normal <a href="#FunctionAttributes"><i>FunctionAttributes</i></a>) affect
|
|
the context pointer:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> test(<span class="d_keyword">int</span> x, <span class="d_keyword">immutable</span> <span class="d_keyword">int</span> y)
|
|
{
|
|
<span class="d_keyword">int</span> foo() <span class="d_comment">// hidden context pointer is mutable
|
|
</span> {
|
|
x = 10; <span class="d_comment">// can access data in enclosing scope
|
|
</span> <span class="d_comment">// through the mutable context pointer
|
|
</span> <span class="d_keyword">return</span> x;
|
|
}
|
|
|
|
<span class="d_keyword">int</span> bar() <span class="d_keyword">immutable</span> <span class="d_comment">// hidden context pointer is immutable
|
|
</span> {
|
|
<span class="d_comment">//return x; // error, cannot access nested data
|
|
</span> <span class="d_comment">// through the immutable context pointer
|
|
</span> <span class="d_keyword">return</span> y; <span class="d_comment">// OK, `y` is immutable
|
|
</span> }
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="nested-declaration-order" href="#nested-declaration-order">Declaration Order</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>Unlike module level declarations, declarations within function
|
|
scope are processed in order. This means that two nested functions
|
|
cannot mutually call each other:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> test()
|
|
{
|
|
<span class="d_keyword">void</span> foo() { bar(); } <span class="d_comment">// error, bar not defined
|
|
</span> <span class="d_keyword">void</span> bar() { foo(); } <span class="d_comment">// ok
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>There are several workarounds for this limitation:</p>
|
|
<div class="blankline"></div>
|
|
<ul><div class="blankline"></div>
|
|
<li>Declare the functions to be static members of a nested struct:</li>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> test()
|
|
{
|
|
<span class="d_keyword">static</span> <span class="d_keyword">struct</span> S
|
|
{
|
|
<span class="d_keyword">static</span> <span class="d_keyword">void</span> foo() { bar(); } <span class="d_comment">// ok
|
|
</span> <span class="d_keyword">static</span> <span class="d_keyword">void</span> bar() { foo(); } <span class="d_comment">// ok
|
|
</span> }
|
|
|
|
S.foo(); <span class="d_comment">// compiles (but note the infinite runtime loop)
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<li>Declare one or more of the functions to be function templates
|
|
even if they take no specific template arguments:</li>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> test()
|
|
{
|
|
<span class="d_keyword">void</span> foo()() { bar(); } <span class="d_comment">// ok (foo is a function template)
|
|
</span> <span class="d_keyword">void</span> bar() { foo(); } <span class="d_comment">// ok
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<li>Declare the functions inside of a mixin template:</li>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">mixin</span> <span class="d_keyword">template</span> T()
|
|
{
|
|
<span class="d_keyword">void</span> foo() { bar(); } <span class="d_comment">// ok
|
|
</span> <span class="d_keyword">void</span> bar() { foo(); } <span class="d_comment">// ok
|
|
</span>}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">mixin</span> T!();
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<li>Use a delegate:</li>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> test()
|
|
{
|
|
<span class="d_keyword">void</span> <span class="d_keyword">delegate</span>() fp;
|
|
<span class="d_keyword">void</span> foo() { fp(); }
|
|
<span class="d_keyword">void</span> bar() { foo(); }
|
|
fp = &bar;
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<p>Nested functions cannot be overloaded.</p>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="function-pointers-delegates" href="#function-pointers-delegates">Function Pointers, Delegates and Closures</a></h2>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="function-pointers" href="#function-pointers">Function Pointers</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>A <a href="../spec/type.html#function-pointers">function pointer</a>
|
|
is declared with the <span class="d_inlinecode donthyphenate notranslate">function</span> keyword:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> f(<span class="d_keyword">int</span>);
|
|
<span class="d_keyword">void</span> <span class="d_keyword">function</span>(<span class="d_keyword">int</span>) fp = &f; <span class="d_comment">// fp is a pointer to a function taking an int
|
|
</span></pre>
|
|
|
|
</div>
|
|
<p>A function pointer can point to a static <a href="#nested">nested function</a>:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> <span class="d_keyword">function</span>() fp; <span class="d_comment">// fp is a pointer to a function returning an int
|
|
</span>
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
<span class="d_keyword">static</span> <span class="d_keyword">int</span> a = 7;
|
|
<span class="d_keyword">static</span> <span class="d_keyword">int</span> foo() { <span class="d_keyword">return</span> a + 3; }
|
|
|
|
fp = &foo;
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">assert</span>(!fp);
|
|
test();
|
|
<span class="d_keyword">int</span> i = fp();
|
|
<span class="d_keyword">assert</span>(i == 10);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> Two functions with identical bodies, or two functions
|
|
that compile to identical assembly code, are not guaranteed to have
|
|
distinct function pointer values. The implementation may merge
|
|
functions bodies into one if they compile to identical code.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> abc(<span class="d_keyword">int</span> x) { <span class="d_keyword">return</span> x + 1; }
|
|
<span class="d_keyword">uint</span> def(<span class="d_keyword">uint</span> y) { <span class="d_keyword">return</span> y + 1; }
|
|
|
|
<span class="d_keyword">int</span> <span class="d_keyword">function</span>(<span class="d_keyword">int</span>) fp1 = &abc;
|
|
<span class="d_keyword">uint</span> <span class="d_keyword">function</span>(<span class="d_keyword">uint</span>) fp2 = &def;
|
|
<span class="d_comment">// Do not rely on fp1 and fp2 being different values; the compiler may merge
|
|
</span><span class="d_comment">// them.
|
|
</span></pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="closures" href="#closures">Delegates & Closures</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>A <a href="../spec/type.html#delegates">delegate</a> can be set to a
|
|
non-static <a href="#nested">nested function</a>:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg;
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
<span class="d_keyword">int</span> a = 7;
|
|
<span class="d_keyword">int</span> foo() { <span class="d_keyword">return</span> a + 3; }
|
|
|
|
dg = &foo;
|
|
<span class="d_keyword">int</span> i = dg(); <span class="d_comment">// i is set to 10
|
|
</span>}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
test();
|
|
<span class="d_keyword">int</span> i = dg(); <span class="d_comment">// ok, test.a is in a closure and still exists
|
|
</span> <span class="d_keyword">assert</span>(i == 10);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>The stack variables referenced by a nested function are
|
|
still valid even after the function exits (NOTE this is different
|
|
from D 1.0).
|
|
This combining of the environment and the function is called
|
|
a <i>dynamic closure</i>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Those referenced stack variables that make up the closure
|
|
are allocated on the GC heap, unless:</p>
|
|
|
|
<ul><li>The closure is passed to a <a href="#scope-parameters"><span class="d_inlinecode donthyphenate notranslate">scope</span> parameter</a>.</li>
|
|
<li>The closure is an initializer for a
|
|
<a href="../spec/attribute.html#scope"><span class="d_inlinecode donthyphenate notranslate">scope</span> variable</a>.</li>
|
|
<li>The closure is assigned to a <span class="d_inlinecode donthyphenate notranslate">scope</span> variable.
|
|
</li>
|
|
</ul>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate">@nogc:
|
|
<span class="d_keyword">void</span> f(<span class="d_keyword">scope</span> <span class="d_keyword">int</span> <span class="d_keyword">delegate</span>());
|
|
<span class="d_keyword">void</span> g(<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>());
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">int</span> i;
|
|
<span class="d_keyword">int</span> h() { <span class="d_keyword">return</span> i; }
|
|
h(); <span class="d_comment">// OK
|
|
</span> <span class="d_keyword">scope</span> x = &h; <span class="d_comment">// OK
|
|
</span> x(); <span class="d_comment">// OK
|
|
</span> <span class="d_comment">//auto y = &h; // error, can't allocate closure in @nogc function
|
|
</span> f(&h); <span class="d_comment">// OK
|
|
</span> <span class="d_comment">//g(&h); // error
|
|
</span>
|
|
<span class="d_comment">// delegate literals
|
|
</span> f(() => i); <span class="d_comment">// OK
|
|
</span> <span class="d_keyword">scope</span> d = () => i; <span class="d_comment">// OK
|
|
</span> d = () => i + 1; <span class="d_comment">// OK
|
|
</span> f(d);
|
|
<span class="d_comment">//g(() => i); // error, can't allocate closure in @nogc function
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> Returning addresses of stack variables, however, is not
|
|
a closure and is an error.
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="method-delegates" href="#method-delegates">Method Delegates</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>Delegates to non-static nested functions contain two pieces of
|
|
data: the pointer to the stack frame of the lexically enclosing
|
|
function (called the <i>context pointer</i>) and the address of the
|
|
function. This is analogous to struct/class non-static member
|
|
function delegates consisting of a <i>this</i> pointer and
|
|
the address of the member function.
|
|
Both forms of delegates are indistinguishable, and are
|
|
the same type.
|
|
</p>
|
|
<p>A delegate can be set to a particular object and method using <span class="d_inlinecode donthyphenate notranslate">&obj.method</span>:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> Foo
|
|
{
|
|
<span class="d_keyword">int</span> a;
|
|
<span class="d_keyword">int</span> get() { <span class="d_keyword">return</span> a; }
|
|
}
|
|
|
|
<span class="d_keyword">int</span> add1(<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg)
|
|
{
|
|
<span class="d_keyword">return</span> dg() + 1;
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
Foo f = {7};
|
|
<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg = &f.get; <span class="d_comment">// bind to an instance of Foo and a method
|
|
</span> <span class="d_keyword">int</span> i = add1(dg);
|
|
<span class="d_keyword">assert</span>(i == 8);
|
|
|
|
<span class="d_keyword">int</span> x = 27;
|
|
<span class="d_keyword">int</span> abc() { <span class="d_keyword">return</span> x; }
|
|
|
|
i = add1(&abc);
|
|
<span class="d_keyword">assert</span>(i == 28);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="function-pointer-attributes" href="#function-pointer-attributes">Attributes</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>A function pointer or delegate can have <a href="#FunctionAttributes"><i>FunctionAttributes</i></a> or
|
|
<a href="#MemberFunctionAttributes"><i>MemberFunctionAttributes</i></a> respectively. A function pointer/delegate type
|
|
implicitly converts to a more-loosely qualified type (i.e. when the original
|
|
type is <a href="../spec/type.html#covariance">covariant</a> with the destination type).</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> <span class="d_keyword">function</span>() <span class="d_keyword">pure</span> pfp;
|
|
<span class="d_keyword">void</span> <span class="d_keyword">function</span>() fp = pfp; <span class="d_comment">// OK, impure `fp` can call pure
|
|
</span>pfp = fp; <span class="d_comment">// Error, pure `pfp` cannot call impure
|
|
</span></pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="function-delegate-init" href="#function-delegate-init">Initialization</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>Function pointers are zero-initialized by default.
|
|
They can be initialized to the address of any function (including a function literal).
|
|
Initialization with the address of a function that requires a context pointer
|
|
is not allowed in <a href="#safe-functions"><span class="d_inlinecode donthyphenate notranslate">@safe</span> functions</a>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes undefined-behavior"><b>Undefined Behavior:</b> Calling a function pointer that was set to point to
|
|
a function that requires a context pointer.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> S
|
|
{
|
|
<span class="d_keyword">static</span> <span class="d_keyword">int</span> sfunc() @safe;
|
|
<span class="d_keyword">int</span> member(); <span class="d_comment">// has hidden `this` reference parameter
|
|
</span>}
|
|
|
|
@safe <span class="d_keyword">void</span> sun()
|
|
{
|
|
<span class="d_keyword">int</span> <span class="d_keyword">function</span>() @safe fp = &S.sfunc;
|
|
fp(); <span class="d_comment">// Ok
|
|
</span> fp = &S.member; <span class="d_comment">// error
|
|
</span>}
|
|
|
|
@system <span class="d_keyword">void</span> moon()
|
|
{
|
|
<span class="d_keyword">int</span> <span class="d_keyword">function</span>() fp = &S.member; <span class="d_comment">// Ok because @system
|
|
</span> fp(); <span class="d_comment">// undefined behavior
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>Delegates are zero-initialized by default.
|
|
They can be initialized by taking the address of a non-static member function,
|
|
but a context pointer must be supplied.
|
|
They can be initialized by taking the address of a non-static nested function
|
|
or function literal,
|
|
where the context pointer will be set to point to the stack frame, closure, or <span class="d_inlinecode donthyphenate notranslate">null</span>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Delegates cannot be initialized by taking the address of a global function,
|
|
a static member function, or a static nested function.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">struct</span> S
|
|
{
|
|
<span class="d_keyword">static</span> <span class="d_keyword">int</span> sfunc();
|
|
<span class="d_keyword">int</span> member() { <span class="d_keyword">return</span> 1; }
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
S s;
|
|
<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg = &s.member; <span class="d_comment">// Ok, s supplies context pointer
|
|
</span> <span class="d_keyword">assert</span>(dg() == 1);
|
|
|
|
<span class="d_comment">//dg = &S.sfunc; // error
|
|
</span> <span class="d_comment">//dg = &S.member; // error
|
|
</span>
|
|
<span class="d_keyword">int</span> moon() { <span class="d_keyword">return</span> 2; }
|
|
dg = &moon; <span class="d_comment">// Ok
|
|
</span> <span class="d_keyword">assert</span>(dg() == 2);
|
|
|
|
<span class="d_keyword">static</span> <span class="d_keyword">int</span> mars() { <span class="d_keyword">return</span> 3; }
|
|
<span class="d_comment">//dg = &mars; // error
|
|
</span>
|
|
dg = () { <span class="d_keyword">return</span> 4; }; <span class="d_comment">// Ok
|
|
</span> <span class="d_keyword">assert</span>(dg() == 4);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<p>The last assignment uses a <a href="../spec/expression.html#FunctionLiteral"><i>FunctionLiteral</i></a>, which
|
|
<a href="../spec/expression.html#lambda-type-inference">is inferred</a>
|
|
as a delegate.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> Function pointers can be passed to functions taking a delegate argument by passing
|
|
them through the <a href="../phobos/std_functional.html#.toDelegate"><span class="d_inlinecode donthyphenate notranslate">std.functional.toDelegate</span></a> template, which converts any callable
|
|
to a delegate with a <span class="d_inlinecode donthyphenate notranslate">null</span> context pointer.
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="anonymous" href="#anonymous">Anonymous Functions and Anonymous Delegates</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>See <a href="../spec/expression.html#FunctionLiteral"><i>FunctionLiteral</i></a>s.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="main" href="#main"><span class="d_inlinecode donthyphenate notranslate">main()</span> Function</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>For console programs, <span class="d_inlinecode donthyphenate notranslate">main()</span> serves as the entry point.
|
|
It gets called after all the <a href="../spec/module.html#staticorder">module initializers</a>
|
|
are run, and after any <a href="../spec/unittest.html">unittests</a> are run.
|
|
After it returns, all the module destructors are run.
|
|
<span class="d_inlinecode donthyphenate notranslate">main()</span> must be declared as follows:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="bnf notranslate"><a id="MainFunction"><span class="gname">MainFunction</span></a>:
|
|
<a href="#MainReturnDecl"><i>MainReturnDecl</i></a> <span class="d_inlinecode donthyphenate notranslate">main()</span> <a href="#FunctionBody"><i>FunctionBody</i></a>
|
|
<a href="#MainReturnDecl"><i>MainReturnDecl</i></a> <span class="d_inlinecode donthyphenate notranslate">main(string[]</span> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a><span class="d_inlinecode donthyphenate notranslate">)</span> <a href="#FunctionBody"><i>FunctionBody</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="MainReturnDecl"><span class="gname">MainReturnDecl</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">void</span>
|
|
<span class="d_inlinecode donthyphenate notranslate">int</span>
|
|
<a href="../spec/type.html#noreturn"><i>noreturn</i></a>
|
|
<a href="#auto-functions"><span class="d_inlinecode donthyphenate notranslate">auto</span></a>
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<ul> <li>If <span class="d_inlinecode donthyphenate notranslate">main</span> returns <span class="d_inlinecode donthyphenate notranslate">void</span>, the OS will receive a zero value on success.</li>
|
|
<li>If <span class="d_inlinecode donthyphenate notranslate">main</span> returns <span class="d_inlinecode donthyphenate notranslate">void</span> or <span class="d_inlinecode donthyphenate notranslate">noreturn</span>, the OS will receive a non-zero
|
|
value on abnormal termination, such as an uncaught exception.</li>
|
|
<li>If <span class="d_inlinecode donthyphenate notranslate">main</span> is declared as <span class="d_inlinecode donthyphenate notranslate">auto</span>, the inferred return type must be
|
|
one of <span class="d_inlinecode donthyphenate notranslate">void</span>, <span class="d_inlinecode donthyphenate notranslate">int</span> and <span class="d_inlinecode donthyphenate notranslate">noreturn</span>.</li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<p>If the <span class="d_inlinecode donthyphenate notranslate">string[]</span> parameter is declared, the parameter will hold
|
|
arguments passed to the program by the OS. The first argument is typically
|
|
the executable name, followed by any command-line arguments.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> The runtime can remove any arguments prefixed <span class="d_inlinecode donthyphenate notranslate">--DRT-</span>.</div>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> The aforementioned return / parameter types may be annotated with <span class="d_inlinecode donthyphenate notranslate">const</span>,
|
|
<span class="d_inlinecode donthyphenate notranslate">immutable</span>. They may also be replaced by <span class="d_inlinecode donthyphenate notranslate">enum</span>'s with matching base types.</div>
|
|
<div class="blankline"></div>
|
|
<p>The main function must have D linkage.</p>
|
|
<div class="blankline"></div>
|
|
<p>Attributes may be added as needed, e.g. <span class="d_inlinecode donthyphenate notranslate">@safe</span>, <span class="d_inlinecode donthyphenate notranslate">@nogc</span>, <span class="d_inlinecode donthyphenate notranslate">nothrow</span>, etc.</p>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="betterc-main" href="#betterc-main"><span class="d_inlinecode donthyphenate notranslate">extern(C) main()</span> Function</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>Programs may define an <span class="d_inlinecode donthyphenate notranslate">extern(C) main</span> function as an alternative to the
|
|
standard <a href="#main">entry point</a>. This form is required for
|
|
<a href="../spec/betterc.html"><b>BetterC</b></a> programs.</p>
|
|
<div class="blankline"></div>
|
|
<p>A C <span class="d_inlinecode donthyphenate notranslate">main</span> function must be declared as follows:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="bnf notranslate"><a id="CMainFunction"><span class="gname">CMainFunction</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">extern (C)</span> <a href="#MainReturnDecl"><i>MainReturnDecl</i></a> <span class="d_inlinecode donthyphenate notranslate">main(<a href="#CmainParameters"><i>CmainParameters</i></a><sub>opt</sub>)</span> <a href="../spec/statement.html#BlockStatement"><i>BlockStatement</i></a>
|
|
<div class="blankline"></div>
|
|
<a id="CmainParameters"><span class="gname">CmainParameters</span></a>:
|
|
<span class="d_inlinecode donthyphenate notranslate">int</span> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a>, <span class="d_inlinecode donthyphenate notranslate">char**</span> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a>
|
|
<span class="d_inlinecode donthyphenate notranslate">int</span> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a>, <span class="d_inlinecode donthyphenate notranslate">char**</span> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a>, <span class="d_inlinecode donthyphenate notranslate">char**</span> <a href="../spec/lex.html#Identifier"><i>Identifier</i></a>
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>When defined, the first two parameters denote a C-style array (length + pointer)
|
|
that holds the arguments passed to the program by the OS. The third parameter is a POSIX
|
|
extension called <span class="d_inlinecode donthyphenate notranslate">environ</span> and holds information about the current environment variables.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> The exemption for storage classes / <span class="d_inlinecode donthyphenate notranslate">enum</span>'s defined for a D <span class="d_inlinecode donthyphenate notranslate">main</span> function
|
|
also applies to C <span class="d_inlinecode donthyphenate notranslate">main</span> functions.</div>
|
|
<div class="blankline"></div>
|
|
<p>This function takes the place of the C main function and is executed immediately without
|
|
any setup or teardown associated with a D <span class="d_inlinecode donthyphenate notranslate">main</span> function. Programs reliant on module
|
|
constructors, module destructors, or unittests need to manually perform (de)initialization
|
|
using the appropriate <a href="../phobos/core_runtime.html#Runtime">runtime functions</a>.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> Other system-specific entry points may exist, such as
|
|
<span class="d_inlinecode donthyphenate notranslate">WinMain</span> and <span class="d_inlinecode donthyphenate notranslate">DllMain</span> on Windows systems.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> Programs targeting platforms which require a different signature for <span class="d_inlinecode donthyphenate notranslate">main</span> can use
|
|
a function with <a href="../spec/pragma.html#mangle">explicit mangling</a>:
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">pragma</span>(mangle, <span class="d_string">"main"</span>)
|
|
<span class="d_keyword">int</span> myMain(<span class="d_keyword">int</span> a, <span class="d_keyword">int</span> b, <span class="d_keyword">int</span> c)
|
|
{
|
|
<span class="d_keyword">return</span> 0;
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="function-templates" href="#function-templates">Function Templates</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>Functions can have compile time arguments in the form of a template.
|
|
See <a href="../spec/template.html#function-templates">function templates</a>.</p>
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="interpretation" href="#interpretation">Compile Time Function Execution (CTFE)</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>In contexts where a compile time value is required, functions
|
|
can be used to compute those values. This is called <i>Compile Time Function
|
|
Execution</i>, or <i>CTFE</i>.</p>
|
|
<div class="blankline"></div>
|
|
<p>These contexts are:</p>
|
|
<div class="blankline"></div>
|
|
<ul> <li>initialization of a global/static variable or a
|
|
<a href="../spec/enum.html#manifest_constants">manifest constant</a></li>
|
|
<li>static initializers of struct/class fields</li>
|
|
<li>dimension of a <a href="../spec/arrays.html#static-arrays">static array</a> type</li>
|
|
<li>argument for a <a href="../spec/template.html#template_value_parameter"> template value parameter</a></li>
|
|
<li><a href="../spec/version.html#staticif"><span class="d_inlinecode donthyphenate notranslate">static if</span></a></li>
|
|
<li><a href="../spec/version.html#staticforeach"><span class="d_inlinecode donthyphenate notranslate">static foreach</span></a></li>
|
|
<li><a href="../spec/version.html#static-assert"><span class="d_inlinecode donthyphenate notranslate">static assert</span></a></li>
|
|
<li><a href="../spec/statement.html#mixin-statement"> <span class="d_inlinecode donthyphenate notranslate">mixin</span> statement</a>/expression/declaration</li>
|
|
<li><a href="../spec/pragma.html"><span class="d_inlinecode donthyphenate notranslate">pragma</span> argument</a></li>
|
|
<li><a href="../spec/traits.html"><span class="d_inlinecode donthyphenate notranslate">__traits</span> argument</a></li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">enum</span> eval(<span class="d_keyword">alias</span> arg) = arg;
|
|
|
|
<span class="d_keyword">int</span> square(<span class="d_keyword">int</span> i)
|
|
{
|
|
<span class="d_keyword">return</span> i * i;
|
|
}
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">import</span> std.stdio;
|
|
|
|
<span class="d_keyword">static</span> j = square(3); <span class="d_comment">// CTFE
|
|
</span> writeln(j);
|
|
<span class="d_keyword">assert</span>(square(4) == 16); <span class="d_comment">// run time
|
|
</span> <span class="d_keyword">static</span> <span class="d_keyword">assert</span>(square(3) == 9); <span class="d_comment">// CTFE
|
|
</span> writeln(eval!(square(5))); <span class="d_comment">// CTFE
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>The function must have a <a href="#FunctionBody"><i>FunctionBody</i></a>.</p>
|
|
<div class="blankline"></div>
|
|
<p>CTFE is subject to the following restrictions:</p>
|
|
<div class="blankline"></div>
|
|
<ol> <li>Expressions may not reference any mutable global/static variables.</li>
|
|
<div class="blankline"></div>
|
|
<li><a href="../spec/iasm.html#asmstatements"><em>AsmStatement</em>s</a> are not permitted.</li>
|
|
<div class="blankline"></div>
|
|
<li>Non-portable casts (e.g., from <span class="d_inlinecode donthyphenate notranslate">int[]</span> to <span class="d_inlinecode donthyphenate notranslate">float[]</span>), including
|
|
casts which depend on endianness, are not permitted.
|
|
Casts between signed and unsigned types are permitted.</li>
|
|
<div class="blankline"></div>
|
|
<li>Reinterpretation of overlapped fields in a union is not permitted.</li>
|
|
<div class="blankline"></div>
|
|
<li>Undefined behavior must not occur.</li>
|
|
<div class="blankline"></div>
|
|
<li>Non-recoverable errors (such as <span class="d_keyword">assert</span> failures) are not permitted.</li>
|
|
</ol>
|
|
<div class="blankline"></div>
|
|
<p>Pointers are permitted in CTFE, provided they are used safely:</p>
|
|
<div class="blankline"></div>
|
|
<ul> <li> Pointer arithmetic is permitted only on pointers which point to static
|
|
or dynamic array elements.
|
|
A pointer may also point to the first element past the array, although
|
|
such pointers cannot be dereferenced.
|
|
Pointer arithmetic on pointers which are null,
|
|
or which point to a non-array, is not allowed.
|
|
</li>
|
|
<div class="blankline"></div>
|
|
<li> Ordered comparison (<span class="d_inlinecode donthyphenate notranslate"><</span>, <span class="d_inlinecode donthyphenate notranslate"><</span><span class="d_inlinecode donthyphenate notranslate">=</span>, <span class="d_inlinecode donthyphenate notranslate">></span>, <span class="d_inlinecode donthyphenate notranslate">>=</span>) between two pointers is permitted
|
|
when both pointers point to the same array, or when at least one
|
|
pointer is <span class="d_inlinecode donthyphenate notranslate">null</span>.
|
|
</li>
|
|
<div class="blankline"></div>
|
|
<li> Pointer comparisons between discontiguous memory blocks are illegal,
|
|
unless two such comparisons are combined
|
|
using <span class="d_inlinecode donthyphenate notranslate">&&</span> or <span class="d_inlinecode donthyphenate notranslate">|</span><span class="d_inlinecode donthyphenate notranslate">|</span> to yield a result which is independent of the
|
|
ordering of memory blocks. Each comparison must consist of two pointer
|
|
expressions compared with <span class="d_inlinecode donthyphenate notranslate"><</span>, <span class="d_inlinecode donthyphenate notranslate"><</span><span class="d_inlinecode donthyphenate notranslate">=</span>, <span class="d_inlinecode donthyphenate notranslate">></span>,
|
|
or <span class="d_inlinecode donthyphenate notranslate">></span><span class="d_inlinecode donthyphenate notranslate">=</span>, and may optionally be
|
|
negated with <span class="d_inlinecode donthyphenate notranslate">!</span>.
|
|
For example, the expression <span class="d_inlinecode donthyphenate notranslate">(p1 > q1 && p2 <= q2)</span>
|
|
is permitted when <span class="d_inlinecode donthyphenate notranslate">p1</span>, <span class="d_inlinecode donthyphenate notranslate">p2</span> are expressions yielding pointers
|
|
to memory block <i>P</i>, and <span class="d_inlinecode donthyphenate notranslate">q1</span>, <span class="d_inlinecode donthyphenate notranslate">q2</span> are expressions yielding
|
|
pointers to memory block <i>Q</i>, even when <i>P</i> and <i>Q</i> are
|
|
unrelated memory blocks.
|
|
It returns true if <span class="d_inlinecode donthyphenate notranslate">[p1..p2]</span> lies inside <span class="d_inlinecode donthyphenate notranslate">[q1..q2]</span>, and false otherwise.
|
|
Similarly, the expression <span class="d_inlinecode donthyphenate notranslate">(p1 < q1 || p2 > q2)</span> is true if
|
|
<span class="d_inlinecode donthyphenate notranslate">[p1..p2]</span> lies outside <span class="d_inlinecode donthyphenate notranslate">[q1..q2]</span>, and false otherwise.
|
|
</li>
|
|
<div class="blankline"></div>
|
|
<li> Equality comparisons (<span class="d_inlinecode donthyphenate notranslate">==</span>, <span class="d_inlinecode donthyphenate notranslate">!=</span>, <span class="d_inlinecode donthyphenate notranslate">is</span>, <span class="d_inlinecode donthyphenate notranslate">!is</span>) are
|
|
permitted between all pointers, without restriction.
|
|
</li>
|
|
<div class="blankline"></div>
|
|
<li>The following pointer casts are permitted:</li>
|
|
|
|
<ul><li>Casting a pointer to <span class="d_inlinecode donthyphenate notranslate">void*</span> and from that <span class="d_inlinecode donthyphenate notranslate">void*</span> back to
|
|
its original type.</li>
|
|
<li>Casting from an integer pointer to another integer pointer
|
|
iff each integer type has the same size.
|
|
</li>
|
|
</ul>
|
|
<li>Casting between pointer and non-pointer types is illegal.</li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<p>The above restrictions apply only to expressions which are
|
|
actually evaluated. For example:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">static</span> <span class="d_keyword">int</span> y = 0;
|
|
|
|
<span class="d_keyword">int</span> countTen(<span class="d_keyword">int</span> x)
|
|
{
|
|
<span class="d_keyword">if</span> (x > 10)
|
|
++y; <span class="d_comment">// access static variable
|
|
</span> <span class="d_keyword">return</span> x;
|
|
}
|
|
|
|
<span class="d_keyword">static</span> <span class="d_keyword">assert</span>(countTen(6) == 6); <span class="d_comment">// OK
|
|
</span><span class="d_comment">//static assert(countTen(12) == 12); // Error, `y` is modified
|
|
</span></pre>
|
|
|
|
</div>
|
|
<p>The <span class="d_inlinecode donthyphenate notranslate">__ctfe</span> boolean pseudo-variable evaluates to <span class="d_keyword">true</span>
|
|
during CTFE but <span class="d_keyword">false</span> otherwise.
|
|
It cannot be read in a compile time context (such as a <span class="d_inlinecode donthyphenate notranslate">static if</span> condition).
|
|
</p>
|
|
<div class="spec-boxes rationale"><b>Rationale:</b> <span class="d_inlinecode donthyphenate notranslate">__ctfe</span> can be used to provide
|
|
an alternative execution path to avoid operations which are forbidden
|
|
in CTFE.
|
|
</div>
|
|
|
|
|
|
<div class="spec-boxes note"><b>Note:</b> Every usage of <span class="d_inlinecode donthyphenate notranslate">__ctfe</span> is statically evaluated and has no run time cost.</div>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> i = 10;
|
|
<span class="d_keyword">int</span> f() => __ctfe ? 5 : i; <span class="d_comment">// only read `i` at runtime
|
|
</span><span class="d_keyword">static</span> <span class="d_keyword">assert</span>(f() == 5);
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">assert</span>(f() == 10);
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>See also: The <a href="../spec/attribute.html#ctfeonly"><span class="d_inlinecode donthyphenate notranslate">@__ctfe</span> attribute</a>
|
|
disables run time code generation of a function.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> <ul><li>Executing functions via CTFE can take considerably
|
|
longer than executing it at run time.
|
|
If the function goes into an infinite loop, it may cause the compiler to hang.</li>
|
|
<li>Functions executed via CTFE can give different results
|
|
from run time when implementation-defined behavior occurs.
|
|
</li>
|
|
</ul></div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="string-mixins" href="#string-mixins">Run Time Values during CTFE</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>All functions that execute in CTFE must first pass semantic
|
|
checks for run time code generation. The compile time evaluation of
|
|
a function is similar to running the function at
|
|
run time. The compile time semantics of a function undergoing CTFE cannot
|
|
depend on values with a run time context. For example:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> foo(string s)
|
|
{
|
|
<span class="d_keyword">enum</span> e = s; <span class="d_comment">// Error: cannot read `s` at compile time
|
|
</span> <span class="d_keyword">return</span> <span class="d_keyword">mixin</span>(s); <span class="d_comment">// ditto
|
|
</span>}
|
|
|
|
<span class="d_keyword">const</span> <span class="d_keyword">int</span> x = foo(<span class="d_string">"1"</span>);
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> A function template, where <span class="d_inlinecode donthyphenate notranslate">s</span> is a template value argument,
|
|
would be the appropriate way to do this sort of thing.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="nogc-functions" href="#nogc-functions">No-GC Functions</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>No-GC functions are functions marked with the <span class="d_inlinecode donthyphenate notranslate">@nogc</span> attribute.
|
|
Those functions do not allocate memory on the GC heap.
|
|
These operations are not allowed in No-GC functions:
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<ol> <li><a href="../spec/expression.html#array-literal-heap">constructing an array</a> on the heap</li>
|
|
<li>resizing an array by writing to its <span class="d_inlinecode donthyphenate notranslate">.length</span> property</li>
|
|
<li><a href="../spec/expression.html#CatExpression">array concatenation</a></li>
|
|
<li><a href="../spec/expression.html#simple_assignment_expressions">array appending</a></li>
|
|
<li><a href="../spec/expression.html#AssocArrayLiteral">constructing an associative array</a></li>
|
|
<li><a href="../spec/expression.html#IndexOperation">indexing</a> an associative array
|
|
<div class="spec-boxes rationale"><b>Rationale:</b> Indexing may throw a <span class="d_inlinecode donthyphenate notranslate">RangeError</span> if the specified key is not present.</div>
|
|
|
|
</li>
|
|
<li><a href="../spec/expression.html#NewExpression">allocating an object with <span class="d_inlinecode donthyphenate notranslate">new</span></a> on the heap
|
|
<div class="spec-boxes note"><b>Note:</b> <span class="d_inlinecode donthyphenate notranslate">new</span> declarations of <span class="d_inlinecode donthyphenate notranslate">class</span> types in function scopes are compatible with
|
|
<span class="d_inlinecode donthyphenate notranslate">@nogc</span> if used to initialize a <a href="../spec/attribute.html#scope-class-var"><span class="d_inlinecode donthyphenate notranslate">scope</span> variable</a>,
|
|
as they result in allocations on the stack.</div></li>
|
|
<li>calling functions that are not <span class="d_inlinecode donthyphenate notranslate">@nogc</span>, unless the call is
|
|
in a <a href="../spec/version.html#ConditionalStatement"><i>ConditionalStatement</i></a>
|
|
controlled by a <a href="../spec/version.html#DebugCondition"><i>DebugCondition</i></a></li>
|
|
</ol>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">@nogc <span class="d_keyword">void</span> foo()
|
|
{
|
|
<span class="d_keyword">auto</span> a = ['a']; <span class="d_comment">// (1) error, allocates
|
|
</span> a.length = 1; <span class="d_comment">// (2) error, array resizing allocates
|
|
</span> a = a ~ a; <span class="d_comment">// (3) error, arrays concatenation allocates
|
|
</span> a ~= 'c'; <span class="d_comment">// (4) error, appending to arrays allocates
|
|
</span>
|
|
<span class="d_keyword">auto</span> aa = [<span class="d_string">"x"</span>:1]; <span class="d_comment">// (5) error, allocates
|
|
</span> aa[<span class="d_string">"abc"</span>]; <span class="d_comment">// (6) error, indexing may allocate and throws
|
|
</span>
|
|
<span class="d_keyword">auto</span> p = <span class="d_keyword">new</span> <span class="d_keyword">int</span>; <span class="d_comment">// (7) error, operator new allocates
|
|
</span> <span class="d_keyword">scope</span> <span class="d_keyword">auto</span> p = <span class="d_keyword">new</span> GenericClass(); <span class="d_comment">// (7) Ok
|
|
</span> bar(); <span class="d_comment">// (8) error, bar() may allocate
|
|
</span> <span class="d_keyword">debug</span> bar(); <span class="d_comment">// (8) Ok
|
|
</span>}
|
|
<span class="d_keyword">void</span> bar() { }
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>No-GC functions can only use a closure if it is <span class="d_inlinecode donthyphenate notranslate">scope</span> -
|
|
see <a href="#closures">Delegates & Closures</a>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">@nogc <span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() foo()
|
|
{
|
|
<span class="d_keyword">int</span> n; <span class="d_comment">// error, variable n cannot be allocated on heap
|
|
</span> <span class="d_keyword">return</span> (){ <span class="d_keyword">return</span> n; } <span class="d_comment">// since `n` escapes `foo()`, a closure is required
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p><span class="d_inlinecode donthyphenate notranslate">@nogc</span> affects the type of the function. A <span class="d_inlinecode donthyphenate notranslate">@nogc</span>
|
|
function is <a href="../spec/type.html#covariance">covariant</a> with a non-<span class="d_inlinecode donthyphenate notranslate">@nogc</span> function.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> <span class="d_keyword">function</span>() fp;
|
|
<span class="d_keyword">void</span> <span class="d_keyword">function</span>() @nogc gp; <span class="d_comment">// pointer to @nogc function
|
|
</span>
|
|
<span class="d_keyword">void</span> foo();
|
|
@nogc <span class="d_keyword">void</span> bar();
|
|
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
fp = &foo; <span class="d_comment">// same type
|
|
</span> fp = &bar; <span class="d_comment">// ok, it's covariant
|
|
</span> <span class="d_comment">//gp = &foo; // error, not covariant
|
|
</span> gp = &bar; <span class="d_comment">// same type
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> Since a function marked <span class="d_inlinecode donthyphenate notranslate">@nogc</span> will not do any GC allocations,
|
|
that implies it will not cause any GC collections to run. However,
|
|
another thread may still allocate with the GC and trigger a collection.
|
|
The recommended way to prevent GC collections from being run is to call
|
|
<a href="https://dlang.org/phobos/core_memory.html#GC.disable">core.memory.GC.disable()</a>
|
|
instead. This will stop collections from being run in any thread until a corresponding
|
|
call to <span class="d_inlinecode donthyphenate notranslate">core.memory.GC.enable()</span> is run. GC allocations can still be performed
|
|
when <span class="d_inlinecode donthyphenate notranslate">GC.disable()</span> is in effect.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="function-safety" href="#function-safety">Function Safety</a></h2>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="safe-functions" href="#safe-functions">Safe Functions</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>Safe functions are marked with the <span class="d_inlinecode donthyphenate notranslate">@safe</span> attribute.
|
|
<span class="d_inlinecode donthyphenate notranslate">@safe</span> can be inferred,
|
|
see <a href="#function-attribute-inference">Function Attribute Inference</a>.</p>
|
|
<div class="blankline"></div>
|
|
<p>Safe functions have <a href="#safe-interfaces">safe
|
|
interfaces</a>. An implementation must enforce this by restricting the
|
|
function's body to operations that are known to be safe,
|
|
except for calls to <a href="#trusted-functions"><span class="d_inlinecode donthyphenate notranslate">@trusted</span> functions</a>.</p>
|
|
<div class="blankline"></div>
|
|
<p>The following restrictions are enforced by the compiler in safe
|
|
functions:</p>
|
|
<div class="blankline"></div>
|
|
<ul> <li>No casting from a pointer type <span class="d_inlinecode donthyphenate notranslate">T</span> to any type <span class="d_inlinecode donthyphenate notranslate">U</span> with pointers, except when:</li>
|
|
<ul><li><span class="d_inlinecode donthyphenate notranslate">T</span> implicitly converts to <span class="d_inlinecode donthyphenate notranslate">U</span></li>
|
|
<li><span class="d_inlinecode donthyphenate notranslate">U</span> <a href="../spec/expression.html#cast_class">implements</a> class or interface
|
|
<span class="d_inlinecode donthyphenate notranslate">T</span>, and both types are <span class="d_inlinecode donthyphenate notranslate">extern(D)</span></li>
|
|
<li><span class="d_inlinecode donthyphenate notranslate">T.opCast!U</span> is <span class="d_inlinecode donthyphenate notranslate">@safe</span></li>
|
|
<li>Both types <a href="../spec/expression.html#cast_array">are dynamic arrays</a>, or
|
|
both types <a href="../spec/expression.html#cast_pointers">are raw pointers</a>, and:
|
|
<ul><li>The target element type is not a pointer type</li>
|
|
<li>The target element type is not mutable when the source element type is a pointer type</li>
|
|
<li>Either the target element type is a dynamic array, or the target element
|
|
type is no larger than the source element type</li>
|
|
<li>Any source element type modifiers implicitly convert to the target element type modifiers</li>
|
|
<li>Neither element type is a function type</li>
|
|
<li>The target element type is not mutable when the source type is <span class="d_inlinecode donthyphenate notranslate">void[]</span></li>
|
|
<li>The target element type only stores <a href="#safe-values">safe values</a></li>
|
|
<li>The source element type only stores safe values when the target element type is mutable</li>
|
|
<li>Neither element type is <a href="../spec/struct.html#opaque_struct_unions">opaque</a>.</li>
|
|
</ul></li>
|
|
</ul>
|
|
<li>No casting from any non-pointer type to a pointer type.</li>
|
|
<li>No <a href="../spec/expression.html#pointer_arithmetic">pointer arithmetic</a>
|
|
(including pointer indexing & slicing).</li>
|
|
<li>Cannot access array <a href="../spec/arrays.html#ptr-property"><span class="d_inlinecode donthyphenate notranslate">.ptr</span> property</a>.</li>
|
|
<li>Cannot copy into a <a href="../spec/arrays.html#void_arrays">void array</a>.</li>
|
|
<li>Cannot access union fields that:</li>
|
|
<ul><li>Have pointers or references overlapping with other types</li>
|
|
<li>Have invariants overlapping with other types</li>
|
|
<li>Overlap with fields that could become <a href="#safe-values">unsafe values</a></li>
|
|
</ul>
|
|
<li>Calling any <a href="#system-functions">System Functions</a>.</li>
|
|
<li>No catching of exceptions that are not derived from
|
|
<a href="https://dlang.org/phobos/object.html#.Exception"><span class="d_inlinecode donthyphenate notranslate">class Exception</span></a>.</li>
|
|
<li><a href="../spec/iasm.html#asmstatements">Inline assembler</a> must be marked as
|
|
<span class="d_inlinecode donthyphenate notranslate">@trusted</span>.</li>
|
|
<li>No explicit casting (except with a matching <span class="d_inlinecode donthyphenate notranslate">@safe</span> <span class="d_inlinecode donthyphenate notranslate">opCast</span>) of:</li>
|
|
<ul><li>mutable objects to immutable (except basic data types)</li>
|
|
<li>immutable objects to mutable (except basic data types)</li>
|
|
<li>thread local objects to shared</li>
|
|
<li>shared objects to thread local</li>
|
|
</ul>
|
|
<li>Cannot access <a href="../spec/attribute.html#system-variables"><span class="d_inlinecode donthyphenate notranslate">@system</span></a>
|
|
or <span class="d_inlinecode donthyphenate notranslate">__gshared</span> variables.</li>
|
|
<li>Cannot use <span class="d_inlinecode donthyphenate notranslate">void</span> initializers for types containing:</li>
|
|
<ul><li>Pointers/reference types</li>
|
|
<li>Types with invariants</li>
|
|
<li>Unsafe values</li>
|
|
</ul>
|
|
<li>Cannot use <a href="../spec/expression.html#RvalueExpression"><i>RvalueExpression</i></a>.</li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> When indexing or slicing an array, an out of bounds access
|
|
will cause a runtime error.
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>Functions nested inside safe functions default to being
|
|
safe functions.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Safe functions are <a href="../spec/type.html#covariance">covariant</a> with
|
|
trusted or system functions.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> Mark as many functions <span class="d_inlinecode donthyphenate notranslate">@safe</span> as practical.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<h4>Safe External Functions</h4>
|
|
<div class="blankline"></div>
|
|
<p>External functions don't have a function body visible to the compiler:
|
|
</p>
|
|
<pre class="d_code notranslate">@safe <span class="d_keyword">extern</span> (C) <span class="d_keyword">void</span> play();
|
|
</pre>
|
|
and so safety cannot be verified automatically.
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> Explicitly set an attribute for external functions rather
|
|
than relying on default settings.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="trusted-functions" href="#trusted-functions">Trusted Functions</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>Trusted functions are marked with the <span class="d_inlinecode donthyphenate notranslate">@trusted</span> attribute.</p>
|
|
<div class="blankline"></div>
|
|
<p>Like <a href="#safe-functions">safe functions</a>, trusted
|
|
functions have <a href="#safe-interfaces">safe interfaces</a>.
|
|
Unlike safe functions, this is not enforced by restrictions on the
|
|
function body. Instead, it is the responsibility of the programmer to
|
|
ensure that the interface of a trusted function is safe.</p>
|
|
<div class="blankline"></div>
|
|
<p>Example:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">immutable</span>(<span class="d_keyword">int</span>)* f(<span class="d_keyword">int</span>* p) @trusted
|
|
{
|
|
<span class="d_keyword">version</span> (none) p[2] = 13;
|
|
<span class="d_comment">// Invalid. p[2] is out of bounds. This line would exhibit undefined
|
|
</span> <span class="d_comment">// behavior.
|
|
</span>
|
|
<span class="d_keyword">version</span> (none) p[1] = 13;
|
|
<span class="d_comment">// Invalid. In this program, p[1] happens to be in-bounds, so the
|
|
</span> <span class="d_comment">// line would not exhibit undefined behavior, but a trusted function
|
|
</span> <span class="d_comment">// is not allowed to rely on this.
|
|
</span>
|
|
<span class="d_keyword">version</span> (none) <span class="d_keyword">return</span> <span class="d_keyword">cast</span>(<span class="d_keyword">immutable</span>) p;
|
|
<span class="d_comment">// Invalid. @safe code still has mutable access and could trigger
|
|
</span> <span class="d_comment">// undefined behavior by overwriting the value later on.
|
|
</span>
|
|
<span class="d_keyword">int</span>* p2 = <span class="d_keyword">new</span> <span class="d_keyword">int</span>;
|
|
*p2 = 42;
|
|
<span class="d_keyword">return</span> <span class="d_keyword">cast</span>(<span class="d_keyword">immutable</span>) p2;
|
|
<span class="d_comment">// Valid. After f returns, no mutable aliases of p2 can exist.
|
|
</span>}
|
|
|
|
<span class="d_keyword">void</span> main() @safe
|
|
{
|
|
<span class="d_keyword">int</span>[2] a = [10, 20];
|
|
<span class="d_keyword">int</span>* mp = &a[0];
|
|
<span class="d_keyword">immutable</span>(<span class="d_keyword">int</span>)* ip = f(mp);
|
|
<span class="d_keyword">assert</span>(a[1] == 20); <span class="d_comment">// Guaranteed. f cannot access a[1].
|
|
</span> <span class="d_keyword">assert</span>(ip !<span class="d_keyword">is</span> mp); <span class="d_comment">// Guaranteed. f cannot introduce unsafe aliasing.
|
|
</span>}
|
|
</pre>
|
|
|
|
<ul><li>Trusted functions may call safe, trusted, or system functions.</li>
|
|
<li>Trusted functions are <a href="../spec/type.html#covariance">contravariant</a>
|
|
with safe or system functions.
|
|
</li>
|
|
</ul>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> Trusted functions should be kept small so
|
|
that they are easier to manually verify.
|
|
</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="system-functions" href="#system-functions">System Functions</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>System functions are functions not marked with <span class="d_inlinecode donthyphenate notranslate">@safe</span> or
|
|
<span class="d_inlinecode donthyphenate notranslate">@trusted</span>
|
|
and are not nested inside <span class="d_inlinecode donthyphenate notranslate">@safe</span> functions.
|
|
System functions may be marked with the <span class="d_inlinecode donthyphenate notranslate">@system</span> attribute.
|
|
A function being system does not mean it actually is unsafe, it just
|
|
means that its safety must be manually verified.
|
|
</p>
|
|
|
|
<ul><li>System functions can call safe and trusted functions.</li>
|
|
<li>System functions are <b>not</b> <a href="../spec/type.html#covariance">covariant</a>
|
|
with trusted or safe functions.
|
|
</li>
|
|
</ul>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> When in doubt, mark <span class="d_inlinecode donthyphenate notranslate">extern (C)</span> and <span class="d_inlinecode donthyphenate notranslate">extern (C++)</span> functions as
|
|
<span class="d_inlinecode donthyphenate notranslate">@system</span> when their implementations are not in D, as the D compiler will be
|
|
unable to check them. Most of them are <span class="d_inlinecode donthyphenate notranslate">@safe</span>, but will need to be manually
|
|
checked.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes best-practice"><b>Best Practices:</b> The number and size of system functions should be minimized.
|
|
This minimizes the work necessary to manually check for safety.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="safe-interfaces" href="#safe-interfaces">Safe Interfaces</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>When a function call's arguments, <a href="#closures">any context</a>
|
|
and accessible globals each have <a href="#safe-values">safe
|
|
values</a> with <a href="#safe-aliasing">safe aliasing</a>, that
|
|
function has a safe interface when:</p>
|
|
<ol> <li>it cannot exhibit
|
|
<a href="../spec/glossary.html#undefined_behavior">undefined behavior</a>,
|
|
and</li>
|
|
<li>it cannot create unsafe values that are accessible from
|
|
<span class="d_inlinecode donthyphenate notranslate">@safe</span> code (e.g., via return values, global variables,
|
|
or <span class="d_inlinecode donthyphenate notranslate">ref</span> parameters), and</li>
|
|
<li>it cannot introduce unsafe aliasing that is accessible from
|
|
<span class="d_inlinecode donthyphenate notranslate">@safe</span> code.</li>
|
|
</ol>
|
|
<div class="blankline"></div>
|
|
<p>Functions that meet these requirements may be
|
|
<a href="#safe-functions"><span class="d_inlinecode donthyphenate notranslate">@safe</span></a> or
|
|
<a href="#trusted-functions"><span class="d_inlinecode donthyphenate notranslate">@trusted</span></a>. Function that do not
|
|
meet these requirements can only be
|
|
<a href="#system-functions"><span class="d_inlinecode donthyphenate notranslate">@system</span></a>.</p>
|
|
<div class="blankline"></div>
|
|
<p>Examples:</p>
|
|
<div class="blankline"></div>
|
|
<ul> <li> C's <span class="d_inlinecode donthyphenate notranslate">free</span> does not have a safe interface:
|
|
<pre class="d_code notranslate"><span class="d_keyword">extern</span> (C) @system <span class="d_keyword">void</span> free(<span class="d_keyword">void</span>* ptr);
|
|
</pre>
|
|
because <span class="d_inlinecode donthyphenate notranslate">free(p)</span> invalidates <span class="d_inlinecode donthyphenate notranslate">p</span>, making its value unsafe.
|
|
<span class="d_inlinecode donthyphenate notranslate">free</span> can only be <span class="d_inlinecode donthyphenate notranslate">@system</span>.
|
|
</li>
|
|
<li> C's <span class="d_inlinecode donthyphenate notranslate">strlen</span> and <span class="d_inlinecode donthyphenate notranslate">memcpy</span> do not have safe interfaces:
|
|
<pre class="d_code notranslate"><span class="d_keyword">extern</span> (C) @system size_t strlen(<span class="d_keyword">char</span>* s);
|
|
<span class="d_keyword">extern</span> (C) @system <span class="d_keyword">void</span>* memcpy(<span class="d_keyword">void</span>* dst, <span class="d_keyword">void</span>* src, size_t nbytes);
|
|
</pre>
|
|
because they iterate pointers based on unverified assumptions
|
|
(<span class="d_inlinecode donthyphenate notranslate">strlen</span> assumes that <span class="d_inlinecode donthyphenate notranslate">s</span> is zero-terminated; <span class="d_inlinecode donthyphenate notranslate">memcpy</span> assumes
|
|
that the memory objects pointed to by <span class="d_inlinecode donthyphenate notranslate">dst</span> and <span class="d_inlinecode donthyphenate notranslate">src</span> are at least <span class="d_inlinecode donthyphenate notranslate">nbytes</span> big). Any function
|
|
that traverses a C string passed as an argument can only be
|
|
<span class="d_inlinecode donthyphenate notranslate">@system</span>. Any function that trusts a separate parameter for
|
|
array bounds can only be <span class="d_inlinecode donthyphenate notranslate">@system</span>.
|
|
</li>
|
|
<li> C's <span class="d_inlinecode donthyphenate notranslate">malloc</span> does have a safe interface:
|
|
<pre class="d_code notranslate"><span class="d_keyword">extern</span> (C) @trusted <span class="d_keyword">void</span>* malloc(size_t sz);
|
|
</pre>
|
|
It does not exhibit undefined behavior for any input. It returns
|
|
either a valid pointer, which is safe, or <span class="d_inlinecode donthyphenate notranslate">null</span> which is also
|
|
safe. It returns a pointer to a fresh allocation, so it cannot
|
|
introduce any unsafe aliasing.
|
|
<div class="spec-boxes note"><b>Note:</b> The implementation of <span class="d_inlinecode donthyphenate notranslate">malloc</span> is most likely @system code.</div>
|
|
</li>
|
|
<li> A D version of <span class="d_inlinecode donthyphenate notranslate">memcpy</span> can have a safe interface:
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate">@safe <span class="d_keyword">void</span> memcpy(E)(E[] src, E[] dst)
|
|
{
|
|
<span class="d_keyword">import</span> std.math : min;
|
|
<span class="d_keyword">foreach</span> (i; 0 .. min(src.length, dst.length))
|
|
{
|
|
dst[i] = src[i];
|
|
}
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
because the rules for <a href="#safe-values">safe
|
|
values</a> ensure that the lengths of the arrays are correct.
|
|
</li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="safe-values" href="#safe-values">Safe Values</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>A variable or field <a href="../spec/attribute.html#system-variables"> marked as <span class="d_inlinecode donthyphenate notranslate">@system</span></a> does not hold a safe value, regardless of its type.</p>
|
|
<div class="blankline"></div>
|
|
<p>For a <a href="../spec/type.html#bool"><span class="d_inlinecode donthyphenate notranslate">bool</span></a>, only 0 and 1 are safe values.</p>
|
|
<div class="blankline"></div>
|
|
<p>For all other <a href="../spec/type.html#basic-data-types">basic data types</a>, all
|
|
possible bit patterns are safe.</p>
|
|
<div class="blankline"></div>
|
|
<p>A pointer is a safe value when it is one of:</p>
|
|
<ol> <li><span class="d_inlinecode donthyphenate notranslate">null</span> - <a href="#null-dereferences">see below</a></li>
|
|
<li>it points to a memory object that is live and
|
|
the pointed to value in that memory object is safe.</li>
|
|
</ol>
|
|
<p>Examples:</p>
|
|
<div class="runnable-examples">
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span>* n = <span class="d_keyword">null</span>; <span class="d_comment">/* n is safe because dereferencing null must either crash
|
|
or abort. */</span>
|
|
<span class="d_keyword">int</span>* x = <span class="d_keyword">cast</span>(<span class="d_keyword">int</span>*) 0xDEADBEEF; <span class="d_comment">/* x is (most likely) unsafe because it
|
|
is not a valid pointer and cannot be dereferenced. */</span>
|
|
|
|
<span class="d_keyword">import</span> core.stdc.stdlib: malloc, free;
|
|
<span class="d_keyword">int</span>* p1 = <span class="d_keyword">cast</span>(<span class="d_keyword">int</span>*) malloc(<span class="d_keyword">int</span>.sizeof); <span class="d_comment">/* p1 is safe because the
|
|
pointer is valid and *p1 is safe regardless of its actual value. */</span>
|
|
free(p1); <span class="d_comment">/* This makes p1 unsafe. */</span>
|
|
<span class="d_keyword">int</span>** p2 = &p1; <span class="d_comment">/* While it can be dereferenced, p2 is unsafe because p1
|
|
is unsafe. */</span>
|
|
p1 = <span class="d_keyword">null</span>; <span class="d_comment">/* This makes p1 and p2 safe. */</span>
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>A dynamic array is safe when:</p>
|
|
<ol> <li>its pointer is safe, and</li>
|
|
<li>its length is in-bounds with the corresponding memory object,
|
|
and</li>
|
|
<li>all its elements are safe.</li>
|
|
</ol>
|
|
<div class="blankline"></div>
|
|
<p>Examples:</p>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span>[] f() @system
|
|
{
|
|
<span class="d_keyword">bool</span> b = <span class="d_keyword">true</span>; <span class="d_comment">/* b is initialized safe */</span>
|
|
*(<span class="d_keyword">cast</span>(<span class="d_keyword">ubyte</span>*) &b) = 0xAA; <span class="d_comment">/* b is now unsafe because it's not 0 or 1 */</span>
|
|
<span class="d_keyword">int</span>[3] a;
|
|
<span class="d_keyword">int</span>[] d1 = a[0 .. 3]; <span class="d_comment">/* d1 is safe. */</span>
|
|
<span class="d_keyword">int</span>[] d2 = a.ptr[0 .. 4]; <span class="d_comment">/* d2 is unsafe because it goes beyond a's
|
|
bounds. */</span>
|
|
<span class="d_keyword">int</span>*[] d3 = [<span class="d_keyword">cast</span>(<span class="d_keyword">int</span>*) 0xDEADBEEF]; <span class="d_comment">/* d3 is unsafe because the
|
|
element is unsafe. */</span>
|
|
<span class="d_keyword">return</span> d1; <span class="d_comment">/* Up to here, d1 was safe, but its pointer becomes
|
|
invalid when the function returns, so the returned dynamic array
|
|
is unsafe. */</span>
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>A static array is safe when all its elements are safe. Regardless
|
|
of the element type, a static array with length zero is always safe.</p>
|
|
<div class="blankline"></div>
|
|
<p>An associative array is safe when all its keys and elements are
|
|
safe.</p>
|
|
<div class="blankline"></div>
|
|
<p>A struct/union instance is safe when:</p>
|
|
<ol> <li>the values of its accessible fields are safe, and</li>
|
|
<li>it does not introduce <a href="#safe-aliasing">unsafe
|
|
aliasing</a> with unions.</li>
|
|
</ol>
|
|
<div class="blankline"></div>
|
|
<p>Examples:</p>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate">
|
|
<span class="d_keyword">void</span> fun()
|
|
{
|
|
<span class="d_keyword">struct</span> S { <span class="d_keyword">int</span>* p; }
|
|
S s1 = S(<span class="d_keyword">new</span> <span class="d_keyword">int</span>); <span class="d_comment">/* s1 is safe. */</span>
|
|
S s2 = S(<span class="d_keyword">cast</span>(<span class="d_keyword">int</span>*) 0xDEADBEEF); <span class="d_comment">/* s2 is unsafe, because s2.p is
|
|
unsafe. */</span>
|
|
|
|
<span class="d_keyword">union</span> U { <span class="d_keyword">int</span>* p; size_t x; }
|
|
U u = U(<span class="d_keyword">new</span> <span class="d_keyword">int</span>); <span class="d_comment">/* Even though both u.p and u.x are safe, u is unsafe
|
|
because of unsafe aliasing. */</span>
|
|
}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<p>A class reference is safe when it is <span class="d_inlinecode donthyphenate notranslate">null</span> or:</p>
|
|
<ol> <li>it refers to a valid class instance of the class type or a
|
|
type derived from the class type, and</li>
|
|
<li>the values of the instance's accessible fields are safe, and</li>
|
|
<li>it does not introduce unsafe aliasing with unions.</li>
|
|
</ol>
|
|
<div class="blankline"></div>
|
|
<p>A function pointer is safe when it is <span class="d_inlinecode donthyphenate notranslate">null</span> or it refers to a valid
|
|
function that has the same or a <a href="../spec/type.html#covariance">covariant</a> signature.</p>
|
|
<div class="blankline"></div>
|
|
<p>A <span class="d_inlinecode donthyphenate notranslate">delegate</span> is safe when:</p>
|
|
<ol> <li>its <span class="d_inlinecode donthyphenate notranslate">.funcptr</span> property is <span class="d_inlinecode donthyphenate notranslate">null</span> or refers to a function that matches
|
|
or is covariant with the delegate type, and</li>
|
|
<li>its <span class="d_inlinecode donthyphenate notranslate">.ptr</span> property is <span class="d_inlinecode donthyphenate notranslate">null</span> or refers to a memory object that is in a form
|
|
expected by the function.</li>
|
|
</ol>
|
|
<div class="blankline"></div>
|
|
<h3><a class="anchor" title="Permalink to this section" id="null-dereferences" href="#null-dereferences">Null Dereferences</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>When generating <span class="d_inlinecode donthyphenate notranslate">@safe</span> code, a compliant implementation:</p>
|
|
|
|
<ul><li>Must not assume that a null dereference will not occur. Optimizations
|
|
that require that assumption cannot be used for <span class="d_inlinecode donthyphenate notranslate">@safe</span> functions.</li>
|
|
<li>Must generate code that will detect and abort execution:
|
|
<ul><li>When a null dereference occurs on systems that by default do not protect
|
|
access to the first page of memory addresses. (Note that e.g. calling
|
|
<a href="https://pubs.opengroup.org/onlinepubs/007904875/functions/mprotect.html"><span class="d_inlinecode donthyphenate notranslate">mprotect</span></a>
|
|
is <span class="d_inlinecode donthyphenate notranslate">@system</span>).</li>
|
|
<li>On all systems when an expression causes a null pointer to be indexed,
|
|
causing a memory access that is not prevented by the system.
|
|
<span class="red">Warning:</span> <em class="tt">dmd</em>
|
|
<a href="https://github.com/dlang/dmd/issues/17776">has not implemented</a> this yet.
|
|
</li>
|
|
</ul></li>
|
|
</ul>
|
|
<h3><a class="anchor" title="Permalink to this section" id="safe-aliasing" href="#safe-aliasing">Safe Aliasing</a></h3>
|
|
<div class="blankline"></div>
|
|
<p>When one memory location is accessible with two different types, that
|
|
aliasing is considered safe if:</p>
|
|
<ol> <li>both types are <span class="d_inlinecode donthyphenate notranslate">const</span> or <span class="d_inlinecode donthyphenate notranslate">immutable</span>; or</li>
|
|
<li>one of the types is mutable while the other is a <span class="d_inlinecode donthyphenate notranslate">const</span>-qualified
|
|
<a href="../spec/type.html#basic-data-types">basic data type</a>; or</li>
|
|
<li>both types are mutable basic data types; or</li>
|
|
<li>one of the types is a static array type with length zero; or</li>
|
|
<li>one of the types is a static array type with non-zero length, and
|
|
aliasing of the array's element type and the other type is safe; or</li>
|
|
<li>both types are pointer types, and aliasing of the target types is
|
|
safe, and the target types have the same size.</li>
|
|
</ol>
|
|
<div class="blankline"></div>
|
|
<p>All other cases of aliasing are considered unsafe.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> Safe aliasing may be exposed to functions with
|
|
<a href="#safe-interfaces">safe interfaces</a> without affecting their
|
|
guaranteed safety. Unsafe aliasing does not guarantee safety.</div>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes note"><b>Note:</b> Safe aliasing does not imply that all aliased
|
|
views of the data have <a href="#safe-values">safe values</a>.
|
|
Those must be examined separately for safety.</div>
|
|
<div class="blankline"></div>
|
|
<p>Examples:</p>
|
|
<div class="blankline"></div>
|
|
<div class="runnable-examples" data-compile=''>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> f1(<span class="d_keyword">ref</span> <span class="d_keyword">ubyte</span> x, <span class="d_keyword">ref</span> <span class="d_keyword">float</span> y) @safe { x = 0; y = <span class="d_keyword">float</span>.init; }
|
|
<span class="d_keyword">union</span> U1 { <span class="d_keyword">ubyte</span> x; <span class="d_keyword">float</span> y; } <span class="d_comment">// safe aliasing
|
|
</span>
|
|
<span class="d_keyword">void</span> test1()
|
|
{
|
|
U1 u1;
|
|
f1(u1.x, u1.y); <span class="d_comment">// Ok
|
|
</span>}
|
|
|
|
<span class="d_keyword">void</span> f2(<span class="d_keyword">ref</span> <span class="d_keyword">int</span>* x, <span class="d_keyword">ref</span> <span class="d_keyword">int</span> y) @trusted { x = <span class="d_keyword">new</span> <span class="d_keyword">int</span>; y = 0xDEADBEEF; }
|
|
<span class="d_keyword">union</span> U2 { <span class="d_keyword">int</span>* x; <span class="d_keyword">int</span> y; } <span class="d_comment">// unsafe aliasing
|
|
</span>
|
|
<span class="d_keyword">void</span> test2()
|
|
{
|
|
U2 u2;
|
|
<span class="d_keyword">version</span> (none) f1(u2.x, u2.y); <span class="d_comment">// not safe
|
|
</span>}
|
|
</pre>
|
|
|
|
</div>
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="function-attribute-inference" href="#function-attribute-inference">Function Attribute Inference</a></h2>
|
|
<div class="blankline"></div>
|
|
<p><a href="../spec/expression.html#FunctionLiteral"><i>FunctionLiteral</i></a>s,
|
|
<a href="#auto-functions">Auto Functions</a>,
|
|
<a href="#auto-ref-functions">Auto Ref Functions</a>,
|
|
<a href="#nested">nested functions</a> and
|
|
<a href="../spec/template.html#function-templates">function templates</a>,
|
|
since their function bodies are always present, infer the
|
|
following attributes unless specifically overridden:
|
|
</p>
|
|
<ul><li><a href="#pure-functions"><span class="d_inlinecode donthyphenate notranslate">pure</span></a></li>
|
|
<li><a href="#nothrow-functions"><span class="d_inlinecode donthyphenate notranslate">nothrow</span></a></li>
|
|
<li><a href="#safe-functions"><span class="d_inlinecode donthyphenate notranslate">@safe</span></a></li>
|
|
<li><a href="#nogc-functions"><span class="d_inlinecode donthyphenate notranslate">@nogc</span></a>
|
|
</li>
|
|
</ul>
|
|
<p>Likewise, the following parameter attributes will be inferred:</p>
|
|
|
|
<ul><li><a href="#return-ref-parameters"><span class="d_inlinecode donthyphenate notranslate">return ref</span></a></li>
|
|
<li><a href="#scope-parameters"><span class="d_inlinecode donthyphenate notranslate">scope</span></a></li>
|
|
<li><a href="#return-scope-parameters"><span class="d_inlinecode donthyphenate notranslate">return scope</span></a></li>
|
|
<li><a href="#ref-return-scope-parameters"><span class="d_inlinecode donthyphenate notranslate">ref return scope</span></a>
|
|
</li>
|
|
</ul>
|
|
<p>Attribute inference is not done for other functions, even if the function
|
|
body is present.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>The inference is done by determining if the function body follows the
|
|
rules of the particular attribute.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>Cyclic functions (i.e. functions that wind up directly or indirectly
|
|
calling themselves) are inferred as being impure, throwing, and <span class="d_inlinecode donthyphenate notranslate">@system</span>.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<p>If a function attempts to test itself for those attributes, then
|
|
the function is inferred as not having those attributes.
|
|
</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes rationale"><b>Rationale:</b> Function attribute inference greatly reduces the need for the user to add attributes
|
|
to functions, especially for templates.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<h2><a class="anchor" title="Permalink to this section" id="pseudo-member" href="#pseudo-member">Uniform Function Call Syntax (UFCS)</a></h2>
|
|
<div class="blankline"></div>
|
|
<p>A free function can be called like a member function when both:</p>
|
|
<ul> <li>The member function does not (or cannot) exist for the object expression</li>
|
|
<li>The free function's first parameter type matches the object expression</li>
|
|
</ul>
|
|
<p>The object expression can be any type.
|
|
This is called a <i>UFCS function call</i>.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">void</span> sun(T, <span class="d_keyword">int</span>);
|
|
|
|
<span class="d_keyword">void</span> moon(T t)
|
|
{
|
|
t.sun(1);
|
|
<span class="d_comment">// If `T` does not have a member function `sun`,
|
|
</span> <span class="d_comment">// `t.sun(1)` is interpreted as if it were written `sun(t, 1)`
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes rationale"><b>Rationale:</b> This provides a way to add external functions to a class as if they were
|
|
public <a href="#final"><span class="d_inlinecode donthyphenate notranslate">final</span></a> member functions.
|
|
This enables minimizing the number of functions in a class to only the essentials that
|
|
are needed to take care of the object's private state, without the temptation to add
|
|
a kitchen-sink's worth of member functions.
|
|
It also enables
|
|
<a href="http://www.drdobbs.com/architecture-and-design/component-programming-in-d/240008321"> function chaining and component programming</a>.
|
|
</div>
|
|
|
|
|
|
This general idea has different names in other programming languages.
|
|
The following is a short list:
|
|
<ul> <li>C#: Extension methods</li>
|
|
<li>Kotlin: Extension functions</li>
|
|
<li>Zig: Dot notation</li>
|
|
</ul>
|
|
<div class="blankline"></div>
|
|
<p>A more complex example:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">stdin.byLine(KeepTerminator.yes)
|
|
.map!(a => a.idup)
|
|
.array
|
|
.sort
|
|
.copy(stdout.lockingTextWriter());
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>is the equivalent of:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">copy(sort(array(map!(a => a.idup)(byLine(stdin, KeepTerminator.yes)))), lockingTextWriter(stdout));
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>UFCS works with <span class="d_inlinecode donthyphenate notranslate">@property</span> functions:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate">@property prop(X thisObj);
|
|
@property prop(X thisObj, <span class="d_keyword">int</span> value);
|
|
|
|
X obj;
|
|
obj.prop; <span class="d_comment">// if X does not have member prop, reinterpret as prop(obj);
|
|
</span>obj.prop = 1; <span class="d_comment">// similarly, reinterpret as prop(obj, 1);
|
|
</span></pre>
|
|
<div class="blankline"></div>
|
|
<p>Functions declared in a local scope are not found when searching for a matching
|
|
UFCS function. Neither are other local symbols, although local imports are searched:</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">module</span> a;
|
|
|
|
<span class="d_keyword">void</span> foo(X);
|
|
<span class="d_keyword">alias</span> boo = foo;
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">void</span> bar(X); <span class="d_comment">// bar declared in local scope
|
|
</span> <span class="d_keyword">import</span> b : baz; <span class="d_comment">// void baz(X);
|
|
</span>
|
|
X obj;
|
|
obj.foo(); <span class="d_comment">// OK, calls a.foo;
|
|
</span> <span class="d_comment">//obj.bar(); // NG, UFCS does not see nested functions
|
|
</span> obj.baz(); <span class="d_comment">// OK, calls b.baz, because it is declared at the
|
|
</span> <span class="d_comment">// top level scope of module b
|
|
</span>
|
|
<span class="d_keyword">import</span> b : boo = baz;
|
|
obj.boo(); <span class="d_comment">// OK, calls aliased b.baz instead of a.boo (== a.foo),
|
|
</span> <span class="d_comment">// because the declared alias name 'boo' in local scope
|
|
</span> <span class="d_comment">// overrides module scope name
|
|
</span>}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Member functions are not found when searching for a matching
|
|
UFCS function.</p>
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">class</span> C
|
|
{
|
|
<span class="d_keyword">void</span> mfoo(X); <span class="d_comment">// member function
|
|
</span> <span class="d_keyword">static</span> <span class="d_keyword">void</span> sbar(X); <span class="d_comment">// static member function
|
|
</span> <span class="d_keyword">import</span> b : ibaz = baz; <span class="d_comment">// void baz(X);
|
|
</span>
|
|
<span class="d_keyword">void</span> test()
|
|
{
|
|
X obj;
|
|
<span class="d_comment">//obj.mfoo(); // NG, UFCS does not see member functions
|
|
</span> <span class="d_comment">//obj.sbar(); // NG, UFCS does not see static member functions
|
|
</span> obj.ibaz(); <span class="d_comment">// OK, ibaz is an alias of baz which is declared at
|
|
</span> <span class="d_comment">// the top level scope of module b
|
|
</span> }
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
<p>Otherwise, UFCS function lookup proceeds normally.</p>
|
|
<div class="blankline"></div>
|
|
<div class="spec-boxes rationale"><b>Rationale:</b> Local function symbols are not considered by UFCS
|
|
to avoid unexpected name conflicts. See below for problematic examples.</div>
|
|
|
|
|
|
<div class="blankline"></div>
|
|
<pre class="d_code notranslate"><span class="d_keyword">int</span> front(<span class="d_keyword">int</span>[] arr) { <span class="d_keyword">return</span> arr[0]; }
|
|
|
|
<span class="d_keyword">void</span> main()
|
|
{
|
|
<span class="d_keyword">int</span>[] a = [1,2,3];
|
|
<span class="d_keyword">auto</span> x = a.front(); <span class="d_comment">// call .front by UFCS
|
|
</span>
|
|
<span class="d_keyword">auto</span> front = x; <span class="d_comment">// front is now a variable
|
|
</span> <span class="d_keyword">auto</span> y = a.front(); <span class="d_comment">// Error, front is not a function
|
|
</span>}
|
|
|
|
<span class="d_keyword">class</span> C
|
|
{
|
|
<span class="d_keyword">int</span>[] arr;
|
|
<span class="d_keyword">int</span> front()
|
|
{
|
|
<span class="d_keyword">return</span> arr.front(); <span class="d_comment">// Error, C.front is not callable
|
|
</span> <span class="d_comment">// using argument types (int[])
|
|
</span> }
|
|
}
|
|
</pre>
|
|
<div class="blankline"></div>
|
|
|
|
<div style="float: left"><i class="fa fa-angle-left" aria-hidden="true"></i> <a href="../spec/const3.html">Type Qualifiers</a></div>
|
|
<div style="float: right"><a href="../spec/operatoroverloading.html">Operator Overloading</a> <i class="fa fa-angle-right" aria-hidden="true"></i></div>
|
|
<div style="clear:both"></div>
|
|
)
|
|
|
|
|
|
<div class="smallprint" id="copyright">Copyright © 1999-2026 by the <a href="../foundation_overview.html">D Language Foundation</a> | Page generated by
|
|
<a href="../spec/ddoc.html">Ddoc</a> on Mon Oct 26 00:46:12 2026
|
|
|