1 module cogito;
2 
3 import dmd.frontend;
4 import dmd.astcodegen;
5 import dmd.errors;
6 import dmd.globals;
7 
8 public import cogito.list;
9 public import cogito.meter;
10 public import cogito.visitor;
11 
12 import std.algorithm;
13 import std.range;
14 
15 private Result runOnFile(string file)
16 {
17     initialize();
18     LocalHandler localHandler;
19     diagnosticHandler = &localHandler.handler;
20 
21     scope (exit)
22     {
23         diagnosticHandler = null;
24         deinitialize();
25     }
26     auto tree = parseModule!AST(file);
27 
28     if (tree.diagnostics.hasErrors())
29     {
30         return typeof(return)(localHandler.errors);
31     }
32     auto visitor = new CognitiveVisitor(file);
33 
34     tree.module_.accept(visitor);
35 
36     return typeof(return)(visitor.source);
37 }
38 
39 /**
40  * Measure the complexity in a list of modules.
41  *
42  * Params:
43  *     args = File paths.
44  *
45  * Returns: List of collected scores in each file.
46  */
47 auto runOnFiles(R)(R args)
48 if (isInputRange!R && is(ElementType!R == string))
49 {
50     return args.map!runOnFile();
51 }
52 
53 /**
54  * Measure the complexity of the given code.
55  *
56  * Params:
57  *     code = Code as string.
58  *
59  * Returns: Collected score.
60  */
61 Result runOnCode(string code)
62 {
63     synchronized
64     {
65         initialize();
66         LocalHandler localHandler;
67         scope (exit)
68         {
69             diagnosticHandler = null;
70             deinitialize();
71         }
72         auto tree = parseModule!ASTCodegen("app.d", code);
73 
74         if (tree.diagnostics.hasErrors())
75         {
76             return typeof(return)(localHandler.errors);
77         }
78         auto visitor = new CognitiveVisitor();
79 
80         tree.module_.accept(visitor);
81 
82         return typeof(return)(visitor.source);
83     }
84 }