Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Language Reference

table of contents

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

Lexical

Contents
  1. Source Text
  2. Character Set
  3. End of File
  4. End of Line
  5. White Space
  6. Comments
  7. Tokens
  8. Identifiers
  9. String Literals
    1. Wysiwyg Strings
    2. Double Quoted Strings
    3. Delimited Strings
    4. Token Strings
    5. Hex Strings
    6. String Postfix
  10. Escape Sequences
  11. Character Literals
  12. Integer Literals
  13. Floating Point Literals
  14. Keywords
  15. Special Tokens
  16. Special Token Sequences

The lexical analysis is independent of the syntax parsing and the semanticanalysis. The lexical analyzer splits the source text into tokens. Thelexical grammar describes the syntax of these tokens. The grammar is designed tobe suitable for high-speed scanning and to facilitate the implementation of a correctscanner. It has a minimum of special case rules and there is only onephase of translation.

Source Text

SourceFile:ByteOrderMarkModuleoptShebangModuleoptModuleopt
ByteOrderMark:\uFEFF
Shebang:#!CharactersoptEndOfShebang
EndOfShebang:\u000AEndOfFile

Source text can be encoded as any one of the following:

One of the following UTFBOMs (Byte Order Marks) can be present at the beginning of the source text:

UTF Byte Order Marks
FormatBOM
UTF-8EF BB BF
UTF-16BEFE FF
UTF-16LEFF FE
UTF-32BE00 00 FE FF
UTF-32LEFF FE 00 00
ASCIIno BOM

If the source file does not begin with a BOM, then the first character mustbe less than or equal to U+0000007F.

The source text is decoded from its source representation into UnicodeCharacters. TheCharacters are further divided into:WhiteSpace,EndOfLine,Comments,SpecialTokenSequences, andTokens, with the source terminated by anEndOfFile.

The source text is split into tokens using the maximal munch algorithm,i.e., the lexical analyzer assumes the longest possible token. For example,>> is a right-shift token rather than two greater-than tokens. There are twoexceptions to this rule:

Character Set

Character:any Unicode character

End of File

EndOfFile:physical end of the file\u0000\u001A

The source text is terminated by whichever comes first.

End of Line

EndOfLine:\u000D\u000A\u000D\u000A\u2028\u2029EndOfFile

White Space

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

Comments

Comment:BlockCommentLineCommentNestingBlockComment
BlockComment:/*Charactersopt*/
LineComment://CharactersoptEndOfLine
NestingBlockComment:/+NestingBlockCommentCharactersopt+/
NestingBlockCommentCharacters:NestingBlockCommentCharacterNestingBlockCommentCharacterNestingBlockCommentCharacters
NestingBlockCommentCharacter:CharacterNestingBlockComment
Characters:CharacterCharacterCharacters

There are three kinds of comments:

  1. Block comments can span multiple lines, but do not nest.
  2. Line comments terminate at the end of the line.
  3. Nesting block comments can span multiple lines and can nest.

The contents of strings and comments are not tokenized. Consequently, comment openings occurring within a string do not begin a comment, and string delimiters within a comment do not affect the recognition of comment closings and nested/+ comment openings. With the exception of/+ occurring within a/+ comment, comment openings within a comment are ignored.

a =/+ // +/ 1;// parses as if 'a = 1;'a =/+ "+/" +/ 1";// parses as if 'a = " +/ 1";'a =/+ /* +/ */ 3;// parses as if 'a = */ 3;'

Comments cannot be used as token concatenators, for example,abc/**/defis two tokens,abc anddef, not oneabcdef token.

Tokens

Tokens:TokenTokenTokens
Token:{}TokenNoBraces
TokenNoBraces:IdentifierStringLiteralInterpolationExpressionSequenceCharacterLiteralIntegerLiteralFloatLiteralKeyword//=......&&=&&||=||--=--++=++<<=<<<<=>>=>>=>>>=>>>>>!!=()[]?,;:$===**=%%=^^=^^^^=~~=@=>

Identifiers

Identifier:IdentifierStartIdentifierStartIdentifierChars
IdentifierChars:IdentifierCharIdentifierCharIdentifierChars
IdentifierStart:_LetterUniversalAlpha
IdentifierChar:IdentifierStart0NonZeroDigit

