/
MarkupCompiler.cs
3615 lines (3059 loc) · 151 KB
/
MarkupCompiler.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//---------------------------------------------------------------------------
//
// Description:
// Markup Compiler class that compiles the markup in a Xaml file into a
// binary stream (Baml) and\or code (IL) in an assembly.
//
//---------------------------------------------------------------------------
#pragma warning disable 1634, 1691
using System;
using System.Xml;
using System.IO;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.ComponentModel;
using System.Security.Cryptography;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using MS.Internal.Markup;
using MS.Internal.Tasks;
using MS.Utility; // for SR
using Microsoft.Build.Utilities;
using Microsoft.Build.Tasks.Windows;
using System.Runtime.CompilerServices;
namespace MS.Internal
{
internal sealed class MarkupCompiler
{
#region ExternalAPI
#region Public Properties
///<summary>String that specifies the directory to place the generated files into</summary>
public string TargetPath
{
get { return _targetPath; }
set { _targetPath = value;}
}
/// <summary>
/// The version of the assembly
/// </summary>
public string AssemblyVersion
{
get { return _assemblyVersion; }
set { _assemblyVersion = value; }
}
/// <summary>
/// The public key token of the assembly
/// </summary>
public string AssemblyPublicKeyToken
{
get { return _assemblyPublicKeyToken; }
set { _assemblyPublicKeyToken = value; }
}
///<summary>Array of loose files associated with this assembly</summary>
public string [] ContentList
{
get { return _contentList; }
set { _contentList = value; }
}
/// <summary>
/// Splash screen image to be displayed before application init
/// </summary>
public string SplashImage
{
set { _splashImage = value; }
}
///<summary> Array of local xaml page files to be compiled at pass2 </summary>
public string[] LocalXamlPages
{
get { return _localXamlPages; }
}
///<summary> Local Application xaml file to be compiled at pass2 </summary>
public string LocalXamlApplication
{
get { return _localXamlApplication; }
}
/// <summary>
/// ReferenceAssemblyList. every item is an instance of ReferenceAssembly.
/// </summary>
/// <value></value>
public ArrayList ReferenceAssemblyList
{
get { return _referenceAssemblyList; }
set { _referenceAssemblyList = value; }
}
///<summary>The language source file extension set in a project or the registered default.</summary>
public string LanguageSourceExtension
{
get { return _languageSourceExtension; }
set { _languageSourceExtension = value; }
}
///<summary>Allows to hook a custom parser during compilation.</summary>
public ParserHooks ParserHooks
{
get { return _parserHooks; }
set { _parserHooks = value; }
}
///<summary>If true code for supporting hosting in Browser is generated</summary>
public bool HostInBrowser
{
get { return _hostInBrowser; }
set { _hostInBrowser = value; }
}
///<summary>Generate Debug information in the BAML file.</summary>
public bool XamlDebuggingInformation
{
get { return _xamlDebuggingInformation; }
set { _xamlDebuggingInformation = value; }
}
/// <summary>
/// Get/Sets the TaskFileService which is used for abstracting simple
/// files services provided by CLR and the HostObject (IVsMsBuildTaskFileManager)
/// </summary>
internal ITaskFileService TaskFileService
{
get { return _taskFileService; }
set { _taskFileService = value; }
}
/// <summary>
/// The CompilerWrapper's TaskLoggingHelper for reporting compiler warnings.
/// </summary>
internal TaskLoggingHelper TaskLogger
{
set { _taskLogger = value; }
}
/// <summary>
/// Support custom IntermediateOutputPath and BaseIntermediateOutputPath outside the project path
/// </summary>
internal bool SupportCustomOutputPaths { get; set; } = false;
// If the xaml has local references, then it could have internal element & properties
// but there is no way to determine this until MCPass2. Yet, GeneratedInternalTypeHelper,
// which is the class that allows access to legitimate internals, needs to be generated
// in MCPass1. So, to determine if GeneratedInternalTypeHelper.cs needs to be kept or not,
// MCPass1 & MCPass2 task will use the HasInternals property as indicated below:
// In pass1, if this property returns true, it will be due to friend internals & so
// MCPass1 will just decide to keep the file & this property will be ignored in MCPass2
// if that task is executed as well.
// In pass1, if this property returns false, MCPass2 will look at this property again after
// the Xaml Compiler has been called to compile all the local markup files. Now if this
// property still returns false, the file will be removed, else it will be kept, because
// this property was true as the xaml compiler encountered local or friend internals
// during MCPass2.
// The above will apply only for a clean build, not incremental build.
public static bool HasInternals
{
get { return XamlTypeMapper.HasInternals; }
}
#endregion Public Properties
#region Public Events
/// <summary>
/// The Error event is fired when an error is encountered while compiling a xaml file.
/// </summary>
public event MarkupErrorEventHandler Error;
/// <summary>
/// The SourceFileResolve event is fired when it starts to compile one xaml file or handle
/// resource file. The event handler will resolve the original filepath to a new
/// SourcePath and RelativeSourceFilePath.
/// </summary>
public event SourceFileResolveEventHandler SourceFileResolve;
#endregion Public Events
#region Public Methods
///<summary>Complies list of file items comprising an Application.</summary>
public void Compile(CompilationUnit cu)
{
// KnownTypes, XamlTypeMapper, and ReflectionHelper all hold on to data statically that
// must not be reused between compilations as different compilations can target different
//
// Defensively clear static data even though the prior compilation should have done it.
// This is done to mitigate against a failed cleanup of a prior compilation from influencing
// the current compilation.
XamlTypeMapper.Clear();
KnownTypes.Clear();
ReflectionHelper.Dispose();
try
{
CompileCore(cu);
}
finally
{
// Don't rely on next compilation to reset as that would unnecessarily delay
// garbage collection of this static data that cannot be reused by the next compilation.
// Also, the ReflectionHelper must be disposed now to release file locks on assemblies.
XamlTypeMapper.Clear();
KnownTypes.Clear();
ReflectionHelper.Dispose();
}
}
private void CompileCore(CompilationUnit cu)
{
try
{
AssemblyName = cu.AssemblyName;
InitCompilerState();
DefaultNamespace = cu.DefaultNamespace;
_compilationUnitSourcePath = cu.SourcePath;
if (!IsLanguageSupported(cu.Language))
{
OnError(new Exception(SR.Get(SRID.UnknownLanguage, cu.Language)));
return;
}
if (!cu.Pass2)
{
EnsureLanguageSourceExtension();
}
if (cu.ApplicationFile.Path != null && cu.ApplicationFile.Path.Length > 0)
{
Initialize(cu.ApplicationFile);
ApplicationFile = SourceFileInfo.RelativeSourceFilePath;
if (ApplicationFile.Length > 0)
{
IsCompilingEntryPointClass = true;
_Compile(cu.ApplicationFile.Path, cu.Pass2);
IsCompilingEntryPointClass = false;
if (_pendingLocalFiles != null && _pendingLocalFiles.Count == 1)
{
Debug.Assert(!cu.Pass2);
_localXamlApplication = (string)_pendingLocalFiles[0];
_pendingLocalFiles.Clear();
}
}
}
if (cu.FileList != null)
{
for (int i = 0; i < cu.FileList.Length; i++)
{
FileUnit sourceFile = cu.FileList[i];
Initialize(sourceFile);
if (SourceFileInfo.RelativeSourceFilePath.Length > 0)
{
_Compile(sourceFile.Path, cu.Pass2);
}
}
if (_pendingLocalFiles != null && _pendingLocalFiles.Count > 0)
{
Debug.Assert(!cu.Pass2);
_localXamlPages = (string[])_pendingLocalFiles.ToArray(typeof(string));
_pendingLocalFiles.Clear();
}
}
if (!cu.Pass2 && ContentList != null && ContentList.Length > 0)
{
GenerateLooseContentAttributes();
}
Debug.Assert(!cu.Pass2 || _pendingLocalFiles == null);
Debug.Assert(_pendingLocalFiles == null || _pendingLocalFiles.Count == 0);
_pendingLocalFiles = null;
if (cu.Pass2)
{
_localAssembly = null;
_localXamlApplication = null;
_localXamlPages = null;
}
}
finally
{
if (s_hashAlgorithm != null)
{
s_hashAlgorithm.Clear();
s_hashAlgorithm = null;
}
}
}
#endregion Public Methods
#endregion ExternalAPI
#region Implementation
#region Properties
private CompilerInfo CompilerInfo
{
get { return _ci; }
set
{
_ci = value;
if (value == null)
{
_codeProvider = null;
}
}
}
private string ApplicationFile
{
get { return _applicationFile; }
set { _applicationFile = value; }
}
private string DefaultNamespace
{
get { return _defaultNamespace; }
set
{
IsValidCLRNamespace(value, true);
_defaultNamespace = value;
}
}
private bool IsCodeNeeded
{
get { return _isCodeNeeded; }
set { _isCodeNeeded = value; }
}
internal bool IsBamlNeeded
{
get { return IsCompilingEntryPointClass ? _isBamlNeeded : true; }
set { _isBamlNeeded = value; }
}
internal bool IsRootPublic
{
get { return _ccRoot != null && _ccRoot.CodeClass.TypeAttributes == TypeAttributes.Public; }
}
internal bool ProcessingRootContext
{
get { return _ccRoot == null; }
}
internal bool IsRootNameScope
{
get
{
CodeContext cc = (CodeContext)_codeContexts.Peek();
return cc.IsAllowedNameScope;
}
}
internal bool HasLocalEvent
{
get { return _hasLocalEvent; }
set { _hasLocalEvent = value; }
}
internal static bool HasLocalReference
{
get { return XamlTypeMapper.HasLocalReference; }
}
internal Assembly LocalAssembly
{
get
{
if (_localAssembly == null)
{
if (LocalAssemblyFile != null)
{
_localAssembly = ReflectionHelper.LoadAssembly(LocalAssemblyFile.AssemblyName, LocalAssemblyFile.Path);
}
}
return _localAssembly;
}
}
internal ReferenceAssembly LocalAssemblyFile
{
get { return _localAssemblyFile; }
set { _localAssemblyFile = value; }
}
internal string AssemblyName
{
get { return _assemblyName; }
set { _assemblyName = value; }
}
internal SourceFileInfo SourceFileInfo
{
get { return _sourceFileInfo; }
set { _sourceFileInfo = value; }
}
internal bool IsCompilingEntryPointClass
{
get { return _isCompilingEntryPointClass; }
set { _isCompilingEntryPointClass = value; _isBamlNeeded = !value; }
}
internal static string DefinitionNSPrefix
{
get { return _definitionNSPrefix; }
set { _definitionNSPrefix = value; }
}
internal string Language
{
get { return _language; }
}
#endregion Properties
#region CompileUnit
private void InitCompilerState()
{
_hasGeneratedInternalTypeHelper = false;
CompilerInfo = null;
InitializeReflectionHelper();
InitializeTypeMapper();
}
//
// Generate the SourceFileInfo for the source file.
// Do the appropriate initiallization work and file checking.
//
private void Initialize(FileUnit sourceFile)
{
try
{
// Keep the SourceFileInfo for the passed source file.
SourceFileInfo = OnSourceFileResolve(sourceFile);
// Process the input file
if (sourceFile.Path == null || !SourceFileInfo.IsXamlFile)
{
ThrowCompilerException(SRID.InvalidMarkupFile);
}
if (!TaskFileService.Exists(sourceFile.Path))
{
ThrowCompilerException(SRID.FileNotFound, sourceFile.Path);
}
// Prime the output directory
if (TargetPath.Length > 0)
{
// check for ending Path.DirectorySeparatorChar
if (!TargetPath.EndsWith(string.Empty + Path.DirectorySeparatorChar, StringComparison.Ordinal))
{
TargetPath += Path.DirectorySeparatorChar;
}
}
int pathEndIndex = SourceFileInfo.RelativeSourceFilePath.LastIndexOf(string.Empty + Path.DirectorySeparatorChar, StringComparison.Ordinal);
string targetPath = TargetPath + SourceFileInfo.RelativeSourceFilePath.Substring(0, pathEndIndex + 1);
// Create if not already exists
if (targetPath.Length > 0 && !Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
}
// All exceptions including NullRef & SEH need to be caught by the markupcompiler
// since it is an app and not a component.
#pragma warning suppress 6500
catch (Exception e)
{
OnError(e);
}
}
private void _Compile(string relativeSourceFile, bool pass2)
{
bool error = false;
Stream bamlStream = null;
XamlParser xamlParser = null;
try
{
DefinitionNSPrefix = DEFINITION_PREFIX;
IsCodeNeeded = false;
_ccRoot = null;
_hasLocalEvent = false;
_codeContexts = new Stack();
_parserContext = new ParserContext();
_parserContext.XamlTypeMapper = _typeMapper;
_hasEmittedEventSetterDeclaration = false;
bamlStream = new MemoryStream();
BamlRecordWriter bamlWriter = new BamlRecordWriter(bamlStream, _parserContext, true);
bamlWriter.DebugBamlStream = XamlDebuggingInformation;
xamlParser = new ParserExtension(this, _parserContext, bamlWriter, SourceFileInfo.Stream, pass2);
xamlParser.ParserHooks = ParserHooks;
try
{
xamlParser.Parse();
}
finally
{
_typeMapper.ResetMapper();
}
}
catch (XamlParseException e)
{
OnError(e);
error = true;
}
// All exceptions including NullRef & SEH need to be caught by the markupcompiler
// since it is an app and not a component.
#pragma warning suppress 6500
catch (Exception e)
{
OnError(e);
error = true;
}
finally
{
if (!error &&
xamlParser.BamlRecordWriter == null &&
IsBamlNeeded)
{
if (_pendingLocalFiles == null)
{
_pendingLocalFiles = new ArrayList(10);
}
_pendingLocalFiles.Add(relativeSourceFile);
}
if (_codeContexts != null)
{
_codeContexts.Clear();
_codeContexts = null;
}
if (SourceFileInfo != null)
{
SourceFileInfo.CloseStream();
}
if (bamlStream != null)
{
bamlStream.Close();
bamlStream = null;
}
}
}
private void GenerateSource()
{
Debug.Assert(_codeContexts.Count == 0);
CodeNamespace cnsImports = IsLanguageCSharp ? new CodeNamespace() : _ccRoot.CodeNS;
if (IsCodeNeeded)
{
cnsImports.Imports.Add(new CodeNamespaceImport("System"));
if (_usingNS != null)
{
foreach (string u in _usingNS)
{
cnsImports.Imports.Add(new CodeNamespaceImport(u));
}
}
// } end SubClass
_ccRoot.CodeNS.Types.Add(_ccRoot.CodeClass);
}
if (_usingNS != null)
{
_usingNS.Clear();
_usingNS = null;
}
if (IsCompilingEntryPointClass)
{
GenerateAppEntryPoint();
}
if (IsCodeNeeded)
{
MemoryStream codeMemStream = new MemoryStream();
// using Disposes the StreamWriter when it ends. Disposing the StreamWriter
// also closes the underlying MemoryStream. Furthermore, don't add BOM here since
// TaskFileService.WriteGeneratedCodeFileFile adds it.
using (StreamWriter codeStreamWriter = new StreamWriter(codeMemStream, new UTF8Encoding(false)))
{
CodeGeneratorOptions o = new CodeGeneratorOptions();
// } end namespace
CodeCompileUnit ccu = new CodeCompileUnit();
// Use SHA1 if compat flag is set
// generate pragma checksum data
if (s_hashAlgorithm == null)
{
s_hashAlgorithm = SHA1.Create();
s_hashGuid = s_hashSHA1Guid;
}
CodeChecksumPragma csPragma = new CodeChecksumPragma();
csPragma.FileName = ParentFolderPrefix + SourceFileInfo.RelativeSourceFilePath + XAML;
csPragma.ChecksumAlgorithmId = s_hashGuid;
csPragma.ChecksumData = TaskFileService.GetChecksum(SourceFileInfo.OriginalFilePath, s_hashGuid);
ccu.StartDirectives.Add(csPragma);
if (cnsImports != _ccRoot.CodeNS)
{
ccu.Namespaces.Add(cnsImports);
}
ccu.Namespaces.Add(_ccRoot.CodeNS);
CodeDomProvider codeProvider = EnsureCodeProvider();
if (codeProvider.Supports(GeneratorSupport.PartialTypes) && _ccRoot.SubClass.Length == 0)
{
_ccRoot.CodeClass.IsPartial = true;
}
codeProvider.GenerateCodeFromCompileUnit(ccu, codeStreamWriter, o);
codeStreamWriter.Flush();
TaskFileService.WriteGeneratedCodeFile(codeMemStream.ToArray(),
TargetPath + SourceFileInfo.RelativeSourceFilePath,
SharedStrings.GeneratedExtension, SharedStrings.IntellisenseGeneratedExtension,
LanguageSourceExtension);
}
}
// Generate the InternalTypeHelper class in a separate code file only once and on an as
// needed basis for the current assembly being built. This class provides support for
// accessing legitimate internal types and properties that are present in the same (local)
// or a friend assembly and it is generated only when any such internals are actually
// encountered in any of the xaml files in the project.
GenerateInternalTypeHelperImplementation();
}
//
// Return FileInfo for the given source file.
//
private SourceFileInfo OnSourceFileResolve(FileUnit file)
{
SourceFileInfo sourceFileInfo;
if (SourceFileResolve != null)
{
//
// If SourceFileResolve event handler is registered, the handler
// is responsible for generating the SourceFileInfo.
// This is for MSBUILD tasks.
//
SourceFileResolveEventArgs scea = new SourceFileResolveEventArgs(file);
SourceFileResolve(this, scea);
sourceFileInfo = scea.SourceFileInfo;
}
else
{
// If SourceFileResolve event handler is not registered, generate
// the default SourceFileInfo for this file.
//
sourceFileInfo = new SourceFileInfo(file);
sourceFileInfo.SourcePath = _compilationUnitSourcePath;
if (sourceFileInfo.IsXamlFile)
{
int fileExtIndex = file.Path.LastIndexOf(DOT, StringComparison.Ordinal);
sourceFileInfo.RelativeSourceFilePath = file.Path.Substring(0, fileExtIndex);
}
}
return sourceFileInfo;
}
#endregion CompileUnit
#region ErrorHandling
static void ThrowCompilerException(string id)
{
string message = SR.Get(id);
ThrowCompilerExceptionImpl(message);
}
internal static void ThrowCompilerException(string id, string value)
{
string message = SR.Get(id, value);
ThrowCompilerExceptionImpl(message);
}
internal static void ThrowCompilerException(string id, string value1, string value2)
{
string message = SR.Get(id, value1, value2);
ThrowCompilerExceptionImpl(message);
}
internal static void ThrowCompilerException(string id, string value1, string value2, string value3)
{
string message = SR.Get(id, value1, value2, value3);
ThrowCompilerExceptionImpl(message);
}
static void ThrowCompilerException(string id, string value1, string value2, string value3, string value4)
{
string message = SR.Get(id, value1, value2, value3, value4);
ThrowCompilerExceptionImpl(message);
}
static void ThrowCompilerExceptionImpl(string message)
{
Exception compilerException = new Exception(message);
throw compilerException;
}
internal void OnError(Exception e)
{
// Don't treat an AssemblyVersion parsing error as a XamlParseException.
// Throw it back to the task execution.
if(e is AssemblyVersionParseException)
{
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e).Throw();
}
if (Error != null)
{
XamlParseException xe = e as XamlParseException;
int lineNum = xe != null ? xe.LineNumber : 0;
int linePos = xe != null ? xe.LinePosition : 0;
string filename = SourceFileInfo.OriginalFilePath;
MarkupErrorEventArgs eea = new MarkupErrorEventArgs(e, lineNum, linePos, filename);
Error(this, eea);
}
}
#endregion ErrorHandling
#region Definition Namespace processing
internal void ProcessDefinitionNamespace(XamlDefTagNode xamlDefTagNode)
{
bool exitLoop = false;
XmlReader xmlReader = xamlDefTagNode.XmlReader;
string LocalName = xmlReader.LocalName;
bool isEmptyElement = xamlDefTagNode.IsEmptyElement;
bool isProcessingCodeTag = false;
do
{
XmlNodeType currNodeType = xmlReader.NodeType;
switch (currNodeType)
{
case XmlNodeType.Element:
{
if (isProcessingCodeTag)
{
ThrowCompilerException(SRID.DefnTagsCannotBeNested, DefinitionNSPrefix, LocalName, xmlReader.LocalName);
}
switch (LocalName)
{
case CODETAG:
isProcessingCodeTag = true;
if (!IsCodeNeeded)
{
ThrowCompilerException(SRID.MissingClassDefinitionForCodeTag,
_ccRoot.ElementName,
DefinitionNSPrefix,
SourceFileInfo.RelativeSourceFilePath + XAML);
}
bool moreAttributes = xmlReader.MoveToFirstAttribute();
while (moreAttributes)
{
string attributeNamespaceUri = xmlReader.LookupNamespace(xmlReader.Prefix);
if (!attributeNamespaceUri.Equals(XamlReaderHelper.DefinitionNamespaceURI) ||
!xmlReader.LocalName.Equals(XamlReaderHelper.DefinitionUid))
{
ThrowCompilerException(SRID.AttributeNotAllowedOnCodeTag,
xmlReader.Name,
DefinitionNSPrefix,
CODETAG);
}
moreAttributes = xmlReader.MoveToNextAttribute();
}
break;
default:
ThrowCompilerException(SRID.UnknownDefinitionTag, DefinitionNSPrefix, LocalName);
break;
}
// if an empty element do a Reader to
// get to the next node and then exit
if (isEmptyElement)
{
xmlReader.Read();
exitLoop = true;
}
break;
}
case XmlNodeType.EndElement:
{
xmlReader.Read();
exitLoop = true;
break;
}
case XmlNodeType.CDATA:
case XmlNodeType.Text:
{
IXmlLineInfo xmlLineInfo = xmlReader as IXmlLineInfo;
int lineNumber = 0;
if (null != xmlLineInfo)
{
lineNumber = xmlLineInfo.LineNumber;
}
if (LocalName.Equals(CODETAG))
{
AddCodeSnippet(xmlReader.Value, lineNumber);
}
else
{
ThrowCompilerException(SRID.IllegalCDataTextScoping, DefinitionNSPrefix, LocalName, (currNodeType == XmlNodeType.CDATA ? "a CDATA section" : "text content"));
}
break;
}
}
}
while (!exitLoop && xmlReader.Read());
}
#endregion Definition Namespace processing
#region Baml Hookup Functions
private CodeMemberMethod EnsureStyleConnector()
{
if (_ccRoot.StyleConnectorFn == null)
{
_ccRoot.StyleConnectorFn = new CodeMemberMethod();
_ccRoot.StyleConnectorFn.Name = CONNECT;
_ccRoot.StyleConnectorFn.Attributes = MemberAttributes.Public | MemberAttributes.Final;
_ccRoot.StyleConnectorFn.PrivateImplementationType = new CodeTypeReference(KnownTypes.Types[(int)KnownElements.IStyleConnector]);
// void IStyleConnector.Connect(int connectionId, object target) {
//
CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(int), CONNECTIONID);
CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression(typeof(object), TARGET);
_ccRoot.StyleConnectorFn.Parameters.Add(param1);
_ccRoot.StyleConnectorFn.Parameters.Add(param2);
AddDebuggerNonUserCodeAttribute(_ccRoot.StyleConnectorFn);
AddGeneratedCodeAttribute(_ccRoot.StyleConnectorFn);
AddEditorBrowsableAttribute(_ccRoot.StyleConnectorFn);
AddSuppressMessageAttribute(_ccRoot.StyleConnectorFn, "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes");
AddSuppressMessageAttribute(_ccRoot.StyleConnectorFn, "Microsoft.Performance", "CA1800:DoNotCastUnnecessarily");
AddSuppressMessageAttribute(_ccRoot.StyleConnectorFn, "Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity");
if (SwitchStatementSupported())
{
// switch (connectionId) -- Start Switch
// {
CodeSnippetStatement css = new CodeSnippetStatement(SWITCH_STATEMENT);
_ccRoot.StyleConnectorFn.Statements.Add(css);
}
}
return _ccRoot.StyleConnectorFn;
}
internal void ConnectStyleEvent(XamlClrEventNode xamlClrEventNode)
{
CodeConditionStatement ccsConnector = null;
// validate the event handler name per C# grammar for identifiers
ValidateEventHandlerName(xamlClrEventNode.EventName, xamlClrEventNode.Value);
EnsureStyleConnector();
if (!xamlClrEventNode.IsSameScope)
{
int connectionId = xamlClrEventNode.ConnectionId;
if (SwitchStatementSupported())
{
// break any previous case staements as we are starting a new connection scope.
if (_ccRoot.StyleConnectorFn.Statements.Count > 1)
{
CodeSnippetStatement cssBreak = new CodeSnippetStatement(BREAK_STATEMENT);
_ccRoot.StyleConnectorFn.Statements.Add(cssBreak);
}
// case 1:
//
CodeSnippetStatement cssCase = new CodeSnippetStatement(CASE_STATEMENT + connectionId + COLON);
_ccRoot.StyleConnectorFn.Statements.Add(cssCase);
}
else
{
// if (connectionId == 1)
//
ccsConnector = new CodeConditionStatement();
ccsConnector.Condition = new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CONNECTIONID),
CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(connectionId));
}
}
else if (!SwitchStatementSupported())
{
// if in the same scope then use the if statement that was last generated
// at the start of the scope
Debug.Assert(_ccRoot.StyleConnectorFn.Statements.Count > 0);
ccsConnector = _ccRoot.StyleConnectorFn.Statements[_ccRoot.StyleConnectorFn.Statements.Count - 1] as CodeConditionStatement;
Debug.Assert(ccsConnector != null);
}
CodeArgumentReferenceExpression careTarget = new CodeArgumentReferenceExpression(TARGET);
if (xamlClrEventNode.IsStyleSetterEvent)
{
// EventSetter declaration only once to avoid warning!
if (!_hasEmittedEventSetterDeclaration)
{
_hasEmittedEventSetterDeclaration = true;
// EventSetter eventSetter;
//
CodeVariableDeclarationStatement cvdsES = new CodeVariableDeclarationStatement(KnownTypes.Types[(int)KnownElements.EventSetter], EVENTSETTER);
_ccRoot.StyleConnectorFn.Statements.Insert(0, cvdsES);
}
// eventSetter = new EventSetter();
//
CodeExpression[] esParams = {};
CodeVariableReferenceExpression cvreES = new CodeVariableReferenceExpression(EVENTSETTER);
CodeAssignStatement casES = new CodeAssignStatement(cvreES,
new CodeObjectCreateExpression(KnownTypes.Types[(int)KnownElements.EventSetter],
esParams));