Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TypeSystemService.cs « MonoDevelop.Ide.TypeSystem « MonoDevelop.Ide « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8a5bf71552b50c6308128f4bf44899dc2f1a1404 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
// 
// TypeSystemService.cs
//  
// Author:
//       Mike Krüger <mkrueger@novell.com>
// 
// Copyright (c) 2011 Mike Krüger <mkrueger@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 System.Collections.Generic;
using System.Linq;
using System.IO;
using MonoDevelop.Projects;
using Mono.Addins;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using System.Threading;
using System.Xml;
using ICSharpCode.NRefactory.Utils;
using System.Threading.Tasks;
using MonoDevelop.Ide.Extensions;
using MonoDevelop.Core.Assemblies;
using System.Text;
using MonoDevelop.Ide.Editor;
using MonoDevelop.Core.Text;
using Microsoft.CodeAnalysis.Text;
using Mono.Posix;

namespace MonoDevelop.Ide.TypeSystem
{
	public static partial class TypeSystemService
	{
		const string CurrentVersion = "1.1.8";
		static readonly List<TypeSystemParserNode> parsers;
		static string[] filesSkippedInParseThread = new string[0];

		static IEnumerable<TypeSystemParserNode> Parsers {
			get {
				return parsers;
			}
		}

		public static bool TrackFileChanges {
			get;
			set;
		}

		public static void RemoveSkippedfile (FilePath fileName)
		{
			filesSkippedInParseThread = filesSkippedInParseThread.Where (f => f != fileName).ToArray ();
		}

		public static void AddSkippedFile (FilePath fileName)
		{
			if (filesSkippedInParseThread.Any (f => f == fileName))
				return;
			filesSkippedInParseThread = filesSkippedInParseThread.Concat (new string[] { fileName }).ToArray ();
		}

		static TypeSystemService ()
		{
			parsers = new List<TypeSystemParserNode> ();
			AddinManager.AddExtensionNodeHandler ("/MonoDevelop/TypeSystem/Parser", delegate (object sender, ExtensionNodeEventArgs args) {
				switch (args.Change) {
				case ExtensionChange.Add:
					parsers.Add ((TypeSystemParserNode)args.ExtensionNode);
					break;
				case ExtensionChange.Remove:
					parsers.Remove ((TypeSystemParserNode)args.ExtensionNode);
					break;
				}
			});
			try {
				emptyWorkspace = new MonoDevelopWorkspace ();
			} catch (Exception e) {
				LoggingService.LogFatalError ("Can't create roslyn workspace", e); 
			}

			FileService.FileChanged += delegate(object sender, FileEventArgs e) {
				//				if (!TrackFileChanges)
				//					return;
				foreach (var file in e) {
					// Open documents are handled by the Document class itself.
					if (IdeApp.Workbench != null && IdeApp.Workbench.GetDocument (file.FileName) != null)
						continue;
					try {
						var text = MonoDevelop.Core.Text.StringTextSource.ReadFrom (file.FileName).Text;
						foreach (var w in Workspaces)
							w.UpdateFileContent (file.FileName, text);
					} catch (FileNotFoundException) {}
				}
				if (IdeApp.Workbench != null)
					foreach (var w in IdeApp.Workbench.Documents)
						w.StartReparseThread ();
			};

			IntitializeTrackedProjectHandling ();
		}
/*
			AddinManager.AddExtensionNodeHandler ("/MonoDevelop/TypeSystem/OutputTracking", delegate (object sender, ExtensionNodeEventArgs args) {
				var node = (TypeSystemOutputTrackingNode)args.ExtensionNode;
				switch (args.Change) {
				case ExtensionChange.Add:
					outputTrackedProjects.Add (node);
					break;
				case ExtensionChange.Remove:
					outputTrackedProjects.Remove (node);
					break;
				}
			});

		static readonly List<TypeSystemOutputTrackingNode> outputTrackedProjects = new List<TypeSystemOutputTrackingNode> ();

		static bool IsOutputTracked (DotNetProject project)
		{
			foreach (var projectType in project.GetProjectTypes ()) {
				if (outputTrackedProjects.Any (otp => otp.ProjectType != null && string.Equals (otp.ProjectType, projectType, StringComparison.OrdinalIgnoreCase))) {
					return true;
				}
			}
			return outputTrackedProjects.Any (otp => otp.LanguageName != null && string.Equals (otp.LanguageName, project.LanguageName, StringComparison.OrdinalIgnoreCase));
		}

*/

