Jump to content

D (programming language)

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Intgr (talk | contribs) at 10:02, 4 April 2007 (rvv: Undid revision 120179084 by 61.17.14.70 (talk)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

D
Paradigmmultiparadigm
Designed byWalter Bright
First appeared1999
Stable release
1.010 / March 24 2007
Typing disciplinestrong, static
Websitedlang.org
Major implementations
DMD, GDC
Influenced by
C, C++, 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 predominantly 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, such as Java, C# and Eiffel. A stable version, 1.0, was released on January 2, 2007.

Features

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 source code. 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 Java style 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 system 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, and by simply calling C's malloc and free directly. Garbage collection can be disabled for individual objects, or even for a full program, if more control over memory management is desired. The manual gives many examples of how to implement different highly optimized memory management schemes for when garbage collection is inadequate in a program.

Interaction with other systems

C's application binary interface (ABI) 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.

Even though D is still under development, changes to the language are no longer made regularly since version 1.0 of January 2, 2007. The design is currently virtually frozen, and newer releases focus on resolving existing bugs. Version 1.0 is not completely compatible with older versions of the language and compiler. The official compiler by Walter Bright defines the language itself.

  • 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; sources for the front end are distributed along with the compiler binaries. The compiler back end is proprietary.
  • GDC: D Compiler, built using the DMD compiler front end and the GCC back end.

Development tools

D is still lacking professional grade development tools, and this is a major obstacle holding back many potential users. D modes exist for emacs, vi and Smultron, there is a bundle available for TextMate, and Code::Blocks IDE includes partial support for the language. However, standard IDE features such as code completion and refactoring do not yet exist. One tool is Ddbg, a D debugger for windows that can be used with Code::Blocks IDE and from the command line. Interactive debuggers that are written for C or C++ also work with D since it uses the same object file formats. However, debugging features are extremely limited using them.

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 indexes (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 runtime
	int count, allocated;
	// however you can choose to avoid array initialization
	int[10000] 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