2
// Gendarme.Rules.Exceptions.NewExceptionsRule
5
// Daniel Abramov <ex@vingrad.ru>
6
// Sebastien Pouliot <sebastien@ximian.com>
8
// Copyright (C) 2008 Daniel Abramov
9
// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
11
// Permission is hereby granted, free of charge, to any person obtaining a copy
12
// of this software and associated documentation files (the "Software"), to deal
13
// in the Software without restriction, including without limitation the rights
14
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
// copies of the Software, and to permit persons to whom the Software is
16
// furnished to do so, subject to the following conditions:
18
// The above copyright notice and this permission notice shall be included in
19
// all copies or substantial portions of the Software.
21
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
34
using Gendarme.Framework;
35
using Gendarme.Framework.Engines;
36
using Gendarme.Framework.Rocks;
38
namespace Gendarme.Rules.Exceptions {
40
[EngineDependency (typeof (OpCodeEngine))]
41
abstract public class NewExceptionsRule : Rule, IMethodRule {
43
public override void Initialize (IRunner runner)
45
base.Initialize (runner);
46
// if the module does not reference any of these types, don't analyze it
47
// (unless this is corlib itself since they're defined in it :-)
48
Runner.AnalyzeModule += delegate (object o, RunnerEventArgs e) {
49
Active = (e.CurrentAssembly.Name.Name == "mscorlib" ||
50
e.CurrentModule.AnyTypeReference ((TypeReference tr) => {
51
return CheckException (tr);
56
abstract protected bool CheckException (TypeReference type);
57
abstract protected Severity Severity { get; }
59
public RuleResult CheckMethod (MethodDefinition method)
61
// if method has no IL, the rule doesn't apply
63
return RuleResult.DoesNotApply;
65
// and when the IL contains a NewObj instruction
66
if (!OpCodeEngine.GetBitmask (method).Get (Code.Newobj))
67
return RuleResult.DoesNotApply;
69
// look for newobj instructions
70
foreach (Instruction ins in method.Body.Instructions) {
71
if (ins.OpCode.Code != Code.Newobj)
74
// obtain a reference to the constructor's type
75
TypeReference ctype = (ins.Operand as MethodReference).DeclaringType;
77
// report a defect if an offending exception type is found
78
if (CheckException (ctype))
79
Runner.Report (method, ins, Severity, Confidence.High, ctype.Name);
82
return Runner.CurrentRuleResult;