Solution for Fatal flaw in D design which is holding back widespread adoption(tm)

Walter Bright newshound1 at digitalmars.com
Wed Mar 31 12:36:28 PDT 2010


Nick Sabalausky wrote:
> Alhough it wouldn't necessarily even need to be a full-fledged source 
> formatter. Just something to sanitize the whitespace between start-of-line 
> and anything non-whitespace would be a huge improvement *and* be 
> cross-language. 

I think that's a great idea. Yesterday, I wrote the following program and added 
it to the dmd makefile so that all checkins and installs run the source code 
through it first. I welcome improvements. The current version replaces tabs with 
spaces, and removes trailing whitespace.

If someone is ambitious, a full fletched D source code pretty printer would be 
valuable that anyone could use, and which all Phobos source code could be run 
through in order to enforce a common style.
----------------------------------------

/* Replace tabs with spaces, and remove trailing whitespace from lines.
  */

import std.file;
import std.path;

int main(string[] args)
{
     foreach (f; args[1 .. $])
     {
         auto input = cast(char[]) std.file.read(f);
         auto output = filter(input);
         if (output != input)
             std.file.write(f, output);
     }
     return 0;
}


char[] filter(char[] input)
{
     char[] output;
     size_t j;

     int column;
     for (size_t i = 0; i < input.length; i++)
     {
         auto c = input[i];

         switch (c)
         {
             case '\t':
                 while ((column & 7) != 7)
                 {   output ~= ' ';
                     j++;
                     column++;
                 }
                 c = ' ';
                 column++;
                 break;

             case '\r':
             case '\n':
                 while (j && output[j - 1] == ' ')
                     j--;
                 output = output[0 .. j];
                 column = 0;
                 break;

             default:
                 column++;
                 break;
         }
         output ~= c;
         j++;
     }
     while (j && output[j - 1] == ' ')
         j--;
     return output[0 .. j];
}



More information about the Digitalmars-d mailing list