-
Notifications
You must be signed in to change notification settings - Fork 7.2k
/
AddType.cs
2900 lines (2644 loc) · 203 KB
/
AddType.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
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
#region Using directives
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Reflection;
using System.Text;
#if CORECLR
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System.IO;
using Microsoft.CodeAnalysis.Emit;
using System.Collections.Immutable;
using System.Security;
using PathType = System.IO.Path;
#else
using System.CodeDom.Compiler;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CSharp;
using System.Collections.Concurrent;
#endif
#endregion
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Languages supported for code generation
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public enum Language
{
/// <summary>
/// The C# programming language: latest version.
/// </summary>
CSharp,
#if CORECLR
/// <summary>
/// The C# programming language v6
/// </summary>
CSharpVersion6,
/// <summary>
/// The C# programming language v5
/// </summary>
CSharpVersion5,
/// <summary>
/// The C# programming language v4
/// </summary>
CSharpVersion4,
#endif
/// <summary>
/// The C# programming language v3 (for Linq, etc)
/// </summary>
CSharpVersion3,
/// <summary>
/// The C# programming language v2
/// </summary>
CSharpVersion2,
#if CORECLR
/// <summary>
/// The C# programming language v1
/// </summary>
CSharpVersion1,
#endif
/// <summary>
/// The Visual Basic programming language
/// </summary>
VisualBasic,
/// <summary>
/// The Managed JScript programming language
/// </summary>
JScript,
}
/// <summary>
/// Types supported for the OutputAssembly parameter
/// </summary>
public enum OutputAssemblyType
{
/// <summary>
/// A Dynamically linked library (DLL)
/// </summary>
Library,
/// <summary>
/// An executable application that targets the console subsystem
/// </summary>
ConsoleApplication,
/// <summary>
/// An executable application that targets the graphical subsystem
/// </summary>
WindowsApplication
}
/// <summary>
/// Compile error or warning.
/// </summary>
public class AddTypeCompilerError
{
/// <summary>
/// FileName, if compiled from paths.
/// </summary>
public string FileName { get; internal set; }
/// <summary>
/// Line number.
/// </summary>
public int Line { get; internal set; }
/// <summary>
/// Column number.
/// </summary>
public int Column { get; internal set; }
/// <summary>
/// Error number code, i.e. CS0116
/// </summary>
public string ErrorNumber { get; internal set; }
/// <summary>
/// Error message text.
/// </summary>
public string ErrorText { get; internal set; }
/// <summary>
/// true if warning. false if error.
/// </summary>
public bool IsWarning { get; internal set; }
}
/// <summary>
/// Base class that contains logic for Add-Type cmdlet based on
/// - CodeDomProvider
/// - CodeAnalysis(Roslyn)
/// </summary>
public abstract class AddTypeCommandBase : PSCmdlet
{
/// <summary>
/// The source code of this type
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "FromSource")]
public String TypeDefinition
{
get
{
return sourceCode;
}
set
{
sourceCode = value;
}
}
/// <summary>
/// The name of the type used for auto-generated types
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "FromMember")]
public String Name { get; set; }
/// <summary>
/// The source code of this method / member
/// </summary>
[Parameter(Mandatory = true, Position = 1, ParameterSetName = "FromMember")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] MemberDefinition
{
get
{
return new string[] { sourceCode };
}
set
{
sourceCode = "";
if (value != null)
{
for (int counter = 0; counter < value.Length; counter++)
{
sourceCode += value[counter] + "\n";
}
}
}
}
internal String sourceCode;
/// <summary>
/// The namespaced used for the auto-generated type
/// </summary>
[Parameter(ParameterSetName = "FromMember")]
[Alias("NS")]
[AllowNull]
public String Namespace
{
get
{
return typeNamespace;
}
set
{
typeNamespace = value;
if (typeNamespace != null)
{
typeNamespace = typeNamespace.Trim();
}
}
}
internal string typeNamespace = "Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes";
/// <summary>
/// Any using statements required by the auto-generated type
/// </summary>
[Parameter(ParameterSetName = "FromMember")]
[Alias("Using")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] UsingNamespace { get; set; } = Utils.EmptyArray<string>();
/// <summary>
/// The path to the source code or DLL to load
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "FromPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Path
{
get
{
return paths;
}
set
{
if (value == null)
{
paths = null;
return;
}
string[] pathValue = value;
List<string> resolvedPaths = new List<string>();
// Verify that the paths are resolved and valid
foreach (string path in pathValue)
{
// Try to resolve the path
ProviderInfo provider = null;
Collection<string> newPaths = SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider);
// If it didn't resolve, add the original back
// for a better error message.
if (newPaths.Count == 0)
{
resolvedPaths.Add(path);
}
else
{
resolvedPaths.AddRange(newPaths);
}
}
ProcessPaths(resolvedPaths);
}
}
/// <summary>
/// The literal path to the source code or DLL to load
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "FromLiteralPath")]
[Alias("PSPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LiteralPath
{
get
{
return paths;
}
set
{
if (value == null)
{
paths = null;
return;
}
List<string> resolvedPaths = new List<string>();
foreach (string path in value)
{
string literalPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
resolvedPaths.Add(literalPath);
}
ProcessPaths(resolvedPaths);
}
}
private void ProcessPaths(List<string> resolvedPaths)
{
// Now, get the file type. At the same time, make sure
// we aren't attempting to mix languages, as that is
// not supported by the CodeDomProvider. While it
// would be possible to partition the files into
// languages, that would be much too complex to
// describe.
string activeExtension = null;
foreach (string path in resolvedPaths)
{
string currentExtension = PathType.GetExtension(path).ToUpperInvariant();
switch (currentExtension)
{
case ".CS":
Language = Language.CSharp;
break;
case ".VB":
Language = Language.VisualBasic;
break;
case ".JS":
Language = Language.JScript;
break;
case ".DLL":
loadAssembly = true;
break;
// Throw an error if it is an unrecognized extension
default:
ErrorRecord errorRecord = new ErrorRecord(
new Exception(
StringUtil.Format(AddTypeStrings.FileExtensionNotSupported, currentExtension)),
"EXTENSION_NOT_SUPPORTED",
ErrorCategory.InvalidArgument,
currentExtension);
ThrowTerminatingError(errorRecord);
break;
}
if (activeExtension == null)
{
activeExtension = currentExtension;
}
else if (!String.Equals(activeExtension, currentExtension, StringComparison.OrdinalIgnoreCase))
{
// Throw an error if they are switching extensions
ErrorRecord errorRecord = new ErrorRecord(
new Exception(
StringUtil.Format(AddTypeStrings.MultipleExtensionsNotSupported)),
"MULTIPLE_EXTENSION_NOT_SUPPORTED",
ErrorCategory.InvalidArgument,
currentExtension);
ThrowTerminatingError(errorRecord);
}
paths = resolvedPaths.ToArray();
}
}
internal string[] paths;
/// <summary>
/// The name of the assembly to load
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "FromAssemblyName")]
[Alias("AN")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] AssemblyName
{
get
{
return assemblyNames;
}
set
{
assemblyNames = value;
loadAssembly = true;
}
}
internal String[] assemblyNames;
internal bool loadAssembly = false;
/// <summary>
/// The language used to generate source code
/// </summary>
[Parameter(ParameterSetName = "FromSource")]
[Parameter(ParameterSetName = "FromMember")]
public Language Language
{
get
{
return language;
}
set
{
language = value;
languageSpecified = true;
PostSetLanguage(language);
}
}
/// <summary>
/// Post-action for Language setter.
/// </summary>
/// <param name="language"></param>
internal virtual void PostSetLanguage(Language language)
{
}
internal bool languageSpecified = false;
internal Language language = Language.CSharp;
/// <summary>
/// Any reference DLLs to use in the compilation
/// </summary>
[Parameter(ParameterSetName = "FromSource")]
[Parameter(ParameterSetName = "FromMember")]
[Parameter(ParameterSetName = "FromPath")]
[Parameter(ParameterSetName = "FromLiteralPath")]
[Alias("RA")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ReferencedAssemblies
{
get { return referencedAssemblies; }
set
{
if (value != null) { referencedAssemblies = value; }
}
}
internal string[] referencedAssemblies = Utils.EmptyArray<string>();
/// <summary>
/// The path to the output assembly
/// </summary>
[Parameter(ParameterSetName = "FromSource")]
[Parameter(ParameterSetName = "FromMember")]
[Parameter(ParameterSetName = "FromPath")]
[Parameter(ParameterSetName = "FromLiteralPath")]
[Alias("OA")]
public string OutputAssembly
{
get
{
return outputAssembly;
}
set
{
outputAssembly = value;
if (outputAssembly != null)
{
outputAssembly = outputAssembly.Trim();
// Try to resolve the path
ProviderInfo provider = null;
Collection<string> newPaths = new Collection<string>();
try
{
newPaths = SessionState.Path.GetResolvedProviderPathFromPSPath(outputAssembly, out provider);
}
// Ignore the ItemNotFound -- we handle it.
catch (ItemNotFoundException) { }
ErrorRecord errorRecord = new ErrorRecord(
new Exception(
StringUtil.Format(AddTypeStrings.OutputAssemblyDidNotResolve, outputAssembly)),
"INVALID_OUTPUT_ASSEMBLY",
ErrorCategory.InvalidArgument,
outputAssembly);
// If it resolved to a non-standard provider,
// generate an error.
if (!String.Equals("FileSystem", provider.Name, StringComparison.OrdinalIgnoreCase))
{
ThrowTerminatingError(errorRecord);
return;
}
// If it resolved to more than one path,
// generate an error.
if (newPaths.Count > 1)
{
ThrowTerminatingError(errorRecord);
return;
}
// It didn't resolve to any files. They may
// want to create the file.
else if (newPaths.Count == 0)
{
// We can't create one with wildcard characters
if (WildcardPattern.ContainsWildcardCharacters(outputAssembly))
{
ThrowTerminatingError(errorRecord);
}
// Create the file
else
{
outputAssembly = SessionState.Path.GetUnresolvedProviderPathFromPSPath(outputAssembly);
}
}
// It resolved to a single file
else
{
outputAssembly = newPaths[0];
}
}
}
}
internal string outputAssembly = null;
/// <summary>
/// The output type of the assembly
/// </summary>
[Parameter(ParameterSetName = "FromSource")]
[Parameter(ParameterSetName = "FromMember")]
[Parameter(ParameterSetName = "FromPath")]
[Parameter(ParameterSetName = "FromLiteralPath")]
[Alias("OT")]
public OutputAssemblyType OutputType
{
get
{
return outputType;
}
set
{
outputTypeSpecified = true;
outputType = value;
}
}
internal OutputAssemblyType outputType = OutputAssemblyType.Library;
internal bool outputTypeSpecified = false;
/// <summary>
/// Flag to pass the resulting types along
/// </summary>
[Parameter()]
public SwitchParameter PassThru
{
get
{
return passThru;
}
set
{
passThru = value;
}
}
internal SwitchParameter passThru;
/// <summary>
/// Flag to ignore warnings during compilation
/// </summary>
[Parameter()]
public SwitchParameter IgnoreWarnings
{
get
{
return ignoreWarnings;
}
set
{
ignoreWarnings = value;
ignoreWarningsSpecified = true;
}
}
internal bool ignoreWarningsSpecified;
internal SwitchParameter ignoreWarnings;
internal string GenerateTypeSource(string typeNamespace, string name, string sourceCode, Language language)
{
string usingSource = String.Format(
CultureInfo.CurrentCulture,
GetUsingTemplate(language), GetUsingSet(language));
string typeSource = String.Format(
CultureInfo.CurrentCulture,
GetMethodTemplate(language), Name, sourceCode);
if (!String.IsNullOrEmpty(typeNamespace))
{
return usingSource + String.Format(
CultureInfo.CurrentCulture,
GetNamespaceTemplate(language), typeNamespace, typeSource);
}
else
{
return usingSource + typeSource;
}
}
internal bool IsCSharp(Language language)
{
switch (language)
{
case Language.CSharp:
case Language.CSharpVersion2:
case Language.CSharpVersion3:
#if CORECLR
case Language.CSharpVersion1:
case Language.CSharpVersion4:
case Language.CSharpVersion5:
case Language.CSharpVersion6:
#endif
return true;
default:
return false;
}
}
// Get the -FromMember template for a given language
internal string GetMethodTemplate(Language language)
{
if (IsCSharp(language))
{
return
" public class {0}\n" +
" {{\n" +
" {1}\n" +
" }}\n";
}
switch (language)
{
case Language.VisualBasic:
return
" public Class {0}\n" +
" \n" +
" {1}\n" +
" \n" +
" End Class\n";
case Language.JScript:
return
" public class {0}\n" +
" {{\n" +
" {1}\n" +
" }}\n";
}
return null;
}
// Get the -FromMember namespace template for a given language
internal string GetNamespaceTemplate(Language language)
{
if (IsCSharp(language))
{
return
"namespace {0}\n" +
"{{\n" +
"{1}\n" +
"}}\n";
}
switch (language)
{
case Language.VisualBasic:
return
"Namespace {0}\n" +
"\n" +
"{1}\n" +
"End Namespace\n";
case Language.JScript:
return
"package {0}\n" +
"{{\n" +
"{1}\n" +
"}}\n";
}
return null;
}
// Get the -FromMember namespace template for a given language
internal string GetUsingTemplate(Language language)
{
if (IsCSharp(language))
{
return
"using System;\n" +
"using System.Runtime.InteropServices;\n" +
"{0}" +
"\n";
}
switch (language)
{
case Language.VisualBasic:
return
"Imports System\n" +
"Imports System.Runtime.InteropServices\n" +
"{0}" +
"\n";
case Language.JScript:
return
"import System;\n" +
"import System.Runtime.InteropServices;\n" +
"{0}" +
"\n";
}
return null;
}
// Generate the code for the using statements
internal string GetUsingSet(Language language)
{
StringBuilder usingNamespaceSet = new StringBuilder();
if (IsCSharp(language))
{
foreach (string namespaceValue in UsingNamespace)
{
usingNamespaceSet.Append("using " + namespaceValue + ";\n");
}
}
else
{
switch (language)
{
case Language.VisualBasic:
foreach (string namespaceValue in UsingNamespace)
{
usingNamespaceSet.Append("Imports " + namespaceValue + "\n");
}
break;
case Language.JScript:
foreach (string namespaceValue in UsingNamespace)
{
usingNamespaceSet.Append("import " + namespaceValue + ";\n");
}
break;
}
}
return usingNamespaceSet.ToString();
}
/// <summary>
/// Perform common error checks.
/// Populate source code.
/// </summary>
protected override void EndProcessing()
{
// Generate an error if they've specified an output
// assembly type without an output assembly
if (String.IsNullOrEmpty(outputAssembly) && outputTypeSpecified)
{
ErrorRecord errorRecord = new ErrorRecord(
new Exception(
String.Format(
CultureInfo.CurrentCulture,
AddTypeStrings.OutputTypeRequiresOutputAssembly)),
"OUTPUTTYPE_REQUIRES_ASSEMBLY",
ErrorCategory.InvalidArgument,
outputType);
ThrowTerminatingError(errorRecord);
return;
}
PopulateSource();
}
internal void PopulateSource()
{
// Prevent code compilation in ConstrainedLanguage mode
if (SessionState.LanguageMode == PSLanguageMode.ConstrainedLanguage)
{
ThrowTerminatingError(
new ErrorRecord(
new PSNotSupportedException(AddTypeStrings.CannotDefineNewType), "CannotDefineNewType", ErrorCategory.PermissionDenied, null));
}
// Load the source if they want to load from a file
if (String.Equals(ParameterSetName, "FromPath", StringComparison.OrdinalIgnoreCase) ||
String.Equals(ParameterSetName, "FromLiteralPath", StringComparison.OrdinalIgnoreCase)
)
{
sourceCode = "";
foreach (string file in paths)
{
sourceCode += System.IO.File.ReadAllText(file) + "\n";
}
}
if (String.Equals(ParameterSetName, "FromMember", StringComparison.OrdinalIgnoreCase))
{
sourceCode = GenerateTypeSource(typeNamespace, Name, sourceCode, language);
}
}
internal void HandleCompilerErrors(AddTypeCompilerError[] compilerErrors)
{
// Get the source code that corresponds to their type in the case of errors
string[] actualSource = Utils.EmptyArray<string>();
// Get the source code that corresponds to the
// error if we generated it
if ((compilerErrors.Length > 0) &&
(!String.Equals(ParameterSetName, "FromPath", StringComparison.OrdinalIgnoreCase)) &&
(!String.Equals(ParameterSetName, "FromLiteralPath", StringComparison.OrdinalIgnoreCase))
)
{
actualSource = sourceCode.Split(Utils.Separators.Newline);
}
// Write any errors to the pipeline
foreach (var error in compilerErrors)
{
OutputError(error, actualSource);
}
if (compilerErrors.Any(e => !e.IsWarning))
{
ErrorRecord errorRecord = new ErrorRecord(
new InvalidOperationException(AddTypeStrings.CompilerErrors),
"COMPILER_ERRORS",
ErrorCategory.InvalidData,
null);
ThrowTerminatingError(errorRecord);
}
}
private void OutputError(AddTypeCompilerError error, string[] actualSource)
{
// Get the actual line of the file if they
// used the -FromPath parameter set
if (String.Equals(ParameterSetName, "FromPath", StringComparison.OrdinalIgnoreCase) ||
String.Equals(ParameterSetName, "FromLiteralPath", StringComparison.OrdinalIgnoreCase)
)
{
if (!String.IsNullOrEmpty(error.FileName))
{
actualSource = System.IO.File.ReadAllText(error.FileName).Split(Utils.Separators.Newline);
}
}
string errorText = StringUtil.Format(AddTypeStrings.CompilationErrorFormat,
error.FileName, error.Line, error.ErrorText) + "\n";
for (int lineNumber = error.Line - 1; lineNumber < error.Line + 2; lineNumber++)
{
if (lineNumber > 0)
{
if (lineNumber > actualSource.Length)
break;
string lineText = "";
if (lineNumber == error.Line)
{
lineText += ">>> ";
}
lineText += actualSource[lineNumber - 1];
errorText += "\n" + StringUtil.Format(AddTypeStrings.CompilationErrorFormat,
error.FileName, lineNumber, lineText) + "\n";
}
}
if (error.IsWarning)
{
WriteWarning(errorText);
}
else
{
ErrorRecord errorRecord = new ErrorRecord(
new Exception(errorText),
"SOURCE_CODE_ERROR",
ErrorCategory.InvalidData,
error);
WriteError(errorRecord);
}
}
}
#if CORECLR
/// <summary>
/// Adds a new type to the Application Domain.
/// This version is based on CodeAnalysis (Roslyn).
/// </summary>
[Cmdlet(VerbsCommon.Add, "Type", DefaultParameterSetName = "FromSource", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135195")]
[OutputType(typeof(Type))]
public sealed class AddTypeCommand : AddTypeCommandBase
{
private static Dictionary<string, int> s_sourceCache = new Dictionary<string, int>();
/// <summary>
/// Generate the type(s)
/// </summary>
protected override void EndProcessing()
{
base.EndProcessing();
if (loadAssembly)
{
if (String.Equals(ParameterSetName, "FromPath", StringComparison.OrdinalIgnoreCase) ||
String.Equals(ParameterSetName, "FromLiteralPath", StringComparison.OrdinalIgnoreCase))
{
LoadAssemblies(this.paths);
}
if (String.Equals(ParameterSetName, "FromAssemblyName", StringComparison.OrdinalIgnoreCase))
{
LoadAssemblies(this.assemblyNames);
}
}
else
{
// Load the source if they want to load from a file
if (String.Equals(ParameterSetName, "FromPath", StringComparison.OrdinalIgnoreCase) ||
String.Equals(ParameterSetName, "FromLiteralPath", StringComparison.OrdinalIgnoreCase))
{
this.sourceCode = "";
foreach (string file in paths)
{
this.sourceCode += System.IO.File.ReadAllText(file) + "\n";
}
}
CompileSourceToAssembly(this.sourceCode);
}
}
private void LoadAssemblies(IEnumerable<string> assemblies)
{
foreach (string assemblyName in assemblies)
{
// CoreCLR doesn't allow re-load TPA assemblies with different API (i.e. we load them by name and now want to load by path).
// LoadAssemblyHelper helps us avoid re-loading them, if they already loaded.
Assembly assembly = LoadAssemblyHelper(assemblyName);
if (assembly == null)
{
assembly = LoadFrom(ResolveAssemblyName(assemblyName, false));
}
if (passThru)
{
WriteTypes(assembly);
}
}
}
private OutputKind OutputAssemblyTypeToOutputKind(OutputAssemblyType outputType)
{
switch (outputType)
{
case OutputAssemblyType.Library:
return OutputKind.DynamicallyLinkedLibrary;
case OutputAssemblyType.ConsoleApplication:
return OutputKind.ConsoleApplication;
case OutputAssemblyType.WindowsApplication:
return OutputKind.WindowsApplication;
default:
throw new ArgumentOutOfRangeException("outputType");
}
}
private void CheckTypesForDuplicates(Assembly assembly)
{
foreach (var type in assembly.GetTypes())
{
if (s_sourceCache.ContainsKey(type.FullName))
{
if (s_sourceCache[type.FullName] != sourceCode.GetHashCode())
{
ErrorRecord errorRecord = new ErrorRecord(