Identifiers start with a letter,_, or universal alpha, and arefollowed by any number of letters,_, digits, or universal alphas.Universal alphas are as defined in ISO/IEC 9899:1999(E) Appendix D of the C99 Standard.Identifiers can be arbitrarily long, and are case sensitive.

Implementation Defined: Identifiers starting with__ (two underscores) are reserved.

String Literals

StringLiteral:WysiwygStringAlternateWysiwygStringDoubleQuotedStringDelimitedStringTokenStringHexString

A string literal is either a wysiwyg quoted string, a double quotedstring, a delimited string, a token string, or a hex string.

In all string literal forms, anEndOfLine is regarded as a single\n character.

Wysiwyg Strings

WysiwygString:r"WysiwygCharactersopt"StringPostfixopt
AlternateWysiwygString:`WysiwygCharactersopt`StringPostfixopt
WysiwygCharacters:WysiwygCharacterWysiwygCharacterWysiwygCharacters
WysiwygCharacter:CharacterEndOfLine

Wysiwyg ("what you see is what you get") quoted strings can be defined using either of two syntaxes.

In the first form, they are enclosed betweenr" and". All characters between ther" and" are part of the string. There are no escape sequences inside wysiwyg strings.

r"I am Oz"r"c:\games\Sudoku.exe"r"ab\n"// string is 4 characters,// 'a', 'b', '\', 'n'

Alternatively, wysiwyg strings can be enclosed by backquotes, using the ` character.

`the Great and Powerful.``c:\games\Empire.exe``The "lazy" dog``a"b\n`// string is 5 characters,// 'a', '"', 'b', '\', 'n'

See alsoInterpolatedWysiwygLiteral

Double Quoted Strings

DoubleQuotedString:"DoubleQuotedCharactersopt"StringPostfixopt
DoubleQuotedCharacters:DoubleQuotedCharacterDoubleQuotedCharacterDoubleQuotedCharacters
DoubleQuotedCharacter:CharacterEscapeSequenceEndOfLine

Double quoted strings are enclosed by "".EscapeSequences can be embedded in them.

"Who are you?""c:\\games\\Doom.exe""ab\n"// string is 3 characters,// 'a', 'b', and a linefeed"ab"// string is 3 characters,// 'a', 'b', and a linefeed

See alsoInterpolatedDoubleQuotedLiteral

Delimited Strings

DelimitedString:q"DelimiterWysiwygCharactersoptMatchingDelimiter"StringPostfixoptq"(ParenDelimitedCharactersopt)"StringPostfixoptq"[BracketDelimitedCharactersopt]"StringPostfixoptq"{BraceDelimitedCharactersopt}"StringPostfixoptq"<AngleDelimitedCharactersopt>"StringPostfixopt
Delimiter:Identifier
MatchingDelimiter:Identifier
ParenDelimitedCharacters:WysiwygCharacterWysiwygCharacterParenDelimitedCharacters(ParenDelimitedCharactersopt)
BracketDelimitedCharacters:WysiwygCharacterWysiwygCharacterBracketDelimitedCharacters[BracketDelimitedCharactersopt]
BraceDelimitedCharacters:WysiwygCharacterWysiwygCharacterBraceDelimitedCharacters{BraceDelimitedCharactersopt}
AngleDelimitedCharacters:WysiwygCharacterWysiwygCharacterAngleDelimitedCharacters<AngleDelimitedCharactersopt>

Delimited strings use various forms of delimiters. The delimiter, whether a character or identifier, must immediately follow the " without any intervening whitespace. The terminating delimiter must immediately precede the closing " without any intervening whitespace. Anesting delimiter nests, and is one of the following characters:

Nesting Delimiters
DelimiterMatching Delimiter
[]
()
<>
{}
q"(foo(xxx))"// "foo(xxx)"q"[foo{]"// "foo{"

If the delimiter is an identifier, the identifier must be immediately followed by a newline, and the matching delimiter must be the same identifier starting at the beginning of the line:

writeln(q"EOSThisis a multi-lineheredoc stringEOS");

The newline following the opening identifier is not part of the string, but the last newline before the closing identifier is part of the string. The closing identifier must be placed on its own line at the leftmost column.

Otherwise, the matching delimiter is the same as the delimiter character:

q"/foo]/"// "foo]"// q"/abc/def/"    // error

Token Strings

