Author Archives: Michael Parker

DConf Online 2020: How to Participate

DConf Online 2020
As I write, we are a little over 24 hours away from the start of DConf Online 2020, our first online version of DConf. All of the talks for Day One are uploaded, the livestreams are scheduled, and #BeerConf is almost ready to launch.

The details

All of the prerecorded talks will be accessible on our YouTube channel via the DConf Online 2020 playlist (look under the live chat box for the full playlist; you may have to scroll down). Use the live chat to ask questions during the talk. The speaker will be available to provide short answers in the chat box. Longer, more complex answers, and/or additional context, will be provided in the Q & A livestream. The speaker will let you know if he is providing more detail in the livestream. If you don’t want to tab over to the livestream and miss part of the talk, the livestream will be saved to our channel once it ends and you will be able to go back and watch any part of it you may be interested in.

Each day, the Q & A livestream will begin at 13:50 UTC. Each speaker will be in the livestream 5 minutes before his talk begins and will be available to answer questions for the duration of the talk and for up to 15 minutes after. As I said above, you may ask questions in the live chat of the talk, but you may also ask them in the live chat of the livestream (and will likely have to if you have questions after the talk ends). Depending on the amount of time available, the number of questions, and the speaker’s schedule, each speaker may stay longer than 15 minutes after the talk, but is not required to.

Please note that speakers are not expected to answer off-topic questions. It’s entirely up to them if they do so.

I’ll be hosting the livestream throughout each day. I’ll be chatting with the speakers about their talks and D in general to fill in the dead time when no one is asking questions. After the conference is over, I intend to chop up the livestream and upload the Q & A session for each talk as separate videos.

On Day One, we have an Ask us Anything session scheduled with Walter and Átila. This will take place in the Q & A livestream for that day. We also have a livecoding session by Adam Ruppe scheduled. That will take place in a separate livestream when the Day One Q & A livestream ends (links below). Adam will be monitoring the chat as he codes, so he will answer any questions you have.

The livestream links:

BeerConf

From 18:00 UTC November 20, we’ll be running a Jitsi Meet instance for our online version of BeerConf. Everyone is welcome to join, no alcohol required. If you aren’t familiar with BeerConf, you can read a brief description of it on the DConf Online 2020 website. You can also read about it here on the blog.

BeerConf will run all weekend long. You can come and go as you please, during talks, in between talks, day time, night time, anytime!

See this D forum thread for details on how to join.

The prizes

Throughout the event, I’ll be announcing different ways for viewers to win various prizes. We’ll be handing out t-shirts, coffee mugs, and other items from the DLang Swag Emporium (and maybe a DMan shirt or two). I’ll announce the details in the Q & A livestream and, if a talk is ongoing, in the talk’s live chat. Sometimes, winning the prize may involve tweeting, in which case I’ll announce the details on Twitter, so be sure to follow us if you aren’t already.

Additionally, everyone who asks a question to which a speaker provides an answer will be entered into at least two random drawings. There will be one random drawing at the end of each day which includes those eligible on that day. The winners of these drawings will receive a $50 Amazon eGift card. The winner of the two-day drawing will receive a $100 Amazon eGift card. If you win on Day One, you will not be eligible to win on Day Two, but both winners will be eligible to win the two-day drawing.

Funding for all prizes comes from the D Language Foundation General Fund. You can contribute by buying DConf Online 2020 swag or other items from the DLang Swag Emporium, by selecting the D Language Foundation as your preferred AmazonSmile charity and shopping through smile.amazon.com, or by donating directly to the General Fund.

Swag prize winners will be announced in a talk’s live chat and/or the Q & A livestream, depending on the nature of the prize task. For prize tasks that take place on Twitter, winners will not be announced, but will be notified through private message. Amazon eGift card winners will be announced in the livestream. Since YouTube apparently no longer allows private messages, winners on YouTube will be instructed on how to claim their prize when they are announced in the livestream.

Enjoy!

We want to thank all of our speakers for volunteering their time to put together these presentations and making themselves available for Q & A. Without them, this event would not be possible. We hope you enjoy DConf Online 2020!

D 2.094.0, DConf Online Schedule, and SAOC 2020

Digital Mars D logo

The end of September saw a new release of the reference D compiler, DMD 2.094.0, sporting the latest language features. That was followed not long after by a beta release of LDC, the LLVM-based D compiler, based on the same frontend version. The DMD 2.094.1 patch release entered into beta a few days before this post was published. Meanwhile, the first Milestone of the Symmetry Autumn of Code has come to an end, and the DConf Online 2020 schedule has been published.

DMD 2.094.0

This release of DMD incorporates 21 major changes and 119 fixed Bugzilla issues, thanks to the efforts of 49 contributors. Here are some highlights.

This ain’t your grandpa’s in parameter

Back in the days of yore, when DMD was still a pre-1.000 alpha, the D language supported in, out, and inout parameter storage classes. They had the following meanings:

  • in (input), the default, was the bog standard function parameter which is a mutable copy of its argument, i.e., the normal passed-by-value parameter.
  • out (output) parameters were passed by reference and, upon function entry, initialized to the default initializer value for the parameter type (e.g., 0 for int, float.nan for float, etc).
  • inout (input/output) parameters were passed unmodified by reference.

When D2 came along, there were some changes. inout was replaced by the ref keyword and out kept the same meaning, but now there was an explicit restriction that these parameters could only take lvalue references; rvalue references, commonly used in C++, were forbidden as arguments. With in, things became a little muddy. And that brings us to scope parameters, a D2 feature that has evolved over time.

For quite some time, it was not fully implemented and only affected parameters that were delegates: the compiler would only allocate a closure for a scope delegate if it absolutely needed to. The D2 version of in was intended to be equivalent to const scope, but it was never fully implemented and was effectively equivalent to const. Today, scope is intended to be applied to ref or out parameters to prevent them from escaping the function scope, and with DMD 2.092.0, in finally became equivalent to const scope. In DMD 2.094.0, in has been reimagined and extended to solve the rvalue reference issue.

The first thing to know about the new in is that it’s still equivalent to const scope, but now the compiler is free to choose whether to pass an in parameter’s argument by reference or by value. The second thing to know is that in parameters can now take rvalue references. All of this is implemented behind the -preview=in command line switch first introduced in 2.092.0.

Like any preview feature, the new in may or may not make it into the language proper, and if it does it might not be without changes. But for now, it’s there and waiting to be put through its paces. The more people using it, pushing it, and looking for holes, the sooner we can know if this is the in we’re looking for.

Ddoc Markdown support

Quite a while ago, Ddoc, D’s built-in documentation syntax, was enhanced to support some Markdown features. It was hidden beind a -preview switch. Now, that switch is no longer necessary—Ddoc supports Markdown out of the box.

Note that this is not full-on Markdown. For example, although asterisks are supported for italic and bold text, underscores are not. But Markdown-style links, code blocks, inline code, and images are supported. For the details, see the Documentation Generator documentation.

More speed please

