Jump to content

D (programming language): Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Undid revision 401137302 by 84.26.114.209 (talk)
influence
Line 17: Line 17:
| dialects =
| dialects =
| influenced_by = [[C (programming language)|C]], [[C++ (programming language)|C++]], [[C Sharp (programming language)|C#]], [[Java (programming language)|Java]], [[Eiffel (programming language)|Eiffel]], [[Python (programming language)|Python]], [[Ruby (programming language)|Ruby]]
| influenced_by = [[C (programming language)|C]], [[C++ (programming language)|C++]], [[C Sharp (programming language)|C#]], [[Java (programming language)|Java]], [[Eiffel (programming language)|Eiffel]], [[Python (programming language)|Python]], [[Ruby (programming language)|Ruby]]
| influenced =
| influenced = [[MiniD]], [[DScript]], [[Vala]], [[Go (programming language)|Go]]
| operating_system = DMD: [[Unix-like]], [[Microsoft Windows|Windows]], [[Mac OS X]]
| operating_system = DMD: [[Unix-like]], [[Microsoft Windows|Windows]], [[Mac OS X]]
| license =
| license =

Revision as of 12:12, 20 December 2010

D programming language
Paradigmmulti-paradigm: object-oriented, imperative, meta
Designed byWalter Bright
First appeared1999 (1999)
Stable release
1.065 / October 29, 2010; 13 years ago (2010-10-29)[1]
Preview release
2.050 / October 29, 2010; 13 years ago (2010-10-29)[2]
Typing disciplinestrong, static
OSDMD: Unix-like, Windows, Mac OS X
Filename extensions.d
Websitedigitalmars.com/d
Major implementations
DMD (reference implementation), GDC, LDC
Influenced by
C, C++, C#, Java, Eiffel, Python, Ruby
Influenced
MiniD, DScript, Vala, Go

The D programming language, also known simply as D, is an object-oriented, imperative, multi-paradigm system programming language designed 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, Python, C#, and Eiffel.

Features

D is being designed with lessons learned from practical C++ usage rather than from a theoretical perspective. Even though it uses many C/C++ concepts it also discards some, and as such is not compatible with C/C++ source code. It adds to the functionality of C++ by also implementing design by contract, unit testing, true modules, garbage collection, first class arrays, associative arrays, dynamic arrays, array slicing, nested functions, inner classes, closures, anonymous functions, compile time function execution, 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 within 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 documentation comments, allowing automatic documentation generation.

Programming paradigms

D supports three main programming paradigmsimperative, object-oriented, and metaprogramming.

D 2.0 adds two programming paradigms - functional, concurrent (Actor model).

Imperative

Imperative programming in D is almost identical to C. Functions, data, statements, declarations and expressions work just as in C, and the C runtime library can be accessed directly. Some notable differences between D and C in the area of imperative programming include D's foreach loop construct, which allows looping over a collection, and nested functions, which are functions that are declared inside of another and may access the enclosing function's local variables.

Object oriented

Object oriented programming in D is based on a single inheritance hierarchy, with all classes derived from class Object. D does not support multiple inheritance; instead, it uses Java-style interfaces, which are comparable to C++ pure abstract classes, and mixins, which allow separating common functionality out of the inheritance hierarchy. Additionally, D 2.0 allows declaring static and final (non-virtual) methods in interfaces.

Metaprogramming

Metaprogramming is supported by a combination of templates, compile time function execution, tuples, and string mixins. The following examples demonstrate some of D's compile-time features.

Templates in D can be written in a more function-like style than those in C++. This is a regular function that calculates the factorial of a number:

ulong factorial(ulong n)
{
    if(n < 2)
        return 1;
    else
        return n * factorial(n - 1);
}

Here, the use of static if, D's compile-time conditional construct, is demonstrated to construct a template that performs the same calculation using code that is similar to that of the above function:

template Factorial(ulong n)
{
    static if(n < 2)
        const Factorial = 1;
    else
        const Factorial = n * Factorial!(n - 1);
}

In the following two examples, the template and function defined above are used to compute factorials. The types of constants need not be specified explicitly as the compiler infers their types from the right-hand sides of assignments:

const fact_7 = Factorial!(7);

This is an example of compile time function execution. Ordinary functions may be used in constant, compile-time expressions provided they meet certain criteria:

const fact_9 = factorial(9);

The std.metastrings.Format template performs printf-like data formatting, and the "msg" pragma displays the result at compile time:

import std.metastrings;
pragma(msg, Format!("7! = %s", fact_7));
pragma(msg, Format!("9! = %s", fact_9));

String mixins, combined with compile-time function execution, allow generating D code using string operations at compile time. This can be used to parse domain-specific languages to D code, which will be compiled as part of the program:

import FooToD; // hypothetical module which contains a function that parses Foo source code 
               // and returns equivalent D code
void main()
{
    mixin(fooToD(import("example.foo")));
}


Functional

D 2.0 only.

import std.algorithm, std.range, std.stdio;

int main()
{
    int[] a1 = [0,1,2,3,4,5,6,7,8,9];
    int[] a2 = [6,7,8,9];
    immutable pivot = 5; // must be immutable to allow access from inside mysum
	
    int mysum(int a, int b) pure // pure function
    {
        if (b <= pivot) // ref to enclosing-scope
            return a + b;
        else
            return a;
    }

    auto result = reduce!(mysum)( chain(a1, a2) ); // passing a delegate (closure)
    writeln("Result: ", result); // output is "15"
	
    return 0;
}

Concurrent

D 2.0 only.

import std.concurrency, std.stdio, std.typecons;
 
int main()
{
    auto tid = spawn(&foo); // create an actor object

    foreach(i; 0 .. 10)
        tid.send(i);    // send some integers
    tid.send(1.0f);     // send a float
    tid.send("hello");  // send a string
    tid.send(thisTid);  // send an object (Tid)
	
    receive( (int x) {  writeln("Main thread receives message: ", x);  });
 
    return 0;
}
 
void foo()
{
    bool cont = true;
 
    while (cont)
    {
        receive(  // pattern matching
            (int msg) 	{ writeln("int receive: ", msg); },  // int type
            (Tid sender){ cont = false; sender.send(-1); },  // object type
            (Variant v)	{ writeln("huh?"); }  // any type
        );
    }
}

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 controlled: programmers can add and exclude memory ranges from being observed by the collector, can disable and enable the collector and force a generational or a full collection cycle[3]. 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. Without 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 fully supported, although D can access C++ code that is written to the C ABI. The D parser understands an extern (C++) calling convention for limited linking to C++ objects, but it is only implemented in D 2.0.

On Microsoft Windows, D can access COM (Component Object Model) code.

Versions

The D programming language exists in two versions: 1.0 and 2.0. D 1.0 became stable with the release of D 2.0, on June 17, 2007, and further additions to the language have since been added to 2.0. The release of Andrei Alexandrescu's book The D Programming Language on June 12, 2010 marked the stabilization of D 2.0.

D 1.0

Version 1.00 of the Digital Mars D compiler was released on Jan 2, 2007[4]. Since the release of D 2.0, D 1.0 and its DigitalMars implementation only received bugfixes and insignificant features which did not affect backwards compatibility.

D 2.0

D 2.0 introduced multiple new features, some of which broke compatibility with D 1.0 code[5]. Some of these features are:[6]

  • Support for enforcing const-correctness:
    • D differentiates between mutable references to immutable data, const references to mutable data, and combinations thereof
    • const and immutable keywords are transitive.
  • Limited support for linking with code written in C++.
  • Iteration with foreach over defined range only.
  • Support for "real" closures. Previously closures couldn't be safely returned from functions, because stack-allocated variables would become inaccessible.
  • Support for pure functions which can only access immutable data and call other pure functions. This ensures a pure function has no side effects (the same stack inputs always result in the same outputs and outputs exist only through return values). Together with real closure support this allows Functional Programming in D and also opens theoretical paths for safe automatic threading.
  • nothrow functions.
  • "safe" subset (SafeD), which can't directly access memory not belonging to process (only limited set of casts and pointer arithmetic is possible in such code).
  • Vector operations, i.e. a[] = b[] + c[] (element-wise summation of two dynamic/static arrays), or a[] *= 3 (multiply by 3 each element of array).
  • Classic global storage defaults to Thread Local Storage.
  • Changes to standard Phobos library, including metaprogramming and functional programming additions.
  • Template function literals

Implementation

Most current D implementations compile directly into machine code for efficient execution.

DMD
The Digital Mars D compiler is the official D compiler by Walter Bright. The compiler front-end is licensed under both the Artistic License and the GNU GPL; the source code for the front-end is distributed along with the compiler binaries. The compiler back-end source code is available but not under an open source license.
GDC
A front-end for the GCC back-end, built using the open DMD compiler source code. Development snapshots also support D version 2.0.[7]
LDC
A compiler based on the DMD front-end that uses LLVM as its compiler back-end. The first release quality version was published on January 9, 2009.[8]
D Compiler for .NET
A back-end for the D 2.0 Programming Language Compiler.[9][10] It compiles the code to CIL bytecode rather than to machine code. The CIL can then be run via a CLR virtual machine.

Development tools

Editors and IDEs supporting D include Eclipse, Microsoft Visual Studio, SlickEdit, emacs, vim, SciTE, Smultron, TextMate, Zeus, and Geany among others[11].

  • There are two Eclipse plug-ins for D, Descent and DDT.
  • Visual Studio integration is provided by VisualD.
  • Vim supports both syntax highlighting and code completion (through patched ctags).
  • A bundle is available for TextMate, and the Code::Blocks IDE includes partial support for the language. However, standard IDE features such as code completion or refactoring are not yet available, though they do work partially in Code::Blocks (due to D's similarity to C).
  • A plugin for XCode is available, D for Xcode, that enables D-based projects and development.

Additionally, there are open source D IDEs (some written in the D language itself), such as Poseidon, D-IDE, and Entice Designer. There is also a commercial IDE available, BITPROX Development Environment.

D applications can be debugged using any C/C++ debugger, like GDB or WinDbg, although support for various D-specific language features is extremely limited. On Windows, D programs can be debugged using Ddbg, or Microsoft debugging tools (WinDBG and Visual Studio), after having converted the debug information using cv2pdb. The commercial ZeroBUGS debugger for Linux has experimental support for the D language. Ddbg can be used with various IDEs or from the command line; ZeroBUGS has its own GUI.

Problems and controversies

Division concerning the standard library

The standard library in D is called Phobos. Some members of the D community had thought that Phobos was too simplistic and that it had numerous quirks and other issues, and a replacement of the library called Tango was written.[12] However, in the D 1.0 branch, Tango and Phobos are incompatible due to different runtime support APIs (the garbage collector, threading support, etc). The existence of two libraries, both widely in use, has led to significant problems where some packages use Phobos and others use Tango.

This problem is being addressed in the D 2.0 branch by creating a stand-alone runtime called druntime, and porting both Phobos and Tango to druntime. As of October, 2008, Phobos has been ported to druntime in the newest alpha version of the Digital Mars compiler. Tango is in the process of being ported to D 2.0, and is expected to eventually run on top of druntime. For the foreseeable future, D will have two competing runtime libraries, but in the D 2.0 branch, they will be compatible and usable side-by-side in the same codebase.

Unfinished support for shared/dynamic libraries

Unix's ELF shared libraries are supported to an extent using the GDC compiler.

On Windows systems, DLLs are supported and allow D's garbage collector-allocated objects to be safely passed to C functions, since the garbage collector scans the stack for pointers. However, there are still limitations with DLLs in D including the fact that run-time type information of classes defined in the DLL is incompatible with those defined in the executable, and that any object created from within the DLL must be finalized before the DLL is unloaded.[13]

String handling

The language has three distinct character types (char, wchar and dchar) and three string aliases (string, wstring and dstring, which are simply dynamic arrays of the former) which represent UTF-8, UTF-16 and UTF-32 code units and strings respectively. For performance reasons, string slicing and the length property operate on code units rather than code points (characters), which frequently confuses developers.[14] Since UTF-8 and UTF-16 are variable-length character encodings, access by code point index in constant time is not possible without maintaining additional lookup tables. Code that needs fast random access to code points should convert strings to UTF-32 first, or use lookup tables. However, this is also true for other programming languages supporting Unicode, like Java and C# that use UTF-16, thus may need surrogate pairs to represent some code points.

Examples

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[] in D 1.0, or immutable(char)[] in D 2.0 alpha. Newer versions of the language define string as an alias for char[] or immutable(char)[], however, an explicit alias definition is necessary for compatibility with older versions.

import std.stdio: writefln;

void main(string[] args)
{
    foreach (i, arg; args)
        writefln("args[%d] = '%s'", i, arg);
}

The foreach statement can iterate over any collection, in this case it is producing a sequence of indexes (i) and values (arg) from the array args. The index i and the value arg have their types inferred from the type of the array args.

Using the Tango library, the above code would be as follows:

import tango.io.Stdout;

void main(char[][] args)
{
    foreach (i, arg; args)
        Stdout("args[")(i)("] = '")(arg)("'").newline();
}

Example 2

The following shows several capabilities of D in a very short program. It iterates the lines of a text file named words.txt that contains a different word on each line, and prints all the words that are anagrams of other words.

import std.stdio: writefln;
import std.stream: BufferedFile;
import std.string: tolower, join;

void main()
{
    string[][string] signature2words;

    foreach (string line; new BufferedFile("words.txt"))
        signature2words[line.tolower.sort] ~= line.dup;

    foreach (words; signature2words)
        if (words.length > 1)
            writefln(words.join(" "));
}
  1. The type of signature2words is a built-in associative array that maps string keys to arrays of strings. It is similar to defaultdict(list) in Python.
  2. BufferedFile yields lines lazily, without their newline, for performance the line it yields is just a view on a string, so it has to be copied with dup to have an actual string copy that can be used later (the dup property of arrays returns a duplicate of the array).
  3. The ~= operator appends a new string to the values of the associate array.
  4. tolower and join are string functions that D allows to use with a method syntax, their names are often similar to Python string methods. The tolower converts an ASCII string to lower case and join(" ") joins an array of strings into a single string using a single space as separator.
  5. The sort property sorts the array in place, creating a unique signature for words that are anagrams of each other.
  6. The second foreach iterates on the values of the associative array, it's able to infer the type of words.

See also

References

  1. ^ "Changelog". D Programming Language 1.0. Digital Mars. Retrieved 10 August 2010.
  2. ^ "Changelog". D Programming Language 2.0. Digital Mars. Retrieved 10 August 2010.
  3. ^ "std.gc". D Programming Language 1.0. Digital Mars. Retrieved 6 July 2010.
  4. ^ "D Change Log (older versions)". D Programming Language 1.0. Digital Mars. Retrieved 6 July 2010.
  5. ^ "Migrating D1 Code to D2". D Programming Language 2.0. Digital Mars. Retrieved 6 July 2010.
  6. ^ "D 2.0 Enhancements from D 1.0". D Programming Language 2.0. Digital Mars. Retrieved 6 July 2010.
  7. ^ "gdc project on bitbucket". Retrieved 3 July 2010.
  8. ^ "LLVM D compiler project on DSource". Retrieved 3 July 2010.
  9. ^ "D .NET project on CodePlex". Retrieved 3 July 2010.
  10. ^ Jonathan Allen (15 May 2009). "Source for the D.NET Compiler is Now Available". InfoQ. Retrieved 6 July 2010.
  11. ^ "Wiki4D - Editor Support". Retrieved 3 July 2010.
  12. ^ "Wiki4D - Standard Lib". Retrieved 6 July 2010.
  13. ^ "Wiki4D - BestPractices/DLL". Retrieved 6 July 2010.
  14. ^ Keep, Daniel. "Wiki4D - Text in D". Retrieved 6 July 2010.

Further reading

  • Alexandrescu, Andrei (January 4, 2010). The D Programming Language (1 ed.). Addison-Wesley Professional. ISBN 978-0321635365.
  • Alexandrescu, Andrei (June 15, 2009). "The Case for D". Dr. Dobb's Journal.

External links