TokenString:q{TokenStringTokensopt}StringPostfixopt
TokenStringTokens:TokenStringTokenTokenStringTokenTokenStringTokens
TokenStringToken:TokenNoBraces{TokenStringTokensopt}

Token strings open with the charactersq{ and close with the token}. In between must be valid D tokens. The{ and} tokens nest. The string is formed of all the characters between the opening and closing of the token string, including comments.

q{this is the voice of}// "this is the voice of"q{/*}*/ }// "/*}*/ "q{ world(q{control}); }// " world(q{control}); "q{ __TIME__ }// " __TIME__ "// i.e. it is not replaced with the time// q{ __EOF__ }         // error// __EOF__ is not a token, it's end of file

See alsoInterpolatedTokenLiteral

Hex Strings

HexString:x"HexStringCharsopt"StringPostfixopt
HexStringChars:HexStringCharHexStringCharHexStringChars
HexStringChar:HexDigitWhiteSpaceEndOfLine

Hex strings allow string literals to be created using hex data. The hex data need not form valid UTF characters.

x"0A"// same as "\x0A"x"00 FBCD 32FD 0A"// same as "\x00\xFB\xCD\x32\xFD\x0A"

Whitespace and newlines are ignored, so the hex data can be easily formatted. The number of hex characters must be a multiple of 2.

String Postfix

StringPostfix:cwd

The optionalStringPostfix character gives a specific type to the string, rather than it being inferred from the context. The types corresponding to the postfix characters are:

String Literal Postfix Characters
PostfixTypeAlias
cimmutable(char)[]string
wimmutable(wchar)[]wstring
dimmutable(dchar)[]dstring
"hello"c// string"hello"w// wstring"hello"d// dstring

The string literals are assembled as UTF-8 char arrays, and the postfix is applied to convert to wchar or dchar as necessary as a final step.

Escape Sequences

EscapeSequence:\'\"\?\\\0\a\b\f\n\r\t\v\xHexDigitHexDigit\OctalDigit\OctalDigitOctalDigit\OctalDigitOctalDigitOctalDigit\uHexDigitHexDigitHexDigitHexDigit\UHexDigitHexDigitHexDigitHexDigitHexDigitHexDigitHexDigitHexDigit\NamedCharacterEntity
OctalDigit:01234567
Escape Sequences
SequenceMeaning
\'Literal single-quote:'
\"Literal double-quote:"
\?Literal question mark:?
\\Literal backslash:\
\0Binary zero (NUL, U+0000).
\aBEL (alarm) character (U+0007).
\bBackspace (U+0008).
\fForm feed (FF) (U+000C).
\nEnd-of-line (U+000A).
\rCarriage return (U+000D).
\tHorizontal tab (U+0009).
\vVertical tab (U+000B).
\xnnByte value in hexadecimal, wherenn is specified as two hexadecimal digits.
For example:\xFF represents the character with the value 255.
See also:std.conv.hexString.
\n
\nn
\nnn
Byte value in octal.
For example:\101 represents the character with the value 65 ('A'). Analogous to hexadecimal characters, the largest byte value is\377 (=\xFF in hexadecimal or255 in decimal)
See also:std.conv.octal.
\unnnnUnicode character U+nnnn, wherennnn are four hexadecimal digits.
For example,\u03B3 represents the Unicode character γ (U+03B3 - GREEK SMALL LETTER GAMMA).
\UnnnnnnnnUnicode character U+nnnnnnnn, wherennnnnnnn are 8 hexadecimal digits.
For example,\U0001F603 represents the Unicode character U+1F603 (SMILING FACE WITH OPEN MOUTH).
\nameNamed character entity from the HTML5 specification.
These names begin with& and end with;, e.g.,&euro;. SeeNamedCharacterEntity.

Character Literals

CharacterLiteral:'SingleQuotedCharacter'
SingleQuotedCharacter:CharacterEscapeSequence

Character literals are a single character or escape sequence enclosed bysingle quotes.

'h'// the letter h'\n'// newline'\\'// the backslash character

A character literal resolves to one of typechar,wchar, ordchar (seeBasic Data Types).

Otherwise, it resolves to the type with the smallest size it will fit into.

Integer Literals

