D Specification: 05/02/2007 Snapshot

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 223

1

D Specification

D Specification
05/02/2007 snapshot

D Specification

Contents
Lexical.......................................................................................................................................... 3 Modules...................................................................................................................................... 17 Declarations................................................................................................................................ 23 Types...........................................................................................................................................31 roperties.................................................................................................................................... 35 !ttri"utes.................................................................................................................................... 3# ra$%as.......................................................................................................................................&& 'xpressions................................................................................................................................. &( State%ents................................................................................................................................... (& !rrays..........................................................................................................................................#2 !ssociati)e arrays....................................................................................................................... *3 Structs + unions..........................................................................................................................*7 ,lasses...................................................................................................................................... 100 -nterfaces...................................................................................................................................11& 'nu%s....................................................................................................................................... 117 .unctions...................................................................................................................................11* /perator /)erloadin$............................................................................................................... 13& Te%plates..................................................................................................................................1&1 Mixins....................................................................................................................................... 152 ,ontracts................................................................................................................................... 157 ,onditional ,o%pilation...........................................................................................................1(0 0andlin$ 'rrors.........................................................................................................................1(7 1ar"a$e ,ollection................................................................................................................... 170 .loatin$ oint............................................................................................................................17& -nline !sse%"ler....................................................................................................................... 177 Docu%entation ,o%%ents....................................................................................................... 1#( -nterfacin$ to ,......................................................................................................................... 1*# orta"ility 1uide.......................................................................................................................203 '%"eddin$ D in 0TML............................................................................................................205 2a%ed ,haracter 'ntities......................................................................................................... 20( !pplication 3inary -nterface.................................................................................................... 21&

D Specification

Lexical
-n D4 the lexical analysis is independent of the syntax parsin$ and the se%antic analysis. The lexical analy5er splits the source text up into to6ens. The lexical $ra%%ar descri"es 7hat those to6ens are. The D lexical $ra%%ar is desi$ned to "e suita"le for hi$h speed scannin$4 it has a %ini%u% of special case rules4 there is only one phase of translation4 and to %a6e it easy to 7rite a correct scanner for. The to6ens are readily reco$ni5a"le "y those fa%iliar 7ith , and ,88.

Phases of Compilation
The process of co%pilin$ is di)ided into %ultiple phases. 'ach phase has no dependence on su"se9uent phases. .or exa%ple4 the scanner is not pertur"ed "y the se%antic analy5er. This separation of the passes %a6es lan$ua$e tools li6e syntax directed editors relati)ely easy to produce. -t also is possi"le to co%press D source "y storin$ it in :to6eni5ed: for%. 1. source character set The source file is chec6ed to see 7hat character set it is4 and the appropriate scanner is loaded. !S,-- and ;T. for%ats are accepted. 2. script line -f the first line starts 7ith <= then the first line is i$nored. 3. lexical analysis The source file is di)ided up into a se9uence of to6ens. Special To6ens are replaced 7ith other to6ens.Special to6en se9uences Special to6en se9uences are processed and re%o)ed. &. syntax analysis The se9uence of to6ens is parsed to for% syntax trees. 5. semantic analysis The syntax trees are tra)ersed to declare )aria"les4 load sy%"ol ta"les4 assi$n types4 and in $eneral deter%ine the %eanin$ of the pro$ra%. (. optimization /pti%i5ation is an optional pass that tries to re7rite the pro$ra% in a se%antically e9ui)alent4 "ut faster executin$4 )ersion. 7. code generation -nstructions are selected fro% the tar$et architecture to i%ple%ent the se%antics of the pro$ra%. The typical result 7ill "e an o">ect file4 suita"le for input to a lin6er.

Source Text
D source text can "e in one of the follo7in$ for%ats?

!S,-;T.@# ;T.@1(3' ;T.@1(L' ;T.@323' ;T.@32L'

;T.@# is a superset of traditional 7@"it !S,--. /ne of the follo7in$ ;T. 3/Ms A3yte /rder Mar6sB can "e present at the "e$innin$ of the source text? Format ;T.@# BOM '. 33 3.

D Specification ;T.@1(3' .' .. ;T.@1(L' .. .' ;T.@323' 00 00 .' .. ;T.@32L' .. .' 00 00 !S,-no 3/M -f the source file does not start 7ith a 3/M4 then the first character %ust "e less than or e9ual to ;0000007.. There are no di$raphs or tri$raphs in D.

&

The source text is decoded fro% its source representation into ;nicode Characters. The Characters are further di)ided into? 7hite space4 end of lines4 co%%ents4 special to6en se9uences4 to6ens4 all follo7ed "y end of file. The source text is split into to6ens usin$ the %axi%al %unch techni9ue4 i.e.4 the lexical analy5er tries to %a6e the lon$est to6en it can. .or exa%ple >> is a ri$ht shift to6en4 not t7o $reater than to6ens.

End of File
EndOfFile: physical end of the file \u0000 \u001A

The source text is ter%inated "y 7hiche)er co%es first.

End of Line
EndOfLine: \u000D \u000A \u000D \u000A EndOfFile

There is no "ac6slash line splicin$4 nor are there any li%its on the len$th of a line.

hite Space
WhiteSpace: Space Space WhiteSpace Space: \u0020 \u0009 \u000B \u000C

Comments
Comment: /* Characters */

5
// Characters EndOfLine NestingBlockComment Characters: Character Character Characters NestingBlockComment: /+ NestingBlockCommentCharacters +/ NestingBlockCommentCharacters: NestingBlockCommentCharacter NestingBlockCommentCharacter NestingBlockCommentCharacters NestingBlockCommentCharacter: Character NestingBlockComment

D Specification

D has three 6inds of co%%ents? 1. 3loc6 co%%ents can span %ultiple lines4 "ut do not nest. 2. Line co%%ents ter%inate at the end of the line. 3. 2estin$ co%%ents can span %ultiple lines and can nest. The contents of strin$s and co%%ents are not to6eni5ed. ,onse9uently4 co%%ent openin$s occurrin$ 7ithin a strin$ do not "e$in a co%%ent4 and strin$ deli%iters 7ithin a co%%ent do not affect the reco$nition of co%%ent closin$s and nested C/8C co%%ent openin$s. Dith the exception of C/8C occurrin$ 7ithin a C/8C co%%ent4 co%%ent openin$s 7ithin a co%%ent are i$nored.
a = /+ // +/ 1; a = /+ "+/" +/ 1"; a = /+ /* +/ */ 3; // parses as if 'a = 1;' // parses as if 'a = " +/ 1";' // parses as if 'a = */ 3;'

,o%%ents cannot "e used as to6en concatenators4 for exa%ple4 abc/**/def is t7o to6ens4 abc and def4 not one abcdef to6en.

To!ens
Token: Identifier StringLiteral CharacterLiteral IntegerLiteral FloatLiteral Key ord / /= . .. ... & &= && | |= || -= --

D Specification
+ += ++ < <= << <<= <> <>= > >= >>= >>>= >> >>> ! != !== !<> !<>= !< !<= !> !>= !~ ( ) [ ] { } ? , ; : $ = == === * *= % %= ^ ^= ~ ~= ~~

"dentifiers
Identifier: IdentiferStart IdentiferStart IdentifierChars IdentifierChars: IdentiferChar IdentiferChar IdentifierChars IdentifierStart:

7
_ Letter !ni"ersal#lpha IdentifierChar: IdentiferStart 0 Non$ero%igit

D Specification

-dentifiers start 7ith a letter4 #4 or uni)ersal alpha4 and are follo7ed "y any nu%"er of letters4 #4 di$its4 or uni)ersal alphas. ;ni)ersal alphas are as defined in -S//-', *#**?1***A'B !ppendix D. AThis is the ,** Standard.B -dentifiers can "e ar"itrarily lon$4 and are case sensiti)e. -dentifiers startin$ 7ith ## At7o underscoresB are reser)ed.

String Literals
StringLiteral: Wysi ygString #lternateWysi ygString %o&'le(&otedString EscapeSe)&ence *e+String Wysi ygString: r" Wysi ygCharacters " ,ostfi+opt #lternateWysi ygString: ` Wysi ygCharacters ` ,ostfi+opt Wysi ygCharacters: Wysi ygCharacter Wysi ygCharacter Wysi ygCharacters Wysi ygCharacter: Character EndOfLine %o&'le(&otedString: " %o&'le(&otedCharacters " ,ostfi+opt %o&'le(&otedCharacters: %o&'le(&otedCharacter %o&'le(&otedCharacter %o&'le(&otedCharacters %o&'le(&otedCharacter: Character EscapeSe)&ence EndOfLine EscapeSe)&ence: \ \" \? \\ \! \" \# \$ \r

D Specification
\% \& \ EndOfFile \' *e+%igit *e+%igit \ Octal%igit \ Octal%igit Octal%igit \ Octal%igit Octal%igit Octal%igit \( *e+%igit *e+%igit *e+%igit *e+%igit \) *e+%igit *e+%igit *e+%igit *e+%igit *e+%igit *e+%igit *e+%igit *e+%igit \& NamedCharacterEntity ; *e+String: '" *e+StringChars " ,ostfi+opt *e+StringChars: *e+StringChar *e+StringChar *e+StringChars *e+StringChar *e+%igit WhiteSpace EndOfLine ,ostfi+ * + ,

! strin$ literal is either a dou"le 9uoted strin$4 a 7ysi7y$ 9uoted strin$4 an escape se9uence4 or a hex strin$. Dysi7y$ 9uoted strin$s are enclosed "y rC and C. !ll characters "et7een the rC and C are part of the strin$ except for EndOfLine 7hich is re$arded as a sin$le En character. There are no escape se9uences inside rC C?
r" e!!"" r"c:\r""#\f""$e%e" r"ab\&" // s#ri&' is ( c arac#ers) 'a') 'b') '\') '&'

!n alternate for% of 7ysi7y$ strin$s are enclosed "y "ac69uotes4 the F character. The F character is not a)aila"le on so%e 6ey"oards and the font renderin$ of it is so%eti%es indistin$uisha"le fro% the re$ular : character. Since4 ho7e)er4 the F is rarely used4 it is useful to delineate strin$s 7ith C in the%.
* e!!"* *c:\r""#\f""$e%e* *ab\&* // s#ri&' is ( c arac#ers) 'a') 'b') '\') '&'

Dou"le 9uoted strin$s are enclosed "y CC. 'scape se9uences can "e e%"edded into the% 7ith the typical E notation. EndOfLine is re$arded as a sin$le En character.
" e!!"" "c:\\r""#\\f""$e%e" "ab\&" "ab " // s#ri&' is 3 c arac#ers) 'a') 'b') a&d a !i&efeed // s#ri&' is 3 c arac#ers) 'a') 'b') a&d a !i&efeed

'scape strin$s start 7ith a E and for% an escape character se9uence. !d>acent escape strin$s are

* concatenated?
\& \# \" \012 \%1A \u123( \-0010123( \.re'; \r\& # e !i&efeed c arac#er # e #ab c arac#er # e d"ub!e +u"#e c arac#er "c#a! e% ,c ar c arac#er dc ar c arac#er / dc ar c arac#er carria'e re#ur&) !i&e feed

D Specification

;ndefined escape se9uences are errors. !lthou$h strin$ literals are defined to "e co%posed of ;T. characters4 the octal and hex escape se9uences allo7 the insertion of ar"itrary "inary data. Eu and E; escape se9uences can only "e used to insert )alid ;T. characters. 0ex strin$s allo7 strin$ literals to "e created usin$ hex data. The hex data need not for% )alid ;T. characters.
%"0A" %"00 1BCD 321D 0A" // sa0e as "\%0A" // sa0e as "\%00\%1B\%CD\%32\%1D\%0A"

Dhitespace and ne7lines are i$nored4 so the hex data can "e easily for%atted. The nu%"er of hex characters %ust "e a %ultiple of 2. !d>acent strin$s are concatenated 7ith the G operator4 or "y si%ple >uxtaposition?
" e!!" " 2 ","r!d" 2 \& // f"r0s # e s#ri&' ' ')'e')'!')'!')'"')' ') // ',')'"')'r')'!')'d')!i&efeed

The follo7in$ are all e9ui)alent?


"ab" "c" r"ab" r"c" r"a" "bc" "a" 2 "b" 2 "c" \%31"bc"

The optional Postfix character $i)es a specific type to the strin$4 rather than it "ein$ inferred fro% the context. This is useful 7hen the type cannot "e una%"i$uously inferred4 such as 7hen o)erloadin$ "ased on strin$ type. The types correspondin$ to the postfix characters are? Postfix c $ d
" e!!""c " e!!"", " e!!""d

Type charH I 7charH I dcharH I


// c ar45 // ,c ar45 // dc ar45

Character Literals
CharacterLiteral: Single(&otedCharacter Single(&otedCharacter

D Specification
Character EscapeSe)&ence

10

,haracter literals are a sin$le character or escape se9uence enclosed "y sin$le 9uotes4 : :.

"nteger Literals
IntegerLiteral: Integer Integer IntegerS&ffi+ Integer: %ecimal Binary Octal *e+adecimal Integer

IntegerS&ffi+: ( ) -( -) ()%ecimal: 0 Non$ero%igit Non$ero%igit %ecimal%igits 0" Binary%igits 0. Binary%igits Octal: 0 Octal%igits *e+adecimal: 0' *e+%igits 0/ *e+%igits Non$ero%igit: 0 1 2 3 4 5 6 7 8 %ecimal%igits: %ecimal%igit %ecimal%igit %ecimal%igits %ecimal%igit: 0

Binary:

11
Non$ero%igit _ Binary%igits: Binary%igit Binary%igit Binary%igits Binary%igit: 0 0 _ Octal%igits: Octal%igit Octal%igit Octal%igits Octal%igit: 0 0 1 2 3 4 5 6 _ *e+%igits: *e+%igit *e+%igit *e+%igits *e+%igit: %ecimal%igit ! " * , 9 # : . ; < = >

D Specification

-nte$ers can "e specified in deci%al4 "inary4 octal4 or hexadeci%al. Deci%al inte$ers are a se9uence of deci%al di$its. 3inary inte$ers are a se9uence of "inary di$its preceded "y a :0":. /ctal inte$ers are a se9uence of octal di$its preceded "y a :0:. 0exadeci%al inte$ers are a se9uence of hexadeci%al di$its preceded "y a :0x: or follo7ed "y an :h:. -nte$ers can ha)e e%"edded :J: characters4 7hich are i$nored. The e%"edded :J: are useful for for%attin$ lon$ literals4 such as usin$ the% as a thousands separator?
1236(73 162636(67636 // 123(73 // 123(73

D Specification -nte$ers can "e i%%ediately follo7ed "y one :L: or one :u: or "oth. The type of the inte$er is resol)ed as follo7s? %ecimal Literal 0 .. 21&7&#3(&7 21&7&#3(&# .. *22337203(#5&775#07 %ecimal Literal& L Suffix 0L .. *22337203(#5&775#07L %ecimal Literal& ' Suffix 0; .. &2*&*(72*5; &2*&*(72*(; .. 1#&&(7&&07370*551(15; %ecimal Literal& 'L Suffix 0;L .. 1#&&(7&&07370*551(15;L (on)%ecimal Literal 0x0 .. 0x7....... 0x#0000000 .. 0x........ 0x100000000 .. 0x7............... 0x#000000000000000 .. 0x................ (on)%ecimal Literal& L Suffix 0x0L .. 0x7...............L (on)%ecimal Literal& ' Suffix 0x0; .. 0x........; 0x100000000;L .. 0x................;L (on)%ecimal Literal& 'L Suffix 0x0;L .. 0x................;L Type int lon$ Type lon$ Type uint ulon$ Type ulon$ Type int uint lon$ ulon$ Type lon$ Type uint ulon$ Type ulon$

12

0x#000000000000000L .. 0x................L ulon$

Floating Literals
FloatLiteral: Float Float FloatS&ffi+ Float ImaginaryS&ffi+ Float FloatS&ffi+ ImaginaryS&ffi+ Float: %ecimalFloat *e+Float %ecimalFloat: %ecimal%igits .

13
%ecimal%igits . %ecimal%igits %ecimal%igits . %ecimal%igits %ecimalE+ponent . %ecimal . %ecimal %ecimalE+ponent %ecimal%igits %ecimalE+ponent %ecimalE+ponent 9 %ecimal%igits = %ecimal%igits 9+ %ecimal%igits =+ %ecimal%igits 9- %ecimal%igits =- %ecimal%igits *e+Float: *e+,refi+ *e+,refi+ *e+,refi+ *e+,refi+ *e+,refi+ *e+,refi+ *e+,refi+: 0' 0/ *e+E+ponent ? %ecimal%igits @ %ecimal%igits ?+ %ecimal%igits @+ %ecimal%igits ?- %ecimal%igits @- %ecimal%igits FloatS&ffi+: # > ImaginaryS&ffi+: A *e+%igits . *e+%igits . *e+%igits *e+%igits . *e+%igits *e+E+ponent . *e+%igits . *e+%igits *e+E+ponent *e+%igits *e+E+ponent

D Specification

.loats can "e in deci%al or hexadeci%al for%at4 as in standard ,. 0exadeci%al floats are preceded 7ith a *x and the exponent is a p or P follo7ed "y a deci%al nu%"er ser)in$ as the exponent of 2. .loatin$ literals can ha)e e%"edded :J: characters4 7hich are i$nored. The e%"edded :J: are useful for for%attin$ lon$ literals to %a6e the% %ore reada"le4 such as usin$ the% as a thousands separator?
1236(73$73869 162636(67636$67636869 162636(67636$67e:36 // 123(73$7389 // 123(73$7389 // 123(73$7e:3

.loatin$ literals 7ith no suffix are of type dou"le. .loats can "e follo7ed "y one f4 F4 or L suffix. The f or F suffix %eans it is a float4 and L %eans it is a real. -f a floatin$ literal is follo7ed "y i4 then it is an ireal Ai%a$inaryB type. 'xa%ples?

D Specification
0%1$1111111111111p1023 0%1p:72 1$187(9(371e:391 3$3i 3$3fi 3$3;i // // // // // // d"ub!e$0a% d"ub!e$epsi!"& f!"a#$0i& id"ub!e 3$3 if!"a# 3$3 irea! 3$3

1&

-t is an error if the literal exceeds the ran$e of the type. -t is not an error if the literal is rounded to fit into the si$nificant di$its of the type. ,o%plex literals are not to6ens4 "ut are asse%"led fro% real and i%a$inary expressions in the se%antic analysis?
($7 + 3$2i // c"0p!e% &u0ber

+ey$ords
Key7ords are reser)ed identifiers.
Key ord: !"B%r!*% !CA!B !CAD$ !BE !BB9r% !(%F "F,G "FFC "r9!H "G%9 *!B9 *!B% *!%*I *,F("C9 *9$% *#CF!% *I!r *C!BB *F$B% *F$%A$(9 *r9!C ,*I!r ,9"(D ,9#!(C% ,9C9D!%9 ,9C9%9 ,9?r9*!%9, ,F ,F("C9 9CB9 9$(E 9'?Fr% 9'%9r$ #!CB9 #A$!C

15
#A$!CCG #CF!% #Fr #Fr9!*I #Fr9!*I_r9&9rB9 #($*%AF$ DF%F A,F("C9 A# A#CF!% AE?Fr% A$ A$F(% A$% A$%9r#!*9 A$&!rA!$% Ar9!C AB C!JG CF$D EA'A$ EF,(C9 $9+ $(CC F(% F&9rrA,9 ?!*H!D9 ?r!DE! ?rA&!%9 ?rF%9*%9, ?("CA* r9!C r9%(r$ B*F?9 BIFr% B%!%A* B%r(*% B(?9r B+A%*I BG$*IrF$AJ9, %9E?C!%9 %IAB %IrF+ %r(9 %rG %G?9,9# %G?9A, %G?9F# ("G%9 (*9$%

D Specification

D Specification
(A$% (CF$D ($AF$ ($A%%9B% (BIFr% &9rBAF$ &FA, &FC!%AC9 +*I!r +IAC9 +A%I

1(

Special To!ens
These to6ens are replaced 7ith other to6ens accordin$ to the follo7in$ ta"le? Special To!en ##F"LE## ##L"(E## ##%.TE## ##T"ME## ##T"MEST.MP## ,eplaced $ith--strin$ literal containin$ source file na%e inte$er literal of the current source line nu%"er strin$ literal of the date of co%pilation Cmmm dd yyyyC strin$ literal of the ti%e of co%pilation Chh:mm:ssC strin$ literal of the date and ti%e of co%pilation Cwww mmm dd hh:mm:ss yyyyC

Special To!en Se/uences


Special to6en se9uences are processed "y the lexical analy5er4 %ay appear "et7een any other to6ens4 and do not affect the syntax parsin$. There is currently only one special to6en se9uence4 <!i&e.
SpecialTokenSe)&ence KLCA$9 Integer EndOfLine KLCA$9 Integer Filespec EndOfLine Filespec " Characters "

This sets the source line nu%"er to Integer4 and optionally the source file na%e to Filespec4 "e$innin$ 7ith the next line of source text. The source file and line nu%"er is used for printin$ error %essa$es and for %appin$ $enerated code "ac6 to the source for the sy%"olic de"u$$in$ output. .or exa%ple?
i&# <!i&e 3 "f""\bar" %; // # is is &", !i&e 3 "f fi!e f""\bar

2ote that the "ac6slash character is not treated specially inside Filespec strin$s.

17

D Specification

Modules
-od&le: -od&le%eclaration %ecl%efs %ecl%efs

%ecl%efs: %ecl%ef %ecl%ef %ecl%efs %ecl%ef: #ttri'&teSpecifier Import%eclaration En&m%eclaration Class%eclaration Interface%eclaration #ggregate%eclaration %eclaration Constr&ctor %estr&ctor In"ariant !nitTest StaticConstr&ctor Static%estr&ctor %e'&gSpecification .ersionSpecification ;

Modules ha)e a one@to@one correspondence 7ith source files. The %odule na%e is the file na%e 7ith the path and extension stripped off. Modules auto%atically pro)ide a na%espace scope for their contents. Modules superficially rese%"le classes4 "ut differ in that?

There:s only one instance of each %odule4 and it is statically allocated. There is no )irtual ta"le. Modules do not inherit4 they ha)e no super %odules4 etc. /nly one %odule per file. Module sy%"ols can "e i%ported. Modules are al7ays co%piled at $lo"al scope4 and are unaffected "y surroundin$ attri"utes or other %odifiers.

Modules can "e $rouped to$ether in hierarchies called packages.

Module %eclaration
The Module eclaration sets the na%e of the %odule and 7hat pac6a$e it "elon$s to. -f a"sent4 the %odule na%e is ta6en to "e the sa%e na%e Astripped of path and extensionB of the source file na%e.
-od&le%eclaration: EF,(C9 -od&leName ; -od&leName: Identifier -od&leName . Identifier

The Identifier precedin$ the ri$ht%ost are the packages that the %odule is in. The pac6a$es

D Specification correspond to directory na%es in the source file path.

1#

-f present4 the Module eclaration appears syntactically first in the source file4 and there can "e only one per source file. 'xa%ple?
0"du!e c$s#di"; // # is is 0"du!e B%,AF i& # e * pac=a'e

3y con)ention4 pac6a$e and %odule na%es are all lo7er case. This is "ecause those na%es ha)e a one@to@one correspondence 7ith the operatin$ syste%:s directory and file na%es4 and %any file syste%s are not case sensiti)e. !ll lo7er case pac6a$e and %odule na%es 7ill %ini%i5e pro"le%s %o)in$ pro>ects "et7een dissi%ilar file syste%s.

"mport %eclaration
Sy%"ols fro% one %odule are %ade a)aila"le in another %odule "y usin$ the Import eclaration?
Import%eclaration: AE?Fr% ImportList ; B%!%A*LAE?Fr% ImportList ; ImportList: Import ImportBindings Import , ImportList Import: -od&leName -od&le#liasIdentifier = -od&leName

ImportBindings: Import : ImportBindList ImportBindList: ImportBind ImportBind , ImportBindList ImportBind: Identifier Identifier =

There are se)eral for%s of the Import eclaration4 fro% $enerali5ed to fine@$rained i%portin$. The order in 7hich Import eclarations occur has no si$nificance. Module!ames in the Import eclaration %ust "e fully 9ualified 7ith 7hate)er pac6a$es they are in. They are not considered to "e relati)e to the %odule that i%ports the%.

Basic "mports
The si%plest for% of i%portin$ is to >ust list the %odules "ein$ i%ported?
i0p"r# s#d$s#di"; i0p"r# f"") bar; // i0p"r# 0"du!e B%,AF fr"0 # e B%, pac=a'e // i0p"r# 0"du!es #FF a&d "!r

>"id 0ai&?@ A ,ri#ef!&?" e!!"B\&"@; C

// ca!!s s#d$s#di"$,ri#ef!&

1*

D Specification

0o7 "asic i%ports 7or6 is that first a na%e is searched for in the current na%espace. -f it is not found4 then it is loo6ed for in the i%ports. -f it is found uni9uely a%on$ the i%ports4 then that is used. -f it is in %ore than one i%port4 an error occurs.
0"du!e A; >"id f""?@; >"id bar?@; 0"du!e B; >"id f""?@; >"id bar?@; 0"du!e C; i0p"r# A; >"id f""?@; >"id #es#?@ A f""?@; // C$f""?@ is ca!!ed) i# is f"u&d bef"re i0p"r#s are searc ed bar?@; // A$bar?@ is ca!!ed) si&ce i0p"r#s are searc ed C 0"du!e D; i0p"r# A; i0p"r# B; >"id #es#?@ A f""?@; // err"r) A$f""?@ "r B$f""?@ D A$f""?@; // "=) ca!! A$f""?@ B$f""?@; // "=) ca!! B$f""?@ C 0"du!e E; i0p"r# A; i0p"r# B; a!ias B$f"" f""; >"id #es#?@ A f""?@; // ca!! B$f""?@ A$f""?@; // ca!! A$f""?@ B$f""?@; // ca!! B$f""?@ C

Pu0lic "mports
3y default4 i%ports are pri"ate. This %eans that if %odule ! i%ports %odule 34 and %odule 3 i%ports %odule ,4 then ,:s na%es are not searched for. !n i%port can "e specifically declared pu#lic4 7hen it 7ill "e treated as if any i%ports of the %odule 7ith the Import eclaration also i%port the pu"lic i%ported %odules.
0"du!e A; >"id f""?@ A C 0"du!e B; >"id bar?@ A C 0"du!e C; i0p"r# A; pub!ic i0p"r# B; $$$ f""?@; // ca!! A$f""?@ bar?@; // ca!!s B$bar?@

D Specification
0"du!e D; i0p"r# C; $$$ f""?@; // err"r) f""?@ is u&defi&ed bar?@; // "=) ca!!s B$bar?@

20

Static "mports
3asic i%ports 7or6 7ell for pro$ra%s 7ith relati)ely fe7 %odules and i%ports. -f there are a lot of i%ports4 na%e collisions can start occurrin$ "et7een the na%es in the )arious i%ported %odules. /ne 7ay to stop this is "y usin$ static i%ports. ! static i%port re9uires one to use a fully 9ualified na%e to reference the %odule:s na%es?
s#a#ic i0p"r# s#d$s#di"; >"id 0ai&?@ A ,ri#ef!&?" e!!"B"@; s#d$s#di"$,ri#ef!&?" e!!"B"@; C

// err"r) ,ri#ef!& is u&defi&ed // "=) ,ri#ef!& is fu!!F +ua!ified

,enamed "mports
! local na%e for an i%port can "e $i)en4 throu$h 7hich all references to the %odule:s sy%"ols %ust "e 9ualified 7ith?
i0p"r# i" = s#d$s#di"; >"id 0ai&?@ A i"$,ri#ef!&?" e!!"B"@; s#d$s#di"$,ri#ef!&?" e!!"B"@; ,ri#ef!&?" e!!"B"@; C

// "=) ca!!s s#d$s#di"$,ri#ef!& // err"r) s#d is u&defi&ed // err"r) ,ri#ef!& is u&defi&ed

Lena%ed i%ports are handy 7hen dealin$ 7ith )ery lon$ i%port na%es.

Selecti1e "mports
Specific sy%"ols can "e exclusi)ely i%ported fro% a %odule and "ound into the current na%espace?
i0p"r# s#d$s#di" : ,ri#ef!&) f"" = ,ri#ef; >"id 0ai&?@ A s#d$s#di"$,ri#ef!&?" e!!"B"@; ,ri#ef!&?" e!!"B"@; ,ri#ef?","r!d"@; f""?","r!d"@; f,ri#ef!&?s#d"u#) "abc"@; C

// // // // //

err"r) s#d is u&defi&ed "=) ,ri#ef!& b"u&d i&#" curre&# &a0espace err"r) ,ri#ef is u&defi&ed "=) ca!!s s#d$s#di"$,ri#ef?@ err"r) f,ri#ef!& u&defi&ed

static cannot "e used 7ith selecti)e i%ports.

21

D Specification

,enamed and Selecti1e "mports


Dhen rena%in$ and selecti)e i%portin$ are co%"ined?
i0p"r# i" = s#d$s#di" : f"" = ,ri#ef!&; >"id 0ai&?@ A ,ri#ef!&?"bar"@; s#d$s#di"$f""?"bar"@; s#d$s#di"$,ri#ef!&?"bar"@; f""?"bar"@; i"$,ri#ef!&?"bar"@; 0"du!e i"$f""?"bar"@;

// // // // // // //

err"r) ,ri#ef!& is u&defi&ed err"r) f"" is b"u&d i&#" curre&# &a0espace err"r) s#d is u&defi&ed "=) f"" is b"u&d i&#" curre&# &a0espace) 1GH &"# re+uired "=) i"=s#d$s#di" b"u&d # e &a0e i" i& # e curre&# &a0espace #" refer #" # e e&#ire

// err"r) f"" is b"u&d i&#" curre&# &a0espace) // f"" is &"# a 0e0ber "f i"

Module Scope Operator


So%eti%es4 it:s necessary to o)erride the usual lexical scopin$ rules to access a na%e hidden "y a local na%e. This is done 7ith the $lo"al scope operator4 7hich is a leadin$ :.:?
i&# %; i&# f""?i&# %@ A if ?F@ re#ur& %; e!se re#ur& $%; C

// re#ur&s f""$%) &"# '!"ba! % // re#ur&s '!"ba! %

The leadin$ :.: %eans loo6 up the na%e at the %odule scope le)el.

Static Construction and %estruction


Static constructors are code that $ets executed to initiali5e a %odule or a class "efore the %ainAB function $ets called. Static destructors are code that $ets executed after the %ainAB function returns4 and are nor%ally used for releasin$ syste% resources.

Order of Static Construction


The order of static initiali5ation is i%plicitly deter%ined "y the import declarations in each %odule. 'ach %odule is assu%ed to depend on any i%ported %odules "ein$ statically constructed first. /ther than follo7in$ that rule4 there is no i%posed order on executin$ the %odule static constructors. ,ycles Acircular dependenciesB in the i%port declarations are allo7ed as lon$ as not "oth of the %odules contain static constructors or static destructors. Miolation of this rule 7ill result in a runti%e exception.

Order of Static Construction $ithin a Module


Dithin a %odule4 the static construction occurs in the lexical order in 7hich they appear.

D Specification

22

Order of Static %estruction


-t is defined to "e exactly the re)erse order that static construction 7as perfor%ed in. Static destructors for indi)idual %odules 7ill only "e run if the correspondin$ static constructor successfully co%pleted.

Order of 'nit tests


;nit tests are run in the lexical order in 7hich they appear 7ithin a %odule.

23

D Specification

Declarations
%eclaration: %G?9,9# %ecl !CA!B %ecl %ecl %ecl: StorageClasses %ecl BasicType %eclarators ; BasicType %eclarator F&nctionBody #&to%eclaration %eclarators: %eclaratorInitiali/er %eclaratorInitiali/er , %eclaratorIdentifierList %eclaratorInitiali/er: %eclarator %eclarator = Initiali/er %eclaratorIdentifierList: %eclaratorIdentifier %eclaratorIdentifier , %eclaratorIdentifierList %eclaratorIdentifier: Identifier Identifier = Initiali/er BasicType: "FFC "G%9 ("G%9 BIFr% (BIFr% A$% (A$% CF$D (CF$D *I!r +*I!r ,*I!r #CF!% ,F("C9 r9!C A#CF!% A,F("C9 Ar9!C *#CF!% *,F("C9 *r9!C &FA, .IdentifierList IdentifierList Typeof Typeof . IdentifierList BasicType0: * [L]

D Specification
[ E+pression ] [ Type ] ,9C9D!%9 ,arameters #($*%AF$ ,arameters %eclarator: BasicType0 %eclarator Identifier ()LDeclaratorL Identifier %eclaratorS&ffi+es ()LDeclaratorL %eclaratorS&ffi+es %eclaratorS&ffi+es: %eclaratorS&ffi+ %eclaratorS&ffi+ %eclaratorS&ffi+es %eclaratorS&ffi+: [L] [ E+pression ] [ Type ] ,arameters IdentifierList: Identifier Identifier . IdentifierList TemplateInstance TemplateInstance . IdentifierList Typeof: %G?9F#L( E+pression ) StorageClasses: StorageClass StorageClass StorageClasses StorageClass: !"B%r!*% !(%F *F$B% ,9?r9*!%9, 9'%9r$ #A$!C F&9rrA,9 B*F?9 B%!%A* BG$*IrF$AJ9, Type: BasicType BasicType %eclarator0

2&

%eclarator0: BasicType0 %eclarator0 ( %eclarator0 ) ( %eclarator0 ) %eclaratorS&ffi+es ,arameters: ( ,arameterList ) (L) ,arameterList:

25
,arameter ,arameter , ,arameterList ,arameter ... ... ,arameter: %eclarator %eclarator = #ssignE+pression InO&t %eclarator InO&t %eclarator = #ssignE+pression InO&t: A$ F(% A$F(% C!JG

D Specification

Initiali/er: &FA, Non.oidInitiali/er Non.oidInitiali/er: #ssignE+pression #rrayInitiali/er Str&ctInitiali/er #rrayInitiali/er: [L] [ #rray-em'erInitiali/ations ] #rray-em'erInitiali/ations: #rray-em'erInitiali/ation #rray-em'erInitiali/ation , #rray-em'erInitiali/ation , #rray-em'erInitiali/ations #rray-em'erInitiali/ation: Non.oidInitiali/er #ssignE+pression : Non.oidInitiali/er Str&ctInitiali/er: {LL} { Str&ct-em'erInitiali/ers } Str&ct-em'erInitiali/ers: Str&ct-em'erInitiali/er Str&ct-em'erInitiali/er , Str&ct-em'erInitiali/er , Str&ct-em'erInitiali/ers Str&ct-em'erInitiali/er: Non.oidInitiali/er Identifier : Non.oidInitiali/er #&to%eclaration: StorageClasses Identifier = #ssignE+pression ;

%eclaration Syntax
Declaration syntax $enerally reads ri$ht to left?
i&# %; i&#* %; // % is a& i&# // % is a p"i&#er #" i&#

D Specification
i&#** %; i&#45 %; i&#*45 %; i&#45* %; // // // // % % % % is is is is a p"i&#er #" a p"i&#er #" i&# a& arraF "f i&#s a& arraF "f p"i&#ers #" i&#s a p"i&#er #" a& arraF "f i&#s

2(

!rrays read ri$ht to left as 7ell?


i&#435 %; i&#435475 %; i&#435*475 %; // % is a& arraF "f 3 i&#s // % is a& arraF "f 7 arraFs "f 3 i&#s // % is a& arraF "f 7 p"i&#ers #" arraFs "f 3 i&#s

ointers to functions are declared usin$ the function 6ey7ord?


i&# #($*%AF$?c ar@ %; // // i&# #($*%AF$?c ar@45 %; // // % is a p"i&#er #" a fu&c#i"& #a=i&' a c ar ar'u0e&# a&d re#ur&i&' a& i&# % is a& arraF "f p"i&#ers #" fu&c#i"&s #a=i&' a c ar ar'u0e&# a&d re#ur&i&' a& i&#

,@style array declarations %ay "e used as an alternati)e?


i&# i&# i&# i&# // // // // // i&# ?*45 %@?c ar@; // // %435; %435475; ?*%475@435; ?*%@?c ar@; % is a& arraF "f 3 i&#s % is a& arraF "f 3 arraFs "f 7 i&#s % is a& arraF "f 7 p"i&#ers #" arraFs "f 3 i&#s % is a p"i&#er #" a fu&c#i"& #a=i&' a c ar ar'u0e&# a&d re#ur&i&' a& i&# % is a& arraF "f p"i&#ers #" fu&c#i"&s #a=i&' a c ar ar'u0e&# a&d re#ur&i&' a& i&#

-n a declaration declarin$ %ultiple sy%"ols4 all the declarations %ust "e of the sa%e type?
i&# %)F; i&#* %)F; i&# %)*F; i&#45 %)F; i&# %45)F; // // // // // % a&d F are i&#s % a&d F are p"i&#ers #" i&#s err"r) 0u!#ip!e #Fpes % a&d F are arraFs "f i&#s err"r) 0u!#ip!e #Fpes

"mplicit Type "nference


-f a declaration starts 7ith a $torageClass and has a !on%oidInitiali&er fro% 7hich the type can "e inferred4 the type on the declaration can "e o%itted.
s#a#ic % = 3; // % is #Fpe i&# au#" F = (u; // F is #Fpe ui&# au#" s = "s#ri&'"; // s is #Fpe c ar435 c!ass C A $$$ C au#" c = &e, C?@; // c is a a&d!e #" a& i&s#a&ce "f c!ass C

The !on%oidInitiali&er cannot contain for7ard references Athis restriction %ay "e re%o)ed in the futureB. The i%plicitly inferred type is statically "ound to the declaration at co%pile ti%e4 not run ti%e.

Type %efining
Stron$ types can "e introduced 7ith the typedef. Stron$ types are se%antically a distinct type to the type chec6in$ syste%4 for function o)erloadin$4 and for the de"u$$er.
#Fpedef i&# 0Fi&#;

27
>"id f""?i&# %@ A $ C >"id f""?0Fi&# 0@ A $ C $ 0Fi&# b; f""?b@;

D Specification

// ca!!s f""?0Fi&#@

Typedefs can specify a default initiali5er different fro% the default initiali5er of the underlyin$ type?
#Fpedef i&# 0Fi&# = 8; 0Fi&# 0; // i&i#ia!iIed #" 8

Type .liasing
-t:s so%eti%es con)enient to use an alias for a type4 such as a shorthand for typin$ out a lon$4 co%plex type li6e a pointer to a function. -n D4 this is done 7ith the alias declaration?
!CA!B abc$1""$bar 0Fi&#;

!liased types are se%antically identical to the types they are aliased to. The de"u$$er cannot distin$uish "et7een the%4 and there is no difference as far as function o)erloadin$ is concerned. .or exa%ple?
!CA!B i&# 0Fi&#; >"id f""?i&# %@ A $ C >"id f""?0Fi&# 0@ A $ C // err"r) 0u!#ip!F defi&ed fu&c#i"& f""

Type aliases are e9ui)alent to the , typedef.

.lias %eclarations
! sy%"ol can "e declared as an alias of another sy%"ol. .or exa%ple?
i0p"r# s#ri&'; !CA!B s#ri&'$s#r!e& 0F!e&; $$$ i&# !e& = 0F!e&?" e!!""@;

// ac#ua!!F ca!!s s#ri&'$s#r!e&?@

The follo7in$ alias declarations are )alid?


#e0p!a#e 1""2?J@ A !CA!B J #; C !CA!B 1""2B?i&#@ #1; !CA!B 1""2B?i&#@$# #2; !CA!B #1$# #3; !CA!B #2 #(; #1$# >1; #2 >2; #3 >3; #( >(; // // // // >1 >2 >3 >( is is is is #Fpe #Fpe #Fpe #Fpe i&# i&# i&# i&#

!liased sy%"ols are useful as a shorthand for a lon$ 9ualified sy%"ol na%e4 or as a 7ay to redirect references fro% one sy%"ol to another?
>ersi"& ?Ki&32@ A

D Specification
!CA!B ,i&32$f"" 0Ff""; C >ersi"& ?!i&u%@ A !CA!B !i&u%$bar 0Ff""; C

2#

!liasin$ can "e used to :i%port: a sy%"ol fro% an i%port into the current scope?
!CA!B s#ri&'$s#r!e& s#r!e&;

!liases can also :i%port: a set of o)erloaded functions4 that can "e o)erloaded 7ith functions in the current scope?
c!ass A A i&# f""?i&# a@ A re#ur& 1; C C c!ass B : A A i&# f""? i&# a) ui&# b @ A re#ur& 2; C C c!ass C : B A i&# f""? i&# a @ A re#ur& 3; C !CA!B B$f"" f""; C c!ass D : C C A

>"id #es#?@ A D b = &e, D?@; i&# i; i = b$f""?1) 2u@; i = b$f""?1@; C // ca!!s B$f"" // ca!!s C$f""

(ote2 Type aliases can so%eti%es loo6 indistin$uisha"le fro% alias declarations?
!CA!B f""$bar abc; // is i# a #Fpe "r a sF0b"!D

The distinction is %ade in the se%antic analysis pass. !liases cannot "e used for expressions?
s#ruc# L A s#a#ic i&# i; C L s; a!ias s$i a; a!ias L$i b; b = (; // i!!e'a!) s$i is a& e%pressi"& // "= // se#s L$i #" (

2*

D Specification

Extern %eclarations
Maria"le declarations 7ith the stora$e class extern are not allocated stora$e 7ithin the %odule. They %ust "e defined in so%e other o">ect file 7ith a %atchin$ na%e 7hich is then lin6ed in. The pri%ary usefulness of this is to connect 7ith $lo"al )aria"le declarations in , files.

typeof
'ypeof is a 7ay to specify a type "ased on the type of an expression. .or exa%ple?
>"id fu&c?i&# i@ A %G?9F#?i@ M; %G?9F#?3 + 3$0@ %; %G?9F#?1@* p; i&#4%G?9F#?p@5 a; // // // // M % p a is is is is "f "f "f "f #Fpe #Fpe #Fpe #Fpe i&# d"ub!e p"i&#er #" i&# i&#4i&#*5

pri&#f?"Nd\&") %G?9F#?'c'@$siIe"f@; // pri&#s 1 d"ub!e c = cas#?%G?9F#?1$0@@M; // cas# M #" d"ub!e C

Expression is not e)aluated4 >ust the type of it is $enerated?


>"id fu&c?@ A i&# i = 1; %G?9F#?++i@ M; pri&#f?"Nd\&") i@; C // M is dec!ared #" be a& i&#) i is &"# i&cre0e&#ed // pri&#s 1

There are t7o special cases? typeof3this4 7ill $enerate the type of 7hat this 7ould "e in a non@ static %e%"er function4 e)en if not in a %e%"er function. !nalo$ously4 typeof3super4 7ill $enerate the type of 7hat super 7ould "e in a non@static %e%"er function.
c!ass A A C c!ass B : A A %G?9F#(%IAB) %; %G?9F#(B(?9r) F; C s#ruc# C A %G?9F#(%IAB) I; %G?9F#(B(?9r) +; C %G?9F#(%IAB) r;

// % is dec!ared #" be a B // F is dec!ared #" be a& A

// I is dec!ared #" be a C* // err"r) &" super s#ruc# f"r C // err"r) &" e&c!"si&' s#ruc# "r c!ass

Dhere 'ypeof is %ost useful is in 7ritin$ $eneric te%plate code.

5oid "nitializations
2or%ally4 )aria"les are initiali5ed either 7ith an explicit Initiali&er or are set to the default )alue for the type of the )aria"le. -f the Initiali&er is 1oid4 ho7e)er4 the )aria"le is not initiali5ed. -f its )alue is used "efore it is set4 undefined pro$ra% "eha)ior 7ill result.
>"id f""?@ A

D Specification
i&# % = >"id; ,ri#ef!&?%@; // ,i!! pri&# 'arba'e

30

Therefore4 one should only use 1oid initiali5ers as a last resort 7hen opti%i5in$ critical code.

31

D Specification

Types

Basic %ata Types


+ey$ord >"id b""! bF#e ubF#e s "r# us "r# i&# ui&# !"&' u!"&' ce&# uce&# f!"a# d"ub!e rea! if!"a# no type "oolean )alue si$ned # "its unsi$ned # "its si$ned 1( "its unsi$ned 1( "its si$ned 32 "its unsi$ned 32 "its si$ned (& "its unsi$ned (& "its si$ned 12# "its Areser)ed for future useB unsi$ned 12# "its Areser)ed for future useB 32 "it floatin$ point (& "it floatin$ point lar$est hard7are i%ple%ented floatin$ point si5e A"mplementation (ote2 #0 "its for -ntel , ;sB i%a$inary float %escription @ false 0 0 0 0 0 0 0L 0L 0 0 float.nan dou"le.nan real.nan float.nan N 1.0i dou"le.nan N 1.0i real.nan N 1.0i float.nan 8 float.nan N 1.0i dou"le.nan 8 dou"le.nan N 1.0i real.nan 8 real.nan N 1.0i 0x.. 0x.... 0x0000.... %efault "nitializer 3-init4

id"ub!e i%a$inary dou"le irea! cf!"a# i%a$inary real a co%plex nu%"er of t7o float )alues

cd"ub!e co%plex dou"le crea! c ar ,c ar dc ar co%plex real unsi$ned # "it ;T.@# unsi$ned 1( "it ;T.@1( unsi$ned 32 "it ;T.@32

D Specification

32

%eri1ed %ata Types


pointer array associati)e array function dele$ate

'ser %efined Types


alias typedef enu% struct union class

Base Types
The #ase type of an enu% is the type it is "ased on?
e&u0 E : J A $$$ C // J is # e 'ase type "f E

The #ase type of a typedef is the type it is for%ed fro%?


#Fpedef J -; // J is # e 'ase type "f -

Pointer Con1ersions
,astin$ pointers to non@pointers and )ice )ersa is allo7ed in D4 ho7e)er4 do not do this for any pointers that point to data allocated "y the $ar"a$e collector.

"mplicit Con1ersions
-%plicit con)ersions are used to auto%atically con)ert types as re9uired. ! typedef or enu% can "e i%plicitly con)erted to its "ase type4 "ut $oin$ the other 7ay re9uires an explicit con)ersion. .or exa%ple?
#Fpedef i&# 0Fi&#; i&# i; 0Fi&# 0; i = 0; 0 = i; 0 = cas#?0Fi&#@i;

// OP // err"r // OP

"nteger Promotions
-nte$er ro%otions are con)ersions of the follo7in$ types? from to

33 "ool "yte u"yte short char int int int int int

D Specification

ushort int 7char int dchar uint -f a typedef or enu% has as a "ase type one of the types in the left colu%n4 it is con)erted to the type in the ri$ht colu%n.

'sual .rithmetic Con1ersions


The usual arith%etic con)ersions con)ert operands of "inary operators to a co%%on type. The operands %ust already "e of arith%etic types. The follo7in$ rules are applied in order4 loo6in$ at the "ase type? 1. 2. 3. &. -f either operand is real4 the other operand is con)erted to real. 'lse if either operand is dou"le4 the other operand is con)erted to dou"le. 'lse if either operand is float4 the other operand is con)erted to float. 'lse the inte$er pro%otions are done on each operand4 follo7ed "y? 1. -f "oth are the sa%e type4 no %ore con)ersions are done. 5. -f "oth are si$ned or "oth are unsi$ned4 the s%aller type is con)erted to the lar$er. (. -f the si$ned type is lar$er than the unsi$ned type4 the unsi$ned type is con)erted to the si$ned type. 7. The si$ned type is con)erted to the unsi$ned type. -f one or "oth of the operand types is a typedef or enu% after under$oin$ the a"o)e con)ersions4 the result type is? 1. -f the operands are the sa%e type4 the result 7ill "e the that type. 2. -f one operand is a typedef or enu% and the other is the "ase type of that typedef or enu%4 the result is the "ase type. 3. -f the t7o operands are different typedefs or enu%s "ut of the sa%e "ase type4 then the result is that "ase type. -nte$er )alues cannot "e i%plicitly con)erted to another type that cannot represent the inte$er "it pattern after inte$ral pro%otion. .or exa%ple?
ubF#e us "r# ui&# u!"&' u1 u2 u3 u( = = = = cas#?bF#e@:1; cas#?s "r#@:1; cas#?i&#@:1; cas#?u!"&'@:1; // // // // err"r) err"r) "=) :1 "=) :1 :1 ca&&"# be represe&#ed i& a ubF#e :1 ca&&"# be represe&#ed i& a us "r# ca& be represe&#ed i& a ui&# ca& be represe&#ed i& a u!"&'

.loatin$ point types cannot "e i%plicitly con)erted to inte$ral types. ,o%plex floatin$ point types cannot "e i%plicitly con)erted to non@co%plex floatin$ point types. -%a$inary floatin$ point types cannot "e i%plicitly con)erted to float4 dou"le4 or real types. .loat4 dou"le4 or real types cannot "e i%plicitly con)erted to i%a$inary floatin$ point types.

D Specification

3&

0ool
The "ool type is a 1 "yte si5e type that can only hold the )alue true or false. The only operators that can accept operands of type "ool are? + O P +Q OQ PQ = ++ OO R?. ! "ool )alue can "e i%plicitly con)erted to any inte$ral type4 7ith false "eco%in$ 0 and true "eco%in$ 1. The nu%eric literals 0 and 1 can "e i%plicitly con)erted to the "ool )alues false and true4 respecti)ely. ,astin$ an expression to "ool %eans testin$ for 0 or =Q0 for arith%etic types4 and null or =Qnull for pointers or references.

%elegates
There are no pointers@to@%e%"ers in D4 "ut a %ore useful concept called delegates are supported. Dele$ates are an a$$re$ate of t7o pieces of data? an o">ect reference and a function pointer. The o">ect reference for%s the this pointer 7hen the function is called. Dele$ates are declared si%ilarly to function pointers4 except that the 6ey7ord delegate ta6es the place of ANB4 and the identifier occurs after7ards?
i&# fu&c#i"&?i&#@ fp; i&# de!e'a#e?i&#@ d'; // fp is p"i&#er #" a fu&c#i"& // d' is a de!e'a#e #" a fu&c#i"&

The , style syntax for declarin$ pointers to functions is also supported?


i&# ?*fp@?i&#@; // fp is p"i&#er #" a fu&c#i"&

! dele$ate is initiali5ed analo$ously to function pointers?


i&# fu&c?i&#@; fp = .fu&c; c!ass OB A i&# 0e0ber?i&#@; C OB "; d' = ."$0e0ber; // fp p"i&#s #" fu&c

// d' is a de!e'a#e #" "bMec# o a&d // 0e0ber fu&c#i"& mem'er

Dele$ates cannot "e initiali5ed 7ith static %e%"er functions or non@%e%"er functions. Dele$ates are called analo$ously to function pointers?
fp?3@; d'?3@; // ca!! fu&c?3@ // ca!! "$0e0ber?3@

35

D Specification

Properties
')ery type and expression has properties that can "e 9ueried? Expression int.si5eof float.nan AfloatB.nan A3B.si5eof 2.si5eof int.init yields & yields the floatin$ point nan A2ot ! 2u%"erB )alue yields the floatin$ point nan )alue yields & A"ecause 3 is an intB syntax error4 since C2.C is a floatin$ point nu%"er default initiali5er for int:s 5alue

int.%an$leof yields the strin$ CiC

Properties for .ll Types


Property .init .si5eof .ali$nof .%an$leof initiali5er si5e in "ytes Ae9ui)alent to ,:s si5eofAtypeBB ali$n%ent si5e strin$ representin$ the :%an$led: representation of the type %escription

Properties for "ntegral Types


Property .init .%ax .%in %escription initiali5er A0B %axi%u% )alue %ini%u% )alue

Properties for Floating Point Types


Property .init .infinity .nan .di$ .epsilon initiali5er A2a2B infinity )alue 2a2 )alue nu%"er of deci%al di$its of precision s%allest incre%ent to the )alue 1 %escription

D Specification .%antJdi$ nu%"er of "its in %antissa

3(

.%axJ10Jexp %axi%u% int )alue such that 10%axJ10Jexp is representa"le .%axJexp %axi%u% int )alue such that 2%axJexp@1 is representa"le

%inJ10Jexp is representa"le as a nor%ali5ed .%inJ10Jexp %ini%u% int )alue such that 10 )alue

.%inJexp .%ax .%in .re .i%

%ini%u% int )alue such that 2%inJexp@1 is representa"le as a nor%ali5ed )alue lar$est representa"le )alue that:s not infinity s%allest representa"le nor%ali5ed )alue that:s not 0 real part i%a$inary part

-init Property
-init produces a constant expression that is the default initiali5er. -f applied to a type4 it is the default initiali5er for that type. -f applied to a )aria"le or field4 it is the default initiali5er for that )aria"le or field. .or exa%ple?
i&# a; i&# b = 1; #Fpedef i&# # = 2; # c; # d = cas#?#@3; i&#$i&i# a$i&i# b$i&i# #$i&i# c$i&i# d$i&i# s#ruc# 1"" A i&# a; i&# b = 8; C 1""$a$i&i# 1""$b$i&i# // is 0 // is 8 // // // // // // is is is is is is 0 0 1 2 2 3

Class and Struct Properties


roperties are %e%"er functions that can "e syntactically treated as if they 7ere fields. roperties can "e read fro% or 7ritten to. ! property is read "y callin$ a %ethod 7ith no ar$u%entsS a property is 7ritten "y callin$ a %ethod 7ith its ar$u%ent "ein$ the )alue it is set to. ! si%ple property 7ould "e?
s#ruc# 1"" A i&# da#a?@ A re#ur& 06da#a; C // read pr"per#F

37

D Specification
i&# da#a?i&# >a!ue@ A re#ur& 06da#a = >a!ue; C // ,ri#e pr"per#F pri>a#e: i&# 06da#a;

To use it?
i&# #es#?@ A 1"" f; f$da#a = 3; re#ur& f$da#a + 3; // sa0e as f$da#a?3@; // sa0e as re#ur& f$da#a?@ + 3;

The a"sence of a read %ethod %eans that the property is 7rite@only. The a"sence of a 7rite %ethod %eans that the property is read@only. Multiple 7rite %ethods can existS the correct one is selected usin$ the usual function o)erloadin$ rules. -n all the other respects4 these %ethods are li6e any other %ethods. They can "e static4 ha)e different lin6a$es4 "e o)erloaded 7ith %ethods 7ith %ultiple para%eters4 ha)e their address ta6en4 etc. (ote2 roperties currently cannot "e the l)alue of an opQ4 884 or @@ operator.

D Specification

3#

Attributes
#ttri'&teSpecifier: #ttri'&te : #ttri'&te %eclarationBlock #ttri'&te: Linkage#ttri'&te #lign#ttri'&te ,ragma ,9?r9*!%9, ?rA&!%9 ?!*H!D9 ?rF%9*%9, ?("CA* 9'?Fr% B%!%A* #A$!C F&9rrA,9 !"B%r!*% *F$B% !(%F B*F?9 %eclarationBlock %ecl%ef {L} { %ecl%efs }

!ttri"utes are a 7ay to %odify one or %ore declarations. The $eneral for%s are?
a##ribu#e dec!ara#i"&; a##ribu#e: dec!ara#i"&; dec!ara#i"&; $$$ a##ribu#e A dec!ara#i"&; dec!ara#i"&; $$$ C affec#s # e dec!ara#i"& affec#s a!! dec!ara#i"&s u&#i! # e &e%# C

affec#s a!! dec!ara#i"&s i& # e b!"c=

.or attri"utes 7ith an optional else clause?


a##ribu#e dec!ara#i"&; e!se dec!ara#i"&; a##ribu#e A dec!ara#i"&; dec!ara#i"&; $$$ C e!se A affec#s a!! dec!ara#i"&s i& # e b!"c=

3*
dec!ara#i"&; dec!ara#i"&; $$$ C

D Specification

Lin!age .ttri0ute
Linkage#ttri'&te: 9'%9r$ 9'%9r$ ( LinkageType ) LinkageType: ; ;++ < MA$,F+B @!B*!C

D pro)ides an easy 7ay to call , functions and operatin$ syste% ! - functions4 as co%pati"ility 7ith "oth is essential. The Linkage'ype is case sensiti)e4 and is %eant to "e extensi"le "y the i%ple%entation Athey are not 6ey7ordsB. C and % %ust "e supplied4 the others are 7hat %a6es sense for the i%ple%entation. C66 is reser)ed for future use. "mplementation (ote2 for Din32 platfor%s4 indo$s and Pascal should exist. , function callin$ con)entions are specified "y?
e%#er& ?C@: i&# f""?@; // ca!! f""?@ ,i# C c"&>e&#i"&s

D con)entions are?
e%#er& ?D@:

or?
e%#er&:

Dindo7s ! - con)entions are?


e%#er& ?Ki&d",s@: >"id *Qir#ua!A!!"c? >"id *!pAddress) ui&# d,LiIe) ui&# f!A!!"ca#i"&JFpe) ui&# f!Rr"#ec# @;

.lign .ttri0ute
#lign#ttri'&te: !CAD$ !CAD$ ( Integer )

Specifies the ali$n%ent of struct %e%"ers. align "y itself sets it to the default4 7hich %atches the default %e%"er ali$n%ent of the co%panion , co%piler. Integer specifies the ali$n%ent 7hich %atches the "eha)ior of the co%panion , co%piler 7hen non@default ali$n%ents are used.

D Specification Matchin$ the "eha)ior of the co%panion , co%piler can ha)e so%e surprisin$ results4 such as the follo7in$ for Di$ital Mars ,88?
s#ruc# L A a!i'&?(@ bF#e a; a!i'&?(@ bF#e b; C // p!aced a# "ffse# 0 // p!aced a# "ffse# 1

&0

(lign(ttri#ute is %eant for , !3- co%pati"lity4 7hich is not the sa%e thin$ as "inary co%pati"ility across di)erse platfor%s. .or that4 use pac6ed structs?
a!i'& ?1@ s#ruc# L A bF#e a; // p!aced a# "ffse# 0 bF#e435 fi!!er1; bF#e b; // p!aced a# "ffse# ( bF#e435 fi!!er2; C

! )alue of 1 %eans that no ali$n%ent is doneS %e%"ers are pac6ed to$ether. Do not ali$n references or pointers that 7ere allocated usin$ !ewExpression on "oundaries that are not a %ultiple of siIe6#. The $ar"a$e collector assu%es that pointers and references to $c allocated o">ects 7ill "e on siIe6# "yte "oundaries. -f they are not4 undefined "eha)ior 7ill result. (lign(ttri#ute is i$nored 7hen applied to declarations that are not structs or struct %e%"ers.

%eprecated .ttri0ute
-t is often necessary to deprecate a feature in a li"rary4 yet retain it for "ac67ards co%pati"ility. Such declarations can "e %ar6ed as deprecated4 7hich %eans that the co%piler can "e set to produce an error if any code refers to deprecated declarations?
depreca#ed A >"id "!d1""?@; C

"mplementation (ote2 The co%piler should ha)e a s7itch specifyin$ if deprecated declarations should "e co%piled 7ith out co%plaint or not.

Protection .ttri0ute
rotection is an attri"ute that is one of pri1ate4 pac!age4 protected4 pu0lic or export. ri)ate %eans that only %e%"ers of the enclosin$ class can access the %e%"er4 or %e%"ers and functions in the sa%e %odule as the enclosin$ class. ri)ate %e%"ers cannot "e o)erridden. ri)ate %odule %e%"ers are e9ui)alent to static declarations in , pro$ra%s. ac6a$e extends pri)ate so that pac6a$e %e%"ers can "e accessed fro% code in other %odules that are in the sa%e pac6a$e. This applies to the inner%ost pac6a$e only4 if a %odule is in nested pac6a$es. rotected %eans that only %e%"ers of the enclosin$ class or any classes deri)ed fro% that class4 or %e%"ers and functions in the sa%e %odule as the enclosin$ class4 can access the %e%"er. -f accessin$ a protected instance %e%"er throu$h a deri)ed class %e%"er function4 that %e%"er can only "e accessed for the o">ect instance 7hich is the :this: o">ect for the %e%"er function call.

&1 rotected %odule %e%"ers are ille$al. u"lic %eans that any code 7ithin the executa"le can access the %e%"er.

D Specification

'xport %eans that any code outside the executa"le can access the %e%"er. 'xport is analo$ous to exportin$ definitions fro% a DLL.

Const .ttri0ute
*F$B%

The const attri"ute declares constants that can "e e)aluated at co%pile ti%e. .or exa%ple?
c"&s# i&# f"" = 8; c"&s# A d"ub!e bar = f"" + 3; C

! const declaration 7ithout an initiali5er %ust "e initiali5ed in a constructor Afor class fieldsB or in a static constructor Afor static class %e%"ers4 or %odule )aria"le declarationsB.
c"&s# i&# %; c"&s# i&# F; s#a#ic # is?@ A % = 3; // "= // err"r: F &"# i&i#ia!iIed C >"id f""?@ A % = (; C

// err"r) % is c"&s# a&d &"# i& s#a#ic c"&s#ruc#"r

c!ass C A c"&s# i&# a; c"&s# i&# b; s#a#ic c"&s# i&# c; s#a#ic c"&s# i&# d; # is?@ A a = 3; // a = (; // C p = # is; p$a = (; // c = 7; // // err"r) b is &"# C # is?i&# %@ A # is?@; C s#a#ic # is?@ A "= "=) 0u!#ip!e i&i#ia!iIa#i"& a!!",ed err"r) "&!F 0e0bers "f # is i&s#a&ce err"r) s "u!d i&i#ia!iIe i& s#a#ic c"&s#ruc#"r i&i#ia!iIed

// "=) f"r,ardi&' c"&s#ruc#"r

D Specification
c = 3; // "= // err"r) d is &"# i&i#ia!iIed

&2

C C

-t is not an error to ha)e const %odule )aria"le declarations 7ithout initiali5ers if there is no constructor. This is to support the practice of ha)in$ %odules ser)e only as declarations that are not lin6ed in4 the i%ple%entation of it 7ill "e in another %odule that is lin6ed in.

O1erride .ttri0ute
F&9rrA,9

The o1erride attri"ute applies to )irtual functions. -t %eans that the function %ust o)erride a function 7ith the sa%e na%e and para%eters in a "ase class. The o)erride attri"ute is useful for catchin$ errors 7hen a "ase class:s %e%"er function $ets its para%eters chan$ed4 and all deri)ed classes need to ha)e their o)erridin$ functions updated.
c!ass 1"" A i&# bar?@; i&# abc?i&# %@; C c!ass 1""2 : 1"" A ">erride A i&# bar?c ar c@; i&# abc?i&# %@; C C

// err"r) &" bar?c ar@ i& 1"" // "=

Static .ttri0ute
B%!%A*

The static attri"ute applies to functions and data. -t %eans that the declaration does not apply to a particular instance of an o">ect4 "ut to the type of the o">ect. -n other 7ords4 it %eans there is no this reference. static is i$nored 7hen applied to other declarations.
c!ass 1"" A s#a#ic i&# bar?@ A re#ur& 3; C i&# f""bar?@ A re#ur& 8; C C $$$ 1"" f = &e, 1""; 1""$bar?@; // 1""$f""bar?@; // f$bar?@; // f$f""bar?@; // pr"duces 3 err"r) &" i&s#a&ce "f 1"" pr"duces 3; pr"duces 8;

Static functions are ne)er )irtual.

&3 Static data has only one instance for the entire pro$ra%4 not once per o">ect.

D Specification

Static does not ha)e the additional , %eanin$ of "ein$ local to a file. ;se the pri1ate attri"ute in D to achie)e that. .or exa%ple?
0"du!e f""; i&# % = 3; pri>a#e i&# F = (; // % is '!"ba! // F is !"ca! #" 0"du!e f""

.uto .ttri0ute
!(%F

The auto attri"ute is used 7hen there are no other attri"utes and type inference is desired.
au#" i = 3$9; // dec!are i as a d"ub!e

Scope .ttri0ute
B*F?9

The scope attri"ute is used for local )aria"les and for class declarations. .or class declarations4 the scope attri"ute creates a scope class. .or local declarations4 scope i%ple%ents the L!-- ALesource !c9uisition -s -nitiali5ationB protocol. This %eans that the destructor for an o">ect is auto%atically called 7hen the reference to it $oes out of scope. The destructor is called e)en if the scope is exited )ia a thro7n exception4 thus scope is used to $uarantee cleanup. -f there is %ore than one scope )aria"le $oin$ out of scope at the sa%e point4 then the destructors are called in the re)erse order that the )aria"les 7ere constructed. scope cannot "e applied to $lo"als4 statics4 data %e%"ers4 inout or out para%eters. !rrays of scopes are not allo7ed4 and scope function return )alues are not allo7ed. !ssi$n%ent to a scope4 other than initiali5ation4 is not allo7ed. ,ationale2 These restrictions %ay $et relaxed in the future if a co%pellin$ reason to appears.

.0stract .ttri0ute
-f a class is a"stract4 it cannot "e instantiated directly. -t can only "e instantiated as a "ase class of another4 non@a"stract4 class. ,lasses "eco%e a"stract if they are defined 7ithin an a"stract attri"ute4 or if any of the )irtual %e%"er functions 7ithin it are declared as a"stract. 2on@)irtual functions cannot "e declared as a"stract. .unctions declared as a"stract can still ha)e function "odies. This is so that e)en thou$h they %ust "e o)erridden4 they can still pro)ide :"ase class functionality.:

D Specification

&&

Pragmas
,ragma: ?r!DE! ( Identifier ) ?r!DE! ( Identifier , E+pressionList )

ra$%as are a 7ay to pass special infor%ation to the co%piler and to add )endor specific extensions to D. ra$%as can "e used "y the%sel)es ter%inated 7ith a :S:4 they can influence a state%ent4 a "loc6 of state%ents4 a declaration4 or a "loc6 of declarations.
pra'0a?ide&#@; // Mus# bF i#se!f pra'0a?ide&#@ dec!ara#i"&; // i&f!ue&ce "&e dec!ara#i"& pra'0a?ide&#@: dec!ara#i"&; dec!ara#i"&; pra'0a?ide&#@ A dec!ara#i"&; dec!ara#i"&; C pra'0a?ide&#@ s#a#e0e&#; pra'0a?ide&#@ A s#a#e0e&#; s#a#e0e&#; C // i&f!ue&ce subse+ue&# dec!ara#i"&s

// i&f!ue&ce b!"c= "f dec!ara#i"&s

// i&f!ue&ce "&e s#a#e0e&# // i&f!ue&ce b!"c= "f s#a#e0e&#s

The 6ind of pra$%a it is is deter%ined "y the Identifier. ExpressionList is a co%%a@separated list of (ssignExpressions. The (ssignExpressions %ust "e parsa"le as expressions4 "ut 7hat they %ean se%antically is up to the indi)idual pra$%a se%antics.

Predefined Pragmas
!ll i%ple%entations %ust support these4 e)en if "y >ust i$norin$ the%? msg rints a %essa$e 7hile co%pilin$4 the (ssignExpressions %ust "e strin$ literals?
pra'0a?0s') "c"0pi!i&'$$$"@;

li0 -nserts a directi)e in the o">ect file to lin6 in the li"rary specified "y the (ssignExpression. The (ssignExpressions %ust "e a strin$ literal?
pra'0a?!ib) "f""$!ib"@;

5endor Specific Pragmas


Mendor specific pra$%a Identifiers can "e defined if they are prefixed "y the )endor:s trade%ar6ed na%e4 in a si%ilar %anner to )ersion identifiers?
pra'0a?Di'i#a!Sars6fu&=F6e%#e&si"&@ A $$$ C

&5

D Specification

,o%pilers %ust dia$nose an error for unreco$ni5ed Pragmas4 e)en if they are )endor specific ones. This i%plies that )endor specific pra$%as should "e 7rapped in )ersion state%ents?
>ersi"& ?Di'i#a!Sars@ A pra'0a?Di'i#a!Sars6fu&=F6e%#e&si"&@ A $$$ C C

D Specification

&(

Expressions
, and ,88 pro$ra%%ers 7ill find the D expressions )ery fa%iliar4 7ith a fe7 interestin$ additions. 'xpressions are used to co%pute )alues 7ith a resultin$ type. These )alues can then "e assi$ned4 tested4 or i$nored. 'xpressions can also ha)e side effects.
StringLiterals: StringLiteral StringLiterals StringLiteral #rg&mentList: #ssignE+pression #ssignE+pression , #rg&mentList

E1aluation Order
;nless other7ise specified4 the i%ple%entation is free to e)aluate the co%ponents of an expression in any order. -t is an error to depend on order of e)aluation 7hen it is not specified. .or exa%ple4 the follo7in$ are ille$al?
i = i++; c = a + ?a = b@; fu&c?++i) ++i@;

-f the co%piler can deter%ine that the result of an expression is ille$ally dependent on the order of e)aluation4 it can issue an error A"ut is not re9uired toB. The a"ility to detect these 6inds of errors is a 9uality of i%ple%entation issue.

Expressions
E+pression: #ssignE+pression #ssignE+pression , E+pression

The left operand of the & is e)aluated4 then the ri$ht operand is e)aluated. The type of the expression is the type of the ri$ht operand4 and the result is the result of the ri$ht operand.

.ssign Expressions
#ssignE+pression: ConditionalE+pression ConditionalE+pression ConditionalE+pression ConditionalE+pression ConditionalE+pression ConditionalE+pression ConditionalE+pression ConditionalE+pression ConditionalE+pression ConditionalE+pression ConditionalE+pression ConditionalE+pression ConditionalE+pression ConditionalE+pression = #ssignE+pression += #ssignE+pression -= #ssignE+pression *= #ssignE+pression /= #ssignE+pression %= #ssignE+pression &= #ssignE+pression |= #ssignE+pression ^= #ssignE+pression ~= #ssignE+pression <<= #ssignE+pression >>= #ssignE+pression >>>= #ssignE+pression

&7

D Specification

The ri$ht operand is i%plicitly con)erted to the type of the left operand4 and assi$ned to it. The result type is the type of the l)alue4 and the result )alue is the )alue of the l)alue after the assi$n%ent. The left operand %ust "e an l)alue.

.ssignment Operator Expressions


!ssi$n%ent operator expressions4 such as?
a op1 '

are se%antically e9ui)alent to?


a 1 a op '

except that operand a is only e)aluated once.

Conditional Expressions
ConditionalE+pression: OrOrE+pression OrOrE+pression ? E+pression : ConditionalE+pression

The first expression is con)erted to "ool4 and is e)aluated. -f it is true4 then the second expression is e)aluated4 and its result is the result of the conditional expression. -f it is false4 then the third expression is e)aluated4 and its result is the result of the conditional expression. -f either the second or third expressions are of type )oid4 then the resultin$ type is )oid. /ther7ise4 the second and third expressions are i%plicitly con)erted to a co%%on type 7hich "eco%es the result type of the conditional expression.

OrOr Expressions
OrOrE+pression: #nd#ndE+pression OrOrE+pression || #nd#ndE+pression

The result type of an OrOrExpression is "ool4 unless the ri$ht operand has type )oid4 7hen the result is type )oid. The OrOrExpression e)aluates its left operand. -f the left operand4 con)erted to type "ool4 e)aluates to true4 then the ri$ht operand is not e)aluated. -f the result type of the OrOrExpression is "ool then the result of the expression is true. -f the left operand is false4 then the ri$ht operand is e)aluated. -f the result type of the OrOrExpression is "ool then the result of the expression is the ri$ht operand con)erted to type "ool.

.nd.nd Expressions
#nd#ndE+pression: OrE+pression #nd#ndE+pression && OrE+pression

The result type of an (nd(ndExpression is "ool4 unless the ri$ht operand has type )oid4 7hen the

D Specification result is type )oid. The (nd(ndExpression e)aluates its left operand.

&#

-f the left operand4 con)erted to type "ool4 e)aluates to false4 then the ri$ht operand is not e)aluated. -f the result type of the (nd(ndExpression is "ool then the result of the expression is false. -f the left operand is true4 then the ri$ht operand is e)aluated. -f the result type of the (nd(ndExpression is "ool then the result of the expression is the ri$ht operand con)erted to type "ool.

Bit$ise Expressions
3it 7ise expressions perfor% a "it7ise operation on their operands. Their operands %ust "e inte$ral types. .irst4 the default inte$ral pro%otions are done. Then4 the "it7ise operation is done.

Or Expressions
OrE+pression: 2orE+pression OrE+pression | 2orE+pression

The operands are /L:d to$ether.

7or Expressions
2orE+pression: #ndE+pression 2orE+pression ^ #ndE+pression

The operands are T/L:d to$ether.

.nd Expressions
#ndE+pression: E)&alE+pression #ndE+pression & E)&alE+pression

The operands are !2D:d to$ether.

E/uality Expressions
E)&alE+pression: 3elE+pression E)&alE+pression E)&alE+pression E)&alE+pression E)&alE+pression == 3elE+pression != 3elE+pression AB 3elE+pression !AB 3elE+pression

'9uality expressions co%pare the t7o operands for e9uality A88B or ine9uality A98B. The type of the result is "ool. The operands $o throu$h the usual con)ersions to "rin$ the% to a co%%on type "efore co%parison. -f they are inte$ral )alues or pointers4 e9uality is defined as the "it pattern of the type %atches exactly. '9uality for struct o">ects %eans the "it patterns of the o">ects %atch exactly Athe existence

&*

D Specification

of ali$n%ent holes in the o">ects is accounted for4 usually "y settin$ the% all to 0 upon initiali5ationB. '9uality for floatin$ point types is %ore co%plicated. @0 and 80 co%pare as e9ual. -f either or "oth operands are 2!24 then "oth the QQ returns false and =Q returns true. /ther7ise4 the "it patterns are co%pared for e9uality. .or co%plex nu%"ers4 e9uality is defined as e9ui)alent to?
%$re == F$re .. %$i0 == F$i0

and ine9uality is defined as e9ui)alent to?


%$re B= F$re TT %$i0 B= F$i0

.or class and struct o">ects4 the expression ?a == b@ is re7ritten as a$"pE+ua!s?b@4 and ?a B= b@ is re7ritten as Ba$"pE+ua!s?b@. .or static and dyna%ic arrays4 e9uality is defined as the len$ths of the arrays %atchin$4 and all the ele%ents are e9ual.

"dentity Expressions
E)&alE+pression AB 3elE+pression E)&alE+pression !AB 3elE+pression

The is co%pares for identity. To co%pare for not identity4 use e4 !AB e0. The type of the result is "ool. The operands $o throu$h the usual con)ersions to "rin$ the% to a co%%on type "efore co%parison. .or operand types other than class o">ects4 static or dyna%ic arrays4 identity is defined as "ein$ the sa%e as e9uality. .or class o">ects4 identity is defined as the o">ect references are for the sa%e o">ect. 2ull class o">ects can "e co%pared 7ith is. .or static and dyna%ic arrays4 identity is defined as referrin$ to the sa%e array ele%ents. The identity operator is cannot "e o)erloaded.

,elational Expressions
3elE+pression: ShiftE+pression InE+pression 3elE+pression < ShiftE+pression 3elE+pression <= ShiftE+pression 3elE+pression > ShiftE+pression 3elE+pression >= ShiftE+pression 3elE+pression !<>= ShiftE+pression 3elE+pression !<> ShiftE+pression 3elE+pression <> ShiftE+pression 3elE+pression <>= ShiftE+pression 3elE+pression !> ShiftE+pression 3elE+pression !>= ShiftE+pression 3elE+pression !< ShiftE+pression 3elE+pression !<= ShiftE+pression

.irst4 the inte$ral pro%otions are done on the operands. The result type of a relational expression is

D Specification "ool. .or class o">ects4 the result of /">ect.op,%pAB for%s the left operand4 and 0 for%s the ri$ht operand. The result of the relational expression Ao1 op o2B is?
?"1$"pC0p?"2@ "p 0@

50

-t is an error to co%pare o">ects if one is null. .or static and dyna%ic arrays4 the result of the relational op is the result of the operator applied to the first non@e9ual ele%ent of the array. -f t7o arrays co%pare e9ual4 "ut are of different len$ths4 the shorter array co%pares as ClessC than the lon$er array.

"nteger comparisons
-nte$er co%parisons happen 7hen "oth operands are inte$ral types. -nte$er co%parison operators Operator U V UQ VQ QQ ,elation less $reater less or e9ual $reater or e9ual e9ual

=Q not e9ual -t is an error to ha)e one operand "e si$ned and the other unsi$ned for a U4 UQ4 V or VQ expression. ;se casts to %a6e "oth operands si$ned or "oth operands unsi$ned.

Floating point comparisons


-f one or "oth operands are floatin$ point4 then a floatin$ point co%parison is perfor%ed. ;seful floatin$ point operations %ust ta6e into account 2!2 )alues. -n particular4 a relational operator can ha)e 2!2 operands. The result of a relational operation on float )alues is less4 $reater4 e9ual4 or unordered Aunordered %eans either or "oth of the operands is a 2!2B. That %eans there are 1& possi"le co%parison conditions to test for? :reater Than . T T T . . . T . . T T .loatin$ point co%parison operators Less E/ual 'nordered Exception Than T . . T . T . T . . . . no no yes yes yes yes e9ual unordered4 less4 or $reater $reater $reater or e9ual less less or e9ual

Operator QQ =Q V VQ U UQ

,elation

51 =UVQ UV UVQ =UQ =U =VQ =V =UV (otes2 . T T T T . . . . T T . . T T . . . T . T . T T T . . T T T T T no yes yes no no no no no

D Specification unordered less or $reater less4 e9ual4 or $reater unordered or $reater unordered4 $reater4 or e9ual unordered or less unordered4 less4 or e9ual unordered or e9ual

1. .or floatin$ point co%parison operators4 Aa =op "B is not the sa%e as =Aa op "B. 2. C;norderedC %eans one or "oth of the operands is a 2!2. 3. C'xceptionC %eans the In"alid Exception is raised if one of the operands is a 2!2. -t does not %ean an exception is thro7n. The In"alid Exception can "e chec6ed usin$ the functions in std.c.fen).

"n Expressions
InE+pression: 3elE+pression A$ ShiftE+pression

!n associati)e array can "e tested to see if an ele%ent is in the array?


i&# f""4c ar455; $$$ if ?" e!!"" i& f""@ $$$

The in expression has the sa%e precedence as the relational expressions ;4 ;84 etc. The return )alue of the InExpression is null if the ele%ent is not in the arrayS if it is in the array it is a pointer to the ele%ent.

Shift Expressions
ShiftE+pression: #ddE+pression ShiftE+pression << #ddE+pression ShiftE+pression >> #ddE+pression ShiftE+pression >>> #ddE+pression

The operands %ust "e inte$ral types4 and under$o the usual inte$ral pro%otions. The result type is the type of the left operand after the pro%otions. The result )alue is the result of shiftin$ the "its "y the ri$ht operand:s )alue. ;; is a left shift. << is a si$ned ri$ht shift. <<< is an unsi$ned ri$ht shift. -t:s ille$al to shift "y %ore "its than the si5e of the 9uantity "ein$ shifted?
i&# c;

D Specification
c UU 33; // err"r

52

.dd Expressions
#ddE+pression: -&lE+pression #ddE+pression + -&lE+pression #ddE+pression - -&lE+pression CatE+pression

-f the operands are of inte$ral types4 they under$o inte$ral pro%otions4 and then are "rou$ht to a co%%on type usin$ the usual arith%etic con)ersions. -f either operand is a floatin$ point type4 the other is i%plicitly con)erted to floatin$ point and they are "rou$ht to a co%%on type )ia the usual arith%etic con)ersions. -f the operator is 6 or )4 and the first operand is a pointer4 and the second is an inte$ral type4 the resultin$ type is the type of the first operand4 and the resultin$ )alue is the pointer plus Aor %inusB the second operand %ultiplied "y the si5e of the type pointed to "y the first operand. -f the second operand is a pointer4 and the first is an inte$ral type4 and the operator is 64 the operands are re)ersed and the pointer arith%etic >ust descri"ed is applied. !dd expressions for floatin$ point operands are not associati)e.

Cat Expressions
CatE+pression: #ddE+pression ~ -&lE+pression

! CatExpression concatenates arrays4 producin$ a dyn%aic array 7ith the result. The arrays %ust "e arrays of the sa%e ele%ent type. -f one operand is an array and the other is of that array:s ele%ent type4 that ele%ent is con)erted to an array of len$th 1 of that ele%ent4 and then the concatenation is perfor%ed.

Mul Expressions
-&lE+pression: !naryE+pression -&lE+pression * !naryE+pression -&lE+pression / !naryE+pression -&lE+pression % !naryE+pression

The operands %ust "e arith%etic types. They under$o inte$ral pro%otions4 and then are "rou$ht to a co%%on type usin$ the usual arith%etic con)ersions. .or inte$ral operands4 the =4 >4 and ? correspond to %ultiply4 di)ide4 and %odulus operations. .or %ultiply4 o)erflo7s are i$nored and si%ply chopped to fit into the inte$ral type. -f the ri$ht operand of di)ide or %odulus operators is 04 an 'xception is thro7n. .or inte$ral operands of the ? operator4 the si$n of the result is positi)e if the operands are positi)e4 other7ise the si$n of the result is i%ple%entation defined. .or floatin$ point operands4 the operations correspond to the -''' 75& floatin$ point e9ui)alents. The %odulus operator only 7or6s 7ith reals4 it is ille$al to use it 7ith i%a$inary or co%plex

53 operands. Mul expressions for floatin$ point operands are not associati)e.

D Specification

'nary Expressions
!naryE+pression: ,ostfi+E+pression & !naryE+pression ++ !naryE+pression -- !naryE+pression * !naryE+pression - !naryE+pression + !naryE+pression ! !naryE+pression ~ !naryE+pression ( Type )L. Identifier Ne E+pression %eleteE+pression CastE+pression Ne #nonClassE+pression

(e$ Expressions
Ne E+pression: Ne #rg&ments Ne #rg&ments Ne #rg&ments Ne #rg&ments Type [ #ssignE+pression ] Type ( #rg&mentList ) Type Class#rg&ments BaseClasslist"p# { %ecl%efs }L

Ne #rg&ments: $9+L( #rg&mentList ) $9+L(L) $9+ Class#rg&ments: *C!BBL( #rg&mentList ) *C!BBL(L) *C!BB

!ewExpressions are used to allocate %e%ory on the $ar"a$e collected heap AdefaultB or usin$ a class or struct specific allocator. To allocate %ultidi%ensional arrays4 the declaration reads in the sa%e order as the prefix array declaration order.
c ar4545 f""; // dF&a0ic arraF "f s#ri&'s $$$ f"" = &e, c ar454305; // a!!"ca#e arraF "f 30 s#ri&'s

The a"o)e allocation can also "e 7ritten as?


f"" = &e, c ar4545?30@; // a!!"ca#e arraF "f 30 s#ri&'s

To allocate the nested arrays4 %ultiple ar$u%ents can "e used?


i&#454545 bar; $$$ bar = &e, i&#454545?7)20)30@;

D Specification Dhich is e9ui)alent to?


bar = &e, i&#4545475; f"reac ?i&"u# a; bar@ A a = &e, i&#454205; f"reac ?i&"u# b; a@ A b = &e, i&#4305; C C

5&

-f there is a ne$ 3 (rgumentList 44 then those ar$u%ents are passed to the class or struct specific allocator function after the si5e ar$u%ent. -f a !ewExpression is used as an initiali5er for a function local )aria"le 7ith scope stora$e class4 and the (rgumentList to ne$ is e%pty4 then the instance is allocated on the stac6 rather than the heap or usin$ the class specific allocator.

%elete Expressions
%eleteE+pression: ,9C9%9 !naryE+pression

-f the )naryExpression is a class o">ect reference4 and there is a destructor for that class4 the destructor is called for that o">ect instance. 2ext4 if the )naryExpression is a class o">ect reference4 or a pointer to a struct instance4 and the class or struct has o)erloaded operator delete4 then that operator delete is called for that class o">ect instance or struct instance. /ther7ise4 the $ar"a$e collector is called to i%%ediately free the %e%ory allocated for the class instance or struct instance. -f the $ar"a$e collector 7as not used to allocate the %e%ory for the instance4 undefined "eha)ior 7ill result. -f the )naryExpression is a pointer or a dyna%ic array4 the $ar"a$e collector is called to i%%ediately release the %e%ory. -f the $ar"a$e collector 7as not used to allocate the %e%ory for the instance4 undefined "eha)ior 7ill result. The pointer4 dyna%ic array4 or reference is set to null after the delete is perfor%ed. -f )naryExpression is a )aria"le allocated on the stac64 the class destructor Aif anyB is called for that instance. 2either the $ar"a$e collector nor any class deallocator is called.

Cast Expressions
CastE+pression: *!B%L( Type ) !naryE+pression

! CastExpression con)erts the )naryExpression to 'ype.


*!B%?f""@ :p; ?f""@ : p; // cas# ?:p@ #" #Fpe f"" // sub#rac# p fr"0 f""

!ny castin$ of a class reference to a deri)ed class reference is done 7ith a runti%e chec6 to %a6e sure it really is a do7ncast. null is the result if it isn:t. (ote2 This is e9ui)alent to the "eha)ior of the dyna%icJcast operator in ,88.

55
c!ass A A $$$ C c!ass B : A A $$$ C >"id #es#?A A B b% = B b% = A a% = A a% = C a) B b@ a; cas#?B@ a; b; cas#?A@ b; // // // // err"r) &eed cas# b% is &u!! if a is &"# a B &" cas# &eeded &" ru&#i0e c ec= &eeded f"r upcas#

D Specification

-n order to deter%ine if an o">ect " is an instance of a class B use a cast?


if ?*!B%?B@ "@ A // " is a& i&s#a&ce "f B C e!se A // " is &"# a& i&s#a&ce "f B C

,astin$ a floatin$ point literal fro% one type to another chan$es its type4 "ut internally it is retained at full precision for the purposes of constant foldin$.
>"id #es#?@ A rea! a = 3$(0(93;; rea! b; b = 3$(0(93; // !i#era! is &"# #ru&ca#ed #" d"ub!e precisi"& asser#?a == b@; asser#?a == 3$(0(93@; asser#?a == 3$(0(93;@; asser#?a == 3$(0(931@; d"ub!e d = 3$(0(93; // #ru&ca#e !i#era! , e& assi'&ed #" >ariab!e asser#?d B= a@; // s" i# is &" !"&'er # e sa0e c"&s# d"ub!e % = 3$(0(93; // assi'&0e&# #" c"&s# is &"# asser#?% == a@; // #ru&ca#ed if # e i&i#ia!iIer is >isib!e C

,astin$ a )alue " to a struct $4 7hen )alue is not a struct of the sa%e type4 is e9ui)alent to?
L?>@

Postfix Expressions
,ostfi+E+pression: ,rimaryE+pression ,ostfi+E+pression ,ostfi+E+pression ,ostfi+E+pression ,ostfi+E+pression ,ostfi+E+pression ,ostfi+E+pression Inde+E+pression SliceE+pression . Identifier . Ne E+pression ++ -(L) ( #rg&mentList )

D Specification

5(

"ndex Expressions
Inde+E+pression: ,ostfi+E+pression [ #rg&mentList ]

PostfixExpression is e)aluated. -f PostfixExpression is an expression of type static array or dyna%ic array4 the )aria"le length is declared and set to "e the len$th of the array. if PostfixExpression is an Expression'uple4 the )aria"le length Aand the special )aria"le WB is declared and set to "e the the nu%"er of ele%ents in the tuple. ! ne7 declaration scope is created for the e)aluation of the (rgumentList and length Aand WB appears in that scope only. -f PostfixExpression is an Expression'uple4 then the (rgumentList %ust consist of only one ar$u%ent4 and that %ust "e statically e)aluata"le to an inte$ral constant. That inte$ral constant n then selects the nth expression in the Expression'uple4 7hich is the result of the IndexExpression. -t is an error if n is out of "ounds of the Expression'uple.

Slice Expressions
SliceE+pression: ,ostfi+E+pression [L] ,ostfi+E+pression [ #ssignE+pression .. #ssignE+pression ]

PostfixExpression is e)aluated. if PostfixExpression is an expression of type static array or dyna%ic array4 the )aria"le length Aand the special )aria"le WB is declared and set to "e the len$th of the array. ! ne7 declaration scope is created for the e)aluation of the (ssignExpression..(ssignExpression and length Aand WB appears in that scope only. The first (ssignExpression is ta6en to "e the inclusi)e lo7er "ound of the slice4 and the second (ssignExpression is the exclusi)e upper "ound. The result of the expression is a slice of the PostfixExpression array. -f the @ A for% is used4 the slice is of the entire array. The type of the slice is a dyna%ic array of the ele%ent type of the PostfixExpression. -f PostfixExpression is an Expression'uple4 then the result of the slice is a ne7 Expression'uple for%ed fro% the upper and lo7er "ounds4 7hich %ust statically e)aluate to inte$ral constants. -t is an error if those "ounds are out of ran$e.

Primary Expressions
,rimaryE+pression: Identifier .Identifier %IAB B(?9r $(CC %r(9 #!CB9 N&mericLiteral CharacterLiteral StringLiterals #rrayLiteral F&nctionLiteral #ssertE+pression BasicType . Identifier

57
%G?9A,L( Type ) IsE+pression ( E+pression )

D Specification

-"dentifier
Identifier is loo6ed up at %odule scope4 rather than the current lexically nested scope.

this
Dithin a non@static %e%"er function4 this resol)es to a reference to the o">ect that called the function. -f a %e%"er function is called 7ith an explicit reference to typeof3this44 a non@)irtual call is %ade?
c!ass A A c ar 'e#?@ A re#ur& 'A'; C c ar f""?@ A re#ur& %G?9F#(%IAB)$'e#?@; C c ar bar?@ A re#ur& %IAB$'e#?@; C

c!ass B : A A c ar 'e#?@ A re#ur& 'B'; C C >"id 0ai&?@ A B b = &e, B?@; b$f""?@; b$bar?@; C // re#ur&s 'A' // re#ur&s 'B'

super
Dithin a non@static %e%"er function4 super resol)es to a reference to the o">ect that called the function4 cast to its "ase class. -t is an error if there is no "ase class. A/nly class ObMec# has no "ase class.B super is not allo7ed in struct %e%"er functions. -f a %e%"er function is called 7ith an explicit reference to super4 a non@)irtual call is %ade.

null
null represents the null )alue for pointers4 pointers to functions4 dele$ates4 dyna%ic arrays4 associati)e arrays4 and class o">ects. -f it has not already "een cast to a type4 it is $i)en the type A)oid NB and it is an exact con)ersion to con)ert it to the null )alue for pointers4 pointers to functions4 dele$ates4 etc. !fter it is cast to a type4 such con)ersions are i%plicit4 "ut no lon$er exact.

true& false
These are of type 0ool and 7hen cast to another inte$ral type "eco%e the )alues 1 and 04 respecti)ely.

D Specification

5#

Character Literals
,haracter literals are sin$le characters and resol)e to one of type char4 $char4 or dchar. -f the literal is a Eu escape se9uence4 it resol)es to type $char. -f the literal is a E; escape se9uence4 it resol)es to type dchar. /ther7ise4 it resol)es to the type 7ith the s%allest si5e it 7ill fit into.

.rray Literals
#rrayLiteral: [ #rg&mentList ]

!rray literals are a co%%a@separated list of (ssignExpressions "et7een s9uare "rac6ets H and I. The (ssignExpressions for% the ele%ents of a static array4 the len$th of the array is the nu%"er of ele%ents. The type of the first ele%ent is ta6en to "e the type of all the ele%ents4 and all ele%ents are i%plicitly con)erted to that type. -f that type is a static array4 it is con)erted to a dyna%ic array.
41)2)35; 41u)2)35; // #Fpe is i&#435) ,i# e!e0e&#s 1) 2 a&d 3 // #Fpe is ui&#435) ,i# e!e0e&#s 1u) 2u) a&d 3u

-f any of the ar$u%ents in the (rgumentList are an Expression'uple4 then the ele%ents of the Expression'uple are inserted as ar$u%ents in place of the tuple.

Function Literals
F&nctionLiteral #($*%AF$ Type"p# ( #rg&mentList )"p# F&nctionBody ,9C9D!%9 Type"p# ( #rg&mentList )"p# F&nctionBody ( #rg&mentList ) F&nctionBody F&nctionBody

FunctionLiterals ena"le e%"eddin$ anony%ous functions and anony%ous dele$ates directly into expressions. 'ype is the return type of the function or dele$ate4 if o%itted it is inferred fro% any *eturn$tatements in the Function+ody. 3 (rgumentList 4 for%s the ar$u%ents to the function. -f o%itted it defaults to the e%pty ar$u%ent list 34. The type of a function literal is pointer to function or pointer to dele$ate. -f the 6ey7ords function or delegate are o%itted4 it defaults to "ein$ a dele$ate. .or exa%ple?
i&# fu&c#i"&?c ar c@ fp; // dec!are p"i&#er #" a fu&c#i"& >"id #es#?@ A s#a#ic i&# f""?c ar c@ A re#ur& 3; C fp = .f""; C

is exactly e9ui)alent to?


i&# fu&c#i"&?c ar c@ fp; >"id #es#?@ A fp = #($*%AF$LA$%(*I!rL*)L{Lr9%(r$L5;} ; C

5* !nd?
i&# abc?i&# de!e'a#e?!"&' i@@; >"id #es#?@ A i&# b = 3; i&# f""?!"&' c@ A re#ur& 3 + b; C abc?.f""@; C

D Specification

is exactly e9ui)alent to?


i&# abc?i&# de!e'a#e?!"&' i@@; >"id #es#?@ A i&# b = 3; abc? ,9C9D!%9LA$%(CF$DL*)L{Lr9%(r$L5L+L";L} @; C

and the follo7in$ 7here the return type int is inferred?


i&# abc?i&# de!e'a#e?!"&' i@@; >"id #es#?@ A i&# b = 3; abc? (CF$DL*)L{Lr9%(r$L5L+L";L} @; C

!nony%ous dele$ates can "eha)e li6e ar"itrary state%ent literals. .or exa%ple4 here an ar"itrary state%ent is executed "y a loop?
d"ub!e #es#?@ A d"ub!e d = 8$3; f!"a# f = 2$3; >"id !""p?i&# =) i&# M) >"id de!e'a#e?@ s#a#e0e&#@ A f"r ?i&# i = =; i U M; i++@ A s#a#e0e&#?@; C C !""p?7) 100) {L,L+=L0;L} @; !""p?3) 10) {L#L+=L2;L} @; re#ur& d + f; C

Dhen co%parin$ 7ith nested functions4 the function for% is analo$ous to static or non@nested functions4 and the delegate for% is analo$ous to non@static nested functions. -n other 7ords4 a dele$ate literal can access stac6 )aria"les in its enclosin$ function4 a function literal cannot.

.ssert Expressions
#ssertE+pression: !BB9r%L( E+pression )

D Specification
!BB9r%L( E+pression , E+pression )

(0

!sserts e)aluate the expression. -f the result is false4 an .ssertError is thro7n. -f the result is true4 then no exception is thro7n. -t is an error if the expression contains any side effects that the pro$ra% depends on. The co%piler %ay optionally not e)aluate assert expressions at all. The result type of an assert expression is >"id. !sserts are a funda%ental part of the ,ontract ro$ra%%in$ support in D. The expression asser#?0@ is a special caseS it si$nifies that it is unreacha"le code. 'ither .ssertError is thro7n at runti%e if it is reacha"le4 or the execution is halted Aon the x#( processor4 a BLT instruction can "e used to halt executionB. The opti%i5ation and code $eneration phases of co%pilation %ay assu%e that it is unreacha"le code. The second Expression4 if present4 %ust "e i%plicitly con)erti"le to type c ar45. -t is e)aluated if the result is false4 and the strin$ result is appended to the .ssertError:s %essa$e.
>"id 0ai&?@ A asser#?0) "a&" 2 " err"r 0essa'e"@; C

Dhen co%piled and run4 it 7ill produce the %essa$e?


Err"r: Asser#Err"r 1ai!ure #es#$d?3@ a& err"r 0essa'e

Typeid Expressions
TypeidE+pression: %G?9A,L( Type )

Leturns an instance of class Type"nfo correspondin$ to 'ype.

"sExpression
IsE+pression: ABL( Type ABL( Type ABL( Type ABL( Type ABL( Type ABL( Type ) : TypeSpeciali/ation ) == TypeSpeciali/ation ) Identifier ) Identifier : TypeSpeciali/ation ) Identifier == TypeSpeciali/ation )

TypeSpeciali/ation: Type %G?9,9# B%r(*% ($AF$ *C!BB A$%9r#!*9 9$(E #($*%AF$ ,9C9D!%9 B(?9r

IsExpressions are e)aluated at co%pile ti%e and are used for chec6in$ for )alid types4 co%parin$ types for e9ui)alence4 deter%inin$ if one type can "e i%plicitly con)erted to another4 and deducin$ the su"types of a type. The result of an IsExpression is an int of type 0 if the condition is not

(1 satisified4 1 if it is.

D Specification

'ype is the type "ein$ tested. -t %ust "e syntactically correct4 "ut it need not "e se%antically correct. -f it is not se%antically correct4 the condition is not satisfied. Identifier is declared to "e an alias of the resultin$ type if the condition is satisfied. The Identifier for%s can only "e used if the IsExpression appears in a $taticIfCondition. 'ype$peciali&ation is the type that 'ype is "ein$ co%pared a$ainst. The for%s of the IsExpression are? 1. is 3 'ype 4 The condition is satisfied if 'ype is se%antically correct Ait %ust "e syntactically correct re$ardlessB.
a!ias i&# fu&c?i&#@; >"id f""?@ A if ? AB?fu&c45@ @ e!se // fu&c is a a!ias #" a fu&c#i"& #Fpe

// &"# sa#isfied because arraFs "f // fu&c#i"&s are &"# a!!",ed pri&#f?"sa#isfied\&"@; pri&#f?"&"# sa#isfied\&"@;

if ?AB?4545@@ $$$ C

// err"r) 4545 is &"# a sF&#ac#ica!!F >a!id #Fpe

2. is 3 'ype 2 'ype$peciali&ation 4 The condition is satisfied if 'ype is se%antically correct and it is the sa%e as or can "e i%plicitly con)erted to 'ype$peciali&ation. 'ype$peciali&ation is only allo7ed to "e a 'ype.
a!ias s "r# bar; >"id f""?bar %@ A if ? AB?bar : i&#@ @ pri&#f?"sa#isfied\&"@; e!se C

// sa#isfied because s "r# ca& be // i0p!ici#!F c"&>er#ed #" i&#

pri&#f?"&"# sa#isfied\&"@;

3. is 3 'ype 88 'ype$peciali&ation 4 The condition is satisfied if 'ype is se%antically correct and is the sa%e type as 'ype$peciali&ation. -f 'ype$peciali&ation is one of typedef struct union class interface enum function delegate then the condition is satisifed if 'ype is one of those.
a!ias s "r# bar; #Fpedef c ar f""; >"id #es#?bar %@ A if ? AB?bar == i&#@ @ e!se pri&#f?"sa#isfied\&"@; pri&#f?"&"# sa#isfied\&"@; if ? AB?f"" == #Fpedef@ @ // sa#isfied because f"" is a #Fpedef

// &"# sa#isfied because s "r# is &"# // # e sa0e #Fpe as i&#

D Specification
pri&#f?"sa#isfied\&"@; e!se C pri&#f?"&"# sa#isfied\&"@;

(2

&. is 3 'ype Identifier 4 The condition is satisfied if 'ype is se%antically correct. -f so4 Identifier is declared to "e an alias of 'ype.
a!ias s "r# bar; >"id f""?bar %@ A s#a#ic if ? AB?bar J@ @ a!ias J L; e!se a!ias !"&' L; ,ri#ef!&?#Fpeid?L@@; // pri&#s "s "r#" if ? AB?bar J@ @ $$$ C // err"r) Identifier J f"r0 ca& // "&!F be i& StaticIfConditions

5. is 3 'ype Identifier 2 'ype$peciali&ation 4 The condition is satisfied if 'ype is the sa%e as or can "e i%plicitly con)erted to 'ype$peciali&ation. The Identifier is declared to "e either an alias of the 'ype$peciali&ation or4 if 'ype$peciali&ation is dependent on Identifier4 the deduced type. 'ype$peciali&ation is only allo7ed to "e a 'ype.
a!ias s "r# bar; a!ias !"&'* abc; >"id f""?bar %) abc a@ A s#a#ic if ? AB?bar J : i&#@ @ a!ias J L; e!se a!ias !"&' L; ,ri#ef!&?#Fpeid?L@@; s#a#ic if ? AB?abc - : -*@ @ - u; C ,ri#ef!&?#Fpeid?#Fpe"f?u@@@; // pri&#s "!"&'" // pri&#s "i&#"

The 7ay the type of Identifier is deter%ined is analo$ous to the 7ay te%plate para%eter types are deter%ined "y 'emplate'ypeParameter$peciali&ation. (. is 3 'ype Identifier 88 'ype$peciali&ation 4 The condition is satisfied if 'ype is se%antically correct and is the sa%e as 'ype$peciali&ation. The Identifier is declared to "e either an alias of the 'ype$peciali&ation or4 if 'ype$peciali&ation is dependent on Identifier4 the deduced type. -f 'ype$peciali&ation is one of typedef struct union class interface enum function delegate then the condition is satisifed if 'ype is one of those. .urther%ore4 Identifier is set to "e an alias of the type?

(3 !ey$ord typedef struct union class super enum delegate return 'ype 'ype 'ype 'ype'uple of "ase classes and interfaces the "ase type of the enu% the function type of the dele$ate the return type of the function4 dele$ate4 or function pointer alias type for Identifier the type that 'ype is a typedef of

D Specification

interface 'ype

function 'ype'uple of the function para%eter types

a!ias s "r# bar; e&u0 E : bF#e A E0e0ber C >"id f""?bar %@ A s#a#ic if ? AB?bar J == i&#@ @ // &"# sa#isfied) s "r# is &"# i&# a!ias J L; a!ias J -; // err"r) J is &"# defi&ed s#a#ic if ? AB?E Q == e&u0@ @ Q >; // sa#isified) E is a& e&u0 // > is dec!ared #" be a bF#e

D Specification

(&

Statements
, and ,88 pro$ra%%ers 7ill find the D state%ents )ery fa%iliar4 7ith a fe7 interestin$ additions.
L#a#e0e&#: ; NonEmptyStatement ScopeBlockStatement H"Lc"peH"&E0p#FL#a#e0e&#: NonEmptyStatement BlockStatement H"Lc"peL#a#e0e&#: ; NonEmptyStatement BlockStatement H"&E0p#FOrLc"peB!"c=L#a#e0e&#: NonEmptyStatement ScopeBlockStatement H"&E0p#FL#a#e0e&#: La'eledStatement E+pressionStatement %eclarationStatement IfStatement ConditionalStatement WhileStatement %oStatement ForStatement ForeachStatement S itchStatement CaseStatement %efa&ltStatement Contin&eStatement BreakStatement 3et&rnStatement 5otoStatement WithStatement Synchroni/edStatement TryStatement Scope5&ardStatement Thro Statement .olatileStatement #smStatement ,ragmaStatement

Scope Statements
ScopeStatement: NonEmptyStatement BlockStatement

! ne7 scope for local sy%"ols is introduced for the !onEmpty$tatement or +lock$tatement, ')en thou$h a ne7 scope is introduced4 local sy%"ol declarations cannot shado7 AhideB other local sy%"ol declarations in the sa%e function.

(5
>"id fu&c1?i&# %@ A i&# %; // i!!e'a!) % s ad",s para0e#er % i&# F; A i&# F; C // i!!e'a!) F s ad",s e&c!"si&' sc"pe's F

D Specification

>"id de!e'a#e?@ d'; d' = A i&# F; C; // "=) # is F is &"# i& # e sa0e fu&c#i"& s#ruc# L A i&# F; C A i&# I; C A i&# I; C A i&# #; C A #++; C

// "=) # is F is a 0e0ber) &"# a !"ca!

// "=) # is I is &"# s ad",i&' # e "# er I // i!!e'a!) # is u&defi&ed

The idea is to a)oid "u$s in co%plex functions caused "y scoped declarations inad)ertently hidin$ pre)ious ones. Local na%es should all "e uni9ue 7ithin a function.

Scope Bloc! Statements


ScopeBlockStatement: BlockStatement

! scope "loc6 state%ent introduces a ne7 scope for the +lock$tatement.

La0eled Statements
State%ents can "e la"eled. ! la"el is an identifier that precedes a state%ent.
La'elledStatement: Identifier ':' NoScopeStatement

!ny state%ent can "e la"elled4 includin$ e%pty state%ents4 and so can ser)e as the tar$et of a $oto state%ent. La"elled state%ents can also ser)e as the tar$et of a "rea6 or continue state%ent. La"els are in a na%e space independent of declarations4 )aria"les4 types4 etc. ')en so4 la"els cannot ha)e the sa%e na%e as local declarations. The la"el na%e space is the "ody of the function they appear in. La"el na%e spaces do not nest4 i.e. a la"el inside a "loc6 state%ent is accessi"le fro% outside that "loc6.

Bloc! Statement
BlockStatement: {L} { StatementList } StatementList: Statement Statement StatementList

D Specification ! "loc6 state%ent is a se9uence of state%ents enclosed "y X Y. The state%ents are executed in lexical order.

((

Expression Statement
E+pressionStatement: E+pression ;

The expression is e)aluated. 'xpressions that ha)e no effect4 li6e ?% + %@4 are ille$al in expression state%ents. -f such an expression is needed4 castin$ it to )oid 7ill %a6e it le$al.
i&# %; %++; %; 1+1; cas#?>"id@?% + %@; // // // // "= i!!e'a! i!!e'a! "=

%eclaration Statement
Declaration state%ents declare )aria"les and types.
%eclarationStatement: %eclaration

So%e declaration state%ents?


i&# a; // dec!are a as #Fpe i&# a&d i&i#ia!iIe i# #" 0 s#ruc# L A C // dec!are s#ruc# s a!ias i&# 0Fi&#;

"f Statement
-f state%ents pro)ide si%ple conditional execution of state%ents.
IfStatement: A#L( IfCondition ) ThenStatement A#L( IfCondition ) ThenStatement 9CB9 ElseStatement IfCondition: E+pression !(%F Identifier = E+pression %eclarator = E+pression ThenStatement: ScopeStatement ElseStatement: ScopeStatement

Expression is e)aluated and %ust ha)e a type that can "e con)erted to a "oolean. -f it:s true the 'hen$tatement is transferred to4 else the Else$tatement is transferred to. The :dan$lin$ else: parsin$ pro"le% is sol)ed "y associatin$ the else 7ith the nearest if state%ent. -f an auto Identifier is pro)ided4 it is declared and initiali5ed to the )alue and type of the

(7

D Specification

Expression. -ts scope extends fro% 7hen it is initiali5ed to the end of the 'hen$tatement. -f a eclarator is pro)ided4 it is declared and initiali5ed to the )alue of the Expression. -ts scope extends fro% 7hen it is initiali5ed to the end of the 'hen$tatement.
i0p"r# s#d$re'e%p; $$$ if ?au#" 0 = s#d$re'e%p$searc ?"abcdef") "b?c@d"@@ A ,ri#ef!&?"4Ns5") 0$pre@; // pri&#s 4a5 ,ri#ef!&?"4Ns5") 0$p"s#@; // pri&#s 4ef5 ,ri#ef!&?"4Ns5") 0$0a#c ?0@@; // pri&#s 4bcd5 ,ri#ef!&?"4Ns5") 0$0a#c ?1@@; // pri&#s 4c5 ,ri#ef!&?"4Ns5") 0$0a#c ?2@@; // pri&#s 45 C e!se A ,ri#ef!&?0$p"s#@; // err"r) 0 u&defi&ed C ,ri#ef!&?0$pre@; // err"r) 0 u&defi&ed

hile Statement
WhileStatement: +IAC9L( E+pression ) ScopeStatement

Dhile state%ents i%ple%ent si%ple loops. Expression is e)aluated and %ust ha)e a type that can "e con)erted to a "oolean. -f it:s true the $cope$tatement is executed. !fter the $cope$tatement is executed4 the Expression is e)aluated a$ain4 and if true the $cope$tatement is executed a$ain. This continues until the Expression e)aluates to false.
i&# i = 0; , i!e ?i U 10@ A f""?i@; i++; C

! +reak$tatement 7ill exit the loop. ! <,ontinueState%ent7ill transfer directly to e)aluatin$ Expression a$ain.

%o Statement
%oStatement: ,F ScopeStatement +IAC9L( E+pression )

Do 7hile state%ents i%ple%ent si%ple loops. $cope$tatement is executed. Then Expression is e)aluated and %ust ha)e a type that can "e con)erted to a "oolean. -f it:s true the loop is iterated a$ain. This continues until the Expression e)aluates to false.
i&# i = 0; d" A f""?i@; C , i!e ?++i U 10@;

! +reak$tatement 7ill exit the loop. ! Continue$tatement 7ill transfer directly to e)aluatin$

D Specification Expression a$ain.

(#

For Statement
.or state%ents i%ple%ent loops 7ith initiali5ation4 test4 and incre%ent clauses.
ForStatement: #FrL(Initiali/e Test; Increment) ScopeStatement Initiali/e: ; NoScopeNonEmptyStatement Test: empty E+pression

Increment: empty E+pression

Initiali&e is executed. 'est is e)aluated and %ust ha)e a type that can "e con)erted to a "oolean. -f it:s true the state%ent is executed. !fter the state%ent is executed4 the Increment is executed. Then 'est is e)aluated a$ain4 and if true the state%ent is executed a$ain. This continues until the 'est e)aluates to false. ! +reak$tatement 7ill exit the loop. ! Continue$tatement 7ill transfer directly to the Increment. ! For$tatement creates a ne7 scope. -f Initiali&e declares a )aria"le4 that )aria"le:s scope extends throu$h the end of the for state%ent. .or exa%ple?
f"r ?i&# i = 0; i U 10; i++@ f""?i@;

is e9ui)alent to?
A C i&# i; f"r ?i = 0; i U 10; i++@ f""?i@;

.unction "odies cannot "e e%pty?


f"r ?i&# i = 0; i U 10; i++@ ; // i!!e'a!

;se instead?
f"r ?i&# i = 0; i U 10; i++@ A C

The Initiali&e %ay "e o%itted. 'est %ay also "e o%itted4 and if so4 it is treated as if it e)aluated to true.

Foreach Statement
! foreach state%ent loops o)er the contents of an a$$re$ate.

(*
ForeachStatement: Foreach 6ForeachTypeList; #ggregate) Lc"peL#a#e0e&# Foreach: #Fr9!*I #Fr9!*I_r9&9rB9 ForeachTypeList: ForeachType ForeachType ) ForeachTypeList ForeachType: A$F(% Type Identifier Type Identifier A$F(% Identifier Identifier #ggregate: E+pression T&ple

D Specification

(ggregate is e)aluated. -t %ust e)aluate to an expression of type static array4 dyna%ic array4 associati)e array4 struct4 class4 dele$ate4 or tuple. The !o$cope!onEmpty$tatement is executed4 once for each ele%ent of the a$$re$ate. !t the start of each iteration4 the )aria"les declared "y the Foreach'ypeList are set to "e a copy of the ele%ents of the a$$re$ate. -f the )aria"le is inout4 it is a reference to the contents of that a$$re$ate. The a$$re$ate %ust "e loop in)ariant4 %eanin$ that ele%ents to the a$$re$ate cannot "e added or re%o)ed fro% it in the !o$cope!onEmpty$tatement. -f the a$$re$ate is a static or dyna%ic array4 there can "e one or t7o )aria"les declared. -f one4 then the )aria"le is said to "e the "alue set to the ele%ents of the array4 one "y one. The type of the )aria"le %ust %atch the type of the array contents4 except for the special cases outlined "elo7. -f there are t7o )aria"les declared4 the first is said to "e the index and the second is said to "e the "alue. The index %ust "e of int or uint type4 it cannot "e inout4 and it is set to "e the index of the array ele%ent.
c ar45 a; $$$ f"reac ?i&# i) c ar c; a@ A pri&#f?"a4Nd5 = 'Nc'\&") i) c@; C

.or foreach4 the ele%ents for the array are iterated o)er startin$ at index 0 and continuin$ to the %axi%u% of the array. .or foreach#re1erse4 the array ele%ents are )isited in the re)erse order. -f the a$$re$ate expression is a static or dyna%ic array of chars4 $chars4 or dchars4 then the 'ype of the "alue can "e any of char4 $char4 or dchar. -n this %anner any ;T. array can "e decoded into any ;T. type?
c ar45 a = "\%E2\%99\%A0"; f"reac ?dc ar c; a@ A pri&#f?"a45 = N%\&") c@; C dc ar45 b = "\u2230"; // \u2230 e&c"ded as 3 -J1:9 bF#es

// pri&#s 'a45 = 2230'

D Specification
f"reac ?c ar c; b@ A pri&#f?"N%) ") c@; C

70

// pri&#s 'e2) 99) a0'

!$$re$ates can "e strin$ literals4 7hich can "e accessed as char4 7char4 or dchar arrays?
>"id #es#?@ A f"reac ?c ar c; "ab"@ A pri&#f?"'Nc'\&") c@; C f"reac ?,c ar ,; "%F"@ A ,pri&#f?"'Nc'\&") ,@; C C

7hich 7ould print?


'a' 'b' '%' 'F'

-f the a$$re$ate expression is an associati)e array4 there can "e one or t7o )aria"les declared. -f one4 then the )aria"le is said to "e the "alue set to the ele%ents of the array4 one "y one. The type of the )aria"le %ust %atch the type of the array contents. -f there are t7o )aria"les declared4 the first is said to "e the index and the second is said to "e the "alue. The index %ust "e of the sa%e type as the indexin$ type of the associati)e array. -t cannot "e inout4 and it is set to "e the index of the array ele%ent. The order in 7hich the ele%ents of the array is unspecified for foreach. foreach#re1erse for associati)e arrays is ille$al.
d"ub!e4c ar455 a; // inde+ #Fpe is c ar45) "al&e #Fpe is d"ub!e $$$ f"reac ?c ar45 s) d"ub!e d; a@ A pri&#f?"a4'N$*s'5 = N'\&") s) d@; C

-f it is a struct or class o">ect4 the foreach is defined "y the special op(pply %e%"er function. The foreach#re1erse "eha)ior is defined "y the special op(pply*e"erse %e%"er function. These special functions %ust "e defined "y the type in order to use the correspondin$ foreach state%ent. The functions ha)e the type?
i&# F?:??CG?i&# de!e'a#e?i&"u# Type 4) $$$5@ dg@; i&# F?:??CGN9&9rB9?i&# de!e'a#e?i&"u# Type 4) $$$5@ dg@;

7here 'ype %atches the 'ype used in the Foreach'ype declaration of Identifier. Multiple Foreach'ypes correspond 7ith %ultiple 'ype:s in the dele$ate type passed to op.pply or op.pply,e1erse. There can "e %ultiple op.pply and op.pply,e1erse functions4 one is selected "y %atchin$ the type of dg to the Foreach'ypes of the Foreach$tatement. The "ody of the apply function iterates o)er the ele%ents it a$$re$ates4 passin$ the% each to the dg function. -f the dg returns 04 then apply $oes on to the next ele%ent. -f the dg returns a non5ero )alue4 apply %ust cease iteratin$ and return that )alue. /ther7ise4 after done iteratin$ across all the ele%ents4 apply

71 7ill return 0. .or exa%ple4 consider a class that is a container for t7o ele%ents?
c!ass 1"" A ui&# arraF425; i&# F?:??CG?i&# de!e'a#e?i&"u# ui&#@ dg@ A i&# resu!# = 0; f"r ?i&# i = 0; i U arraF$!e&'# ; i++@ A resu!# = dg?arraF4i5@; if ?resu!#@ brea=; C re#ur& resu!#;

D Specification

C C

!n exa%ple usin$ this %i$ht "e?


>"id #es#?@ A 1"" a = &e, 1""?@; a$arraF405 = 83; a$arraF415 = 92; f"reac ?ui&# u; a@ A pri&#f?"Nd\&") u@; C

7hich 7ould print?


83 92

-f (ggregate is a dele$ate4 the type si$nature of the dele$ate is of the sa%e as for op.pply. This ena"les %any different na%ed loopin$ strate$ies to coexist in the sa%e class or struct. inout can "e used to update the ori$inal ele%ents?
>"id #es#?@ A s#a#ic ui&#425 a = 48) 95; f"reac ?i&"u# ui&# u; a@ A u++; C f"reac ?ui&# u; a@ A pri&#f?"Nd\&") u@; C C

7hich 7ould print?

D Specification
9 9

72

inout can not "e applied to the index )alues. -f not specified4 the 'ypes in the Foreach'ype can "e inferred fro% the type of the (ggregate. The a$$re$ate itself %ust not "e resi5ed4 reallocated4 free:d4 reassi$ned or destructed 7hile the foreach is iteratin$ o)er the ele%ents.
i&#45 a; i&#45 b; f"reac ?i&# i; a@ A a = &u!!; a$!e&'# = a$!e&'# a = b; C a = &u!!;

+ 10;

// err"r // err"r // err"r // "=

-f the a$$re$ate is a tuple4 there can "e one or t7o )aria"les declared. -f one4 then the )aria"le is said to "e the "alue set to the ele%ents of the tuple4 one "y one. -f the type of the )aria"le is $i)en4 it %ust %atch the type of the tuple contents. -f it is not $i)en4 the type of the )aria"le is set to the type of the tuple ele%ent4 7hich %ay chan$e fro% iteration to iteration. -f there are t7o )aria"les declared4 the first is said to "e the index and the second is said to "e the "alue. The index %ust "e of int or uint type4 it cannot "e inout4 and it is set to "e the index of the tuple ele%ent. -f the tuple is a list of types4 then the foreach state%ent is executed once for each type4 and the )alue is aliased to that type.
i0p"r# s#d$s#di"; i0p"r# s#d$#Fpe#up!e; // f"r JFpeJup!e

>"id 0ai&?@ A a!ias JFpeJup!eB?i&#) !"&') d"ub!e@ J;; f"reac ?J; J;@ A ,ri#ef!&?#Fpeid?J@@; C

rints?
i&# !"&' d"ub!e

! +reak$tatement in the "ody of the foreach 7ill exit the foreach4 a Continue$tatement 7ill i%%ediately start the next iteration.

S$itch Statement
! s7itch state%ent $oes to one of a collection of case state%ents dependin$ on the )alue of the s7itch expression.
S itchStatement: B+A%*IL( E+pression ) ScopeStatement

73
CaseL#a#e0e&#: *!B9 E+pressionList : Statement Defau!#L#a#e0e&#: ,9#!(C%: Statement

D Specification

Expression is e)aluated. The result type T %ust "e of inte$ral type or charHI4 7charHI or dcharHI. The result is co%pared a$ainst each of the case expressions. -f there is a %atch4 the correspondin$ case state%ent is transferred to. The case expressions4 ExpressionList4 are a co%%a separated list of expressions. -f none of the case expressions %atch4 and there is a default state%ent4 the default state%ent is transferred to. -f none of the case expressions %atch4 and there is not a default state%ent4 a S7itch'rror is thro7n. The reason for this is to catch the co%%on pro$ra%%in$ error of addin$ a ne7 )alue to an enu%4 "ut failin$ to account for the extra )alue in s7itch state%ents. This "eha)ior is unli6e , or ,88. The case expressions %ust all e)aluate to a constant )alue or array4 and "e i%plicitly con)erti"le to the type T of the s7itch Expression. ,ase expressions %ust all e)aluate to distinct )alues. There %ay not "e t7o or %ore default state%ents. ,ase state%ents and default state%ents associated 7ith the s7itch can "e nested 7ithin "loc6 state%entsS they do not ha)e to "e in the outer%ost "loc6. .or exa%ple4 this is allo7ed?
s,i#c ?i@ A case 1: A case 2: C brea=; C

Li6e in , and ,884 case state%ents :fall throu$h: to su"se9uent case )alues. ! "rea6 state%ent 7ill exit the s7itch +lock$tatement. .or exa%ple?
s,i#c ?i@ A case 1: % = 3; case 2: % = (; brea=; case 3)()7: % = 7; brea=; C

7ill set x to & if i is 1. (ote2 ;nli6e , and ,884 strin$s can "e used in s7itch expressions. .or exa%ple?
c ar45 &a0e; $$$ s,i#c ?&a0e@

D Specification
A case "fred": case "sa!!F": $$$

7&

.or applications li6e co%%and line s7itch processin$4 this can lead to %uch %ore strai$htfor7ard code4 "ein$ clearer and less error prone. 3oth ascii and 7char strin$s are allo7ed. "mplementation (ote2 The co%piler:s code $enerator %ay assu%e that the case state%ents are sorted "y fre9uency of use4 7ith the %ost fre9uent appearin$ first and the least fre9uent last. !lthou$h this is irrele)ant as far as pro$ra% correctness is concerned4 it is of perfor%ance interest.

Continue Statement
Contin&eStatement: *F$%A$(9; *F$%A$(9 Identifier ;

! continue a"orts the current iteration of its enclosin$ loop state%ent4 and starts the next iteration. continue executes the next iteration of its inner%ost enclosin$ 7hile4 for4 or do loop. The incre%ent clause is executed. -f continue is follo7ed "y Identifier4 the Identifier %ust "e the la"el of an enclosin$ 7hile4 for4 or do loop4 and the next iteration of that loop is executed. -t is an error if there is no such state%ent. !ny inter)enin$ finally clauses are executed4 and any inter)enin$ synchroni5ation o">ects are released. (ote2 -f a finally clause executes a return4 thro74 or $oto out of the finally clause4 the continue tar$et is ne)er reached.
f"r ?i = 0; i U 10; i++@ A if ?f""?i@@ c"&#i&ue; bar?@; C

Brea! Statement
BreakStatement: "r9!H; "r9!H Identifier ;

! "rea6 exits the enclosin$ state%ent. "rea6 exits the inner%ost enclosin$ 7hile4 for4 do4 or s7itch state%ent4 resu%in$ execution at the state%ent follo7in$ it. -f "rea6 is follo7ed "y Identifier4 the Identifier %ust "e the la"el of an enclosin$ 7hile4 for4 do or s7itch state%ent4 and that state%ent is exited. -t is an error if there is no such state%ent. !ny inter)enin$ finally clauses are executed4 and any inter)enin$ synchroni5ation o">ects are released. (ote2 -f a finally clause executes a return4 thro74 or $oto out of the finally clause4 the "rea6 tar$et is ne)er reached.

75
f"r ?i = 0; i U 10; i++@ A if ?f""?i@@ brea=; C

D Specification

,eturn Statement
3et&rnStatement: r9%(r$; r9%(r$ E+pression ;

! return exits the current function and supplies its return )alue. Expression is re9uired if the function specifies a return type that is not )oid. The Expression is i%plicitly con)erted to the function return type. !t least one return state%ent4 thro7 state%ent4 or assertA0B expression is re9uired if the function specifies a return type that is not )oid. Expression is allo7ed e)en if the function specifies a 1oid return type. The Expression 7ill "e e)aluated4 "ut nothin$ 7ill "e returned. 3efore the function actually returns4 any o">ects 7ith auto stora$e duration are destroyed4 any enclosin$ finally clauses are executed4 any scopeAexitB state%ents are executed4 any scopeAsuccessB state%ents are executed4 and any enclosin$ synchroni5ation o">ects are released. The function 7ill not return if any enclosin$ finally clause does a return4 $oto or thro7 that exits the finally clause. -f there is an out postcondition Asee ,ontract ro$ra%%in$B4 that postcondition is executed after the Expression is e)aluated and "efore the function actually returns.
i&# f""?i&# %@ A re#ur& % + 3; C

:oto Statement
5otoStatement: DF%F Identifier ; DF%F ,9#!(C% ; DF%F *!B9 ; DF%F *!B9 E+pression ;

! $oto transfers to the state%ent la"elled 7ith Identifier.


if ?f""@ '"#" ;1; % = 3; %++;

;1:

The second for%4 '"#" defau!#;4 transfers to the inner%ost efault$tatement of an enclosin$ $witch$tatement. The third for%4 '"#" case;4 transfers to the next Case$tatement of the inner%ost enclosin$

D Specification $witch$tatement. The fourth for%4 '"#" case E+pression;4 transfers to the Case$tatement of the inner%ost enclosin$ $witch$tatement 7ith a %atchin$ Expression.
s,i#c ?%@ A case 3: '"#" case; case (: '"#" defau!#; case 7: '"#" case (; defau!#: % = (; brea=; C

7(

!ny inter)enin$ finally clauses are executed4 alon$ 7ith releasin$ any inter)enin$ synchroni5ation %utexes. -t is ille$al for a -oto$tatement to "e used to s6ip initiali5ations.

ith Statement
The 7ith state%ent is a 7ay to si%plify repeated references to the sa%e o">ect.
WithStatement: +A%I ( E+pression ) ScopeStatement +A%I ( Sym'ol ) ScopeStatement +A%I ( TemplateInstance ) ScopeStatement

7here Expression e)aluates to a class reference or struct instance. Dithin the 7ith "ody the referenced o">ect is searched first for identifier sy%"ols. The .ith$tatement
+A%I ?e%pressi"&@ A $$$ ide&#; C

is se%antically e9ui)alent to?


A ObMec# #0p; #0p = e%pressi"&; $$$ #0p$ide&#; C

2ote that e%pressi"& only $ets e)aluated once. The 7ith state%ent does not chan$e 7hat this or super refer to. .or $ym#ol 7hich is a scope or 'emplateInstance4 the correspondin$ scope is searched 7hen loo6in$ up sy%"ols. .or exa%ple?
s#ruc# 1"" A #Fpedef i&# V; C

77
$$$ V F; ,i# ?1""@ A V F; C // err"r) V u&defi&ed // sa0e as 1""$V F;

D Specification

Synchronized Statement
The synchroni5ed state%ent 7raps a state%ent 7ith critical section to synchroni5e access a%on$ %ultiple threads.
Synchroni/edStatement: BG$*IrF$AJ9, ScopeStatement BG$*IrF$AJ9,L( E+pression ) ScopeStatement

Synchroni5ed allo7s only one thread at a ti%e to execute $cope$tatement. synchroni5ed AExpressionB4 7here Expression e)aluates to an /">ect reference4 allo7s only one thread at a ti%e to use that /">ect to execute the $cope$tatement. -f Expression is an instance of an Interface4 it is cast to an O#/ect. The synchroni5ation $ets released e)en if $cope$tatement ter%inates 7ith an exception4 $oto4 or return. 'xa%ple?
sF&c r"&iIed A $$$ C

This i%ple%ents a standard critical section.

Try Statement
'xception handlin$ is done 7ith the try@catch@finally state%ent.
TryStatement: %rG ScopeStatement Catches %rG ScopeStatement Catches FinallyStatement %rG ScopeStatement FinallyStatement Catches: LastCatch Catch Catch Catches LastCatch: *!%*I NoScopeNonEmptyStatement Catch: *!%*IL( Catch,arameter ) NoScopeNonEmptyStatement FinallyStatement: #A$!CCG NoScopeNonEmptyStatement

CatchParameter declares a )aria"le ) of type T4 7here T is /">ect or deri)ed fro% /">ect. ) is initiali5ed "y the thro7 expression if T is of the sa%e type or a "ase class of the thro7 expression. The catch clause 7ill "e executed if the exception o">ect is of type T or deri)ed fro% T.

D Specification -f >ust type T is $i)en and no )aria"le )4 then the catch clause is still executed. -t is an error if any CatchParameter type T1 hides a su"se9uent Catch 7ith type T24 i.e. it is an error if T1 is the sa%e type as or a "ase class of T2. LastCatch catches all exceptions.

7#

The Finally$tatement is al7ays executed4 7hether the try $cope$tatement exits 7ith a $oto4 "rea64 continue4 return4 exception4 or fall@throu$h. -f an exception is raised in the Finally$tatement and is not cau$ht "efore the Finally$tatement is executed4 the ne7 exception replaces any existin$ exception?
i&# 0ai&?@ A #rF A #rF A

# r", &e, E%cep#i"&?"firs#"@; C fi&a!!F A pri&#f?"fi&a!!F\&"@; # r", &e, E%cep#i"&?"sec"&d"@; C

C ca#c ?E%cep#i"& e@ A pri&#f?"ca#c N$*s\&") e$0s'@; C pri&#f?"d"&e\&"@; re#ur& 0;

prints?
fi&a!!F ca#c sec"&d d"&e

! Finally$tatement %ay not exit 7ith a $oto4 "rea64 continue4 or returnS nor %ay it "e entered 7ith a $oto. ! Finally$tatement %ay not contain any Catches. This restriction %ay "e relaxed in future )ersions.

Thro$ Statement
Thro7 an exception.
Thro Statement: %IrF+ E+pression ;

Expression is e)aluated and %ust "e an /">ect reference. The /">ect reference is thro7n as an exception.
# r", &e, E%cep#i"&?"0essa'e"@;

7*

D Specification

Scope :uard Statement


Scope5&ardStatement: B*F?9(9'A%) 7NonEmptyOrScopeBlockStatement B*F?9(B(**9BB) 7NonEmptyOrScopeBlockStatement B*F?9(#!AC(r9) 7NonEmptyOrScopeBlockStatement

The $cope-uard$tatement executes !onEmptyOr$cope+lock$tatement at the close of the current scope4 rather than at the point 7here the $cope-uard$tatement appears. scope3exit4 executes !onEmptyOr$cope+lock$tatement 7hen the scope exits nor%ally or 7hen it exits due to exception un7indin$. scope3failure4 executes !onEmptyOr$cope+lock$tatement 7hen the scope exits due to exception un7indin$. scope3success4 executes !onEmptyOr$cope+lock$tatement 7hen the scope exits nor%ally. -f there are %ultiple $cope-uard$tatements in a scope4 they are executed in the re)erse lexical order in 7hich they appear. -f any auto instances are to "e destructed upon the close of the scope4 they also are interlea)ed 7ith the $cope-uard$tatements in the re)erse lexical order in 7hich they appear.
,ri#ef?"1"@; A ,ri#ef?"2"@; sc"pe?e%i#@ ,ri#ef?"3"@; sc"pe?e%i#@ ,ri#ef?"("@; ,ri#ef?"7"@; C ,ri#ef!&?@;

7rites?
127(3 A sc"pe?e%i#@ ,ri#ef?"1"@; sc"pe?success@ ,ri#ef?"2"@; sc"pe?e%i#@ ,ri#ef?"3"@; sc"pe?success@ ,ri#ef?"("@; C ,ri#ef!&?@;

7rites?
(321 c!ass 1"" A # is?@ A ,ri#ef?"0"@; C 2# is?@ A ,ri#ef?"1"@; C C #rF A

sc"pe?e%i#@ ,ri#ef?"2"@; sc"pe?success@ ,ri#ef?"3"@; au#" 1"" f = &e, 1""?@; sc"pe?fai!ure@ ,ri#ef?"("@; # r", &e, E%cep#i"&?"0s'"@; sc"pe?e%i#@ ,ri#ef?"7"@; sc"pe?success@ ,ri#ef?"3"@;

D Specification
sc"pe?fai!ure@ ,ri#ef?"8"@; C ca#c ?E%cep#i"& e@ A C ,ri#ef!&?@;

#0

7rites?
0(12

! scope3exit4 or scope3success4 state%ent %ay not exit 7ith a thro74 $oto4 "rea64 continue4 or returnS nor %ay it "e entered 7ith a $oto.

5olatile Statement
2o code %otion occurs across )olatile state%ent "oundaries.
.olatileStatement: &FC!%AC9 Statement &FC!%AC9 ;

$tatement is e)aluated. Me%ory 7rites occurrin$ "efore the $tatement are perfor%ed "efore any reads 7ithin or after the $tatement. Me%ory reads occurrin$ after the $tatement occur after any 7rites "efore or 7ithin $tatement are co%pleted. ! )olatile state%ent does not $uarantee ato%icity. .or that4 use synchroni5ed state%ents.

.sm Statement
-nline asse%"ler is supported 7ith the as% state%ent?
#smStatement: !BEL{L} !BEL{ #smInstr&ctionList } #smInstr&ctionList: #smInstr&ction ; #smInstr&ction ; #smInstr&ctionList

!n as% state%ent ena"les the direct use of asse%"ly lan$ua$e instructions. This %a6es it easy to o"tain direct access to special , ; features 7ithout resortin$ to an external asse%"ler. The D co%piler 7ill ta6e care of the function callin$ con)entions4 stac6 setup4 etc. The for%at of the instructions is4 of course4 hi$hly dependent on the nati)e instruction set of the tar$et , ;4 and so is i%ple%entation defined. 3ut4 the for%at 7ill follo7 the follo7in$ con)entions?

-t %ust use the sa%e to6ens as the D lan$ua$e uses. The co%%ent for% %ust %atch the D lan$ua$e co%%ents. !s% instructions are ter%inated "y a S4 not "y an end of line.

These rules exist to ensure that D source code can "e to6eni5ed independently of syntactic or se%antic analysis. .or exa%ple4 for the -ntel entiu%?
i&# % = 3;

#1
as0 A C

D Specification

0"> EAW)%;

// !"ad % a&d pu# i# i& re'is#er EAW

-nline asse%"ler can "e used to access hard7are directly?


i&# 'e# ard,are?@ A as0 A 0"> EAW) d,"rd p#r 0%123(; C C

.or so%e D i%ple%entations4 such as a translator fro% D to ,4 an inline asse%"ler %a6es no sense4 and need not "e i%ple%ented. The )ersion state%ent can "e used to account for this?
>ersi"& ?D6X&!i&eAs06W93@ A as0 A $$$ C C e!se A /* $$$ s"0e ,"r=ar"u&d $$$ */ C

Pragma Statement
,ragmaStatement: ,ragma NoScopeStatement

D Specification

#2

Arrays
There are four 6inds of arrays? intN pS intH3I sS intHI aS ointers to data Static arrays Dyna%ic arrays

intHcharHII xS !ssociati)e arrays

Pointers
i&#* p;

These are si%ple pointers to data4 analo$ous to , pointers. ointers are pro)ided for interfacin$ 7ith , and for speciali5ed syste%s 7or6. There is no len$th associated 7ith it4 and so there is no 7ay for the co%piler or runti%e to do "ounds chec6in$4 etc.4 on it. Most con)entional uses for pointers can "e replaced 7ith dyna%ic arrays4 "u# and i&"u# para%eters4 and reference types.

Static .rrays
i&#435 s;

These are analo$ous to , arrays. Static arrays are distin$uished "y ha)in$ a len$th fixed at co%pile ti%e. The total si5e of a static array cannot exceed 1(M". ! dyna%ic array should "e used instead for such lar$e arrays. ! static array 7ith a di%ension of 0 is allo7ed4 "ut no space is allocated for it. -t:s useful as the last %e%"er of a )aria"le len$th struct4 or as the de$enerate case of a te%plate expansion.

%ynamic .rrays
i&#45 a;

Dyna%ic arrays consist of a len$th and a pointer to the array data. Multiple dyna%ic arrays can share all or parts of the array data.

.rray %eclarations
There are t7o 7ays to declare arrays4 prefix and postfix. The prefix for% is the preferred %ethod4 especially for non@tri)ial types. Prefix .rray %eclarations refix declarations appear "efore the identifier "ein$ declared and read ri$ht to left4 so?
i&#45 a; i&#4(5435 b; i&#45475 c; i&#*45*435 d; i&#45* e; // // // // // dF&a0ic arraF "f i&#s arraF "f 3 arraFs "f ( i&#s eac arraF "f 7 dF&a0ic arraFs "f i&#s$ arraF "f 3 p"i&#ers #" dF&a0ic arraFs "f p"i&#ers #" i&#s p"i&#er #" dF&a0ic arraF "f i&#s

#3 Postfix .rray %eclarations

D Specification

ostfix declarations appear after the identifier "ein$ declared and read left to ri$ht. 'ach $roup lists e9ui)alent declarations?
// dF&a0ic arraF "f i&#s i&#45 a; i&# a45; // arraF "f 3 arraFs "f ( i&#s eac i&#4(5435 b; i&#4(5 b435; i&# b4354(5; // arraF "f 7 dF&a0ic arraFs "f i&#s$ i&#45475 c; i&#45 c475; i&# c47545; // arraF "f 3 p"i&#ers #" dF&a0ic arraFs "f p"i&#ers #" i&#s i&#*45*435 d; i&#*45* d435; i&#* ?*d435@45; // p"i&#er #" dF&a0ic arraF "f i&#s i&#45* e; i&# ?*e@45;

,ationale2 The postfix for% %atches the 7ay arrays are declared in , and ,884 and supportin$ this for% pro)ides an easy %i$ration path for pro$ra%%ers used to it.

'sage
There are t7o "road 6inds of operations to do on an array @ affectin$ the handle to the array4 and affectin$ the contents of the array. , only has operators to affect the handle. -n D4 "oth are accessi"le. The handle to an array is specified "y na%in$ the array4 as in p4 s or a?
i&#* p; i&#435 s; i&#45 a; i&#* +; i&#435 #; i&#45 b; p = +; p = s; p = a; s = $$$; a = p; a = s; a = b; // p p"i&#s #" # e sa0e # i&' + d"es$ // p p"i&#s #" # e firs# e!e0e&# "f # e arraF s$ // p p"i&#s #" # e firs# e!e0e&# "f # e arraF a$ // err"r) si&ce s is a c"0pi!ed i& s#a#ic // refere&ce #" a& arraF$ // // // // err"r) si&ce # e !e&'# "f # e arraF p"i&#ed #" bF p is u&=&",& a is i&i#ia!iIed #" p"i&# #" # e s arraF a p"i&#s #" # e sa0e arraF as b d"es

D Specification

#&

Slicing
$licing an array %eans to specify a su"array of it. !n array slice does not copy the data4 it is only another reference to it. .or exa%ple?
i&#4105 a; i&#45 b; b = a41$$35; f""?b415@; a425 = 3; f""?b415@; // dec!are arraF "f 10 i&#s // a41$$35 is a 2 e!e0e&# arraF c"&sis#i&' "f // a415 a&d a425 // e+ui>a!e&# #" f""?0@ // e+ui>a!e&# #" f""?3@

The HI is shorthand for a slice of the entire array. .or exa%ple4 the assi$n%ents to "?
i&#4105 a; i&#45 b; b = a; b = a45; b = a40 $$ a$!e&'# 5;

are all se%antically e9ui)alent. Slicin$ is not only handy for referrin$ to parts of other arrays4 "ut for con)ertin$ pointers into "ounds@chec6ed arrays?
i&#* p; i&#45 b = p40$$95;

.rray Copying
Dhen the slice operator appears as the l)alue of an assi$n%ent expression4 it %eans that the contents of the array are the tar$et of the assi$n%ent rather than a reference to the array. !rray copyin$ happens 7hen the l)alue is a slice4 and the r)alue is an array of or pointer to the sa%e type.
i&#435 s; i&#435 #; s45 = #; s45 = #45; s41$$25 = #40$$15; s40$$25 = #41$$35; s40$$(5 = #40$$(5; s40$$25 = #; // // // // // // # e 3 e!e0e&#s "f #435 are c"pied i&#" s435 # e 3 e!e0e&#s "f #435 are c"pied i&#" s435 sa0e as s415 = #405 sa0e as s405 = #415) s415 = #425 err"r) "&!F 3 e!e0e&#s i& s err"r) differe&# !e&'# s f"r !>a!ue a&d r>a!ue

/)erlappin$ copies are an error?


s40$$25 = s41$$35; s41$$35 = s40$$25; // err"r) ">er!appi&' c"pF // err"r) ">er!appi&' c"pF

Disallo7in$ o)erlappin$ %a6es it possi"le for %ore a$$ressi)e parallel code opti%i5ations than possi"le 7ith the serial se%antics of ,.

#5

D Specification

.rray Setting
-f a slice operator appears as the l)alue of an assi$n%ent expression4 and the type of the r)alue is the sa%e as the ele%ent type of the l)alue4 then the l)alue:s array contents are set to the r)alue.
i&#435 s; i&#* p; s45 = 3; p40$$25 = 3; // sa0e as s405 = 3) s415 = 3) s425 = 3 // sa0e as p405 = 3) p415 = 3

.rray Concatenation
The "inary operator G is the cat operator. -t is used to concatenate arrays?
i&#45 a; i&#45 b; i&#45 c; a = b 2 c; // Crea#e a& arraF fr"0 # e c"&ca#e&a#i"& "f # e // b a&d c arraFs

Many lan$ua$es o)erload the 8 operator to %ean concatenation. This confusin$ly leads to4 does?
"10" + 3

produce the nu%"er 13 or the strin$ C103C as the resultR -t isn:t o")ious4 and the lan$ua$e desi$ners 7ind up carefully 7ritin$ rules to disa%"i$uate it @ rules that $et incorrectly i%ple%ented4 o)erloo6ed4 for$otten4 and i$nored. -t:s %uch "etter to ha)e 8 %ean addition4 and a separate operator to "e array concatenation. Si%ilarly4 the GQ operator %eans append4 as in?
a 2= b; // a bec"0es # e c"&ca#e&a#i"& "f a a&d b

,oncatenation al7ays creates a copy of its operands4 e)en if one of the operands is a 0 len$th array4 so?
a = b; a = b 2 c40$$05; // a refers #" b // a refers #" a c"pF "f b

Pointer .rithmetic
i&#435 abc; i&#45 def = 4 1) 2) 3 5; >"id dibb?i&#* arraF@ A arraF425; *?arraF + 2@; C >"id diss?i&#45 arraF@ A arraF425; *?arraF + 2@; C // s#a#ic arraF "f 3 i&#s // dF&a0ic arraF "f 3 i&#s

// 0ea&s sa0e # i&' as *?arraF + 2@ // 'e# 3rd e!e0e&#

// "= // err"r) arraF is &"# a p"i&#er

D Specification
>"id di##?i&#435 arraF@ A arraF425; *?arraF + 2@; C

#(

// "= // err"r) arraF is &"# a p"i&#er

,ectangular .rrays
'xperienced ./LTL!2 nu%erics pro$ra%%ers 6no7 that %ultidi%ensional Crectan$ularC arrays for thin$s li6e %atrix operations are %uch faster than tryin$ to access the% )ia pointers to pointers resultin$ fro% Carray of pointers to arrayC se%antics. .or exa%ple4 the D syntax?
d"ub!e4545 0a#ri%;

declares %atrix as an array of pointers to arrays. ADyna%ic arrays are i%ple%ented as pointers to the array data.B Since the arrays can ha)e )aryin$ si5es A"ein$ dyna%ically si5edB4 this is so%eti%es called C>a$$edC arrays. ')en 7orse for opti%i5in$ the code4 the array ro7s can so%eti%es point to each other= .ortunately4 D static arrays4 7hile usin$ the sa%e syntax4 are i%ple%ented as a fixed rectan$ular layout?
d"ub!e435435 0a#ri%;

declares a rectan$ular %atrix 7ith 3 ro7s and 3 colu%ns4 all conti$uously in %e%ory. -n other lan$ua$es4 this 7ould "e called a %ultidi%ensional array and "e declared as?
d"ub!e 0a#ri%43)35;

.rray Length
Dithin the H I of a static or a dyna%ic array4 the )aria"le length is i%plicitly declared and set to the len$th of the array. The sy%"ol C can also "e so used.
i&#4(5 f""; i&#45 bar = f""; i&#* p = .f""405; // J ese bar45 bar40 $$ bar40 $$ bar40 $$ bar40 $$ e%pressi"&s are e+ui>a!e&#: (5 C9$D%I5 $5 bar$!e&'# 5 // '!e&'# ' is &"# defi&ed) si&ce p is &"# a& arraF // '!e&'# ' is &"# defi&ed) "u# "f sc"pe "f 4 5 // re#rie>es !as# e!e0e&# "f # e arraF

p40 $$ !e&'# 5 bar405+!e&'# bar4C9$D%I:15

.rray Properties
Static array properties are? -sizeof Leturns the array len$th %ultiplied "y the nu%"er of "ytes per array ele%ent.

#7 -length -ptr -dup

D Specification Leturns the nu%"er of ele%ents in the array. This is a fixed 9uantity for static arrays. Leturns a pointer to the first ele%ent of the array. ,reate a dyna%ic array of the sa%e si5e and copy the contents of the array into it.

-re1erse Le)erses in place the order of the ele%ents in the array. Leturns the array. -sort Sorts in place the order of the ele%ents in the array. Leturns the array. Dyna%ic array properties are? -sizeof -length -ptr -dup Leturns the si5e of the dyna%ic array reference4 7hich is # on 32 "it %achines. 1et/set nu%"er of ele%ents in the array. Leturns a pointer to the first ele%ent of the array. ,reate a dyna%ic array of the sa%e si5e and copy the contents of the array into it.

-re1erse Le)erses in place the order of the ele%ents in the array. Leturns the array. -sort Sorts in place the order of the ele%ents in the array. Leturns the array. .or the -sort property to 7or6 on arrays of class o">ects4 the class definition %ust define the function? i&# "pC0p?ObMec#@. This is used to deter%ine the orderin$ of the class o">ects. 2ote that the para%eter is of type ObMec#4 not the type of the class. .or the -sort property to 7or6 on arrays of structs or unions4 the struct or union definition %ust define the function? i&# "pC0p?L@ or i&# "pC0p?L*@. The type L is the type of the struct or union. This function 7ill deter%ine the sort orderin$. 'xa%ples?
p$!e&'# s$!e&'# a$!e&'# p$dup s$dup a$dup // err"r) !e&'# &"# =&",& f"r p"i&#er // c"0pi!e #i0e c"&s#a&# 3 // ru&#i0e >a!ue // // // // // err"r) !e&'# &"# =&",& crea#es a& arraF "f 3 e!e0e&#s) c"pies e!e0e&#s s i&#" i# crea#es a& arraF "f a$!e&'# e!e0e&#s) c"pies e!e0e&#s "f a i&#" i#

Setting %ynamic .rray Length


The .C9$D%I property of a dyna%ic array can "e set as the l)alue of an Q operator?
arraF$!e&'# = 8;

This causes the array to "e reallocated in place4 and the existin$ contents copied o)er to the ne7 array. -f the ne7 array len$th is shorter4 only enou$h are copied to fill the ne7 array. -f the ne7 array len$th is lon$er4 the re%ainder is filled out 7ith the default initiali5er. To %axi%i5e efficiency4 the runti%e al7ays tries to resi5e the array in place to a)oid extra copyin$. -t 7ill al7ays do a copy if the ne7 si5e is lar$er and the array 7as not allocated )ia the ne7 operator or a pre)ious resi5e operation.

D Specification

##

This %eans that if there is an array slice i%%ediately follo7in$ the array "ein$ resi5ed4 the resi5ed array could o)erlap the sliceS i.e.?
c ar45 a = &e, c ar4205; c ar45 b = a40$$105; c ar45 c = a410$$205; b$!e&'# = 17; // a!,aFs resiIed i& p!ace because i# is s!iced // fr"0 a45 , ic as e&"u' 0e0"rF f"r 17 c ars // a4115 a&d c415 are a!s" affec#ed // &" &e# c a&'e #" 0e0"rF !aF"u# // a!,aFs d"es a c"pF because c45 is &"# a# # e // s#ar# "f a 'c a!!"ca#i"& b!"c= // d"es &"# affec# c"&#e&#s "f a45 "r b45 // 0aF "r 0aF &"# d" a c"pF // 0aF "r 0aF &"# affec# b435 , ic // # e "!d a435 s#i!! ">er!aps

b4115 = '%'; a$!e&'# a$!e&'# c$!e&'# = 1; = 20; = 12;

c475 = 'F'; a$!e&'# = 27; a435 = 'I';

To $uarantee copyin$ "eha)ior4 use the .dup property to ensure a uni9ue array that can "e resi5ed. These issues also apply to concatenatin$ arrays 7ith the G and GQ operators. Lesi5in$ a dyna%ic array is a relati)ely expensi)e operation. So4 7hile the follo7in$ %ethod of fillin$ an array?
i&#45 arraF; , i!e ?1@ A c = 'e#i&pu#?@; if ?Bc@ brea=; arraF$!e&'# = arraF$!e&'# + 1; arraF4arraF$!e&'# : 15 = c; C

7ill 7or64 it 7ill "e inefficient. ! %ore practical approach 7ould "e to %ini%i5e the nu%"er of resi5es?
i&#45 arraF; arraF$!e&'# = 100; // 'uess f"r ?i = 0; 1; i++@ A c = 'e#i&pu#?@; if ?Bc@ brea=; if ?i == arraF$!e&'# @ arraF$!e&'# = arraF$!e&'# * 2; arraF4i5 = c; C arraF$!e&'# = i;

ic6in$ a $ood initial $uess is an art4 "ut you usually can pic6 a )alue co)erin$ **Z of the cases. .or exa%ple4 7hen $atherin$ user input fro% the console @ it:s unli6ely to "e lon$er than #0.

Functions as .rray Properties


-f the first para%eter to a function is an array4 the function can "e called as if it 7ere a property of the array?

#*
i&#45 arraF; >"id f""?i&#45 a) i&# %@; f""?arraF) 3@; arraF$f""?3@; // 0ea&s # e sa0e # i&'

D Specification

.rray Bounds Chec!ing


-t is an error to index an array 7ith an index that is less than 0 or $reater than or e9ual to the array len$th. -f an index is out of "ounds4 an !rray3ounds'rror exception is raised if detected at runti%e4 and an error if detected at co%pile ti%e. ! pro$ra% %ay not rely on array "ounds chec6in$ happenin$4 for exa%ple4 the follo7in$ pro$ra% is incorrect?
#rF A f"r ?i = 0; ; i++@ A arraF4i5 = 7; C ?ArraFB"u&dsErr"r@ // #er0i&a#e !""p

C ca#c A C

The loop is correctly 7ritten?


f"r ?i = 0; i U arraF$!e&'# ; i++@ A arraF4i5 = 7; C

"mplementation (ote2 ,o%pilers should atte%pt to detect array "ounds errors at co%pile ti%e4 for exa%ple?
i&#435 f""; i&# % = f""435; // err"r) "u# "f b"u&ds

-nsertion of array "ounds chec6in$ code at runti%e should "e turned on and off 7ith a co%pile ti%e s7itch.

.rray "nitialization
%efault "nitialization

ointers are initiali5ed to null. Static array contents are initiali5ed to the default initiali5er for the array ele%ent type. Dyna%ic arrays are initiali5ed to ha)in$ 0 ele%ents. !ssociati)e arrays are initiali5ed to ha)in$ 0 ele%ents.

5oid "nitialization
Moid initiali5ation happens 7hen the Initiali&er for an array is 1oid. Dhat it %eans is that no initiali5ation is done4 i.e. the contents of the array 7ill "e undefined. This is %ost useful as an

D Specification efficiency opti%i5ation. Moid initiali5ations are an ad)anced techni9ue and should only "e used 7hen profilin$ indicates that it %atters.

*0

Static "nitialization of Static .rrays


Static initali5ations are supplied "y a list of array ele%ent )alues enclosed in H I. The )alues can "e optionally preceded "y an index and a ?. -f an index is not supplied4 it is set to the pre)ious index plus 14 or 0 if it is the first )alue.
i&#435 a = 4 1:2) 3 5; // a405 = 0) a415 = 2) a425 = 3

This is %ost handy 7hen the array indices are $i)en "y enu%s?
e&u0 C"!"r A red) b!ue) 'ree& C; i&# >a!ue4C"!"r$0a% + 15 = 4 C"!"r$b!ue:3) C"!"r$'ree&:2) C"!"r$red:7 5;

These arrays are static 7hen they appear in $lo"al scope. /ther7ise4 they need to "e %ar6ed 7ith const or static stora$e classes to %a6e the% static arrays.

Special .rray Types


Strings
! strin$ is an array of characters. Strin$ literals are >ust an easy 7ay to 7rite character arrays.
c ar45 s#r; c ar45 s#r1 = "abc";

charHI strin$s are in ;T.@# for%at. 7charHI strin$s are in ;T.@1( for%at. dcharHI strin$s are in ;T.@32 for%at. Strin$s can "e copied4 co%pared4 concatenated4 and appended?
s#r1 = s#r2; if ?s#r1 U s#r3@ $$$ fu&c?s#r3 2 s#r(@; s#r( 2= s#r1;

7ith the o")ious se%antics. !ny $enerated te%poraries $et cleaned up "y the $ar"a$e collector Aor "y usin$ allocaABB. 2ot only that4 this 7or6s 7ith any array not >ust a special Strin$ array. ! pointer to a char can "e $enerated?
c ar* p = .s#r435; c ar* p = s#r; // p"i&#er #" (# e!e0e&# // p"i&#er #" 1s# e!e0e&#

Since strin$s4 ho7e)er4 are not 0 ter%inated in D4 7hen transferrin$ a pointer to a strin$ to ,4 add a ter%inatin$ 0?
s#r 2= "\0";

or use the function s#d$s#ri&'$#"L#ri&'I. The type of a strin$ is deter%ined "y the se%antic phase of co%pilation. The type is one of? charHI4 7charHI4 dcharHI4 and is deter%ined "y i%plicit con)ersion rules. -f there are t7o e9ually applica"le i%plicit con)ersions4 the result is an error. To disa%"i$uate these cases4 a cast or a postfix of c4 $ or

*1 d can "e used?


cas#?,c ar 45@"abc" "abc", // # is is a& arraF "f ,c ar c arac#ers // s" is # is

D Specification

Strin$ literals that do not ha)e a postfix character and that ha)e not "een cast can "e i%plicitly con)erted "et7een charHI4 7charHI4 and dcharHI as necessary.
c ar c; ,c ar ,; dc ar d; c , , , , d = = = = = = 'b'; 'b'; 'bc'; "b"405; \r405; 'd'; // // // // // // c is assi'&ed # e c arac#er 'b' , is assi'&ed # e ,c ar c arac#er 'b' err"r : "&!F "&e ,c ar c arac#er a# a #i0e , is assi'&ed # e ,c ar c arac#er 'b' , is assi'&ed # e carria'e re#ur& ,c ar c arac#er d is assi'&ed # e c arac#er 'd'

CDs printf34 and Strings printf34 is a , function and is not part of D. printf34 7ill print , strin$s4 7hich are 0 ter%inated. There are t7o 7ays to use printf34 7ith D strin$s. The first is to add a ter%inatin$ 04 and cast the result to a charN?
s#r 2= "\0"; pri&#f?"# e s#ri&' is 'Ns'\&") ?c ar*@s#r@;

or?
i0p"r# s#d$s#ri&'; pri&#f?"# e s#ri&' is 'Ns'\&") s#d$s#ri&'$#"L#ri&'I?s#r@@;

Strin$ literals already ha)e a 0 appended to the%4 so can "e used directly?
pri&#f?"# e s#ri&' is 'Ns'\&") "s#ri&' !i#era!"@;

7hich is4 of course4 7hy the for%at strin$ to printf 7as 7or6in$. The second 7ay is to use the precision specifier. The 7ay D arrays are laid out4 the len$th co%es first4 so the follo7in$ 7or6s?
pri&#f?"# e s#ri&' is 'N$*s'\&") s#r@;

The "est 7ay is to use std.stdio.7ritefln4 7hich can handle D strin$s?


i0p"r# s#d$s#di"; ,ri#ef!&?"# e s#ri&' is 'Ns'") s#r@;

"mplicit Con1ersions
! pointer T* can "e i%plicitly con)erted to one of the follo7in$?

>"id* T45 !45

! static array T4dim5 can "e i%plicitly con)erted to one of the follo7in$?

D Specification

*2

>"id45 !45 >"id45

! dyna%ic array T45 can "e i%plicitly con)erted to one of the follo7in$?

Dhere ) is a "ase class of '.

*3

D Specification

Associative Arrays
!ssociati)e arrays ha)e an index that is not necessarily an inte$er4 and can "e sparsely populated. The index for an associati)e array is called the key4 and its type is called the 0ey'ype. !ssociati)e arrays are declared "y placin$ the 0ey'ype 7ithin the HI of an array declaration?
i&#4c ar455 b; b4" e!!""5 = 3; fu&c?b4" e!!""5@; // // // // // ass"cia#i>e arraF b "f i&#s # a# are i&de%ed bF a& arraF "f c arac#ers$ J e KeyType is c ar45 se# >a!ue ass"cia#ed ,i# =eF " e!!"" #" 3 pass 3 as para0e#er #" fu&c?@

articular 6eys in an associati)e array can "e re%o)ed 7ith the re%o)e function?
b$r9EF&9?" e!!""@;

The InExpression yields a pointer to the )alue if the 6ey is in the associati)e array4 or null if not?
i&#* p; p = ?" e!!"" A$ b@; if ?p B= $(CC@ $$$

0ey'ypes cannot "e functions or )oids. -f the 0ey'ype is a struct type4 a default %echanis% is used to co%pute the hash and co%parisons of it "ased on the "inary data 7ithin the struct )alue. ! custo% %echanis% can "e used "y pro)idin$ the follo7in$ functions as struct %e%"ers?
ui&# %FO!BI?@; i&# F?;E??KeyType* s@;

.or exa%ple?
i0p"r# s#d$s#ri&'; s#ruc# SFL#ri&' A c ar45 s#r; ui&# %FO!BI?@ A ui&# as ; f"reac ?c ar c; s@ as = ? as * 9@ + c; re#ur& as ; C i&# F?;E??SFL#ri&'* s@ A re#ur& s#d$s#ri&'$c0p?# is$s#r) s$s#r@; C

'sing Classes as the +eyType


,lasses can "e used as the 0ey'ype. .or this to 7or64 the class definition %ust o)erride the follo7in$ %e%"er functions of class ObMec#?

D Specification

*&

as 6# #"Yas ?@ i&# "pE+ua!s?ObMec#@ i&# "pC0p?ObMec#@

2ote that the para%eter to "pC0p and "pE+ua!s is of type ObMec#4 not the type of the class in 7hich it is defined. .or exa%ple?
c!ass 1"" A i&# a) b; as 6# #"Yas ?@ A re#ur& a + b; C i&# "pE+ua!s?ObMec# "@ A 1"" f = cas#?1""@ "; re#ur& f .. a == f""$a .. b == f""$b; C i&# "pC0p?ObMec# "@ A 1"" f = cas#?1""@ "; if ?Bf@ re#ur& :1; if ?a == f""$a@ re#ur& b : f""$b; re#ur& a : f""$a; C C

The i%ple%entation %ay use either "pE+ua!s or "pC0p or "oth. ,are should "e ta6en so that the results of "pE+ua!s and "pC0p are consistent 7ith each other 7hen the class o">ects are the sa%e or not.

'sing Structs or 'nions as the +eyType


Structs or unions can "e used as the 0ey'ype. .or this to 7or64 the struct or union definition %ust define the follo7in$ %e%"er functions?

as 6# #"Yas ?@ i&# "pE+ua!s?L@ or i&# "pE+ua!s?L*@ i&# "pC0p?L@ or i&# "pC0p?L*@

2ote that the para%eter to "pC0p and "pE+ua!s can "e either the struct or union type4 or a pointer to the struct or union type. .or exa%ple?
s#ruc# L A i&# a) b; as 6# #"Yas ?@ A re#ur& a + b; C i&# "pE+ua!s?L s@ A re#ur& a == s$a .. b == s$b; C

*5
i&# "pC0p?L* s@ A if ?a == s$a@ re#ur& b : s$b; re#ur& a : s$a; C

D Specification

The i%ple%entation %ay use either "pE+ua!s or "pC0p or "oth. ,are should "e ta6en so that the results of "pE+ua!s and "pC0p are consistent 7ith each other 7hen the struct/union o">ects are the sa%e or not.

Properties
roperties for associati)e arrays are? -sizeof Leturns the si5e of the reference to the associati)e arrayS it is typically #. -length -!eys Leturns nu%"er of )alues in the associati)e array. ;nli6e for dyna%ic arrays4 it is read@ only. Leturns dyna%ic array4 the ele%ents of 7hich are the 6eys in the associati)e array.

-1alues Leturns dyna%ic array4 the ele%ents of 7hich are the )alues in the associati)e array. Leor$ani5es the associati)e array in place so that loo6ups are %ore efficient. rehash is -rehash effecti)e 7hen4 for exa%ple4 the pro$ra% is done loadin$ up a sy%"ol ta"le and no7 needs fast loo6ups in it. Leturns a reference to the reor$ani5ed array.

.ssociati1e .rray Example2 $ord count


i0p"r# s#d$fi!e; i0p"r# s#d$s#di"; // D fi!e X/O

i&# 0ai& ?c ar4545 ar's@ A i&# ,"rd6#"#a!; i&# !i&e6#"#a!; i&# c ar6#"#a!; i&#4c ar455 dic#i"&arF; ,ri#ef!&?" !i&es ,"rds bF#es fi!e"@; f"r ?i&# i = 1; i U ar's$!e&'# ; ++i@ // pr"'ra0 ar'u0e&#s A c ar45 i&pu#; // i&pu# buffer i&# ,6c&#) !6c&#) c6c&#; // ,"rd) !i&e) c ar c"u&#s i&# i&,"rd; i&# ,s#ar#; // read fi!e i&#" i&pu#45 i&pu# = cas#?c ar45@s#d$fi!e$read?ar's4i5@; f"reac ?M) c ar c; i&pu#@ A if ?c == '\&'@ ++!6c&#; if ?c >= '0' .. c U= '9'@ A

D Specification
C e!se if ?c >= 'a' .. c U= 'I' TT c >= 'A' .. c U= 'Z'@ A if ?Bi&,"rd@ A ,s#ar# = M; i&,"rd = 1; ++,6c&#; C C e!se if ?i&,"rd@ A c ar45 ,"rd = i&pu#4,s#ar# $$ M5; dic#i"&arF4,"rd5++; // i&cre0e&# c"u&# f"r ,"rd i&,"rd = 0; C ++c6c&#;

*(

C if ?i&,"rd@ A c ar45 ,"rd = i&pu#4,s#ar# $$ i&pu#$!e&'# 5; dic#i"&arF4,"rd5++; C ,ri#ef!&?"N9dN9dN9d Ns") !6c&#) ,6c&#) c6c&#) ar's4i5@; !i&e6#"#a! += !6c&#; ,"rd6#"#a! += ,6c&#; c ar6#"#a! += c6c&#;

if ?ar's$!e&'# > 2@ A ,ri#ef?":::::::::::::::::::::::::::::::::::::\&N9!dN9!dN9!d #"#a!") !i&e6#"#a!) ,"rd6#"#a!) c ar6#"#a!@; C ,ri#ef!&?":::::::::::::::::::::::::::::::::::::"@; f"reac ?,"rd; dic#i"&arF$=eFs$s"r#@ A ,ri#ef!&?"N3d Ns") dic#i"&arF4,"rd5) ,"rd@; C re#ur& 0;

*7

D Specification

Structs & Unions


Dhereas classes are reference types4 structs are )alue types. !ny , struct can "e exactly represented as a D struct. -n ,88 parlance4 a D struct is a /D A lain /ld DataB type4 7ith a tri)ial constructors and destructors. Structs and unions are %eant as si%ple a$$re$ations of data4 or as a 7ay to paint a data structure o)er hard7are or an external type. 'xternal types can "e defined "y the operatin$ syste% ! -4 or "y a file for%at. /">ect oriented features are pro)ided 7ith the class data type. ! struct is defined to not ha)e an identityS that is4 the i%ple%entation is free to %a6e "it copies of the struct as con)enient. Feature )alue type reference type data %e%"ers hidden %e%"ers static %e%"ers default %e%"er initiali5ers "it fields non@)irtual %e%"er functions )irtual %e%"er functions constructors destructors L!-operator o)erloadin$ inheritance in)ariants unit tests synchroni5a"le para%eteri5a"le ali$n%ent control %e%"er protection default pu"lic ta$ na%e space anony%ous
#ggregate%eclaration: Tag { %ecl%efs }

Struct4 ,lass ,o%parison Ta"le struct class C struct C66 struct C66 class T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T

D Specification
Tag Identifier Str&ctBody Tag Identifier ; Tag: B%r(*% ($AF$

*#

Str&ctBody: { } { Str&ctBody%eclarations } Str&ctBody%eclarations: Str&ctBody%eclaration Str&ctBody%eclaration Str&ctBody%eclarations Str&ctBody%eclaration: %eclaration StaticConstr&ctor Static%estr&ctor In"ariant !nitTest Str&ct#llocator Str&ct%eallocator Str&ct#llocator: Class#llocator Str&ct%eallocator: Class%eallocator

They 7or6 li6e they do in ,4 7ith the follo7in$ exceptions?


no "it fields ali$n%ent can "e explicitly specified no separate ta$ na%e space @ ta$ na%es $o into the current scope declarations li6e?
s#ruc# ABC %;

are not allo7ed4 replace 7ith?


ABC %;

anony%ous structs/unions are allo7ed as %e%"ers of other structs/unions Default initiali5ers for %e%"ers can "e supplied. Me%"er functions and static %e%"ers are allo7ed.

Static "nitialization of Structs


Static struct %e%"ers are "y default initiali5ed to 7hate)er the default initiali5er for the %e%"er is4 and if none supplied4 to the default initiali5er for the %e%"er:s type. -f a static initiali5er is supplied4 the %e%"ers are initiali5ed "y the %e%"er na%e4 colon4 expression syntax. The %e%"ers %ay "e initiali5ed in any order. Me%"ers not specified in the initiali5er list are default initiali5ed.
s#ruc# W A i&# a; i&# b; i&# c; i&# d = 8;C s#a#ic W % = A a:1) b:2C; // c is se# #" 0) d #" 8 s#a#ic W I = A c:() b:7) a:2 ) d:7C; // I$a = 2) I$b = 7) I$c = () I$d = 7

**

D Specification

,@style initiali5ation4 "ased on the order of the %e%"ers in the struct declaration4 is also supported?
s#a#ic W + = A 1) 2 C; // +$a = 1) +$b = 2) +$c = 0) +$d = 8

Static "nitialization of 'nions


;nions are initiali5ed explicitly.
u&i"& - A i&# a; d"ub!e b; C s#a#ic - u = A b : 7$0 C; // u$b = 7$0

/ther %e%"ers of the union that o)erlay the initiali5er4 "ut occupy %ore stora$e4 ha)e the extra stora$e initiali5ed to 5ero.

%ynamic "nitialization of Structs


Structs can "e dyna%ically initiali5ed fro% another )alue of the sa%e type?
s#ruc# L A i&# a; C L #; // defau!# i&i#ia!iIed #$a = 3; L s = #; // s$a is se# #" 3

-f "pCa!! is o)erridden for the struct4 and the struct is initiali5ed 7ith a )alue that is of a different type4 then the "pCa!! operator is called?
s#ruc# L A i&# a; s#a#ic L F?;!CC?i&# >@ A L s; s$a = >; re#ur& s; C s#a#ic L F?;!CC?L >@ A L s; s$a = >$a + 1; re#ur& s; C // se#s s$a #" 3 // se#s #$a #" 3) L$F?;!CC?s@ is &"# ca!!ed

L s = 3; L # = s;

Struct Properties
$siIe"f $a!i'&"f $#up!e"f LiIe i& bF#es "f s#ruc# LiIe b"u&darF s#ruc# &eeds #" be a!i'&ed "& [e#s #Fpe #up!e "f fie!ds

Struct Field Properties


$"ffse#"f Offse# i& bF#es "f fie!d fr"0 be'i&&i&' "f s#ruc#

D Specification

100

Classes
The o">ect@oriented features of D all co%e fro% classes. The class hierarchy has as its root the class /">ect. /">ect defines a %ini%u% le)el of functionality that each deri)ed class has4 and a default i%ple%entation for that functionality. ,lasses are pro$ra%%er defined types. Support for classes are 7hat %a6e D an o">ect oriented lan$ua$e4 $i)in$ it encapsulation4 inheritance4 and poly%orphis%. D classes support the sin$le inheritance paradi$%4 extended "y addin$ support for interfaces. ,lass o">ects are instantiated "y reference only. ! class can "e exported4 7hich %eans its na%e and all its non@pri)ate %e%"ers are exposed externally to the DLL or 'T'. ! class declaration is defined?
Class%eclaration: *C!BB Identifier BaseClassList"p# ClassBody BaseClassList: : S&perClass : S&perClass InterfaceClasses : InterfaceClass S&perClass: Identifier ,rotection Identifier InterfaceClasses: InterfaceClass InterfaceClass InterfaceClasses InterfaceClass: Identifier ,rotection Identifier ,rotection: ?rA&!%9 ?!*H!D9 ?("CA* 9'?Fr% ClassBody: { } { ClassBody%eclarations } ClassBody%eclarations: ClassBody%eclaration ClassBody%eclaration ClassBody%eclarations ClassBody%eclaration: %eclaration Constr&ctor %estr&ctor StaticConstr&ctor Static%estr&ctor In"ariant !nitTest Class#llocator

101
Class%eallocator

D Specification

,lasses consist of? a super class interfaces dyna%ic fields static fields types functions static functions dyna%ic functions constructors destructors static constructors static destructors in)ariants unit tests allocators deallocators ! class is defined?
c!ass 1"" A $$$ 0e0bers $$$ C

2ote that there is no trailin$ S after the closin$ Y of the class definition. -t is also not possi"le to declare a )aria"le )ar li6e?
c!ass 1"" A C >ar;

-nstead?
c!ass 1"" A C 1"" >ar;

Fields
,lass %e%"ers are al7ays accessed 7ith the . operator. There are no ?? or @V operators as in ,88. The D co%piler is free to rearran$e the order of fields in a class to opti%ally pac6 the% in an i%ple%entation@defined %anner. ,onsider the fields %uch li6e the local )aria"les in a function @ the co%piler assi$ns so%e to re$isters and shuffles others around all to $et the opti%al stac6 fra%e layout. This frees the code desi$ner to or$ani5e the fields in a %anner that %a6es the code %ore reada"le rather than "ein$ forced to or$ani5e it accordin$ to %achine opti%i5ation rules. 'xplicit control of field layout is pro)ided "y struct/union types4 not classes.

Field Properties
The -offsetof property $i)es the offset in "ytes of the field fro% the "e$innin$ of the class instantiation. -offsetof can only "e applied to fields 9ualified 7ith the type of the class4 not expressions 7hich produce the type of the field itself?

D Specification
c!ass 1"" A i&# %; C $$$ >"id #es#?1"" f""@ A siIe6# "; " = 1""$%.F##B9%F#; " = f""$%.F##B9%F#; C // Fie!ds 9 // err"r) $"ffse#"f a& i&# #Fpe

102

Class Properties
The -tupleof property returns an Expression'uple of all the fields in the class4 excludin$ the hidden fields and the fields in the "ase class.
c!ass 1"" A i&# %; !"&' F; C >"id #es#?1"" f""@ A f""$#up!e"f405 = 1; f""$#up!e"f415 = 2; f"reac ?%; f""$#up!e"f@ ,ri#ef?%@; C

// se# f""$% #" 1 // se# f""$F #" 2 // pri&#s 12

Super Class
!ll classes inherit fro% a super class. -f one is not specified4 it inherits fro% /">ect. /">ect for%s the root of the D class inheritance hierarchy.

Constructors
Constr&ctor: %IAB ,arameters F&nctionBody

Me%"ers are al7ays initiali5ed to the default initiali5er for their type4 7hich is usually 0 for inte$er types and 2!2 for floatin$ point types. This eli%inates an entire class of o"scure pro"le%s that co%e fro% ne$lectin$ to initiali5e a %e%"er in one of the constructors. -n the class definition4 there can "e a static initiali5er to "e used instead of the default?
c!ass Abc A i&# a; // defau!# i&i#ia!iIer f"r a is 0 !"&' b = 8; // defau!# i&i#ia!iIer f"r b is 8 f!"a# f; // defau!# i&i#ia!iIer f"r f is HAH C

This static initiali5ation is done "efore any constructors are called. ,onstructors are defined 7ith a function na%e of this and ha)in$ no return )alue?
c!ass 1"" A %IAB?i&# %@ A $$$ // dec!are c"&s#ruc#"r f"r 1""

103
C %IAB?@ A $$$ C

D Specification

3ase class construction is done "y callin$ the "ase class constructor "y the na%e super?
c!ass A A # is?i&# F@ A C C c!ass B : A A i&# M; # is?@ A $$$ B(?9r?3@; $$$ C C

// ca!! base c"&s#ruc#"r A$# is?3@

,onstructors can also call other constructors for the sa%e class in order to share co%%on initiali5ations?
c!ass C A i&# M; # is?@ A $$$ C # is?i&# i@ A %IAB?@; M = i; C C

-f no call to constructors )ia this or super appear in a constructor4 and the "ase class has a constructor4 a call to superAB is inserted at the "e$innin$ of the constructor. -f there is no constructor for a class4 "ut there is a constructor for the "ase class4 a default constructor of the for%?
# is?@ A C

is i%plicitly $enerated. ,lass o">ect construction is )ery flexi"le4 "ut so%e restrictions apply? 1. -t is ille$al for constructors to %utually call each other?
# is?@ A # is?1@; C # is?i&# i@ A # is?@; C // i!!e'a!) cFc!ic c"&s#ruc#"r ca!!s

2. -f any constructor call appears inside a constructor4 any path throu$h the constructor %ust %a6e exactly one constructor call?
# is?@ A a TT super?@; C // i!!e'a! // "= # is?@ A ?a@ D # is?1@ : super?@; C

D Specification
# is?@ A f"r ?$$$@ A super?@; C C

10&

// i!!e'a!) i&side !""p

3. -t is ille$al to refer to this i%plicitly or explicitly prior to %a6in$ a constructor call. &. ,onstructor calls cannot appear after la"els Ain order to %a6e it easy to chec6 for the pre)ious conditions in the presence of $oto:sB. -nstances of class o">ects are created 7ith !ewExpressions?
A a = &e, A?3@;

The follo7in$ steps happen? 1. Stora$e is allocated for the o">ect. -f this fails4 rather than return null4 an OutOfMemoryException is thro7n. Thus4 tedious chec6s for null references are unnecessary. 2. The ra7 data is statically initiali5ed usin$ the )alues pro)ided in the class definition. The pointer to the )t"lHI Athe array of pointers to )irtual functionsB is assi$ned. This ensures that constructors are passed fully for%ed o">ects for 7hich )irtual functions can "e called. This operation is e9ui)alent to doin$ a %e%ory copy of a static )ersion of the o">ect onto the ne7ly allocated one4 althou$h %ore ad)anced co%pilers %ay "e a"le to opti%i5e %uch of this a7ay. 3. -f there is a constructor defined for the class4 the constructor %atchin$ the ar$u%ent list is called. &. -f class in)ariant chec6in$ is turned on4 the class in)ariant is called at the end of the constructor.

%estructors
%estr&ctor: ~%IAB() F&nctionBody

The $ar"a$e collector calls the destructor function 7hen the o">ect is deleted. The syntax is?
c!ass 1"" A 2# is?@ A C C // des#ruc#"r f"r 1""

There can "e only one destructor per class4 the destructor does not ha)e any para%eters4 and has no attri"utes. -t is al7ays )irtual. The destructor is expected to release any resources held "y the o">ect. The pro$ra% can explicitly infor% the $ar"a$e collector that an o">ect is no lon$er referred to A7ith the delete expressionB4 and then the $ar"a$e collector calls the destructor i%%ediately4 and adds the o">ect:s %e%ory to the free stora$e. The destructor is $uaranteed to ne)er "e called t7ice. The destructor for the super class auto%atically $ets called 7hen the destructor ends. There is no

105 7ay to call the super destructor explicitly.

D Specification

Dhen the $ar"a$e collector calls a destructor for an o">ect of a class that has %e%"ers that are references to $ar"a$e collected o">ects4 those references are no lon$er )alid. This %eans that destructors cannot reference su" o">ects. This rule does not apply to auto o">ects or o">ects deleted 7ith the eleteExpression. The $ar"a$e collector is not $uaranteed to run the destructor for all unreferenced o">ects. .urther%ore4 the order in 7hich the $ar"a$e collector calls destructors for unreference o">ects is not specified. /">ects referenced fro% the data se$%ent ne)er $et collected "y the $c.

Static Constructors
StaticConstr&ctor: B%!%A*L%IAB() F&nctionBody

! static constructor is defined as a function that perfor%s initiali5ations "efore the 0ai&?@ function $ets control. Static constructors are used to initiali5e static class %e%"ers 7ith )alues that cannot "e co%puted at co%pile ti%e. Static constructors in other lan$ua$es are "uilt i%plicitly "y usin$ %e%"er initiali5ers that can:t "e co%puted at co%pile ti%e. The trou"le 7ith this ste%s fro% not ha)in$ $ood control o)er exactly 7hen the code is executed4 for exa%ple?
c!ass 1"" A s#a#ic i&# a = b + 1; s#a#ic i&# b = a * 2; C

Dhat )alues do a and " end up 7ith4 7hat order are the initiali5ations executed in4 7hat are the )alues of a and " "efore the initiali5ations are run4 is this a co%pile error4 or is this a runti%e errorR !dditional confusion co%es fro% it not "ein$ o")ious if an initiali5er is static or dyna%ic. D %a6es this si%ple. !ll %e%"er initiali5ations %ust "e deter%ina"le "y the co%piler at co%pile ti%e4 hence there is no order@of@e)aluation dependency for %e%"er initiali5ations4 and it is not possi"le to read a )alue that has not "een initiali5ed. Dyna%ic initiali5ation is perfor%ed "y a static constructor4 defined 7ith a special syntax s#a#ic # is?@.
c!ass 1"" A s#a#ic i&# a; s#a#ic i&# b = 1; s#a#ic i&# c = b + a; B%!%A*L%IAB?@ A a = b + 1; b = a * 2; C // defau!# i&i#ia!iIed #" 0 // err"r) &"# a c"&s#a&# i&i#ia!iIer // s#a#ic c"&s#ruc#"r // a is se# #" 2 // b is se# #" (

s#a#ic # is?@ is called "y the startup code "efore 0ai&?@ is called. -f it returns nor%ally Adoes not thro7 an exceptionB4 the static destructor is added to the list of functions to "e called on pro$ra% ter%ination. Static constructors ha)e e%pty para%eter lists.

D Specification

10(

Static constructors 7ithin a %odule are executed in the lexical order in 7hich they appear. !ll the static constructors for %odules that are directly or indirectly i%ported are executed "efore the static constructors for the i%porter. The static in the static constructor declaration is not an attri"ute4 it %ust appear i%%ediately "efore the this?
c!ass 1"" A s#a#ic # is?@ A $$$ C // a s#a#ic c"&s#ruc#"r s#a#ic pri>a#e # is?@ A $$$ C // &"# a s#a#ic c"&s#ruc#"r s#a#ic A # is?@ A $$$ C // &"# a s#a#ic c"&s#ruc#"r C s#a#ic: # is?@ A $$$ C // &"# a s#a#ic c"&s#ruc#"r C

Static %estructor
Static%estr&ctor: B%!%A*L~%IAB() F&nctionBody

! static destructor is defined as a special static function 7ith the syntax s#a#ic 2# is?@.
c!ass 1"" A s#a#ic 2# is?@ A C C // s#a#ic des#ruc#"r

! static destructor $ets called on pro$ra% ter%ination4 "ut only if the static constructor co%pleted successfully. Static destructors ha)e e%pty para%eter lists. Static destructors $et called in the re)erse order that the static constructors 7ere called in. The static in the static destructor declaration is not an attri"ute4 it %ust appear i%%ediately "efore the Ethis?
c!ass 1"" A s#a#ic 2# is?@ A $$$ C // a s#a#ic des#ruc#"r s#a#ic pri>a#e 2# is?@ A $$$ C // &"# a s#a#ic des#ruc#"r s#a#ic A 2# is?@ A $$$ C // &"# a s#a#ic des#ruc#"r C s#a#ic: 2# is?@ A $$$ C // &"# a s#a#ic des#ruc#"r C

Class "n1ariants
ClassIn"ariant: A$&!rA!$% BlockStatement

,lass in)ariants are used to specify characteristics of a class that al7ays %ust "e true Aexcept 7hile

107

D Specification

executin$ a %e%"er functionB. .or exa%ple4 a class representin$ a date %i$ht ha)e an in)ariant that the day %ust "e 1..31 and the hour %ust "e 0..23?
c!ass Da#e A i&# daF; i&# "ur; A$&!rA!$% A asser#?1 U= daF .. daF U= 31@; asser#?0 U= "ur .. "ur U 2(@; C

The class in)ariant is a contract sayin$ that the asserts %ust hold true. The in)ariant is chec6ed 7hen a class constructor co%pletes4 at the start of the class destructor4 "efore a pu"lic or exported %e%"er is run4 and after a pu"lic or exported function finishes. The code in the in)ariant %ay not call any pu"lic non@static %e%"ers of the class4 either directly or indirectly. Doin$ so 7ill result in a stac6 o)erflo74 as the in)ariant 7ill 7ind up "ein$ called in an infinitely recursi)e %anner.
c!ass 1"" A pub!ic >"id f?@ A C pri>a#e >"id '?@ A C A$&!rA!$% A f?@; // err"r) ca&&"# ca!! pub!ic 0e0ber fu&c#i"& fr"0 i&>aria&# '?@; // "=) '?@ is &"# pub!ic C

The in)ariant can "e chec6ed 7hen a class o">ect is the ar$u%ent to an asser#?@ expression4 as?
Da#e 0Fda#e; $$$ asser#?0Fda#e@; // c ec= # a# c!ass Da#e i&>aria&# "!ds

-n)ariants contain assert expressions4 and so 7hen they fail4 they thro7 a Asser#Err"rs. ,lass in)ariants are inherited4 that is4 any class in)ariant is i%plicitly anded 7ith the in)ariants of its "ase classes. There can "e only one ClassIn"ariant per class. Dhen co%pilin$ for release4 the in)ariant code is not $enerated4 and the co%piled pro$ra% runs at %axi%u% speed.

'nit Tests
!nitTest: ($A%%9B% F&nctionBody

;nit tests are a series of test cases applied to a class to deter%ine if it is 7or6in$ properly. -deally4 unit tests should "e run e)ery ti%e a pro$ra% is co%piled. The "est 7ay to %a6e sure that unit tests do $et run4 and that they are %aintained alon$ 7ith the class code is to put the test code ri$ht in 7ith

D Specification the class i%ple%entation code. ,lasses can ha)e a special %e%"er function called?
u&i##es# A $$$#es# c"de$$$ C

10#

! co%piler s7itch4 such as )unittest for dmd4 7ill cause the unittest test code to "e co%piled and incorporated into the resultin$ executa"le. The unittest code $ets run after static initiali5ation is run and "efore the 0ai&?@ function is called. .or exa%ple4 $i)en a class Su% that is used to add t7o )alues?
c!ass Lu0 A i&# add?i&# %) i&# F@ A re#ur& % + F; C u&i##es# A Lu0 su0 = &e, Lu0; asser#?su0$add?3)(@ == 8@; asser#?su0$add?:2)0@ == :2@; C C

Class .llocators
Class#llocator: $9+ ,arameters F&nctionBody

! class %e%"er function of the for%?


&e,?ui&# siIe@ A $$$ C

is called a class allocator. The class allocator can ha)e any nu%"er of para%eters4 pro)ided the first one is of type uint. !ny nu%"er can "e defined for a class4 the correct one is deter%ined "y the usual function o)erloadin$ rules. Dhen a ne7 expression?
&e, 1"";

is executed4 and .oo is a class that has an allocator4 the allocator is called 7ith the first ar$u%ent set to the si5e in "ytes of the %e%ory to "e allocated for the instance. The allocator %ust allocate the %e%ory and return it as a >"id*. -f the allocator fails4 it %ust not return a null4 "ut %ust thro7 an exception. -f there is %ore than one para%eter to the allocator4 the additional ar$u%ents are specified 7ithin parentheses after the ne$ in the !ewExpression?
c!ass 1"" A # is?c ar45 a@ A $$$ C &e,?ui&# siIe) i&# %) i&# F@ A $$$ C

10*
C $$$ &e,?1)2@ 1""?a@; // ca!!s &e,?1""$siIe"f)1)2@

D Specification

Deri)ed classes inherit any allocator fro% their "ase class4 if one is not specified. The class allocator is not called if the instance is created on the stac6. See also 'xplicit ,lass -nstance !llocation.

Class %eallocators
Class%eallocator: ,9C9%9 ,arameters F&nctionBody

! class %e%"er function of the for%?


de!e#e?>"id *p@ A $$$ C

is called a class deallocator. The deallocator %ust ha)e exactly one para%eter of type >"id*. /nly one can "e specified for a class. Dhen a delete expression?
de!e#e f;

is executed4 and f is a reference to a class instance that has a deallocator4 the deallocator is called 7ith a pointer to the class instance after the destructor Aif anyB for the class is called. -t is the responsi"ility of the deallocator to free the %e%ory. Deri)ed classes inherit any deallocator fro% their "ase class4 if one is not specified. The class allocator is not called if the instance is created on the stac6. See also 'xplicit ,lass -nstance !llocation.

Scope Classes
! scope class is a class 7ith the scope attri"ute4 as in?
sc"pe c!ass 1"" A $$$ C

The scope characteristic is inherited4 so if any classes deri)ed fro% a scope class are also scope. !n scope class reference can only appear as a function local )aria"le. -t %ust "e declared as "ein$ scope?
sc"pe c!ass 1"" A $$$ C >"id fu&c?@ A 1"" f; // err"r) refere&ce #" sc"pe c!ass 0us# be sc"pe sc"pe 1"" ' = &e, 1""?@; // c"rrec# C

Dhen an scope class reference $oes out of scope4 the destructor Aif anyB for it is auto%atically

D Specification called. This holds true e)en if the scope 7as exited )ia a thro7n exception.

110

(ested Classes
! nested class is a class that is declared inside the scope of a function or another class. ! nested class has access to the )aria"les and other sy%"ols of the classes and functions it is nested inside?
c!ass Ou#er A i&# 0; c!ass X&&er A i&# f""?@ A re#ur& 0; C C C >"id fu&c?@ A i&# 0; c!ass X&&er A i&# f""?@ A re#ur& 0; C C C

// O= #" access 0e0ber "f Ou#er

// O= #" access !"ca! >ariab!e 0 "f fu&c?@

-f a nested class has the static attri"ute4 then it can not access )aria"les of the enclosin$ scope that are local to the stac6 or need a this?
c!ass Ou#er A i&# 0; s#a#ic i&# &; s#a#ic c!ass X&&er A i&# f""?@ A re#ur& 0; re#ur& &; C C

// Err"r) X&&er is s#a#ic a&d 0 &eeds a %IAB // O=) & is s#a#ic

>"id fu&c?@ A i&# 0; s#a#ic i&# &; s#a#ic c!ass X&&er A i&# f""?@ A re#ur& 0; re#ur& &;

// Err"r) X&&er is s#a#ic a&d 0 is !"ca! #" # e s#ac= // O=) & is s#a#ic

111
C C C

D Specification

2on@static nested classes 7or6 "y containin$ an extra hidden %e%"er Acalled the context pointerB that is the fra%e pointer of the enclosin$ function if it is nested inside a function4 or the this of the enclosin$ class:s instance if it is nested inside a class. Dhen a non@static nested class is instantiated4 the context pointer is assi$ned "efore the class:s constructor is called4 therefore the constructor has full access to the enclosin$ )aria"les. ! non@ static nested class can only "e instantiated 7hen the necessary context pointer infor%ation is a)aila"le?
c!ass Ou#er A c!ass X&&er A C s#a#ic c!ass LX&&er A C C >"id fu&c?@ A c!ass Hes#ed A C Ou#er " = &e, Ou#er; // O= Ou#er$X&&er "i = &e, Ou#er$X&&er; // Err"r) &" '# is' f"r Ou#er Ou#er$LX&&er "s = &e, Ou#er$LX&&er; // O= C Hes#ed & = &e, Hes#ed; // O=

Dhile a non@static nested class can access the stac6 )aria"les of its enclosin$ function4 that access "eco%es in)alid once the enclosin$ function exits?
c!ass Base A i&# f""?@ A re#ur& 1; C C Base fu&c?@ A i&# 0 = 3; c!ass Hes#ed : Base A i&# f""?@ A re#ur& 0; C C Base b = &e, Hes#ed; asser#?b$f""?@ == 3@; re#ur& b; C i&# #es#?@ A Base b = fu&c?@; re#ur& b$f""?@; C // O=) fu&c?@ is s#i!! ac#i>e

// Err"r) fu&c?@$0 is u&defi&ed

-f this 6ind of functionality is needed4 the 7ay to %a6e it 7or6 is to %a6e copies of the needed

D Specification )aria"les 7ithin the nested class:s constructor?


c!ass Base A i&# f""?@ A re#ur& 1; C C Base fu&c?@ A i&# 0 = 3; c!ass Hes#ed : Base A i&# 06; # is?@ A 06 = 0; C i&# f""?@ A re#ur& 06; C C Base b = &e, Hes#ed; asser#?b$f""?@ == 3@; re#ur& b; C i&# #es#?@ A Base b = fu&c?@; re#ur& b$f""?@; C // O=) fu&c?@ is s#i!! ac#i>e

112

// O=) usi&' cac ed c"pF "f fu&c?@$0

! this can "e supplied to the creation of an inner class instance "y prefixin$ it to the !ewExpression?
c!ass Ou#er A i&# a; c!ass X&&er A i&# f""?@ A re#ur& a; C C C i&# bar?@ A Ou#er " = &e, Ou#er; "$a = 3; Ou#er$X&&er "i = F$&e, X&&er; re#ur& "i$f""?@; // re#ur&s 3 C

0ere o supplies the this to the outer class instance of Outer. The property -outer used in a nested class $i)es the this pointer to its enclosin$ class. -f the enclosin$ context is not a class4 the -outer 7ill $i)e the pointer to it as a 1oid= type.
c!ass Ou#er A c!ass X&&er A

113
Ou#er f""?@ A re#ur& # is$F(%9r; C

D Specification

>"id bar?@ A X&&er i = &e, X&&er; asser#?# is == i$f""?@@; C C >"id #es#?@ A Ou#er " = &e, Ou#er; "$bar?@; C

.nonymous (ested Classes


!n anony%ous nested class is "oth defined and instantiated 7ith a !ew(nonClassExpression?
Ne #nonClassE+pression: $9+L(#rg&mentList)"p# *C!BBL(#rg&mentList)"p# S&perClass"p# InterfaceClasses"p# ClassBody

7hich is e9ui)alent to?


c!ass Identifier : S&perClass InterfaceClasses ClassBody &e, ?#rg&mentList@ Identifier ?#rg&mentList@;

7here Identifier is the na%e $enerated for the anony%ous nested class.

D Specification

11&

nter!aces
Interface%eclaration: A$%9r#!*9 Identifier InterfaceBody A$%9r#!*9 Identifier : S&perInterfaces InterfaceBody S&perInterfaces Identifier Identifier , S&perInterfaces InterfaceBody: { %ecl%efs }

-nterfaces descri"e a list of functions that a class that inherits fro% the interface %ust i%ple%ent. ! class that i%ple%ents an interface can "e con)erted to a reference to that interface. -nterfaces correspond to the interface exposed "y operatin$ syste% o">ects4 li6e ,/M//L'/!cti)eT for Din32. -nterfaces cannot deri)e fro% classesS only fro% other interfaces. ,lasses cannot deri)e fro% an interface %ultiple ti%es.
i&#erface D A >"id f""?@; C c!ass A : D) D A C // err"r) dup!ica#e i&#erface

!n instance of an interface cannot "e created.


i&#erface D A >"id f""?@; C $$$ D d = &e, D?@; // err"r) ca&&"# crea#e i&s#a&ce "f i&#erface

-nterface %e%"er functions do not ha)e i%ple%entations.


i&#erface D A >"id bar?@ A C C // err"r) i0p!e0e&#a#i"& &"# a!!",ed

!ll interface functions %ust "e defined in a class that inherits fro% that interface?
i&#erface D A >"id f""?@; C c!ass A : D A >"id f""?@ A C C

// "=) pr">ides i0p!e0e&#a#i"&

115
c!ass B : D A i&# f""?@ A C C

D Specification

// err"r) &" >"id f""?@ i0p!e0e&#a#i"&

-nterfaces can "e inherited and functions o)erridden?


i&#erface D A i&# f""?@; C c!ass A : D A i&# f""?@ A re#ur& 1; C C c!ass B : A A i&# f""?@ A re#ur& 2; C C $$$ B b = &e, B?@; b$f""?@; D d = cas#?D@ b; d$f""?@; // re#ur&s 2 // "= si&ce B i& eri#s A's D i0p!e0e&#a#i"& // re#ur&s 2;

-nterfaces can "e rei%ple%ented in deri)ed classes?


i&#erface D A i&# f""?@; C c!ass A : D A i&# f""?@ A re#ur& 1; C C c!ass B : A) D A i&# f""?@ A re#ur& 2; C C $$$ B b = &e, B?@; b$f""?@; D d = cas#?D@ b; d$f""?@; A a = cas#?A@ b; D d2 = cas#?D@ a; d2$f""?@; // re#ur&s 2 // re#ur&s 2 // re#ur&s 2) e>e& # "u' i# is A's D) &"# B's D

! rei%ple%ented interface %ust i%ple%ent all the interface functions4 it does not inherit the% fro% a super class?
i&#erface D

D Specification
A C i&# f""?@;

11(

c!ass A : D A i&# f""?@ A re#ur& 1; C C c!ass B : A) D A C

// err"r) &" f""?@ f"r i&#erface D

COM "nterfaces
! )ariant on interfaces is the ,/M interface. ! ,/M interface is desi$ned to %ap directly onto a Dindo7s ,/M o">ect. !ny ,/M o">ect can "e represented "y a ,/M interface4 and any D o">ect 7ith a ,/M interface can "e used "y external ,/M clients. ! ,/M interface is defined as one that deri)es fro% the interface s#d$c$,i&d",s$c"0$X-&=&",&. ! ,/M interface differs fro% a re$ular D interface in that?

-t deri)es fro% the interface s#d$c$,i&d",s$c"0$X-&=&",&. -t cannot "e the ar$u%ent of a eleteExpression. Leferences cannot "e upcast to the enclosin$ class o">ect4 nor can they "e do7ncast to a deri)ed interface. To acco%plish this4 an appropriate GuerFX&#erface?@ 7ould ha)e to "e i%ple%ented for that interface in standard ,/M fashion.

117

D Specification

Enums " Enumerated Types


En&m%eclaration: 9$(E Identifier En&mBody 9$(E En&mBody 9$(E Identifier : En&mBaseType En&mBody 9$(E : En&mBaseType En&mBody En&mBaseType: Type En&mBody: ; { En&m-em'ers } En&m-em'ers: En&m-em'er En&m-em'er , En&m-em'er , En&m-em'ers En&m-em'er: Identifier Identifier = #ssignE+pression

'nu%s are used to define a $roup of related inte$ral constants. -f the enu% Identifier is present4 the EnumMem#ers are declared in the scope of the enu% Identifier. The enu% Identifier declares a ne7 type. -f the enu% Identifier is not present4 then the enu% is an anonymous enum4 and the EnumMem#ers are declared in the scope the Enum eclaration appears in. 2o ne7 type is createdS the EnumMem#ers ha)e the type of the Enum+ase'ype. The Enum+ase'ype is the underlyin$ type of the enu%. -t %ust "e an inte$ral type. -f o%itted4 it defaults to int.
e&u0 A A) B) C C // a&"&F0"us e&u0

Defines the constants !Q04 3Q14 ,Q2 in a %anner e9ui)alent to?


c"&s# i&# A = 0; c"&s# i&# B = 1; c"&s# i&# C = 2;

Dhereas?
e&u0 W A A) B) C C // &a0ed e&u0

Define a ne7 type T 7hich has )alues T.!Q04 T.3Q14 T.,Q2 2a%ed enu% %e%"ers can "e i%plicitly cast to inte$ral types4 "ut inte$ral types cannot "e i%plicitly cast to an enu% type. 'nu%s %ust ha)e at least one %e%"er. -f an Expression is supplied for an enu% %e%"er4 the )alue of the %e%"er is set to the result of the Expression. The Expression %ust "e resol)a"le at co%pile ti%e. Su"se9uent enu% %e%"ers 7ith no Expression are set to the )alue of the pre)ious %e%"er plus one?
e&u0 A A) B = 7+8) C) D = 9) E C

D Specification Sets !Q04 3Q124 ,Q134 DQ#4 and 'Q*.

11#

Enum Properties
$i&i# $0i& $0a% $siIe"f 1"r e%a0p!e: W$0i& W$0a% W$siIe"f is W$A is W$C is sa0e as i&#$siIe"f 1irs# e&u0 0e0ber >a!ue L0a!!es# >a!ue "f e&u0 ;ar'es# >a!ue "f e&u0 LiIe "f s#"ra'e f"r a& e&u0era#ed >a!ue

"nitialization of Enums
-n the a"sence of an explicit initiali5er4 an enu% )aria"le is initiali5ed to the first enu% )alue.
e&u0 W A A=3) B) C C W %; // % is i&i#ia!iIed #" 3

11*

D Specification

#unctions
F&nctionBody: BlockStatement BodyStatement InStatement BodyStatement O&tStatement BodyStatement InStatement O&tStatement BodyStatement O&tStatement InStatement BodyStatement InStatement: A$ BlockStatement O&tStatement: F(% BlockStatement F(% ( Identifier ) BlockStatement BodyStatement: "F,G BlockStatement

5irtual Functions
Mirtual functions are functions that are called indirectly throu$h a function pointer ta"le4 called a )t"lHI4 rather than directly. !ll non@static non@pri)ate non@te%plate %e%"er functions are )irtual. This %ay sound inefficient4 "ut since the D co%piler 6no7s all of the class hierarchy 7hen $eneratin$ code4 all functions that are not o)erridden can "e opti%i5ed to "e non@)irtual. -n fact4 since ,88 pro$ra%%ers tend to C7hen in dou"t4 %a6e it )irtualC4 the D 7ay of C%a6e it )irtual unless 7e can pro)e it can "e %ade non@)irtualC results4 on a)era$e4 in %any %ore direct function calls. -t also results in fe7er "u$s caused "y not declarin$ a function )irtual that $ets o)erridden. .unctions 7ith non@D lin6a$e cannot "e )irtual4 and hence cannot "e o)erridden. Me%"er te%plate functions cannot "e )irtual4 and hence cannot "e o)erridden. .unctions %ar6ed as fi&a! %ay not "e o)erridden in a deri)ed class4 unless they are also pri>a#e. .or exa%ple?
c!ass A A i&# def?@ A $$$ C fi&a! i&# f""?@ A $$$ C fi&a! pri>a#e i&# bar?@ A $$$ C pri>a#e i&# abc?@ A $$$ C C c!ass B A i&# i&# i&# i&# C : A def?@ f""?@ bar?@ abc?@ A A A A $$$ $$$ $$$ $$$ C C C C // // // // "=) ">errides A$def err"r) A$f"" is fi&a! "=) A$bar is fi&a! pri>a#e) bu# &"# >ir#ua! "=) A$abc is &"# >ir#ua!) B$abc is >ir#ua!

>"id #es#?A a@ A a$def?@; a$f""?@; a$bar?@;

// ca!!s B$def // ca!!s A$f"" // ca!!s A$bar

D Specification
a$abc?@; C >"id fu&c?@ A B b = &e, B?@; #es#?b@; C // ca!!s A$abc

120

,o)ariant return types are supported4 7hich %eans that the o)erridin$ function in a deri)ed class can return a type that is deri)ed fro% the type returned "y the o)erridden function?
c!ass A A C c!ass B : A A C c!ass 1"" A A #es#?@ A re#ur& &u!!; C C c!ass Bar : 1"" A B #es#?@ A re#ur& &u!!; C C

// ">errides a&d is c">aria&# ,i#

1""$#es#?@

Function "nheritance and O1erriding


! functions in a deri)ed class 7ith the sa%e na%e and para%eter types as a function in a "ase class o)errides that function?
c!ass A A i&# f""?i&# %@ A $$$ C C c!ass B : A A ">erride i&# f""?i&# %@ A $$$ C C >"id #es#?@ A B b = &e, B?@; bar?b@; C >"id bar?A a@ A a$f""?1@; C

// ca!!s B$f""?i&#@

0o7e)er4 7hen doin$ o)erload resolution4 the functions in the "ase class are not considered?
c!ass A A i&# f""?i&# %@ A $$$ C i&# f""?!"&' F@ A $$$ C C c!ass B : A A

121
">erride i&# f""?!"&' %@ A $$$ C C >"id #es#?@ A B b = &e, B?@; b$f""?1@; A a = b; a$f""?1@; C

D Specification

// ca!!s B$f""?!"&'@) si&ce A$f""?i&#@ &"# c"&sidered // ca!!s A$f""?i&#@

To consider the "ase class:s functions in the o)erload resolution process4 use an (lias eclaration?
c!ass A A i&# f""?i&# %@ A $$$ C i&# f""?!"&' F@ A $$$ C C c!ass B : A A !CA!BL:.#FFL#FF; ">erride i&# f""?!"&' %@ A $$$ C C >"id #es#?@ A B b = &e, B?@; bar?b@; C >"id bar?A a@ A a$f""?1@; B b = &e, B?@; b$f""?1@; C

// ca!!s A$f""?i&#@ // ca!!s A$f""?i&#@

! function para%eter:s default )alue is not inherited?


c!ass A A >"id f""?i&# 'L=L4@ A $$$ C C c!ass B : A A >"id f""?i&# 'L=L6@ A $$$ C C c!ass C : B A >"id f""?i&# '@ A $$$ C C >"id #es#?@ A A a = &e, A?@; a$f""?@;

// ca!!s A$f""?7@

D Specification
B b = &e, B?@; b$f""?@; C c = &e, C?@; c$f""?@; C // ca!!s B$f""?8@ // err"r) &eed a& ar'u0e&# f"r C$f""

122

"nline Functions
There is no inline 6ey7ord. The co%piler %a6es the decision 7hether to inline a function or not4 analo$ously to the re$ister 6ey7ord no lon$er "ein$ rele)ant to a co%piler:s decisions on enre$isterin$ )aria"les. AThere is no re$ister 6ey7ord either.B

Function O1erloading
-n ,884 there are %any co%plex le)els of function o)erloadin$4 7ith so%e defined as C"etterC %atches than others. -f the code desi$ner ta6es ad)anta$e of the %ore su"tle "eha)iors of o)erload function selection4 the code can "eco%e difficult to %aintain. 2ot only 7ill it ta6e a ,88 expert to understand 7hy one function is selected o)er another4 "ut different ,88 co%pilers can i%ple%ent this tric6y feature differently4 producin$ su"tly disastrous results. -n D4 function o)erloadin$ is si%ple. -t %atches exactly4 it %atches 7ith i%plicit con)ersions4 or it does not %atch. -f there is %ore than one %atch4 it is an error. .unctions defined 7ith non@D lin6a$e cannot "e o)erloaded.

Function Parameters
ara%eters are in4 out4 inout or lazy. in is the defaultS the others 7or6 li6e stora$e classes. .or exa%ple?
i&# f""?i&# %) "u# i&# F) i&"u# i&# I) i&# +@;

x is in4 y is out4 5 is inout4 and 9 is in. out is rare enou$h4 and inout e)en rarer4 to attach the 6ey7ords to the% and lea)e in as the default. The reasons to ha)e the% are?

The function declaration %a6es it clear 7hat the inputs and outputs to the function are. -t eli%inates the need for -DL as a separate lan$ua$e. -t pro)ides %ore infor%ation to the co%piler4 ena"lin$ %ore error chec6in$ and possi"ly "etter code $eneration. -t AperhapsRB eli%inates the need for reference A+B declarations.

out para%eters are set to the default initiali5er for the type of it. .or exa%ple?
>"id f""?"u# i&# %@ A // % is se# #" 0 a# s#ar# "f f""?@ C i&# a = 3; f""?a@; // a is &", 0 >"id abc?"u# i&# %@

123
A C % = 2;

D Specification

i&# F = 3; abc?F@; // F is &", 2 >"id def?i&"u# i&# %@ A % += 1; C i&# I = 3; def?I@; // I is &", (

.or dyna%ic array and o">ect para%eters4 7hich are passed "y reference4 in/out/inout apply only to the reference and not the contents. La5y ar$u%ents are e)aluated not 7hen the function is called4 "ut 7hen the para%eter is e)aluated 7ithin the function. 0ence4 a la5y ar$u%ent can "e executed 0 or %ore ti%es. ! la5y para%eter cannot "e an l)alue.
>"id d"#i0es?i&# &) !aIF >"id e%p@ A , i!e ?&::@ e%p?@; C >"id #es#?@ A i&# %; d"#i0es?3) ,ri#ef!&?%++@@; C

prints to the console?


0 1 2

! la5y para%eter of type >"id can accept an ar$u%ent of any type.

5ariadic Functions
.unctions ta6in$ a )aria"le nu%"er of ar$u%ents are called )ariadic functions. ! )ariadic function can ta6e one of three for%s? 1. ,@style )ariadic functions 2. Mariadic functions 7ith type info 3. Typesafe )ariadic functions

C)style 5ariadic Functions


! ,@style )ariadic function is declared as ta6in$ a para%eter of ... after the re9uired function para%eters. -t has non@D lin6a$e4 such as e%#er& ?C@?

D Specification
e%#er& ?C@ i&# f""?i&# %) i&# F) $$$@; f""?3) (@; // "= f""?3) () 3$9@; // "=) "&e >ariadic ar'u0e&# f""?2@; // err"r) F is a re+uired ar'u0e&#

12&

There %ust "e at least one non@)ariadic para%eter declared.


e%#er& ?C@ i&# def?$$$@; // err"r) 0us# a>e a# !eas# "&e para0e#er

,@style )ariadic functions %atch the , callin$ con)ention for )ariadic functions4 and is %ost useful for callin$ , li"rary functions li6e pri&#f. The i%ple%entiations of these )ariadic functions ha)e a special local )aria"le declared for the%4 #argptr4 7hich is a >"id* pointer to the first of the )ariadic ar$u%ents. To access the ar$u%ents4 #argptr %ust "e cast to a pointer to the expected ar$u%ent type?
f""?3) () 7@; // firs# >ariadic ar'u0e&# is 7 i&# f""?i&# %) i&# F) $$$@ A i&# I; C I = *cas#?i&#*@_!rD?%r; // I is se# #" 7

To protect a$ainst the )a$aries of stac6 layouts on different , ; architectures4 use std-c-stdarg to access the )ariadic ar$u%ents?
i0p"r# B%,.*.B%,!rD;

%)style 5ariadic Functions


Mariadic functions 7ith ar$u%ent and type info are declared as ta6in$ a para%eter of ... after the re9uired function para%eters. -t has D lin6a$e4 and need not ha)e any non@)ariadic para%eters declared?
i&# abc?c ar c) $$$@; i&# def?$$$@; // "&e re+uired para0e#er: c // "=

These )ariadic functions ha)e a special local )aria"le declared for the%4 #argptr4 7hich is a >"id* pointer to the first of the )ariadic ar$u%ents. To access the ar$u%ents4 #argptr %ust "e cast to a pointer to the expected ar$u%ent type?
f""?3) () 7@; // firs# >ariadic ar'u0e&# is 7 i&# f""?i&# %) i&# F) $$$@ A i&# I; I = *cas#?i&#*@_!rD?%r; C // I is se# #" 7

!n additional hidden ar$u%ent 7ith the na%e #arguments and type JFpeX&f"45 is passed to the function. #arguments $i)es the nu%"er of ar$u%ents and the type of each4 ena"lin$ the creation of typesafe )ariadic functions.
c!ass 1"" A i&# % = 3; C c!ass Bar A !"&' F = (; C >"id pri&#ar's?i&# %) $$$@

125
A pri&#f?"Nd ar'u0e&#s\&") _!rD(E9$%B$!e&'# @; f"r ?i&# i = 0; i U _!rD(E9$%B$!e&'# ; i++@ A _!rD(E9$%B4i5$pri&#?@; if ?_!rD(E9$%B4i5 == #Fpeid?i&#@@ A i&# M = *cas#?i&# *@6ar'p#r; 6ar'p#r += i&#$siIe"f; pri&#f?"\#Nd\&") M@; C e!se if ?_!rD(E9$%B4i5 == #Fpeid?!"&'@@ A !"&' M = *cas#?!"&' *@6ar'p#r; 6ar'p#r += !"&'$siIe"f; pri&#f?"\#N!!d\&") M@; C e!se if ?_!rD(E9$%B4i5 == #Fpeid?d"ub!e@@ A d"ub!e d = *cas#?d"ub!e *@6ar'p#r; 6ar'p#r += d"ub!e$siIe"f; pri&#f?"\#N'\&") d@; C e!se if ?_!rD(E9$%B4i5 == #Fpeid?1""@@ A 1"" f = *cas#?1""*@6ar'p#r; 6ar'p#r += 1""$siIe"f; pri&#f?"\#Np\&") f@; C e!se if ?_!rD(E9$%B4i5 == #Fpeid?Bar@@ A Bar b = *cas#?Bar*@6ar'p#r; 6ar'p#r += Bar$siIe"f; pri&#f?"\#Np\&") b@; C e!se asser#?0@; C C

D Specification

>"id 0ai&?@ A 1"" f = &e, 1""?@; Bar b = &e, Bar?@; pri&#f?"Np\&") f@; pri&#ar's?1) 2) 3;) ($7) f) b@; C

7hich prints?
009801E0 7 ar'u0e&#s i&# 2 !"&' 3 d"ub!e ($7 1"" 009801E0

D Specification
Bar 009801D0

12(

To protect a$ainst the )a$aries of stac6 layouts on different , ; architectures4 use std-stdarg to access the )ariadic ar$u%ents?
i0p"r# B%,.B%,!rD; >"id f""?i&# %) $$$@ A pri&#f?"Nd ar'u0e&#s\&") 6ar'u0e&#s$!e&'# @; f"r ?i&# i = 0; i U 6ar'u0e&#s$!e&'# ; i++@ A 6ar'u0e&#s4i5$pri&#?@; if ?6ar'u0e&#s4i5 == #Fpeid?i&#@@ A i&# M = &!_!rDB?i&#@?6ar'p#r@; pri&#f?"\#Nd\&") M@; C e!se if ?6ar'u0e&#s4i5 == #Fpeid?!"&'@@ A !"&' M = &!_!rDB?!"&'@?6ar'p#r@; pri&#f?"\#N!!d\&") M@; C e!se if ?6ar'u0e&#s4i5 == #Fpeid?d"ub!e@@ A d"ub!e d = &!_!rDB?d"ub!e@?6ar'p#r@; pri&#f?"\#N'\&") d@; C e!se if ?6ar'u0e&#s4i5 == #Fpeid?1OO@@ A 1OO f = &!_!rDB?1OO@?6ar'p#r@; pri&#f?"\#Np\&") f@; C e!se asser#?0@; C C

Typesafe 5ariadic Functions


Typesafe )ariadic functions are used 7hen the )aria"le ar$u%ent portion of the ar$u%ents are used to construct an array or class o">ect. .or arrays?
i&# #es#?@ A re#ur& su0?1) 2) 3@ + su0?@; // re#ur&s 3+0 C i&# fu&c?@ A i&#435 ii = 4() 7) 35; re#ur& su0?ii@; C i&# su0?i&#45 ar $$$@ A i&# s;

// re#ur&s 17

127
f"reac ?i&# %; ar@ s += %; re#ur& s; C

D Specification

.or static arrays?


i&# #es#?@ A re#ur& su0?2) 3@; // err"r) &eed 3 >a!ues f"r arraF re#ur& su0?1) 2) 3@; // re#ur&s 3 C i&# fu&c?@ A i&#435 ii = 4() 7) 35; i&#45 MM = ii; re#ur& su0?ii@; re#ur& su0?MM@; C i&# su0?i&#435 ar $$$@ A i&# s; f"reac ?i&# %; ar@ s += %; re#ur& s; C

// re#ur&s 17 // err"r) #Fpe 0is0a#c

.or class o">ects?


c!ass 1"" A i&# %; c ar45 s; # is?i&# %) c ar45 s@ A # is$% = %; # is$s = s; C C >"id #es#?i&# %) 1"" f $$$@; $$$ 1"" ' = #es#?1) #es#?1) #es#?1) &e, 1""?3) "abc"@; '@; // "=) si&ce ' is a& i&s#a&ce "f 1"" () "def"@; // "= 7@; // err"r) &" 0a#c i&' c"&s#ruc#"r f"r 1""

!n i%ple%entation %ay construct the o">ect or array instance on the stac6. Therefore4 it is an error to refer to that instance after the )ariadic function has returned?
1"" #es#?1"" f $$$@ A re#ur& f; // err"r) f i&s#a&ce c"&#e&#s i&>a!id af#er re#ur& C i&#45 #es#?i&#45 a $$$@

D Specification
A re#ur& a; re#ur& a40$$15; re#ur& a$dup; // err"r) arraF c"&#e&#s i&>a!id af#er re#ur& // err"r) arraF c"&#e&#s i&>a!id af#er re#ur& // "=) si&ce c"pF is 0ade

12#

.or other types4 the ar$u%ent is "uilt 7ith itself4 as in?


i&# #es#?i&# i $$$@ A re#ur& i; C $$$ #es#?3@; #es#?3) (@; i&#45 %; #es#?%@; // re#ur&s 3 // err"r) #"" 0a&F ar'u0e&#s // err"r) #Fpe 0is0a#c

Lazy 5ariadic Functions


-f the )ariadic para%eter is an array of dele$ates 7ith no para%eters?
>"id f""?i&# de!e'a#e?@45 d's $$$@;

Then each of the ar$u%ents 7hose type does not %atch that of the dele$ate is con)erted to a dele$ate.
i&# de!e'a#e?@ d'; f""?1) 3+%) d') cas#?i&# de!e'a#e?@@&u!!@;

is the sa%e as?


f""? A re#ur& 1; C) A re#ur& 3+%; C) d') &u!! @;

Local 5aria0les
-t is an error to use a local )aria"le 7ithout first assi$nin$ it a )alue. The i%ple%entation %ay not al7ays "e a"le to detect these cases. /ther lan$ua$e co%pilers so%eti%es issue a 7arnin$ for this4 "ut since it is al7ays a "u$4 it should "e an error. -t is an error to declare a local )aria"le that is ne)er referred to. Dead )aria"les4 li6e anachronistic dead code4 are >ust a source of confusion for %aintenance pro$ra%%ers. -t is an error to declare a local )aria"le that hides another local )aria"le in the sa%e function?
>"id fu&c?i&# %@ A i&# %; d"ub!e F; $$$ A c ar F; i&# I; C A ,c ar I; C C err"r) err"r) ides pre>i"us defi&i#i"& "f % ides pre>i"us defi&i#i"& "f F

!e'a!) pre>i"us I is "u# "f sc"pe

Dhile this %i$ht loo6 unreasona"le4 in practice 7hene)er this is done it either is a "u$ or at least

12* loo6s li6e a "u$. -t is an error to return the address of or a reference to a local )aria"le. -t is an error to ha)e a local )aria"le and a la"el 7ith the sa%e na%e.

D Specification

(ested Functions
.unctions %ay "e nested 7ithin other functions?
i&# bar?i&# a@ A i&# f""?i&# b@ A i&# abc?@ A re#ur& 1; C re#ur& b + abc?@; C re#ur& f""?a@; C >"id #es#?@ A i&# i = bar?3@; C

// i is assi'&ed (

2ested functions can "e accessed only if the na%e is in scope.


>"id f""?@ A >"id A?@ A B?@; // err"r) B?@ is f"r,ard refere&ced C?@; // err"r) C u&defi&ed C >"id B?@ A A?@; // "=) i& sc"pe >"id C?@ A >"id D?@ A A?@; // "= B?@; // "= C?@; // "= D?@; // "= C C C A?@; // "= B?@; // "= C?@; // err"r) C u&defi&ed C

and?
i&# bar?i&# a@ A i&# f""?i&# b@ A re#ur& b + 1; C i&# abc?i&# b@ A re#ur& f""?b@; C re#ur& f""?a@;

// "=

D Specification
C >"id #es#?@ A i&# i = bar?3@; // "= i&# M = bar$f""?3@; // err"r) bar$f"" &"# >isib!e C

130

2ested functions ha)e access to the )aria"les and other sy%"ols defined "y the lexically enclosin$ function. This access includes "oth the a"ility to read and 7rite the%.
i&# bar?i&# a@ A i&# c = 3; i&# f""?i&# b@ A b += c; c++; re#ur& b + c; C c = (; i&# i = f""?a@; re#ur& i + c;

// ( is added #" b // bar$c is &", 7 // 12 is re#ur&ed // i is se# #" 12 // re#ur&s 18

>"id #es#?@ A i&# i = bar?3@; C

// i is assi'&ed 18

This access can span %ultiple nestin$ le)els?


i&# bar?i&# a@ A i&# c = 3; i&# f""?i&# b@ A i&# abc?@ A re#ur& c; // access bar$c C re#ur& b + c + abc?@; C re#ur& f""?3@; C

Static nested functions cannot access any stac6 )aria"les of any lexically enclosin$ function4 "ut can access static )aria"les. This is analo$ous to ho7 static %e%"er functions "eha)e.
i&# bar?i&# a@ A i&# c; s#a#ic i&# d; s#a#ic i&# f""?i&# b@ A b = d; // "= b = c; // err"r) f""?@ ca&&"# access fra0e "f bar?@ re#ur& b + 1; C re#ur& f""?a@;

131 .unctions can "e nested 7ithin %e%"er functions?


s#ruc# 1"" A i&# a; i&# bar?@ A i&# c; i&# f""?@ A re#ur& c + a; C re#ur& 0; C C

D Specification

Me%"er functions of nested classes and structs do not ha)e access to the stac6 )aria"les of the enclosin$ function4 "ut do ha)e access to the other sy%"ols?
>"id #es#?@ A i&# M; s#a#ic i&# s; s#ruc# 1"" A i&# a; i&# bar?@ A i&# c = s; i&# d = M; i&# f""?@ A i&# e = s; i&# f = M; re#ur& c + a; C re#ur& 0; C C C // "=) s is s#a#ic // err"r) &" access #" fra0e "f #es#?@

// // // // //

"=) s is s#a#ic err"r) &" access #" fra0e "f #es#?@ "=) fra0e "f bar?@ is accessib!e) s" are 0e0bers "f 1"" accessib!e >ia # e '# is' p"i&#er #" 1""$bar?@

2ested functions al7ays ha)e the D function lin6a$e type. ;nli6e %odule le)el declarations4 declarations 7ithin function scope are processed in order. This %eans that t7o nested functions cannot %utually call each other?
>"id #es#?@ A >"id f""?@ A bar?@; C >"id bar?@ A f""?@; C C // err"r) bar &"# defi&ed // "=

The solution is to use a dele$ate?


>"id #es#?@ A >"id de!e'a#e?@ fp; >"id f""?@ A fp?@; C

D Specification
>"id bar?@ A f""?@; C fp = .bar;

132

Future directions2 This restriction %ay "e re%o)ed.

%elegates& Function Pointers& and %ynamic Closures


! function pointer can point to a static nested function?
i&# fu&c#i"&?@ fp; >"id #es#?@ A s#a#ic i&# a = 8; s#a#ic i&# f""?@ A re#ur& a + 3; C fp = .f""; C >"id bar?@ A #es#?@; i&# i = fp?@; C

// i is se# #" 10

! dele$ate can "e set to a non@static nested function?


i&# de!e'a#e?@ d'; >"id #es#?@ A i&# a = 8; i&# f""?@ A re#ur& a + 3; C d' = .f""; i&# i = d'?@; C // i is se# #" 10

The stac6 )aria"les4 ho7e)er4 are not )alid once the function declarin$ the% has exited4 in the sa%e %anner that pointers to stac6 )aria"les are not )alid upon exit fro% a function?
i&#* bar?@ A i&# b; #es#?@; i&# i = d'?@; re#ur& .b; C

// err"r) #es#$a &" !"&'er e%is#s // err"r) bar$b &"# >a!id af#er bar?@ e%i#s

Dele$ates to non@static nested functions contain t7o pieces of data? the pointer to the stac6 fra%e of the lexically enclosin$ function Acalled the frame pointerB and the address of the function. This is analo$ous to struct/class non@static %e%"er function dele$ates consistin$ of a this pointer and the address of the %e%"er function. 3oth for%s of dele$ates are interchan$ea"le4 and are actually the sa%e type?
s#ruc# 1"" A i&# a = 8; i&# bar?@ A re#ur& a; C C i&# f""?i&# de!e'a#e?@ d'@

133
A C re#ur& d'?@ + 1;

D Specification

>"id #es#?@ A i&# % = 28; i&# abc?@ A re#ur& %; C 1"" f; i&# i; i = f""?.abc@; i = f""?.f$bar@; C // i is se# #" 29 // i is se# #" 9

This co%"inin$ of the en)iron%ent and the function is called a dynamic closure. The -ptr property of a dele$ate 7ill return the frame pointer )alue as a >"id*. The -funcptr property of a dele$ate 7ill return the function pointer )alue as a function type. Future directions2 .unction pointers and dele$ates %ay %er$e into a co%%on syntax and "e interchan$ea"le 7ith each other.

.nonymous Functions and .nonymous %elegates


See .unction Literals.

main34 Function
.or console pro$ra%s4 0ai&?@ ser)es as the entry point. -t $ets called after all the %odule initiali5ers are run4 and after any unittests are run. !fter it returns4 all the %odule destructors are run. 0ai&?@ %ust "e declared usin$ one of the follo7in$ for%s?
>"id 0ai&?@ A $$$ C >"id 0ai&?c ar4545 ar's@ A $$$ C i&# 0ai&?@ A $$$ C i&# 0ai&?c ar4545 ar's@ A $$$ C

D Specification

13&

$perator $verloading
/)erloadin$ is acco%plished "y interpretin$ specially na%ed struct and class %e%"er functions as "ein$ i%ple%entations of unary and "inary operators. 2o additional syntax is used.

'nary Operator O1erloading


/)erloada"le ;nary /perators op @e 8e Ge e88 e@@ opfunc "pHe' "pR"s "pC"0 "pR"s#X&c "pR"s#Dec

castAtypeB "pCas# e 1i)en a unary o)erloada"le operator op and its correspondin$ class or struct %e%"er function na%e opfunc4 the syntax?
op a

7here a is a class or struct o">ect reference4 is interpreted as if it 7as 7ritten as?


a$opf&nc?@

O1erloading 66e and ))e


Since 88e is defined to "e se%antically e9ui)alent to Ae 8Q 1B4 the expression 88e is re7ritten as Ae 8Q 1B4 and then chec6in$ for operator o)erloadin$ is done. The situation is analo$ous for @@e.

Examples
1$ c!ass A A i&# F?P9D?@; C A a; :a; // e+ui>a!e&# #" a$"pHe'?@; 2$ c!ass A A i&# F?P9D?i&# i@; C A a; :a; // e+ui>a!e&# #" a$"pHe'?@) , ic

is a& err"r

O1erloading cast3type4e
The %e%"er function e.opCast34 is called4 and the return )alue of opCast34 is i%plicitly con)erted to type. Since functions cannot "e o)erloaded "ased on return )alue4 there can "e only one opCast per struct or class. /)erloadin$ the cast operator does not affect i%plicit casts4 it only applies to explicit casts.
s#ruc# A

135
A C i&# F?;!B%?@ A re#ur& 29; C

D Specification

>"id #es#?@ A A a; !"&' i = cas#?!"&'@a; // i is se# #" 29; >"id* p = cas#?>"id*@a; // err"r) ca&&"# i0p!ici#!F // c"&>er# i&# #" >"id* i&# M = a; // err"r) ca&&"# i0p!ici#!F c"&>er# // A #" i&# C

Binary Operator O1erloading


op 8 @ N / Z + O P UU VV VVV G QQ =Q U UQ V VQ Q 8Q @Q commutati1eF yes no yes no no yes yes yes no no no no yes yes yes yes yes yes no no no /)erloada"le 3inary /perators opfunc opfunc_r "pAdd "pLub "pSu! "pDi> "pS"d "pA&d "pOr "pW"r "pL ! "pL r "p-L r "pCa# "pE+ua!s "pE+ua!s "pC0p "pC0p "pC0p "pC0p "pAssi'& "pAddAssi'& "pLubAssi'& "pAdd6r "pLub6r "pSu!6r "pDi>6r "pS"d6r "pA&d6r "pOr6r "pW"r6r "pL !6r "pL r6r "p-L r6r "pCa#6r @ @ @ @ @ @ @ @ @

D Specification NQ /Q ZQ +Q OQ PQ UUQ VVQ GQ in no no no no no no no no no no "pSu!Assi'& "pDi>Assi'& "pS"dAssi'& "pA&dAssi'& "pOrAssi'& "pW"rAssi'& "pL !Assi'& "pL rAssi'& "pCa#Assi'& "pX& @ @ @ @ @ @ @ @ @ "pX&6r

13(

VVVQ no

"p-L rAssi'& @

1i)en a "inary o)erloada"le operator op and its correspondin$ class or struct %e%"er function na%e opfunc and opfunc1r4 and the syntax?
a "p b

the follo7in$ se9uence of rules is applied4 in order4 to deter%ine 7hich for% is used? 1. The expression is re7ritten as "oth?
a$"pfu&c?b@ b$"pfu&c6r?a@

-f any a.opfunc or ".opfuncJr functions exist4 then o)erloadin$ is applied across all of the% and the "est %atch is used. -f either exist4 and there is no ar$u%ent %atch4 then it is an error. 2. -f the operator is co%%utati)e4 then the follo7in$ for%s are tried?
a$"pfu&c6r?b@ b$"pfu&c?a@

3. -f a or # is a struct or class o">ect reference4 it is an error. Examples


1$ c!ass A A i&# F?:,,?i&# i@; C A a; a + 1; // e+ui>a!e&# #" a$"pAdd?1@ 1 + a; // e+ui>a!e&# #" a$"pAdd?1@ 2$ c!ass B A i&# F?<A&_r?i&# i@; C B b; 1 / b; // e+ui>a!e&# #" b$"pDi>6r?1@ 3$ c!ass A c!ass B A a; B b; a + 1; a + b; b + a; A i&# F?:,,?i&# i@; C A i&# F?:,,_r?A a@; C // e+ui>a!e&# #" a$"pAdd?1@ // e+ui>a!e&# #" b$"pAdd6r?a@ // e+ui>a!e&# #" b$"pAdd6r?a@

137
($ c!ass A c!ass B A a; B b; a + b; b + a; 7$ c!ass A c!ass B A a; B b; a + b; b + a; A i&# F?:,,?B b@; A C i&# F?:,,_r?B b@; C

D Specification

// e+ui>a!e&# #" a$"pAdd?b@ // e+ui>a!e&# #" a$"pAdd6r?b@ A i&# F?:,,?B b@; i&# F?:,,_r?B b@; C A i&# F?:,,_r?A a@; C // a0bi'u"us: a$"pAdd?b@ "r b$"pAdd6r?a@ // e+ui>a!e&# #" a$"pAdd6r?b@

O1erloading 88 and 98
3oth operators use the F?=Q(!CB?@ function. The expression ?a == b@ is re7ritten as a$F?=Q(!CB?b@4 and ?a B= b@ is re7ritten as Ba$F?=Q(!CB?b@. The %e%"er function F?=Q(!CB?@ is defined as part of /">ect as?
i&# F?=Q(!CB?ObMec# "@;

so that e)ery class o">ect has a default F?=Q(!CB?@. 3ut e)ery class definition 7hich 7ill "e usin$ QQ or =Q should expect to need to o)erride op'9uals. The para%eter to the o)erridin$ function %ust "e of type ObMec#4 not the type for the class. Structs and unions Ahereafter >ust called structsB can pro)ide a %e%"er function?
i&# F?=Q(!CB?L s@

or?
i&# F?=Q(!CB?L* s@

7here L is the struct na%e4 to define ho7 e9uality is deter%ined. -f a struct has no opE/uals function declared for it4 a "it co%pare of the contents of the t7o structs is done to deter%ine e9uality or ine9uality. (ote2 ,o%parin$ a reference to a class o">ect a$ainst null should "e done as?
if ?a is &u!!@

and not as?


if ?a == &u!!@

The latter is con)erted to?


if ?a$F?=Q(!CB?&u!!@@

7hich 7ill fail if F?=Q(!CB?@ is a )irtual function.

O1erloading ;& ;8& < and <8


These co%parison operators all use the F?;E??@ function. The expression ?a op b@ is re7ritten as ?a$F?;E??b@ op 0@. The co%%utati)e operation is re7ritten as ?0 op b$F?;E??a@@

D Specification The %e%"er function F?;E??@ is defined as part of /">ect as?


i&# F?;E??ObMec# "@;

13#

so that e)ery class o">ect has a F?;E??@. -f a struct has no opCmpAB function declared for it4 atte%ptin$ to co%pare t7o structs is an error. ,ationale The reason for ha)in$ "oth opE/ualsAB and opCmpAB is that?

Testin$ for e9uality can so%eti%es "e a %uch %ore efficient operation than testin$ for less or $reater than. .or so%e o">ects4 testin$ for less or $reater %a6es no sense. .or these4 o)erride opCmpAB 7ith?
c!ass A A i&# F?;E??ObMec# "@ A asser#?0@; // c"0paris"& 0a=es &" se&se re#ur& 0; C C

The para%eter to opE/uals and opCmp for class definitions %ust "e of type /">ect4 rather than the type of the particular class4 in order to o)erride the /">ect.opE/uals and /">ect.opCmp functions properly.

Function Call Operator O1erloading f34


The function call operator4 AB4 can "e o)erloaded "y declarin$ a function na%ed opCall?
s#ruc# 1 A i&# F?;!CC?@; i&# F?;!CC?i&# %) i&# F) i&# I@; C >"id #es#?@ A 1 f; i&# i; i = f(); i = f(2,3,4); C // sa0e as i = f$"pCa!!?@; // sa0e as i = f$"pCa!!?3)()7@;

-n this 7ay a struct or class o">ect can "eha)e as if it 7ere a function.

.rray Operator O1erloading


O1erloading "ndexing a@iA
The array index operator4 HI4 can "e o)erloaded "y declarin$ a function na%ed op"ndex 7ith one or %ore para%eters. !ssi$n%ent to an array can "e o)erloaded 7ith a function na%ed op"ndex.ssign

13*

D Specification

7ith t7o or %ore para%eters. The first para%eter is the r)alue of the assi$n%ent expression.
s#ruc# A A i&# F?R$,9'?siIe6# i1) siIe6# i2) siIe6# i3@; i&# F?R$,9':BBAD$?i&# >a!ue) siIe6# i1) siIe6# i2@; C >"id #es#?@ A A a; i&# i; i = a[7)3)8]; a[i)3] = 8; // sa0e as i = a$"pX&de%?7)3)8@; // sa0e as a$"pX&de%Assi'&?8)i)3@;

-n this 7ay a struct or class o">ect can "eha)e as if it 7ere an array. (ote2 !rray index o)erloadin$ currently does not 7or6 for the l)alue of an opQ4 884 or @@ operator.

O1erloading Slicing a@A and a@i -- jA


/)erloadin$ the slicin$ operator %eans o)erloadin$ expressions li6e a45 and a4i $$ M5. This can "e done "y declarin$ a function na%ed opSlice. !ssi$n%ent to a slice can "e done "y declarin$ opSlice.ssign.
c!ass A A i&# F?SCA*9?@; i&# F?SCA*9?siIe6# %) siIe6# F@; // ">er!"ads a45 // ">er!"ads a4i $$ M5

i&# F?SCA*9:BBAD$?i&# >@; // ">er!"ads a45 = > i&# F?SCA*9:BBAD$?i&# >) siIe6# %) siIe6# F@; // ">er!"ads a4i $$ M5 = > C >"id #es#?@ A A a = &e, A?@; i&# i; i&# >; i = a[]; i = a[3$$(]; a[] = >; a[3$$(] = >; C // sa0e as i = a$"pL!ice?@; // sa0e as i = a$"pL!ice?3)(@; // sa0e as a$"pL!iceAssi'&?>@; // sa0e as a$"pL!iceAssi'&?>)3)(@;

.ssignment Operator O1erloading


The assi$n%ent operator 8 can "e o)erloaded if the l)alue is a struct or class a$$re$ate4 and "pAssi'& is a %e%"er function of that a$$re$ate. The assi$n%ent operator cannot "e o)erloaded for r)alues that can "e i%plicitly cast to the l)alue type. .urther%ore4 the follo7in$ para%eter si$natures for "pAssi'& are not allo7ed?
"pAssi'&?$$$@ "pAssi'&?J@ "pAssi'&?J) $$$@ "pAssi'&?J $$$@

D Specification
"pAssi'&?J) - = defau!#Qa!ue) e#c$@

1&0

7here ' is the sa%e type as the a$$re$ate type (4 is i%plicitly con)erti"le to (4 or if ( is a struct and ' is a pointer to a type that is i%plicitly con)erti"le to (.

Future %irections
The operators =4 .4 ++4 OO4 R?4 and a fe7 others 7ill li6ely ne)er "e o)erloada"le.

1&1

D Specification

Templates
- thin6 that - can safely say that no"ody understands te%plate %echanics. @@ Lichard Dey%an Te%plates are D:s approach to $eneric pro$ra%%in$. Te%plates are defined 7ith a 'emplate eclaration?
Template%eclaration: %9E?C!%9 TemplateIdentifier ( Template,arameterList ) { Dec!Defs } TemplateIdentifier: Identifier Template,arameterList Template,arameter Template,arameter ) Template,arameterList Template,arameter: TemplateType,arameter Template.al&e,arameter Template#lias,arameter TemplateT&ple,arameter TemplateType,arameter: Identifier Identifier TemplateType,arameterSpeciali/ation Identifier TemplateType,arameter%efa&lt Identifier TemplateType,arameterSpeciali/ation TemplateType,arameter%efa&lt TemplateType,arameterSpeciali/ation: : Type TemplateType,arameter%efa&lt: = Type Template.al&e,arameter: %eclaration %eclaration Template.al&e,arameterSpeciali/ation %eclaration Template.al&e,arameter%efa&lt %eclaration Template.al&e,arameterSpeciali/ation Template.al&e,arameter%efa&lt Template.al&e,arameterSpeciali/ation: : ConditionalE+pression Template.al&e,arameter%efa&lt: = ConditionalE+pression Template#lias,arameter: !CA!B Identifier !CA!B Identifier Template#lias,arameterSpeciali/ation !CA!B Identifier Template#lias,arameter%efa&lt !CA!B Identifier Template#lias,arameterSpeciali/ation Template#lias,arameter%efa&lt Template#lias,arameterSpeciali/ation:

D Specification
: Type Template#lias,arameter%efa&lt: = Type TemplateT&ple,arameter: Identifier ...

1&2

The "ody of the 'emplate eclaration %ust "e syntactically correct e)en if ne)er instantiated. Se%antic analysis is not done until instantiated. ! te%plate for%s its o7n scope4 and the te%plate "ody can contain classes4 structs4 types4 enu%s4 )aria"les4 functions4 and other te%plates. Te%plate para%eters can "e types4 )alues4 sy%"ols4 or tuples. Types can "e any type. Malue para%eters %ust "e of an inte$ral type4 floatin$ point type4 or strin$ type and speciali5ations for the% %ust resol)e to an inte$ral constant4 floatin$ point constant4 null4 or a strin$ literal. Sy%"ols can "e any non@local sy%"ol. Tuples are a se9uence of 0 or %ore types4 )alues or sy%"ols. Te%plate para%eter speciali5ations constrain the )alues or types the 'emplateParameter can accept. Te%plate para%eter defaults are the )alue or type to use for the 'emplateParameter in case one is not supplied.

Explicit Template "nstantiation


Te%plates are explicitly instantiated 7ith?
TemplateInstance: TemplateIdentifer !( Template#rg&mentList ) Template#rg&mentList: Template#rg&ment Template#rg&ment ) Template#rg&mentList Template#rg&ment: Type #ssignE+pression Sym'ol

/nce instantiated4 the declarations inside the te%plate4 called the te%plate %e%"ers4 are in the scope of the 'emplateInstance?
#e0p!a#e J1""?J@ A a!ias J* #; C $$$ J1""B?i&#@$# %; // dec!are % #" be "f #Fpe i&#*

! te%plate instantiation can "e aliased?


#e0p!a#e J1""?J@ A a!ias J* #; C a!ias J1""B?i&#@ abc; abc$# %; // dec!are % #" be "f #Fpe i&#*

Multiple instantiations of a 'emplate eclaration 7ith the sa%e 'emplate(rgumentList4 "efore i%plicit con)ersions4 all 7ill refer to the sa%e instantiation. .or exa%ple?
#e0p!a#e J1""?J@ A J f; C a!ias J1""B?i&#@ a; a!ias J1""B?i&#@ b; $$$

1&3
a$f = 3; asser#?b$f == 3@;

D Specification
// a a&d b refer #" # e sa0e i&s#a&ce "f J1""

This is true e)en if the 'emplateInstances are done in different %odules. ')en if te%plate ar$u%ents are i%plicitly con)erted to the sa%e te%plate para%eter type4 they still refer to different instances?
s#ruc# J1""?i&# %@ A C s#a#ic asser#?is?J1""B?3@ == J1""B?2 + 1@@@; i&# s#a#ic asser#?Bis?J1""B?3@ == J1""B?3u@@@; // 3 a&d 2+1 are b"# 3 "f #Fpe

// 3u a&d 3 are differe&# #Fpes

-f %ultiple te%plates 7ith the sa%e 'emplateIdentifier are declared4 they are distinct if they ha)e a different nu%"er of ar$u%ents or are differently speciali5ed. .or exa%ple4 a si%ple $eneric copy te%plate 7ould "e?
#e0p!a#e JC"pF?J@ A >"id c"pF?"u# J #") J fr"0@ A #" = fr"0; C C

To use the te%plate4 it %ust first "e instantiated 7ith a specific type?
i&# i; JC"pFB?i&#@$c"pF?i) 3@;

"nstantiation Scope
'emplateInstantances are al7ays perfor%ed in the scope of 7here the 'emplate eclaration is declared4 7ith the addition of the te%plate para%eters "ein$ declared as aliases for their deduced types. .or exa%ple?

%odule a
#e0p!a#e J1""?J@ A >"id bar?@ A fu&c?@; C C

%odule "
i0p"r# a; >"id fu&c?@ A C a!ias J1""B?i&#@ f; // err"r: fu&c &"# defi&ed i& 0"du!e a

and?

%odule a
#e0p!a#e J1""?J@ A >"id bar?@ A fu&c?1@; C C

D Specification
>"id fu&c?d"ub!e d@ A C

1&&

%odule "
i0p"r# a; >"id fu&c?i&# i@ A C a!ias J1""B?i&#@ f; $$$ f$bar?@; // ,i!! ca!! a$fu&c?d"ub!e@

'emplateParameter speciali5ations and default )alues are e)aluated in the scope of the 'emplate eclaration.

.rgument %eduction
The types of te%plate para%eters are deduced for a particular te%plate instantiation "y co%parin$ the te%plate ar$u%ent 7ith the correspondin$ te%plate para%eter. .or each te%plate para%eter4 the follo7in$ rules are applied in order until a type is deduced for each para%eter? 1. -f there is no type speciali5ation for the para%eter4 the type of the para%eter is set to the te%plate ar$u%ent. 2. -f the type speciali5ation is dependent on a type para%eter4 the type of that para%eter is set to "e the correspondin$ part of the type ar$u%ent. 3. -f after all the type ar$u%ents are exa%ined there are any type para%eters left 7ith no type assi$ned4 they are assi$ned types correspondin$ to the te%plate ar$u%ent in the sa%e position in the 'emplate(rgumentList. &. -f applyin$ the a"o)e rules does not result in exactly one type for each te%plate para%eter4 then it is an error. .or exa%ple?
#e0p!a#e J1""?J@ A C a!ias J1""B?i&#@ 1""1; a!ias J1""B?c ar*@ 1""2; #e0p!a#e JBar?J : J*@ A C a!ias JBarB?c ar*@ 1""3; #e0p!a#e JAbc?D) - : D45@ A C a!ias JAbcB?i&#) i&#45@ Bar1; a!ias JAbcB?c ar) i&#45@ Bar2; #e0p!a#e JDef?D : E*) E@ A C a!ias JDefB?i&#*) i&#@ Bar3; // ?1@ J is deduced #" be i&# // ?1@ J is deduced #" be c ar* // ?2@ J is deduced #" be c ar // ?2@ D is deduced #" be i&#) - is i&#45 // ?(@ err"r) D is b"# c ar a&d i&# // ?1@ E is i&# // ?3@ D is i&#*

Dhen considerin$ %atches4 a class is considered to "e a %atch for any super classes or interfaces?
c!ass A A C c!ass B : A A C #e0p!a#e J1""?J : A@ A C a!ias J1""B?B@ 1""(; #e0p!a#e JBar?J : -*) - : A@ A C // ?3@ J is B

1&5
a!ias JBarB?B*) B@ 1""7; // ?2@ J is B* // ?3@ - is B

D Specification

5alue Parameters
This exa%ple of te%plate foo has a )alue para%eter that is speciali5ed for 10?
#e0p!a#e f""?- : i&#) i&# J : 10@ A - % = J; C >"id 0ai&?@ A asser#?f""B?i&#) 10@$% == 10@; C

Specialization
Te%plates %ay "e speciali5ed for particular types of ar$u%ents "y follo7in$ the te%plate para%eter identifier 7ith a ? and the speciali5ed type. .or exa%ple?
#e0p!a#e #e0p!a#e #e0p!a#e #e0p!a#e a!ias a!ias a!ias a!ias a!ias J1""?J@ J1""?J : J45@ J1""?J : c ar@ J1""?J)-)Q@ A A A A $$$ $$$ $$$ $$$ C C C C // // // // <1 <2 <3 <( i&s#a&#ia#es <1 i&s#a&#ia#es <2 ,i# J bei&' d"ub!e i&s#a&#ia#es <3 err"r) &u0ber "f ar'u0e&#s 0is0a#c // i&s#a&#ia#es <(

J1""B?i&#@ f""1; // J1""B?d"ub!e45@ f""2; // J1""B?c ar@ f""3; // J1""B?c ar) i&#@ f""e; // J1""B?c ar) i&#) i&#@ f""(;

The te%plate pic6ed to instantiate is the one that is %ost speciali5ed that fits the types of the 'emplate(rgumentList. Deter%ine 7hich is %ore speciali5ed is done the sa%e 7ay as the ,88 partial orderin$ rules. -f the result is a%"i$uous4 it is an error.

.lias Parameters
!lias para%eters ena"le te%plates to "e para%eteri5ed 7ith any type of D sy%"ol4 includin$ $lo"al na%es4 local na%es4 type na%es4 %odule na%es4 te%plate na%es4 and te%plate instance na%es. -t is a superset of the uses of te%plate te%plate para%eters in ,88.

1lo"al na%es
i&# %; #e0p!a#e 1""?a!ias W@ A s#a#ic i&#* p = .W; C >"id #es#?@ A a!ias 1""B?%@ bar; *bar$p = 3;

// se# % #" 3

D Specification
s#a#ic i&# F; a!ias 1""B?F@ abc; *abc$p = 3; C

1&(

// se# F #" 3

Type na%es
c!ass 1"" A s#a#ic i&# p; C #e0p!a#e Bar?a!ias J@ A a!ias J$p +; C >"id #es#?@ A a!ias BarB?1""@ bar; bar$+ = 3; // se#s 1""$p #" 3 C

Module na%es
i0p"r# s#d$s#ri&'; #e0p!a#e 1""?a!ias W@ A a!ias W$#"L#ri&' F; C >"id #es#?@ A a!ias 1""B?s#d$s#ri&'@ bar; bar$F?3@; // ca!!s s#d$s#ri&'$#"L#ri&'?3@ C

Te%plate na%es
i&# %; #e0p!a#e 1""?a!ias W@ A s#a#ic i&#* p = .W; C #e0p!a#e Bar?a!ias J@ A a!ias JB?%@ abc; C >"id #es#?@ A a!ias BarB?1""@ bar; *bar$abc$p = 3; // se#s % #" 3 C

Te%plate alias na%es


i&# %;

1&7
#e0p!a#e 1""?a!ias W@ A s#a#ic i&#* p = .W; C #e0p!a#e Bar?a!ias J@ A a!ias J$p +; C >"id #es#?@ A a!ias 1""B?%@ f""; a!ias BarB?f""@ bar; *bar$+ = 3; // se#s % #" 3 C

D Specification

Template Parameter %efault 5alues


Trailin$ te%plate para%eters can "e $i)en default )alues?
#e0p!a#e 1""?J) - = i&#@ A $$$ C 1""B?ui&#)!"&'@; // i&s#a&#ia#e 1"" ,i# 1""B?ui&#@; // i&s#a&#ia#e 1"" ,i# #e0p!a#e 1""?J) - = J*@ A $$$ C 1""B?ui&#@; // i&s#a&#ia#e 1"" ,i# J as ui&#) a&d - as !"&' J as ui&#) a&d - as i&# J as ui&#) a&d - as ui&#*

"mplicit Template Properties


-f a te%plate has exactly one %e%"er in it4 and the na%e of that %e%"er is the sa%e as the te%plate na%e4 that %e%"er is assu%ed to "e referred to in a te%plate instantiation?
#e0p!a#e >FF?J@ A J >FF; // dec!are >ariab!e 1"" "f #Fpe J C >"id #es#?@ A >FFB?i&#@ = 3; C

// i&s#ead "f 1""B?i&#@$1""

Tuple Parameters
-f the last te%plate para%eter in the 'emplateParameterList is declared as a 'emplate'upleParameter4 it is a %atch 7ith any trailin$ te%plate ar$u%ents. The se9uence of ar$u%ents for% a 'uple. ! 'uple is not a type4 an expression4 or a sy%"ol. -t is a se9uence of any %ix of types4 expressions or sy%"ols. ! 'uple 7hose ele%ents consist entirely of types is called a 'ype'uple. ! 'uple 7hose ele%ents consist entirely of expressions is called an Expression'uple. ! 'uple can "e used as an ar$u%ent list to instantiate another te%plate4 or as the list of para%eters for a function.

D Specification
#e0p!a#e Rri&#?A $$$@ A >"id pri&#?@ A ,ri#ef!&?"ar's are ") A@; C C #e0p!a#e Kri#e?A $$$@ A >"id ,ri#e?A a@ A C C >"id 0ai&?@ A Rri&#B?1)'a')3$9@$pri&#?@; // pri&#s: ar's are 1a3$9 Kri#eB?i&#) c ar) d"ub!e@$,ri#e?1) 'a') 3$9@; // pri&#s: ar's are 1a3$9 C

1&#

// A is a TypeT&ple // a is a& E+pressionT&ple

,ri#ef!&?"ar's are ") a@;

Te%plate tuples can "e deduced fro% the types of the trailin$ para%eters of an i%plicitly instantiated function te%plate?
#e0p!a#e 1""?J) \$$$@ A >"id 1""?J #) \ r@ A ,ri#ef!&?#@; s#a#ic if ?r$!e&'# @ 1""?r@; C C >"id 0ai&?@ A 1""?1) 'a') 3$9@; C

// if 0"re ar'u0e&#s // d" # e res# "f # e ar'u0e&#s

prints?
1 a 3$9

The tuple can also "e deduced fro% the type of a dele$ate or function para%eter list passed as a function ar$u%ent?
/* \ is re#ur& #Fpe * A is firs# ar'u0e&# #Fpe * - is TypeT&ple "f res# "f ar'u0e&# #Fpes */ \ de!e'a#e?-@ CurrF?\) A) -$$$@?\ de!e'a#e?A) -@ d') A ar'@ A s#ruc# 1"" A #Fpe"f?d'@ d'60; #Fpe"f?ar'@ ar'60;

1&*
\ bar?- u@ A re#ur& d'60?ar'60) u@; C

D Specification

1""* f = &e, 1""; f$d'60 = d'; f$ar'60 = ar'; re#ur& .f$bar;

>"id 0ai&?@ A i&# p!us?i&# %) i&# F) i&# I@ A re#ur& % + F + I; C au#" p!us6#," = CurrF?.p!us) 2@; pri&#f?"Nd\&") p!us6#,"?3) 9@@; C // pri&#s 13

The nu%"er of ele%ents in a 'uple can "e retrie)ed 7ith the -length property. The nth ele%ent can "e retrie)ed "y indexin$ the 'uple 7ith HnI4 and su" tuples can "e created 7ith the slicin$ syntax. 'uples are static co%pile ti%e entities4 there is no 7ay to dyna%ically chan$e4 add4 or re%o)e ele%ents. -f "oth a te%plate 7ith a tuple para%eter and a te%plate 7ithout a tuple para%eter exactly %atch a te%plate instantiation4 the te%plate 7ithout a 'emplate'upleParameter is selected.

Class Templates
ClassTemplate%eclaration: *C!BB Identifier ( Template,arameterList ) 4S&perClass A, InterfaceClass C5 ClassBody

-f a te%plate declares exactly one %e%"er4 and that %e%"er is a class 7ith the sa%e na%e as the te%plate?
#e0p!a#e .!r?J@ A c!ass .!r A J 0e0ber; C C

then the se%antic e9ui)alent4 called a Class'emplate eclaration can "e 7ritten as?
c!ass .!r?J@ A J 0e0ber; C

D Specification

150

Function Templates
-f a te%plate declares exactly one %e%"er4 and that %e%"er is a function 7ith the sa%e na%e as the te%plate?
F&nctionTemplate%eclaration: Type Identifier ( Template,arameterList ) ( F&nction,arameterList )L F&nctionBody

! function te%plate to co%pute the s9uare of type ' is?


J SQ(!r9?J@?J #@ A re#ur& # * #; C

.unction te%plates can "e explicitly instantiated 7ith a =A'emplate(rgumentListB?


,ri#ef!&?"J e s+uare "f Ns is Ns") 3) L+uareB?i&#@?3@@;

or i%plicitly4 7here the 'emplate(rgumentList is deduced fro% the types of the function ar$u%ents?
,ri#ef!&?"J e s+uare "f Ns is Ns") 3) L+uare?3@@; // J is deduced #" be i&#

.unction te%plate type para%eters that are to "e i%plicitly deduced %ay not ha)e speciali5ations?
>"id >FF?J : J*@?J #@ A $$$ C i&# %)F; 1""B?i&#*@?%@; 1""?.F@; // "=) J is &"# deduced fr"0 fu&c#i"& ar'u0e&# // err"r) J as specia!iIa#i"&

Te%plate ar$u%ents not i%plicitly deduced can ha)e default )alues?


>"id >FF?J) -=J*@?J #@ A - p; $$$ C i&# %; 1""?.%@; // J is i&#) - is i&#*

,ecursi1e Templates
Te%plate features can "e co%"ined to produce so%e interestin$ effects4 such as co%pile ti%e e)aluation of non@tri)ial functions. .or exa%ple4 a factorial te%plate can "e 7ritten?
#e0p!a#e fac#"ria!?i&# & : 1@ A e&u0 A fac#"ria! = 1 C C #e0p!a#e fac#"ria!?i&# &@ A e&u0 A fac#"ria! = &* fac#"ria!B?&:1@ C C >"id #es#?@ A ,ri#ef!&?"Ns") fac#"ria!B?(@@; C

// pri&#s 2(

151

D Specification

Limitations
Te%plates cannot "e used to add non@static %e%"ers or functions to classes. .or exa%ple?
c!ass 1"" A #e0p!a#e JBar?J@ A J %%; i&# fu&c?J@ A $$$ C

// Err"r // Err"r // O= // O=

s#a#ic J FF; s#a#ic i&# fu&c?J #) i&# F@ A $$$ C C C

Te%plates cannot "e declared inside functions.

D Specification

152

Mixins
Mixins %ean different thin$s in different pro$ra%%in$ lan$ua$es. -n D4 a %ixin ta6es an ar"itrary set of declarations fro% the "ody of a 'emplate eclaration and inserts the% into the current context.
Template-i+in: EA'A$ TemplateIdentifier EA'A$ TemplateIdentifier EA'A$ TemplateIdentifier EA'A$ TemplateIdentifier -i+inIdentifier: Identifier ; -i+inIdentifier ; !( Template#rg&mentList ) ; !( Template#rg&mentList ) -i+inIdentifier ;

! 'emplateMixin can occur in declaration lists of %odules4 classes4 structs4 unions4 and as a state%ent. The 'emplateIdentifier refers to a 'emplate eclaration. -f the 'emplate eclaration has no para%eters4 the %ixin for% that has no =A'emplate(rgumentListB can "e used. ;nli6e a te%plate instantiation4 a te%plate %ixin:s "ody is e)aluated 7ithin the scope 7here the %ixin appears4 not 7here the te%plate declaration is defined. -t is analo$ous to cuttin$ and pastin$ the "ody of the te%plate into the location of the %ixin. -t is useful for in>ectin$ para%eteri5ed :"oilerplate: code4 as 7ell as for creatin$ te%plated nested functions4 7hich is not possi"le 7ith te%plate instantiations.
#e0p!a#e 1""?@ A i&# % = 7; C EA'A$L>FF; s#ruc# Bar A EA'A$L>FF; C >"id #es#?@ A pri&#f?"% = Nd\&") %@; A Bar b; i&# % = 3; pri&#f?"b$% = Nd\&") b$%@; pri&#f?"% = Nd\&") %@; A EA'A$L>FF; pri&#f?"% = Nd\&") %@; % = (; pri&#f?"% = Nd\&") %@; C pri&#f?"% = Nd\&") %@; C pri&#f?"% = Nd\&") %@; C

// pri&#s 7

// pri&#s 7 // pri&#s 3 // pri&#s 7 // pri&#s ( // pri&#s 3 // pri&#s 7

Mixins can "e para%eteri5ed?


#e0p!a#e 1""?J@

153
A C J % = 7; // crea#e % "f #Fpe i&#

D Specification

EA'A$L>FF!(A$%);

Mixins can add )irtual functions to a class?


#e0p!a#e 1""?@ A >"id fu&c?@ A pri&#f?"1""$fu&c?@\&"@; C C c!ass Bar A EA'A$L>FF; C c!ass C"de : Bar A >"id fu&c?@ A pri&#f?"C"de$fu&c?@\&"@; C C >"id #es#?@ A Bar b = &e, Bar?@; b$fu&c?@; b = &e, C"de?@; b$fu&c?@;

// ca!!s 1""$fu&c?@ // ca!!s C"de$fu&c?@

Mixins are e)aluated in the scope of 7here they appear4 not the scope of the te%plate declaration?
i&# F = 3; #e0p!a#e 1""?@ A i&# abc?@ A re#ur& F; C C >"id #es#?@ A i&# F = 9; EA'A$L>FF; // !"ca! F is pic=ed up) &"# '!"ba! F asser#?abc?@ == 9@; C

Mixins can para%eteri5e sy%"ols usin$ alias para%eters?


#e0p!a#e 1""?a!ias b@ A i&# abc?@ A re#ur& b; C C >"id #es#?@ A i&# F = 9; EA'A$L>FF!(G); asser#?abc?@ == 9@; C

D Specification

15&

This exa%ple uses a %ixin to i%ple%ent a $eneric Duff:s de)ice for an ar"itrary state%ent Ain this case4 the ar"itrary state%ent is in "oldB. ! nested function is $enerated as 7ell as a dele$ate literal4 these can "e inlined "y the co%piler?
#e0p!a#e duffs6de>ice?a!ias id1) a!ias id2) a!ias s@ A >"id duff6!""p?@ A if ?id1 U id2@ A #Fpe"f?id1@ & = ?id2 : id1 + 8@ / 9; s,i#c ??id2 : id1@ N 9@ A case 0: d" A s?@; case 8: s?@; case 3: s?@; case 7: s?@; case (: s?@; case 3: s?@; case 2: s?@; case 1: s?@; C , i!e ?::& > 0@; C C C C >"id f""?@ A pri&#f?"f""\&"@; C >"id #es#?@ A i&# i = 1; i&# M = 11; 0i%i& duffs6de>iceB?i) M) ,9C9D!%9L{L#FF();L} @; duff6!""p?@; // e%ecu#es f""?@ 10 #i0es

Mixin Scope
The declarations in a %ixin are :i%ported: into the surroundin$ scope. -f the na%e of a declaration in a %ixin is the sa%e as a declaration in the surroundin$ scope4 the surroundin$ declaration o)errides the %ixin one?
i&# % = 3; #e0p!a#e 1""?@ A i&# % = 7; i&# F = 7; C EA'A$L>FF; i&# F = 3; >"id #es#?@ A pri&#f?"% = Nd\&") %@; pri&#f?"F = Nd\&") F@;

// pri&#s 3 // pri&#s 3

155
C

D Specification

-f t7o different %ixins are put in the sa%e scope4 and each define a declaration 7ith the sa%e na%e4 there is an a%"i$uity error 7hen the declaration is referenced?
#e0p!a#e 1""?@ A i&# % = 7; >"id fu&c?i&# %@ A C C #e0p!a#e Bar?@ A i&# % = (; >"id fu&c?@ A C C EA'A$L>FF; EA'A$L.!r; >"id #es#?@ A pri&#f?"% = Nd\&") %@; // err"r) % is a0bi'u"us fu&c?@; // err"r) fu&c is a0bi'u"us C

The call to func34 is a%"i$uous "ecause .oo.func and 3ar.func are in different scopes. -f a %ixin has a MixinIdentifier4 it can "e used to disa%"i$uate?
i&# % = 3; #e0p!a#e 1""?@ A i&# % = 7; i&# F = 8; >"id fu&c?@ A C C #e0p!a#e Bar?@ A i&# % = (; >"id fu&c?@ A C C EA'A$L>FFL>; EA'A$L.!rL.; >"id #es#?@ A pri&#f?"F = pri&#f?"% = pri&#f?"1$% pri&#f?"B$% 1$fu&c?@; B$fu&c?@; C

Nd\&") F@; Nd\&") %@; = Nd\&") 1$%@; = Nd\&") B$%@;

// // // // // //

pri&#s 8 pri&#s 3 pri&#s 7 pri&#s ( ca!!s 1""$fu&c ca!!s Bar$fu&c

!lias declarations can "e used to o)erload to$ether functions declared in different %ixins?
#e0p!a#e 1""?@

D Specification
A C >"id fu&c?i&# %@ A C

15(

#e0p!a#e Bar?@ A >"id fu&c?@ A C 0i%i& 1""B?@ 1; 0i%i& BarB?@ B; !CA!BL>.#($*L#($*; !CA!BL..#($*L#($*; >"id 0ai&?@ A fu&c?@; fu&c?1@; C

// ca!!s B$fu&c // ca!!s 1$fu&c

! %ixin has its o7n scope4 e)en if a declaration is o)erridden "y the enclosin$ one?
i&# % = (; #e0p!a#e 1""?@ A i&# % = 7; i&# bar?@ A re#ur& %; C C EA'A$L>FF; >"id #es#?@ A pri&#f?"% = Nd\&") %@; pri&#f?"bar?@ = Nd\&") bar?@@; C

// pri&#s ( // pri&#s 7

157

D Specification

Contract Programming
,ontracts are a "rea6throu$h techni9ue to reduce the pro$ra%%in$ effort for lar$e pro>ects. ,ontracts are the concept of preconditions4 postconditions4 errors4 and in)ariants. ,ontracts can "e done in ,88 7ithout %odification to the lan$ua$e4 "ut the result is clu%sy and inconsistent. 3uildin$ contract support into the lan$ua$e %a6es for? 1. a consistent loo6 and feel for the contracts 2. tool support 3. it:s possi"le the co%piler can $enerate "etter code usin$ infor%ation $athered fro% the contracts &. easier %ana$e%ent and enforce%ent of contracts 5. handlin$ of contract inheritance

The idea of a contract is si%ple @ it:s >ust an expression that %ust e)aluate to true. -f it does not4 the contract is "ro6en4 and "y definition4 the pro$ra% has a "u$ in it. ,ontracts for% part of the specification for a pro$ra%4 %o)in$ it fro% the docu%entation to the code itself. !nd as e)ery pro$ra%%er 6no7s4 docu%entation tends to "e inco%plete4 out of date4 7ron$4 or non@existent. Mo)in$ the contracts into the code %a6es the% )erifia"le a$ainst the pro$ra%.

.ssert Contract
The %ost "asic contract is the assert. !n assert inserts a chec6a"le expression into the code4 and that expression %ust e)aluate to true?
asser#?e%pressi"&@;

, pro$ra%%ers 7ill find it fa%iliar. ;nli6e ,4 ho7e)er4 an asser# in function "odies 7or6s "y thro7in$ an Asser#Err"r4 7hich can "e cau$ht and handled. ,atchin$ the contract )iolation is useful 7hen the code %ust deal 7ith errant uses "y other code4 7hen it %ust "e failure proof4 and as a useful tool for de"u$$in$.

Pre and Post Contracts


The pre contracts specify the preconditions "efore a state%ent is executed. The %ost typical use of this 7ould "e in )alidatin$ the para%eters to a function. The post contracts )alidate the result of the state%ent. The %ost typical use of this 7ould "e in )alidatin$ the return )alue of a function and of any side effects it has. The syntax is?
i& A

D Specification
$$$c"&#rac# prec"&di#i"&s$$$ C "u# ?resu!#@ A $$$c"&#rac# p"s#c"&di#i"&s$$$ C b"dF A $$$c"de$$$ C

15#

3y definition4 if a pre contract fails4 then the "ody recei)ed "ad para%eters. !n !ssert'rror is thro7n. -f a post contract fails4 then there is a "u$ in the "ody. !n !ssert'rror is thro7n. 'ither the i& or the "u# clause can "e o%itted. -f the "u# clause is for a function "ody4 the )aria"le resu!# is declared and assi$ned the return )alue of the function. .or exa%ple4 let:s i%ple%ent a s9uare root function?
!"&' s+uare6r""#?!"&' %@ i& A asser#?% >= 0@; C "u# ?resu!#@ A asser#??resu!# * resu!#@ U= % .. ?resu!#+1@ * ?resu!#+1@ >= %@; C b"dF A re#ur& cas#?!"&'@s#d$0a# $s+r#?cas#?rea!@%@; C

The assert:s in the in and out "odies are called contracts. !ny other D state%ent or expression is allo7ed in the "odies4 "ut it is i%portant to ensure that the code has no side effects4 and that the release )ersion of the code 7ill not depend on any effects of the code. .or a release "uild of the code4 the in and out code is not inserted. -f the function returns a )oid4 there is no result4 and so there can "e no result declaration in the out clause. -n that case4 use?
>"id fu&c?@ "u# A $$$c"&#rac#s$$$ C b"dF A $$$ C

-n an out state%ent4 result is initiali5ed and set to the return )alue of the function.

"n& Out and "nheritance


-f a function in a deri)ed class o)errides a function in its super class4 then only one of the i& contracts of the function and its "ase functions %ust "e satisfied. /)erridin$ functions then "eco%es a process of loosening the i& contracts.

15*

D Specification

! function 7ithout an i& contract %eans that any )alues of the function para%eters are allo7ed. This i%plies that if any function in an inheritance hierarchy has no i& contract4 then i& contracts on functions o)erridin$ it ha)e no useful effect. ,on)ersely4 all of the "u# contracts needs to "e satisfied4 so o)erridin$ functions "eco%es a processes of tightening the "u# contracts.

Class "n1ariants
,lass in)ariants are used to specify characteristics of a class that al7ays %ust "e true Aexcept 7hile executin$ a %e%"er functionB. They are descri"ed in ,lasses.

D Specification

1(0

Conditional Compilation
Conditional compilation is the process of selectin$ 7hich code to co%pile and 7hich code to not co%pile. A-n , and ,884 conditional co%pilation is done 7ith the preprocessor directi)es <if / <else / <endif.B
Conditional%eclaration: Condition %eclarationBlock Condition %eclarationBlock 9CB9 %eclarationBlock Condition : %eclarations %eclarationBlock: %eclaration { %eclarations } {L} %eclarations: %eclaration %eclaration %eclarations ConditionalStatement: Condition NoScopeNonEmptyStatement Condition NoScopeNonEmptyStatement 9CB9 NoScopeNonEmptyStatement

-f the Condition is satisfied4 then the follo7in$ eclaration+lock or $tatement is co%piled in. -f it is not satisfied4 the eclaration+lock or $tatement after the optional else is co%piled in. !ny eclaration+lock or $tatement that is not co%piled in still %ust "e syntactically correct. 2o ne7 scope is introduced4 e)en if the eclaration+lock or $tatement is enclosed "y G H. Conditional eclarations and Conditional$tatements can "e nested. The $tatic(ssert can "e used to issue errors at co%pilation ti%e for "ranches of the conditional co%pilation that are errors. Condition co%es in the follo7in$ for%s?
Condition: .ersionCondition %e'&gCondition StaticIfCondition

5ersion Condition
Mersions ena"le %ultiple )ersions of a %odule to "e i%ple%ented 7ith a sin$le source file.
.ersionCondition: &9rBAF$L( Integer ) &9rBAF$L( Identifier )

The %ersionCondition is satisfied if the Integer is $reater than or e9ual to the current "ersion le"el4 or if Identifier %atches a "ersion identifier. The "ersion le"el and "ersion identifier can "e set on the co%%and line "y the )1ersion s7itch or in the %odule itself 7ith a %ersion$pecification4 or they can "e predefined "y the co%piler. Mersion identifiers are in their o7n uni9ue na%e space4 they do not conflict 7ith de"u$ identifiers or other sy%"ols in the %odule. Mersion identifiers defined in one %odule ha)e no influence o)er other i%ported %odules.

1(1
i&# =; >ersi"& ?De0"@ A i&# i; i&# =; i = 3; C % = i; // c"0pi!e i& # is c"de b!"c= f"r # e de0" >ersi"& // err"r) = a!readF defi&ed

D Specification

// uses # e i dec!ared ab">e

>ersi"& ?W93@ A $$$ // i0p!e0e&# cus#"0 i&!i&e asse0b!er >ersi"& C e!se A $$$ // use defau!#) bu# s!",) >ersi"& C

5ersion Specification
.ersionSpecification &9rBAF$L= Identifier ; &9rBAF$L= Integer ;

The )ersion specification %a6es it strai$htfor7ard to $roup a set of features under one %a>or )ersion4 for exa%ple?
>ersi"& ?Rr"fessi"&a!Edi#i"&@ A >ersi"& = 1ea#ureA; >ersi"& = 1ea#ureB; >ersi"& = 1ea#ureC; C >ersi"& ?Y"0eEdi#i"&@ A >ersi"& = 1ea#ureA; C $$$ >ersi"& ?1ea#ureB@ A $$$ i0p!e0e&# 1ea#ure B $$$ C

Mersion identifiers or le)els %ay not "e for7ard referenced?


>ersi"& ?1""@ A i&# %; C >ersi"& = 1"";

// err"r) 1"" a!readF used

Dhile the de"u$ and )ersion conditions superficially "eha)e the sa%e4 they are intended for )ery different purposes. De"u$ state%ents are for addin$ de"u$ code that is re%o)ed for the release )ersion. Mersion state%ents are to aid in porta"ility and %ultiple release )ersions. 0ere:s an exa%ple of a full )ersion as opposed to a demo )ersion?
c!ass 1"" A

D Specification
i&# a) b; >ersi"&?fu!!@ A i&# e%#rafu&c#i"&a!i#F?@ A $$$ re#ur& 1; // e%#ra fu&c#i"&a!i#F is supp"r#ed C C e!se // de0" A i&# e%#rafu&c#i"&a!i#F?@ A re#ur& 0; // e%#ra fu&c#i"&a!i#F is &"# supp"r#ed C C C

1(2

Marious different )ersion "uilds can "e "uilt 7ith a para%eter to )ersion?
>ersi"&?n@ // add i& >ersi"& c"de if >ersi"& !e>e! is >= n A $$$ >ersi"& c"de $$$ C >ersi"&?identifier@ // add i& >ersi"& c"de if >ersi"& // =eF,"rd is identifier A $$$ >ersi"& c"de $$$ C

These are presu%a"ly set "y the co%%and line as :>ersi"&=n and :>ersi"&=identifier.

Predefined 5ersions
Se)eral en)iron%ental )ersion identifiers and identifier na%e spaces are predefined for consistent usa$e. Mersion identifiers do not conflict 7ith other identifiers in the code4 they are in a separate na%e space. redefined )ersion identifiers are $lo"al4 i.e. they apply to all %odules "ein$ co%piled and i%ported. %igitalMars Di$ital Mars is the co%piler )endor 7IJ -ntel and !MD 32 "it processors 7IJ#JK !MD and -ntel (& "it processors indo$s Microsoft Dindo7s syste%s inLM Microsoft 32 "it Dindo7s syste%s inJK Microsoft (& "it Dindo7s syste%s linux !ll linux syste%s LittleEndian

1(3 3yte order4 least si$nificant first BigEndian 3yte order4 %ost si$nificant first %#Co1erage ,o)era$e analyser is i%ple%ented and the )co1 s7itch is thro7n %#"nline.sm#7IJ -nline asse%"ler for T#( is i%ple%ented none 2e)er definedS used to >ust disa"le a section of code all !l7ays definedS used as the opposite of none /thers 7ill "e added as they %a6e sense and ne7 i%ple%entations appear.

D Specification

-t is ine)ita"le that the D lan$ua$e 7ill e)ol)e o)er ti%e. Therefore4 the )ersion identifier na%espace "e$innin$ 7ith CDJC is reser)ed for identifiers indicatin$ D lan$ua$e specification or ne7 feature confor%ance. .urther%ore4 predefined )ersion identifiers fro% this list cannot "e set fro% the co%%and line or fro% )ersion state%ents. AThis pre)ents thin$s li6e "oth indo$s and linux "ein$ si%ultaneously set.B ,o%piler )endor specific )ersions can "e predefined if the trade%ar6ed )endor identifier prefixes it4 as in?
>ersi"&?Di'i#a!Sars6fu&=F6e%#e&si"&@ A $$$ C

-t is i%portant to use the ri$ht )ersion identifier for the ri$ht purpose. .or exa%ple4 use the )endor identifier 7hen usin$ a )endor specific feature. ;se the operatin$ syste% identifier 7hen usin$ an operatin$ syste% specific feature4 etc.

%e0ug Condition
T7o )ersions of pro$ra%s are co%%only "uilt4 a release "uild and a de"u$ "uild. The de"u$ "uild includes extra error chec6in$ code4 test harnesses4 pretty@printin$ code4 etc. The de"u$ state%ent conditionally co%piles in its state%ent "ody. -t is D:s 7ay of 7hat in , is done 7ith <ifdef D'3;1 / <endif pairs.
%e'&gCondition: ,9"(D ,9"(DL( Integer ) ,9"(DL( Identifier )

The de0ug condition is satisfied 7hen the )de0ug s7itch is thro7n on the co%piler. The de0ug 3 Integer 4 condition is satisfied 7hen the de"u$ le)el is VQ Integer. The de0ug 3 Identifier 4 condition is satisfied 7hen the de"u$ identifier %atches Identifier.
c!ass 1"" A i&# a) b; debu': i&# f!a';

D Specification
C

1(&

%e0ug Specification
%e'&gSpecification ,9"(DL= Identifier ; ,9"(DL= Integer ;

De"u$ identifiers and le)els are set either "y the co%%and line s7itch )de0ug or "y a e#ug$pecification. De"u$ specifications only affect the %odule they appear in4 they do not affect any i%ported %odules. De"u$ identifiers are in their o7n na%espace4 independent fro% )ersion identifiers and other sy%"ols. -t is ille$al to for7ard reference a de"u$ specification?
debu' ?f""@ pri&#f?"1""\&"@; debu' = f""; // err"r) f"" used bef"re se#

Marious different de"u$ "uilds can "e "uilt 7ith a para%eter to de"u$?
debu'?Integer@ A C // add i& debu' c"de if debu' !e>e! is >= Integer debu'?identifier@ A C // add i& debu' c"de if debu' =eF,"rd is identifier

These are presu%a"ly set "y the co%%and line as :debu'=n and :debu'=identifier.

Static "f Condition


StaticIfCondition: B%!%A*LA#L( #ssignE+pression )

(ssignExpression is i%plicitly con)erted to a "oolean type4 and is e)aluated at co%pile ti%e. The condition is satisfied if it e)aluates to true. -t is not satisfied if it e)aluates to false. -t is an error if (ssignExpression cannot "e i%plicitly con)erted to a "oolean type or if it cannot "e e)aluated at co%pile ti%e. $taticIfConditions can appear in %odule4 class4 te%plate4 struct4 union4 or function scope. -n function scope4 the sy%"ols referred to in the (ssignExpression can "e any that can nor%ally "e referenced "y an expression at that point.
c"&s# i&# i = 3; i&# M = (; B%!%A*LA# ?i == 3@ i&# %; c!ass C A c"&s# i&# = = 7; B%!%A*LA# ?i == 3@ i&# %; 9CB9 !"&' %; B%!%A*LA# ?M == 3@ i&# F; // "= // "=) a# 0"du!e sc"pe

// err"r) M is &"# a c"&s#a&#

1(5
B%!%A*LA# ?= == 7@ i&# I; C #e0p!a#e XHJ?i&# i@ A B%!%A*LA# ?i == 32@ a!ias i&# XHJ; 9CB9LB%!%A*LA# ?i == 13@ a!ias s "r# XHJ; 9CB9 s#a#ic asser#?0@; C XHJB?32@ a; XHJB?13@ b; XHJB?18@ c; // "=) = is i& curre&# sc"pe

D Specification

// &"# supp"r#ed

// a is a& i&# // b is a s "r# // err"r) s#a#ic asser# #rips

! $taticIfConditional condition differs fro% an If$tatement in the follo7in$ 7ays? 1. -t can "e used to conditionally co%pile declarations4 not >ust state%ents. 2. -t does not introduce a ne7 scope e)en if G H are used for conditionally co%piled state%ents. 3. .or unsatisfied conditions4 the conditionally co%piled code need only "e syntactically correct. -t does not ha)e to "e se%antically correct. &. -t %ust "e e)aluata"le at co%pile ti%e.

Static .ssert
Static#ssert: B%!%A*L!BB9r%L( #ssignE+pression ); B%!%A*L!BB9r%L( #ssignE+pression , #ssignE+pression );

(ssignExpression is e)aluated at co%pile ti%e4 and con)erted to a "oolean )alue. -f the )alue is true4 the static assert is i$nored. -f the )alue is false4 an error dia$nostic is issued and the co%pile fails. ;nli6e (ssertExpressions4 $tatic(sserts are al7ays chec6ed and e)aluted "y the co%piler unless they appear in an unsatisfied conditional.
>"id f""?@ A if ?0@ A asser#?0@; // &e>er #rips s#a#ic asser#?0@; // a!,aFs #rips C >ersi"& ?BA\@ A C e!se A s#a#ic asser#?0@; // #rips , e& >ersi"& BA\ is &"# defi&ed C C

$tatic(ssert is useful tool for dra7in$ attention to conditional confi$urations not supported in the code.

D Specification

1((

The optional second (ssertExpression can "e used to supply additional infor%ation4 such as a text strin$4 that 7ill "e printed out alon$ 7ith the error dia$nostic.

1(7

D Specification

Error %andling in D
- ca%e4 - coded4 - crashed. @@ [ulius ,:ster !ll pro$ra%s ha)e to deal 7ith errors. 'rrors are unexpected conditions that are not part of the nor%al operation of a pro$ra%. 'xa%ples of co%%on errors are?

/ut of %e%ory. /ut of dis6 space. -n)alid file na%e. !tte%ptin$ to 7rite to a read@only file. !tte%ptin$ to read a non@existent file. Le9uestin$ a syste% ser)ice that is not supported.

The Error Bandling Pro0lem


The traditional , 7ay of detectin$ and reportin$ errors is not traditional4 it is ad@hoc and )aries fro% function to function4 includin$?

Leturnin$ a 2;LL pointer. Leturnin$ a 0 )alue. Leturnin$ a non@5ero error code. Le9uirin$ errno to "e chec6ed. Le9uirin$ that a function "e called to chec6 if the pre)ious function failed.

To deal 7ith these possi"le errors4 tedious error handlin$ code %ust "e added to each function call. -f an error happened4 code %ust "e 7ritten to reco)er fro% the error4 and the error %ust "e reported to the user in so%e user friendly fashion. -f an error cannot "e handled locally4 it %ust "e explicitly propa$ated "ac6 to its caller. The lon$ list of errno )alues needs to "e con)erted into appropriate text to "e displayed. !ddin$ all the code to do this can consu%e a lar$e part of the ti%e spent codin$ a pro>ect @ and still4 if a ne7 errno )alue is added to the runti%e syste%4 the old code can not properly display a %eanin$ful error %essa$e. 1ood error handlin$ code tends to clutter up 7hat other7ise 7ould "e a neat and clean loo6in$ i%ple%entation. ')en 7orse4 $ood error handlin$ code is itself error prone4 tends to "e the least tested Aand therefore "u$$yB part of the pro>ect4 and is fre9uently si%ply o%itted. The end result is li6ely a C"lue screen of deathC as the pro$ra% failed to deal 7ith so%e unanticipated error. \uic6 and dirty pro$ra%s are not 7orth 7ritin$ tedious error handlin$ code for4 and so such utilities tend to "e li6e usin$ a ta"le sa7 7ith no "lade $uards. Dhat:s needed is an error handlin$ philosophy and %ethodolo$y such that?

-t is standardi5ed @ consistent usa$e %a6es it %ore useful. The result is reasona"le e)en if the pro$ra%%er fails to chec6 for errors. /ld code can "e reused 7ith ne7 code 7ithout ha)in$ to %odify the old code to "e co%pati"le 7ith ne7 error types. 2o errors $et inad)ertently i$nored. :\uic6 and dirty: utilities can "e 7ritten that still correctly handle errors. -t is easy to %a6e the error handlin$ source code loo6 $ood.

D Specification

1(#

The % Error Bandling Solution


Let:s first %a6e so%e o"ser)ations and assu%ptions a"out errors?

'rrors are not part of the nor%al flo7 of a pro$ra%. 'rrors are exceptional4 unusual4 and unexpected. 3ecause errors are unusual4 execution of error handlin$ code is not perfor%ance critical. The nor%al flo7 of pro$ra% lo$ic is perfor%ance critical. !ll errors %ust "e dealt 7ith in so%e 7ay4 either "y code explicitly 7ritten to handle the%4 or "y so%e syste% default handlin$. The code that detects an error 6no7s %ore a"out the error than the code that %ust reco)er fro% the error.

The solution is to use exception handlin$ to report errors. !ll errors are o">ects deri)ed fro% a"stract class 'rror. class 'rror has a pure )irtual function called toStrin$AB 7hich produces a charHI 7ith a hu%an reada"le description of the error. -f code detects an error li6e Cout of %e%ory4C then an 'rror is thro7n 7ith a %essa$e sayin$ C/ut of %e%oryC. The function call stac6 is un7ound4 loo6in$ for a handler for the 'rror. .inally "loc6s are executed as the stac6 is un7ound. -f an error handler is found4 execution resu%es there. -f not4 the default 'rror handler is run4 7hich displays the %essa$e and ter%inates the pro$ra%. 0o7 does this %eet our criteriaR -t is standardi5ed @ consistent usa$e %a6es it %ore useful. This is the D 7ay4 and is used consistently in the D runti%e li"rary and exa%ples. The result is reasona"le result e)en if the pro$ra%%er fails to chec6 for errors. -f no catch handlers are there for the errors4 then the pro$ra% $racefully exits throu$h the default error handler 7ith an appropriate %essa$e. /ld code can "e reused 7ith ne7 code 7ithout ha)in$ to %odify the old code to "e co%pati"le 7ith ne7 error types. /ld code can decide to catch all errors4 or only specific ones4 propa$atin$ the rest up7ards. -n any case4 there is no %ore need to correlate error nu%"ers 7ith %essa$es4 the correct %essa$e is al7ays supplied. 2o errors $et inad)ertently i$nored. 'rror exceptions $et handled one 7ay or another. There is nothin$ li6e a 2;LL pointer return indicatin$ an error4 follo7ed "y tryin$ to use that 2;LL pointer. :\uic6 and dirty: utilities can "e 7ritten that still correctly handle errors. \uic6 and dirty code need not 7rite any error handlin$ code at all4 and don:t need to chec6 for errors. The errors 7ill "e cau$ht4 an appropriate %essa$e displayed4 and the pro$ra% $racefully shut do7n all "y default. -t is easy to %a6e the error handlin$ source code loo6 $ood. The try/catch/finally state%ents loo6 a lot nicer than endless if AerrorB $oto errorhandlerS state%ents. 0o7 does this %eet our assu%ptions a"out errorsR 'rrors are not part of the nor%al flo7 of a pro$ra%. 'rrors are exceptional4 unusual4 and unexpected. D exception handlin$ fits ri$ht in 7ith that. 3ecause errors are unusual4 execution of error handlin$ code is not perfor%ance critical. 'xception handlin$ stac6 un7indin$ is a relati)ely slo7 process. The nor%al flo7 of pro$ra% lo$ic is perfor%ance critical. Since the nor%al flo7 code does not ha)e to chec6 e)ery function call for error returns4 it can

1(*

D Specification

"e realistically faster to use exception handlin$ for the errors. !ll errors %ust "e dealt 7ith in so%e 7ay4 either "y code explicitly 7ritten to handle the%4 or "y so%e syste% default handlin$. -f there:s no handler for a particular error4 it is handled "y the runti%e li"rary default handler. -f an error is i$nored4 it is "ecause the pro$ra%%er specifically added code to i$nore an error4 7hich presu%a"ly %eans it 7as intentional. The code that detects an error 6no7s %ore a"out the error than the code that %ust reco)er fro% the error. There is no %ore need to translate error codes into hu%an reada"le strin$s4 the correct strin$ is $enerated "y the error detection code4 not the error reco)ery code. This also leads to consistent error %essa$es for the sa%e error "et7een applications. ;sin$ exceptions to handle errors leads to another issue @ ho7 to 7rite exception safe pro$ra%s. 0ere:s ho7.

D Specification

170

&arbage Collection
D is a fully $ar"a$e collected lan$ua$e. That %eans that it is ne)er necessary to free %e%ory. [ust allocate as needed4 and the $ar"a$e collector 7ill periodically return all unused %e%ory to the pool of a)aila"le %e%ory. , and ,88 pro$ra%%ers accusto%ed to explicitly %ana$in$ %e%ory allocation and deallocation 7ill li6ely "e s6eptical of the "enefits and efficacy of $ar"a$e collection. 'xperience "oth 7ith ne7 pro>ects 7ritten 7ith $ar"a$e collection in %ind4 and con)ertin$ existin$ pro>ects to $ar"a$e collection sho7s that?

1ar"a$e collected pro$ra%s are faster. This is counterintuiti)e4 "ut the reasons are? Leference countin$ is a co%%on solution to sol)e explicit %e%ory allocation pro"le%s. The code to i%ple%ent the incre%ent and decre%ent operations 7hene)er assi$n%ents are %ade is one source of slo7do7n. 0idin$ it "ehind s%art pointer classes doesn:t help the speed. ALeference countin$ %ethods are not a $eneral solution any7ay4 as circular references ne)er $et deleted.B Destructors are used to deallocate resources ac9uired "y an o">ect. .or %ost classes4 this resource is allocated %e%ory. Dith $ar"a$e collection4 %ost destructors then "eco%e e%pty and can "e discarded entirely. !ll those destructors freein$ %e%ory can "eco%e si$nificant 7hen o">ects are allocated on the stac6. .or each one4 so%e %echanis% %ust "e esta"lished so that if an exception happens4 the destructors all $et called in each fra%e to release any %e%ory they hold. -f the destructors "eco%e irrele)ant4 then there:s no need to set up special stac6 fra%es to handle exceptions4 and the code runs faster. !ll the code necessary to %ana$e %e%ory can add up to 9uite a "it. The lar$er a pro$ra% is4 the less in the cache it is4 the %ore pa$in$ it does4 and the slo7er it runs. 1ar"a$e collection 6ic6s in only 7hen %e%ory $ets ti$ht. Dhen %e%ory is not ti$ht4 the pro$ra% runs at full speed and does not spend any ti%e freein$ %e%ory. Modern $ar"a$e collectors are far %ore ad)anced no7 than the older4 slo7er ones. 1enerational4 copyin$ collectors eli%inate %uch of the inefficiency of early %ar6 and s7eep al$orith%s. Modern $ar"a$e collectors do heap co%paction. 0eap co%paction tends to reduce the nu%"er of pa$es acti)ely referenced "y a pro$ra%4 7hich %eans that %e%ory accesses are %ore li6ely to "e cache hits and less s7appin$. 1ar"a$e collected pro$ra%s do not suffer fro% $radual deterioration due to an accu%ulation of %e%ory lea6s. 1ar"a$e collectors reclai% unused %e%ory4 therefore they do not suffer fro% C%e%ory lea6sC 7hich can cause lon$ runnin$ applications to $radually consu%e %ore and %ore %e%ory until they "rin$ do7n the syste%. 1, pro$ra%s ha)e lon$er ter% sta"ility. 1ar"a$e collected pro$ra%s ha)e fe7er hard@to@find pointer "u$s. This is "ecause there are no dan$lin$ references to freed %e%ory. There is no code to explicitly %ana$e %e%ory4 hence no "u$s in such code. 1ar"a$e collected pro$ra%s are faster to de)elop and de"u$4 "ecause there:s no need for de)elopin$4 de"u$$in$4 testin$4 or %aintainin$ the explicit deallocation code. 1ar"a$e collected pro$ra%s can "e si$nificantly s%aller4 "ecause there is no code to %ana$e deallocation4 and there is no need for exception handlers to deallocate %e%ory. -t is not predicta"le 7hen a collection $ets run4 so the pro$ra% can ar"itrarily pause. The ti%e it ta6es for a collection to run is not "ounded. Dhile in practice it is )ery 9uic64

1ar"a$e collection is not a panacea. There are so%e do7nsides?


171

D Specification this cannot "e $uaranteed. !ll threads other than the collector thread %ust "e halted 7hile the collection is in pro$ress. 1ar"a$e collectors can 6eep around so%e %e%ory that an explicit deallocator 7ould not. -n practice4 this is not %uch of an issue since explicit deallocators usually ha)e %e%ory lea6s causin$ the% to e)entually use far %ore %e%ory4 and "ecause explicit deallocators do not nor%ally return deallocated %e%ory to the operatin$ syste% any7ay4 instead >ust returnin$ it to its o7n internal pool. 1ar"a$e collection should "e i%ple%ented as a "asic operatin$ syste% 6ernel ser)ice. 3ut since they are not4 $ar"a$e collectin$ pro$ra%s %ust carry around 7ith the% the $ar"a$e collection i%ple%entation. Dhile this can "e a shared DLL4 it is still there.

These constraints are addressed "y techni9ues outlined in Me%ory Mana$e%ent.

Bo$ :ar0age Collection


The 1, 7or6s "y?

or!s

1. Loo6in$ for all the pointer :roots: into 1, allocated %e%ory. 2. Lecursi)ely scannin$ all allocated %e%ory pointed to "y roots loo6in$ for %ore pointers into 1, allocated %e%ory. 3. .reein$ all 1, allocated %e%ory that has no acti)e pointers to it. &. ossi"ly co%pactin$ the re%ainin$ used %e%ory "y copyin$ the allocated o">ects Acalled a copyin$ collectorB.

"nterfacing :ar0age Collected O0Nects


The $ar"a$e collector loo6s for roots in? 1. its static data se$%ent 2. the stac6s and re$ister contents of each thread 3. any roots added "y std.$c.addLootAB or std.$c.addLan$eAB

ith Foreign Code

-f the only root of an o">ect is held outside of this4 then the collecter 7ill %iss it and free the %e%ory. To a)oid this fro% happenin$4

Maintain a root to the o">ect in an area the collector does scan for roots. !dd a root to the o">ect usin$ std.$c.addLootAB or std.$c.addLan$eAB. Leallocate and copy the o">ect usin$ the forei$n code:s stora$e allocator or usin$ the , runti%e li"rary:s %alloc/free.

Pointers and the :ar0age Collector


ointers in D can "e "roadly di)ided into t7o cate$ories? those that point to $ar"a$e collected %e%ory4 and those that do not. 'xa%ples of the latter are pointers created "y calls to ,:s %allocAB4 pointers recei)ed fro% , li"rary routines4 pointers to static data4 pointers to o">ects on the stac64 etc. .or those pointers4 anythin$ that is le$al in , can "e done 7ith the%. .or $ar"a$e collected pointers and references4 ho7e)er4 there are so%e restrictions. These restrictions are %inor4 "ut they are intended to ena"le the %axi%u% flexi"ility in $ar"a$e collector desi$n. ;ndefined "eha)ior?

D Specification

172

Do not xor pointers 7ith other )alues4 li6e the xor pointer lin6ed list tric6 used in ,. Do not use the xor tric6 to s7ap t7o pointer )alues. Do not store pointers into non@pointer )aria"les usin$ casts and other tric6s.
>"id* p; $$$ i&# % = cas#?i&#@p; // err"r: u&defi&ed be a>i"r

The $ar"a$e collector does not scan non@pointer types for roots.

Do not ta6e ad)anta$e of ali$n%ent of pointers to store "it fla$s in the lo7 order "its?
p = cas#?>"id*@?cas#?i&#@p T 1@; // err"r: u&defi&ed be a>i"r

Do not store into pointers )alues that %ay point into the $ar"a$e collected heap?
p = cas#?>"id*@123(7389; // err"r: u&defi&ed be a>i"r

! copyin$ $ar"a$e collector %ay chan$e this )alue.


Do not store %a$ic )alues into pointers4 other than &u!!. Do not 7rite pointer )alues out to dis6 and read the% "ac6 in a$ain. Do not use pointer )alues to co%pute a hash function. ! copyin$ $ar"a$e collector can ar"itrarily %o)e o">ects around in %e%ory4 thus in)alidatin$ the co%puted hash )alue. Do not depend on the orderin$ of pointers?
if ?p1 U p2@ $$$ // err"r: u&defi&ed be a>i"r

since4 a$ain4 the $ar"a$e collector can %o)e o">ects around in %e%ory.

Do not add or su"tract an offset to a pointer such that the result points outside of the "ounds of the $ar"a$e collected o">ect ori$inally allocated.
c c + + ar* ar* = p = p p + + : = &e, c ar4105; = p + 3; // "= 11; // err"r: u&defi&ed be a>i"r 1; // err"r: u&defi&ed be a>i"r

Do not %isali$n pointers if those pointers %ay point into the $c heap4 such as?
a!i'& ?1@ s#ruc# 1"" A bF#e b; c ar* p; // 0isa!i'&ed p"i&#er C

Misali$ned pointers %ay "e used if the underlyin$ hard7are supports the% and the pointer is ne)er used to point into the $c heap.

Do not use "yte@"y@"yte %e%ory copies to copy pointer )alues. This %ay result in inter%ediate conditions 7here there is not a )alid pointer4 and if the $c pauses the thread in such a condition4 it can corrupt %e%ory. Most i%ple%entations of 0e0cpF?@ 7ill 7or6 since the internal i%ple%entation of it does the copy in ali$ned chun6s $reater than or e9ual to a pointer si5e4 "ut since this 6ind of i%ple%entation is not $uaranteed "y the , standard4 use 0e0cpF?@ only 7ith extre%e caution.

173 Thin$s that are relia"le and can "e done?

D Specification

;se a union to share stora$e 7ith a pointer?


u&i"& - A >"id* p#r; i&# >a!ue C

! pointer to the start of a $ar"a$e collected o">ect need not "e %aintained if a pointer to the interior of the o">ect exists.
c ar45 p = &e, c ar4105; c ar45 + = p43$$35; // + is e&"u' #" "!d "& #" # e "bMec#) d"&'# &eed #" =eep // p as ,e!!$

/ne can a)oid usin$ pointers any7ay for %ost tas6s. D pro)ides features renderin$ %ost explicit pointer uses o"solete4 such as reference o">ects4 dyna%ic arrays4 and $ar"a$e collection. ointers are pro)ided in order to interface successfully 7ith , ! -s and for so%e lo7 le)el 7or6.

or!ing $ith the :ar0age Collector


1ar"a$e collection doesn:t sol)e e)ery %e%ory deallocation pro"le%. .or exa%ple4 if a root to a lar$e data structure is 6ept4 the $ar"a$e collector cannot reclai% it4 e)en if it is ne)er referred to a$ain. To eli%inate this pro"le%4 it is $ood practice to set a reference or pointer to an o">ect to null 7hen no lon$er needed. This ad)ice applies only to static references or references e%"edded inside other o">ects. There is not %uch point for such stored on the stac6 to "e nulled4 since the collector doesn:t scan for roots past the top of the stac64 and "ecause ne7 stac6 fra%es are initiali5ed any7ay.

,eferences

Di6ipedia 1, .!\ ;niprocessor 1ar"a$e ,ollector Techni9ues 1ar"a$e ,ollection ? !l$orith%s for !uto%atic Dyna%ic Me%ory Mana$e%ent

D Specification

17&

#loating Point
Floating Point "ntermediate 5alues
/n %any co%puters4 $reater precision operations do not ta6e any lon$er than lesser precision operations4 so it %a6es nu%erical sense to use the $reatest precision a)aila"le for internal te%poraries. The philosophy is not to du%" do7n the lan$ua$e to the lo7est co%%on hard7are deno%inator4 "ut to ena"le the exploitation of the "est capa"ilities of tar$et hard7are. .or floatin$ point operations and expression inter%ediate )alues4 a $reater precision can "e used than the type of the expression. /nly the %ini%u% precision is set "y the types of the operands4 not the %axi%u%. "mplementation (ote2 /n -ntel x#( %achines4 for exa%ple4 it is expected A"ut not re9uiredB that the inter%ediate calculations "e done to the full #0 "its of precision i%ple%ented "y the hard7are. -t:s possi"le that4 due to $reater use of te%poraries and co%%on su"expressions4 opti%i5ed code %ay produce a %ore accurate ans7er than unopti%i5ed code. !l$orith%s should "e 7ritten to 7or6 "ased on the %ini%u% precision of the calculation. They should not de$rade or fail if the actual precision is $reater. .loat or dou"le types4 as opposed to the real AextendedB type4 should only "e used for?

reducin$ %e%ory consu%ption for lar$e arrays 7hen speed is %ore i%portant than accuracy data and function ar$u%ent co%pati"ility 7ith ,

Floating Point Constant Folding


Le$ardless of the type of the operands4 floatin$ point constant foldin$ is done in real or $reater precision. -t is al7ays done follo7in$ -''' 75& rules and round@to@nearest is used. .loatin$ point constants are internally represented in the i%ple%entation in at least real precision4 re$ardless of the constant:s type. The extra precision is a)aila"le for constant foldin$. ,o%%ittin$ to the precision of the result is done as late as possi"le in the co%pilation process. .or exa%ple?
c"&s# f!"a# f = 0$2f; ,ri#ef!&?f : 0$2@;

7ill print 0. ! non@const static )aria"le:s )alue cannot "e propa$ated at co%pile ti%e4 so?
s#a#ic f!"a# f = 0$2f; ,ri#ef!&?f : 0$2@;

7ill print 2.*#023e@0*. 0ex floatin$ point constants can also "e used 7hen specific floatin$ point "it patterns are needed that are unaffected "y roundin$. To find the hex )alue of 0.2f?
i0p"r# s#d$s#di"; >"id 0ai&?@ A ,ri#ef!&?"Na") 0$2f@; C

7hich is 0x1.*****ap@3. ;sin$ the hex constant?


c"&s# f!"a# f = 0%1$99999ap:3f;

175
,ri#ef!&?f : 0$2@;

D Specification

prints 2.*#023e@0*. Different co%piler settin$s4 opti%i5ation settin$s4 and inlinin$ settin$s can affect opportunities for constant foldin$4 therefore the results of floatin$ point calculations %ay differ dependin$ on those settin$s.

Complex and "maginary types


-n existin$ lan$ua$es4 there is an astonishin$ a%ount of effort expended in tryin$ to >a% a co%plex type onto existin$ type definition facilities? te%plates4 structs4 operator o)erloadin$4 etc.4 and it all usually ulti%ately fails. -t fails "ecause the se%antics of co%plex operations can "e su"tle4 and it fails "ecause the co%piler doesn:t 6no7 7hat the pro$ra%%er is tryin$ to do4 and so cannot opti%i5e the se%antic i%ple%entation. This is all done to a)oid addin$ a ne7 type. !ddin$ a ne7 type %eans that the co%piler can %a6e all the se%antics of co%plex 7or6 Cri$htC. The pro$ra%%er then can rely on a correct Aor at least fixa"le B i%ple%entation of co%plex. ,o%in$ 7ith the "a$$a$e of a co%plex type is the need for an i%a$inary type. !n i%a$inary type eli%inates so%e su"tle se%antic issues4 and i%pro)es perfor%ance "y not ha)in$ to perfor% extra operations on the i%plied 0 real part. -%a$inary literals ha)e an i suffix?
irea! M = 1$3i;

There is no particular co%plex literal syntax4 >ust add a real and i%a$inary type?
cd"ub!e cd = 3$3 + (i; crea! c = ($7 + 2i;

,o%plex4 real and i%a$inary nu%"ers ha)e t7o properties?


$re $i0 'e# rea! par# ?0 f"r i0a'i&arF &u0bers@ 'e# i0a'i&arF par# as a rea! ?0 f"r rea! &u0bers@

.or exa%ple?
cd$re cd$i0 c$re c$i0 M$i0 M$re is is is is is is ($7 d"ub!e 2 d"ub!e ($7 rea! 2 rea! 1$3 rea! 0 rea!

,ounding Control
-''' 75& floatin$ point arith%etic includes the a"ility to set & different roundin$ %odes. These are accessi"le )ia the functions in std.c.fen).

Exception Flags
-''' 75& floatin$ point arith%etic can set se)eral fla$s "ased on 7hat happened 7ith a co%putation?

D Specification .'J-2M!L-D .'JD'2/LM!L .'JD-M3]^'L/ .'J/M'L.L/D .'J;2D'L.L/D .'J-2'T!,T These fla$s can "e set/reset )ia the functions in std.c.fen).

17(

Floating Point Comparisons


-n addition to the usual U UQ V VQ QQ =Q co%parison operators4 D adds %ore that are specific to floatin$ point. These are =UVQ UV UVQ =UQ =U =VQ =V =UV and %atch the se%antics for the 2,'1 extensions to ,. See .loatin$ point co%parisons.

177

D Specification

D x'( nline Assembler


D4 "ein$ a syste%s pro$ra%%in$ lan$ua$e4 pro)ides an inline asse%"ler. The inline asse%"ler is standardi5ed for D i%ple%entations across the sa%e , ; fa%ily4 for exa%ple4 the -ntel entiu% inline asse%"ler for a Din32 D co%piler 7ill "e syntax co%pati"le 7ith the inline asse%"ler for Linux runnin$ on an -ntel entiu%. Differin$ D i%ple%entations4 ho7e)er4 are free to inno)ate upon the %e%ory %odel4 function call/return con)entions4 ar$u%ent passin$ con)entions4 etc. This docu%ent descri"es the x#( i%ple%entation of the inline asse%"ler.
#smInstr&ction: Identifier : #smInstr&ction !CAD$ IntegerE+pression 9&9$ $!H9, ," Operands ,B Operands ,A Operands ,C Operands ,# Operands ,, Operands ,9 Operands Opcode Opcode Operands Operands Operand Operand , Operands

La0els
!sse%"ler instructions can "e la"eled >ust li6e other state%ents. They can "e the tar$et of $oto state%ents. .or exa%ple?
>"id *pc; as0 A ca!! ;1 ;1: p"p EBW 0"> pc4EBR5)EBW C

; ; ; ;

// pc &", p"i&#s #" c"de a# ;1

align IntegerExpression
,auses the asse%"ler to e%it 2/ instructions to ali$n the next asse%"ler instruction on an IntegerExpression "oundary. IntegerExpression %ust e)aluate to an inte$er that is a po7er of 2. !li$nin$ the start of a loop "ody can so%eti%es ha)e a dra%atic effect on the execution speed.

D Specification

17#

e1en
,auses the asse%"ler to e%it 2/ instructions to ali$n the next asse%"ler instruction on an e)en "oundary.

na!ed
,auses the co%piler to not $enerate the function prolo$ and epilo$ se9uences. This %eans such is the responsi"ility of inline asse%"ly pro$ra%%er4 and is nor%ally used 7hen the entire function is to "e 7ritten in asse%"ler.

d0& ds& di& dl& df& dd& de


These pseudo ops are for insertin$ ra7 data directly into the code. d0 is for "ytes4 ds is for 1( "it 7ords4 di is for 32 "it 7ords4 dl is for (& "it 7ords4 df is for 32 "it floats4 dd is for (& "it dou"les4 and de is for #0 "it extended reals. 'ach can ha)e %ultiple operands. -f an operand is a strin$ literal4 it is as if there 7ere length operands4 7here length is the nu%"er of characters in the strin$. /ne character is used per operand. .or exa%ple?
as0 A db ds di d! df dd de db ds 7)3)0%93; 0%123(; 0%123(; 0%123(; 1$23(; 1$23(; 1$23(; "abc"; "abc"; // // // // // // // // // i&ser# i&ser# i&ser# i&ser# i&ser# i&ser# i&ser# i&ser# i&ser# bF#es bF#es bF#es bF#es 0%07) 0%3() 0%3() 0%3() 0%03) a&d 0%93 i&#" c"de 0%12 0%12) 0%00) 0%00 0%12) 0%00) 0%00) 0%00) 0%00) 0%00)

0%00

f!"a# 1$23( d"ub!e 1$23( rea! 1$23( bF#es 0%31) 0%32) a&d 0%33 bF#es 0%31) 0%00) 0%32) 0%00) 0%33) 0%00

Opcodes
! list of supported opcodes is at the end. The follo7in$ re$isters are supported. Le$ister na%es are al7ays in upper case. .L4 .B4 .74 E.7 BL4 BB4 B74 EB7 CL4 CB4 C74 EC7 %L4 %B4 %74 E%7 BP4 EBP SP4 ESP %"4 E%" S"4 ES" ES4 CS4 SS4 %S4 :S4 FS C,*4 C,M4 C,L4 C,K %,*4 %,O4 %,M4 %,L4 %,J4 %,P T,L4 T,K4 T,Q4 T,J4 T,P ST ST3*44 ST3O44 ST3M44 ST3L44 ST3K44 ST3Q44 ST3J44 ST3P4

17* MM*4 MMO4 MMM4 MML4 MMK4 MMQ4 MMJ4 MMP 7MM*4 7MMO4 7MMM4 7MML4 7MMK4 7MMQ4 7MMJ4 7MMP

D Specification

Special Cases
loc!4 rep4 repe4 repne4 repnz4 repz These prefix instructions do not appear in the sa%e state%ent as the instructions they prefixS they appear in their o7n state%ent. .or exa%ple?
as0 A C

rep ; 0">sb ;

pause This opcode is not supported "y the asse%"ler4 instead use
A C rep &"p ; ;

7hich produces the sa%e result. floating point ops ;se the t7o operand for% of the instruction for%atS
fdi> f0u! fdi> f0u! LJ?1@; LJ; LJ)LJ?1@; LJ)LJ?0@; // // // // ,r"&' ,r"&' ri' # ri' #

Operands
Operand: #smE+p #smE+p: #smLogOrE+p #smLogOrE+p ? #smE+p : #smE+p #smLogOrE+p: #smLog#ndE+p #smLog#ndE+p || #smLog#ndE+p #smLog#ndE+p: #smOrE+p #smOrE+p && #smOrE+p #smOrE+p: #sm2orE+p #sm2orE+p | #sm2orE+p #sm2orE+p: #sm#ndE+p

D Specification
#sm#ndE+p ^ #sm#ndE+p #sm#ndE+p: #smE)&alE+p #smE)&alE+p & #smE)&alE+p #smE)&alE+p: #sm3elE+p #sm3elE+p == #sm3elE+p #sm3elE+p != #sm3elE+p #sm3elE+p: #smShiftE+p #smShiftE+p #smShiftE+p #smShiftE+p #smShiftE+p

1#0

< #smShiftE+p <= #smShiftE+p > #smShiftE+p >= #smShiftE+p

#smShiftE+p: #sm#ddE+p #sm#ddE+p << #sm#ddE+p #sm#ddE+p >> #sm#ddE+p #sm#ddE+p >>> #sm#ddE+p #sm#ddE+p: #sm-&lE+p #sm-&lE+p + #sm-&lE+p #sm-&lE+p - #sm-&lE+p #sm-&lE+p: #smBrE+p #smBrE+p * #smBrE+p #smBrE+p / #smBrE+p #smBrE+p % #smBrE+p #smBrE+p: #sm!naE+p #smBrE+p [ #smE+p ] #sm!naE+p: #smType,refi+ #smE+p F##B9% #smE+p B9D #smE+p + #sm!naE+p - #sm!naE+p ! #sm!naE+p ~ #sm!naE+p #sm,rimaryE+p #sm,rimaryE+p IntegerConstant FloatConstant __-T;:-_SRU= $ 3egister %otIdentifier %otIdentifier Identifier Identifier . %otIdentifier

1#1

D Specification

The operand syntax %ore or less follo7s the -ntel , ; docu%entation con)entions. -n particular4 the con)ention is that for t7o operand instructions the source is the ri$ht operand and the destination is the left operand. The syntax differs fro% that of -ntel:s in order to "e co%pati"le 7ith the D lan$ua$e to6eni5er and to si%plify parsin$.

Operand Types
#smType,refi+: $9!rL?%r #!rL?%r "G%9L?%r BIFr%L?%r A$%L?%r +Fr,L?%r ,+Fr,L?%r #CF!%L?%r ,F("C9L?%r r9!CL?%r

-n cases 7here the operand si5e is a%"i$uous4 as in?


add 4EAW5)3 ;

it can "e disa%"i$uated "y usin$ an (sm'ypePrefix?


add add bF#e p#r 4EAW5)3 i&# p#r 4EAW5)8 ; ;

Struct>'nion>Class Mem0er Offsets


To access %e%"ers of an a$$re$ate4 $i)en a pointer to the a$$re$ate is in a re$ister4 use the 9ualified na%e of the %e%"er?
s#ruc# 1"" A i&# a)b)c; C i&# bar?1"" *f@ A as0 A 0"> EBW)f 0"> EAW)1""$b4EBW5 C C

; ;

Special Sym0ols
CC Lepresents the pro$ra% counter of the start of the next instruction. So4
M0p ] ;

"ranches to the instruction follo7in$ the >%p instruction. ##LOC.L#S"RE This $ets replaced "y the nu%"er of local "ytes in the local stac6 fra%e. -t is %ost handy 7hen the na!ed is in)o6ed and a custo% stac6 fra%e is pro$ra%%ed.

D Specification

1#2

Opcodes Supported
aaa add and arpl "t c"7 cli c%o)" c%o)$e c%o)n" c%o)n$e c%o)ns c%o)po c%pps c%ps7 cpuid c)tpd2ps c)tps2pi c)tss2sd c)ttps2pi da de di)pd d9 enter f"ld fc%o)"e fc%o)nu fco%p fdi) ffree fidi)r aad addpd andnpd "ound "tc cd9 clts c%o)"e c%o)l c%o)n"e c%o)nl c%o)n5 c%o)s c%ps c%pxch#" c)td92pd c)tpi2pd c)tsd2si c)tss2si c)ttsd2si daa dec di)ps ds f2x%1 f"stp fc%o)e fc%o)u fco%pp fdi)p fiadd fild aa% addps andnps "sf "tr clc c%c c%o)c c%o)le c%o)nc c%o)nle c%o)o c%o)5 c%ps" c%pxch$ c)td92ps c)tpi2ps c)tsd2ss c)ttpd2d9 c)ttss2si das df di)sd dt fa"s fchs fc%o)n" fco% fcos fdi)r fico% fi%ul aas addsd andpd "sr "ts cld c%o)a c%o)e c%o)na c%o)ne c%o)no c%o)p c%p c%psd co%isd c)tpd2d9 c)tps2d9 c)tsi2sd c)ttpd2pi c7d d" di di)ss d7 fadd fclex fc%o)n"e fco%i fdecstp fdi)rp fico%p fincstp adc addss andps "s7ap call clflush c%o)ae c%o)$ c%o)nae c%o)n$ c%o)np c%o)pe c%ppd c%pss co%iss c)tpd2pi c)tps2pd c)tsi2ss c)ttps2d9 c7de dd di) dl e%%s faddp fc%o)" fc%o)ne fco%ip fdisi feni fidi) finit

1#3 fist fld1 fldl$2 f%ulp fnop fpatan frstor fsincos fstp fsu"rp fuco%p fxrstor hlt ins into >a >cx5 >l >n" >n$e >ns >po ld%xcsr lfence lldt lodsd loopn5 %axss %inss %o)d929 %o)hps %o)%s6ps fistp fldc7 fldln2 fnclex fnsa)e fpre% fsa)e fs9rt fsts7 ftst fuco%pp fxsa)e idi) ins" in)d >ae >e >le >n"e >nl >n5 >s lds lfs l%s7 lods7 loop5 %fence %o) %o)d9a %o)lhps %o)ntd9 fisu" flden) fldpi fndisi fnstc7 fpre%1 fscale fst fsu" fuco% f7ait fxtract i%ul insd in)lp$ >" >ecx5 >%p >nc >nle >o >5 lea l$dt loc6 loop lsl %axpd %inpd %o)apd %o)d9u %o)lpd %o)nti fisu"r fldl2e fld5 fneni fnsten) fptan fsetp% fstc7 fsu"p fuco%i fxa% fyl2x in ins7 iret >"e >$ >na >ne >no >p lahf lea)e l$s lods loope lss %axps %inps %o)aps %o)hlps %o)lps %o)ntpd fld fldl2t f%ul fninit fnsts7 frndint fsin fsten) fsu"r fuco%ip fxch fyl2xp1 inc int iretd >c >$e >nae >n$ >np >pe lar les lidt lods" loopne ltr %axsd %insd %o)d %o)hpd %o)%s6pd %o)ntps

D Specification

%as6%o)d9u %as6%o)9

D Specification %o)nt9 %o)sd %o)ups %ulsd or outs" pac6us7" padds7 pandn pc%pe97 pinsr7 p%inu" p%ulud9 popfd prefetcht2 pshuf7 psrad psrl7 psu"s7 punpc6hd9 punpc6l9d9 pushf rcpss rep ret rs9rtps s"" seta sete setna setne setno setp %o)9 %o)ss %o)5x %ulss orpd outsd padd" paddus" pa)$" pc%p$t" p%add7d p%o)%s6" pop por psad"7 pslld psra7 psu"" psu"us" punpc6l7d pushfd rcr repe retf rs9rtss scas setae set$ setnae setn$ setnp setpe %o)92d9 %o)s7 %ul ne$ orps outs7 paddd paddus7 pa)$7 pc%p$td p%axs7 p%ulhu7 popa pshufd pslld9 psrld psu"d psu"us7 push pxor rd%sr repne rol sahf scas" set" set$e setn" setn$e setns setpo %o)s %o)sx %ulpd nop out pac6ssd7 padd9 padd7 pc%pe9" pc%p$t7 p%axu" p%ulh7 popad pshufh7 psll9 psrld9 psu"9 psu"7 pusha rcl rdp%c repn5 ror sal scasd set"e setl setn"e setnl setn5 sets %o)s" %o)upd %ulps not outs pac6ss7" padds" pand pc%pe9d pextr7 p%ins7 p%ull7 popf pshufl7 psll7 psrl9 psu"s" punpc6h"7 pushad rcpps rdtsc rep5 rs% sar scas7 setc setle setnc setnle seto set5

1#&

prefetchnta prefetcht0 prefetcht1

punpc6h9d9 punpc6h7d punpc6l"7 punpc6ld9

1#5 sfence shrd s%s7 stc stos" su"pd sysexit unpc6hpd )er7 xch$ xorps s$dt shufpd s9rtpd std stosd su"ps test unpc6hps 7ait xlat shl shufps s9rtps sti stos7 su"sd uco%isd unpc6lpd 7"in)d xlat" shld sidt s9rtsd st%xcsr str su"ss uco%iss unpc6lps 7r%sr xor shr sldt s9rtss stos su" sysenter ud2 )err xadd xorpd

D Specification

Pentium K 3Prescott4 Opcodes Supported


addsu"pd addsu"ps fisttp haddpd haddps hsu"pd hsu"ps ldd9u %onitor %o)ddup %o)shdup %o)sldup %7ait

.M% Opcodes Supported


pa)$us" pf2id pfnacc pfrs9it1 pfacc pfadd pfc%pe9 pf%ul pi2fd pfc%p$e pfc%p$t pf%ax pf%in pfrs9rt pfsu" pfsu"r

pfpnacc pfrcp pfrcpit1 pfrcpit2

p%ulhr7 ps7apd

D Specification

1#(

Embedded Documentation
The D pro$ra%%in$ lan$ua$e ena"les e%"eddin$ "oth contracts and test code alon$ side the actual code4 7hich helps to 6eep the% all consistent 7ith each other. /ne thin$ lac6in$ is the docu%entation4 as ordinary co%%ents are usually unsuita"le for auto%ated extraction and for%attin$ into %anual pa$es. '%"eddin$ the user docu%entation into the source code has i%portant ad)anta$es4 such as not ha)in$ to 7rite the docu%entation t7ice4 and the li6elihood of the docu%entation stayin$ consistent 7ith the code. So%e existin$ approaches to this are?

Doxy$en 7hich already has so%e support for D [a)a:s [a)adoc4 pro"a"ly the %ost 7ell@6no7n ,<:s e%"edded TML /ther docu%entation tools

D:s $oals for e%"edded docu%entation are? 1. -t loo6s $ood as e%"edded docu%entation4 not >ust after it is extracted and processed. 2. -t:s easy and natural to 7rite4 i.e. %ini%al reliance on Uta$sV and other clu%sy for%s one 7ould ne)er see in a finished docu%ent. 3. -t does not repeat infor%ation that the co%piler already 6no7s fro% parsin$ the code. &. -t doesn:t rely on e%"edded 0TML4 as such 7ill i%pede extraction and for%attin$ for other purposes. 5. -t:s "ased on existin$ D co%%ent for%s4 so it is co%pletely independent of parsers only interested in D code. (. -t should loo6 and feel different fro% code4 so it 7on:t "e )isually confused 7ith code. 7. -t should "e possi"le for the user to use Doxy$en or other docu%entation extractor if desired.

Specification
The specification for the for% of e%"edded docu%entation co%%ents only specifies ho7 infor%ation is to "e presented to the co%piler. -t is i%ple%entation@defined ho7 that infor%ation is used and the for% of the final presentation. Dhether the final presentation for% is an 0TML 7e" pa$e4 a %an pa$e4 a D. file4 etc. is not specified as part of the D ro$ra%%in$ Lan$ua$e.

Phases of Processing
'%"edded docu%entation co%%ents are processed in a series of phases? 1. 2. 3. &. 5. (. 7. Lexical @ docu%entation co%%ents are identified and attached to to6ens. arsin$ @ docu%entation co%%ents are associated 7ith specific declarations and co%"ined. Sections @ each docu%entation co%%ent is di)ided up into a se9uence of sections. Special sections are processed. 0i$hli$htin$ of non@special sections is done. !ll sections for the %odule are co%"ined. Macro text su"stitution is perfor%ed to produce the final result.

Lexical
'%"edded docu%entation co%%ents are one of the follo7in$ for%s?

1#7 1. /NN ... N/ The t7o N:s after the openin$ / 2. /88 ... 8/ The t7o 8:s after the openin$ / 3. /// The three slashes The follo7in$ are all e%"edded docu%entation co%%ents?
/// J is is a "&e !i&e d"cu0e&#a#i"& c"00e&#$ /** L" is # is$ */ /++ A&d # is$ +/ /** */ J is is a brief d"cu0e&#a#i"& c"00e&#$

D Specification

/** * J e !eadi&' * "& # is !i&e is &"# par# "f # e d"cu0e&#a#i"& c"00e&#$ */ /********************************* J e e%#ra *'s i00edia#e!F f"!!",i&' # e /** are &"# par# "f # e d"cu0e&#a#i"& c"00e&#$ */ /++ +/ /++ + J e !eadi&' + "& # is !i&e is &"# par# "f # e d"cu0e&#a#i"& c"00e&#$ +/ /+++++++++++++++++++++++++++++++++ J e e%#ra +'s i00edia#e!F f"!!",i&' # e / ++ are &"# par# "f # e d"cu0e&#a#i"& c"00e&#$ +/ /**************** C!"si&' *'s are &"# par# *****************/ J is is a brief d"cu0e&#a#i"& c"00e&#$

The extra N:s and 8:s on the co%%ent openin$4 closin$ and left %ar$in are i$nored and are not part of the e%"edded docu%entation. ,o%%ents not follo7in$ one of those for%s are not docu%entation co%%ents.

Parsing
'ach docu%entation co%%ent is associated 7ith a declaration. -f the docu%entation co%%ent is on a line "y itself or 7ith only 7hitespace to the left4 it refers to the next declaration. Multiple docu%entation co%%ents applyin$ to the sa%e declaration are concatenated. Docu%entation co%%ents not associated 7ith a declaration are i$nored. Docu%entation co%%ents precedin$ the Module eclaration apply to the entire %odule. -f the docu%entation co%%ent appears on the sa%e line to the ri$ht of a declaration4 it applies to that. -f a docu%entation co%%ent for a declaration consists only of the identifier di##" then the docu%entation co%%ent for the pre)ious declaration at the sa%e declaration scope is applied to this declaration as 7ell. -f there is no docu%entation co%%ent for a declaration4 that declaration %ay not appear in the

D Specification output. To ensure it does appear in the output4 put an e%pty declaration co%%ent for it.
i&# a; i&# b; /** /** i&# /** i&# /// d"cu0e&#a#i"& f"r a; b as &" d"cu0e&#a#i"&

1##

d"cu0e&#a#i"& f"r c a&d d */ 0"re d"cu0e&#a#i"& f"r c a&d d */ c; di##" */ d;

/** d"cu0e&#a#i"& f"r e a&d f */ i&# e; i&# f; /// di##" /** d"cu0e&#a#i"& f"r ' */ i&# '; /// 0"re d"cu0e&#a#i"& f"r ' /// d"cu0e&#a#i"& f"r C a&d D c!ass C A i&# %; /// d"cu0e&#a#i"& f"r C$% /** d"cu0e&#a#i"& f"r C$F a&d C$I */ i&# F; i&# I; /// di##" C /// di##" c!ass D A C

Sections
The docu%ent co%%ent is a series of $ections. ! $ection is a na%e that is the first non@"lan6 character on a line i%%ediately follo7ed "y a :?:. This na%e for%s the section na%e. The section na%e is not case sensiti)e. Summary The first section is the $ummary4 and does not ha)e a section na%e. -t is first para$raph4 up to a "lan6 line or a section na%e. Dhile the su%%ary can "e any len$th4 try to 6eep it to one line. The $ummary section is optional. %escription The next unna%ed section is the escription. -t consists of all the para$raphs follo7in$ the $ummary until a section na%e is encountered or the end of the co%%ent. Dhile the escription section is optional4 there cannot "e a escription 7ithout a $ummary section.
/*********************************** * Brief su00arF "f , a# * 0Ffu&c d"es) f"r0i&' # e su00arF sec#i"&$ * * 1irs# para'rap "f sF&"psis descrip#i"&$ * * Lec"&d para'rap "f * sF&"psis descrip#i"&$

1#*
*/ >"id 0Ffu&c?@ A C

D Specification

2a%ed sections follo7 the $ummary and escription unna%ed sections.

Standard Sections
.or consistency and predicta"ility4 there are se)eral standard sections. 2one of these are re9uired to "e present. .uthors2 Lists the authorAsB of the declaration.
/** * Au# "rs: Se!>i& D$ Herd) 0e!>i&^0ai!i&a#"r$c"0 */

Bugs2 Lists any 6no7n "u$s.


/** * Bu's: D"es&'# ,"r= f"r &e'a#i>e >a!ues$ */

%ate2 Specifies the date of the current re)ision. The date should "e in a for% parsea"le "y std.date.
/** * Da#e: Sarc */ 1() 2003

%eprecated2 ro)ides an explanation for and correcti)e action to ta6e if the associated declaration is %ar6ed as deprecated.
/** * Depreca#ed: superseded bF fu&c#i"& bar?@$ */ depreca#ed >"id f""?@ A $$$ C

Examples2 !ny usa$e exa%ples


/** * E%a0p!es: * :::::::::::::::::::: * ,ri#ef!&?"3"@; // ,ri#es '3' #" s#d"u# * :::::::::::::::::::: */

Bistory2 Le)ision history.

D Specification
/** * Yis#"rF: * Q1 is i&i#ia! >ersi"& * * Q2 added fea#ure W */

1*0

License2 !ny license infor%ation for copyri$hted code.


/** * ;ice&se: use free!F f"r a&F purp"se */ >"id bar?@ A $$$ C

,eturns2 'xplains the return )alue of the function. -f the function returns 1oid4 don:t redundantly docu%ent it.
/** * \ead # e fi!e$ * \e#ur&s: J e c"&#e&#s "f # e fi!e$ */ >"id45 read1i!e?c ar45 fi!e&a0e@ A $$$ C

See#.lso2 List of other sy%"ols and ;LL:s to related ite%s.


/** * Lee6A!s": * f"") bar) */

##p://,,,$di'i#a!0ars$c"0/d/p "b"s/i&de%$ #0!

Standards2 -f this declaration is co%pliant 7ith any particular standard4 the description of it $oes here.
/** * L#a&dards: C"&f"r0s #" DLREC:123( */

Thro$s2 Lists exceptions thro7n and under 7hat circu%stances they are thro7n.
/** * Kri#e # e fi!e$ * J r",s: Kri#eE%cep#i"& "& fai!ure$ */ >"id ,ri#e1i!e?c ar45 fi!e&a0e@ A $$$ C

5ersion2 Specifies the current )ersion of the declaration.

1*1
/** * Qersi"&: 1$3a */

D Specification

Special Sections
So%e sections ha)e speciali5ed %eanin$s and syntax. Copyright2 This contains the copyri$ht notice. The %acro ,/ ]L-10T is set to the contents of the section 7hen it docu%ents the %odule declaration. The copyri$ht section only $ets this special treat%ent 7hen it is for the %odule declaration.
/** C"pFri' #: Rub!ic D"0ai& */ 0"du!e f"";

Params2 .unction para%eters can "e docu%ented "y listin$ the% in a para%s section. 'ach line that starts 7ith an identifier follo7ed "y an :Q: starts a ne7 para%eter description. ! description can span %ultiple lines.
/*********************************** * f"" d"es # is$ * Rara0s: * % = is f"r # is * a&d &"# f"r # a# * F = is f"r # a# */ >"id f""?i&# %) i&# F@ A C

Macros2 The %acros section follo7s the sa%e syntax as the Params2 section. -t:s a series of !(MEQ"alue pairs. The !(ME is the %acro na%e4 and "alue is the replace%ent text.
/** * Sacr"s: * 1OO = * * BA\ = * SA[EHJA */

&", is # e #i0e f"r a!! '""d 0e& bar = .!#;f"&# c"!"r=0a'e&#a.'#;.!#;/f"&#.'#;

Bighlighting
Em0edded Comments The docu%entation co%%ents can the%sel)es "e co%%ented usin$ the WADD/,J,/MM'2T co%%ent textB syntax. These co%%ents do not nest.

D Specification Em0edded Code D code can "e e%"edded usin$ lines 7ith at least three hyphens in the% to delineate the code section?
/++++++++++++++++++++++++ + Our fu&c#i"&$ + E%a0p!e: + :::::::::::::::::::::::::: + i0p"r# s#d$s#di"; + + >"id f""?@ + A + ,ri#ef!&?"f""B"@; /* pri&# # e s#ri&' */ + C + :::::::::::::::::::::::::: +/

1*2

2ote that the docu%entation co%%ent uses the /88 ... 8/ for% so that /N ... N/ can "e used inside the code section. Em0edded BTML 0TML can "e e%"edded into the docu%entation co%%ents4 and it 7ill "e passed throu$h to the 0TML output unchan$ed. 0o7e)er4 since it is not necessarily true that 0TML 7ill "e the desired output for%at of the e%"edded docu%entation co%%ent extractor4 it is "est to a)oid usin$ it 7here practical.
/** E%a0p!e "f e0bedded YJS;: * * U!i> Ua ref=",,,$di'i#a!0ars$c"0">Di'i#a! SarsU/a> * U!i> Ua ref=",,,$c!assice0pire$c"0">E0pireU/a> * */

Emphasis -dentifiers in docu%entation co%%ents that are function para%eters or are na%es that are in scope at the associated declaration are e%phasi5ed in the output. This e%phasis can ta6e the for% of italics4 "oldface4 a hyperlin64 etc. 0o7 it is e%phasi5ed depends on 7hat it is @ a function para%eter4 type4 D 6ey7ord4 etc. To pre)ent unintended e%phasis of an identifier4 it can "e preceded "y an underscore AJB. The underscore 7ill "e stripped fro% the output. Character Entities So%e characters ha)e special %eanin$ to the docu%entation processor4 to a)oid confusion it can "e "est to replace the% 7ith their correspondin$ character entities? Character Entity U V +ltS +$tS

+ +a%pS -t is not necessary to do this inside a code section4 or if the special character is not i%%ediately follo7ed "y a < or a letter.

1*3

D Specification

Macros
The docu%entation co%%ent processor includes a si%ple %acro text preprocessor. Dhen a WA!(MEB appears in section text it is replaced 7ith !(ME:s correspondin$ replace%ent text. The replace%ent text is then recursi)ely scanned for %ore %acros. -f a %acro is recursi)ely encountered4 7ith no ar$u%ent or 7ith the sa%e ar$u%ent text as the enclosin$ %acro4 it is replaced 7ith no text. Macro in)ocations that cut across replace%ent text "oundaries are not expanded. -f the %acro na%e is undefined4 the replace%ent text has no characters in it. -f a WA2!M'B is desired to exist in the output 7ithout "ein$ %acro expanded4 the W should "e replaced 7ith +<3(S. Macros can ha)e ar$u%ents. !ny text fro% the end of the identifier to the closin$ :B: is the W0 ar$u%ent. ! W0 in the replace%ent text is replaced 7ith the ar$u%ent text. -f there are co%%as in the ar$u%ent text4 W1 7ill represent the ar$u%ent text up to the first co%%a4 W2 fro% the first co%%a to the second co%%a4 etc.4 up to W*. W8 represents the text fro% the first co%%a to the closin$ :B:. The ar$u%ent text can contain nested parentheses4 CC or :: strin$s4 co%%ents4 or ta$s. -f stray4 unnested parentheses are used4 they can "e replaced 7ith the entity +<&0S for A and +<&1S for B. Macro definitions co%e fro% the follo7in$ sources4 in the specified order? 1. 2. 3. &. 5. redefined %acros. Definitions fro% file specified "y sc.ini:s DD/,.-L' settin$. Definitions fro% N.ddoc files specified on the co%%and line. Lunti%e definitions $enerated "y Ddoc. Definitions fro% any Macros? sections.

Macro redefinitions replace pre)ious definitions of the sa%e na%e. This %eans that the se9uence of %acro definitions fro% the )arious sources for%s a hierarchy. Macro na%es "e$innin$ 7ith CDJC and CDD/,JC are reser)ed.

Predefined Macros
These are hard7ired into Ddoc4 and represent the %ini%al definitions needed "y Ddoc to for%at and hi$hli$ht the presentation. The definitions are for si%ple 0TML.
B = X = - = R = D; = DJ = DD = JAB;E = J\ = JY = JD = O; = -; = ;X = BX[ = LSA;; = B\ = ;XHP = ;XHP2 = \ED = B;-E = Ub>]0U/b> Ui>]0U/i> Uu>]0U/u> Up>]0U/p> Ud!>]0U/d!> Ud#>]0U/d#> Udd>]0U/dd> U#ab!e>]0U/#ab!e> U#r>]0U/#r> U# >]0U/# > U#d>]0U/#d> U"!>]0U/"!> Uu!>]0U/u!> U!i>]0U/!i> Ubi'>]0U/bi'> Us0a!!>]0U/s0a!!> Ubr> Ua ref="]0">]0U/a> Ua ref="]1">]+U/a> Uf"&# c"!"r=red>]0U/f"&#> Uf"&# c"!"r=b!ue>]0U/f"&#>

D Specification
[\EEH = Uf"&# VE;;OK =Uf"&# B;ACP = Uf"&# KYXJE = Uf"&# c"!"r='ree&>]0U/f"&#> c"!"r=Fe!!",>]0U/f"&#> c"!"r=b!ac=>]0U/f"&#> c"!"r=, i#e>]0U/f"&#>

1*&

D6CODE = Upre c!ass="d6c"de">]0U/pre> D6COSSEHJ = ]?[\EEH ]0@ D6LJ\XH[ = ]?\ED ]0@ D6PEVKO\D = ]?B;-E ]0@ D6RLVSBO; = ]?- ]0@ D6RA\AS = ]?X ]0@ DDOC = U #0!>U ead> USEJA ##p:e+ui>="c"&#e&#:#Fpe" c"&#e&#="#e%#/ #0!; c arse#=u#f:9"> U#i#!e>]?JXJ;E@U/#i#!e> U/ ead>Ub"dF> U 1>]?JXJ;E@U/ 1> ]?BODV@ U/b"dF>U/ #0!>

DDOC6COSSEHJ = DDOC6DEC; = DDOC6DEC;6DD = DDOC6DXJJO = DDOC6LECJXOHL = DDOC6L-SSA\V = DDOC6DELC\XRJXOH DDOC6A-JYO\L =

UB:: ]0 ::> ]?DJ ]?BX[ ]0@@ ]?DD ]0@ ]?B\@]0 ]0 ]0]?B\@]?B\@ = ]0]?B\@]?B\@ ]?B Au# "rs:@]?B\@ ]0]?B\@]?B\@ DDOC6B-[L = ]?\ED B-[L:@]?B\@ ]0]?B\@]?B\@ DDOC6CORV\X[YJ = ]?B C"pFri' #:@]?B\@ ]0]?B\@]?B\@ DDOC6DAJE = ]?B Da#e:@]?B\@ ]0]?B\@]?B\@ DDOC6DER\ECAJED = ]?\ED Depreca#ed:@]?B\@ ]0]?B\@]?B\@ DDOC6EWASR;EL = ]?B E%a0p!es:@]?B\@ ]0]?B\@]?B\@ DDOC6YXLJO\V = ]?B Yis#"rF:@]?B\@ ]0]?B\@]?B\@ DDOC6;XCEHLE = ]?B ;ice&se:@]?B\@ ]0]?B\@]?B\@ DDOC6\EJ-\HL = ]?B \e#ur&s:@]?B\@ ]0]?B\@]?B\@ DDOC6LEE6A;LO = ]?B Lee A!s":@]?B\@ ]0]?B\@]?B\@ DDOC6LJAHDA\DL = ]?B L#a&dards:@]?B\@ ]0]?B\@]?B\@ DDOC6JY\OKL = ]?B J r",s:@]?B\@ ]0]?B\@]?B\@ DDOC6QE\LXOH = ]?B Qersi"&:@]?B\@ ]0]?B\@]?B\@ DDOC6LECJXOH6Y = ]?B ]0@]?B\@]?B\@ DDOC6LECJXOH = ]0]?B\@]?B\@ DDOC6SESBE\L = ]?D; ]0@ DDOC6SOD-;E6SESBE\L = ]?DDOC6SESBE\L ]0@ DDOC6C;ALL6SESBE\L = ]?DDOC6SESBE\L ]0@ DDOC6LJ\-CJ6SESBE\L = ]?DDOC6SESBE\L ]0@ DDOC6EH-S6SESBE\L = ]?DDOC6SESBE\L ]0@ DDOC6JESR;AJE6SESBE\L = ]?DDOC6SESBE\L ]0@

1*5
DDOC6RA\ASL = ]?B Rara0s:@]?B\@\&]?JAB;E ]0@]?B\@ DDOC6RA\AS6\OK = ]?J\ ]0@ DDOC6RA\AS6XD = ]?JD ]0@ DDOC6RA\AS6DELC = ]?JD ]0@ DDOC6B;AHP;XHE = ]?B\@]?B\@ DDOC6RLVSBO; DDOC6PEVKO\D DDOC6RA\AS = ]?- ]0@ = ]?B ]0@ = ]?X ]0@

D Specification

Ddoc does not $enerate 0TML code. -t for%ats into the "asic for%attin$ %acros4 7hich Ain their predefined for%B are then expanded into 0TML. -f output other than 0TML is desired4 then these %acros need to "e redefined. 3asic .or%attin$ Macros B "oldface the ar$u%ent " italici5e the ar$u%ent ' underline the ar$u%ent P ar$u%ent is a para$raph %L ar$u%ent is a definition list %T ar$u%ent is a definition in a definition list %% ar$u%ent is a description of a definition T.BLE ar$u%ent is a ta"le T, ar$u%ent is a ro7 in a ta"le TB ar$u%ent is a header entry in a ro7 T% ar$u%ent is a data entry in a ro7 OL ar$u%ent is an ordered list 'L ar$u%ent is an unordered list L" ar$u%ent is an ite% in a list B": ar$u%ent is one font si5e "i$$er SM.LL ar$u%ent is one font si5e s%aller B, start ne7 line L"(+ $enerate clic6a"le lin6 on ar$u%ent L"(+M $enerate clic6a"le lin64 first ar$ is address ,E% ar$u%ent is set to "e red BL'E ar$u%ent is set to "e "lue :,EE( ar$u%ent is set to "e $reen SELLO ar$u%ent is set to "e yello7 BL.C+ ar$u%ent is set to "e "lac6 B"TE ar$u%ent is set to "e 7hite %#CO%E ar$u%ent is D code %%OC o)erall te%plate for output %%OC is special in that it specifies the "oilerplate into 7hich the entire $enerated text is inserted Arepresented "y the Ddoc $enerated %acro BO%SB. .or exa%ple4 in order to use a style sheet4 %%OC 7ould "e redefined as?
DDOC = UBDOCJVRE YJS; R-B;XC "://K3C//DJD YJS; ($01//EH" " ##p://,,,$,3$"r'/J\/ #0!(/s#ric#$d#d">

D Specification
U #0!>U ead> USEJA ##p:e+ui>="c"&#e&#:#Fpe" c"&#e&#="#e%#/ #0!; c arse#=u#f:9"> U#i#!e>]?JXJ;E@U/#i#!e> U!i&= re!="s#F!es ee#" #Fpe="#e%#/css" ref="B%GC9.*BB"> U/ ead>Ub"dF> U 1>]?JXJ;E@U/ 1> ]?BODV@ U/b"dF>U/ #0!>

1*(

%%OC#COMME(T is used to insert co%%ents into the output file. 0i$hli$htin$ of D code is perfor%ed "y the follo7in$ %acros? D ,ode .or%attin$ Macros 0i$hli$htin$ of co%%ents 0i$hli$htin$ of strin$ literals 0i$hli$htin$ of D 6ey7ords 0i$hli$htin$ of current declaration na%e 0i$hli$htin$ of current function declaration %#P.,.M para%eters The hi$hli$htin$ %acros start 7ith %%OC#. They control the for%attin$ of indi)idual parts of the presentation. %#COMME(T %#ST,"(: %#+ES O,% %#PSSMBOL %%OC#%ECL %%OC#%ECL#%% %%OC#%"TTO %%OC#SECT"O(S %%OC#S'MM.,S %%OC#%ESC,"PT"O( %%OC#.'TBO,S -%%OC#5E,S"O( %%OC#SECT"O(#B %%OC#SECT"O( Ddoc Section .or%attin$ Macros 0i$hli$htin$ of the declaration. 0i$hli$htin$ of the description of a declaration. 0i$hli$htin$ of ditto declarations. 0i$hli$htin$ of all the sections. 0i$hli$htin$ of the su%%ary section. 0i$hli$htin$ of the description section. 0i$hli$htin$ of the correspondin$ standard section.

0i$hli$htin$ of the section na%e of a non@standard section. 0i$hli$htin$ of the contents of a non@standard section. Default hi$hli$htin$ of all the %e%"ers of a class4 struct4 %%OC#MEMBE,S etc. %%OC#MO%'LE#MEMBE,S 0i$hli$htin$ of all the %e%"ers of a %odule. %%OC#CL.SS#MEMBE,S 0i$hli$htin$ of all the %e%"ers of a class. %%OC#ST,'CT#MEMBE,S 0i$hli$htin$ of all the %e%"ers of a struct. %%OC#E('M#MEMBE,S 0i$hli$htin$ of all the %e%"ers of an enu%. %%OC#TEMPL.TE#MEMBE,S 0i$hli$htin$ of all the %e%"ers of a te%plate. %%OC#P.,.MS 0i$hli$htin$ of a function para%eter section. %%OC#P.,.M#,O 0i$hli$htin$ of a na%eQ)alue function para%eter. %%OC#P.,.M#"% 0i$hli$htin$ of the para%eter na%e. %%OC#P.,.M#%ESC 0i$hli$htin$ of the para%eter )alue. 0i$hli$htin$ of declaration na%e to 7hich a particular %%OC#PSSMBOL section is referrin$. %%OC#+ES O,% 0i$hli$htin$ of D 6ey7ords.

1*7 %%OC#P.,.M 0i$hli$htin$ of function para%eters. %%OC#BL.(+L"(E -nserts a "lan6 line. .or exa%ple4 one could redefine %%OC#S'MM.,S?
DDOC6L-SSA\V = ]?[\EEH ]0@

D Specification

!nd all the su%%ary sections 7ill no7 "e $reen.

Macro %efinitions from sc-iniDs %%OCF"LE


! text file of %acro definitions can "e created4 and specified in sc.ini?
DDOC1X;E=0Fpr"Mec#$dd"c

Macro %efinitions from -ddoc Files on the Command Line


.ile na%es on the DMD co%%and line 7ith the extension .ddoc are text files that are read and processed in order.

Macro %efinitions :enerated 0y %doc


BO%S T"TLE %.TET"ME SE., Set to the $enerated docu%ent text. Set to the %odule na%e. Set to the current date and ti%e. Set to the current year. Set to the contents of any Copyright2 section that is part of the %odule COPS,":BT co%%ent.

'sing %doc for other %ocumentation


Ddoc is pri%arily desi$ned for use in producin$ docu%entation fro% e%"edded co%%ents. -t can also4 ho7e)er4 "e used for processin$ other $eneral docu%entation. The reason for doin$ this 7ould "e to ta6e ad)anta$e of the %acro capa"ility of Ddoc and the D code syntax hi$hli$htin$ capa"ility. -f the .d source file starts 7ith the strin$ CDdocC then it is treated as $eneral purpose docu%entation4 not as a D code source file. .ro% i%%ediately after the CDdocC strin$ to the end of the file or any CMacros?C section for%s the docu%ent. 2o auto%atic hi$hli$htin$ is done to that text4 other than hi$hli$htin$ of D code e%"edded "et7een lines delineated 7ith @@@ lines. /nly %acro processin$ is done. Much of the D docu%entation itself is $enerated this 7ay4 includin$ this pa$e. Such docu%entation is %ar6ed at the "otto% as "ein$ $enerated "y Ddoc.

,eferences
,andyDoc is a )ery nice exa%ple of ho7 one can custo%i5e the Ddoc results 7ith %acros and style sheets.

D Specification

1*#

nter!acing to C
D is desi$ned to fit co%forta"ly 7ith a , co%piler for the tar$et syste%. D %a6es up for not ha)in$ its o7n MM "y relyin$ on the tar$et en)iron%ent:s , runti%e li"rary. -t 7ould "e senseless to atte%pt to port to D or 7rite D 7rappers for the )ast array of , ! -s a)aila"le. 0o7 %uch easier it is to >ust call the% directly. This is done "y %atchin$ the , co%piler:s data types4 layouts4 and function call/return se9uences.

Calling C Functions
, functions can "e called directly fro% D. There is no need for 7rapper functions4 ar$u%ent s7i55lin$4 and the , functions do not need to "e put into a separate DLL. The , function %ust "e declared and $i)en a callin$ con)ention4 %ost li6ely the C,C callin$ con)ention4 for exa%ple?
e%#er& ?C@ i&# s#rc0p?c ar* s#ri&'1) c ar* s#ri&'2@;

and then it can "e called 7ithin D code in the o")ious 7ay?
i0p"r# s#d$s#ri&'; i&# 0FDfu&c#i"&?c ar45 s@ A re#ur& s#rc0p?s#d$s#ri&'$#"L#ri&'I?s@) "f"""@; C

There are se)eral thin$s $oin$ on here?


D understands ho7 , function na%es are C%an$ledC and the correct , function call/return se9uence. , functions cannot "e o)erloaded 7ith another , function 7ith the sa%e na%e. There are no JJcdecl4 JJfar4 JJstdcall4 JJdeclspec4 or other such , type %odifiers in D. These are handled "y attri"utes4 such as e%#er& ?C@. There are no const or )olatile type %odifiers in D. To declare a , function that uses those type %odifiers4 >ust drop those 6ey7ords fro% the declaration. Strin$s are not 0 ter%inated in D. See CData Type ,o%pati"ilityC for %ore infor%ation a"out this. 0o7e)er4 strin$ literals in D are 0 ter%inated.

, code can correspondin$ly call D functions4 if the D functions use an attri"ute that is co%pati"le 7ith the , co%piler4 %ost li6ely the extern A,B?
// 0Ffu&c?@ ca& be ca!!ed fr"0 a&F C fu&c#i"& e%#er& ?C@ A >"id 0Ffu&c?i&# a) i&# b@ A $$$ C C

Storage .llocation
, code explicitly %ana$es %e%ory 7ith calls to %allocAB and freeAB. D allocates %e%ory usin$ the D $ar"a$e collector4 so no explicit free:s are necessary.

1**

D Specification

D can still explicitly allocate %e%ory usin$ c.stdli".%allocAB and c.stdli".freeAB4 these are useful for connectin$ to , functions that expect %alloc:d "uffers4 etc. -f pointers to D $ar"a$e collector allocated %e%ory are passed to , functions4 it:s critical to ensure that that %e%ory 7ill not "e collected "y the $ar"a$e collector "efore the , function is done 7ith it. This is acco%plished "y?

Ma6in$ a copy of the data usin$ c.stdli".%allocAB and passin$ the copy instead. Lea)in$ a pointer to it on the stac6 Aas a para%eter or auto%atic )aria"leB4 as the $ar"a$e collector 7ill scan the stac6. Lea)in$ a pointer to it in the static data se$%ent4 as the $ar"a$e collector 7ill scan the static data se$%ent. Le$isterin$ the pointer 7ith the $ar"a$e collector 7ith the $c.addLootAB or $c.addLan$eAB calls.

!n interior pointer to the allocated %e%ory "loc6 is sufficient to let the 1, 6no7 the o">ect is in useS i.e. it is not necessary to %aintain a pointer to the "e$innin$ of the allocated %e%ory. The $ar"a$e collector does not scan the stac6s of threads not created "y the D Thread interface. 2or does it scan the data se$%ents of other DLL:s4 etc.

%ata Type Compati0ility


% type 1oid 0it 0yte u0yte char $char dchar short ushort int uint long ulong float dou0le real 1oid no e9ui)alent signed char unsigned char char Achars are unsi$ned in DB $char#t A7hen si5eofA7charJtB is 2B $char#t A7hen si5eofA7charJtB is &B short unsigned short int unsigned long long unsigned long long float dou0le long dou0le C type

D Specification ifloat idou0le ireal cfloat cdou0le creal struct union enum class type= type@dimA type@dimA= type@A type@typeA float #"maginary dou0le #"maginary long dou0le #"maginary float #Complex dou0le #Complex long dou0le #Complex struct union enum no e9ui)alent type = type@dimA type3=4@dimA no e9ui)alent no e9ui)alent

200

type function3parameters4 type3=43parameters4 type delegate3parameters4 no e9ui)alent These e9ui)alents hold for %ost 32 "it , co%pilers. The , standard does not pin do7n the si5es of the types4 so so%e care is needed.

Calling printf34
This %ostly %eans chec6in$ that the printf for%at specifier %atches the correspondin$ D data type. !lthou$h printf is desi$ned to handle 0 ter%inated strin$s4 not D dyna%ic arrays of chars4 it turns out that since D dyna%ic arrays are a len$th follo7ed "y a pointer to the data4 the N$*s for%at 7or6s perfectly?
>"id f""?c ar45 s#ri&'@ A pri&#f?"0F s#ri&' is: N$*s\&") s#ri&'@; C

The printf for%at strin$ literal in the exa%ple doesn:t end 7ith E0. This is "ecause strin$ literals4 7hen they are not part of an initiali5er to a lar$er data structure4 ha)e a E0 character helpfully stored after the end of the%. !n i%pro)ed D function for for%atted output is s#d$s#di"$,ri#ef?@.

Structs and 'nions


D structs and unions are analo$ous to ,:s.

201

D Specification

, code often ad>usts the ali$n%ent and pac6in$ of struct %e%"ers 7ith a co%%and line s7itch or 7ith )arious i%ple%entation specific <pra$%a:s. D supports explicit ali$n%ent attri"utes that correspond to the , co%piler:s rules. ,hec6 7hat ali$n%ent the , code is usin$4 and explicitly set it for the D struct declaration. D does not support "it fields. -f needed4 they can "e e%ulated 7ith shift and %as6 operations.

D Specification

202

nter!acing to C))
D does not pro)ide an interface to ,88. Since D4 ho7e)er4 interfaces directly to ,4 it can interface directly to ,88 code if it is declared as ha)in$ , lin6a$e. D class o">ects are inco%pati"le 7ith ,88 class o">ects.

203

D Specification

Portability &uide
-t:s $ood soft7are en$ineerin$ practice to %ini%i5e $ratuitous porta"ility pro"le%s in the code. Techni9ues to %ini%i5e potential porta"ility pro"le%s are?

The inte$ral and floatin$ type si5es should "e considered as %ini%u%s. !l$orith%s should "e desi$ned to continue to 7or6 properly if the type si5e increases. .loatin$ point co%putations can "e carried out at a hi$her precision than the si5e of the floatin$ point )aria"le can hold. .loatin$ point al$orith%s should continue to 7or6 properly if precision is ar"itrarily increased. !)oid dependin$ on the order of side effects in a co%putation that %ay $et reordered "y the co%piler. .or exa%ple?
a + b + c

can "e e)aluated as Aa 8 "B 8 c4 a 8 A" 8 cB4 Aa 8 cB 8 "4 Ac 8 "B 8 a4 etc. arentheses control operator precedence4 parentheses do not control order of e)aluation. .unction para%eters can "e e)aluated either left to ri$ht or ri$ht to left4 dependin$ on the particular callin$ con)entions used. -f the operands of an associati)e operator 8 or N are floatin$ point )alues4 the expression is not reordered.

!)oid dependence on "yte orderS i.e. 7hether the , ; is "i$@endian or little@endian. !)oid dependence on the si5e of a pointer or reference "ein$ the sa%e si5e as a particular inte$ral type. -f si5e dependencies are ine)ita"le4 put an asser# in the code to )erify it?
asser#?i&#$siIe"f == ?i&#*@$siIe"f@;

LM to JK Bit Porta0ility
(& "it processors and operatin$ syste%s are here. Dith that in %ind?

-nte$ral types 7ill re%ain the sa%e si5es "et7een 32 and (& "it code. ointers and o">ect references 7ill increase in si5e fro% & "ytes to # "ytes $oin$ fro% 32 to (& "it code. ;se size#t as an alias for an unsi$ned inte$ral type that can span the address space. !rray indices should "e of type size#t. ;se ptrdiff#t as an alias for a si$ned inte$ral type that can span the address space. ! type representin$ the difference "et7een t7o pointers should "e of type ptrdiff#t. The -length4 -size4 -sizeof4 and -alignof properties 7ill "e of type size#t.

Endianness
'ndianness refers to the order in 7hich %ulti"yte types are stored. The t7o %ain orders are #ig endian and little endian. The co%piler predefines the )ersion identifier BigEndian or LittleEndian dependin$ on the order of the tar$et syste%. The x#( syste%s are all little endian. The ti%es 7hen endianness %atters are?

Dhen readin$ data fro% an external source Ali6e a fileB 7ritten in a different endian for%at. Dhen readin$ or 7ritin$ indi)idual "ytes of a %ulti"yte type li6e longs or dou0les.

D Specification

20&

OS Specific Code
Syste% specific code is handled "y isolatin$ the differences into separate %odules. !t co%pile ti%e4 the correct syste% specific %odule is i%ported. Minor differences can "e handled "y constant defined in a syste% specific i%port4 and then usin$ that constant in an If$tatement or $taticIf$tatement.

205

D Specification

Embedding D in %TML
The D co%piler is desi$ned to "e a"le to extract and co%pile D code e%"edded 7ithin 0TML files. This capa"ility %eans that D code can "e 7ritten to "e displayed 7ithin a "ro7ser utili5in$ the full for%attin$ and display capa"ility of 0TML. .or exa%ple4 it is possi"le to %a6e all uses of a class na%e actually "e hyperlin6s to 7here the class is defined. There:s nothin$ ne7 to learn for the person "ro7sin$ the code4 he >ust uses the nor%al features of an 0TML "ro7ser. Strin$s can "e displayed in $reen4 co%%ents in red4 and 6ey7ords in 0oldface4 for one possi"ility. -t is e)en possi"le to e%"ed pictures in the code4 as nor%al 0TML i%a$e ta$s. '%"eddin$ D in 0TML %a6es it possi"le to put the docu%entation for code and the code itself all to$ether in one file. -t is no lon$er necessary to rele$ate docu%entation in co%%ents4 to "e extracted later "y a tech 7riter. The code and the docu%entation for it can "e %aintained si%ultaneously4 7ith no duplication of effort. 0o7 it 7or6s is strai$htfor7ard. -f the source file to the co%piler ends in .ht% or .ht%l4 the code is assu%ed to "e e%"edded in 0TML. The source is then preprocessed "y strippin$ all text outside of UcodeV and U/codeV ta$s. Then4 all other 0TML ta$s are stripped4 and e%"edded character encodin$s are con)erted to !S,--. The processin$ does not atte%pt to dia$nose errors in the 0TML itself. !ll ne7lines in the ori$inal 0TML re%ain in their correspondin$ positions in the preprocessed text4 so the de"u$ line nu%"ers re%ain consistent. The resultin$ text is then fed to the D co%piler. 0ere:s an exa%ple of the D pro$ra% Chello 7orldC e%"edded in this )ery 0TML file. This file can "e co%piled and run.
i0p"r# s#d$c$s#di"; i&# E!A$?@ A pri&#f?" e!!" ,"r!d\&"@; re#ur& 0; C

D Specification

20(

*amed C+aracter Entities


These are the character entity na%es supported "y D. (ote2 2ot all 7ill display properly in the Sym0ol colu%n in all "ro7sers. 2a%ed ,haracter 'ntities (ame 9uot a%p lt $t /'li$ oeli$ Scaron scaron ]u%l circ tilde ensp e%sp thinsp 57n> 57> lr% rl% ndash %dash ls9uo rs9uo s"9uo ld9uo rd9uo "d9uo da$$er Da$$er 5alue 3& 3# (0 (2 33# 33* 352 353 37( 710 732 #1*& #1*5 #201 #20& #205 #20( #207 #211 #212 #21( #217 #21# #220 #221 #222 #22& #225 f g h i j k l m n o C + U V _ ` a b c d e Sym0ol

207 per%il lsa9uo rsa9uo euro n"sp iexcl cent pound curren yen "r)"ar sect u%l copy ordf la9uo not shy re$ %acr de$ plus%n sup2 sup3 acute %icro para %iddot cedil sup1 ord% ra9uo #2&0 #2&* #250 #3(& 1(0 1(1 1(2 1(3 1(& 1(5 1(( 1(7 1(# 1(* 170 171 172 173 17& 175 17( 177 17# 17* 1#0 1#1 1#2 1#3 1#& 1#5 1#( 1#7 t u v w x y z { | } ~ p q r s

D Specification

Latin)O 3"SO)IIQT)O4 Entities

D Specification frac1& frac12 frac3& i9uest !$ra)e !acute !circ !tilde !u%l !rin$ !'li$ ,cedil '$ra)e 'acute 'circ 'u%l -$ra)e -acute -circ -u%l 'T0 2tilde /$ra)e /acute /circ /tilde /u%l ti%es /slash ;$ra)e ;acute ;circ ;u%l 1## 1#* 1*0 1*1 1*2 1*3 1*& 1*5 1*( 1*7 1*# 1** 200 201 202 203 20& 205 20( 207 20# 20* 210 211 212 213 21& 215 21( 217 21# 21* 220

20#

20* ]acute T0/L2 s5li$ a$ra)e aacute acirc atilde au%l arin$ aeli$ ccedil e$ra)e eacute ecirc eu%l i$ra)e iacute icirc iu%l eth ntilde o$ra)e oacute ocirc otilde ou%l di)ide oslash u$ra)e uacute ucirc uu%l yacute 221 222 223 22& 225 22( 227 22# 22* 230 231 232 233 23& 235 23( 237 23# 23* 2&0 2&1 2&2 2&3 2&& 2&5 2&( 2&7 2&# 2&* 250 251 252 253

D Specification

D Specification thorn yu%l fnof !lpha 3eta 1a%%a Delta 'psilon ^eta 'ta Theta -ota Kappa La%"da Mu 2u Ti /%icron i Lho Si$%a Tau ;psilon hi ,hi si /%e$a alpha "eta $a%%a delta epsilon 25& 255 &02 *13 *1& *15 *1( *17 *1# *1* *20 *21 *22 *23 *2& *25 *2( *27 *2# *2* *31 *32 *33 *3& *35 *3( *37 *&5 *&( *&7 *&# *&*

210

Sym0ols and :ree! letter entities

211 5eta eta theta iota 6appa la%"da %u nu xi o%icron pi rho si$%af si$%a tau upsilon phi chi psi o%e$a thetasy% upsih pi) "ull hellip pri%e ri%e oline frasl 7eierp i%a$e real trade *50 *51 *52 *53 *5& *55 *5( *57 *5# *5* *(0 *(1 *(2 *(3 *(& *(5 *(( *(7 *(# *(* *77 *7# *#2 #22( #230 #2&2 #2&3 #25& #2(0 #&72 #&(5 #&7( #&#2

D Specification

D Specification alefsy% larr uarr rarr darr harr crarr l!rr u!rr r!rr d!rr h!rr forall part exist e%pty na"la isin notin ni prod su% %inus lo7ast radic prop infin an$ and or cap cup int #501 #5*2 #5*3 #5*& #5*5 #5*( #(2* #(5( #(57 #(5# #(5* #((0 #70& #70( #707 #70* #711 #712 #713 #715 #71* #721 #722 #727 #730 #733 #73& #73( #7&3 #7&& #7&5 #7&( #7&7

212

213 there& si% con$ asy%p ne e9ui) le $e su" sup nsu" su"e supe oplus oti%es perp sdot lceil rceil lfloor rfloor lan$ ran$ lo5 spades clu"s hearts dia%s #75( #7(& #773 #77( ##00 ##01 ##0& ##05 ##3& ##35 ##3( ##3# ##3* ##53 ##55 ##(* #*01 #*(# #*(* #*70 #*71 *001 *002 *(7& *#2& *#27 *#2* *#30 ! " ! " # $ % & ' ( ) * + , . /

D Specification

D Specification

21&

D Application ,inary nter!ace


! D i%ple%entation that confor%s to the D !3- A!pplication 3inary -nterfaceB 7ill "e a"le to $enerate li"raries4 DLL:s4 etc.4 that can interoperate 7ith D "inaries "uilt "y other i%ple%entations. Most of this specification re%ains T3D ATo 3e DefinedB.

C .B"
The , !3- referred to in this specification %eans the , !pplication 3inary -nterface of the tar$et syste%. , and D code should "e freely lin6a"le to$ether4 in particular4 D code shall ha)e access to the entire , !3- runti%e li"rary.

Basic Types
T3D

Structs
,onfor%s to the tar$et:s , !3- struct layout.

Classes
!n o">ect consists of? offset 0 ptrsi&e contents pointer to )ta"le %onitor

ptrsi&e23... non@static %e%"ers The )ta"le consists of? offset 0 ptrsi&e... contents pointer to instance of ,lass-nfo

pointers to )irtual %e%"er functions The class definition?


c!ass WWWW A $$$$ C;

1enerates the follo7in$?


!n instance of ,lass called ,lassTTTT. ! type called Static,lassTTTT 7hich defines all the static %e%"ers. !n instance of Static,lassTTTT called StaticTTTT for the static %e%"ers.

215

D Specification

"nterfaces
T3D

.rrays
! dyna%ic array consists of? offset 0 contents array di%ension

si&e1t pointer to array data ! dyna%ic array is declared as?


#Fpe45 arraF;

7hereas a static array is declared as?


#Fpe4di0e&si"&5 arraF;

Thus4 a static array al7ays has the di%ension statically a)aila"le as part of the type4 and so it is i%ple%ented li6e in ,. Static array:s and Dyna%ic arrays can "e easily con)erted "ac6 and forth to each other.

.ssociati1e .rrays
!ssociati)e arrays consist of a pointer to an opa9ue4 i%ple%entation defined type. The current i%ple%entation is contained in pho"os/internal/aa!.d.

,eference Types
D has reference types4 "ut they are i%plicit. .or exa%ple4 classes are al7ays referred to "y referenceS this %eans that class instances can ne)er reside on the stac6 or "e passed as function para%eters. Dhen passin$ a static array to a function4 the result4 althou$h declared as a static array4 7ill actually "e a reference to a static array. .or exa%ple?
i&#435 abc;

assin$ a"c to functions results in these i%plicit con)ersions?


>"id fu&c?i&#435 arraF@; // ac#ua!!F Urefere&ce #">UarraF435 "f>Ui&#> >"id fu&c?i&#* p@; // abc is c"&>er#ed #" a p"i&#er // #" # e firs# e!e0e&# >"id fu&c?i&#45 arraF@; // abc is c"&>er#ed #" a dF&a0ic arraF

(ame Mangling
D acco%plishes typesafe lin6in$ "y mangling a D identifier to include scope and type infor%ation.
-angledName: _< (&alifiedName Type _< (&alifiedName V Type (&alifiedName:

D Specification
Sym'olName Sym'olName (&alifiedName Sym'olName: LName TemplateInstanceName

21(

The M %eans that the sy%"ol is a function that re9uires a # is pointer. Te%plate -nstance 2a%es ha)e the types and )alues of its para%eters encoded into it?
TemplateInstanceName: __W LName Template#rgs U Template#rgs: Template#rg Template#rg Template#rgs Template#rg: W Type X Type .al&e S LName .al&e: $ N&m'er P N&m'er 9 *e+Float * *e+Float * *e+Float : N&m'er .al&e$$$ *e+Float: P:P RP> PRP> P *e+%igits @ E+ponent *e+%igits @ E+ponent E+ponent: P N&m'er N&m'er *e+%igits: *e+%igit *e+%igit *e+%igits *e+%igit: %igit : . ; < = >

n is for null ar$u%ents. !um#er is for positi)e nu%eric literals Aincludin$ character literalsB. ( !um#er

217

D Specification

is for ne$ati)e nu%eric literals. e 4exFloat is for real and i%a$inary floatin$ point literals. c 4exFloat c 4exFloat is for co%plex floatin$ point literals. .idth !um#er # 4ex igits .idth is 7hether the characters are 1 "yte AaB4 2 "ytes A$B or & "ytes AdB in si5e. !um#er is the nu%"er of characters in the strin$. The 4ex igits are the hex data for the strin$. . !um#er %alue... !n array literal. %alue is repeated !um#er ti%es.
Name: Namestart Namestart Namechars Namestart: _ #lpha Namechar: Namestart %igit Namechars: Namechar Namechar Namechars

! !ame is a standard D identifier.


LName: N&m'er Name N&m'er: %igit %igit N&m'er %igit: 0 0 1 2 3 4 5 6 7 8

!n L!ame is a na%e preceded "y a !um#er $i)in$ the nu%"er of characters in the !ame.

Type Mangling
Types are %an$led usin$ a si%ple linear sche%e?
Type: Type#rray TypeSarray Type#array

D Specification
Type,ointer TypeF&nction TypeIdent TypeClass TypeStr&ct TypeEn&m TypeTypedef Type%elegate TypeNone Type.oid TypeByte Type!'yte TypeShort Type!short TypeInt Type!int TypeLong Type!long TypeFloat Type%o&'le Type3eal TypeIfloat TypeIdo&'le TypeIreal TypeCfloat TypeCdo&'le TypeCreal TypeBool TypeChar TypeWchar Type%char TypeT&ple Type#rray: : Type TypeSarray: Y N&m'er Type Type#array: O Type Type Type,ointer: @ Type TypeF&nction: CallCon"ention #rg&ments #rgClose Type CallCon"ention: > ) M X N #rg&ments: #rg&ment #rg&ment #rg&ments #rg&ment8 Type

21#

21*
Z Type [ Type - Type #rgClose / \ U TypeIdent: R LName TypeClass: ; LName TypeStr&ct: S LName TypeEn&m: = LName TypeTypedef: W LName Type%elegate: < TypeF&nction TypeNone: $ Type.oid: & TypeByte: D Type!'yte: I TypeShort: B Type!short: % TypeInt: A Type!int: H TypeLong: C Type!long: E TypeFloat: # Type%o&'le:

D Specification

D Specification
, Type3eal: 9 TypeIfloat: F TypeIdo&'le: ? TypeIreal: ] TypeCfloat: Q TypeCdo&'le: r TypeCreal: * TypeBool: " TypeChar: ! TypeWchar: ( Type%char: + TypeT&ple: . N&m'er #rg&ments

220

Function Calling Con1entions


The extern A,B callin$ con)ention %atches the , callin$ con)ention used "y the supported , co%piler on the host syste%. The extern ADB callin$ con)ention for x#( is descri"ed here. ,egister Con1entions

'!T4 ',T4 'DT are scratch re$isters and can "e destroyed "y a function. '3T4 'S-4 'D-4 '3 %ust "e preser)ed across function calls. '.L!1S is assu%ed destroyed across function calls4 except for the direction fla$ 7hich %ust "e for7ard. The . ; stac6 %ust "e e%pty 7hen callin$ a function. The . ; control 7ord %ust "e preser)ed across function calls. .loatin$ point return )alues are returned on the . ; stac6. These %ust "e cleaned off "y the caller4 e)en if they are not used.

,eturn 5alue

The types "ool4 "yte4 u"yte4 short4 ushort4 int4 uint4 pointer4 /">ect4 and interfaces are

221

D Specification returned in '!T. lon$ and ulon$ are returned in 'DT4'!T4 7here 'DT $ets the %ost si$nificant half. float4 dou"le4 real4 ifloat4 idou"le4 ireal are returned in ST0. cfloat4 cdou"le4 creal are returned in ST14ST0 7here ST1 is the real part and ST0 is the i%a$inary part. Dyna%ic arrays are returned 7ith the pointer in 'DT and the len$th in '!T. !ssociati)e arrays are returned in '!T 7ith $ar"a$e returned in 'DT. The 'DT )alue 7ill pro"a"ly "e re%o)ed in the futureS it:s there for "ac67ards co%pati"ility 7ith an earlier i%ple%entation of !!:s. Dele$ates are returned 7ith the pointer to the function in 'DT and the context pointer in '!T. .or Dindo7s4 14 2 and & "yte structs are returned in '!T. .or Dindo7s4 # "yte structs are returned in 'DT4'!T4 7here 'DT $ets the %ost si$nificant half. .or other struct si5es4 and for all structs on Linux4 the return )alue is stored throu$h a hidden pointer passed as an ar$u%ent to the function. ,onstructors return the this pointer in '!T.

Parameters The para%eters to the non@)ariadic function?


f""?a1) a2) $$$) a&@;

are passed as follo7s? a1 a2 ... an hidden this 7here hidden is present if needed to return a struct )alue4 and this is present if needed as the this pointer for a %e%"er function or the context pointer for a nested function. The last para%eter is passed in '!T rather than "ein$ pushed on the stac6 if the follo7in$ conditions are %et?

-t fits in '!T. -t is not a 3 "yte struct.

ara%eters are al7ays pushed as %ultiples of & "ytes4 roundin$ up7ards4 so the stac6 is al7ays ali$ned on & "yte "oundaries. They are pushed %ost si$nificant first. out and inout are passed as pointers. Static arrays are passed as pointers to their first ele%ent. /n Dindo7s4 a real is pushed as a 10 "yte 9uantity4 a creal is pushed as a 20 "yte 9uantity. /n Linux4 a real is pushed as a 12 "yte 9uantity4 a creal is pushed as t7o 12 "yte 9uantities. The extra t7o "ytes of pad occupy the :%ost si$nificant: position. The callee cleans the stac6. The para%eters to the )ariadic function?
>"id f""?i&# p1) i&# p2) i&#45 p3$$$@ f""?a1) a2) $$$) a&@;

D Specification are passed as follo7s? p1 p2 a3 hidden this The )ariadic part is con)erted to a dyna%ic array and the rest is the sa%e as for non@)ariadic functions. The para%eters to the )ariadic function?
>"id f""?i&# p1) i&# p2) $$$@ f""?a1) a2) a3) $$$) a&@;

222

are passed as follo7s? an ... a3 a2 a1 Jar$u%ents hidden this The caller is expected to clean the stac6. #argptr is not passed4 it is co%puted "y the callee.

Exception Bandling
indo$s ,onfor%s to the Microsoft Dindo7s Structured 'xception 0andlin$ con)entions. Linux ;ses static address ran$e/handler ta"les. T3D

:ar0age Collection
The interface to this is found in p "b"s/i&#er&a!/'c.

,untime Belper Functions


These are found in p "b"s/i&#er&a!.

Module "nitialization and Termination


T3D

223

D Specification

'nit Testing
T3D

You might also like