Bachelor of Technology IN Computer Science and Engineering: A Seminar Report ON D Programming Language
Bachelor of Technology IN Computer Science and Engineering: A Seminar Report ON D Programming Language
Bachelor of Technology IN Computer Science and Engineering: A Seminar Report ON D Programming Language
Submitted to Jawaharlal Nehru Technological University for the Partial fulfillment of the requirement for the Award of Degree in
CONTENTS
1) ABSTRACT---------------------------------------------------------------3 2) INTRODUCTION--------------------------------------------------------4 3) FEATURES----------------------------------------------------------------6 4) IMPLEMENTATION----------------------------------------------------10 5) DEVELOPMENT TOOLS----------------------------------------------11 6) PROBLEMS & CONTRAVERSIS------------------------------------12 7) D vs. OTHER LANGUAGES------------------------------------------14 8) COMPARING D WITH OTHER LANGUAGES--------------------17 9) EXAMPLES---------------------------------------------------------------22 10) BIBLIOGRAPHY---------------------------------------------------------25
ABSTRACT
Growth in Computer Technology has resulted in evolution of many programming languages. Each language was developed to overcome the drawbacks of the previous one. Each computer language comes into existence for a specific purpose. COBOL was being used for commercial applications, FORTRON for scientific applications etc. This resulted in increase in number of programming languages, each programming language being used for a particular purpose. At this stage there came a need to develop a programming language, which could program all applications. This resulted in the development of the D programming language. D programming language is a new addition to the C family of programming languages. D incorporates ideas and improvements from language like C++, Java and C#. Although D programming language incorporates ideas from its predecessors, it also eliminates or repairs features that were present in them. D programming language has now evolved into a major industrial force, one of the reasons being the inclusion of a new feature in it called multiparadigm, which was not present in the earlier languages. 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.
INTRODUCTION
What is D? D is a high level programming language for applications and systems programming. D is a compiled language like C/C++, no byte code like in Java, no interpreter like in Perl. D is targeted to iron out several design flaws of C/C++. You can think of D as an upgraded Version of C++, as the syntax is fairly similar - although it is probably more than that. D is a general purpose systems and applications programming language. It is a higher level language than C++, but retains the ability to write high performance code and interface directly with the operating system API's and with hardware. D is well suited to writing medium to large scale million line programs with teams of developers. D is easy to learn, provides many capabilities to aid the programmer, and is well suited to aggressive compiler optimization Technologys 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. D is the culmination of decades of experience implementing compilers for many diverse languages, and attempting to construct large projects using those languages. D draws inspiration from those other languages (most especially C++) and tempers it with experience and real world practicality.
Who D is for? Programmers who routinely use lint or similar code analysis tools to eliminate bugs before the code is even compiled. People who compile with maximum warning levels turned on and who instruct the compiler to treat warnings as errors. Programming managers who are forced to rely on programming style guidelines to avoid common C bugs. Those who decide the promise of C++ object oriented programming is not fulfilled due to the complexity of it.
Programmers who enjoy the expressive power of C++ but are frustrated by the need to expend much effort explicitly managing memory and finding pointer bugs. Projects that need built-in testing and verification. Teams who write apps with a million lines of code in it. Programmers who think the language should provide enough features to obviate the continual necessity to manipulate pointers directly. Numerical programmers. D has many features to directly support features needed by numerics programmers, like direct support for the complex data type and defined behavior for NaN's and infinities. (These are added in the new C99 standard, but not in C++.) D's lexical analyzer and parser are totally independent of each other and of the semantic analyzer. This means it is easy to write simple tools to manipulate D source perfectly without having to build a full compiler. It also means that source code can be transmitted in tokenized form for specialized applications.
Who D is not for? Realistically, nobody is going to convert million line C or C++ programs into D, and since D does not compile unmodified C/C++ source code, D is not for legacy apps. (However, D supports legacy C API's very well.) Very small programs - a scripting or interpreted language like Python, DMDScript, or Perl is likely more suitable. As a first programming language - Basic or Java is more suitable for beginners. D makes an excellent second language for intermediate to advanced programmers. The D Programming Language Language purists. D is a practical language, and each feature of it is evaluated in that light, rather than by an ideal. For example, D has constructs and semantics that virtually eliminate the need for pointers for ordinary tasks. But pointers are still there, because sometimes the rules need to be broken. Similarly, casts are still there for those times when the typing system needs to be overridden.
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 mixings. 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 codea 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 Paradigm:
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 Javastyle 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. Templates in D can be written in a more function-like style than those in C++.
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. 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 itbut 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. Some of these features are:
D differentiates between mutable references to immutable data, const references to mutable data, and combinations thereof
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.
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. 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. D Compiler for .NET A back-end for the D 2.0 Programming Language Compiler. It compiles the code to CIL bytecode rather than to machine code. The CIL can then be run via a CLR virtual machine.
10
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.
11
12
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 variablelength 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.
13
Feature
Garbage Collection
D
Yes
Functions
Function delegates Function overloading Out function parameters Nested functions Function literals Closures Typesafe variadic arguments Compile time function evaluation Yes Yes Yes Yes Yes Yes Yes Yes
Arrays
Lightweight arrays Resizable arrays Built-in strings Array slicing Array bounds checking Array literals Associative arrays Strong typedefs String switches Aliases Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes
OOP
Object Oriented Multiple Inheritance Yes No
14
interfaces Operator overloading Dynamic class loading Nested classes Inner (adaptor) classes Covariant return types Properties
Performance
Inline assembler Direct access to hardware Lightweight objects Explicit memory allocation control Independent of VM Direct native code gen Table 1 Description of Features: Object Oriented This means support for classes, member functions, inheritance, and virtual function dispatch. Inline assembler Many C and C++ compilers support an inline assembler, but this is not a standard part of the language, and implementations vary widely in syntax and quality. Interfaces Support in C++ for interfaces is weak enough that an IDL (Interface Description Language) was invented to compensate. Yes Yes Yes Yes Yes Yes
15
Modules Many correctly argue that C++ doesn't really have modules. But C++ namespaces coupled with header files share many features with modules. Garbage Collection The Hans-Boehm garbage collector can be successfully used with C and C++, but it is not a standard part of the language. Implicit Type Inference This refers to the ability to pick up the type of a declaration from its initializer. Contract Programming The Digital Mars C++ compiler supports Contract Programming as an extension. Compare some C++ techniques for doing Contract Programming with D. Resizable arrays Part of the standard library for C++ implements resizable arrays, however, they are not part of the core language. A conforming freestanding implementation of C++ (C++98 17.4.1.3) does not need to provide these libraries. Built-in Strings Part of the standard library for C++ implements strings, however, they are not part of the core language. A conforming freestanding implementation of C++ (C++98 17.4.1.3) does not need to provide these libraries. Here's a comparison of C++ strings and D built-in strings. Strong typedefs Strong typedefs can be emulated in C/C++ by wrapping a type in a struct. Getting this to work right requires much tedious programming, and so is considered as not supported.
16
17
The constructor and destructor are always called "this" and "~this". The base class' constructor can be called with "super":
} Comparing class references to "null" is done with the "is" operator, because the "==" can be overloaded!
18
From Java: Switching from Java to D is not a big step. There are a few differences because D is compiled for native code. As both languages are somehow influenced by or inherited from C or C++ syntax, there won't be a big problem: Let me show you some D code that works and is very similar to java code:
// a class called Foo class Foo { // a variable int myInteger; // this is the constructor!! this() { myInteger = 1; } // a function :-) int bar() { for (ubyte i=0; i<2; i++) { myInteger *= 2; } return myInteger; } } // end of class Foo void main() { // creates a new class of Foo Foo myFoo = new Foo(); // calls the function bar in foo three times. writefln("%d",myFoo.bar()); writefln("%d",myFoo.bar()); writefln("%d",myFoo.bar()); }
Output: 4 16 64
19
Difference: In D, we don't have to use a class name that is same name as the file and we import std.stdio to write to the display:
// Import standard-in-out import std.stdio; // Main function int main(char[][] args) { char[] world() { return "world!"; } writefln("Hello "~world()); // We have to return with a int to exit the program (0 means "no error"). return 0; }
Difference: The main function must return an int to the system. Difference: In D "+" and "~" are not the same! The first one (plus) is only for numbers (innt b=5+3, int a=2+b) and the concatenation ("~") is only for arrays (which strings are): char[] str = "Paradise"; char[] text = "Welcome to "~str~".";
From Pascal/Delphi: You will have to get used to the C syntax and the C way of doing things. The C/C++/D syntax looks a bit weird and full of special characters to the human eye :) but it is very efficient your fingers will be pleased. (If you want to go to extremes, learn Perl *g*). The "import" syntax is very similar to "uses" in Pascal, modules are like units and strings work almost the same way as in Delphi: you won't have to worry about string length and zero termination unless your interfacing to one of the "lesser" (*g*) languages.
20
From PHP: I often use PHP. No, not only for websites, i write a lot of networking hacks in it, e.g. IRC-Bots and stuff. So i came up with the idea to "compare" PHP and D. First and most important: D is a compiled language, PHP is interpreted. Although PHP people may think PHP is a pretty fast interpreter because code is pre-compiled and cached and... D is always faster. I even believe that D code could be faster when you add up compile and execute time. D is strictly typed. PHP isn't. You wont be able to multiply your string "45" with integer 3. You also have to declare variables before using them, and they will only hold one certain type. D has a lot more complex object orientation. Learn about that soon (Templates and stuff). You may even be able to compensate the type problem with that as you could write a class that can do anything a PHP variable can do. PHP's got a really great standard library, thats why I have to write functions only for really specialized stuff. D's standard library, Phobos, isn't that large, but there are tons of libs from other people around.
21
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;
22
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;
23
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.
24
BIBLIOGRAPHY
References: 1. "Changelog". D Programming Language 1.0. Digital Mars. http://www.digitalmars.com/d/1.0/changelog.html. Retrieved 10 August 2010. 2. "Changelog". D Programming Language 2.0. Digital Mars. http://www.digitalmars.com/d/2.0/changelog.html. Retrieved 10 August 2010.
25