Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
221 changes: 221 additions & 0 deletions src/analysis/allman.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

module analysis.allman;

import dparse.lexer;
import dparse.ast;
import analysis.base : BaseAnalyzer;
import dsymbol.scope_ : Scope;

/**
Checks for the allman style (braces should be on their own line)

------------
if (param < 0) {

}
------------

should be

------------
if (param < 0)
{

}
------------
*/
class AllManCheck : BaseAnalyzer
{
///
this(string fileName, const(ubyte)[] code, bool skipTests = false)
{
super(fileName, null, skipTests);
this.code = code;
}

override void visit(const WhileStatement st)
{
if (st.declarationOrStatement !is null)
checkForBrace(st.declarationOrStatement, st.expression.line, st.expression.column);
}

override void visit(const ForeachStatement st)
{
checkForBrace(st.declarationOrStatement, st.low.line, st.low.column);
}

override void visit(const ForStatement st)
{
checkForBrace(st.declarationOrStatement, st.test.line, st.test.column);
}

override void visit(const DoStatement st)
{
// the DoStatement only knows about the line and column of the expression
checkForBrace(st.statementNoCaseNoDefault, 0, 0);
Copy link
Member Author

@wilzbach wilzbach Dec 15, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For

do {

} while(true)

the AST is:

<doStatement>
  <expression>
    <unaryExpression>
      <primaryExpression>
        <true/>
      </primaryExpression>
    </unaryExpression>
  </expression>
  <statementNoCaseNoDefault>
    <blockStatement>
      <declarationsAndStatements>
        <declarationOrStatement>
          <statement>
            <statementNoCaseNoDefault>
              <expressionStatement>
                <expression>
                  <unaryExpression>
                    <primaryExpression>
                      <identifierOrTemplateInstance>
                        <identifier>i</identifier>
                      </identifierOrTemplateInstance>
                    </primaryExpression>
                    <suffix>++</suffix>
                  </unaryExpression>
                </expression>
              </expressionStatement>
            </statementNoCaseNoDefault>
          </statement>
        </declarationOrStatement>
      </declarationsAndStatements>
    </blockStatement>
  </statementNoCaseNoDefault>
</doStatement>

and none of the elements contains information about the line and column:

DoStatement: https://github.com/Hackerpilot/libdparse/blob/master/src/dparse/ast.d#L1467
BlockStatement: https://github.com/Hackerpilot/libdparse/blob/master/src/dparse/ast.d#L959
StatementNoCaseNoDefault: https://github.com/Hackerpilot/libdparse/blob/master/src/dparse/ast.d#L2249

st.statementNoCaseNoDefault.accept(this);
}

override void visit(const IfStatement st)
{
checkForBrace(st.thenStatement, st.expression.line, st.expression.column);
if (st.elseStatement !is null)
checkForBrace(st.elseStatement, st.expression.line, st.expression.column);
}

alias visit = ASTVisitor.visit;

private:

const(ubyte)[] code;

enum string KEY = "dscanner.style.allman";
enum string MESSAGE = "Braces should be on their own line";

void checkForBrace(const DeclarationOrStatement declOrSt, size_t line, size_t column)
{
if(auto stst = declOrSt.statement)
{
checkForBrace(stst.statementNoCaseNoDefault, line, column);
}
declOrSt.accept(this);
}

void checkForBrace(const StatementNoCaseNoDefault st, size_t line, size_t column)
{
if(st !is null)
{
findBraceOrNewLine(st.startLocation, st.endLocation, line, column);
}
}

/**
Checks whether a brace or newline comes first
*/
void findBraceOrNewLine(size_t start, size_t end, size_t line, size_t column)
{
import std.algorithm : canFind;
import std.utf : byCodeUnit;

auto codeRange = (cast(char[]) code[start..end]).byCodeUnit;

// inline statements are allowed -> search for newline
if (codeRange.canFind('\n'))
{
foreach (s; codeRange)
{
// first brace
if (s == '{')
{
// DoStatement hasn't a proper line and column attached
// -> calculate ourselves
if (line == 0 && column == 0)
{
// find line & column of brace
auto t = findLineAndColumnForPos(start);
line = t.line + 1; // Dscanner starts lines at 1
column = t.column;
}
addErrorMessage(line, column, KEY, MESSAGE);
break;
}
// newline - test passed
else if (s == '\n')
{
break;
}
}
}
}

/**
Counts all matches of an symbol and the number of iterated characters
*/
auto findLineAndColumnForPos(size_t pos)
{
import std.utf : byCodeUnit;
import std.typecons : tuple;

auto textBefore = (cast(char[]) code[0..pos]).byCodeUnit;
size_t line = 0;
size_t column = 0;

foreach (s; textBefore)
{
if (s == '\n')
{
line++;
column = 0;
}
else if (s != '\r')
{
// ignore carriage return
column++;
}
}
return tuple!("line", "column")(line, column);
}

}

