Está en la página 1de 9

D programming language

( Submited by Seenia Francis , Lecturer in CSE, JEC Thrissur,


seeniaf@yahoo.com)

D is a general purpose systems and applications programming language. Its focus is on


combining the power and high performance of C and C++ with the programmer productivity of modern
languages like Ruby and Python. It is also influenced by java and c#. Special attention is given to the
needs of quality assurance, documentation, management, portability and reliability.

D is not a scripting language, nor an interpreted language. It doesn't come with a VM, a
religion, or an overriding philosophy. It's a practical language for practical programmers who need to get
the job done quickly, reliably, and leave behind maintainable, easy to understand code. The D language
is statically typed and compiles directly to machine code. It's multiparadigm, supporting many
programming styles: imperative, object oriented, and metaprogramming. It's a member of the C

History

During the past few decades, programming languages have come a long way. In comparison to
the dawn of UNIX and C, when compiled languages were just getting their start, today's world is full of
languages with all sorts of goals and features. The D programming language, also known simply as D,
is an object-oriented, imperative, multiparadigm system programming language by Walter Bright of
Digital Mars. He is the man who wrote the first ANSI C++ compiler for DOS.

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++. C++ is a difficult and costly language to implement, resulting in
implementation variations that make it frustrating to write fully portable C++ code. A stable version, 1.0,
was released on January 2, 2007. An experimental version, 2.0, was released on June 17, 2007. The
latest relese is 1.036 (stable) on October 20, 2008.

Major Goals of D

• Reduce software development costs by at least 10% by adding in proven productivity


enhancing features and by adjusting language features so that common, time-consuming bugs
are eliminated from the start.
• Make it easier to write code that is portable from compiler to compiler, machine to machine, and
operating system to operating system.
• Support multi-paradigm programming, i.e. at a minimum support imperative, structured, object
oriented, and generic programming paradigms.
• Have a short learning curve for programmers comfortable with programming in C or C++.
• Provide low level bare metal access as required.
• Make D substantially easier to implement a compiler for than C++.
• Be compatible with the local C application binary interface.
• Have a context-free grammar.
• Easily support writing internationalized applications.
• Incorporate Contract Programming and unit testing methodology.
• Be able to build lightweight, standalone programs.
• Reduce the costs of creating documentation.

Implementation

DMD: 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: A front end for the GCC back end, built using the open DMD compiler sources. Development
snapshots also support D version 2.0.

LDC: A new compiler, also based on open DMD sources that uses LLVM as its compiler back end. It's
in early development.

Programming paradigms

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

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.

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.

Major Features of D

This section lists some of the more interesting features of D in various categories.

1. Object Oriented Programming

Classes : D's object oriented nature comes from classes. The inheritance model is single inheritance
enhanced with interfaces. The class Object sits at the root of the inheritance hierarchy, so all classes
implement a common set of functionality. Classes are instantiated by reference, and so complex code
to clean up after exceptions is not required.

Operator Overloading : Classes can be crafted that work with existing operators to extend the type
system to support new types. An example would be creating a bignumber class and then overloading
the +, -, * and / operators to enable using ordinary algebraic syntax with them.

2. Productivity

Modules : Source files have a one-to-one correspondence with modules. Instead of #include'ing the text
of a file of declarations, just import the module. There is no need to worry about multiple imports of the
same module, no need to wrapper header files with #ifndef/#endif or #pragma once kludges, etc.

Declaration vs Definition : C++ usually requires that functions and classes be declared twice - the
declaration that goes in the .h header file, and the definition that goes in the .c source file. This is an
error prone and tedious process. Obviously, the programmer should only need to write it once, and the
compiler should then extract the declaration information and make it available for symbolic importing.
This is exactly how D works.

Templates : D templates offer a clean way to support generic programming while offering the power of
partial specialization. Template classes and template functions are available, along with variadic
template arguments and tuples.
Associative Arrays : Associative arrays are arrays with an arbitrary data type as the index rather than
being limited to an integer index. In essence, associated arrays are hash tables. Associative arrays
make it easy to build fast, efficient, bug-free symbol tables.

Real Typedefs : C and C++ typedefs are really type aliases, as no new type is really introduced. D
implements real typedefs, where, really does create a new type .Type checking is enforced, and
typedefs participate in function overloading.

Documentation : Documentation has traditionally been done twice - first there are comments
documenting what a function does, and then this gets rewritten into a separate html or man page. And
naturally, over time, they'll tend to diverge as the code gets updated and the separate documentation
doesn't. Being able to generate the requisite polished documentation directly from the comments
embedded in the source will not only cut the time in half needed to prepare documentation, it will make
it much easier to keep the documentation in sync with the code. Ddoc is the specification for the D
documentation generator. This page was generated by Ddoc, too.

3. Functions

D has the expected support for ordinary functions including global functions, overloaded functions,
inlining of functions, member functions, virtual functions, function pointers, etc. In addition:

Nested Functions : Functions can be nested within other functions. This is highly useful for code
factoring, locality, and function closure techniques.

Function Literals : Anonymous functions can be embedded directly into an expression.

Dynamic Closures : Nested functions and class member functions can be referenced with closures
(also called delegates), making generic programming much easier and type safe.

In Out and Inout Parameters : Not only does specifying this help make functions more self-
documenting, it eliminates much of the necessity for pointers without sacrificing anything, and it opens
up possibilities for more compiler help in finding coding problems. Such makes it possible for D to
directly interface to a wider variety of foreign API's. There would be no need for workarounds like
"Interface Definition Languages".

4. Arrays

In D, the [] for the array go on the left:

Eg : int[3]* array; // declares a pointer to an array of 3 ints


