1 //          Copyright Brian Schott (Hackerpilot) 2014.
2 // Distributed under the Boost Software License, Version 1.0.
3 //    (See accompanying file LICENSE_1_0.txt or copy at
4 //          http://www.boost.org/LICENSE_1_0.txt)
5 
6 module analysis.run;
7 
8 import std.stdio;
9 import std.array;
10 import std.conv;
11 import std.algorithm;
12 import std.range;
13 import std.array;
14 import dparse.lexer;
15 import dparse.parser;
16 import dparse.ast;
17 import dparse.rollback_allocator;
18 import std.typecons : scoped;
19 
20 import std.experimental.allocator : CAllocatorImpl;
21 import std.experimental.allocator.mallocator : Mallocator;
22 import std.experimental.allocator.building_blocks.region : Region;
23 import std.experimental.allocator.building_blocks.allocator_list : AllocatorList;
24 
25 import analysis.config;
26 import analysis.base;
27 import analysis.style;
28 import analysis.enumarrayliteral;
29 import analysis.pokemon;
30 import analysis.del;
31 import analysis.fish;
32 import analysis.numbers;
33 import analysis.objectconst;
34 import analysis.range;
35 import analysis.ifelsesame;
36 import analysis.constructors;
37 import analysis.unused;
38 import analysis.unused_label;
39 import analysis.duplicate_attribute;
40 import analysis.opequals_without_tohash;
41 import analysis.length_subtraction;
42 import analysis.builtin_property_names;
43 import analysis.asm_style;
44 import analysis.logic_precedence;
45 import analysis.stats_collector;
46 import analysis.undocumented;
47 import analysis.comma_expression;
48 import analysis.function_attributes;
49 import analysis.local_imports;
50 import analysis.unmodified;
51 import analysis.if_statements;
52 import analysis.redundant_parens;
53 import analysis.mismatched_args;
54 import analysis.label_var_same_name_check;
55 import analysis.line_length;
56 import analysis.auto_ref_assignment;
57 import analysis.incorrect_infinite_range;
58 import analysis.useless_assert;
59 import analysis.alias_syntax_check;
60 import analysis.static_if_else;
61 
62 import dsymbol.string_interning : internString;
63 import dsymbol.scope_;
64 import dsymbol.semantic;
65 import dsymbol.conversion;
66 import dsymbol.conversion.first;
67 import dsymbol.conversion.second;
68 import dsymbol.modulecache : ModuleCache;
69 
70 import readers;
71 
72 bool first = true;
73 
74 private alias ASTAllocator = CAllocatorImpl!(
75 		AllocatorList!(n => Region!Mallocator(1024 * 128), Mallocator));
76 
77 void messageFunction(string fileName, size_t line, size_t column, string message, bool isError)
78 {
79 	writefln("%s(%d:%d)[%s]: %s", fileName, line, column, isError ? "error" : "warn", message);
80 }
81 
82 void messageFunctionJSON(string fileName, size_t line, size_t column, string message, bool)
83 {
84 	writeJSON("dscanner.syntax", fileName, line, column, message);
85 }
86 
87 void writeJSON(string key, string fileName, size_t line, size_t column, string message)
88 {
89 	if (!first)
90 		writeln(",");
91 	else
92 		first = false;
93 	writeln("    {");
94 	writeln(`      "key": "`, key, `",`);
95 	writeln(`      "fileName": "`, fileName, `",`);
96 	writeln(`      "line": `, line, `,`);
97 	writeln(`      "column": `, column, `,`);
98 	writeln(`      "message": "`, message.replace(`"`, `\"`), `"`);
99 	write("    }");
100 }
101 
102 bool syntaxCheck(string[] fileNames, ref StringCache stringCache, ref ModuleCache moduleCache)
103 {
104 	StaticAnalysisConfig config = defaultStaticAnalysisConfig();
105 	return analyze(fileNames, config, stringCache, moduleCache, false);
106 }
107 
108 void generateReport(string[] fileNames, const StaticAnalysisConfig config,
109 		ref StringCache cache, ref ModuleCache moduleCache)
110 {
111 	writeln("{");
112 	writeln(`  "issues": [`);
113 	first = true;
114 	StatsCollector stats = new StatsCollector("");
115 	ulong lineOfCodeCount;
116 	foreach (fileName; fileNames)
117 	{
118 		auto code = fileName == "stdin" ? readStdin() : readFile(fileName);
119 		// Skip files that could not be read and continue with the rest
120 		if (code.length == 0)
121 			continue;
122 		RollbackAllocator r;
123 		const(Token)[] tokens;
124 		const Module m = parseModule(fileName, code, &r, cache, true, tokens, &lineOfCodeCount);
125 		stats.visit(m);
126 		MessageSet results = analyze(fileName, m, config, moduleCache, tokens, true);
127 		foreach (result; results[])
128 		{
129 			writeJSON(result.key, result.fileName, result.line, result.column, result.message);
130 		}
131 	}
132 	writeln();
133 	writeln("  ],");
134 	writefln(`  "interfaceCount": %d,`, stats.interfaceCount);
135 	writefln(`  "classCount": %d,`, stats.classCount);
136 	writefln(`  "functionCount": %d,`, stats.functionCount);
137 	writefln(`  "templateCount": %d,`, stats.templateCount);
138 	writefln(`  "structCount": %d,`, stats.structCount);
139 	writefln(`  "statementCount": %d,`, stats.statementCount);
140 	writefln(`  "lineOfCodeCount": %d,`, lineOfCodeCount);
141 	writefln(`  "undocumentedPublicSymbols": %d`, stats.undocumentedPublicSymbols);
142 	writeln("}");
143 }
144 
145 /**
146  * For multiple files
147  *
148  * Returns: true if there were errors or if there were warnings and `staticAnalyze` was true.
149  */
150 bool analyze(string[] fileNames, const StaticAnalysisConfig config,
151 		ref StringCache cache, ref ModuleCache moduleCache, bool staticAnalyze = true)
152 {
153 	bool hasErrors = false;
154 	foreach (fileName; fileNames)
155 	{
156 		auto code = fileName == "stdin" ? readStdin() : readFile(fileName);
157 		// Skip files that could not be read and continue with the rest
158 		if (code.length == 0)
159 			continue;
160 		RollbackAllocator r;
161 		uint errorCount = 0;
162 		uint warningCount = 0;
163 		const(Token)[] tokens;
164 		const Module m = parseModule(fileName, code, &r, cache, false, tokens,
165 				null, &errorCount, &warningCount);
166 		assert(m);
167 		if (errorCount > 0 || (staticAnalyze && warningCount > 0))
168 			hasErrors = true;
169 		MessageSet results = analyze(fileName, m, config, moduleCache, tokens, staticAnalyze);
170 		if (results is null)
171 			continue;
172 		foreach (result; results[])
173 		{
174 			hasErrors = true;
175 			writefln("%s(%d:%d)[warn]: %s", result.fileName, result.line,
176 					result.column, result.message);
177 		}
178 	}
179 	return hasErrors;
180 }
181 
182 const(Module) parseModule(string fileName, ubyte[] code, RollbackAllocator* p,
183 		ref StringCache cache, bool report, ref const(Token)[] tokens,
184 		ulong* linesOfCode = null, uint* errorCount = null, uint* warningCount = null)
185 {
186 	import stats : isLineOfCode;
187 
188 	LexerConfig config;
189 	config.fileName = fileName;
190 	config.stringBehavior = StringBehavior.source;
191 	tokens = getTokensForParser(code, config, &cache);
192 	if (linesOfCode !is null)
193 		(*linesOfCode) += count!(a => isLineOfCode(a.type))(tokens);
194 	return dparse.parser.parseModule(tokens, fileName, p, report
195 			? &messageFunctionJSON : &messageFunction, errorCount, warningCount);
196 }
197 
198 MessageSet analyze(string fileName, const Module m, const StaticAnalysisConfig analysisConfig,
199 		ref ModuleCache moduleCache, const(Token)[] tokens, bool staticAnalyze = true)
200 {
201 	if (!staticAnalyze)
202 		return null;
203 
204 	auto symbolAllocator = new ASTAllocator;
205 	auto first = scoped!FirstPass(m, internString(fileName), symbolAllocator,
206 			symbolAllocator, true, &moduleCache, null);
207 	first.run();
208 
209 	secondPass(first.rootSymbol, first.moduleScope, moduleCache);
210 	typeid(SemanticSymbol).destroy(first.rootSymbol);
211 	const(Scope)* moduleScope = first.moduleScope;
212 
213 	BaseAnalyzer[] checks;
214 
215 	if (analysisConfig.asm_style_check)
216 		checks ~= new AsmStyleCheck(fileName, moduleScope);
217 	if (analysisConfig.backwards_range_check)
218 		checks ~= new BackwardsRangeCheck(fileName, moduleScope);
219 	if (analysisConfig.builtin_property_names_check)
220 		checks ~= new BuiltinPropertyNameCheck(fileName, moduleScope);
221 	if (analysisConfig.comma_expression_check)
222 		checks ~= new CommaExpressionCheck(fileName, moduleScope);
223 	if (analysisConfig.constructor_check)
224 		checks ~= new ConstructorCheck(fileName, moduleScope);
225 	if (analysisConfig.could_be_immutable_check)
226 		checks ~= new UnmodifiedFinder(fileName, moduleScope);
227 	if (analysisConfig.delete_check)
228 		checks ~= new DeleteCheck(fileName, moduleScope);
229 	if (analysisConfig.duplicate_attribute)
230 		checks ~= new DuplicateAttributeCheck(fileName, moduleScope);
231 	if (analysisConfig.enum_array_literal_check)
232 		checks ~= new EnumArrayLiteralCheck(fileName, moduleScope);
233 	if (analysisConfig.exception_check)
234 		checks ~= new PokemonExceptionCheck(fileName, moduleScope);
235 	if (analysisConfig.float_operator_check)
236 		checks ~= new FloatOperatorCheck(fileName, moduleScope);
237 	if (analysisConfig.function_attribute_check)
238 		checks ~= new FunctionAttributeCheck(fileName, moduleScope);
239 	if (analysisConfig.if_else_same_check)
240 		checks ~= new IfElseSameCheck(fileName, moduleScope);
241 	if (analysisConfig.label_var_same_name_check)
242 		checks ~= new LabelVarNameCheck(fileName, moduleScope);
243 	if (analysisConfig.length_subtraction_check)
244 		checks ~= new LengthSubtractionCheck(fileName, moduleScope);
245 	if (analysisConfig.local_import_check)
246 		checks ~= new LocalImportCheck(fileName, moduleScope);
247 	if (analysisConfig.logical_precedence_check)
248 		checks ~= new LogicPrecedenceCheck(fileName, moduleScope);
249 	if (analysisConfig.mismatched_args_check)
250 		checks ~= new MismatchedArgumentCheck(fileName, moduleScope);
251 	if (analysisConfig.number_style_check)
252 		checks ~= new NumberStyleCheck(fileName, moduleScope);
253 	if (analysisConfig.object_const_check)
254 		checks ~= new ObjectConstCheck(fileName, moduleScope);
255 	if (analysisConfig.opequals_tohash_check)
256 		checks ~= new OpEqualsWithoutToHashCheck(fileName, moduleScope);
257 	if (analysisConfig.redundant_parens_check)
258 		checks ~= new RedundantParenCheck(fileName, moduleScope);
259 	if (analysisConfig.style_check)
260 		checks ~= new StyleChecker(fileName, moduleScope);
261 	if (analysisConfig.undocumented_declaration_check)
262 		checks ~= new UndocumentedDeclarationCheck(fileName, moduleScope);
263 	if (analysisConfig.unused_label_check)
264 		checks ~= new UnusedLabelCheck(fileName, moduleScope);
265 	if (analysisConfig.unused_variable_check)
266 		checks ~= new UnusedVariableCheck(fileName, moduleScope);
267 	if (analysisConfig.long_line_check)
268 		checks ~= new LineLengthCheck(fileName, tokens);
269 	if (analysisConfig.auto_ref_assignment_check)
270 		checks ~= new AutoRefAssignmentCheck(fileName);
271 	if (analysisConfig.incorrect_infinite_range_check)
272 		checks ~= new IncorrectInfiniteRangeCheck(fileName);
273 	if (analysisConfig.useless_assert_check)
274 		checks ~= new UselessAssertCheck(fileName);
275 	if (analysisConfig.alias_syntax_check)
276 		checks ~= new AliasSyntaxCheck(fileName);
277 	if (analysisConfig.static_if_else_check)
278 		checks ~= new StaticIfElse(fileName);
279 	version (none)
280 		if (analysisConfig.redundant_if_check)
281 			checks ~= new IfStatementCheck(fileName, moduleScope);
282 
283 	foreach (check; checks)
284 	{
285 		check.visit(m);
286 	}
287 
288 	MessageSet set = new MessageSet;
289 	foreach (check; checks)
290 		foreach (message; check.messages)
291 			set.insert(message);
292 	return set;
293 }