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

MonoDevelopWorkspace.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: 7d1f6727b1a12fcc15cb0735a5b9f94bb4f096b3 (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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
//
// MonoDevelopWorkspace.cs
//
// Author:
//       Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc. (http://xamarin.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 Microsoft.CodeAnalysis;
using System.Linq;
using System.IO;
using MonoDevelop.Core;
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
using System.Threading.Tasks;
using MonoDevelop.Ide.Editor;
using Microsoft.CodeAnalysis.Host;
using MonoDevelop.Core.Text;
using System.Collections.Concurrent;
using MonoDevelop.Ide.CodeFormatting;
using Gtk;
using MonoDevelop.Ide.Editor.Projection;
using System.Reflection;
using Microsoft.CodeAnalysis.Host.Mef;
using System.Text;
using System.Collections.Immutable;
using System.ComponentModel;
using Mono.Addins;
using MonoDevelop.Core.AddIns;
using Microsoft.CodeAnalysis.Shared.Utilities;

namespace MonoDevelop.Ide.TypeSystem
{

	public class MonoDevelopWorkspace : Workspace
	{
		public const string ServiceLayer = nameof(MonoDevelopWorkspace);

		readonly static HostServices services;
		internal readonly WorkspaceId Id;

		CancellationTokenSource src = new CancellationTokenSource ();
		bool disposed;
		readonly MonoDevelop.Projects.Solution monoDevelopSolution;
		object addLock = new object();
		bool added;

		public MonoDevelop.Projects.Solution MonoDevelopSolution {
			get {
				return monoDevelopSolution;
			}
		}

		static string[] mefHostServices = new [] {
			"Microsoft.CodeAnalysis.Workspaces",
			//FIXME: this does not load yet. We should provide alternate implementations of its services.
			//"Microsoft.CodeAnalysis.Workspaces.Desktop",
			"Microsoft.CodeAnalysis.Features",
			"Microsoft.CodeAnalysis.CSharp",
			"Microsoft.CodeAnalysis.CSharp.Workspaces",
			"Microsoft.CodeAnalysis.CSharp.Features",
			"Microsoft.CodeAnalysis.VisualBasic",
			"Microsoft.CodeAnalysis.VisualBasic.Workspaces",
			"Microsoft.CodeAnalysis.VisualBasic.Features",
		};

		internal static HostServices HostServices {
			get {
				return services;
			}
		}

		static MonoDevelopWorkspace ()
		{
			List<Assembly> assemblies = new List<Assembly> ();
			assemblies.Add (typeof (MonoDevelopWorkspace).Assembly);
			foreach (var asmName in mefHostServices) {
				try {
					var asm = Assembly.Load (asmName);
					if (asm == null)
						continue;
					assemblies.Add (asm);
				} catch (Exception ex) {
					LoggingService.LogError ("Error - can't load host service assembly: " + asmName, ex);
				}
			}
			assemblies.Add (typeof(MonoDevelopWorkspace).Assembly);
			foreach (var node in AddinManager.GetExtensionNodes ("/MonoDevelop/Ide/TypeService/MefHostServices")) {
				var assemblyNode = node as AssemblyExtensionNode;
				if (assemblyNode == null)
					continue;
				try {
					var assemblyFilePath = assemblyNode.Addin.GetFilePath(assemblyNode.FileName);
					var assembly = Assembly.LoadFrom(assemblyFilePath);
					assemblies.Add (assembly);
				} catch (Exception e) {
					LoggingService.LogError ("Workspace can't load assembly " + assemblyNode.FileName + " to host mef services.", e);
					continue;
				}
			}
			services = MefHostServices.Create (assemblies);
		}

		/// <summary>
		/// This bypasses the type system service. Use with care.
		/// </summary>
		[EditorBrowsable(EditorBrowsableState.Never)]
		internal void OpenSolutionInfo (SolutionInfo sInfo)
		{
			OnSolutionAdded (sInfo);
		}

		internal MonoDevelopWorkspace (MonoDevelop.Projects.Solution solution) : base (services, "MonoDevelop")
		{
			this.monoDevelopSolution = solution;
			this.Id = WorkspaceId.Next ();
			if (IdeApp.Workspace != null && solution != null) {
				IdeApp.Workspace.ActiveConfigurationChanged += HandleActiveConfigurationChanged;
			}
		}

		protected override void Dispose (bool finalize)
		{
			base.Dispose (finalize);
			if (disposed)
				return;
			disposed = true;
			CancelLoad ();
			if (IdeApp.Workspace != null) {
				IdeApp.Workspace.ActiveConfigurationChanged -= HandleActiveConfigurationChanged;
			}
			foreach (var prj in monoDevelopSolution.GetAllProjects ()) {
				UnloadMonoProject (prj);
			}
		}

		internal void InformDocumentTextChange (DocumentId id, SourceText text)
		{
			base.ApplyDocumentTextChanged (id, text);
		}

		void CancelLoad ()
		{
			src.Cancel ();
			src = new CancellationTokenSource ();
		}

		static StatusBarIcon statusIcon = null;
		static int workspacesLoading = 0;

		internal static event EventHandler LoadingFinished;

		static void OnLoadingFinished (EventArgs e)
		{
			var handler = LoadingFinished;
			if (handler != null)
				handler (null, e);
		}

		internal void HideStatusIcon ()
		{
			Gtk.Application.Invoke (delegate {
				workspacesLoading--;
				if (workspacesLoading == 0 && statusIcon != null) {
					statusIcon.Dispose ();
					statusIcon = null;
					OnLoadingFinished (EventArgs.Empty);
					WorkspaceLoaded?.Invoke (this, EventArgs.Empty);
				}
			});
		}

		public event EventHandler WorkspaceLoaded;

		internal void ShowStatusIcon ()
		{
			Gtk.Application.Invoke (delegate {
				workspacesLoading++;
				if (statusIcon != null)
					return;
				statusIcon = IdeApp.Workbench?.StatusBar.ShowStatusIcon (ImageService.GetIcon ("md-parser"));
				if (statusIcon != null)
					statusIcon.ToolTip = GettextCatalog.GetString ("Gathering class information");
			});
		}

		async void HandleActiveConfigurationChanged (object sender, EventArgs e)
		{
			ShowStatusIcon ();
			CancelLoad ();
			var token = src.Token;

			try {
				var si = await CreateSolutionInfo (monoDevelopSolution, token).ConfigureAwait (false);
				if (si != null)
					OnSolutionReloaded (si);
			} catch (OperationCanceledException) {
			} catch (AggregateException ae) {
				ae.Flatten ().Handle (x => x is OperationCanceledException);
			} catch (Exception ex) {
				LoggingService.LogError ("Error while reloading solution.", ex);
			} finally {
				HideStatusIcon ();
			}
		}

		SolutionData solutionData;
		Task<SolutionInfo> CreateSolutionInfo (MonoDevelop.Projects.Solution solution, CancellationToken token)
		{
			return Task.Run (async delegate {
				var projects = new ConcurrentBag<ProjectInfo> ();
				var mdProjects = solution.GetAllProjects ();
				projectionList = projectionList.Clear ();
				projectIdMap.Clear ();
				projectIdToMdProjectMap = projectIdToMdProjectMap.Clear ();
				projectDataMap.Clear ();
				solutionData = new SolutionData ();
				List<Task> allTasks = new List<Task> ();
				foreach (var proj in mdProjects) {
					if (token.IsCancellationRequested)
						return null;
					var netProj = proj as MonoDevelop.Projects.DotNetProject;
					if (netProj != null && !netProj.SupportsRoslyn)
						continue;
					var tp = LoadProject (proj, token).ContinueWith (t => {
						if (!t.IsCanceled)
							projects.Add (t.Result);
					});
					allTasks.Add (tp);
				}
				await Task.WhenAll (allTasks.ToArray ()).ConfigureAwait (false);
				if (token.IsCancellationRequested)
					return null;
				var modifiedWhileLoading = modifiedProjects;
				modifiedProjects = new List<MonoDevelop.Projects.DotNetProject> ();
				var solutionInfo = SolutionInfo.Create (GetSolutionId (solution), VersionStamp.Create (), solution.FileName, projects);
				foreach (var project in modifiedWhileLoading) {
					if (solution.ContainsItem (project)) {
						return await CreateSolutionInfo (solution, token).ConfigureAwait (false);
					}
				}

				lock (addLock) {
					if (!added) {
						added = true;
						OnSolutionAdded (solutionInfo);
					}
				}
				return solutionInfo;
			});
		}

		internal Task<SolutionInfo> TryLoadSolution (CancellationToken cancellationToken = default(CancellationToken))
		{
			return CreateSolutionInfo (monoDevelopSolution, CancellationTokenSource.CreateLinkedTokenSource (cancellationToken, src.Token).Token);
		}

		internal void UnloadSolution ()
		{
			OnSolutionRemoved (); 
		}

		Dictionary<MonoDevelop.Projects.Solution, SolutionId> solutionIdMap = new Dictionary<MonoDevelop.Projects.Solution, SolutionId> ();

		internal SolutionId GetSolutionId (MonoDevelop.Projects.Solution solution)
		{
			if (solution == null)
				throw new ArgumentNullException ("solution");
			lock (solutionIdMap) {
				SolutionId result;
				if (!solutionIdMap.TryGetValue (solution, out result)) {
					result = SolutionId.CreateNewId (solution.Name);
					solutionIdMap [solution] = result;
				}
				return result;
			}
		}

		ConcurrentDictionary<MonoDevelop.Projects.Project, ProjectId> projectIdMap = new ConcurrentDictionary<MonoDevelop.Projects.Project, ProjectId> ();
		ImmutableDictionary<ProjectId, MonoDevelop.Projects.Project> projectIdToMdProjectMap = ImmutableDictionary<ProjectId, MonoDevelop.Projects.Project>.Empty;
		ConcurrentDictionary<ProjectId, ProjectData> projectDataMap = new ConcurrentDictionary<ProjectId, ProjectData> ();

		internal MonoDevelop.Projects.Project GetMonoProject (Project project)
		{
			return GetMonoProject (project.Id);
		}

		internal MonoDevelop.Projects.Project GetMonoProject (ProjectId projectId)
		{
			projectIdToMdProjectMap.TryGetValue (projectId, out var result);
			return result;
		}

		internal bool Contains (ProjectId projectId) 
		{
			return projectDataMap.ContainsKey (projectId);
		}

		internal ProjectId GetProjectId (MonoDevelop.Projects.Project p)
		{
			lock (projectIdMap) {
				ProjectId result;
				if (projectIdMap.TryGetValue (p, out result))
					return result;
				return null;
			}
		}

		internal ProjectId GetOrCreateProjectId (MonoDevelop.Projects.Project p)
		{
			lock (projectIdMap) {
				ProjectId result;
				if (!projectIdMap.TryGetValue (p, out result)) {
					result = ProjectId.CreateNewId (p.Name);
					projectIdMap [p] = result;
					projectIdToMdProjectMap = projectIdToMdProjectMap.Add (result, p);
				}
				return result;
			}
		}

		ProjectData GetProjectData (ProjectId id)
		{
			lock (projectIdMap) {
				ProjectData result;

				if (projectDataMap.TryGetValue (id, out result)) {
					return result;
				}
				return null;
			}
		}

		ProjectData CreateProjectData (ProjectId id)
		{
			lock (projectIdMap) {
				var result = new ProjectData (id);
				projectDataMap [id] = result;
				return result;
			}
		}

		class ProjectData
		{
			readonly ProjectId projectId;
			readonly Dictionary<string, DocumentId> documentIdMap;

			public ProjectInfo Info {
				get;
				set;
			}

			public ProjectData (ProjectId projectId)
			{
				this.projectId = projectId;
				documentIdMap = new Dictionary<string, DocumentId> (FilePath.PathComparer);
			}

			internal DocumentId GetOrCreateDocumentId (string name, ProjectData previous)
			{
				if (previous != null) {
					var oldId = previous.GetDocumentId (name);
					if (oldId != null) {
						AddDocumentId (oldId, name);
						return oldId;
					}
				}
				return GetOrCreateDocumentId (name);
			}

			internal DocumentId GetOrCreateDocumentId (string name)
			{
				lock (documentIdMap) {
					DocumentId result;
					if (!documentIdMap.TryGetValue (name, out result)) {
						result = DocumentId.CreateNewId (projectId, name);
						documentIdMap [name] = result;
					}
					return result;
				}
			}

			internal void AddDocumentId (DocumentId id, string name)
			{
				lock (documentIdMap) {
					documentIdMap[name] = id;
				}
			}
			
			public DocumentId GetDocumentId (string name)
			{
				DocumentId result;
				if (!documentIdMap.TryGetValue (name, out result)) {
					return null;
				}
				return result;
			}

			internal void RemoveDocument (string name)
			{
				documentIdMap.Remove (name);
			}
		}

		internal DocumentId GetDocumentId (ProjectId projectId, string name)
		{
			var data = GetProjectData (projectId);
			if (data == null)
				return null;
			return data.GetDocumentId (name);
		}

		void UnloadMonoProject (MonoDevelop.Projects.Project project)
		{
			if (project == null)
				throw new ArgumentNullException (nameof (project));
			project.FileAddedToProject -= OnFileAdded;
			project.FileRemovedFromProject -= OnFileRemoved;
			project.FileRenamedInProject -= OnFileRenamed;
			project.Modified -= OnProjectModified;
		}

		async Task<ProjectInfo> LoadProject (MonoDevelop.Projects.Project p, CancellationToken token)
		{
			if (!projectIdMap.ContainsKey (p)) {
				p.FileAddedToProject += OnFileAdded;
				p.FileRemovedFromProject += OnFileRemoved;
				p.FileRenamedInProject += OnFileRenamed;
				p.Modified += OnProjectModified;
			}

			var projectId = GetOrCreateProjectId (p);

			//when reloading e.g. after a save, preserve document IDs
			var oldProjectData = GetProjectData (projectId);
			var projectData = CreateProjectData (projectId);

			var references = await CreateMetadataReferences (p, projectId, token).ConfigureAwait (false);
			if (token.IsCancellationRequested)
				return null;
			var config = IdeApp.Workspace != null ? p.GetConfiguration (IdeApp.Workspace.ActiveConfiguration) as MonoDevelop.Projects.DotNetProjectConfiguration : null;
			MonoDevelop.Projects.DotNetCompilerParameters cp = null;
			if (config != null)
				cp = config.CompilationParameters;
			FilePath fileName = IdeApp.Workspace != null ? p.GetOutputFileName (IdeApp.Workspace.ActiveConfiguration) : (FilePath)"";
			if (fileName.IsNullOrEmpty)
				fileName = new FilePath (p.Name + ".dll");

			if (token.IsCancellationRequested)
				return null;
			var sourceFiles = await p.GetSourceFilesAsync (config != null ? config.Selector : null).ConfigureAwait (false);
			var documents = CreateDocuments (projectData, p, token, sourceFiles, oldProjectData);
			if (documents == null)
				return null;
			var info = ProjectInfo.Create (
				projectId,
				VersionStamp.Create (),
				p.Name,
				fileName.FileNameWithoutExtension,
				LanguageNames.CSharp,
				p.FileName,
				fileName,
				cp != null ? cp.CreateCompilationOptions () : null,
				cp != null ? cp.CreateParseOptions (config) : null,
				documents.Item1,
				CreateProjectReferences (p, token),
				references,
				additionalDocuments: documents.Item2
			);
			projectData.Info = info;
			return info;
		}

		internal void UpdateProjectionEntry (MonoDevelop.Projects.ProjectFile projectFile, IReadOnlyList<Projection> projections)
		{
			if (projectFile == null)
				throw new ArgumentNullException (nameof (projectFile));
			if (projections == null)
				throw new ArgumentNullException (nameof (projections));
			lock (projectionListUpdateLock) {
				foreach (var entry in projectionList) {
					if (entry?.File?.FilePath == projectFile.FilePath) {
						projectionList = projectionList.Remove (entry);
						break;
					}
				}
				projectionList = projectionList.Add (new ProjectionEntry { File = projectFile, Projections = projections });
			}

		}

		internal class SolutionData
		{
			public ConcurrentDictionary<string, TextLoader> Files = new ConcurrentDictionary<string, TextLoader> (); 
		}

		internal static Func<SolutionData, string, TextLoader> CreateTextLoader = (data, fileName) => data.Files.GetOrAdd (fileName, a => new MonoDevelopTextLoader (a));

		static DocumentInfo CreateDocumentInfo (SolutionData data, string projectName, ProjectData id, MonoDevelop.Projects.ProjectFile f, SourceCodeKind sourceCodeKind)
		{
			var filePath = f.FilePath;
			return DocumentInfo.Create (
				id.GetOrCreateDocumentId (filePath),
				filePath,
				new [] { projectName }.Concat (f.ProjectVirtualPath.ParentDirectory.ToString ().Split (Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)),
				sourceCodeKind,
				CreateTextLoader (data, f.Name),
				f.Name,
				false
			);
		}
		object projectionListUpdateLock = new object ();
		ImmutableList<ProjectionEntry> projectionList = ImmutableList<ProjectionEntry>.Empty;

		internal IReadOnlyList<ProjectionEntry> ProjectionList {
			get {
				return projectionList;
			}
		}

		internal class ProjectionEntry
		{
			public MonoDevelop.Projects.ProjectFile File;
			public IReadOnlyList<Projection> Projections;
		}

		static bool CanGenerateAnalysisContextForNonCompileable (MonoDevelop.Projects.Project p, MonoDevelop.Projects.ProjectFile f)
		{
			var mimeType = DesktopService.GetMimeTypeForUri (f.FilePath);
			var node = TypeSystemService.GetTypeSystemParserNode (mimeType, f.BuildAction);
			if (node?.Parser == null)
				return false;
			return node.Parser.CanGenerateAnalysisDocument (mimeType, f.BuildAction, p.SupportedLanguages);
		}

		Tuple<List<DocumentInfo>, List<DocumentInfo>> CreateDocuments (ProjectData projectData, MonoDevelop.Projects.Project p, CancellationToken token, MonoDevelop.Projects.ProjectFile [] sourceFiles, ProjectData oldProjectData)
		{
			var documents = new List<DocumentInfo> ();
			var additionalDocuments = new List<DocumentInfo> ();
			var duplicates = new HashSet<DocumentId> ();
			// use given source files instead of project.Files because there may be additional files added by msbuild targets
			foreach (var f in sourceFiles) {
				if (token.IsCancellationRequested)
					return null;
				if (f.Subtype == MonoDevelop.Projects.Subtype.Directory)
					continue;

				SourceCodeKind sck;
				if (TypeSystemParserNode.IsCompileableFile (f, out sck) || CanGenerateAnalysisContextForNonCompileable (p, f)) {
					var id = projectData.GetOrCreateDocumentId (f.Name, oldProjectData);
					if (!duplicates.Add (id))
						continue;
					documents.Add (CreateDocumentInfo (solutionData, p.Name, projectData, f, sck));
				} else {
					var id = projectData.GetOrCreateDocumentId (f.Name, projectData);
					if (!duplicates.Add (id))
						continue;
					additionalDocuments.Add (CreateDocumentInfo (solutionData, p.Name, projectData, f, sck));

					foreach (var projectedDocument in GenerateProjections (f, projectData, p, oldProjectData)) {
						var projectedId = projectData.GetOrCreateDocumentId (projectedDocument.FilePath, oldProjectData);
						if (!duplicates.Add (projectedId))
							continue;
						documents.Add (projectedDocument);
					}
				}
			}
			return Tuple.Create (documents, additionalDocuments);
		}

		IEnumerable<DocumentInfo> GenerateProjections (MonoDevelop.Projects.ProjectFile f, ProjectData projectData, MonoDevelop.Projects.Project p, ProjectData oldProjectData, HashSet<DocumentId> duplicates = null)
		{
			var mimeType = DesktopService.GetMimeTypeForUri (f.FilePath);
			var node = TypeSystemService.GetTypeSystemParserNode (mimeType, f.BuildAction);
			if (node == null || !node.Parser.CanGenerateProjection (mimeType, f.BuildAction, p.SupportedLanguages))
				yield break;
			var options = new ParseOptions {
				FileName = f.FilePath,
				Project = p,
				Content = TextFileProvider.Instance.GetReadOnlyTextEditorData (f.FilePath),
			};
			var projections = node.Parser.GenerateProjections (options);
			var entry = new ProjectionEntry ();
			entry.File = f;
			var list = new List<Projection> ();
			entry.Projections = list;
			foreach (var projection in projections.Result) {
				list.Add (projection);
				if (duplicates != null && !duplicates.Add (projectData.GetOrCreateDocumentId (projection.Document.FileName, oldProjectData)))
					continue;
				var plainName = projection.Document.FileName.FileName;
				yield return DocumentInfo.Create (
					projectData.GetOrCreateDocumentId (projection.Document.FileName, oldProjectData),
					plainName,
					new [] { p.Name }.Concat (f.ProjectVirtualPath.ParentDirectory.ToString ().Split (Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)),
					SourceCodeKind.Regular,
					TextLoader.From (TextAndVersion.Create (new MonoDevelopSourceText (projection.Document), VersionStamp.Create (), projection.Document.FileName)),
					projection.Document.FileName,
					false
				);
			}
			projectionList = projectionList.Add (entry);
		}

		internal static readonly string [] DefaultAssemblies = {
			typeof(string).Assembly.Location,                                // mscorlib
			typeof(System.Text.RegularExpressions.Regex).Assembly.Location,  // System
			typeof(System.Linq.Enumerable).Assembly.Location,                // System.Core
			typeof(System.Data.VersionNotFoundException).Assembly.Location,  // System.Data
			typeof(System.Xml.XmlDocument).Assembly.Location,                // System.Xml
		};


		static async Task<List<MetadataReference>> CreateMetadataReferences (MonoDevelop.Projects.Project proj, ProjectId projectId, CancellationToken token)
		{
			List<MetadataReference> result = new List<MetadataReference> ();

			var netProject = proj as MonoDevelop.Projects.DotNetProject;
			if (netProject == null) {
				// create some default references for unsupported project types.
				foreach (var asm in DefaultAssemblies) {
					var metadataReference = MetadataReferenceCache.LoadReference (projectId, asm);
					result.Add (metadataReference);
				}
				return result;
			}
			var configurationSelector = IdeApp.Workspace?.ActiveConfiguration ?? MonoDevelop.Projects.ConfigurationSelector.Default;
			var hashSet = new HashSet<string> (FilePath.PathComparer);

			try {
				foreach (var file in await netProject.GetReferencedAssemblies (configurationSelector, false).ConfigureAwait (false)) {
					if (token.IsCancellationRequested)
						return result;
					string fileName;
					if (!Path.IsPathRooted (file.FilePath)) {
						fileName = Path.Combine (Path.GetDirectoryName (netProject.FileName), file.FilePath);
					} else {
						fileName = file.FilePath.FullPath;
					}
					if (!hashSet.Add (fileName))
						continue;
					var metadataReference = MetadataReferenceCache.LoadReference (projectId, fileName);
					if (metadataReference == null)
						continue;
					metadataReference = metadataReference.WithAliases (file.EnumerateAliases ());
					result.Add (metadataReference);
				}
			} catch (Exception e) {
				LoggingService.LogError ("Error while getting referenced assemblies", e);
			}

			try {
				foreach (var pr in netProject.GetReferencedItems (configurationSelector)) {
					if (token.IsCancellationRequested)
						return result;
					var referencedProject = pr as MonoDevelop.Projects.DotNetProject;
					if (referencedProject == null)
						continue;
					if (TypeSystemService.IsOutputTrackedProject (referencedProject)) {
						var fileName = referencedProject.GetOutputFileName (configurationSelector);
						if (!hashSet.Add (fileName))
							continue;
						var metadataReference = MetadataReferenceCache.LoadReference (projectId, fileName);
						if (metadataReference != null)
							result.Add (metadataReference);
					}
				}
			} catch (Exception e) {
				LoggingService.LogError ("Error while getting referenced projects", e);
			}
			return result;
		}

		IEnumerable<ProjectReference> CreateProjectReferences (MonoDevelop.Projects.Project p, CancellationToken token)
		{
			var netProj = p as MonoDevelop.Projects.DotNetProject;
			if (netProj == null)
				yield break;

			//GetReferencedAssemblyProjects returns filtered projects, like:
			//MSBuild Condtion='something'
			//pref.ReferenceOutputAssembly
			//and for iOS/Android extensions
			MonoDevelop.Projects.DotNetProject [] referencedProjects;
			try {
				referencedProjects = netProj.GetReferencedAssemblyProjects (IdeApp.Workspace?.ActiveConfiguration ?? MonoDevelop.Projects.ConfigurationSelector.Default).ToArray ();
			} catch (Exception e) {
				LoggingService.LogError ("Error while getting referenced projects.", e);
				yield break;
			};
			var addedProjects = new HashSet<MonoDevelop.Projects.DotNetProject> ();
			foreach (var pr in netProj.References.Where (pr => pr.ReferenceType == MonoDevelop.Projects.ReferenceType.Project)) {
				//But since GetReferencedAssemblyProjects is returing DotNetProject, we lose information about
				//reference Aliases, hence we have to loop over references
				var referencedProject = pr.ResolveProject (p.ParentSolution) as MonoDevelop.Projects.DotNetProject;
				if (referencedProject == null)
					continue;
				if (!referencedProjects.Contains (referencedProject))
					continue;
				if (!addedProjects.Add (referencedProject))
					continue;
				if (TypeSystemService.IsOutputTrackedProject (referencedProject))
					continue;
				var splittedAliases = (pr.Aliases ?? "").Split (new [] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
				yield return new ProjectReference (GetOrCreateProjectId (referencedProject), ImmutableArray<string>.Empty.AddRange (splittedAliases));
			}
		}

		#region Open documents
		public override bool CanOpenDocuments {
			get {
				return true;
			}
		}

		public override void OpenDocument (DocumentId documentId, bool activate = true)
		{
			var doc = GetDocument (documentId);
			if (doc != null) {
				var mdProject = GetMonoProject (doc.Project);
				if (doc != null) {
					IdeApp.Workbench.OpenDocument (doc.FilePath, mdProject, activate);
				}
			}
		}

		List<MonoDevelopSourceTextContainer> openDocuments = new List<MonoDevelopSourceTextContainer>();
		internal void InformDocumentOpen (DocumentId documentId, ITextDocument editor)
		{
			var document = InternalInformDocumentOpen (documentId, editor);
			if (document as Document != null) {
				foreach (var linkedDoc in ((Document)document).GetLinkedDocumentIds ()) {
					InternalInformDocumentOpen (linkedDoc, editor);
				}
			}
		}

		TextDocument InternalInformDocumentOpen (DocumentId documentId, ITextDocument editor)
		{
			TextDocument document = this.GetDocument (documentId) ?? this.GetAdditionalDocument (documentId);
			if (document == null || openDocuments.Any (d => d.Id == documentId)) {
				return document;
			}
			var monoDevelopSourceTextContainer = new MonoDevelopSourceTextContainer (documentId, editor);
			lock (openDocuments) {
				openDocuments.Add (monoDevelopSourceTextContainer);
			}
			if (document is Document) {
				OnDocumentOpened (documentId, monoDevelopSourceTextContainer);
			} else {
				OnAdditionalDocumentOpened (documentId, monoDevelopSourceTextContainer);
			}
			return document;
		}

		ProjectChanges projectChanges;

		protected override void OnDocumentTextChanged (Document document)
		{
			base.OnDocumentTextChanged (document);
		}

		protected override void OnDocumentClosing (DocumentId documentId)
		{
			base.OnDocumentClosing (documentId);
			lock (openDocuments) {
				var openDoc = openDocuments.FirstOrDefault (d => d.Id == documentId);
				if (openDoc != null) {
					openDoc.Dispose ();
					openDocuments.Remove (openDoc);
				}
			}
		}

//		internal override bool CanChangeActiveContextDocument {
//			get {
//				return true;
//			}
//		}

		internal void InformDocumentClose (DocumentId analysisDocument, string filePath)
		{
			try {
				lock (openDocuments) {
					var openDoc = openDocuments.FirstOrDefault (d => d.Id == analysisDocument);
					if (openDoc != null) {
						openDoc.Dispose ();
						openDocuments.Remove (openDoc);
					}
				}
				if (!CurrentSolution.ContainsDocument (analysisDocument))
					return;
				var loader = new MonoDevelopTextLoader (filePath);
				var document = this.GetDocument (analysisDocument);
				var openDocument = this.openDocuments.FirstOrDefault (w => w.Id == analysisDocument);
				if (openDocument != null) {
					openDocument.Dispose ();
					openDocuments.Remove (openDocument);
				}

				if (document == null) {
					var ad = this.GetAdditionalDocument (analysisDocument);
					if (ad != null)
						OnAdditionalDocumentClosed (analysisDocument, loader);
					return;
				}
				OnDocumentClosed (analysisDocument, loader);
				foreach (var linkedDoc in document.GetLinkedDocumentIds ()) {
					OnDocumentClosed (linkedDoc, loader); 
				}
			} catch (Exception e) {
				LoggingService.LogError ("Exception while closing document.", e); 
			}
		}
		
		public override void CloseDocument (DocumentId documentId)
		{
		}

		//FIXME: this should NOT be async. our implementation is doing some very expensive things like formatting that it shouldn't need to do.
		protected override void ApplyDocumentTextChanged (DocumentId id, SourceText text)
		{
			tryApplyState_documentTextChangedTasks.Add (ApplyDocumentTextChangedCore (id, text));
		}

		async Task ApplyDocumentTextChangedCore (DocumentId id, SourceText text)
		{
			var document = GetDocument (id);
			if (document == null)
				return;
			bool isOpen;
			var filePath = document.FilePath;
			Projection projection = null;
			foreach (var entry in ProjectionList) {
				var p = entry.Projections.FirstOrDefault (proj => proj?.Document?.FileName != null && FilePath.PathComparer.Equals (proj.Document.FileName, filePath));
				if (p != null) {
					filePath = entry.File.FilePath;
					projection = p;
					break;
				}
			}
			var data = TextFileProvider.Instance.GetTextEditorData (filePath, out isOpen);
			// Guard against already done changes in linked files.
			// This shouldn't happen but the roslyn merging seems not to be working correctly in all cases :/
			if (document.GetLinkedDocumentIds ().Length > 0 && isOpen && !(text.GetType ().FullName == "Microsoft.CodeAnalysis.Text.ChangedText")) {
				return;
			}

			SourceText formerText;
			lock (tryApplyState_documentTextChangedContents) {
				if (tryApplyState_documentTextChangedContents.TryGetValue (filePath, out formerText)) {
					if (formerText.Length == text.Length && formerText.ToString () == text.ToString ())
						return;
				}
				tryApplyState_documentTextChangedContents[filePath] = text;
			}

			SourceText oldFile;
			if (!isOpen || !document.TryGetText (out oldFile)) {
				oldFile = await document.GetTextAsync ();
			}
			var changes = text.GetTextChanges (oldFile).OrderByDescending (c => c.Span.Start).ToList ();
			int delta = 0;

			if (!isOpen) {
				delta = ApplyChanges (projection, data, changes);
				var formatter = CodeFormatterService.GetFormatter (data.MimeType);
				if (formatter != null && formatter.SupportsPartialDocumentFormatting) {
					var mp = GetMonoProject (CurrentSolution.GetProject (id.ProjectId));
					string currentText = data.Text;

					foreach (var change in changes) {
						delta -= change.Span.Length - change.NewText.Length;
						var startOffset = change.Span.Start - delta;

						if (projection != null) {
							int originalOffset;
							if (projection.TryConvertFromProjectionToOriginal (startOffset, out originalOffset))
								startOffset = originalOffset;
						}

						string str;
						if (change.NewText.Length == 0) {
							str = formatter.FormatText (mp.Policies, currentText, TextSegment.FromBounds (Math.Max (0, startOffset - 1), Math.Min (data.Length, startOffset + 1)));
						} else {
							str = formatter.FormatText (mp.Policies, currentText, new TextSegment (startOffset, change.NewText.Length));
						}
						data.ReplaceText (startOffset, change.NewText.Length, str);
					}
				}
				data.Save ();
				if (projection != null) {
					await UpdateProjectionsDocuments (document, data);
				} else {
					OnDocumentTextChanged (id, new MonoDevelopSourceText (data), PreservationMode.PreserveValue);
				}
				FileService.NotifyFileChanged (filePath);
			} else {
				var formatter = CodeFormatterService.GetFormatter (data.MimeType);
				var documentContext = IdeApp.Workbench.Documents.FirstOrDefault (d => FilePath.PathComparer.Compare (d.FileName, filePath) == 0);
				var root = await projectChanges.NewProject.GetDocument (id).GetSyntaxRootAsync ();
				var annotatedNode = root.DescendantNodesAndSelf ().FirstOrDefault (n => n.HasAnnotation (TypeSystemService.InsertionModeAnnotation));
				SyntaxToken? renameTokenOpt = root.GetAnnotatedNodesAndTokens (Microsoft.CodeAnalysis.CodeActions.RenameAnnotation.Kind)
												  .Where (s => s.IsToken)
												  .Select (s => s.AsToken ())
												  .Cast<SyntaxToken?> ()
												  .FirstOrDefault ();

				if (documentContext != null) {
					var editor = (TextEditor)data;
					await Runtime.RunInMainThread (async () => {
						using (var undo = editor.OpenUndoGroup ()) {
							var oldVersion = editor.Version;
							delta = ApplyChanges (projection, data, changes);
							var versionBeforeFormat = editor.Version;

							if (formatter != null && formatter.SupportsOnTheFlyFormatting) {
								foreach (var change in changes) {
									delta -= change.Span.Length - change.NewText.Length;
									var startOffset = change.Span.Start - delta;
									if (projection != null) {
										int originalOffset;
										if (projection.TryConvertFromProjectionToOriginal (startOffset, out originalOffset))
											startOffset = originalOffset;
									}
									if (change.NewText.Length == 0) {
										formatter.OnTheFlyFormat (editor, documentContext, TextSegment.FromBounds (Math.Max (0, startOffset - 1), Math.Min (data.Length, startOffset + 1)));
									} else {
										formatter.OnTheFlyFormat (editor, documentContext, new TextSegment (startOffset, change.NewText.Length));
									}
								}
							}
							if (annotatedNode != null && GetInsertionPoints != null) {
								IdeApp.Workbench.Documents.First (d => d.FileName == editor.FileName).Select ();
								var formattedVersion = editor.Version;

								int startOffset = versionBeforeFormat.MoveOffsetTo (editor.Version, annotatedNode.Span.Start);
								int endOffset = versionBeforeFormat.MoveOffsetTo (editor.Version, annotatedNode.Span.End);

								// alway whole line start & delimiter
								var startLine = editor.GetLineByOffset (startOffset);
								startOffset = startLine.Offset;

								var endLine = editor.GetLineByOffset (endOffset);
								endOffset = endLine.EndOffsetIncludingDelimiter + 1;

								var insertionCursorSegment = TextSegment.FromBounds (startOffset, endOffset);
								string textToInsert = editor.GetTextAt (insertionCursorSegment).TrimEnd ();
								editor.RemoveText (insertionCursorSegment);
								var insertionPoints = await GetInsertionPoints (editor, editor.CaretOffset);
								if (insertionPoints.Count == 0) {
									// Just to get sure if no insertion points -> go back to the formatted version.
									var textChanges = editor.Version.GetChangesTo (formattedVersion).ToList ();
									using (var undo2 = editor.OpenUndoGroup ()) {
										foreach (var textChange in textChanges) {
											foreach (var v in textChange.TextChanges.Reverse ()) {
												editor.ReplaceText (v.Offset, v.RemovalLength, v.InsertedText);
											}
										}
									}
									return;
								}
								string insertionModeOperation;
								const int CSharpMethodKind = 8875;


								bool isMethod = annotatedNode.RawKind == CSharpMethodKind;

								if (!isMethod) {
									// atm only for generate field/property : remove all new lines generated & just insert the plain node.
									// for methods it's not so easy because of "extract code" changes.
									foreach (var textChange in editor.Version.GetChangesTo (oldVersion).ToList ()) {
										foreach (var v in textChange.TextChanges.Reverse ()) {
											editor.ReplaceText (v.Offset, v.RemovalLength, v.InsertedText);
										}
									}
								}

								switch (annotatedNode.RawKind) {
								case 8873: // C# field
									insertionModeOperation = GettextCatalog.GetString ("Insert Field");
									break;
								case CSharpMethodKind:
									insertionModeOperation = GettextCatalog.GetString ("Insert Method");
									break;
								case 8892: // C# property 
									insertionModeOperation = GettextCatalog.GetString ("Insert Property");
									break;
								default:
									insertionModeOperation = GettextCatalog.GetString ("Insert Code");
									break;
								}

								var options = new InsertionModeOptions (
									insertionModeOperation,
									insertionPoints,
									point => {
										if (!point.Success)
											return;
										point.InsertionPoint.Insert (editor, textToInsert);
									}
								);
								options.ModeExitedAction += delegate (InsertionCursorEventArgs args) {
									if (!args.Success) {
										var textChanges = editor.Version.GetChangesTo (oldVersion).ToList ();
										using (var undo2 = editor.OpenUndoGroup ()) {
											foreach (var textChange in textChanges) {
												foreach (var v in textChange.TextChanges.Reverse ())
													editor.ReplaceText (v.Offset, v.RemovalLength, v.InsertedText);
											}
										}
									}
								};
								for (int i = 0; i < insertionPoints.Count; i++) {
									if (insertionPoints [i].Location.Line < editor.CaretLine) {
										options.FirstSelectedInsertionPoint = Math.Min (isMethod ? i + 1 : i, insertionPoints.Count - 1);
									} else {
										break;
									}
								}
								options.ModeExitedAction += delegate {
									if (renameTokenOpt.HasValue)
										StartRenameSession (editor, documentContext, versionBeforeFormat, renameTokenOpt.Value);
								};
								editor.StartInsertionMode (options);
							}
						}
					});
				}

				if (projection != null) {
					await UpdateProjectionsDocuments (document, data);
				} else {
					OnDocumentTextChanged (id, new MonoDevelopSourceText (data.CreateDocumentSnapshot ()), PreservationMode.PreserveValue);
				}
			}
		}
		internal static Func<TextEditor, int, Task<List<InsertionPoint>>> GetInsertionPoints;
		internal static Action<TextEditor, DocumentContext, ITextSourceVersion, SyntaxToken?> StartRenameSession;

		async Task UpdateProjectionsDocuments (Document document, ITextDocument data)
		{
			var project = TypeSystemService.GetMonoProject (document.Project);
			var file = project.Files.GetFile (data.FileName);
			var node = TypeSystemService.GetTypeSystemParserNode (data.MimeType, file.BuildAction);
			if (node != null && node.Parser.CanGenerateProjection (data.MimeType, file.BuildAction, project.SupportedLanguages)) {
				var options = new ParseOptions {
					FileName = file.FilePath,
					Project = project,
					Content = TextFileProvider.Instance.GetReadOnlyTextEditorData (file.FilePath),
				};
				var projections = await node.Parser.GenerateProjections (options);
				UpdateProjectionEntry (file, projections);
				var projectId = GetProjectId (project);
				var projectdata = GetProjectData (projectId);
				foreach (var projected in projections) {
					OnDocumentTextChanged (projectdata.GetDocumentId (projected.Document.FileName), new MonoDevelopSourceText (projected.Document), PreservationMode.PreserveValue);
				}
			}
		}

		static int ApplyChanges (Projection projection, ITextDocument data, List<Microsoft.CodeAnalysis.Text.TextChange> changes)
		{
			int delta = 0;
			foreach (var change in changes) {
				var offset = change.Span.Start;

				if (projection != null) {
					int originalOffset;
					//If change is outside projection segments don't apply it...
					if (projection.TryConvertFromProjectionToOriginal (offset, out originalOffset)) {
						offset = originalOffset;
						data.ReplaceText (offset, change.Span.Length, change.NewText);
						delta += change.Span.Length - change.NewText.Length;
					}
				} else {
					data.ReplaceText (offset, change.Span.Length, change.NewText);
					delta += change.Span.Length - change.NewText.Length;
				}
			}

			return delta;
		}

		// used to pass additional state from Apply* to TryApplyChanges so it can batch certain operations such as saving projects
		HashSet<MonoDevelop.Projects.Project> tryApplyState_changedProjects = new HashSet<MonoDevelop.Projects.Project> ();
		List<Task> tryApplyState_documentTextChangedTasks = new List<Task> ();
		Dictionary<string, SourceText> tryApplyState_documentTextChangedContents =  new Dictionary<string, SourceText> ();

		internal override bool TryApplyChanges (Solution newSolution, IProgressTracker progressTracker)
		{
			// this is supported on the main thread only
			// see https://github.com/dotnet/roslyn/pull/18043
			// as a result, we can assume that the things it calls are _also_ main thread only
			Runtime.CheckMainThread ();
			lock (projectModifyLock) {
				freezeProjectModify = true;
				try {
					var ret = base.TryApplyChanges (newSolution, progressTracker);

					if (tryApplyState_documentTextChangedTasks.Count > 0) {
						Task.WhenAll (tryApplyState_documentTextChangedTasks).ContinueWith (t => {
							try {
								t.Wait ();
							} catch (Exception ex) {
								LoggingService.LogError ("Error applying changes to documents", ex);
							}
							if (IdeApp.Workbench != null) {
								var changedFiles = new HashSet<string> (tryApplyState_documentTextChangedContents.Keys, FilePath.PathComparer);
								foreach (var w in IdeApp.Workbench.Documents) {
									if (w.IsFile && changedFiles.Contains (w.FileName)) {
										w.StartReparseThread ();
									}
								}
							}
						}, CancellationToken.None, TaskContinuationOptions.None, Runtime.MainTaskScheduler);
					}

					if (tryApplyState_changedProjects.Count > 0) {
						IdeApp.ProjectOperations.SaveAsync (tryApplyState_changedProjects);
					}

					return ret;
				} finally {
					tryApplyState_documentTextChangedContents.Clear ();
					tryApplyState_documentTextChangedTasks.Clear ();
					tryApplyState_changedProjects.Clear ();
					freezeProjectModify = false; 
				}
			}
		}

		public override bool CanApplyChange (ApplyChangesKind feature)
		{
			switch (feature) {
			case ApplyChangesKind.AddDocument:
			case ApplyChangesKind.RemoveDocument:
			case ApplyChangesKind.ChangeDocument:
			//HACK: we don't actually support adding and removing metadata references from project
			//however, our MetadataReferenceCache currently depends on (incorrectly) using TryApplyChanges
			case ApplyChangesKind.AddMetadataReference:
			case ApplyChangesKind.RemoveMetadataReference:
				return true;
			default:
				return false;
			}
		}

		protected override void ApplyProjectChanges (ProjectChanges projectChanges)
		{
			this.projectChanges = projectChanges;
			base.ApplyProjectChanges (projectChanges);
		}

		protected override void ApplyDocumentAdded (DocumentInfo info, SourceText text)
		{
			var id = info.Id;
			MonoDevelop.Projects.Project mdProject = null;

			if (id.ProjectId != null) {
				var project = CurrentSolution.GetProject (id.ProjectId);
				mdProject = GetMonoProject (project);
				if (mdProject == null)
					LoggingService.LogWarning ("Couldn't find project for newly generated file {0} (Project {1}).", info.Name, info.Id.ProjectId);
			}

			var path = DetermineFilePath (info.Id, info.Name, info.FilePath, info.Folders, mdProject?.FileName.ParentDirectory, true);
			info = info.WithFilePath (path).WithTextLoader (new MonoDevelopTextLoader (path));

			string formattedText;
			var formatter = CodeFormatterService.GetFormatter (DesktopService.GetMimeTypeForUri (path)); 
			if (formatter != null && mdProject != null) {
				formattedText = formatter.FormatText (mdProject.Policies, text.ToString ());
			} else {
				formattedText = text.ToString ();
			}

			var textSource = new StringTextSource (formattedText, text.Encoding ?? System.Text.Encoding.UTF8);
			try {
				textSource.WriteTextTo (path);
			} catch (Exception e) {
				LoggingService.LogError ("Exception while saving file to " + path, e);
			}

			if (mdProject != null) {
				var data = GetProjectData (id.ProjectId);
				data.AddDocumentId (info.Id, path);
				var file = new MonoDevelop.Projects.ProjectFile (path);
				mdProject.Files.Add (file);
				tryApplyState_changedProjects.Add (mdProject);
			}

			this.OnDocumentAdded (info);
		}

		protected override void ApplyDocumentRemoved (DocumentId documentId)
		{
			var document = GetDocument (documentId);
			var mdProject = GetMonoProject (documentId.ProjectId);
			if (document == null || mdProject == null) {
				return;
			}

			FilePath filePath = document.FilePath;
			var projectFile = mdProject.Files.GetFile (filePath);
			if (projectFile == null) {
				return;
			}

			//force-close the old doc even if it's dirty
			var openDoc = IdeApp.Workbench.Documents.FirstOrDefault (d => d.IsFile && filePath.Equals (d.FileName));
			if (openDoc != null && openDoc.IsDirty) {
				openDoc.Save ();
				((Gui.SdiWorkspaceWindow)openDoc.Window).CloseWindow (true, true).Wait ();
			}

			//this will fire a OnDocumentRemoved event via OnFileRemoved
			mdProject.Files.Remove (projectFile);
			FileService.DeleteFile (filePath);
			tryApplyState_changedProjects.Add (mdProject);
		}

		string DetermineFilePath (DocumentId id, string name, string filePath, IReadOnlyList<string> docFolders, string defaultFolder, bool createDirectory = false)
		{
			var path = filePath;

			if (string.IsNullOrEmpty (path)) {
				var monoProject = GetMonoProject (id.ProjectId);

				// If the first namespace name matches the name of the project, then we don't want to
				// generate a folder for that.  The project is implicitly a folder with that name.
				IEnumerable<string> folders;
				if (docFolders != null && monoProject != null && docFolders.FirstOrDefault () == monoProject.Name) {
					folders = docFolders.Skip (1);
				} else {
					folders = docFolders;
				}

				if (folders.Any ()) {
					string baseDirectory = Path.Combine (monoProject?.BaseDirectory ?? monoDevelopSolution.BaseDirectory, Path.Combine (folders.ToArray ()));
					try {
						if (createDirectory && !Directory.Exists (baseDirectory))
							Directory.CreateDirectory (baseDirectory);
					} catch (Exception e) {
						LoggingService.LogError ("Error while creating directory for a new file : " + baseDirectory, e);
					}
					path = Path.Combine (baseDirectory, name);
				} else {
					path = Path.Combine (defaultFolder, name);
				}
			}
			return path;
		}
		#endregion

		internal Document GetDocument (DocumentId documentId, CancellationToken cancellationToken = default (CancellationToken))
		{
			var project = CurrentSolution.GetProject (documentId.ProjectId);
			if (project == null)
				return null;
			return project.GetDocument (documentId);
		}

		internal TextDocument GetAdditionalDocument (DocumentId documentId, CancellationToken cancellationToken = default(CancellationToken))
		{
			var project = CurrentSolution.GetProject (documentId.ProjectId);
			if (project == null)
				return null;
			return project.GetAdditionalDocument (documentId);
		}

		internal async void UpdateFileContent (string fileName, string text)
		{
			SourceText newText = SourceText.From (text);
			foreach (var kv in this.projectDataMap) {
				var projectId = kv.Key;
				var docId = this.GetDocumentId (projectId, fileName);
				if (docId != null) {
					try { 
						base.OnDocumentTextChanged (docId, newText, PreservationMode.PreserveIdentity);
					} catch (Exception e) {
						LoggingService.LogWarning ("Roslyn error on text change", e);
					}
				}
				var monoProject = GetMonoProject (projectId);
				if (monoProject != null) {
					var pf = monoProject.GetProjectFile (fileName);
					if (pf != null) {
						var mimeType = DesktopService.GetMimeTypeForUri (fileName);
						if (TypeSystemService.CanParseProjections (monoProject, mimeType, fileName))
							await TypeSystemService.ParseProjection (new ParseOptions { Project = monoProject, FileName = fileName, Content = new StringTextSource(text), BuildAction = pf.BuildAction }, mimeType).ConfigureAwait (false);
					}
				}
			}
		}

		internal void RemoveProject (MonoDevelop.Projects.Project project)
		{
			var id = GetProjectId (project); 
			if (id != null) {
				foreach (var docId in GetOpenDocumentIds (id).ToList ()) {
					ClearOpenDocument (docId);
				}
				ProjectId val;
				projectIdMap.TryRemove (project, out val);
				projectIdToMdProjectMap = projectIdToMdProjectMap.Remove (val);
				ProjectData val2;
				projectDataMap.TryRemove (id, out val2);
				MetadataReferenceCache.RemoveReferences (id);

				UnloadMonoProject (project);
			}
		}

		#region Project modification handlers

		void OnFileAdded (object sender, MonoDevelop.Projects.ProjectFileEventArgs args)
		{
			try {
				var project = (MonoDevelop.Projects.Project)sender;
				foreach (MonoDevelop.Projects.ProjectFileEventInfo fargs in args) {
					var projectFile = fargs.ProjectFile;
					if (projectFile.Subtype == MonoDevelop.Projects.Subtype.Directory)
						continue;
					var projectData = GetProjectData (GetProjectId (project));
					SourceCodeKind sck;
					if (TypeSystemParserNode.IsCompileableFile (projectFile, out sck) || CanGenerateAnalysisContextForNonCompileable (project, projectFile)) {
						if (projectData.GetDocumentId (projectFile.FilePath) != null) // may already been added by a rename event.
							return;
						var newDocument = CreateDocumentInfo (solutionData, project.Name, projectData, projectFile, sck);
						OnDocumentAdded (newDocument);
					} else {
						foreach (var projectedDocument in GenerateProjections (projectFile, projectData, project, null)) {
							OnDocumentAdded (projectedDocument);
						}
					}

				}
			} catch (Exception ex) {
				LoggingService.LogInternalError (ex);
			}
		}

		void OnFileRemoved (object sender, MonoDevelop.Projects.ProjectFileEventArgs args)
		{
			try {
				var project = (MonoDevelop.Projects.Project)sender;
				foreach (MonoDevelop.Projects.ProjectFileEventInfo fargs in args) {
					var projectId = GetProjectId (project);
					var data = GetProjectData (projectId);
					var id = data.GetDocumentId (fargs.ProjectFile.FilePath);
					if (id != null) {
						ClearDocumentData (id);
						try {
							OnDocumentRemoved (id);
						} catch (Exception e) {
							LoggingService.LogInternalError (e);
						}
						data.RemoveDocument (fargs.ProjectFile.FilePath);
					} else {
						foreach (var entry in ProjectionList) {
							if (entry.File == fargs.ProjectFile) {
								foreach (var projectedDocument in entry.Projections) {
									id = data.GetDocumentId (projectedDocument.Document.FileName);
									if (id != null) {
										ClearDocumentData (id);
										try {
											OnDocumentRemoved (id);
										} catch {
											// already removed as document
										}
										data.RemoveDocument (projectedDocument.Document.FileName);
									}
									break;
								}
							}
						}
					}
				}
			} catch (Exception ex) {
				LoggingService.LogInternalError (ex);
			}
		}

		void OnFileRenamed (object sender, MonoDevelop.Projects.ProjectFileRenamedEventArgs args)
		{
			try {
				var project = (MonoDevelop.Projects.Project)sender;
				foreach (MonoDevelop.Projects.ProjectFileRenamedEventInfo fargs in args) {
					var projectFile = fargs.ProjectFile;
					if (projectFile.Subtype == MonoDevelop.Projects.Subtype.Directory)
						continue;
					var projectId = GetProjectId (project);
					var data = GetProjectData (projectId);
					SourceCodeKind sck;
					if (TypeSystemParserNode.IsCompileableFile (projectFile, out sck) || CanGenerateAnalysisContextForNonCompileable (project, projectFile)) {
						var id = data.GetDocumentId (fargs.OldName);
						if (id != null) {
							if (this.IsDocumentOpen (id)) {
								this.InformDocumentClose (id, fargs.OldName);
							}
							OnDocumentRemoved (id);
							data.RemoveDocument (fargs.OldName);
						}
						var newDocument = CreateDocumentInfo (solutionData, project.Name, GetProjectData (projectId), projectFile, sck);
						OnDocumentAdded (newDocument);
					} else {
						foreach (var entry in ProjectionList) {
							if (entry.File == projectFile) {
								foreach (var projectedDocument in entry.Projections) {
									var id = data.GetDocumentId (projectedDocument.Document.FileName);
									if (id != null) {
										if (this.IsDocumentOpen (id)) {
											this.InformDocumentClose (id, projectedDocument.Document.FileName);
										}
										OnDocumentRemoved (id);
										data.RemoveDocument (projectedDocument.Document.FileName);
									}
								}
								break;
							}
						}

						foreach (var projectedDocument in GenerateProjections (fargs.ProjectFile, data, project, null)) {
							OnDocumentAdded (projectedDocument);
						}
					}
				}
			} catch (Exception ex) {
				LoggingService.LogInternalError (ex);
			}
		}

		List<MonoDevelop.Projects.DotNetProject> modifiedProjects = new List<MonoDevelop.Projects.DotNetProject> ();
		object projectModifyLock = new object ();
		bool freezeProjectModify;
		async void OnProjectModified (object sender, MonoDevelop.Projects.SolutionItemModifiedEventArgs args)
		{
			lock (projectModifyLock) {
				if (freezeProjectModify)
					return;
				try {
					if (!args.Any (x => x.Hint == "TargetFramework" || x.Hint == "References"))
						return;
					var project = sender as MonoDevelop.Projects.DotNetProject;
					if (project == null)
						return;
					var projectId = GetProjectId (project);
					if (CurrentSolution.ContainsProject (projectId)) {
						HandleActiveConfigurationChanged (this, EventArgs.Empty);
					} else {
						modifiedProjects.Add (project);
					}
				} catch (Exception ex) {
					LoggingService.LogInternalError (ex);
				}
			}
		}

		#endregion

		/// <summary>
		/// Tries the get original file from projection. If the fileName / offset is inside a projection this method tries to convert it 
		/// back to the original physical file.
		/// </summary>
		internal bool TryGetOriginalFileFromProjection (string fileName, int offset, out string originalName, out int originalOffset)
		{
			foreach (var projectionEntry in ProjectionList) {
				var projection = projectionEntry.Projections.FirstOrDefault (p => FilePath.PathComparer.Equals (p.Document.FileName, fileName));
				if (projection != null) {
					if (projection.TryConvertFromProjectionToOriginal (offset, out originalOffset)) {
						originalName = projectionEntry.File.FilePath;
						return true;
					}
				}
			}

			originalName = fileName;
			originalOffset = offset;
			return false;
		}

	}

	//	static class MonoDevelopWorkspaceFeatures
	//	{
	//		static FeaturePack pack;
	//
	//		public static FeaturePack Features {
	//			get {
	//				if (pack == null)
	//					Interlocked.CompareExchange (ref pack, ComputePack (), null);
	//				return pack;
	//			}
	//		}
	//
	//		static FeaturePack ComputePack ()
	//		{
	//			var assemblies = new List<Assembly> ();
	//			var workspaceCoreAssembly = typeof(Workspace).Assembly;
	//			assemblies.Add (workspaceCoreAssembly);
	//
	//			LoadAssembly (assemblies, "Microsoft.CodeAnalysis.CSharp.Workspaces");
	//			//LoadAssembly (assemblies, "Microsoft.CodeAnalysis.VisualBasic.Workspaces");
	//
	//			var catalogs = assemblies.Select (a => new System.ComponentModel.Composition.Hosting.AssemblyCatalog (a));
	//
	//			return new MefExportPack (catalogs);
	//		}
	//
	//		static void LoadAssembly (List<Assembly> assemblies, string assemblyName)
	//		{
	//			try {
	//				var loadedAssembly = Assembly.Load (assemblyName);
	//				assemblies.Add (loadedAssembly);
	//			} catch (Exception e) {
	//				LoggingService.LogWarning ("Couldn't load assembly:" + assemblyName, e);
	//			}
	//		}
	//	}

	public class RoslynProjectEventArgs : EventArgs
	{
		public ProjectId ProjectId { get; private set; }

		public RoslynProjectEventArgs (ProjectId projectId)
		{
			ProjectId = projectId;
		}
	}

}