Since the release of DMD 2.091.0, the DMD binaries in the Windows release packages are being compiled with LDC. This is a good thing because LDC has a better optimizer than DMD, which makes DMD’s fast compile times even faster. Now, LDC is used to compile binary releases on Linux, OSX, and FreeBSD. As a side effect, there are now no more 32-bit releases for FreeBSD, and additional binary tools are no longer included. If you need them, you can still pick them up from https://digitalmars.com/ or from older DMD releases.

Download

The latest release of DMD is always available for download at https://dlang.org/download.html. The latest Beta or Release Candidate can always be found there as well. You can also find links to download LDC and GDC, the GCC-based D compiler (which is now an official component of GCC). While you’re there, if you enjoy the D programming language, consider leaving a tip to the D Language Foundation.

DConf Online 2020 Schedule

DConf Online 2020 is coming together nicely. Over the two days of November 21 and 22, we have nine prerecorded talks, a livestream Q & A with the language maintainers, and a livecoding session. We’ll also be bringing our annual real-world BeerConf to the virtual world.

The talks

The prerecorded talks will be scheduled to premiere on our YouTube channel at the UTC times listed on the schedule. For the duration of each talk and for 15 minutes after, each speaker will be avalailable in a separate livestream for questions and answers related to the talk. We want to record the questions and answers verbally for posterity. The idea is that viewers of the prerecorded talk can ask questions in the video’s chat, or ask in the livestream chat during or up to 15 minutes after the talk. The speaker will read the questions out loud. Short answers will be provided both verbally and in the chat. Longer answers will be provided verbally only. Commenters asking questions during the talk will be notified in the chat if their questions were selected so that they don’t have to tab out to the Q & A and miss a portion of the talk. They can go back and watch the Q & A video later on our YouTube channel.

The livestream Q & A with the language maintainers will run on our YouTube channel. We’ll be streaming a video conference call and questions will be taken from the livestream chat. During the livestream, some viewers will be invited to join in on the conference call and ask their question directly in order to provide more opportunity for follow up and feedback. Details on how to participate will be released on the day of the livestream.

Throughout the weekend, we’ll be handing out prizes to random viewers. Eligibility details will be provided during the course of the event, so pay attention!

BeerConf

BeerConf is a real-world DConf tradition dating back to the first edition of the conference, though the name didn’t come around until Ethan Watson coined it a few years later. Every year, we designate a gathering spot where DConf attendees can mingle every evening to unwind. The DConf days are where we all wear our D programmer hats and spend our time talking about our favorite programming language, but BeerConf is our chance to be human. We still talk about D, but we also have the opportunity to go beyond the code and get to know each other on a more personal level.

So for DConf Online, we’re taking BeerConf online. On the evening (UTC) of Friday, November 20, we’ll open the BeerConf video conference to any and all, and we’ll leave it open all weekend. Despite the name, no alcohol is required to participate. All you need is an internet connection and a web browser, and you can come and go as you please. We’ve been running monthly BeerConf events since June of this year, so we know that, though it’s not quite the same as being in the same place, it’s still a lot of fun.

We hope to see you November 20–22 in BeerConf and DConf!

Symmetry Autumn of Code

We are currently running our third annual Symmetry Autumn of Code (SAOC). Sponsored by Symmetry Investments, the event provides an opportunity for D programmers to make a little money working on projects aimed at improving the D ecosystem. Particpants each get paid $1000 for the successful completion of each of three milestones. At the end of a fourth milestone, the progress of each participant will be evaluated by the SAOC committee, then one participant will be awarded a final $1000 payment, and receive free registration and reimbursement for transportation and lodging for the next real-world DConf.

We currently have four programmers coding away toward their goals. Milestone 1 has just come to an end and Milestone 2 is set to begin. The participants will soon be sending in their milestone reports, their mentors will send in progress evaluations, and the SAOC Committee will review it all to determine if everyone has put forth the effort required to continue through the event (we expect no issues on that front!). You can follow the progress of each participant, and perhaps provide them with some timely advice, through their weekly updates in the D General Forum. Search for “SAOC2020”.

Symmetry Investments and the D Language Foundation are Hiring

Digital Mars D logo

The D Language Foundation is hiring! Thanks to generous funding from Symmetry Investments, we are looking to fill two (mostly) non-programming positions geared toward improving the D ecosystem. Symmetry is also offering a bounty for a specific improvement to DUB, the D build tool and package manager. And on top of all of that, they are hiring D programmers.

D Pull Request/Issue Manager

A lot of good work goes into the D Programming Language GitHub repositories. Unfortunately, some of that good work sometimes gets left behind. A similar story can be told for our Bugzilla database, where some issues are fixed almost as soon as they’re reported and others fall victim to a lack of attention. Efforts have been made in the past to tidy things up, but without someone in a position to permanently keep at it, it’s a task that is never complete.

The D Language Foundation is looking for one or two motivated individuals to take on that permanent position, get the work done, and keep things running smoothly. Symmetry Investements is generously funding this role with $50,000 per year for one person, or $25,000 per year for each of two.

The ideal candidate is someone who:

  • is familiar with git, GitHub, and Bugzilla;
  • is familiar enough with D to be able to review simple pull requests;
  • is able to recognize when more specialized reviews are required and
  • is able to proofread English text (for reviewing documentation and web site pull requests).

Examples of the role’s responsibilities include:

  • ensuring all pull requests follow procedure;
  • reviewing simple pull requests;
  • finding appropriate reviewers for more complex pull requests;
  • ensuring that pull requests are reviewed in a timely manner;
  • reviving stale pull requests;
  • coordinating between pull request submitters and reviewers to prevent pull requests from going stale;
  • closing pull requests that are no longer valid;
  • identifying Bugzilla issues that are duplicates or invalid;
  • identifying Bugzilla issues that are candidates for bounties;
  • publicizing Bugzilla issues in need of a champion and
  • other related tasks.

We are hoping to hire from within the D community, though we will accept queries from anyone. If you are interested in taking on the role, please send your resume to social@dlang.org. You should also indicate if you are willing to do the job full time (just you) or part time (share the responsibilities with someone else).

Community Relations Assistant

I’ve been working with the D Language Foundation for the past three years. Much of what I do falls loosely in the category of Community Relations. These days, I’m in need of an assistant. Symmetry Investments is providing $600 per month for the role.

The job will involve a number of different activities as the need arises, such as:

  • seeking out guest authors and projects to highlight for the D Blog;
  • monitoring our social media accounts;
  • sending out messages from the D Language Foundation (such as thank you notes to new donors);
  • assisting with maintenance of pages at dlang.org and dconf.org;
  • assisting with the organization of events like DConf and SAOC and
  • any odd jobs that pop up now and again.

If you have good communication skills, an optimistic disposition, and enthusiasm for the D Programming Language, I’d like to talk to you. I don’t need a resume. Instead, please send an email to social@dlang.org explaining why you’re the right person for the job.

DUB Bounty

Symmetry Investments logoDUB has become a critical component in the D ecosystem. A significant number of projects depend on it and we need it to be able to meet a wide range of project needs. To that end, there are certainly improvements to be made. One such is in how DUB determines which of a project’s source files are in need of recompilation. Currently, DUB follows in the tradition of the venerable make and uses timestamp comparisons to make that determination.