unittest
{
import analysis.config : StaticAnalysisConfig, Check;
import analysis.helpers : assertAnalyzerWarnings;
import std.format : format;
import std.stdio : stderr;

StaticAnalysisConfig sac;
sac.allman_braces_check = Check.enabled;

assertAnalyzerWarnings(q{
void testAllman()
{
while (true) { // [warn]: %s
auto f = 1;
}

do { // [warn]: %s
auto f = 1;
} while (true);

// inline braces are OK
while (true) { auto f = 1; }

if (true) { // [warn]: %s
auto f = 1;
}
if (true) { auto f = 1; }
foreach (r; [1]) { // [warn]: %s
}
foreach (r; [1]) { }
foreach_reverse (r; [1]) { // [warn]: %s
}
foreach_reverse (r; [1]) { }
for (int i = 0; i < 10; i++) { // [warn]: %s
}
for (int i = 0; i < 10; i++) { }

// nested check
while (true) { // [warn]: %s
while (true) { // [warn]: %s
auto f = 1;
}
}
}
}c.format(
AllManCheck.MESSAGE,
AllManCheck.MESSAGE,
AllManCheck.MESSAGE,
AllManCheck.MESSAGE,
AllManCheck.MESSAGE,
AllManCheck.MESSAGE,
AllManCheck.MESSAGE,
AllManCheck.MESSAGE,
), sac);

stderr.writeln("Unittest for Allman passed.");
}
9 changes: 9 additions & 0 deletions src/analysis/config.d
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,13 @@ struct StaticAnalysisConfig

@INI("Check for sortedness of imports")
string imports_sortedness = Check.disabled;

@INI("Check allman brace style")
string allman_braces_check = Check.disabled;

@INI("Check for trailing whitespace")
string trailing_whitespace_check = Check.disabled;

@INI("Check for two or more consecutive empty lines")
string consecutive_empty_lines = Check.disabled;
}
91 changes: 91 additions & 0 deletions src/analysis/consecutive_empty_lines.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

module analysis.consecutive_empty_lines;

import dparse.lexer;
import dparse.ast;
import analysis.base : BaseAnalyzer, Message;
import dsymbol.scope_ : Scope;

/**
Checks whether a file contains two or more consecutive empty lines
*/
class ConsecutiveEmptyLines: BaseAnalyzer
{
///
this(string fileName, const(ubyte)[] code, bool skipTests = false)
{
super(fileName, null, skipTests);
this.code = code;
}

override void visit(const Module)
{
findConsecutiveLines();
}

alias visit = ASTVisitor.visit;

private:

const(ubyte)[] code;

enum string KEY = "dscanner.style.consecutive_empty_lines";
enum string MESSAGE = "Consecutive empty lines detected";

/**
Searches for two or more consecutive empty lines
*/
void findConsecutiveLines()
{
import std.utf: byCodeUnit;
import std.ascii: isWhite;

size_t line = 0;
size_t newLineCount = 0;

foreach (s; (cast(char[]) code).byCodeUnit)
{
if (s == '\n')
{
if (newLineCount >= 2)
addErrorMessage(line, 0, KEY, MESSAGE);
line++;
newLineCount++;
}
// ignore carriage returns for windows compatibility
else if (!(s == '\r' || isWhite(s)))
{
newLineCount = 0;
}
}
}
}

unittest
{
import analysis.config : StaticAnalysisConfig, Check;
import analysis.helpers;
import std.stdio;

StaticAnalysisConfig sac;
sac.consecutive_empty_lines = Check.enabled;

auto msgs = getAnalyzerWarnings(q{
void testConsecutiveEmptyLines(){


}

void foo(){

}
}c, sac);
assert(msgs.length == 1);
Message msg = Message("test", 3, 0, ConsecutiveEmptyLines.KEY, ConsecutiveEmptyLines.MESSAGE);
assert(msgs.front == msg);

stderr.writeln("Unittest for ConsecutiveEmptyLines passed.");
}
22 changes: 16 additions & 6 deletions src/analysis/helpers.d
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,9 @@ S after(S)(S value, S separator) if (isSomeString!S)
}

/**
* This assert function will analyze the passed in code, get the warnings,
* and make sure they match the warnings in the comments. Warnings are
* marked like so: // [warn]: Failed to do somethings.
*/
void assertAnalyzerWarnings(string code, const StaticAnalysisConfig config,
* Get analzer warnings for the given code
*/
MessageSet getAnalyzerWarnings(string code, const StaticAnalysisConfig config,
string file = __FILE__, size_t line = __LINE__)
{
import analysis.run : parseModule;
Expand All @@ -58,7 +56,19 @@ void assertAnalyzerWarnings(string code, const StaticAnalysisConfig config,
auto moduleCache = ModuleCache(new CAllocatorImpl!Mallocator);

// Run the code and get any warnings
MessageSet rawWarnings = analyze("test", m, config, moduleCache, tokens);
return analyze("test", m, config, moduleCache, tokens, cast(ubyte[]) code);
}

/**
* This assert function will analyze the passed in code, get the warnings,
* and make sure they match the warnings in the comments. Warnings are
* marked like so: // [warn]: Failed to do somethings.
*/
void assertAnalyzerWarnings(string code, const StaticAnalysisConfig config,
string file = __FILE__, size_t line = __LINE__)
{

MessageSet rawWarnings = getAnalyzerWarnings(code, config, file, line);
string[] codeLines = code.split("\n");

// Get the warnings ordered by line
Expand Down
Loading