IntegerLiteral:IntegerIntegerIntegerSuffix
Integer:DecimalIntegerBinaryIntegerHexadecimalInteger
IntegerSuffix:LuULuLUuLUL
DecimalInteger:0UnderscoresoptNonZeroDigitNonZeroDigitDecimalDigitsUS
Underscores:_Underscores_
NonZeroDigit:123456789
DecimalDigits:DecimalDigitDecimalDigitDecimalDigits
DecimalDigitsUS:DecimalDigitUSDecimalDigitUSDecimalDigitsUS
DecimalDigitsNoSingleUS:DecimalDigitsUSoptDecimalDigitDecimalDigitsUSopt
DecimalDigitsNoStartingUS:DecimalDigitDecimalDigitDecimalDigitsUS
DecimalDigit:0NonZeroDigit
DecimalDigitUS:DecimalDigit_
BinaryInteger:BinPrefixBinaryDigitsNoSingleUS
BinPrefix:0b0B
BinaryDigitsNoSingleUS:BinaryDigitsUSoptBinaryDigitBinaryDigitsUSopt
BinaryDigitsUS:BinaryDigitUSBinaryDigitUSBinaryDigitsUS
BinaryDigit:01
BinaryDigitUS:BinaryDigit_
HexadecimalInteger:HexPrefixHexDigitsNoSingleUS
HexDigits:HexDigitHexDigitHexDigits
HexDigitsUS:HexDigitUSHexDigitUSHexDigitsUS
HexDigitsNoSingleUS:HexDigitsUSoptHexDigitHexDigitsUSopt
HexDigitsNoStartingUS:HexDigitHexDigitHexDigitsUS
HexDigit:DecimalDigitHexLetter
HexDigitUS:HexDigit_
HexLetter:abcdefABCDEF

Integers can be specified in decimal, binary, or hexadecimal.

10// decimal0b1010// binary0xA// hex

Integers can have embedded ‘_’ characters after a digit to improve readability, which are ignored.

20_000// leagues under the sea867_5309// number on the wall1_522_000// thrust of F1 engine (lbf sea level)0xBAAD_F00D// magic number for debugging

Integers can be immediately followed by one ‘L’ or one of ‘u’ or ‘U’ or both. Note that there is no ‘l’ suffix.

The type of the integer is resolved as follows:

Decimal Literal Types
LiteralType
Usual decimal notation
0 .. 2_147_483_647int
2_147_483_648 .. 9_223_372_036_854_775_807long
9_223_372_036_854_775_808 .. 18_446_744_073_709_551_615ulong
Explicit suffixes
0L .. 9_223_372_036_854_775_807Llong
0U .. 4_294_967_295Uuint
4_294_967_296U .. 18_446_744_073_709_551_615Uulong
0UL .. 18_446_744_073_709_551_615ULulong
Hexadecimal notation
0x0 .. 0x7FFF_FFFFint
0x8000_0000 .. 0xFFFF_FFFFuint
0x1_0000_0000 .. 0x7FFF_FFFF_FFFF_FFFFlong
0x8000_0000_0000_0000 .. 0xFFFF_FFFF_FFFF_FFFFulong
Hexadecimal notation with explicit suffixes
0x0L .. 0x7FFF_FFFF_FFFF_FFFFLlong
0x8000_0000_0000_0000L .. 0xFFFF_FFFF_FFFF_FFFFLulong
0x0U .. 0xFFFF_FFFFUuint
0x1_0000_0000U .. 0xFFFF_FFFF_FFFF_FFFFUulong
0x0UL .. 0xFFFF_FFFF_FFFF_FFFFULulong

An integer literal may not exceed these values.

Best Practices: Octal integer notation is not supported for integer literals. However, octal integer literals can be interpreted at compile time through thestd.conv.octal template, as inoctal!167.

Floating Point Literals

