Movatterモバイル変換


[0]ホーム

URL:


www.digitalmars.com

D Programming Language 1.0


Last update Sun Dec 30 20:34:42 2012

Articles

Tools

Forums

Community

Appendices

Books

Overview

What is D?

D is a general purpose systems and applications programming language.It is a higher level language than C++, but retains the abilityto write high performance code and interface directly with theoperating systemAPI'sand with hardware.D is well suited to writing medium to large scalemillion line programs with teams of developers. D is easyto learn, provides many capabilities to aid the programmer,and is well suited to aggressive compiler optimization technology.D Man

D is not a scripting language, nor an interpreted language.It doesn'tcome with aVM,a religion, or an overridingphilosophy. It's a practical language for practical programmerswho need to get the job done quickly, reliably, and leave behindmaintainable, easy to understand code.

D is the culmination of decades of experience implementingcompilers for many diverse languages, and attempting to constructlarge projects using those languages. D draws inspiration fromthose other languages (most especially C++) and tempers it withexperience and real world practicality.

Why D?

Why, indeed. Who needs another programming language?

The software industry has come a long way since the C language wasinvented.Many new concepts were added to the language with C++, but backwardscompatibility with C was maintained, including compatibility withnearly all the weaknesses of the original design.There have been many attempts to fix those weaknesses, but thecompatibility issue frustrates it.Meanwhile, both C and C++ undergo a constant accretion of newfeatures. These new features must be carefully fitted into theexisting structure without requiring rewriting old code.The end result is very complicated - the C standard is nearly500 pages, and the C++ standard is about 750 pages!C++ is a difficult and costly language to implement,resulting in implementation variations that make it frustratingto write fully portable C++ code.

C++ programmers tend to program in particular islands of the language,i.e. getting very proficient using certain features while avoidingother feature sets. While the code is usually portable from compilerto compiler, it can be hard to port it from programmer to programmer.A great strength of C++ is that it can support many radicallydifferent styles of programming - but in long term use, theoverlapping and contradictory styles are a hindrance.

C++ implements things like resizable arrays and string concatenationas part of the standard library, not as part of the core language.Not being part of the core language has severalsuboptimal consequences.

Can the power and capability of C++ be extracted, redesigned,and recast into a language that is simple, orthogonal,and practical?Can it all be put into a packagethat is easy for compilerwriters to correctly implement, andwhich enables compilers to efficiently generate aggressivelyoptimized code?

Modern compiler technology has progressed to the point where languagefeatures for the purpose of compensating for primitive compilertechnology can be omitted. (An example of this would be the 'register' keyword in C, a moresubtle example is the macro preprocessor in C.)We can rely on modern compiler optimization technology to notneed language features necessary to get acceptable code quality out ofprimitive compilers.

Major Goals of D

Features To Keep From C/C++

The general look of D is like C and C++. This makes it easier to learnand port code to D. Transitioning from C/C++ to D should feel natural.The programmer will not have to learn an entirely new way of doing things.

Using D will not mean that the programmer will become restricted to aspecialized runtime vm (virtual machine) like the Java vm or theSmalltalk vm.There is no D vm, it's a straightforward compiler that generateslinkable object files.D connects to the operating system just like C does.The usual familiar tools likemake will fit right in withD development.

Features To Drop

Who D is For

Who D is Not For

Major Features of D

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

Object Oriented Programming

Classes

D's object oriented nature comes from classes.The inheritance model is single inheritance enhancedwith interfaces. The class Object sits at the rootof the inheritance hierarchy, so all classes implementa common set of functionality.Classes are instantiatedby reference, and so complex code to clean up after exceptionsis not required.

Operator Overloading

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

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 aboutmultiple imports of the same module, no need to wrapper headerfiles with#ifndef/#endif or#pragma once kludges,etc.

Declaration vs Definition

C++ usually requires that functions and classes be declared twice - the declarationthat goes in the .h header file, and the definition that goes in the .c sourcefile. 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.

Example:

class ABC{int func() {return 7; }staticint z = 7;}int q;

There is no longer a need for a separate definition of member functions, staticmembers, externs, nor for clumsy syntaxes like:

int ABC::func() { return 7; }int ABC::z = 7;extern int q;

Note: Of course, in C++, trivial functions like{ return 7; }are written inline too, but complex ones are not. In addition, ifthere are any forward references, the functions need to be prototyped.The following will not work in C++:

class Foo{    int foo(Bar *c) { return c->bar(); }};class Bar{  public:    int bar() { return 3; }};

But the equivalent D code will work:

class Foo{int foo(Bar c) {return c.bar; }}class Bar{int bar() {return 3; }}

Whether a D function is inlined or not is determined by theoptimizer settings.

Templates

D templates offer a clean way to support generic programming whileoffering the power of partial specialization.Template classes and template functions are available, alongwith variadic template arguments and tuples.

Associative Arrays

Associative arrays are arrays with an arbitrary data type asthe index rather than being limited to an integer index.In essence, associated arrays are hash tables. Associativearrays make it easy to build fast, efficient, bug-free symboltables.

Real Typedefs

C and C++ typedefs are really typealiases, as no newtype is really introduced. D implements real typedefs, where:

typedefint handle;

really does create a new typehandle. Type checking isenforced, and typedefs participate in function overloading.For example:

int foo(int i);int foo(handle h);

Documentation

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

Although third party tools exist to do this for C++, they have someserious shortcomings:

Functions

D has the expected support for ordinary functions includingglobal 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, andfunction closure techniques.

Function Literals

Anonymous functions can be embedded directly into an expression.

Dynamic Closures

Nested functions and class member functions can be referencedwith closures (also called delegates), making generic programmingmuch easier and type safe.

In Out and Inout Parameters

Not only does specifying this help make functions moreself-documenting, it eliminates much of the necessity for pointerswithout sacrificing anything, and it opens up possibilitiesfor more compiler help in finding coding problems.

Such makes it possible for D to directly interface to awider variety of foreign API's. There would be no need forworkarounds like "Interface Definition Languages".

Arrays

C arrays have several faults that can be corrected:

D arrays come in several varieties: pointers, static arrays, dynamicarrays, and associative arrays.

SeeArrays.

Strings

String manipulation is so common, and so clumsy in C and C++, thatit needs direct support in the language. Modern languages handlestring concatenation, copying, etc., and so does D. Strings area direct consequence of improved array handling.

Resource Management

Automatic Memory Management

D memory allocation is fully garbage collected. Empirical experiencesuggests that a lot of the complicated features of C++ are necessaryin order to manage memory deallocation. With garbage collection, thelanguage gets much simpler.

There's a perception that garbage collection is for lazy, juniorprogrammers. I remember when that was said about C++, after all,there's nothing in C++ that cannot be done in C, or in assemblerfor that matter.

Garbage collection eliminates the tedious, error prone memoryallocationtracking code necessary in C and C++. This not only means muchfaster development time and lower maintenance costs,but the resulting program frequently runsfaster!

Sure, garbage collectors can be used with C++, and I've used themin my own C++ projects. The language isn't friendly to collectors,however, impeding the effectiveness of it. Much of the runtimelibrary code can't be used withcollectors.

For a fuller discussion of this, seegarbage collection.

Explicit Memory Management

Despite D being a garbage collected language, the new and deleteoperations can be overridden for particular classes so thata custom allocator can be used.

RAII

RAII is a modern software development technique to manage resourceallocation and deallocation. D supports RAII in a controlled,predictable manner that is independent of the garbage collectioncycle.

Performance

Lightweight Aggregates

D supports simple C style structs, both for compatibility withC data structures and because they're useful when the full powerof classes is overkill.

Inline Assembler

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

Many D implementations will also support intrinsic functionsanalogously to C's support of intrinsics for I/O port manipulation,direct access to special floating point operations, etc.

Reliability

A modern language should do all it can to help the programmer flushout 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.

Contracts