		public static TypeSystemParser GetParser (string mimeType, string buildAction = BuildAction.Compile)
		{
			var n = GetTypeSystemParserNode (mimeType, buildAction);
			return n != null ? n.Parser : null;
		}

		internal static TypeSystemParserNode GetTypeSystemParserNode (string mimeType, string buildAction)
		{
			foreach (var mt in DesktopService.GetMimeTypeInheritanceChain (mimeType)) {
				var provider = Parsers.FirstOrDefault (p => p.CanParse (mt, buildAction));
				if (provider != null)
					return provider;
			}
			return null;
		}

		public static Task<ParsedDocument> ParseFile (Project project, string fileName, CancellationToken cancellationToken = default(CancellationToken))
		{
			StringTextSource text;

			try {
				if (!File.Exists (fileName))
					return null;
				text = StringTextSource.ReadFrom (fileName);
			} catch (Exception) {
				return null;
			}

			return ParseFile (project, fileName, DesktopService.GetMimeTypeForUri (fileName), text, cancellationToken);
		}

		public static Task<ParsedDocument> ParseFile (ParseOptions options, string mimeType, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (options == null)
				throw new ArgumentNullException ("options");
			if (options.FileName == null)
				throw new ArgumentNullException ("options.FileName");

			var parser = GetParser (mimeType);
			if (parser == null)
				return Task.FromResult ((ParsedDocument)null);

			var t = Counters.ParserService.FileParsed.BeginTiming (options.FileName);
			try {
				var result = parser.Parse (options, cancellationToken);
				return result;
			} catch (OperationCanceledException) {
				return Task.FromResult ((ParsedDocument)null);
			} catch (Exception e) {
				LoggingService.LogError ("Exception while parsing: " + e);
				return Task.FromResult ((ParsedDocument)null);
			} finally {
				t.Dispose ();
			}
		}

		internal static bool CanParseProjections (Project project, string mimeType, string fileName)
		{
			var parser = GetParser (mimeType);
			if (parser == null)
				return false;
			var projectFile = project.GetProjectFile (fileName);
			if (projectFile == null)
				return false;

			return parser.CanGenerateProjection (mimeType, projectFile.BuildAction, project.SupportedLanguages);
		}

		public static Task<ParsedDocument> ParseFile (Project project, string fileName, string mimeType, ITextSource content, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ParseFile (new ParseOptions { FileName = fileName, Project = project, Content = content }, mimeType, cancellationToken);
		}

		public static Task<ParsedDocument> ParseFile (Project project, string fileName, string mimeType, TextReader content, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ParseFile (project, fileName, mimeType, new StringTextSource (content.ReadToEnd ()), cancellationToken);
		}

		public static Task<ParsedDocument> ParseFile (Project project, IReadonlyTextDocument data, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ParseFile (project, data.FileName, data.MimeType, data, cancellationToken);
		}