long[] func(int x); // declares a function returning an array of longs

which is much simpler to understand. D arrays come in several varieties: pointers, static arrays,
dynamic arrays, and associative arrays.

5. Strings

String manipulation is so common, and so clumsy in C and C++, that it needs direct support in the
language. Modern languages handle string concatenation, copying, etc., and so does D. Strings are a
direct consequence of improved array handling.

6. Resource Management

Automatic Memory Management : D memory allocation is fully garbage collected. Empirical experience
suggests that a lot of the complicated features of C++ are necessary in order to manage memory
deallocation. With garbage collection, the language gets much simpler.

Explicit Memory Management : Despite D being a garbage collected language, the new and delete
operations can be overridden for particular classes so that a custom allocator can be used.

RAII : RAII is a modern software development technique to manage resource allocation and
deallocation. D supports RAII in a controlled, predictable manner that is independent of the garbage
collection cycle.

7. Performance

Lightweight Aggregates : D supports simple C style structs, both for compatibility with C data structures
and because they're useful when the full power of classes is overkill.

Inline Assembler : Device drivers, high performance system applications, embedded systems, and
specialized code sometimes need to dip into assembly language to get the job done. While D
implementations are not required to implement the inline assembler, it is defined and part of the
language. Most assembly code needs can be handled with it, obviating the need for separate
assemblers or DLL's.

8. Reliability

A modern language should do all it can to help the programmer flush out bugs in the code. Help can
come in many forms; from making it easy to use more robust techniques, to compiler flagging of
obviously incorrect code, to runtime checking.
Unit Tests : Unit tests can be added to a class, such that they are automatically run upon program
startup. This aids in verifying, in every build, that class implementations weren't inadvertently broken.
The unit tests form part of the source code for a class. Creating them becomes a natural part of the
class development process, as opposed to throwing the finished code over the wall to the testing group.

Debug Attributes and Statements : Now debug is part of the syntax of the language. The code can be
enabled or disabled at compile time, without the use of macros or preprocessing commands. The debug
syntax enables a consistent, portable, and understandable recognition that real source code needs to
be able to generate both debug compilations and release compilations.

Exception Handling : The superior try-catch-finally model is used rather than just try-catch. There's no
need to create dummy objects just to have the destructor implement the finally semantics.

9. Synchronization

Multithreaded programming is becoming more and more mainstream, and D provides primitives to build
multithreaded programs with. Synchronization can be done at either the method or the object level.
Synchronized functions allow only one thread at a time to be executing that function. The synchronize
statement puts a mutex around a block of statements, controlling access either by object or globally.

10. Compatibility

Direct Access to C API's : Not only does D have data types that correspond to C types, it provides
direct access to C functions. There is no need to write wrapper functions, parameter swizzlers, nor code
to copy aggregate members one by one.

Support for all C data types : Making it possible to interface to any C API or existing C library code. This
support includes structs, unions, enums, pointers, and all C99 types. D includes the capability to set the
alignment of struct members to ensure compatibility with externally imposed data formats.

OS Exception Handling: D's exception handling mechanism will connect to the way the underlying
operating system handles exceptions in an application.

Standard library

The standard library in D is called Phobos. Some members of the D community think Phobos is too
simplistic and that it has numerous quirks and other issues, and a replacement of the library called
Tango was written. However, in the D 1.0 branch, Tango and Phobos are incompatible due to different
runtime libraries (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.

Problems and controversies

Operator overloading : D operator overloads are sometimes less powerful than the C++ counterparts.
An example is the opIndex, which suffers because D does not allow returning references. This makes
operations like obj[i]++; impossible.

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.

Other : D has no built-in support for weak references, although there are some libraries that implement
them. Operations on Unicode strings are unintuitive (compiler accepts Unicode source code, standard
library and foreach constructs operate on UTF-8, but string slicing and length property operate on bytes
rather than characters).

Two Example Programs.

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 invariant(char)[] in D 2.0 alpha.

import std.stdio: writefln;

void main(string[] args)

foreach(i, a; args)

writefln("args[%d] = '%s'", i, a);

}
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.

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;

import std.stream;

import std.string;

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(" "));

The type of 'signature2words' is a built-in associative array that maps string keys to arrays of strings. It
equals about to defaultdict(list) in Python. 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 '~=' appends a new string to the values of the associate array. '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 lowercase and join(" ") joins an array of strings into a
single string using a single space as separator. The 'sort' sorts the array in place, creating an unique
signature for words that are anagrams of each other. The second foreach iterates on the values of the
associative array, it's able to infer the type of 'words'.

Future

The following new features for D are planned for post, but the details have not been worked out:

1. Template inheritance.
2. Array operations.

Conclusion

D is a promising language that is able to supply many different needs in the programming
community. Features such as arrays, SH syntax and type inference make D comparable to languages,
such as Ruby and Python, in those regards, while still leaving the door open for low-level system
programmers with the inline assembler and other features. D can be applied to many programming
paradigms—be they object-oriented with classes and interfaces, generic programming with templates
and mixins, procedural programming with functions and arrays, or any other. The garbage collector
relieves the programmer of the need to manage all memory chunks manually, while still making it
possible for those situations in which manual memory management is preferred. It brings in features of
imperative languages, such as Lisp, with the lazy storage class, which drastically speeds up efficiency.
The language is relatively stable, with the occasional new features or changes added in.

In short, D is a language ready for real-world deployment.

References

http://www.digitalmars.com/d/2.0/overview.html

http://en.wikipedia.org/wiki/D_(programming_language)

http://www.linuxjournal.com/article/9307

http://d-programming-language.org/

También podría gustarte