Contract Programming (invented by B. Meyer) is a revolutionarytechniqueto aid in ensuring the correctness of programs. D's version ofDBC includes function preconditions, function postconditions, classinvariants, and assert contracts.SeeContracts for D's implementation.

Unit Tests

Unit tests can be added to a class, such that they are automaticallyrun upon program startup. This aids in verifying, in every build,that class implementations weren't inadvertently broken. The unittests form part of the source code for a class. Creating thembecomes a natural part of the class development process, as opposedto throwing the finished code over the wall to the testing group.

Unit tests can be done in other languages, but the result is kludgyand the languages just aren't accommodating of the concept.Unit testing is a main feature of D. For library functions it worksout great, serving both to guarantee that the functionsactually work and to illustrate how to use the functions.

Consider the many C++ library and application code bases out there fordownload on the web. How much of it comes with *any* verificationtests at all, let alone unit testing? Less than 1%? The usual practiceis if it compiles, we assume it works. And we wonder if the warningsthe compiler spits out in the process are real bugs or just natteringabout nits.

Along with Contract Programming, unit testing makes D far and awaythe best language for writing reliable, robust systems applications.Unit testing also gives us a quick-and-dirty estimate of the qualityof some unknown piece of D code dropped in our laps - if it has nounit tests and no contracts, it's unacceptable.

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 theuse of macros or preprocessing commands. The debug syntax enablesa consistent, portable, and understandable recognition that realsource code needs to be able to generate both debug compilations andrelease compilations.

Exception Handling

The superiortry-catch-finally model is used rather than justtry-catch. There's no need to create dummy objects just to havethe destructor implement thefinally semantics.

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.

synchronizedint func() { ... }

Synchronized functions allow only one thread at a time to beexecuting that function.

The synchronize statement puts a mutex around a block of statements,controlling access either by object or globally.

Support for Robust Techniques

Compile Time Checks

Runtime Checking

Compatibility

Operator precedence and evaluation rules

D retains C operators and their precedence rules, order ofevaluation rules, and promotion rules. This avoids subtlebugs that might arise from being so used to the way Cdoes things that one has a great deal of trouble findingbugs due to different semantics.

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 needto write wrapper functions, parameter swizzlers, nor code to copyaggregate members one by one.

Support for all C data types

Making it possible to interface to any C API or existing Clibrary code. This support includes structs, unions, enums,pointers, and all C99 types.D includes the capability toset the alignment of struct members to ensure compatibility withexternally imposed data formats.

OS Exception Handling

D's exception handling mechanism will connect to the waythe underlying operating system handles exceptions inan application.

Uses Existing Tools

D produces code in standard object file format, enabling the useof standard assemblers, linkers, debuggers, profilers, exe compressors,and other analyzers, as well as linking to code written in otherlanguages.

Project Management

Versioning

D provides built-in support for generation of multiple versionsof a program from the same text. It replaces the C preprocessor#if/#endif technique.

Deprecation

As code evolves over time, some old library code gets replacedwith newer, better versions. The old versions must be availableto support legacy code, but they can be marked asdeprecated.Code that uses deprecated versions will be normally flaggedas illegal, but would be allowed by a compiler switch.This will make it easy for maintenanceprogrammers to identify any dependence on deprecated features.

Sample D Program (sieve.d)

/* Sieve of Eratosthenes prime numbers */import std.stdio;bool[8191] flags;int main(){int i, count, prime, k, iter;    writefln("10 iterations");for (iter = 1; iter <= 10; iter++)    {count = 0;flags[] = 1;for (i = 0; i < flags.length; i++){if (flags[i])    {prime = i + i + 3;k = i + prime;while (k < flags.length){    flags[k] = 0;    k += prime;}count += 1;    }}    }    writefln("%d primes", count);return 0;}




Forums |Comments | D  |Search |Downloads |Home
Copyright © 1999-2012 by Digital Mars ®, All Rights Reserved |Page generated byDdoc.

[8]ページ先頭

©2009-2025 Movatter.jp