		internal static Task<ParsedDocumentProjection> ParseProjection (ParseOptions options, string mimeType, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (options == null)
				throw new ArgumentNullException ("options");
			if (options.FileName == null)
				throw new ArgumentNullException ("fileName");

			var parser = GetParser (mimeType);
			if (parser == null)
				return Task.FromResult ((ParsedDocumentProjection)null);

			var t = Counters.ParserService.FileParsed.BeginTiming (options.FileName);
			try {
				var result = parser.GenerateParsedDocumentProjection (options, cancellationToken);
				if (options.Project != null) {
					var Workspace = Workspaces.First () ;
					var projectId = Workspace.GetProjectId (options.Project);
					if (projectId != null) {
						foreach (var projection in result.Result.Projections) {
							var docId = Workspace.GetDocumentId (projectId, projection.Document.FileName);
							if (docId != null)
								Workspace.InformDocumentTextChange (docId, new MonoDevelopSourceText (projection.Document));
						}
					}
				}
				return result;
			} catch (OperationCanceledException) {
				return Task.FromResult ((ParsedDocumentProjection)null);
			} catch (Exception e) {
				LoggingService.LogError ("Exception while parsing: " + e);
				return Task.FromResult ((ParsedDocumentProjection)null);
			} finally {
				t.Dispose ();
			}
		}

		internal static Task<ParsedDocumentProjection> ParseProjection (Project project, string fileName, string mimeType, ITextSource content, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ParseProjection (new ParseOptions { FileName = fileName, Project = project, Content = content }, mimeType, cancellationToken);
		}

		internal static Task<ParsedDocumentProjection> ParseProjection (Project project, string fileName, string mimeType, TextReader content, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ParseProjection (project, fileName, mimeType, new StringTextSource (content.ReadToEnd ()), cancellationToken);
		}

		internal static Task<ParsedDocumentProjection> ParseProjection (Project project, IReadonlyTextDocument data, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ParseProjection (project, data.FileName, data.MimeType, data, cancellationToken);
		}

	
		#region Folding parsers
		static List<MimeTypeExtensionNode> foldingParsers;

		static IEnumerable<MimeTypeExtensionNode> FoldingParsers {
			get {
				if (foldingParsers == null) {
					foldingParsers = new List<MimeTypeExtensionNode> ();
					AddinManager.AddExtensionNodeHandler ("/MonoDevelop/TypeSystem/FoldingParser", delegate (object sender, ExtensionNodeEventArgs args) {
						switch (args.Change) {
						case ExtensionChange.Add:
							foldingParsers.Add ((MimeTypeExtensionNode)args.ExtensionNode);
							break;
						case ExtensionChange.Remove:
							foldingParsers.Remove ((MimeTypeExtensionNode)args.ExtensionNode);
							break;
						}
					});
				}
				return foldingParsers;
			}
		}

		public static IFoldingParser GetFoldingParser (string mimeType)
		{
			foreach (var mt in DesktopService.GetMimeTypeInheritanceChain (mimeType)) {
				var node = FoldingParsers.FirstOrDefault (n => n.MimeType == mt);
				if (node != null)
					return node.CreateInstance () as IFoldingParser;
			}
			return null;
		}
		#endregion

		#region Parser Database Handling

		static string GetCacheDirectory (TargetFramework framework)
		{
			var derivedDataPath = UserProfile.Current.CacheDir.Combine ("DerivedData");

			var name = new StringBuilder ();
			foreach (var ch in framework.Name) {
				if (char.IsLetterOrDigit (ch)) {
					name.Append (ch);
				} else {
					name.Append ('_');
				}
			}

			string result = derivedDataPath.Combine (name.ToString ());
			try {
				if (!Directory.Exists (result))
					Directory.CreateDirectory (result);
			} catch (Exception e) {
				LoggingService.LogError ("Error while creating derived data directories.", e);
			}
			return result;
		}

		static string InternalGetCacheDirectory (FilePath filename)
		{
			CanonicalizePath (ref filename);
			var assemblyCacheRoot = GetAssemblyCacheRoot (filename);
			try {
				if (!Directory.Exists (assemblyCacheRoot))
					return null;
				foreach (var dir in Directory.EnumerateDirectories (assemblyCacheRoot)) {
					string result;
					if (CheckCacheDirectoryIsCorrect (filename, dir, out result))
						return result;
				}
			} catch (Exception e) {
				LoggingService.LogError ("Error while getting derived data directories.", e);
			}
			return null;
		}

