# D Programming Language

- Page: https://shared.btbytes.com/p/dlang
- Date: 2020-04-13
- Tags: dlang, programming-language

## Why D?

- [May I Propose D](https://lobste.rs/s/myqc9z/its_time_for_memory_safety_intervention/comments/bmcnfs#c_bmcnfs) for memory safe programing?



## Show off D

- [Functional image processing in D | CyberShadow's blog](https://blog.thecybershadow.net/2014/03/21/functional-image-processing-in-d/)
- [10 features of D that I love](https://bradley.chatha.dev/blog/dlang-propaganda/features-of-d-that-i-love/); [via HN](https://news.ycombinator.com/item?id=44445877)


## Semantics

- [Copy and Move Semantics in the D Programming Language](http://dconf.org/2013/talks/cehreli.pdf), talk by Ali Çehreli at DConf 2013. Describes the differences between `const`, `immutable`; `struct`, `class` etc.,

## Garbage Collection

- See the D [garbage](http://dlang.org/garbage.html) page on how to set GC options on a D program and also collect GC summary on program termination. Very handy!
- [Don’t Fear the Reaper – The D Blog](https://dlang.org/blog/2017/03/20/dont-fear-the-reaper/) [March 2017 on D blog].
- [Concurrent garbage collection for D](http://web.archive.org/web/20130218064734/http://dconf.org/talks/lucarella.html) -- Dconf 2013 talk by Leandro Lucarella. [DGC](http://web.archive.org/web/20091130105155/http://llucax.com.ar/proj/dgc/) (appears to be for D1/tango only)... need to find out if it's been ported to the D2 runtime.
- See [Lucarella's garbage collection posts](http://web.archive.org/web/20091021140733/http://www.llucax.com.ar/blog/blog/tag/understanding%20the%20current%20gc) circa 2009.
- Maxime Chevalier-Boisvert on [D's garbage collection problem](http://pointersgonewild.com/2014/09/09/ds-garbage-collector-problem/) and [Circumventing the D garbage collector](http://pointersgonewild.com/2014/10/26/circumventing-the-d-garbage-collector/); Oct 2014. Her [Higgjs JIT compiler for JS](https://github.com/higgsjs/Higgs) written in D. [D's New GC and Object Allocation Pools](http://forum.dlang.org/thread/nkqymnaolmqpdsvaxszd@forum.dlang.org)
- [Matt Kline](http://bitbashing.io)'s work on [D's owning types (Unique and RefCounted)](http://bitbashing.io/time-for-d-to-own-up.html)
- [Martin Nowak](https://code.dawg.eu/)'s ["Garbage Collection in D"](http://web.archive.org/web/20190327193453/https://code.dawg.eu/talks/2015-03-20-garbage_collection_dmeetup/) talk; Mar 2015.
- [Audio plugin written in D](http://forum.dlang.org/post/hbmbztydvyfwemfnerwb@forum.dlang.org)
- Forum discussion on [garbage collection](http://forum.dlang.org/thread/odtrxzhxgeqisosqgjuf@forum.dlang.org), Dec 2015.
- [Xomb](http://web.archive.org/web/20090225040704/http://wiki.xomb.org/index.php?title=Main_Page) (pronounced zombie), an exokernel operating system written in D without use of GC.
- [The real problem with GC in D - Infognition tech blog](http://www.infognition.com/blog/2014/the_real_problem_with_gc_in_d.html)
- [DmitryOlshansky/gchunt](https://github.com/DmitryOlshansky/gchunt)  is a tool to identify and keep in check GC usage of D projects. [My question about dub flags](http://forum.dlang.org/post/aseowdowbgwarykjmgih@forum.dlang.org)
- [Implementing Alternative Garbage Collector - D Programming Language Discussion Forum](http://forum.dlang.org/post/ms8pp1$74p$1@digitalmars.com)
- ["D generates lot less garbage"](https://www.reddit.com/r/programming/comments/6as1di/serialization_in_d/dhh1lzf/)

[Example code](http://web.archive.org/web/20120718064740/http://dpaste.dzfl.pl/9fbc4827547d) showing GCStats:

```d
import std.stdio;

extern (C)
{
	void gc_stats(GCStats* stats) nothrow;
}

struct GCStats
{
    size_t poolsize;        // total size of pool
    size_t usedsize;        // bytes allocated
    size_t freeblocks;      // number of blocks marked FREE
    size_t freelistsize;    // total of memory on free lists
    size_t pageblocks;      // number of blocks marked PAGE
}

void main()
{
	GCStats stats;
	gc_stats(&stats);
	writeln(stats);
	auto p = new byte[200];
	gc_stats(&stats);
	writeln(stats);
	p = new byte[1000];
	gc_stats(&stats);
	writeln(stats);
	p = new byte[10000];
	gc_stats(&stats);
	writeln(stats);
}

```

To turn on [garbage collection profiling](https://dlang.org/blog/2017/05/24/faster-command-line-tools-in-d/)

```bash
$ max_column_sum_by_key_v1 --DRT-gcopt=profile:1 ngrams.tsv 1 2
max_key: 2006 sum: 22569013
        Number of collections:  132
        Grand total GC time:  246 milliseconds
GC summary:   35 MB,  132 GC  246 ms

```

- [What's the go with the GC these days?](https://forum.dlang.org/thread/mailman.6243.1546725935.29801.digitalmars-d@puremagic.com) ; Jan 2019 D forum discussion. [recent PRs to add a more precise GC](https://forum.dlang.org/post/zyytohtcskqikmheggqv@forum.dlang.org).


- [Profiling D's Garbage Collection with Bpftrace — The Art of Machinery](https://theartofmachinery.com/2019/04/26/bpftrace_d_gc.html); Apr 2019.

### Summary of GC discussion

See June 2016 discussion on the [Garbage collector](http://forum.dlang.org/thread/rarodflehfribrgqeuds@forum.dlang.org)

* [Precise GC](http://forum.dlang.org/thread/hdwwkzqswwtffjehenjt@forum.dlang.org) is in the works. (todo: summarise progress)
* "Only a few language features forces you to use the GC." (which ones?)
* "For most uses you are not forced to use the GC in any form especially with the help of std.experimental.allocator." (How?)
* Current GC is based on a forked version of Boehm GC. So, not easy to upgrade to current version without deep understanding of how D does Thread Local Storage etc.,
* "we can disable the GC so it won't go ahead and scan upon allocation (only time it does)" (how?)

> Memory allocations are /always/ expensive.
> Higher level languages like Java have the benefit of using pools and optimizing for this usage pattern, D does and will never have this.
>  Keep in mind an allocation = usage of malloc + write to returned pointer. -- rikki c.

>The point is, D doesn't have to have a GC. Not using it is way easier
than in most other languages because all the tools to help you
profile it and avoid it are provided by the compiler. Go without a
good GC is a dead language. D without a good GC is just not as good
as it could be. And btw we're generally faster than Go ;-)
> The point is: while a better GC is a work in progress we'll *never*
have a GC that can fit all needs, but it's not as critical as it is
in Go or in C# because we provide other ways to manage memory when
limitations arise. -- cym13

> "Has anyone thought about taking GC from .NET and reusing it in D?"

> One significant point has been already mentioned: cost of write barriers.
I'd like to mention another factor: .NET GC is a copying one, it moves data
around. One good feature of current D is it never moves data, so you can very
easily call C and C++ code and pass pointers to your buffers and stuff and
C/C++ code just takes these pointers and works with them as usual. No pinning,
no marshaling, zero overhead. If you take a moving GC like .NET's, you
immediately make all C/C++ interaction much harder, now you need to worry
about pinning stuff or copying "managed" data to "unmanaged" memory and back.
This is all costly both in terms of CPU cycles and of programmer cycles.
You'll need "FFI", what most other GC-ed languages have to have, and D
doesn't. --thedeemon

### Precise Garbage Collector

[GSoC project](https://github.com/dlang/druntime/pull/1603)

> It is essentially in a similar state that it was when Rainer presented it at DConf2013.
> The version in the pull request is not different from the one Rainer
> presented at all. It's actually the same one, just updated with what has
> been changed in druntime recently and my attempts at making the marking
> phase faster.

## Meta programming3

- [User:Quickfur/Compile-time vs. compile-time - D Wiki](https://wiki.dlang.org/User:Quickfur/Compile-time_vs._compile-time)
- [Metaprogramming in D - From a beginner's perspective](https://maikklein.github.io/2015/08/11/Metaprogramming-D/)
- [Type safe OpenGL - Converting strings into types in D](https://maikklein.github.io/2015/11/14/Converting-strings-to-types/) -- using templates and mixins.

## Debugging

- [support for line numbers and file names in backtraces](http://forum.dlang.org/thread/nwcddbapjubyumbzkdjg@forum.dlang.org?page=4); [Example](http://forum.dlang.org/thread/soobhkdzpwlhezdfwtxi@forum.dlang.org)

## Building

- To build projects using `ldc2` instead of `dmd2` with `dub`, use the `--compiler` switch, thus:  `dub build --compiler=ldc2`
- To build the release version of the software, use the `-b` switch, thus: `dub build -b release`

### Cross Compiling

* [Cross-compiling with LDC - D Wiki](https://wiki.dlang.org/Cross-compiling_with_LDC)

## Serialization

- [Orange](https://github.com/jacob-carlborg/orange) library for serialization.

## Concurrency

- Forum question [What are the real advantages that D offers in multithreading?](http://forum.dlang.org/thread/bqaryebtpkwimcbeyggc@forum.dlang.org)
    + See [Ali's book](http://ddili.org/ders/d.en/index.html) from "Parallelism" to "Fibers".
    + [Getting more fiber in your diet](http://octarineparrot.com/article/view/getting-more-fiber-in-your-diet)
    + [Concurrency in the D Programming Language | 13.1 Concurrentgate](http://www.informit.com/articles/printerfriendly/1609144) from Andrei's D book.


## Range based programming

- [poita.org](http://poita.org/) has couple of articles on range based programming.


## Profiling / performance

- [andrewtrotman / D Profile Viewer — Bitbucket](https://bitbucket.org/andrewtrotman/d-profile-viewer) -- The D language profiler that comes with DMD produces traces that are not designed for humans to read. This program reads a trace file (trace.log) and turns it into an interactive HTML file designed for human navigation and understanding.
- [PGO: Optimizing D's virtual calls](https://johanengelen.github.io/ldc/2016/04/13/PGO-in-LDC-virtual-calls.html)

## D run time

- [Running D without its runtime](https://www.auburnsounds.com/blog/2016-11-10_Running-D-without-its-runtime.html) (experience in building audio plugins in D without  using the D run time.)

## Testing

- Behaviour-driven development with D and cucumber by [Atila Neves at Dconf 2015](https://www.youtube.com/watch?v=bxSPCmwqgYs)


## C/C++ binding

- [Creating D bindings for a C library](http://forum.dlang.org/post/owskieyycptjtnfjcjae@forum.dlang.org) on D forum. "State of the art" as of Nov 2015.
- [Interfacing D with C and Fortran](http://www.active-analytics.com/blog/interface-d-with-c-fortran/) uses `-betterC` technique.

- [(2) Exporting C APIs from Zig, D, and Nim - YouTube](https://www.youtube.com/watch?v=4o_tmccinds)


## Lexing and parsing

- [hsc - Halo 3 scripting lexer, parser, compiler in D](https://github.com/landaire/hsc)
- [Implementing a programming language in D: Lexical Analysis](http://blog.felixangell.com/implementing-a-programming-language-in-d-part-1/)

> Another option is to use a lexer/state machine generator. [Ragel](http://www.colm.net/open-source/ragel/)
supports D and Rust (as of the not-quite-released v7) as target
languages.  [HN](https://news.ycombinator.com/item?id=10803461)

## Memory safety

- [Memory Safety](https://jakobovrum.github.io/d/2016/01/20/memory-safety.html) in by Jakob Øvrum.

## Documenting D code

- [harbored-mod](https://github.com/kiith-sa/harbored-mod) A documentation generator for D with support for both DDoc and Markdown in documentation comments.

## Higher level programming

- [Recursive algebraic types in D](http://www.infognition.com/blog/2014/recursive_algebraic_types_in_d.html)

# Resources

## Introduction

- [Diving into Dlanguage](http://www.informit.com/articles/article.aspx?p=1381876) -- Andrei Alexandrescu explains the basics of [D programming Language](http://dlang.org/).
- [Pragmatic D Tutorial](http://qznc.github.io/d-tut/index.html) by `qznc`.
- [DPaste](http://web.archive.org/web/20120718064740/http://dpaste.dzfl.pl/) -- paste code, run it online, see the output.
- [The Dlang tour](http://dlang-tour.steinsoft.net/), [forum announcement](http://forum.dlang.org/post/n85ucg$3g7$1@digitalmars.com) -- "The basic idea behind this tour is to introduce features of the language with short explanations and example code that is compiled and run online.". See also [playpen](https://github.com/thestinger/playpen), a sandbox used by Rust to create their playpen.
- [glot.io](https://glot.io/) -- an open source pastebin with runnable snippets and API.
- [explore.dgnu.org](http://explore.dgnu.org/)  compiler disassembler.
- [An active D reddit](http://www.reddit.com/r/d_language/)
- [Three cool things about D](http://web.archive.org/web/20120905183952/http://erdani.com/d/three-cool-things-about-d.pdf) - PDF presentation.
- [ApplyYourDLang Channel on Youtube](http://vibed.org/blog/posts/apply-your-dlang)
- [Quick start with D!](https://d.readthedocs.org/en/latest/index.html)
- [D tutorials by Minas Mina](http://minas-mina.com/d-tutorials/)


## Intermediary

- [D Idioms](http://p0nce.github.io/d-idioms/)
- [Template primer, in D](http://semitwist.com/articles/article/view/template-primer-in-d)
- [D templates tutorial](https://github.com/PhilippeSigaud/D-templates-tutorial)

## Articles

- [Evaluating D for games](https://redd.it/2s67en)
- [Functional programming in D](http://beza1e1.tuxen.de/articles/functional_D.html)
- [A comparison between C++ and D](https://maikklein.github.io/post/CppAndD/)
- [D as a scripting language - Infognition tech blog](http://www.infognition.com/blog/2014/d_as_scripting_language.html)

## Tutorials

- Beginner level -- [Tutorials - D-Land](http://d-land.sepany.de/tutorials/) (in German)


## Presentations

- [Dive into D: Slides](http://slides.com/dmitryolshansky/deck/fullscreen/#/) by Dmitry Olshansky; Mar 2016.

## Editor

- [IntelliJ plugin for D language](https://github.com/kingsleyh/DLanguage) -- look at the screenshots. It is a fairly complete IDE with syntax highlighting, auto completion, compile checking, code linting (via Dscanner), navigate to classes etc.,
- [DDT](https://code.google.com/a/eclipselabs.org/p/ddt/wiki/Installation)
  -- the Eclipse based D IDE works as advertised. Use the 3.7(Indigo)
  version. [In Oct 2012, DDT did not work with the latest version of Eclipse: Juno].

- Setting up [TextAdept](http://foicica.com/textadept/) to autocomplete D code using [DCD](https://github.com/Hackerpilot/DCD)

## Blogs

- [The art of machinery](https://theartofmachinery.com/) by Seimon Arneaud.
- [Planet D](http://planet.dsource.org/)
- [nomad.so/tag/d](http://nomad.so/tag/d/)
- [To:goto To;](https://togototo.wordpress.com/) -- D, go, nim, rust ; language benchmarks.
- [Bitbashing.io](http://bitbashing.io/)
- [braingam.es](http://braingam.es/)
- [w0rpzone](https://w0rp.com/blog/)
- [rharriso](http://rharriso.github.io/) -- D, intellij, lldb.
- [infocognition blog](http://www.infognition.com/blog/)
- [leonardo](http://leonardo-m.livejournal.com/)
- [Programming blog of Johan Engelen](http://johanengelen.github.io/)
* [Blog - Bradley Chatha](https://bradley.chatha.dev/Home/Blog), see "Simple JSON Serialiser" etc.,

## Talks

- [Andrei Alexandrescu Three Cool Things about D - YouTube](https://www.youtube.com/watch?v=FdpaBHyQNco); Dec 2015.
- [Functional Programming with D ― Andreas Zwinkau](http://beza1e1.tuxen.de/articles/functional_D.html)
- [DConf 2013 Day 1 Talk 5: Using D Alongside a Game Engine by Manu Evans - YouTube](https://www.youtube.com/watch?v=FKceA691Wcg)

## Read code

- [dmin.io -- URL shortener in D](https://github.com/yamadapc/dmin.io/). Uses [vibe.d](http://vibed.org).
	- See also [ccbikai/Sink: ⚡ A Simple / Speedy / Secure URL Shortener with Analytics, 100% run on Cloudflare.](https://github.com/ccbikai/Sink), written in JS.
- [DUB registry](http://code.dlang.org/) -- list of D library packages; dub can be installed on Mac OS X using `brew`.
- [facebook/warp](https://github.com/facebook/warp) -- A fast preprocessor for C and C++
- [https://github.com/karpovr/veda](https://github.com/karpovr/veda) uses vibe.d
- [terminix -A tiling terminal emulator for Linux using GTK+ 3](https://github.com/gnunn1/terminix). GTK + D.


## Discussions

- [Andrei Alexandrescu's AMA on reddit](https://redd.it/3ioy9b) post his decision to work on D full time. [Aug 2015]
- [Why didn't D language become mainstream comparing to Golang?](https://www.quora.com/Why-didnt-D-language-become-mainstream-comparing-to-Golang/answer/Laeeth-Isharc)
- [D Roadmap etc.,](https://redd.it/3k0oyt); specifically DIPs, Review Queue.
- [RejectedSoftware Forums](http://forum.rejectedsoftware.com/) for vibe.d, dub etc discussion forum.


## Contributing to D development

- [starting as a contributor](http://wiki.dlang.org/Starting_as_a_Contributor)

## Software written in D

- [Commercial video processing app in D (experience report)](http://forum.dlang.org/post/rivvjmrqmhaacfwxwish@forum.dlang.org)

## Developing and distributing D software

- [Carlos Soriano Sánchez / GtkDApp · GitLab](https://gitlab.com/csoriano/GtkDApp). This is a template for a Linux app, using Flatpak, GTK+, Meson, and D.

## Misc

- [Dlang comic strips](http://dlangcomicstrips.tumblr.com/)
- [Codeeval](https://www.codeeval.com/) supports D.
- [Rust v D](https://users.rust-lang.org/t/rust-vs-dlang-i-want-more-experienced/4472/8)
- [SDLang](https://sdlang.org/) -- "simple declarative langauge" used by dub project for configuration.

### User experience

- [D for HFT](http://forum.dlang.org/post/ezbjetbckibowtcryamw@forum.dlang.org) by [SD](https://www.linkedin.com/in/saurabh-das-a6a76421)
- [wilzbach comments on An introduction to non-uniform random sampling using D](https://www.reddit.com/r/programming/comments/4z4sp7/an_introduction_to_nonuniform_random_sampling/d6t3ow0). Experience report of using D for six months. [Forum link](http://forum.dlang.org/thread/ckwjysezxagpnrdkbtpq@forum.dlang.org)
- [The Expressive C++17 Coding Challenge in D](https://seb.wilzba.ch/b/2018/02/the-expressive-c17-coding-challenge-in-d/)
- [Advent of D – The Scribbler of the Rueful Countenance](http://jordi.inversethought.com/blog/advent-of-d/) -- see day 18 for concurrency, 8 for mixins, 7 for ctRegex.
- [Why D is a good choice for writing a language](http://web.archive.org/web/20180816183200/https://lambdahackers.com/@b4asile/why-d-is-a-good-choice-for-writing-a-toy-language-4vapyvas5a)

### Libraries

For some reason, many D programmers have this "collection of D
libraries", which is *interesting* in the sense that more than one
developer has found it just easy to write their own library to do X...

- [adamruppe/arsd](https://github.com/adamdruppe/arsd)
- [CyberShadow/ae](https://github.com/CyberShadow/ae)
- [kxml](https://github.com/opticron/kxml) -- recommended in D
  cookbook for XML parsing large files.
- [treecount](https://github.com/drones-for-ag/treecount) SDL2 etc.,
- [runtimer](https://github.com/chrishalebarnes/runtimer) Application runtime configuration for applications built in the D programming language.
- [dstruct](https://github.com/w0rp/dstruct) -- has `WeakReference(T), Some(T), Option(T), HashMap(K,V), HashSet(T), Matrix(T), Matrix(T, rowCount, columnCount), BasicGraph(T, edgeDirection)`.
- [Tango-D2](https://github.com/SiegeLord/Tango-D2)
- [mbierlee/poodinis: A dependency injection framework for D with support for autowiring.](https://github.com/mbierlee/poodinis) and [aedi](https://github.com/aermicioi/aedi)
- [Literate](https://github.com/zyedidia/Literate) -- A modern literate programming system written in D
- [Abscissa/scriptlike: Utility library to help you write script-like programs in D](https://github.com/Abscissa/scriptlike)
- [sociomantic-tsunami/ocean: General purpose, platform-dependant, high-performance library for D](https://github.com/sociomantic-tsunami/ocean) extends [Tango-D2](https://github.com/SiegeLord/Tango-D2), which is a D2 port of the Tango project.
- [Derelict](https://github.com/DerelictOrg) -- D bindings to popular C libraries.
- [tamediadigital/asdf: fast and simple JSON for Dlang](http://web.archive.org/web/20180627104154/https://github.com/tamediadigital/asdf)
- [tamediadigital/je: json extract: a tool to extract data from json](https://github.com/tamediadigital/je)
- [Ocean](https://github.com/sociomantic-tsunami/ocean) is a general purpose library, compatible with both D1 and D2, with a focus on supporting the development of high-performance, real-time applications. developed by Sociomantic. **runs only on linux**. What's inside -- `core, io, math, net, stdc, task, text, time, util`.

In addition to those of CWEB:

* Markdown based -- very easy to read and write Literate source.
* Generates readable and commented code in the target language (the generated code is usable by others)
* Reports syntax errors back from the compiler to the right line in the literate source
* Supports any language including syntax highlighting and pretty printing in HTML
* Compatible with Vim ([literate.vim](https://github.com/zyedidia/literate.vim))
* Highly customizable (you can add your own HTML or CSS)
* Runs fast -- wc.lit compiled for me in 7ms for both code and HTML output
* Supports TeX equations with `$` notation.

Inspired from CWEB:

* Automatically generates hyperlinks between code sections
* Formatted output similar to CWEB

- [future -- async combinator library for D](https://github.com/evenex/future/)
- [DlangScience](https://github.com/DlangScience)

## Interop

- [taylorh140/Calling-NET-from-D: An example of how I set up a call to .NET](https://github.com/taylorh140/Calling-NET-from-D)

[The power of reflection | Átila on Code](https://atilaoncode.blog/2020/01/22/the-power-of-reflection/)

```
import autowrap;
mixin(
    wrapDlang!(
        LibraryName("mylib"),
        Modules(
            Module("mymodule"),
            Module("myothermodule"),
        )
    )
);
```

> The code above, when compiled, will generate a Python extension (shared library) that exposes every D function marked as “export” in the modules “mymodule” and “myothermodule” as Python functions. It’ll even convert their names from camelCase to snake_case. Any D exceptions thrown will become Python exceptions. D structs and classes become Python classses. If the original D functions take a D string, you’ll be able to pass Python strings to them in user code. Modulo bugs, this… works! The code shown above is the only code that needs to be written. Setting up the build system takes more work!