A new generation of version control and build tools (git, buck, bazel, scons, waf, plz, and more) rely on file checksums to assess the need for action. This is a much more robust approach because it detects actual changes in file content. Timestamps can change in any number of irrelevant ways. Robustness is important if one is to depend on a build working properly even when files are moved, copied, and shared across people, machines, and teams. As hashes are fast to compute on modern hardware, the impact on speed is very low.

Symmetry Investments is offering a $2,000 bounty to the programmer who either converts DUB’s use of timestamp-dependent builds to use SHA-1 hashing throughout, or implements it as a global option to preserve the current behavior.

For inspiration, see this clip from Linus Torvald’s Google talk, and the article Build-Systems Should Use Hashes Over Timestamps. Note that shasum $(git ls-files) in Phobos takes 0.05 seconds on a warm SSD drive in a desktop machine.

Anyone interested in taking on this bounty should contact social@dlang.org beforehand. Anyone interested in contributing to the bounty amount can do so via the bounty card Support for Hash-Based Recompilation in DUB at our Task Bounties page.

Symmetry Autumn of Code 2020 Projects and Participants

Symmetry Investments logoThe verdict is in! Five programmers will be participating in the 2020 edition of the Symmetry Autumn of Code. Over the next three weeks, they will be working with their mentors to take the goals they outlined in their applications and turn them into concrete tasks across four milestones. Then, on September 15th, the first milestone gets under way.

Throughout the event, anyone can follow the progress of each project through the participants’ weekly updates in the General forum. Please don’t ignore those posts! You might be able to offer suggestions to help them along the way.

And now a little about the SAOC 2020 participants and their projects.

  • Robert Aron is a fourth-year Computer Science student at University POLITEHNICA of Bucharest. For his project, he’ll be implementing D client libraries for the Google APIs. When it’s complete, we’ll be able to interact with Google service APIs, such as GDrive, Calendar, Search, and GMail, directly from D. The goal is to complete the project by the end of the event.
  • Michael Boston is currently developing a game in D. For his SAOC project, he’ll be taking some custom data structures he’s developed and adapting them to be more generic. The ultimate goal is to get Michael’s modified implementation merged into Phobos. Should that not happen, the library will still be part of the D ecosystem once it’s complete.
  • Mihaela Chirea is a fourth-year Computer Engineering student at University POLITEHNICA of Bucharest. Mihaela will spend SAOC 2020 improving DMD as a library. Part of this project will involve soliciting community feedback regarding proposed changes, so anyone interested in using DMD as a library should keep an eye out for Mihaela’s posts in the D forums.
  • Teona Severin is a first-year master’s degree student at University POLITEHNICA of Bucharest who will be working on a mini DRuntime in order to bring D to low-performance microcontrollers based on ARM Cortex-M CPUs. Currently, D can run on such systems when compiled as -betterC, but the end goal of this project is to get enough of a functional DRuntime to write “a simple application that actively uses a class.“
  • Adela Vais is yet another fourth-year Computer Engineering student at University POLITEHNICA of Bucharest. For her project, she’ll be implementing a new D backend for GNU Bison. Currently, Bison has an experimental LALR1 parser for D. Adela’s implementation will be a GLR parser intended to overcome the limitations of the LALR1 parser.

The strong showing from Bucharest is down to the work of Razvan Nitzu and Eduard Staniloiu. They have introduced a number of students to the D programming language and encouraged them in seeking out projects beneficial both to their education and to the D community. Plus, Razvan and Edi will be participating in SAOC 2020 as mentors.

On behalf of the SAOC 2020 committee, the D Language Foundation, and Symmetry Investments, I want to thank everyone who submitted an application and wish the participants the best of luck in the coming months.

Deadlines and New Swag

SAOC 2020 Application Deadline

Symmetry Investments logoThe deadline for Symmetry Autumn of Code (SAOC) 2020 applications is on August 16th. There’s work to be done and money to be paid (courtesy of Symmetry Investments). If you know of a project that can keep an eager programmer busy for at least 20 hours a week over the course of four months, please advertise it in the forums and add it to the project ideas list if it isn’t already there.

As for potential applicants, remember that experience with D is not necessary. Experience with another language can be transferred to D “on the job”, with a mentor to guide the way. Tell your friends and spread the word to other programming communities. This is a great way to bring new faces to the D community and the new ideas they may bring with them. All the information on how to apply and how to become a mentor is available on the SAOC 2020 page.

DConf Online 2020 Swag

DConf Online 2020 Logo

The DConf Online 2020 submission deadline of August 31 will be here before we know it. If you haven’t put a submission together yet, head over to the DConf Online 2020 home page (and/or the announcement here on the blog) for the details on what we’re looking for and how to go about it. Everyone whose submission is accepted for the event schedule will receive a t-shirt and coffee mug to commemorate the occasion.

For everyone else, those t-shirts and mugs are on sale now at the DLang Swag Emporium along with tote bags and stickers. Remember, all of the money we raise through the store goes straight into the General Fund, which we’ll dip into to provide DConf Online 2020 speakers with their free stuff and a few lucky viewers with prizes. Donations made directly to the General Fund, or to any of our ongoing campaigns, are also greatly appreciated.

The ABC’s of Templates in D

D was not supposed to have templates.

Several months before Walter Bright released the first alpha version of the DMD compiler in December 2001, he completed a draft language specification in which he wrote:

Templates. A great idea in theory, but in practice leads to numbingly complex code to implement trivial things like a “next” pointer in a singly linked list.

The (freely available) HOPL IV paper, Origins of the D Programming Language, expands on this:

[Walter] initially objected to templates on the grounds that they added disproportionate complexity to the front end, they could lead to overly complex user code, and, as he had heard many C++ users complain, they had a syntax that was difficult to understand. He would later be convinced to change his mind.

It did take some convincing. As activity grew in the (then singular) D newsgroup, requests that templates be added to the language became more frequent. Eventually, Walter started mulling over how to approach templates in a way that was less confusing for both the programmer and the compiler. Then he had an epiphany: the difference between template parameters and function parameters is one of compile time vs. run time.

From this perspective, there’s no need to introduce a special template syntax (like the C++ style <T>) when there’s already a syntax for parameter lists in the form of (T). So a template declaration in D could look like this:

template foo(T, U) {
    // template members here
}

From there, the basic features fell into place and were expanded and enhanced over time.

In this article, we’re going to lay the foundation for future articles by introducing the most basic concepts and terminology of D’s template implementation. If you’ve never used templates before in any language, this may be confusing. That’s not unexpected. Even though many find D’s templates easier to understand than other implementations, the concept itself can still be confusing. You’ll find links at the end to some tutorial resources to help build a better understanding.

Template declarations

Inside a template declaration, one can nest any other valid D declaration:

template foo(T, U) {
    int x;
    T y;

    struct Bar {
        U thing;
    }

    void doSomething(T t, U u) {
        ...
    }
}

In the above example, the parameters T and U are template type parameters, meaning they are generic substitutes for concrete types, which might be built-in types like int, float, or any type the programmer might implement with a class or struct declaration. By declaring a template, it’s possible to, for example, write a single implementation of a function like doSomething that can accept multiple types for the same parameters. The compiler will generate as many copies of the function as it needs to accomodate the concrete types used in each unique template instantiation.