		/// <summary>
		/// Gets the cache directory for a projects derived data cache directory.
		/// If forceCreation is set to false the method may return null, if the cache doesn't exist.
		/// </summary>
		/// <returns>The cache directory.</returns>
		/// <param name="project">The project to get the cache for.</param>
		/// <param name="forceCreation">If set to <c>true</c> the creation is forced and the method doesn't return null.</param>
		public static string GetCacheDirectory (Project project, bool forceCreation = false)
		{
			if (project == null)
				throw new ArgumentNullException ("project");
			return GetCacheDirectory (project.FileName, forceCreation);
		}

		static readonly Dictionary<string, object> cacheLocker = new Dictionary<string, object> ();

		/// <summary>
		/// Gets the cache directory for arbitrary file names.
		/// If forceCreation is set to false the method may return null, if the cache doesn't exist.
		/// </summary>
		/// <returns>The cache directory.</returns>
		/// <param name="fileName">The file name to get the cache for.</param>
		/// <param name="forceCreation">If set to <c>true</c> the creation is forced and the method doesn't return null.</param>
		public static string GetCacheDirectory (string fileName, bool forceCreation = false)
		{
			if (fileName == null)
				throw new ArgumentNullException ("fileName");
			object locker;
			bool newLock;
			lock (cacheLocker) {
				if (!cacheLocker.TryGetValue (fileName, out locker)) {
					cacheLocker [fileName] = locker = new object ();
					newLock = true;
				} else {
					newLock = false;
				}
			}
			lock (locker) {
				var result = InternalGetCacheDirectory (fileName);
				if (newLock && result != null)
					TouchCache (result);
				if (forceCreation && result == null)
					result = CreateCacheDirectory (fileName);
				return result;
			}
		}

		struct CacheDirectoryInfo
		{
			public static readonly CacheDirectoryInfo Empty = new CacheDirectoryInfo ();

			public string FileName { get; set; }

			public string Version { get; set; }
		}

		static readonly Dictionary<FilePath, CacheDirectoryInfo> cacheDirectoryCache = new Dictionary<FilePath, CacheDirectoryInfo> ();

		static void CanonicalizePath (ref FilePath fileName)
		{
			try {
				// There are some situations where that may cause an exception.
				fileName = fileName.CanonicalPath;
			} catch (Exception) {
				// Fallback
				string fp = fileName;
				if (fp.Length > 0 && fp [fp.Length - 1] == Path.DirectorySeparatorChar)
					fileName = fp.TrimEnd (Path.DirectorySeparatorChar);
				if (fp.Length > 0 && fp [fp.Length - 1] == Path.AltDirectorySeparatorChar)
					fileName = fp.TrimEnd (Path.AltDirectorySeparatorChar);
			}
		}

		static bool CheckCacheDirectoryIsCorrect (FilePath filename, FilePath candidate, out string result)
		{
			CanonicalizePath (ref filename);
			CanonicalizePath (ref candidate);
			lock (cacheDirectoryCache) {
				CacheDirectoryInfo info;
				if (!cacheDirectoryCache.TryGetValue (candidate, out info)) {
					var dataPath = candidate.Combine ("data.xml");

					try {
						if (!File.Exists (dataPath)) {
							result = null;
							return false;
						}
						using (var reader = XmlReader.Create (dataPath)) {
							while (reader.Read ()) {
								if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "File") {
									info.Version = reader.GetAttribute ("version");
									info.FileName = reader.GetAttribute ("name");
								}
							}
						}
						cacheDirectoryCache [candidate] = info;
					} catch (Exception e) {
						LoggingService.LogError ("Error while reading derived data file " + dataPath, e);
					}
				}
	
				if (info.Version == CurrentVersion && info.FileName == filename) {
					result = candidate;
					return true;
				}
	
				result = null;
				return false;
			}
		}

		static string GetAssemblyCacheRoot (string filename)
		{
			string derivedDataPath = UserProfile.Current.CacheDir.Combine ("DerivedData");
			string name = Path.GetFileName (filename);
			return Path.Combine (derivedDataPath, name + "-" + GetStableHashCode(name).ToString ("x")); 	
		}

