-
Notifications
You must be signed in to change notification settings - Fork 0
/
CscompUtilities.cs
2639 lines (2219 loc) · 95.7 KB
/
CscompUtilities.cs
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
// CscompUtilities.cs
// ------------------------------------------------------------------
//
// Author: Dinoch
// built on host: DINOCH-2
// Created Mon Apr 21 08:40:47 2008
//
// Last Saved: <2011-May-12 15:19:19>
//
//
// This file defines code for an assembly containing one main class, a
// static class that exposes only static methods. The assembly is
// intended to run within Powershell, in an emacs inferior shell.
//
// Using csharp-complete.el, when the user asks for code-completion on a
// segment of code, csharp-complete will send a command in the
// powershell - which just invokes a method on this static
// class.
//
// The logic in this assembly will then perform whatever is necessary:
// reflect on the specified type, or qualify a name, and so on, and then
// return the result information to the Csharp Completion elisp logic.
//
// In broad strokes, you can think of this assembly as the thing that
// performs .NET reflection, and sends the list of potential completions
// to elisp, which presents a pop-up menu. There are a bunch of
// supplementary tasks required, in order to make the "return the list
// of potential completions" possible: for example, is the completion
// being requested on a type? A namespace? is it a static method? A
// property? and so on. All of these extra supporting functions are also
// implemented as static methods on the main Utilities class.
//
// =======================================================
//
// compile with:
// csc.exe /target:library /debug /out:CscompUtilities.dll CscompUtilities.cs
//
// ------------------------------------------------------------------
//
// Copyright (c) 2008-2011 by Dino Chiesa
// All rights reserved!
//
// ------------------------------------------------------------------
using System;
using System.IO;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using ICSharpCode.NRefactory;
using ICSharpCode.NRefactory.Ast;
// to allow fast ngen
[assembly: AssemblyTitle("CscompUtilities.cs")]
[assembly: AssemblyDescription("an assembly to be loaded into powershell, allows integration with emacs, code completion, etc.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dino Chiesa")]
[assembly: AssemblyProduct("Tools")]
[assembly: AssemblyCopyright("Copyright © Dino Chiesa 2010, 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.3.0.2")]
namespace Ionic.Cscomp
{
public static class Utilities
{
private static List<string> StarterAssemblies = new List<string>()
{
"System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
// {"System.Xml","Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" },
// {"System.Xml.Linq", "Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" },
// {"System.Data", "Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" },
};
// "Microsoft.JScript",
// "Microsoft.VisualBasic",
// "Microsoft.VisualBasic.Vsa",
// "Microsoft.VisualC",
// "Microsoft.Vsa",
// "Microsoft.Vsa.Vb.CodeDOMPRocessor",
// "System.Configuration.Install",
// "System.Data",
// "System.Design",
// "System.DirectoryServices",
// "System.Drawing",
// "System.Drawing.Design",
// "System.EnterpriseServices",
// "System.Management",
// "System.Messaging",
// "System.Runtime.Remoting",
// "System.Runtime.Serialization.Formatters.Soap",
// "System.Security",
// "System.ServiceProcess",
// "System.Web",
// "System.Web.RegularExpressions",
// "System.Web.Services",
// "System.Windows.Forms",
private static List<String> _GacAssemblies;
private static Dictionary<String,Object> _assembliesNotLoaded;
private static Dictionary<String,Assembly> _assembliesLoaded;
private static Dictionary<String,String> _assemblyForType;
private static Dictionary<String,List<String>> _typesForNamespace;
private static Dictionary<String,String> _fullNamesForShortNames;
private static List<String> _SearchPaths;
static Utilities()
{
try
{
SetBasicSearchPaths();
ReadGac(false);
LoadAssembliesAndPopulateHashes();
}
catch (System.Exception exc1)
{
System.Console.WriteLine("uncaught exception {0}", exc1);
}
}
public static string ReadGac(bool wantList)
{
if (_GacAssemblies == null)
{
var p = new System.Diagnostics.Process
{
StartInfo =
{
FileName = "gacutil.exe",
CreateNoWindow = true,
Arguments = "-l",
RedirectStandardOutput = true,
//RedirectStandardError = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
UseShellExecute = false,
}
};
p.Start();
_GacAssemblies = new List<String>();
string output = p.StandardOutput.ReadToEnd();
string[] lines = output.Split("\n".ToCharArray());
foreach (var line in lines)
{
var mcol= Regex.Matches(line,"^([^,]+), *(.+)");
foreach (Match match in mcol)
{
// var p1 = match.Groups[1].Value;
// var p2 = match.Groups[2].Value;
// System.Console.WriteLine("{0}, {1}", p1, p2);
_GacAssemblies.Add(line.Trim());
}
}
}
if (!wantList) return "t";
string atoms = String.Join("\" \"", _GacAssemblies.ToArray());
return "(list \"" + atoms + "\")";
}
// private static string ExpandEnvVarsInPath(string path)
// {
// bool done;
// do
// {
// done= true;
// Match match = Regex.Match(path,"%([^%]+)%");
// if (match.Success)
// {
// done= false;
// var envvar = match.Groups[1].Value.ToString();
// var value = System.Environment.GetEnvironmentVariable(envvar);
// path = path.Replace("%"+envvar+"%", value);
// }
// } while (!done);
// return path;
// }
private static void SetBasicSearchPaths()
{
_SearchPaths= new List<String>();
Microsoft.Win32.RegistryKey rkey=
Microsoft.Win32.Registry.LocalMachine.OpenSubKey
("SOFTWARE\\Microsoft\\.NETFramework", false);
String DotNetDir= (string) rkey.GetValue("InstallRoot");
string programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
foreach (var path in new String[] {
Path.Combine(DotNetDir,"v2.0.50727"),
Path.Combine(programFiles,"Reference Assemblies\\Microsoft\\Framework\\v3.5"),
Path.Combine(programFiles,"Reference Assemblies\\Microsoft\\Framework\\v3.0") } )
{
if (Directory.Exists(path))
{
Tracing.Trace("SetBasicSearchPaths: {0}", path);
_SearchPaths.Add(path);
}
}
}
// private static Assembly LoadRefAssembly(string fileName)
// {
// var fullPath = FindAssemblyInSearchPaths(fileName);
// if (fullPath != null)
// return Assembly.LoadFrom(fullPath) ;
// }
private static Assembly AssemblyIsLoaded(string assemblyName)
{
// exact match
if (_assembliesLoaded.Keys.Contains(assemblyName))
return _assembliesLoaded[assemblyName];
// check for short name
if (!assemblyName.Contains(","))
{
foreach (var key in _assembliesLoaded.Keys)
{
int ix = key.LastIndexOf(',');
if (ix > 0)
{
var stub = key.Substring(0, ix);
if (assemblyName == stub)
return _assembliesLoaded[key];
}
}
}
return null;
}
private static String InternalLoadOneAssembly(string assemblyName)
{
// assemblyName can be a path, or a fully-qualified name, or
// a partially qualified name. We need to map all those to
// the FQ name.
Tracing.Trace("InternalLoadOneAssembly '{0}'", assemblyName);
if (String.IsNullOrEmpty(assemblyName))
{
Tracing.Trace("InternalLoadOneAssembly: arg is null, returning null");
return null;
}
// check if already loaeded
if (AssemblyIsLoaded(assemblyName)!=null)
{
Tracing.Trace("InternalLoadOneAssembly: already loaded");
return "t";
}
// maybe not already loaded. Try to load it.
Assembly thisAssembly = null;
try
{
thisAssembly = TryLoadAssembly(assemblyName);
}
catch(Exception exc1)
{
_assembliesNotLoaded[assemblyName] = exc1;
Tracing.Trace("InternalLoadOneAssembly: exception: {0}", exc1);
return null;
}
if (thisAssembly == null)
{
_assembliesNotLoaded[assemblyName] = "Assembly was null.";
Tracing.Trace("InternalLoadOneAssembly: loaded assembly was null");
return null;
}
// ok, we now have an assembly loaded
string shortName = thisAssembly.FullName.Split(',')[0];
// check if already loaeded
if (AssemblyIsLoaded(shortName)!=null)
{
Tracing.Trace("InternalLoadOneAssembly: assembly '{0}' already loaded",
shortName);
return "t";
}
Tracing.Trace("InternalLoadOneAssembly: loading assembly '{0}'...",
thisAssembly.FullName);
_assembliesLoaded.Add(shortName, thisAssembly);
Module[] ma = thisAssembly.GetModules();
if (ma != null)
{
List<String> list;
for (int k = 0; k < ma.Length; k++)
{
try
{
if (ma[k] == null) continue;
Type[] types = ma[k].GetTypes();
if (types == null) continue;
foreach (Type t in types)
{
try
{
if (t == null) continue;
String ns = t.Namespace;
if (ns == null) ns = String.Empty;
if (_typesForNamespace.ContainsKey(ns))
list= (List<String>) _typesForNamespace[ns];
else
{
list= new List<String>();
_typesForNamespace[ns]= list;
}
// sometimes we get duplicate types
if (!list.Contains(t.FullName))
{
list.Add(t.FullName);
//_assemblyForType[t.FullName]= assemblyName;
_assemblyForType[t.FullName]= shortName;
var fixedName = FixupGenericTypeName(t.Name);
if (_fullNamesForShortNames.ContainsKey(fixedName))
{
var x = _fullNamesForShortNames[fixedName];
_fullNamesForShortNames[fixedName] =
String.Format("{0}, {1}", t.FullName, x);
}
else
_fullNamesForShortNames[fixedName] = t.FullName;
}
}
catch(ReflectionTypeLoadException)
{
//Response.Write("Problem with : " + t.FullName);
continue;
}
}
}
catch(Exception)
{
continue;
}
}
}
return shortName; // assemblyName
}
private static void LoadAssembliesAndPopulateHashes()
{
_assembliesNotLoaded = new Dictionary<String,Object>();
_assemblyForType = new Dictionary<String,String>();
_typesForNamespace = new Dictionary<String,List<String>>();
_fullNamesForShortNames = new Dictionary<String,String>();
_assembliesLoaded = new Dictionary<String,Assembly>();
foreach (var aname in StarterAssemblies)
{
InternalLoadOneAssembly(aname);
}
Alphabetize();
}
private static void Alphabetize()
{
foreach (string key in _typesForNamespace.Keys)
{
_typesForNamespace[key].Sort();
}
}
public static String GetTypeInfo(String typeName)
{
string q= null;
String[] s = null;
try
{
q= QualifyType(typeName);
s = q.Replace(")","").Replace("(","").Split(" ".ToCharArray(), 3);
return GetTypeInfo(s[1].Replace("\"",""), s[2].Replace("\"",""));
}
catch (System.Exception exc1)
{
System.Console.WriteLine("uncaught exception {0}", exc1.ToString());
System.Console.WriteLine("q= {0}", q);
System.Console.WriteLine("s.Length= {0}", s.Length);
throw ;
}
}
public static String GetTypeInfo(String typeName, String assemblyName)
{
try
{
if (_assemblyForType.Keys.Contains(typeName) &&
_assemblyForType[typeName] == assemblyName &&
_assembliesLoaded.Keys.Contains(assemblyName))
{
Assembly a2 = _assembliesLoaded[assemblyName];
Ionic.Cscomp.TypeInfo ti2= new Ionic.Cscomp.TypeInfo(a2, typeName);
return ti2.AsSexp();
}
// Load from a strongname, eg
// "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
Assembly a= Assembly.Load(assemblyName);
if ((a == null) && (System.IO.File.Exists(assemblyName)))
a= Assembly.LoadFrom(assemblyName);
if (a == null)
{
System.Console.Error.WriteLine("Cannot load that assembly");
return null;
}
Ionic.Cscomp.TypeInfo ti= new Ionic.Cscomp.TypeInfo(a, typeName);
return ti.AsSexp();
}
catch(TypeLoadException e2)
{
Console.Error.WriteLine("TypeLoadException: Could not load type: \"{0}\"\n{1}", typeName, e2);
return null;
}
catch (Exception e1)
{
Console.Error.WriteLine("Exception: type '{0}'\n{1}", typeName, e1);
return null;
}
}
private static Assembly TryLoadAssembly(String assemblyName)
{
Assembly a= null;
if (assemblyName.Contains(','))
{
// smells like a fully-qualified name
Tracing.Trace("TryLoadAssembly: loading as strong name");
a= Assembly.Load(assemblyName);
}
else if (assemblyName.EndsWith(".dll") || assemblyName.EndsWith(".exe"))
{
Tracing.Trace("TryLoadAssembly: looks like a filename");
if (System.IO.File.Exists(assemblyName))
{
Tracing.Trace("TryLoadAssembly: file exists");
a= Assembly.LoadFrom(assemblyName) ;
}
else
{
// look in search paths
var fullname = FindAssemblyInSearchPaths(assemblyName);
if (fullname != null && fullname != "nil")
{
a= Assembly.LoadFrom(fullname.Replace("\"", ""));
}
}
}
else
{
var dll = GetShortDllName(assemblyName);
var fullname = FindAssemblyInSearchPaths(dll);
if (fullname != null && fullname != "nil")
{
fullname = fullname.Replace("\"", "");
Tracing.Trace("TryLoadAssembly: LoadFrom({0})", fullname);
a= Assembly.LoadFrom(fullname);
}
}
return a; // maybe null
}
private static System.Type TryLoadType(String theTypeName, String assemblyName)
{
System.Type t= null;
Assembly a= TryLoadAssembly(assemblyName);
if (a != null)
t = a.GetType(theTypeName, false, true);
return t; // maybe null
}
public static String LoadOneAssembly (string name)
{
Tracing.Trace("LoadOneAssembly: {0}", name);
try
{
string r = InternalLoadOneAssembly(name);
if (r == null)
{
Tracing.Trace("LoadOneAssembly: null");
return "nil";
}
Alphabetize();
if (r == "t") {
Tracing.Trace("LoadOneAssembly: already loaded.");
return r;
}
var retval = "\"" + r + "\"";
// need this? Don't think so.
// Only if the return value is a path.
retval = retval.Replace("\\", "\\\\");
Tracing.Trace("returning: [{0}]", retval);
return retval;
}
catch (System.Exception exc1)
{
Tracing.Trace("uncaught exception: {0} {1}", exc1, exc1.StackTrace);
throw;
}
}
public static String ListLoadedAssemblies ()
{
string atoms = String.Join("\" \"", _assembliesLoaded.Keys.ToArray());
return "(list \"" + atoms + "\")";
}
/// <summary>
/// Gets the version of the assembly, in a string form.
/// </summary>
/// <remarks>
/// <para>
/// Returns a quoted string, suitable for use as a lisp
/// s-expression. Example: "1.2.0.4"
/// </para>
/// </remarks>
/// <returns>
/// The quoted version string
/// </returns>
public static String Version ()
{
return "\"" +
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + "\"";
}
public static String ListKnownTypes()
{
string atoms = String.Join("\" \"", _assemblyForType.Keys.ToArray());
return "(list \"" + atoms + "\")" ;
}
/// <summary>
/// Gets all the known completions in the given namespace.
/// </summary>
/// <remarks>
/// <para>
/// The completions include all the types, and all the child namespaces.
/// So, for ns "System", the completion list will include System.Delegate
/// as well as System.Diagnostics
/// </para>
/// </remarks>
/// <returns>
/// </returns>
public static String GetCompletionsForNamespace(string ns)
{
if (String.IsNullOrEmpty(ns))
{
Tracing.Trace("GetCompletionsForNamespace: null input");
return null;
}
if (!_typesForNamespace.ContainsKey(ns))
{
Tracing.Trace("GetCompletionsForNamespace: unknown ns '{0}'", ns);
return null;
}
var result= new System.Text.StringBuilder();
int len = ns.Length+1;
result.Append("(list \"").Append(ns).Append("\" (list 'types (list ");
foreach (var t in _typesForNamespace[ns])
{
var s = t.Substring(len);
//System.Console.WriteLine(" " + t.Substring(len));
//Tracing.Trace(" {0}", s);
result.Append("\"").Append(s).Append("\" ");
}
result.Append("))");
var childlist = new List<String>();
foreach (var key in _typesForNamespace.Keys)
{
if (key.StartsWith(ns) && !key.Equals(ns))
{
var child = key.Substring(len);
var p = child.IndexOf('.');
if (p > 0)
child = child.Substring(0,p);
if (!childlist.Contains(child))
childlist.Add(child);
}
}
if (childlist.Count() > 0)
{
result.Append(" (list 'namespaces (list ");
foreach (var c in childlist)
result.Append("\"").Append(c).Append("\" ");
result.Append("))");
}
result.Append(")");
return result.ToString();
}
private static string Escape(string s)
{
return s.Replace("\"", "\\\"");
}
/// <summary>
/// Qualify a name
/// </summary>
/// <returns>
/// ("type" fulltypename) if the name is a type
/// ("namespace" parentNamespace) if the name is a namespace
/// ("unknown" name) if the name is a namespace
/// </returns>
public static String QualifyName(String name)
{
Tracing.Trace("QualifyName ({0})", name);
var suffix = "." + name;
IEnumerable<String> collection;
// if (!name.Contains("."))
// {
// // no dot in the name = assume short name
// collection = _fullNamesForShortNames.Keys;
//
// // check for exact match in the keys
// foreach (var key in collection)
// {
// if (key.Equals(name))
// return String.Format("(list \"type\" \"{0}\")",
// _fullNamesForShortNames[key]);
// }
//
// return String.Format("(list \"unknown\" \"{0}\")",name);
// }
if (Verbose)
System.Console.WriteLine("checking name: {0}", name);
// look for exact match on a fully-qualified typename
collection = _fullNamesForShortNames.Values;
foreach (var value in collection)
{
foreach (var v2 in value.Split(", ".ToCharArray()))
{
if (v2.Equals(name))
return String.Format("(list \"type\" \"{0}\")", v2);
}
}
// look for ends-with match on a fully-qualified typename
foreach (var value in collection)
{
foreach (var v2 in value.Split(", ".ToCharArray()))
{
if (v2.EndsWith(suffix))
return String.Format("(list \"type\" \"{0}\")", v2);
}
}
// now check for exact match on known namespaces...
collection = _typesForNamespace.Keys;
foreach (var key in collection)
{
if (key.Equals(name))
return String.Format("(list \"namespace\" \"{0}\")", name);
}
// Match on the last segment of the namespace. Eg, if name is "Diagnostics",
// should match on "System.Diagnostics".
foreach (var key in collection)
{
if (key.EndsWith(suffix))
return String.Format("(list \"namespace\" \"{0}\")", key);
}
Tracing.Trace("checking GAC...");
// Finally, check the names of assemblies in the gac.
// If found, load the assembly.
collection = _GacAssemblies;
foreach (var strongname in collection)
{
var parts = strongname.Split(", ".ToCharArray());
if (parts!= null && parts[0].Equals(name))
{
var r = LoadOneAssembly(strongname);
if (r!=null && r != "nil")
return String.Format("(list \"namespace\" \"{0}\")", name);
}
}
return String.Format("(list \"unknown\" \"{0}\")", Escape(name));
}
/// <summary>
/// Return all possible matches on a given symbol fragment.
/// </summary>
///
/// <param name='fragment'>
/// the fragment of the name to match on.
/// </param>
///
/// <param name='namespaces'>
/// a comma-separated list of namespaces
/// </param>
///
/// <returns>
/// a list containing pairs of all possible completions.
/// eg, if completing on Ba?, maybe return:
/// (list
/// ("type" "Foo.Bar")
/// ("type" "Utils.Bands")
/// ("namespace" "Barrels")
/// )
/// </returns>
public static String GetMatches(String fragment, String namespaces)
{
if (String.IsNullOrEmpty(fragment))
return "nil";
List<String> responseSet = new List<String>();
var reTypeStub = "\\." + fragment + ".*$";
var reNamespace = "^" + fragment + ".*$";
IEnumerable<String> collection;
Tracing.Trace("checking fragment: {0}", fragment);
// look for types with short names that begin with the fragment
collection = _fullNamesForShortNames.Values;
foreach (string ns in namespaces.Split(','))
{
foreach (var value in collection)
{
foreach (var v2 in value.Split(", ".ToCharArray()))
{
Match match = Regex.Match(v2,"^"+ns+reTypeStub);
if (match.Success)
responseSet.Add(String.Format("(list \"type\" \"{0}\")", v2));
}
}
}
// look for namespaces that begin with the fragment
collection = _typesForNamespace.Keys;
foreach (var key in collection)
{
Match match = Regex.Match(key,reNamespace);
if (match.Success)
responseSet.Add(String.Format("(list \"namespace\" \"{0}\")", key));
// I think maybe we want to exclude child namespaces. . .
// maybe later.
}
if (responseSet.Count == 0)
return "nil";
string items = String.Join(" ", responseSet.ToArray());
return "(list " + items + ")";
}
public static string FixupGenericTypeName(string typeName)
{
var name = typeName;
Match match = Regex.Match(name,"(.+)`([1-9])$");
if (match.Success)
name = match.Groups[1].Value.ToString();
return name;
}
public static String QualifyType(String typeName)
{
return QualifyType(typeName, null);
}
/// <summary>
/// Qualifies the type name.
/// </summary>
/// <param name='typeName'>
/// the name of the type, possibly a short name, like "Console" or "Stream",
/// and possibly a long name like System.IO.Stream
/// </param>
/// <param name='usinglist'>
/// a list of namespaces referenced at the top of the module in using
/// statements. Favor these namespaces when doing type qualification.
/// </param>
/// <returns>
/// sexp: (list "fulltypename" "assemblyname") or nil if the type is not known
/// The assembly name
/// </returns>
public static String QualifyType(String typeName, String usinglist)
{
string stub = null;
System.Text.StringBuilder residual = null;
int repeats = 0;
Tracing.Trace("QualifyType: {0}", typeName);
// fixup generic type
var name = typeName;
Match match = Regex.Match(name,"(.+`[1-9])\\[.+\\]$");
if (match.Success)
name = match.Groups[1].Value.ToString();
name = name.Trim();
Tracing.Trace("QualifyType: name '{0}'", name);
if (!name.Contains("."))
{
Tracing.Trace("QualifyType: name contains no dot");
Tracing.Trace("QualifyType: examining {0} short names",
_fullNamesForShortNames.Keys.Count);
foreach (var key in _fullNamesForShortNames.Keys)
{
var value = _fullNamesForShortNames[key];
if (key.Equals(name))
{
string tname = null;
if (_fullNamesForShortNames[key].Contains(','))
{
var nlist = _fullNamesForShortNames[key].Split(", ".ToCharArray());
if (usinglist != null)
{
var ulist = usinglist.Split(", ".ToCharArray());
var GetNamespace = new Func<string,string>((s) =>
{
int ix = s.LastIndexOf('.') ;
if (ix <= 0)
return null;
return s.Substring(0,ix);
});
var selection = from fn in nlist
join u in ulist on GetNamespace(fn) equals u
select fn;
int c = selection.Count();
tname = (c>=1)
? selection.First()
: nlist[0];
}
else
tname = nlist[0];
}
else
{
tname = _fullNamesForShortNames[key];
}
return
String.Format("(list \"{0}\" \"{1}\")",
tname,
_assemblyForType[tname]);
}
}
}
// it may be a fully- or partially qualified type name
Tracing.Trace("QualifyType: examining {0} full names",
_fullNamesForShortNames.Values.Count);
foreach (var v1 in _fullNamesForShortNames.Values)
{
foreach (var value in v1.Split(", ".ToCharArray()))
{
if (stub == null || !value.StartsWith(stub))
{
int ix = value.LastIndexOf('.');
stub= (ix > 0)
? value.Substring(0, ix)
: value ;
repeats = 0;
if (residual!=null)
{
var r = residual.ToString();
if (!String.IsNullOrEmpty(r))
Tracing.Trace(" {0}", r);
}
residual = new System.Text.StringBuilder();
}
else
{
residual.Append(".");
repeats++;
}
// if (repeats == 0)
// Tracing.Trace(" check: {0}.*", stub);
// check for exact match
if (value.Equals(name))
{
return
String.Format("(list \"{0}\" \"{1}\")",
value,
_assemblyForType[value]);
}
}
}
return "nil";
}
public static string GetConstructors (string typeName)
{
Tracing.Trace("GetConstructors: {0}", typeName);
if (!_assemblyForType.Keys.Contains(typeName))
{
Tracing.Trace("GetConstructors: unknown assembly, found 0 constructors");
return "nil";
}
Assembly a = AssemblyIsLoaded(_assemblyForType[typeName]);
if (a==null)
{
Tracing.Trace("GetConstructors: could not load assembly, found 0 constructors");
return "nil";
}
var tinfo= new Ionic.Cscomp.TypeInfo(a, typeName);
return tinfo.GetConstructorsSexp();
}
public static string GetTypeGivenVarDecl (string csharpVarDeclaration)
{
return GetTypeGivenVarDecl(csharpVarDeclaration,
null,