Other kinds of parameters are supported: value parameters, alias parameters, sequence (or variadic) parameters, and this parameters, all of which we’ll explore in future blog posts.

One name to rule them all

In practice, it’s not very common to implement templates with multiple members. By far, the most common form of template declaration is the single-member eponymous template. Consider the following:

template max(T) {
    T max(T a, T b) { ... }
}

An eponymous template can have multiple members that share the template name, but when there is only one, D provides us with an alternate template declaration syntax. In this example, we can opt for a normal function declaration that has the template parameter list in front of the function parameter list:

T max(T)(T a, T b) { ... }

The same holds for eponymous templates that declare an aggregate type:

// Instead of the longhand template declaration...
/* 
template MyStruct(T, U) {
    struct MyStruct { 
        T t;
        U u;
    }
}
*/

// ...just declare a struct with a type parameter list
struct MyStruct(T, U) {
    T t;
    U u;
}

Eponymous templates also offer a shortcut for instantiation, as we’ll see in the next section.

Instantiating templates

In relation to templates, the term instantiate means essentially the same as it does in relation to classes and structs: create an instance of something. A template instance is, essentially, a concrete implementation of the template in which the template parameters have been replaced by the arguments provided in the instantiation. For a template function, that means a new copy of the function is generated, just as if the programmer had written it. For a type declaration, a new copy of the declaration is generated, just as if the programmer had written it.

We’ll see an example, but first we need to see the syntax.

Explicit instantiations

An explicit instantiation is a template instance created by the programmer using the template instantiation syntax. To easily disambiguate template instantiations from function calls, D requires the template instantiation operator, !, to be present in explicit instantiations. If the template has multiple members, they can be accessed in the same manner that members of aggregates are accessed: using dot notation.

import std;

template Temp(T, U) {
    T x;
    struct Pair {
        T t;
        U u;
    }
}

void main()
{
    Temp!(int, float).x = 10;
    Temp!(int, float).Pair p;
    p.t = 4;
    p.u = 3.2;
    writeln(Temp!(int, float).x);
    writeln(p);            
}

Run it online at run.dlang.io

There is one template instantiation in this example: Temp!(int, float). Although it appears three times, it refers to the same instance of Temp, one in which T == int and U == float. The compiler will generate declarations of x and the Pair type as if the programmer had written the following:

int x;
struct Pair {
    int t;
    float u;
}

However, we can’t just refer to x and Pair by themselves. We might have other instantiations of the same template, like Temp!(double, long), or Temp(MyStruct, short). To avoid conflict, the template members must be accessed through a namespace unique to each instantiation. In that regard, Temp!(int, float) is like a class or struct with static members; just as you would access a static x member variable in a struct Foo using the struct name, Foo.x, you access a template member using the template name, Temp!(int, float).x.

There is only ever one instance of the variable x for the instantiation Temp!(int float), so no matter where you use it in a code base, you will always be reading and writing the same x. Hence, the first line of main isn’t declaring and initializing the variable x, but is assigning to the already declared variable. Temp!(int, float).Pair is a struct type, so that after the declaration Temp!(int, float).Pair p, we can refer to p by itself. Unlike x, p is not a member of the template. The type Pair is a member, so we can’t refer to it without the prefix.

Aliased instantiations

It’s possible to simplify the syntax by using an alias declaration for the instantiation:

import std;

template Temp(T, U) {
    T x;
    struct Pair {
        T t;
        U u;
    }
}
alias TempIF = Temp!(int, float);

void main()
{
    TempIF.x = 10;
    TempIF.Pair p = TempIF.Pair(4, 3.2);
    writeln(TempIF.x);
    writeln(p);            
}

Run it online at run.dlang.io

Since we no longer need to type the template argument list, using a struct literal to initialize p, in this case TempIF.Pair(3, 3.2), looks cleaner than it would with the template arguments. So I opted to use that here rather than first declare p and then initialize its members. We can trim it down still more using D’s auto attribute, but whether this is cleaner is a matter of preference:

auto p = TempIF.Pair(4, 3.2);

Run it online at run.dlang.io

Instantiating eponymous templates

Not only do eponymous templates have a shorthand declaration syntax, they also allow for a shorthand instantiation syntax. Let’s take the x out of Temp and rename the template to Pair. We’re left with a Pair template that provides a declaration struct Pair. Then we can take advantage of both the shorthand declaration and instantiation syntaxes:

import std;

struct Pair(T, U) {
    T t;
    U u;
}

// We can instantiate Pair without the dot operator, but still use
// the alias to avoid writing the argument list every time
alias PairIF = Pair!(int, float);

void main()
{
    PairIF p = PairIF(4, 3.2);
    writeln(p);            
}

Run it online at run.dlang.io

The shorthand instantiation syntax means we don’t have to use the dot operator to access the Pair type.

Even shorter syntax

When a template instantiation is passed only one argument, and the argument’s symbol is a single token (e.g., int as opposed to int[] or int*), the parentheses can be dropped from the template argument list. Take the standard library template function std.conv.to as an example:

void main() {
    import std.stdio : writeln;
    import std.conv : to;
    writeln(to!(int)("42"));
}

Run it online at run.dlang.io

std.conv.to is an eponymous template, so we can use the shortened instantiation syntax. But the fact that we’ve instantiated it as an argument to the writeln function means we’ve got three pairs of parentheses in close proximity. That sort of thing can impair readability if it pops up too often. We could move it out and store it in a variable if we really care about it, but since we’ve only got one template argument, this is a good place to drop the parentheses from the template argument list.

writeln(to!int("42"));

Whether that looks better is another case where it’s up to preference, but it’s fairly idiomatic these days to drop the parentheses for a single template argument no matter where the instantiation appears.

Not done with the short stuff yet

std.conv.to is an interesting example because it’s an eponymous template with multiple members that share the template name. That means that it must be declared using the longform syntax (as you can see in the source code), but we can still instantiate it without the dot notation. It’s also interesting because, even though it accepts two template arguments, it is generally only instantiated with one. This is because the second template argument can be deduced by the compiler based on the function argument.

For a somewhat simpler example, take a look at std.utf.toUTF8:

void main()
{    
    import std.stdio : writeln;
    import std.utf : toUTF8;
    string s1 = toUTF8("This was a UTF-16 string."w);
    string s2 = toUTF8("This was a UTF-32 string."d);
    writeln(s1);
    writeln(s2);
}

Run it online at run.dlang.io

Unlike std.conv.to, toUTF8 takes exactly one parameter. The signature of the declaration looks like this:

string toUTF8(S)(S s)

But in the example, we aren’t passing a type as a template argument. Just as the compiler was able to deduce to’s second argument, it’s able to deduce toUTF8’s sole argument.

toUTF8 is an eponymous function template with a template parameter S and a function parameter s of type S. There are two things we can say about this: 1) the return type is independent of the template parameter and 2) the template parameter is the type of the function parameter. Because of 2), the compiler has all the information it needs from the function call itself and has no need for the template argument in the instantiation.