		/// <summary>
		/// Retrieves a hash code for the specified string that is stable across
		/// .NET upgrades.
		/// 
		/// Use this method instead of the normal <c>string.GetHashCode</c> if the hash code
		/// is persisted to disk.
		/// </summary>
		static int GetStableHashCode(string text)
		{
			unchecked {
				int h = 0;
				foreach (char c in text) {
					h = (h << 5) - h + c;
				}
				return h;
			}
		}

		static IEnumerable<string> GetPossibleCacheDirNames (string baseName)
		{
			int i = 0;
			while (i < 4096) {
				yield return Path.Combine (baseName, i.ToString ());
				i++;
			}
			throw new Exception ("Too many cache directories");
		}

		static string CreateCacheDirectory (FilePath fileName)
		{
			CanonicalizePath (ref fileName);
			try {
				string cacheRoot = GetAssemblyCacheRoot (fileName);
				string cacheDir = GetPossibleCacheDirNames (cacheRoot).First (d => !Directory.Exists (d));

				Directory.CreateDirectory (cacheDir);

				File.WriteAllText (
					Path.Combine (cacheDir, "data.xml"),
					string.Format ("<DerivedData><File name=\"{0}\" version =\"{1}\"/></DerivedData>", fileName, CurrentVersion)
				);

				return cacheDir;
			} catch (Exception e) {
				LoggingService.LogError ("Error creating cache for " + fileName, e);
				return null;
			}
		}

		static readonly FastSerializer sharedSerializer = new FastSerializer ();

