D (programming language)
Paradigm | multiparadigm |
---|---|
Designed by | Walter Bright |
First appeared | 1999 |
Stable release | |
Typing discipline | strong, static |
Website | dlang |
Major implementations | |
DMD, DGCC | |
Influenced by | |
C++, Java |
D is an object-oriented, imperative, multiparadigm system programming language by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is predominately influenced by that language, it is not a variant of C++. D has redesigned some C++ features and has been influenced by concepts used in other programming languages.
Features
NOTE: The feature set and detailed design of the language is not quite finalized as at the time of writing this.
D is being designed with lessons learned from practical C++ usage rather than from a theoretical perspective. It uses many C++ concepts but discards some, such as strict backwards compatibility with C. It adds to the functionality of C++ by also implementing design by contract, unit testing, true modules, automatic memory management (garbage collection), first class arrays, associative arrays, dynamic arrays, array slicing, nested functions, inner classes, closures (anonymous functions), lazy evaluation and has a reengineered template syntax. D retains C++'s ability to do low-level coding, and adds to it with support for an integrated inline assembler. C++ multiple inheritance is replaced by single inheritance with interfaces and mixins. D's declaration, statement and expression syntax closely matches that of C++.
The inline assembler typifies the differences between D and application languages like Java and C#. An inline assembler lets programmers enter machine-specific assembly code in with standard D code—a technique often used by systems programmers to access the low-level features of the processor needed to run programs that interface directly with the underlying hardware, such as operating systems and device drivers.
D has built-in support for embedded documentation comments (called Ddoc), but so far only the compiler supplied by DigitalMars implements a documentation generator.
Memory management
Memory is usually managed with garbage collection, but specific objects can be finalized immediately when they go out of scope. Explicit memory management is possible using the overloaded operators new and delete, as well as simply calling C's malloc and free directly. It is also possible to disable garbage collection for individual objects, or even for the entire program if more control over memory management is desired. The manual gives numerous examples as to how to implement different extremely optimized memory management schemes when garbage collection won't quite do it for part of the program.
Interaction with other systems
C's ABI (Application Binary Interface) is supported as well as all of C's fundamental and derived types, enabling direct access to existing C code and libraries. C's standard library is part of standard D. Unless you use very explicit namespaces it can be somewhat messy to access, as it is spread throughout the D modules that use it -- but the pure D standard library is usually sufficient unless interfacing with C code.
C++'s ABI is not supported, although D can access C++ code that is written to the C ABI, and can access C++ COM (Component Object Model) code. The D parser understands an extern (C++) calling convention for linking to C++ objects, but it is not yet implemented.
Implementation
Current D implementations compile directly into native code for efficient execution.
D is still under development, and changes to the language are made regularly. Although the design is almost frozen, it is possible that some of these changes could break D programs written for older versions of the language and compiler. The official compiler by Walter Bright defines the language itself, and it is currently in the beta testing state.
- DMD Compiler: the Digital Mars D compiler, the official D compiler by Walter Bright. The compiler front end is licensed under both the Artistic License and the GNU GPL license, sources for the front end are distributed along with the compiler binaries. The compiler back end is copyrighted closed-source.
- Gnu D Compiler (GDC): the GNU D Compiler, built making the DMD compiler front end and the GCC compiler back end work together.
Examples
Keywords are in blue, strings in red, comments in green.
Example 1
This example program prints its command line arguments. The main function is the entry point of a D program, and args is an array of strings representing the command line arguments. A string in D is an array of characters, represented by char[].
import std.stdio; // for writefln() int main(char[][] args) { foreach(int i, char[] a; args) writefln("args[%d] = '%s'", i, a); return 0; }
The foreach statement can iterate over any collection, in this case it is producing a sequence of keys (i) and values (a) from the array args.
Example 2
This illustrates the use of associative arrays to build much more complex data structures.
import std.stdio; // for writefln() int main() { // Declare an associative array with string keys and // arrays of strings as data char[][] [char[]] container; // Add some people to the container and let them carry some items container["Anya"] ~= "scarf"; container["Dimitri"] ~= "tickets"; container["Anya"] ~= "puppy"; // Iterate over all the persons in the container foreach (char[] person, char[][] items; container) display_item_count(person, items); return 0; } void display_item_count(char[] person, char[][] items) { writefln(person, " is carrying ", items.length, " items."); }
Example 3
This heavily annotated example highlights many of the differences from C++, while still retaining some C++ aspects.
#!/usr/bin/dmd -run /* sh style script syntax is supported! */ /* Hello World in D * To compile: * dmd hello.d * or to optimize: * dmd -O -inline -release hello.d * or to get generated documentation: * dmd hello.d -D */ import std.stdio; // References to commonly used I/O routines. void main(char[][] args) // 'void' for main means return 0 by default. { // 'writefln' (Write-Formatted-Line) is the type-safe 'printf' writefln("Hello World, " // automatic concatenation of string literals "Reloaded"); // Strings are denoted as a dynamic array of chars 'char[]' // auto type inference and built-in foreach foreach(argc, argv; args) { auto cl = new CmdLin(argc, argv); // OOP is supported writefln(cl.argnum, cl.suffix, " arg: %s", cl.argv); // user-defined class properties. delete cl; // Garbage Collection or explicit memory management - your choice } // Nested structs, classes and functions struct specs { // all vars automatically initialized to 0 at compile-time int count, allocated; // however you can choose to avoid array initialization int[1000000] bigarray = void; } specs argspecs(char[][] args) // Optional (built-in) function contracts. in { assert(args.length > 0); // assert built in } out(result) { assert(result.count == CmdLin.total); assert(result.allocated > 0); } body { specs* s = new specs; // no need for '->' s.count = args.length; // The 'length' property is number of elements. s.allocated = typeof(args).sizeof; // built-in properties for native types foreach(arg; args) s.allocated += arg.length * typeof(arg[0]).sizeof; return *s; } // built-in string and common string operations, eg. '~' is concatenate. char[] argcmsg = "argc = %d"; char[] allocmsg = "allocated = %d"; writefln(argcmsg ~ ", " ~ allocmsg, argspecs(args).count,argspecs(args).allocated); } /** * Stores a single command line argument. */ class CmdLin { private { int _argc; char[] _argv; static uint _totalc; } public: /** * Object constructor. * params: * argc = ordinal count of this argument. * argv = text of the parameter */ this(int argc, char[] argv) { _argc = argc + 1; _argv = argv; _totalc++; } ~this() // Object destructor { // Doesn't actually do anything for this example. } int argnum() // A property that returns arg number { return _argc; } char[] argv() // A property that returns arg text { return _argv; } wchar[] suffix() // A property that returns ordinal suffix { wchar[] suffix; // Built in Unicode strings (UTF-8, UTF-16, UTF-32) switch(_argc) { case 1: suffix = "st"; break; case 2: suffix = "nd"; break; case 3: suffix = "rd"; break; default: // 'default' is mandatory with "-w" compile switch. suffix = "th"; } return suffix; } /** * A static property, as in C++ or Java, * applying to the class object rather than instances. * returns: The total number of commandline args added. */ static typeof(_totalc) total() { return _totalc; } // Class invariant, things that must be true after any method is run. invariant { assert(_argc > 0); assert(_totalc >= _argc); } }
See also
External links
- Digital Mars: D programming language
- Open Directory Project: D programming language
- DSource, an open source community for the D Programming Language.
- Dprogramming.com, home of the DFL windowing library.
- Wiki4D, "the wiki for the d programming language"
- gdc, D front-end for GCC
- The Programming Language Shootout
- D Documentation Wiki