Take the first call to the toUTF8 function in the declaration of s1. In long form, it would be toUTF8!(wstring)("blah"w). The w at the end of the string literal indicates it is of type wstring, with UTF-16 encoding, as opposed to string, with UTF-8 encoding (the default for string literals). In this situation, having to specify !(wstring) in the template instantiation is completely redundant. The compiler already knows that the argument to the function is a wstring. It doesn’t need the programmer to tell it that. So we can drop the template instantiation operator and the template argument list, leaving what looks like a simple function call. The compiler knows that toUTF8 is a template, knows that the template is declared with one type parameter, and knows that the type should be wstring.

Similarly, the d suffix on the literal in the initialization of s2 indicates a UTF-32 encoded dstring, and the compiler knows all it needs to know for that instantiation. So in this case also, we drop the template argument and make the instantiation appear as a function call.

It does seem silly to convert a wstring or dstring literal to a string when we could just drop the w and d prefixes and have string literals that we can directly assign to s1 and s2. Contrived examples and all that. But the syntax the examples are demonstrating really shines when we work with variables.

wstring ws = "This is a UTF-16 string"w;
string s = ws.toUTF8;
writeln(s);

Run it online at run.dlang.io

Take a close look at the initialization of s. This combines the shorthand template instantiation syntax with Uniform Function Call Syntax (UFCS) and D’s shorthand function call syntax. We’ve already seen the template syntax in this post. As for the other two:

  • UFCS allows using dot notation on the first argument of any function call so that it appears as if a member function is being called. By itself, it doesn’t offer much benefit aside from, some believe, readability. Generally, it’s a matter of preference. But this feature can seriously simplify the implementation of generic templates that operate on aggregate types and built-in types.
  • The parentheses in a function call can be dropped when the function takes no arguments, so that foo() becomes foo. In this case, the function takes one argument, but we’ve taken it out of the argument list using UFCS, so the argument list is now empty and the parentheses can be dropped. (The compiler will lower this to a normal function call, toUTF8(ws)—it’s purely programmer convenience.) When and whether to do this in the general case is a matter of preference. The big win, again, is in the simplification of template implementations: a template can be implemented to accept a type T with a member variable foo or a member function foo, or a free function foo for which the first argument is of type T.

All of this shorthand syntax is employed to great effect in D’s range API, which allows chained function calls on types that are completely hidden from the public-facing API (aka Voldemort types).

More to come

In future articles, we’ll explore the different kinds of template parameters, introduce template constraints, see inside a template instantiation, and take a look at some of the ways people combine templates with D’s powerful compile-time features in the real world. In the meantime, here are some template tutorial resources to keep you busy:

  • Ali Çehreli’s Programming in D is an excellent introduction to D in general, suitable even for those with little programming experience. The two chapters on templates (the first called ‘Templates’ and the second ‘More Templates’) provide a great introduction. (The online version of the book is free, but if you find it useful, please consider throwing Ali some love by buying the ebook or print version linked at the top of the TOC.)
  • More experienced programmers may find Phillipe Sigaud’s ‘D Template Tutorial’ a good read. It’s almost a decade old, but still relevant (and still free!). This tutorial goes beyond the basics into some of the more advanced template features. It includes a look at D’s compile-time features, provides a number of examples, and sports an appendix detailing the is expression (a key component of template constraints). It can also serve as a great reference when reading open source D code until you learn your way around D templates.

There are other resources, though other than my book ‘Learning D’ (this is a referral link that will benefit the D Language Foundation), I’m not aware of any that provide as much detail as the above. (And my book is currently not freely available). Eventually, we’ll be able to add this blog series to the list.

Thanks to Stefan Koch for reviewing this article.

DConf Online 2020: Call For Submissions

DConf Online 2020 LogoDConf Online 2020 is happening November 21 & 22, 2020 in your local web browser! We are currently taking submissions for pre-recorded talks, livstreamed panels, and livecoding events. See the DConf Online 2020 web site for details on how you can participate. Keep reading here for more info on how it came together and what we hope to achieve, as well as for a reminder about the 2020 edition of the Symmetry Autumn of Code (the SAOC 2020 registration deadline is just over three weeks away!).

Maybe Next Time, London!

Due to the onset of COVID-19, the D Language Foundation and Symmetry Investments decided in early March to cancel DConf 2020, which had been scheduled to take place June 17–20 in London. DConf has been the premiere D programming language event every year since 2013, the one chance for members of the D community from around the world to gather face-to-face outside of their local meetups for four days of knowledge sharing and comradery. It was a painful decision, but the right one. As of now, we can’t say for sure there will be a DConf 2021, but it’s looking increasingly unlikely.

Immediately upon reaching the decision to cancel DConf, the obvious question arose of whether we should take the conference online. It was something none of the DConf organizers had any experience with, so we were unwilling to commit to anything until we could figure out a way to go about it that makes sense for our community. As time progressed and we explored our options, the idea became more attractive. Finally, we settled on an approach that we think will work for our community while still allowing outsiders to easily drop by to get a look at our favorite programming language.

We also decided that this is not going to be an online substitute for the real-world DConf. That’s why we’ve named it DConf Online 2020 and not DConf 2020 Online. We’re planning to make this an annual event. The real-world DConf will still take place in spring or summer (barring pandemics or other unforeseen circumstances), and DConf Online six months or so later. Without the DConf cancellation, we never would have reached this point, so for us that’s a bit of a bright side to these dark days.

DConf on YouTube

DConf Online will take place on the D Language Foundation’s YouTube Channel. The event will kick off with a pre-recorded keynote from Walter Bright, the creator and co-maintainer of D, on November 21, scheduled to premiere at a yet-to-be-determined time. Other pre-recorded talks will be scheduled to premiere throughout the weekend, including a Day Two keynote on November 22 from co-maintainer Átila Neves. Presenters from the pre-recorded talks will be available for livestreamed question and answer sessions just as they would be in the real-world DConf.

We’ll also be livestreaming an Ask Us Anything session, a DConf tradition, with Walter and Átila. We’re looking for other ideas for livestream panels. Anyone submitting a panel proposal should either be willing to moderate the panel or have already found someone to commit to the position.

And we really, really want to have at least two livecoding sessions. Anyone familiar with D who has experience livecoding is welcome to submit a proposal. Ideally, we’re looking for sessions that present a solid demonstration of D in use, preferably a small project designed exclusively for the livestream, something that can be developed from start to finish in no more than 90 minutes. We aren’t looking for tutorial style sessions that go into great detail on a feature or two (though that sort of thing is great for a pre-recorded talk submission!), but something that shows how a D program comes together and what D features look like in action.

Everything you need to know to submit a pre-recorded talk, panel, or livecoding session to the D Language Foundation can be found at the DConf Online 2020 web site. We’ll have more details here and on the web site in the coming weeks as our plans solidify. Oh, and everyone whose submission is accepted will receive some swag from the DLang Swag Emporium (DConf Online 2020 swag is coming soon).

BeerConf

It’s a DConf tradition that a gathering spot is selected where attendees can get together each evening for drinks, food, and conversation. For many attendees, this is a highlight of the conference. The opportunity to engage in conversation with so many smart, like-minded people is not one to be missed. Ethan Watson dubbed these evening soirees “BeerConf”, and the name has stuck.

