//
// Gendarme.Rules.Concurrency.WriteStaticFieldFromInstanceMethodRule
//
// Authors:
//	Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2006,2008 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;

using Mono.Cecil;
using Mono.Cecil.Cil;

using Gendarme.Framework;
using Gendarme.Framework.Engines;
using Gendarme.Framework.Helpers;
using Gendarme.Framework.Rocks;

namespace Gendarme.Rules.Concurrency {

	/// <summary>
	/// This rule is used to check for instance methods which write values to static fields.
	/// This may cause problems if multiple instances of the type exist and are used in 
	/// multithreaded applications. 
	/// </summary>
	/// <example>
	/// Bad example:
	/// <code>
	/// static int default_value;
 	///
	/// public int Value {
	///	get {
	///		if (default_value == 0) {
	///   			default_value = -1;
	///   		}
	/// 		return (value > default_value) ? value : 0;
	///	}
	/// }
	/// </code>
	/// </example>
	/// <example>
	/// Good example:
	/// <code>
	/// static int default_value = -1;
 	///
	/// public int Value {
    	/// 	get {
	/// 		return (value > default_value) ? value : 0;
	/// 	}
	/// }
	/// </code>
	/// </example>

	[Problem ("This instance method writes to static fields. This may cause problem with multiple instances in multithreaded applications.")]
	[Solution ("Move initialization to the static constructor or ensure appropriate locking.")]
	[EngineDependency (typeof (OpCodeEngine))]
	public class WriteStaticFieldFromInstanceMethodRule : Rule, IMethodRule {

		private const string ThreadStaticAttribute = "System.ThreadStaticAttribute";

		static bool CheckField (FieldReference field)
		{
			// skip instance fields and generated static field (likely by the compiler)
			if ((field == null) || field.IsGeneratedCode ())
				return false;

			// check if the field could be resolved
			FieldDefinition fd = field.Resolve ();
			if (fd == null)
				return false;

			// skip fields decorated with [ThreadStatic] (the runtime will use
			// thread local storage for these so they are thread safe)
			if (fd.HasCustomAttributes) {
				if (fd.CustomAttributes.ContainsType (ThreadStaticAttribute))
					return false;
			}
			return true;
		}

		public RuleResult CheckMethod (MethodDefinition method)
		{
			// rule does not apply if 
			// - the method has no body (e.g. p/invokes, icalls don't)
			// - the method is static
			// - the method was generated by the compiler or a tool
			if (!method.HasBody || method.IsStatic || method.IsGeneratedCode ())
				return RuleResult.DoesNotApply;

			// avoid looping if we're sure there's no call in the method
			if (!OpCodeEngine.GetBitmask (method).Get (Code.Stsfld))
				return RuleResult.DoesNotApply;

			// *** ok, the rule applies! ***

			foreach (Instruction ins in method.Body.Instructions) {
				// look for stsfld instructions
				if (ins.OpCode.Code == Code.Stsfld) {
					FieldReference fr = (ins.Operand as FieldReference);
					if (CheckField (fr)) {
						string text = String.Format ("The static field '{0}', of type '{1}'. is being set in an instance method.", fr.Name, fr.FieldType);
						Runner.Report (method, ins, Severity.Medium, Confidence.High, text);
					}
				}
			}

			return Runner.CurrentRuleResult;
		}
	}
}