		static T DeserializeObject<T> (string path) where T : class
		{
			var t = Counters.ParserService.ObjectDeserialized.BeginTiming (path);
			try {
				using (var fs = new FileStream (path, System.IO.FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
					using (var reader = new BinaryReaderWith7BitEncodedInts (fs)) {
						lock (sharedSerializer) {
							return (T)sharedSerializer.Deserialize (reader);
						}
					}
				}
			} catch (Exception e) {
				LoggingService.LogError ("Error while trying to deserialize " + typeof(T).FullName + ". stack trace:" + Environment.StackTrace, e);
				return default(T);
			} finally {
				t.Dispose ();
			}
		}

		static void SerializeObject (string path, object obj)
		{
			if (obj == null)
				throw new ArgumentNullException ("obj");

			var t = Counters.ParserService.ObjectSerialized.BeginTiming (path);
			try {
				using (var fs = new FileStream (path, System.IO.FileMode.Create, FileAccess.Write)) {
					using (var writer = new BinaryWriterWith7BitEncodedInts (fs)) {
						lock (sharedSerializer) {
							sharedSerializer.Serialize (writer, obj);
						}
					}
				}
			} catch (Exception e) {
				Console.WriteLine ("-----------------Serialize stack trace:");
				Console.WriteLine (Environment.StackTrace);
				LoggingService.LogError ("Error while writing type system cache. (object:" + obj.GetType () + ")", e);
			} finally {
				t.Dispose ();
			}
		}

		/// <summary>
		/// Removes all cache directories which are older than 30 days.
		/// </summary>
		static void CleanupCache ()
		{
			string derivedDataPath = UserProfile.Current.CacheDir.Combine ("DerivedData");
			string[] subDirs;
			
			try {
				if (!Directory.Exists (derivedDataPath))
					return;
				subDirs = Directory.GetDirectories (derivedDataPath);
			} catch (Exception e) {
				LoggingService.LogError ("Error while getting derived data directories.", e);
				return;
			}
			
			foreach (var subDir in subDirs) {
				try {
					var days = Math.Abs ((DateTime.Now - Directory.GetLastWriteTime (subDir)).TotalDays);
					if (days > 30)
						Directory.Delete (subDir, true);
				} catch (Exception e) {
					LoggingService.LogError ("Error while removing outdated cache " + subDir, e);
				}
			}
		}

		static void RemoveCache (string cacheDir)
		{
			try {
				Directory.Delete (cacheDir, true);
			} catch (Exception e) {
				LoggingService.LogError ("Error while removing cache " + cacheDir, e);
			}
		}

		static void TouchCache (string cacheDir)
		{
			try {
				Directory.SetLastWriteTime (cacheDir, DateTime.Now);
			} catch (Exception e) {
				LoggingService.LogError ("Error while touching cache directory " + cacheDir, e);
			}
		}

		static void StoreExtensionObject (string cacheDir, object extensionObject)
		{
			if (cacheDir == null)
				throw new ArgumentNullException ("cacheDir");
			if (extensionObject == null)
				throw new ArgumentNullException ("extensionObject");
			var fileName = Path.GetTempFileName ();
			SerializeObject (fileName, extensionObject);
			var cacheFile = Path.Combine (cacheDir, extensionObject.GetType ().FullName + ".cache");

			try {
				if (File.Exists (cacheFile))
					File.Delete (cacheFile);
				File.Move (fileName, cacheFile);
			} catch (Exception e) {
				LoggingService.LogError ("Error whil saving cache " + cacheFile + " for extension object:" + extensionObject, e);
			}
		}

		#endregion
	
		internal static Microsoft.CodeAnalysis.Document GetCodeAnalysisDocument (Microsoft.CodeAnalysis.DocumentId analysisDocument, CancellationToken cancellationToken = default (CancellationToken))
		{
			foreach (var w in Workspaces) {
				var doc = w.GetDocument (analysisDocument, cancellationToken);
				if (doc != null)
					return doc;
			}
			return null;
		}

		internal static void InformDocumentClose (Microsoft.CodeAnalysis.DocumentId analysisDocument, FilePath fileName)
		{
			foreach (var w in Workspaces) {
				if (w.GetOpenDocumentIds ().Contains (analysisDocument) )
					w.InformDocumentClose (analysisDocument, fileName); 

			}
		}

		internal static void InformDocumentOpen (Microsoft.CodeAnalysis.DocumentId analysisDocument, TextEditor editor)
		{
			foreach (var w in Workspaces) {
				if (w.Contains (analysisDocument.ProjectId)) {
					w.InformDocumentOpen (analysisDocument, editor); 
					return;
				}
			}
			if (!gotDocumentRequestError) {
				gotDocumentRequestError = true;
				LoggingService.LogWarning ("Can't open requested document : " + analysisDocument + ":" + editor.FileName);
			}
		}

		internal static void InformDocumentOpen (Microsoft.CodeAnalysis.Workspace ws, Microsoft.CodeAnalysis.DocumentId analysisDocument, TextEditor editor)
		{
			((MonoDevelopWorkspace)ws).InformDocumentOpen (analysisDocument, editor); 
		}

		static bool gotDocumentRequestError = false;

		public static Microsoft.CodeAnalysis.ProjectId GetProjectId (MonoDevelop.Projects.Project project)
		{
			if (project == null)
				throw new ArgumentNullException ("project");
			foreach (var w in Workspaces) {
				var projectId = w.GetProjectId (project);
				if (projectId != null) {
					return projectId;
				}
			}
			return null;
		}

		public static Microsoft.CodeAnalysis.Document GetCodeAnysisDocument (Microsoft.CodeAnalysis.DocumentId docId, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (docId == null)
				throw new ArgumentNullException ("docId");
			foreach (var w in Workspaces) {
				var documentId = w.GetDocument (docId, cancellationToken);
				if (documentId != null) {
					return documentId;
				}
			}
			return null;
		}

		public static MonoDevelop.Projects.Project GetMonoProject (Microsoft.CodeAnalysis.Project project)
		{
			if (project == null)
				throw new ArgumentNullException ("project");
			foreach (var w in Workspaces) {
				var documentId = w.GetMonoProject (project);
				if (documentId != null) {
					return documentId;
				}
			}
			return null;
		}

	}
}