Recently, Ethan and other D community members have been gathering for a monthly online #BeerConf. Given that it’s such an integral part of the DConf experience, we hope to make use of the lessons they’re learning to run a BeerConf in parallel to DConf Online, starting on the 20th. Despite the name, no one will be expected to drink alcohol of any kind. It’s all about getting together to socialize as close to face-to-face as we can get online.

More details regarding BeerConf will be announced closer to the conference dates, so keep an eye on the blog!

SAOC 2020

Symmetry Autumn of Code is an annual event where a handful of lucky programmers get paid to write some D code. Sponsored by Symmetry Investments, SAOC 2020 is the third edition of the event. Although priority is given to university students, SAOC is open to anyone over 18.

Applicants send a project proposal and a short bio to the D Language Foundation. Those who are selected will be required to work on their project at least 20 hours per week from September 15, 2020, until January 15, 2021. The event consists of four milestones. Participants who meet their goals for the first three milestones will each receive a payment of $1000. For the fourth milestone, the SAOC Committee will evaluate each participant’s progress for the entire event. On that basis, one will be selected to receive a final $1000 payment and a free trip to the next real-world DConf (no registration fee; travel and lodging expenses reimbursed on the same terms as offered to DConf speakers). The lucky participant will be asked to submit a proposal for the same DConf they attend, but their proposal will be evaluated in the same manner as all proposals (i.e., acceptance is not guaranteed), but they are guaranteed free registration and reimbursement regardless.

Although Roberto Romaninho, our SAOC 2019 selectee, was robbed of the opportunity to attend DConf 2020, he will still be eligible to make use of his reward at our next real-world event along with the 2020 selectee. Francesco Gallà, who was selected in the inaugural SAOC 2018, gave a presentation about his project and the SAOC experience at DConf 2019. The runner up, Franceso Mecca, wrote about his own project for the D Blog.

SAOC 2020 applications are open until August 16. See the SAOC 2020 page for all the details on how to apply.

SAOC 2020 and Other News

Symmetry Autumn of Code 2020

Symmetry Investments logo

The 3rd annual Symmetry Autumn of Code (SAoC) is on!

From now until August 16th, we’re accepting applications from motivated coders interested in getting paid to improve the D ecosystem. The SAoC committee will review all submissions and, based on the quality of the applications received, select a number of applicants to complete four milestones from September 15th to January 15th. Each participant will receive $1000 for the successful completion of each of the first three milestones, and one of them will receive an additional $1000 and a free trip (reimbursement for transportation and accommodation, and free registration) to the next real-world DConf (given the ongoing pandemic, we can’t yet be sure when that will be).

Anyone interested in programming D is welcome to apply, but preference will be given to those who can provide proof of enrollment in undergraduate or postgraduate university programs. For details on how to apply, see the SAoC 2020 page here at the D Blog.

The participants will need mentors, so we invite experienced D programmers interested in lending a hand to get in touch and to keep an eye out in the forums for any SAoC applicants in search of a mentor. As with the previous edition of SAoC, all mentors whose mentee completes the event will be guaranteed a one-time payment of $500 after the final milestone (mentors of unsuccessful mentees may still be eligible for the payment at the discretion of the SAoC committee). Potential mentors can follow the same link for details on their responsibilities and how to make themselves available.

We’re also looking for community input on potential SAoC projects. If there’s any work you’re aware of that needs doing in the D ecosystem and which may keep a lone coder occupied for 20 hours per week over four months, please let us know! Once again, details on how submit your suggestions and what sort of information we’re looking for can be found on the SAoC 2020 page.

Our SAoC 2019 selectee, Roberto Rosmaninho, was all set to attend DConf 2020 and we were all looking forward to meeting him. He’ll still be eligible to claim his free DConf trip at the next available opportunity.

SAoC would not be possible without the generosity of Symmetry Investments. A big thanks to them for once again funding this event and for the other ways, both financial and otherwise, they contribute back to the D programming language community.

Finances

Thanks to everyone who has shopped in the DLang Swag Emporium! To date, the D Language Foundation has received over $177 in royalties and referral fees. Thanks are also in order to those who have supported the foundation through smile.amazon.com. Your purchases have brought over $288 into the General Fund. Amazon Smile is perhaps the easiest way to support D financially if you shop through Amazon’s .com domain (the D Language Foundation is unavailable in other Amazon domains). If you’ve never done so, you can select a charitable foundation (the D Language Foundation, of course) on your first visit to smile.amazon.com. Then, every time you shop through that link, the foundation will receive a small percentage of your total purchase. Check your browser’s extension market for plugins that convert every amazon.com link to a smile.amazon.com link!

On the Task Bounties front, we may have closed out a big bounty for bringing D to iOS and iPadOS, but there are still several other bounties waiting to be claimed. The latest, currently at $220, is a bounty to improve DLL support on Windows by closing two related Bugzilla issues; 50% of the total bounty will be paid for the successful closure (merged PR and DMD release) of each issue. We welcome anyone interested in fixing these issues to either up the bounty or roll up their sleeves and start working toward claiming it. If you’d like to contribute to multiple bounties with a single credit card payment, or seed one or more new bounties with a specific amount, visit the Task Bounty Catch-All and follow the instructions there.

Finally, the question was recently raised in the forums about how to view the D Language Foundation’s finances. Because the foundation is a 501(3)(c) non-profit public charity, the Form 990 that the organization is required to submit to the IRS every year is publicly available. There are different ways you can obtain the documents for multiple years, such as searching online databases or contacting the IRS directly. Several websites, such as grantspace.org, provide details on how to do so. The Form 990 does not break down specific expenditures or sources of income except for special circumstances (like scholarship payments). With Andrei’s help, I’m currently working on gathering up more information on the past five years of the foundation’s finances so that we can put up an overview page at dlang.org. It won’t be at line-item detail, but we hope to provide a little more detail than the Form 990. I can’t provide a timeline on when it will be available (I don’t consider it a high priority task, so I’m working on it sporadically), but expect it sometime in the next few months.

DConf Online?

Rumor has it that online conferences are actually a thing. Voices in the wind speak of the potential for an annual event related to D. I don’t usually listen to voices I hear in the wind, but this time I’m intrigued…

Interfacing D with C: Arrays and Functions (Arrays Part 2)

Digital Mars D logo

This post is part of an ongoing series on working with both D and C in the same project. The previous post explored the differences in array declaration and initialization. This post takes the next step: declaring and calling C functions that take arrays as parameters.

Arrays and C function declarations

Using C libraries in D is extremely easy. Most of the time, things work exactly as one would expect, but as we saw in the previous article there can be subtle differences. When working with C functions that expect arrays, it’s necessary to fully understand these differences.

The most straightforward and common way of declaring a C function that accepts an array as a parameter is to to use a pointer in the parameter list. For example, this hypothetical C function:

void f0(int *arr);

In C, any array of int can be passed to this function no matter how it was declared. Given int a[], int b[3], or int *c, the function calls f0(a), f0(b), and f0(c) are all the same: a pointer to the first element of each array is passed to the function. Or using the lingo of C programmers, arrays decay to pointers