FloatLiteral:FloatSuffixoptIntegerFloatSuffixImaginarySuffixoptIntegerRealSuffixoptImaginarySuffix
Float:DecimalFloatHexFloat
DecimalFloat:LeadingDecimal.DecimalDigitsNoStartingUSoptLeadingDecimal.DecimalDigitsNoStartingUSDecimalExponent.DecimalDigitsNoStartingUSDecimalExponentoptLeadingDecimalDecimalExponent
DecimalExponent:DecimalExponentStartDecimalDigitsNoSingleUS
DecimalExponentStart:eEe+E+e-E-
HexFloat:HexPrefixHexDigitsNoSingleUS.HexDigitsNoStartingUSHexExponentHexPrefix.HexDigitsNoStartingUSHexExponentHexPrefixHexDigitsNoSingleUSHexExponentHexPrefixHexExponent
HexPrefix:0x0X
HexExponent:HexExponentStartDecimalDigitsNoSingleUS
HexExponentStart:pPp+P+p-P-
Suffix:FloatSuffixImaginarySuffixoptRealSuffixImaginarySuffixoptImaginarySuffix
FloatSuffix:fF
RealSuffix:L
ImaginarySuffix:i
LeadingDecimal:DecimalInteger0DecimalDigitsNoSingleUS

Floats can be in decimal or hexadecimal format, and must have at least one digit and either a decimal point, an exponent, or aFloatSuffix.

Decimal floats can have an exponent which ise orE followed by a decimal number serving as the exponent of 10.

-1.01e2// 100.01e-2// 0.01-1.175494351e-38F// float.min

Hexadecimal floats are preceded by a0x or0X and the exponent is ap orP followed by a decimal number serving as the exponent of 2.

0xAp0// 10.00x1p2// 4.00x1.FFFFFFFFFFFFFp1023// double.max0x1p-52// double.epsilon

Floating literals can have embedded_ characters after a digit to improve readability, which are ignored.

2.645_7516.022140857E+236_022.140857E+206_022_.140_857E+20_
0.0// double0F// float0.0L// real

The literal may not exceed the range of the type. The literal is rounded to fit into the significant digits of the type.

If a floating literal has a. and a type suffix, at least one digit must be in-between:

1f;// OK, float1.f;// error1.;// OK, double
Note: Floating literals followed byi to denote imaginary floating point values have been deprecated.

Keywords

Keywords are reserved identifiers.

Keyword:abstractaliasalignasmassertauto
bodyboolbreakbyte
casecastcatchcdoublecentcfloatcharclassconstcontinuecreal
dchardebugdefaultdelegatedeletedeprecateddodouble
elseenumexportextern
falsefinalfinallyfloatforforeachforeach_reversefunction
goto
idoubleififloatimmutableimportininoutintinterfaceinvariantirealis
lazylong
macromixinmodule
newnothrownull
outoverride
packagepragmaprivateprotectedpublicpure
realrefreturn
scopesharedshortstaticstructsuperswitchsynchronized
templatethisthrowtruetrytypeidtypeof
ubyteucentuintulongunionunittestushort
versionvoid
wcharwhilewith
__FILE____FILE_FULL_PATH____FUNCTION____LINE____MODULE____PRETTY_FUNCTION__
__gshared__parameters__rvalue__traits__vector

Special Tokens

These tokens are replaced with other tokens according to the following table:

Special Tokens
Special TokenReplaced with
__DATE__string literal of the date of compilation "mmm dd yyyy"
__EOF__tells the scanner to ignore everything after this token
__TIME__string literal of the time of compilation "hh:mm:ss"
__TIMESTAMP__string literal of the date and time of compilation "www mmm dd hh:mm:ss yyyy"
__VENDOR__Compiler vendor string
__VERSION__Compiler version as an integer
Implementation Defined: The replacement string literal for__VENDOR__ and the replacement integer value for__VERSION__.

Special Token Sequences

SpecialTokenSequence:# lineIntegerLiteralFilespecoptEndOfLine# line__LINE__FilespecoptEndOfLine
Filespec:"DoubleQuotedCharactersopt"

Special token sequences are processed by the lexical analyzer, may appear between any other tokens, and do not affect the syntax parsing.

Special token sequences are terminated by the first newline that follows the first# token at the beginning of the sequence.

There is currently only one special token sequence,#line.

This sets the line number of the next source line toIntegerLiteral, and optionally the current source file name toFilespec, beginning with the next line of source text.

For example:

int #line 6 "pkg/mod.d"x;// this is now line 6 of file pkg/mod.d
Implementation Defined: The source file and line number is typically used for printing error messages and for mapping generated code back to the source for the symbolic debugging output.
Introduction
Interpolation Expression Sequence
Copyright © 1999-2025 by theD Language Foundation | Page generated byDdoc on Fri Oct 10 22:16:56 2025

[8]ページ先頭

©2009-2025 Movatter.jp