@@ -31,7 +31,6 @@
 using System.Runtime.CompilerServices;
 using System.Security;
 using System.Text;
-using System.Text.RegularExpressions;
 using System.Threading;
 
 using Microsoft.Scripting;
@@ -51,8 +50,8 @@
 using Debugging = Microsoft.Scripting.Debugging;
 using PyAst = IronPython.Compiler.Ast;
 
-
-namespace IronPython.Runtime {
+namespace IronPython.Runtime
+{
     public delegate int HashDelegate(object o, ref HashDelegate dlg);
 
     public sealed partial class PythonContext : LanguageContext {
@@ -188,23 +187,22 @@ public sealed partial class PythonContext : LanguageContext {
         // tracing / in-proc debugging support
         private Debugging.CompilerServices.DebugContext _debugContext;
         private Debugging.ITracePipeline _tracePipeline;
-        
-        [ThreadStatic]
-        private static Stack<PythonTracebackListener> _tracebackListeners;
+
+        private Microsoft.Scripting.Utils.ThreadLocal<Stack<PythonTracebackListener>> _tracebackListeners;
         private static int _tracingThreads;
 
         internal FunctionCode.CodeList _allCodes;
         internal readonly object _codeCleanupLock = new object(), _codeUpdateLock = new object();
         internal int _codeCount, _nextCodeCleanup = 200;
         private int _recursionLimit;
-        [ThreadStatic]
-        private static bool _enableTracing;
+
+        private Microsoft.Scripting.Utils.ThreadLocal<bool> _enableTracing = new Microsoft.Scripting.Utils.ThreadLocal<bool>();
 
         internal readonly List<FunctionStack> _mainThreadFunctionStack;
         private CallSite<Func<CallSite, CodeContext, object, object>> _callSite0LightEh;
         private List<WeakReference> _weakExtensionMethodSets;
 
-        #region Generated Python Shared Call Sites Storage
+#region Generated Python Shared Call Sites Storage
 
         // *** BEGIN GENERATED CODE ***
         // generated by function: gen_shared_call_sites_storage from: generate_calls.py
@@ -219,7 +217,7 @@ public sealed partial class PythonContext : LanguageContext {
 
         // *** END GENERATED CODE ***
 
-        #endregion
+#endregion
 
         /// <summary>
         /// Creates a new PythonContext not bound to Engine.
@@ -375,8 +373,8 @@ public PythonContext(ScriptDomainManager/*!*/ manager, IDictionary<string, objec
             }
             set {
                 lock (_codeUpdateLock) {
-                    bool oldEnableTracing = _enableTracing;
-                    _enableTracing = value;
+                    bool oldEnableTracing = _enableTracing.Value;
+                    _enableTracing.Value = value;
 
                     bool flip = false;
                     if (value && !oldEnableTracing) {
@@ -454,7 +452,7 @@ internal sealed class PythonEqualityComparer : IEqualityComparer, IEqualityCompa
             }
         }
 
-        #region Specialized Hashers
+#region Specialized Hashers
 
         [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
         internal readonly HashDelegate InitialHasher;
@@ -565,7 +563,7 @@ private sealed class OptimizedBuiltinHasher {
             }
         }
 
-        #endregion
+#endregion
 
         public override LanguageOptions/*!*/ Options {
             get { return PythonOptions; }
@@ -1131,7 +1129,7 @@ private sealed class OptimizedBuiltinHasher {
         }
 #endif
 
-        #region Scopes
+#region Scopes
 
         public override Scope GetScope(string/*!*/ path) {
             PythonModule module = GetModuleByPath(path);
@@ -1290,7 +1288,7 @@ private sealed class OptimizedBuiltinHasher {
             return module;
         }
 
-        #endregion
+#endregion
 
         public object GetWarningsModule() {
             object warnings = null;
@@ -1324,7 +1322,7 @@ private sealed class OptimizedBuiltinHasher {
             return res;
         }
 
-        #region Assembly Loading
+#region Assembly Loading
 #if FEATURE_ASSEMBLY_RESOLVE && FEATURE_FILESYSTEM
 
         internal Assembly LoadAssemblyFromFile(string file) {
@@ -1414,7 +1412,7 @@ class AssemblyResolveHolder {
             }
         }
 #endif
-        #endregion
+#endregion
 
         public override ICollection<string> GetSearchPaths() {
             List<string> result = new List<string>();
@@ -1471,7 +1469,7 @@ class AssemblyResolveHolder {
         }
 
         // TODO: ExceptionFormatter service
-        #region Stack Traces and Exceptions
+#region Stack Traces and Exceptions
 
         public override string FormatException(Exception exception) {
             ContractUtils.RequiresNotNull(exception, "exception");
@@ -1709,7 +1707,7 @@ class AssemblyResolveHolder {
 
 #endif
 
-        #endregion
+#endregion
         
         // TODO: Replace all usages with direct access
         internal static PythonContext/*!*/ GetContext(CodeContext/*!*/ context) {
@@ -2144,7 +2142,7 @@ class AssemblyResolveHolder {
 
         }
 
-        #region Object Operations
+#region Object Operations
 
         public override ConvertBinder/*!*/ CreateConvertBinder(Type/*!*/ toType, bool? explicitCast) {
             if (explicitCast != null) {
@@ -2194,9 +2192,9 @@ class AssemblyResolveHolder {
             );
         }
 
-        #endregion
+#endregion
 
-        #region Per-Runtime Call Sites
+#region Per-Runtime Call Sites
 
         private bool InvokeOperatorWorker(CodeContext/*!*/ context, UnaryOperators oper, object target, out object result) {
             if (_newUnarySites == null) {
@@ -2548,15 +2546,15 @@ class AttrKey : IEquatable<AttrKey> {
                 _name = name;
             }
 
-            #region IEquatable<AttrKey> Members
+#region IEquatable<AttrKey> Members
 
             public bool Equals(AttrKey other) {
                 if (other == null) return false;
 
                 return _type == other._type && _name == other._name;
             }
 
-            #endregion
+#endregion
 
             public override bool Equals(object obj) {
                 return Equals(obj as AttrKey);
@@ -2591,9 +2589,9 @@ class AttrKey : IEquatable<AttrKey> {
             }
         }
 
-        #endregion
+#endregion
 
-        #region Conversions
+#region Conversions
 
         internal Int32 ConvertToInt32(object value) {
             if (_intSite == null) {
@@ -3058,9 +3056,9 @@ class AttrKey : IEquatable<AttrKey> {
 
         }
 
-        #endregion
+#endregion
 
-        #region Compiled Code Support
+#region Compiled Code Support
 
         internal CompiledLoader GetCompiledLoader() {
             if (_compiledLoader == null) {
@@ -3079,7 +3077,7 @@ class AttrKey : IEquatable<AttrKey> {
             return _compiledLoader;
         }
 
-        #endregion
+#endregion
 
         /// <summary>
         /// Returns a shared code context for the current PythonContext.  This shared
@@ -3190,7 +3188,7 @@ class AttrKey : IEquatable<AttrKey> {
             set { _numericCulture = value; }
         }
 
-        #region Command Dispatching
+#region Command Dispatching
 
         /// <summary>
         /// Sets the current command dispatcher for the Python command line.  The previous dispatcher
@@ -3226,7 +3224,7 @@ class AttrKey : IEquatable<AttrKey> {
             }
         }
 
-        #endregion
+#endregion
 
         internal CallSite<Func<CallSite, CodeContext, object, object, object>> PropertyGetSite {
             get {
@@ -3485,7 +3483,7 @@ public FunctionComparer(PythonContext/*!*/ context, T cmpfunc)
             }
         }
 
-        #region Binder Factories
+#region Binder Factories
 
         internal CompatibilityInvokeBinder/*!*/ CompatInvoke(CallInfo /*!*/ callInfo) {
             if (_compatInvokeBinders == null) {
@@ -3950,13 +3948,13 @@ class OperationRetTypeKey<T> : IEquatable<OperationRetTypeKey<T>> {
                 Operation = operation;
             }
 
-            #region IEquatable<BinaryOperationRetTypeKey> Members
+#region IEquatable<BinaryOperationRetTypeKey> Members
 
             public bool Equals(OperationRetTypeKey<T> other) {
                 return other.ReturnType == ReturnType && other.Operation.Equals(Operation);
             }
 
-            #endregion
+#endregion
 
             public override int GetHashCode() {
                 return ReturnType.GetHashCode() ^ Operation.GetHashCode();
@@ -4004,9 +4002,9 @@ class OperationRetTypeKey<T> : IEquatable<OperationRetTypeKey<T>> {
             );
         }
 
-        #endregion
+#endregion
 
-        #region Scope Access
+#region Scope Access
 
         public override T ScopeGetVariable<T>(Scope scope, string name) {
             var storage = scope.Storage as ScopeStorage;
@@ -4068,19 +4066,9 @@ class OperationRetTypeKey<T> : IEquatable<OperationRetTypeKey<T>> {
             return base.ScopeTryGetVariable(scope, name, out value);
         }
 
-        #endregion
-
-        #region Tracing
+#endregion
 
-        internal static PythonTracebackListener TracebackListener {
-            get {
-                if (_tracebackListeners == null) {
-                    return null;
-                }
-
-                return _tracebackListeners.Peek(); 
-            }
-        }
+#region Tracing
 
         internal Debugging.CompilerServices.DebugContext DebugContext {
             get {
@@ -4101,9 +4089,10 @@ class OperationRetTypeKey<T> : IEquatable<OperationRetTypeKey<T>> {
             }
 
             if (_tracebackListeners == null) {
-                _tracebackListeners = new Stack<PythonTracebackListener>();
+                _tracebackListeners = new Microsoft.Scripting.Utils.ThreadLocal<Stack<PythonTracebackListener>>();
+                _tracebackListeners.Value = new Stack<PythonTracebackListener>();
                 // push the default listener
-                _tracebackListeners.Push(new PythonTracebackListener(this));
+                _tracebackListeners.Value.Push(new PythonTracebackListener(this));
             }
         }
 
@@ -4116,7 +4105,7 @@ class OperationRetTypeKey<T> : IEquatable<OperationRetTypeKey<T>> {
         internal void RegisterTracebackHandler() {
             Debug.Assert(_tracePipeline != null);   // ensure debug context should have been called
 
-            _tracePipeline.TraceCallback = _tracebackListeners.Peek();
+            _tracePipeline.TraceCallback = _tracebackListeners.Value.Peek();
             EnableTracing = true;
         }
 
@@ -4127,22 +4116,24 @@ class OperationRetTypeKey<T> : IEquatable<OperationRetTypeKey<T>> {
         }
 
         internal void PushTracebackHandler(PythonTracebackListener listener) {
+            var tracebackListeners = _tracebackListeners.Value;
             if (_debugContext != null) {
-                while (_tracebackListeners.Count > 0 && _tracebackListeners.Peek().ExceptionThrown) {
+                while (tracebackListeners.Count > 0 && tracebackListeners.Peek().ExceptionThrown) {
                     // remove any orphaned traceback listeners that are just doing pops
-                    _tracebackListeners.Pop();
+                    tracebackListeners.Pop();
                 }
-                _tracebackListeners.Push(listener);
+                tracebackListeners.Push(listener);
             }
         }
 
         internal void PopTracebackHandler() {
-            if (_debugContext != null && _tracebackListeners.Count > 1) {
-                _tracebackListeners.Pop();
+            var tracebackListeners = _tracebackListeners.Value;
+            if (_debugContext != null && tracebackListeners.Count > 1) {
+                tracebackListeners.Pop();
             }
         }
 
-        #endregion
+#endregion
 
         internal ExtensionMethodSet UniqifyExtensions(ExtensionMethodSet newSet) {
             int deadIndex = -1;