Typically, in a function like f0, the implementer will expect the array to have been terminated with a marker appropriate to the context. For example, strings in C are arrays of char that are terminated with the \0 character (we’ll look at D strings vs. C strings in a future post). This is necessary because, without that character, the implementation of f0 has no way to know which element in the array is the last one. Sometimes, a function is simply documented to expect a certain length, either in comments or in the function name, e.g., a vector3f_add(float *vec) will expect that vec points to exactly 3 elements. Another option is to require the length of the array as a separate argument:

void f1(int *arr, size_t len);

None of these approaches is foolproof. If f0 receives an array with no end marker or which is shorter than documented, or if f1 receives an array with an actual length shorter than len, then the door is open for memory corruption. D arrays take this possibility into account, making it much easier to avoid such problems. But again, even D’s safety features aren’t 100% foolproof when calling C functions from D.

There are other, less common, ways array parameters may be declared in C:

void f2(int arr[]);
void f3(int arr[9]);
void f4(int arr[static 9]);

Although these parameters are declared using C’s array syntax, they boil down to the exact same function signature as f0 because of the aforementioned pointer decay. The [9] in f3 triggers no special enforcement by the compiler; arr is still effectively a pointer to int with unknown length. The [9] serves as documentation of what the function expects, and the implementation cannot rely on the array having nine elements.

The only potential difference is in f4. The static added to the declaration tells the compiler that the function must take an array of, in this case, at least nine elements. It could have more than nine, but it can’t have fewer. That also rules out null pointers. The problem is, this isn’t necessarily enforced. Depending on which C compiler you use, if you shortchange the function and send it less than nine elements you might see warnings if they are enabled, but the compiler might not complain at all. (I haven’t tested current compilers for this article to see if any are actually reporting errors for this, or which ones provide warnings.)

The behavior of C compilers doesn’t matter from the D side. All we need be concerned with is declaring these functions appropriately so that we can call them from D such that there are no crashes or unexpected results. Because they are all effectively the same, we could declare them all in D like so:

extern(C):
void f0(int* arr);
void f1(int* arr, size_t len);
void f2(int* arr);
void f3(int* arr);
void f4(int* arr);

But just because we can do a thing doesn’t mean we should. Consider these alternative declarations of f2, f3, and f4:

extern(C):
void f2(int[] arr);
void f3(int[9] arr);
void f4(int[9] arr);

Are there any consequences of taking this approach? The answer is yes, but that doesn’t mean we should default to int* in each case. To understand why, we need first to explore the innards of D arrays.

The anatomy of a D array

The previous article showed that D makes a distinction between dynamic and static arrays:

int[] a0;
int[9] a1;

a0 is a dynamic array and a1 is a static array. Both have the properties .ptr and .length. Both may be indexed using the same syntax. But there are some key differences between them.

Dynamic arrays

Dynamic arrays are usually allocated on the heap (though that isn’t a requirement). In the above case, no memory for a0 has been allocated. It would need to be initialized with memory allocated via new or malloc, or some other allocator, or with an array literal. Because a0 is uninitialized, a0.ptr is null and a0.length is 0.

A dynamic array in D is an aggregate type that contains the two properties as members. Something like this:

struct DynamicArray {
    size_t length;
    size_t ptr;
}

In other words, a dynamic array is essentially a reference type, with the pointer/length pair serving as a handle that refers to the elements in the memory address contained in the ptr member. Every built-in D type has a .sizeof property, so if we take a0.sizeof, we’ll find it to be 8 on 32-bit systems, where size_t is a 4-byte uint, and 16 on 64-bit systems, where size_t is an 8-byte ulong. In short, it’s the size of the handle and not the cumulative size of the array elements.

Static arrays

Static arrays are generally allocated on the stack. In the declaration of a1, stack space is allocated for nine int values, all of which are initialized to int.init (which is 0) by default. Because a1 is initialized, a1.ptr points to the allocated space and a1.length is 9. Although these two properties are the same as those of the dynamic array, the implementation details differ.

A static array is a value type, with the value being all of its elements. So given the declaration of a1 above, its nine int elements indicate that a1.sizeof is 9 * int.sizeof, or 36. The .length property is a compile-time constant that never changes, and the .ptr property, though not readable at compile time, is also a constant that never changes (it’s not even an lvalue, which means it’s impossible to make it point somewhere else).

These implementation details are why we must pay attention when we cut and paste C array declarations into D source modules.

Passing D arrays to C

Let’s go back to the declaration of f2 in C and give it an implementation:

void f2(int arr[]) {
    for(int i=0; i<3; ++i)
        printf("%d\n", arr[i]);
}

A naïve declaration in D:

extern(C) void f2(int[]);

void main() {
    int[] a = [10, 20, 30];
    f2(a);
}

I say naïve because this is never the right answer. Compiling f2.c with df2.d on Windows (cl /c f2.c in the “x64 Native Tools” command prompt for Visual Studio, followed by dmd -m64 df2.d f2.obj), then running df2.exe, shows me the following output:

3
0
1970470928

There is no compiler error because the declaration of f2 is pefectly valid D. The extern(C) indicates that this function uses the cdecl calling convention. Calling conventions affect the way arguments are passed to functions and how the function’s symbol is mangled. In this case, the symbol will be either _f2 or f2 (other calling conventions, like stdcallextern(Windows) in D—have different mangling schemes). The declaration still has to be valid D. (In fact, any D function can be marked as extern(C), something which is necessary when creating a D library that will be called from other languages.)

There is also no linker error. DMD is calling out to the system linker (in this case, Microsoft’s link.exe), the same linker used by the system’s C and C++ compilers. That means the linker has no special knowledge about D functions. All it knows is that there is a call to a symbol, f2 or _f2, that needs to be linked with the implementation. Since the type and number of parameters are not mangled into the symbol name, the linker will happily link with any matching symbol it finds (which, by the way, is the same thing it would do if a C program tried to call a C function which was declared with an incorrect parameter list).

The C function is expecting a single pointer as an argument, but it’s instead receiving two values: the array length followed by the array pointer.

The moral of this story is that any C function with array parameters declared using array syntax, like int[], should be declared to accept pointers in D. Change the D source to the following and recompile using the same command line as before (there’s no need to recompile the C file):

extern(C) void f2(int*);

void main() {
    int[] a = [10, 20, 30];
    f2(a.ptr);
}

Note the use of a.ptr. It’s an error to try to pass a D array argument where a pointer is expected (with one very special exception, string literals, which I’ll cover in the next article in this series), so the array’s .ptr property must be used instead.

The story for f3 and f4 is similar:

void f3(int arr[9]);
void f4(int arr[static 9]);

Remember, int[9] in D is a static array, not a dynamic array. The following do not match the C declarations:

void f3(int[9]);
void f4(int[9]);

Try it yourself. The C implementation:

void f3(int arr[9]) {
    for(int i=0; i<9; ++i)
        printf("%d\n", arr[i]);
}

And the D implementation:

extern(C) void f3(int[9]);

void main() {
    int[9] a = [10, 20, 30, 40, 50, 60, 70, 80, 90];
    f3(a);
}

This is likely to crash, depending on the system. Rather than passing a pointer to the array, this code is instead passing all nine array elements by value! Now consider a C library that does something like this:

typedef float[16] mat4f;
void do_stuff(mat4f mat);

