"Fossies" - the Fresh Open Source Software Archive

Member "dmd-2.089.0/src/examples/avg.d" (2 Nov 2019, 1686 Bytes) of package /linux/misc/dmd-2.089.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) D source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 #!/usr/bin/env dub
    2 /+dub.sdl:
    3 dependency "dmd" path="../.."
    4 +/
    5 /* This file contains an example on how to use the transitive visitor.
    6    It implements a visitor which computes the average function length from
    7    a *.d file.
    8  */
    9 
   10 module examples.avg;
   11 
   12 import dmd.astbase;
   13 import dmd.errors;
   14 import dmd.parse;
   15 import dmd.transitivevisitor;
   16 
   17 import dmd.globals;
   18 import dmd.id;
   19 import dmd.identifier;
   20 
   21 import std.stdio;
   22 import std.file;
   23 
   24 extern(C++) class FunctionLengthVisitor(AST) : ParseTimeTransitiveVisitor!AST
   25 {
   26     alias visit = ParseTimeTransitiveVisitor!AST.visit;
   27     ulong[] lengths;
   28 
   29     double getAvgLen(AST.Module m)
   30     {
   31         m.accept(this);
   32 
   33         if (lengths.length == 0)
   34             return 0;
   35 
   36         import std.algorithm;
   37         return double(lengths.sum)/lengths.length;
   38     }
   39 
   40     override void visitFuncBody(AST.FuncDeclaration fd)
   41     {
   42         lengths ~= fd.endloc.linnum - fd.loc.linnum;
   43         super.visitFuncBody(fd);
   44     }
   45 }
   46 
   47 void main()
   48 {
   49     string fname = "examples/testavg.d";
   50 
   51     Id.initialize();
   52     global._init();
   53     global.params.isLinux = true;
   54     global.params.is64bit = (size_t.sizeof == 8);
   55     global.params.useUnitTests = true;
   56     ASTBase.Type._init();
   57 
   58     auto id = Identifier.idPool(fname);
   59     auto m = new ASTBase.Module(&(fname.dup)[0], id, false, false);
   60     auto input = readText(fname);
   61 
   62     scope diagnosticReporter = new StderrDiagnosticReporter(global.params.useDeprecated);
   63     scope p = new Parser!ASTBase(m, input, false, diagnosticReporter);
   64     p.nextToken();
   65     m.members = p.parseModule();
   66 
   67     scope visitor = new FunctionLengthVisitor!ASTBase();
   68     writeln("Average function length: ", visitor.getAvgLen(m));
   69 }