介绍一下D语言--翻译

来源:互联网 发布:中国博士论文数据库 编辑:程序博客网 时间:2024/05/13 01:57
 

D程序设计语言

来自于维基百科

D 程序语言, 简称为D,是由Digital Mars公司的Walter Bright设计的一种面向对象的, 命令方式的,多范例的系统级程序设计语言. D语言起源于重构C++语言这一想法,仅管它受C++语言的极大影响,但它并不是C++语言的一种变体.D语言被设计成具备C++的一些特征,并且也具备其他语言的一些优良特点,如Java,C#和Eiffer. 当前D语言的版本是在2007年一月二是发布的1.0版.在2007年6月发布的2.0是它的一个实验版本

D语言的特点

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 strictly backward compatible with C/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, limited form of 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 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 documentation comments, but so far only the compiler supplied by Digital Mars implements a documentation generator.

 

一些例子

D supports three main programming paradigms—imperative, object-oriented, and metaprogramming.

 

[edit] Imperative

Imperative programming is almost identical to C. Functions, data, statements, declarations and expressions work just as C, and the C runtime library can be accessed directly.

 

面向对象

OO programming in D is based on a single inheritance hierarchy, with all classes derived from class Object. Multiple inheritance is possible from interfaces (interfaces are a lot like C++ abstract classes).

 

元程序设计

Metaprogramming is supported by a combination of templates, compile time function execution, tuples, and string mixins.

 

内存管理

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.

 

与其它系统的交互

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 fully 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 only implemented in the currently experimental D 2.0.

[edit] D 2.0

D 2.0, a branch version of D that includes experimental features, was released on June 17, 2007. Some of these features include support for enforcing const-correctness, limited support for linking with code written in C++, and support for "real" closures.

[edit] 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 1.0 Compiler, built using the DMD compiler front end and the GCC back end.

[edit] Development tools

D is still lacking support in many IDEs, which is a potential stumbling block for some users. Editors used include Entice Designer, emacs, vi and Smultron among others. 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.

There are at least two actively developed Eclipse plug-ins for D, Descent and Mmrnmhrm.

Additionally, there are open source D IDEs written in the D language itself such as Poseidon, which does feature code completion, syntax highlighting, and integrated debugging.

D applications can be debugged using any C/C++ debugger, like GDB or WinDBG, although support for various fundamental language features is extremely limited then. Debuggers with explicit support for D are Ddbg for Windows and ZeroBUGS for Linux. Ddbg can be used with various IDEs or from the command line, ZeroBUGS has its own GUI.

[edit] Problems and controversies

[edit] Operator overloading

D operator overloads are significantly less powerful than the C++ counterparts. A popular example is the opIndex, which does not allow returning references. This makes assignments like obj[i] = 5; impossible. The D solution is the opIndexAssign operator, which only fixes this very case, but not variations like obj[i] += 5;. In addition, the C++ way of returning a reference allows for the usage of the returned type's overloaded assignment operator. This is currently not possible in D. D 2.0 will fix this by introducing an opIndexLvalue - like operator overload, and deprecating opIndexAssign.

[edit] Division around and lack of functionality in the standard library

D's standard library is called Phobos, and is often perceived as being far too simplistic, in addition to having numerous quirks and other issues. The tango project is an attempt at fixing this by writing an alternative standard library. However, phobos and tango are currently incompatible due to different implementation of the Object class (which leads to GC difficulties). The existence of two de-facto standard libraries could lead to significant problems where some packages use phobos and others use tango.

[edit] Lack of a clear goal

D is often stated as being a "fixed and improved C++". This can lead to featuritis due to the fact that new features are added just because they are perceived as being useful.

[edit] Unfinished support for shared/dynamic libraries

Unix' ELF shared libraries are supported to an extent using the GDC compiler. On Windows systems, DLLs are supported. D's garbage collector allocated objects can 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 are incompatible with those defined in the executable, and that any object created from within the DLL must be finalized before the DLL is unloaded.[1]

[edit] Examples

[edit] 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[]. Newer versions of the language define string as an alias for char[], however, an explicit alias definition is necessary for compatibility with older versions.

import std.stdio;       // for writefln() int main(string[] args){    foreach(i, 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. The index i and the value a have their types inferred from the type of the array args.

[edit] Example 2

This illustrates the use of associative arrays to build much more complex data structures.

import std.stdio;       // for writefln() int main(string[] args){    // Declare an associative array with string keys and    // arrays of strings as data    string[] [string] 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 (string person, string[] items; container)        display_item_count(person, items);    return 0;//success} void display_item_count(string person, string[] items){    writefln(person, " is carrying ", items.length, " items.");}

[edit] 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. int main(string[] args)                 {    // '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[]', aliased as 'string'    // 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(string[] 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.    string argcmsg  = "argc = %d";    string allocmsg = "allocated = %d";    writefln(argcmsg ~ ", " ~ allocmsg,            argspecs(args).count,argspecs(args).allocated);    return 0;} /** * Stores a single command line argument. */class CmdLin{    private    {        int _argc;        string _argv;        static uint _totalc;    }     public:        /**         * Object constructor.         * params:         *   argc = ordinal count of this argument.         *   argv = text of the parameter         */        this(int argc, string 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;        }         string argv() // A property that returns arg text        {            return _argv;        }         wstring suffix() // A property that returns ordinal suffix        {            wstring 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);        }}

[edit] Example 4

This example demonstrates some of the power of D's compile-time features.

/* * Templates in D are much more powerful than those in C++.  Here we can see * the use of static if, D's compile-time conditional construct, to easily * construct a factorial template. */template Factorial(ulong n){    static if( n <= 1 )        const Factorial = 1;    else        const Factorial = n * Factorial!(n-1);} /* * Here is a regular function that performs the same calculation.  Notice how * similar they are. */ulong factorial(ulong n){    if( n <= 1 )        return 1;    else        return n * factorial(n-1);} /* * Finally, we can compute our factorials.  Notice that we don't need to * specify the type of our constants explicitly: the compiler is smart enough * to fill in the blank for us, since it already knows the type of the * right-hand side of the assignment. */const fact_7 = Factorial!(7); /* * This is an example of compile-time function evaluation: ordinary functions * may be used in constant, compile-time expressions provided they meet * certain criteria. */const fact_9 = factorial(9); /* * Here we can see just how powerful D's templates are: we are using the * std.metastrings.Format template to perform printf-style data formatting, * and displaying the result using the message pragma. */import std.metastrings;pragma(msg, Format!("7! = %s", fact_7));pragma(msg, Format!("9! = %s", fact_9)); /* * Our task done, we can forcibly stop compilation.  This program need never * actually be compiled into an executable! */static assert(false, "My work here is done.");
原创粉丝点击