Generally, when writing D bindings to C libraries, it’s a good idea to keep the same interface as the C library. But if the above is translated like the following in D:

alias mat4f = float[16];
extern(C) void do_stuff(mat4f);

The sixteen floats will be passed to do_stuff every time it’s called. The same for all functions that take a mat4f parameter. One solution is just to do the same as in the int[] case and declare the function to take a pointer. However, that’s no better than C, as it allows the function to be called with an array that has fewer elements than expected. We can’t do anything about that in the int[] case, but that will usually be accompanied by a length parameter on the C side anyway. C functions that take typedef’d types like mat4f usually don’t have a length parameter and rely on the caller to get it right.

In D, we can do better:

void do_stuff(ref mat4f);

Not only does this match the API implementor’s intent, the compiler will guarantee that any arrays passed to do_stuff are static float arrays with 16 elements. Since a ref parameter is just a pointer under the hood, all is as it should be on the C side.

With that, we can rewrite the f3 example:

extern(C) void f3(ref int[9]);

void main() {
    int[9] a = [10, 20, 30, 40, 50, 60, 70, 80, 90];
    f3(a);
}

Conclusion

Most of the time, when interfacing with C from D, the C API declarations and any example code can be copied verbatim in D. But most of the time is not all of the time, so care must be taken to account for those exceptional cases. As we saw in the previous article, carelessness when declaring array variables can usually be caught by the compiler. As this article shows, the same is not the case for C function declarations. Interfacing D with C requires the same care as when writing C code.

In the next article in this series, we’ll look at mixing D strings and C strings in the same program and some of the pitfalls that may arise. In the meantime, Steven Schveighoffer’s excellent article, “D Slices”, is a great place to start for more details about D arrays.

Thanks to Walter Bright and Átila Neves for their valuable feedback on this article.

D 2.091.0 Released

Digital Mars D logoThe latest release of DMD, the D reference compiler, ships with 18 major changes and 66 bugfixes from 55 contributors. This release contains, among other goodies, improvements to the Windows experience and enhancements to C and C++ interoperability. As fate would have it, the initial release announcement came in the aftermath of some unfortunate news regarding DConf 2020.

DMD on Windows

Over the years, some D users have remarked that the development of D is Linux-centric, that Windows is the black sheep or red-headed stepchild of D platforms. For anyone familiar with D’s early history, that seems an odd thing to say, given that DMD started out as a Windows-only compiler that could only output 32-bit objects in the OMF format. But it’s also understandable, as anyone not familiar with that history could only see that DMD on Windows lagged behind the Linux releases.

64-bit

One place where the official DMD releases on Windows have continued to differ from the releases on other platforms is the lack of 64-bit binaries in the release packages. Again, there’s a historical reason for this. The default output of the compiler is determined by how it is compiled, e.g., 32-bit versions output 32-bit binaries by default. When Walter first added support to DMD for 64-bit output on Windows, it required giving the back end the ability to generate object files in Microsoft’s version of the COFF format and also requiring users to install the Microsoft Build Tools and Platform SDK for access to the MS linker and system link libraries. This is quite a different experience from other platforms, where you can generally expect a common set of build tools to have been installed via the system package manager on any system set up for C and C++ development.

For a Windows developer who chooses GCC for their C and C++ development (or who does no C or C++ development at all), it’s a big ask to require them to download and install several GBs they might not already have installed and probably will never use for anything else. So D releases on Windows continued to ship with 32-bit binaries and the OPTLINK linker in order to provide a minimum out-of-the-box experience. That was a perfectly fine solution, unless you happened to be someone who really wanted 64-bit output (posts from disgruntled Windows users who didn’t want to install the MS tools can be found sprinkled throughout the forum archives).

Eventually, the LLVM linker (LLD) was added to the DMD Windows release packages, along with system link libraries generated from the MinGW definitions. This allowed users to compile 64-bit output out of the box and, once the kinks were worked out, eliminated the dependency on the MS linker. Yet, the official release packages still did not include a 64-bit version of DMD and still did not support 64-bit output by default.

With DMD 2.091.0, the black sheep has come back into the fold. The official DMD releases on Windows now ship with 64-bit binaries, so those of you masochists out there who cling to Makefiles and custom build scripts can expect the default output be what you expect it to be (for the record, DUB, the build tool and package manager that ships with DMD, has been instructing the compiler to compile 64-bit output by default on 64-bit systems for the past few releases).

Windows gets even more love

There are lots of goodies for Windows in this release. Another biggie is that DMD is now 30-40% faster on Windows. It’s no secret that LDC, the LLVM-based D compiler, generates faster binaries than DMD (for some D users, the general rule of thumb is to develop with DMD for its fast compile times and release with LDC for its faster binaries, though others argue that LDC is plenty fast for development and DMD is fine for production). There have been requests for some time to stop compiling DMD with DMD and start doing it with LDC instead. This release is the first to put that into practice.

There are a number of smaller enhancements to the Windows experience: the install.sh script available on the DMD downloads page that some people prefer now supports POSIX environments on Windows; the system link libraries that ship with the compiler have been upgraded from MinGW  5.0.2 to 7.0.0; LLD has been upgraded to 9.0.0; and there’s plenty more in the changelog.

C++ Header Generation

With just about every major release of DMD, D’s interoperability with C and C++ sees some kind of improvement. This release brings a huge one.

Over the years, some have speculated that it would be excellent if the D compiler could generate headers for C and C++ for D libraries intended to be usable in C or C++ programs. Now that wishful thinking has become a(n experimental) reality. Given a set of extern(C) or extern(C++) functions, DMD can generate header files that contain the appropriate C or C++ declarations. Three compiler switches get the job done:

  • -HC will cause the header to be generated and printed to standard output
  • -HCf=fileName will cause the header to be generated and printed to the specified file
  • -HCd=directoryname will (once it’s implemented) cause the header to be printed to a file in the specified directory

See the changelog for example output.

Other News

While the Corona virus was initially ramping up out of sight from most of the world, plans for DConf 2020 were ramping up online from different locations around the world. Planning began in November, the venue was secured in late December, and the website launched with the announcement in early January.

As news of the virus outbreak spread, the conference organizers grew concerned. Would we be okay in June? In late February, that concern manifested as a discussion of possible contingency plans. Two weeks later, it resulted in the decision to cancel DConf 2020. Thankfully, the D community has been supportive of the decision.

As part of the discussion of contingency plans, the possibility was raised of hosting an online conference. The idea of course came up in the discussion of the cancellation in the forums, and a few people reached out shortly after the initial announcement offering to provide help in setting something up. Walter created a forum thread to discuss the topic for anyone interested.

No one involved with organizing DConf has any experience with hosting an online conference. We’re currently exploring options and looking at what the organizers of other Conferences in the Time of COVID-19 are doing. We want to do it, and we want to do it well. Experience with organizing DConf in the real world has taught us not to jump on any old technology without first having a fallback (ahem, DConf 2018 livestream) and making sure the tech does what we expect it to (ahem, DConf 2019 livestream). So don’t expect a quick announcement. We want to find the right tech that fits our requirements and explore how it works before we move forward with setting dates. But do expect that DConf 2020 Online is looking more and more likely to become a thing.