2 // Microsoft.VisualBasic.VBCodeGenerator.cs
5 // Andreas Nahr (ClassDevelopment@A-SoftTech.com)
6 // (partially based on CSharpCodeGenerator)
7 // Jochen Wezel (jwezel@compumaster.de)
8 // Frederik Carlier (frederik.carlier@carlier-online.be)
9 // Rolf Bjarne Kvinge (RKvinge@novell.com)
11 // (C) 2003 Andreas Nahr
12 // (C) 2003 Jochen Wezel (http://www.compumaster.de)
15 // 2003-11-06 JW: some corrections regarding missing spaces in generated code (e. g. "Property ")
16 // 2003-11-06 JW: QuoteSnippetString implemented
17 // 2003-11-08 JW: automatically add Microsoft.VisualBasic
18 // 2003-11-12 JW: some corrections to allow correct compilation
19 // 2003-11-28 JW: implementing code differences into current build of this file
20 // 2003-12-10 JW: added "String." for the ChrW method because mbas doesn't support it without the String currently / TODO: remove it ASAP!
21 // 2007-04-13 FC: Added support for the IdentityInequality operator when comparing against Nothing
24 // Permission is hereby granted, free of charge, to any person obtaining
25 // a copy of this software and associated documentation files (the
26 // "Software"), to deal in the Software without restriction, including
27 // without limitation the rights to use, copy, modify, merge, publish,
28 // distribute, sublicense, and/or sell copies of the Software, and to
29 // permit persons to whom the Software is furnished to do so, subject to
30 // the following conditions:
32 // The above copyright notice and this permission notice shall be
33 // included in all copies or substantial portions of the Software.
35 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
36 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
37 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
38 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
39 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
40 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
41 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
46 using System.Globalization;
48 using System.Text.RegularExpressions;
50 using System.CodeDom.Compiler;
52 using System.Reflection;
53 using System.Collections;
55 namespace Microsoft.VisualBasic
57 internal class VBCodeGenerator : CodeGenerator
59 private string [] Keywords = new string [] {
60 "AddHandler", "AddressOf", "Alias", "And",
61 "AndAlso", "Ansi", "As", "Assembly",
62 "Auto", "Boolean", "ByRef", "Byte",
63 "ByVal", "Call", "Case", "Catch",
64 "CBool", "CByte", "CChar", "CDate",
65 "CDec", "CDbl", "Char", "CInt",
66 "Class", "CLng", "CObj", "Const",
67 "CShort", "CSng", "CStr", "CType",
68 "Date", "Decimal", "Declare", "Default",
69 "Delegate", "Dim", "DirectCast", "Do",
70 "Double", "Each", "Else", "ElseIf",
71 "End", "Enum", "Erase", "Error",
72 "Event", "Exit", "False", "Finally",
73 "For", "Friend", "Function", "Get",
74 "GetType", "Global", "GoSub", "GoTo", "Handles",
75 "If", "Implements", "Imports", "In",
76 "Inherits", "Integer", "Interface", "Is",
77 "Let", "Lib", "Like", "Long",
78 "Loop", "Me", "Mod", "Module",
79 "MustInherit", "MustOverride", "MyBase", "MyClass",
80 "Namespace", "New", "Next", "Not",
81 "Nothing", "NotInheritable", "NotOverridable", "Object",
82 "On", "Option", "Optional", "Or",
83 "OrElse", "Overloads", "Overridable", "Overrides",
84 "ParamArray", "Partial", "Preserve", "Private", "Property",
85 "Protected", "Public", "RaiseEvent", "ReadOnly",
86 "ReDim", "REM", "RemoveHandler", "Resume",
87 "Return", "Select", "Set", "Shadows",
88 "Shared", "Short", "Single", "Static",
89 "Step", "Stop", "String", "Structure",
90 "Sub", "SyncLock", "Then", "Throw",
91 "To", "True", "Try", "TypeOf",
92 "Unicode", "Until", "Variant", "When",
93 "While", "With", "WithEvents", "WriteOnly",
96 public VBCodeGenerator()
100 protected override string NullToken {
106 protected override void ContinueOnNewLine (string st)
109 Output.WriteLine (" _");
112 protected override void GenerateBinaryOperatorExpression (CodeBinaryOperatorExpression e)
114 // We need to special case for comparisons against null;
115 // in Visual Basic the "Not (Expr) Is Nothing" construct is used
117 bool null_comparison = false;
118 bool reverse = false;
119 if (e.Operator == CodeBinaryOperatorType.IdentityInequality) {
120 CodePrimitiveExpression nothing;
121 nothing = e.Left as CodePrimitiveExpression;
122 if (nothing == null) {
123 nothing = e.Right as CodePrimitiveExpression;
127 null_comparison = nothing != null && nothing.Value == null;
130 if (null_comparison) {
131 TextWriter output = Output;
133 output.Write ("(Not (");
134 GenerateExpression (reverse ? e.Right : e.Left);
135 output.Write (") Is ");
136 GenerateExpression (reverse ? e.Left : e.Right);
139 base.GenerateBinaryOperatorExpression (e);
143 protected override void GenerateArrayCreateExpression (CodeArrayCreateExpression expression)
145 TextWriter output = Output;
147 output.Write ("New ");
149 CodeExpressionCollection initializers = expression.Initializers;
150 CodeTypeReference createType = expression.CreateType;
152 if (initializers.Count > 0) {
154 OutputType (createType);
156 output.Write ("() {");
158 OutputExpressionList (initializers);
162 CodeTypeReference arrayType = createType.ArrayElementType;
163 while (arrayType != null) {
164 createType = arrayType;
165 arrayType = arrayType.ArrayElementType;
168 OutputType (createType);
172 CodeExpression size = expression.SizeExpression;
174 GenerateExpression (size);
176 output.Write (expression.Size);
178 output.Write (") - 1) {}");
182 protected override void GenerateBaseReferenceExpression (CodeBaseReferenceExpression expression)
184 Output.Write ("MyBase");
187 protected override void GenerateCastExpression (CodeCastExpression expression)
189 TextWriter output = Output;
190 // ENHANCE: Use a DirectCast if it is known that expression.Expression is no Value-Type
191 output.Write ("CType(");
192 GenerateExpression (expression.Expression);
194 OutputType (expression.TargetType);
198 private bool AsBool (object datavalue)
200 return datavalue != null && datavalue is bool && (bool) datavalue;
203 private string OnOff (bool datavalue)
205 return datavalue ? "On" : "Off";
208 protected override void GenerateCompileUnitStart (CodeCompileUnit compileUnit)
210 GenerateComment (new CodeComment ("------------------------------------------------------------------------------"));
211 GenerateComment (new CodeComment (" <autogenerated>"));
212 GenerateComment (new CodeComment (" This code was generated by a tool."));
213 GenerateComment (new CodeComment (" Mono Runtime Version: " + System.Environment.Version));
214 GenerateComment (new CodeComment (""));
215 GenerateComment (new CodeComment (" Changes to this file may cause incorrect behavior and will be lost if "));
216 GenerateComment (new CodeComment (" the code is regenerated."));
217 GenerateComment (new CodeComment (" </autogenerated>"));
218 GenerateComment (new CodeComment ("------------------------------------------------------------------------------"));
220 if (AsBool (compileUnit.UserData ["AllowLateBound"])) {
221 Output.WriteLine("Option Explicit {0}", OnOff (AsBool (compileUnit.UserData ["RequireVariableDeclaration"])));
222 Output.WriteLine("Option Strict Off");
224 Output.WriteLine("Option Explicit On"); // Strict On implies Explicit On
225 Output.WriteLine("Option Strict On");
230 protected override void GenerateCompileUnit (CodeCompileUnit compileUnit)
232 GenerateCompileUnitStart (compileUnit);
234 OutputAttributes (compileUnit.AssemblyCustomAttributes,
235 "Assembly: ", LineHandling.NewLine);
237 GenerateNamespaces (compileUnit);
239 GenerateCompileUnitEnd (compileUnit);
242 protected override void GenerateDelegateCreateExpression (CodeDelegateCreateExpression expression)
244 TextWriter output = Output;
246 output.Write ("AddressOf ");
248 CodeExpression targetObject = expression.TargetObject;
249 if (targetObject != null) {
250 GenerateExpression (targetObject);
253 output.Write (expression.MethodName);
256 protected override void GenerateFieldReferenceExpression (CodeFieldReferenceExpression expression)
258 CodeExpression targetObject = expression.TargetObject;
259 if (targetObject != null) {
260 GenerateExpression (targetObject);
263 Output.Write (CreateEscapedIdentifier (expression.FieldName));
266 protected override void GenerateArgumentReferenceExpression (CodeArgumentReferenceExpression expression)
268 Output.Write (CreateEscapedIdentifier (expression.ParameterName));
271 protected override void GenerateVariableReferenceExpression (CodeVariableReferenceExpression expression)
273 Output.Write (CreateEscapedIdentifier (expression.VariableName));
276 protected override void GenerateIndexerExpression (CodeIndexerExpression expression)
278 TextWriter output = Output;
280 GenerateExpression (expression.TargetObject);
282 OutputExpressionList (expression.Indices);
286 protected override void GenerateArrayIndexerExpression (CodeArrayIndexerExpression expression)
288 TextWriter output = Output;
290 GenerateExpression (expression.TargetObject);
292 OutputExpressionList (expression.Indices);
296 protected override void GenerateSnippetExpression (CodeSnippetExpression expression)
298 Output.Write (expression.Value);
301 protected override void GenerateMethodInvokeExpression (CodeMethodInvokeExpression expression)
303 TextWriter output = Output;
305 GenerateMethodReferenceExpression (expression.Method);
308 OutputExpressionList (expression.Parameters);
312 protected override void GenerateMethodReferenceExpression (CodeMethodReferenceExpression expression)
314 if (expression.TargetObject != null) {
315 GenerateExpression (expression.TargetObject);
318 Output.Write (CreateEscapedIdentifier (expression.MethodName));
321 protected override void GenerateEventReferenceExpression (CodeEventReferenceExpression expression)
323 if (expression.TargetObject != null) {
324 GenerateExpression (expression.TargetObject);
326 if (expression.TargetObject is CodeThisReferenceExpression) {
327 // We're actually creating a reference to a compiler-generated field here...
328 Output.Write (expression.EventName + "Event");
330 Output.Write (CreateEscapedIdentifier (expression.EventName));
333 Output.Write (CreateEscapedIdentifier (expression.EventName + "Event"));
337 protected override void GenerateDelegateInvokeExpression (CodeDelegateInvokeExpression expression)
339 CodeEventReferenceExpression ev = expression.TargetObject as CodeEventReferenceExpression;
342 Output.Write ("RaiseEvent ");
343 if (ev.TargetObject != null && !(ev.TargetObject is CodeThisReferenceExpression)) {
344 GenerateExpression (ev.TargetObject);
347 Output.Write (ev.EventName);
348 } else if (expression.TargetObject != null) {
349 GenerateExpression (expression.TargetObject);
352 OutputExpressionList (expression.Parameters);
356 protected override void GenerateObjectCreateExpression (CodeObjectCreateExpression expression)
358 Output.Write( "New " );
359 OutputType (expression.CreateType);
361 OutputExpressionList (expression.Parameters);
365 protected override void GenerateParameterDeclarationExpression (CodeParameterDeclarationExpression e)
367 OutputAttributes (e.CustomAttributes, null, LineHandling.InLine);
368 OutputDirection (e.Direction);
369 OutputTypeNamePair (e.Type, e.Name);
372 protected override void GeneratePrimitiveExpression (CodePrimitiveExpression e)
374 if (e.Value is char) {
375 char c = (char) e.Value;
377 Output.Write("Global.Microsoft.VisualBasic.ChrW(" + ch.ToString(CultureInfo.InvariantCulture) + ")");
378 } else if (e.Value is ushort) {
379 ushort uc = (ushort) e.Value;
380 Output.Write (uc.ToString(CultureInfo.InvariantCulture));
382 } else if (e.Value is uint) {
383 uint ui = (uint) e.Value;
384 Output.Write (ui.ToString(CultureInfo.InvariantCulture));
386 } else if (e.Value is ulong) {
387 ulong ul = (ulong) e.Value;
388 Output.Write (ul.ToString(CultureInfo.InvariantCulture));
390 } else if (e.Value is sbyte) {
391 sbyte sb = (sbyte) e.Value;
392 Output.Write ("CSByte(");
393 Output.Write (sb.ToString(CultureInfo.InvariantCulture));
396 base.GeneratePrimitiveExpression(e);
400 protected override void GenerateSingleFloatValue (float s)
402 base.GenerateSingleFloatValue (s);
403 base.Output.Write ('!');
406 protected override void GeneratePropertyReferenceExpression (CodePropertyReferenceExpression expression)
408 if (expression.TargetObject != null) {
409 GenerateMemberReferenceExpression (expression.TargetObject, expression.PropertyName);
411 Output.Write (CreateEscapedIdentifier (expression.PropertyName));
415 protected override void GeneratePropertySetValueReferenceExpression (CodePropertySetValueReferenceExpression expression)
417 Output.Write ("Value");
420 protected override void GenerateThisReferenceExpression (CodeThisReferenceExpression expression)
425 protected override void GenerateExpressionStatement (CodeExpressionStatement statement)
427 GenerateExpression (statement.Expression);
428 Output.WriteLine (); //start new line
431 protected override void GenerateIterationStatement (CodeIterationStatement statement)
433 TextWriter output = Output;
435 GenerateStatement (statement.InitStatement);
436 output.Write ("Do While ");
437 GenerateExpression (statement.TestExpression);
440 GenerateStatements (statement.Statements);
441 GenerateStatement (statement.IncrementStatement);
443 output.WriteLine ("Loop");
446 protected override void GenerateThrowExceptionStatement (CodeThrowExceptionStatement statement)
448 Output.Write ("Throw");
449 if (statement.ToThrow != null) {
451 GenerateExpression (statement.ToThrow);
456 protected override void GenerateComment (CodeComment comment)
458 TextWriter output = Output;
459 string commentChars = null;
461 if (comment.DocComment) {
462 commentChars = "'''";
467 output.Write (commentChars);
468 string text = comment.Text;
470 for (int i = 0; i < text.Length; i++) {
471 output.Write (text [i]);
472 if (text[i] == '\r') {
473 if (i < (text.Length - 1) && text [i + 1] == '\n') {
476 output.Write (commentChars);
477 } else if (text [i] == '\n') {
478 output.Write (commentChars);
485 protected override void GenerateMethodReturnStatement (CodeMethodReturnStatement statement)
487 TextWriter output = Output;
489 if (statement.Expression != null) {
490 output.Write ("Return ");
491 GenerateExpression (statement.Expression);
494 output.WriteLine ("Return");
498 protected override void GenerateConditionStatement (CodeConditionStatement statement)
500 TextWriter output = Output;
501 output.Write ("If ");
503 GenerateExpression (statement.Condition);
505 output.WriteLine (" Then");
507 GenerateStatements (statement.TrueStatements);
510 CodeStatementCollection falses = statement.FalseStatements;
511 if (falses.Count > 0) {
512 output.WriteLine ("Else");
514 GenerateStatements (falses);
518 if (Options.ElseOnClosing)
519 output.WriteLine ("Else");
521 output.WriteLine ("End If");
524 protected override void GenerateTryCatchFinallyStatement (CodeTryCatchFinallyStatement statement)
526 TextWriter output = Output;
528 output.WriteLine ("Try ");
530 GenerateStatements (statement.TryStatements);
533 foreach (CodeCatchClause clause in statement.CatchClauses) {
534 output.Write ("Catch ");
535 OutputTypeNamePair (clause.CatchExceptionType, clause.LocalName);
538 GenerateStatements (clause.Statements);
542 CodeStatementCollection finallies = statement.FinallyStatements;
543 if (finallies.Count > 0) {
544 output.WriteLine ("Finally");
546 GenerateStatements (finallies);
550 output.WriteLine("End Try");
553 protected override void GenerateAssignStatement (CodeAssignStatement statement)
555 TextWriter output = Output;
556 GenerateExpression (statement.Left);
557 output.Write (" = ");
558 GenerateExpression (statement.Right);
562 protected override void GenerateAttachEventStatement (CodeAttachEventStatement statement)
564 TextWriter output = Output;
566 Output.Write ("AddHandler ");
567 if (statement.Event.TargetObject != null) {
568 GenerateEventReferenceExpression (statement.Event);
570 Output.Write (CreateEscapedIdentifier (statement.Event.EventName));
572 Output.Write ( ", ");
573 GenerateExpression (statement.Listener);
577 protected override void GenerateRemoveEventStatement (CodeRemoveEventStatement statement)
579 TextWriter output = Output;
581 Output.Write ("RemoveHandler ");
582 if (statement.Event.TargetObject != null) {
583 GenerateEventReferenceExpression (statement.Event);
585 Output.Write (CreateEscapedIdentifier (statement.Event.EventName));
587 Output.Write ( ", ");
588 GenerateExpression (statement.Listener);
592 protected override void GenerateGotoStatement (CodeGotoStatement statement)
594 TextWriter output = Output;
596 output.Write ("goto ");
597 output.Write (statement.Label);
601 protected override void GenerateLabeledStatement (CodeLabeledStatement statement)
603 TextWriter output = Output;
606 output.WriteLine (statement.Label + ":");
608 if (statement.Statement != null) {
609 GenerateStatement (statement.Statement);
613 protected override void GenerateTypeOfExpression (CodeTypeOfExpression e)
615 TextWriter output = Output;
617 output.Write ("GetType(");
622 protected override void GenerateVariableDeclarationStatement( CodeVariableDeclarationStatement statement )
624 TextWriter output = Output;
626 output.Write ("Dim ");
627 OutputTypeNamePair (statement.Type, statement.Name);
629 CodeExpression initExpression = statement.InitExpression;
630 if (initExpression != null) {
631 output.Write (" = ");
632 GenerateExpression (initExpression);
638 protected override void GenerateLinePragmaStart (CodeLinePragma linePragma)
641 Output.Write ("#ExternalSource(\"");
642 Output.Write (linePragma.FileName);
643 Output.Write ("\",");
644 Output.Write (linePragma.LineNumber);
645 Output.WriteLine (")");
646 Output.WriteLine ("");
649 protected override void GenerateLinePragmaEnd (CodeLinePragma linePragma)
651 Output.WriteLine ("#End ExternalSource");
654 protected override void GenerateEvent (CodeMemberEvent eventRef, CodeTypeDeclaration declaration)
656 if (IsCurrentDelegate || IsCurrentEnum)
659 TextWriter output = Output;
661 OutputAttributes (eventRef.CustomAttributes, null,
662 LineHandling.ContinueLine);
664 OutputMemberAccessModifier (eventRef.Attributes);
666 output.Write ("Event ");
667 OutputTypeNamePair (eventRef.Type, GetEventName(eventRef));
669 if (eventRef.ImplementationTypes.Count > 0) {
670 OutputImplementationTypes (eventRef.ImplementationTypes, eventRef.Name);
671 } else if (eventRef.PrivateImplementationType != null) {
672 output.Write (" Implements ");
673 OutputType (eventRef.PrivateImplementationType);
675 output.Write (eventRef.Name);
681 protected override void GenerateField (CodeMemberField field)
683 if (IsCurrentDelegate || IsCurrentInterface)
686 TextWriter output = Output;
688 OutputAttributes (field.CustomAttributes, null,
689 LineHandling.ContinueLine);
692 output.Write (field.Name);
694 MemberAttributes attributes = field.Attributes;
695 OutputMemberAccessModifier (attributes);
696 OutputVTableModifier (attributes);
697 OutputFieldScopeModifier (attributes);
698 OutputTypeNamePair (field.Type, field.Name);
701 CodeExpression initExpression = field.InitExpression;
702 if (initExpression != null) {
703 output.Write (" = ");
704 GenerateExpression (initExpression);
710 protected override void GenerateSnippetMember (CodeSnippetTypeMember member)
712 Output.Write (member.Text);
715 protected override void GenerateEntryPointMethod (CodeEntryPointMethod method, CodeTypeDeclaration declaration)
717 OutputAttributes (method.CustomAttributes, null,
718 LineHandling.ContinueLine);
720 Output.WriteLine ("Public Shared Sub Main()");
722 GenerateStatements (method.Statements);
724 Output.WriteLine ("End Sub");
727 [MonoTODO ("partially implemented")]
728 protected override void GenerateMethod (CodeMemberMethod method, CodeTypeDeclaration declaration)
730 if (IsCurrentDelegate || IsCurrentEnum)
733 bool isSub = method.ReturnType.BaseType == typeof(void).FullName;
735 TextWriter output = Output;
737 OutputAttributes (method.CustomAttributes, null,
738 LineHandling.ContinueLine);
740 MemberAttributes attributes = method.Attributes;
742 if (!IsCurrentInterface) {
743 if (method.PrivateImplementationType == null) {
744 OutputMemberAccessModifier (attributes);
745 if (IsOverloaded (method, declaration)) {
746 output.Write ("Overloads ");
749 OutputVTableModifier (attributes);
750 OutputMemberScopeModifier (attributes);
752 OutputVTableModifier (attributes);
756 output.Write ("Sub ");
758 output.Write ("Function ");
760 output.Write (GetMethodName(method));
761 OutputTypeParameters (method.TypeParameters);
763 OutputParameters (method.Parameters);
767 output.Write (" As ");
768 OutputAttributes (method.ReturnTypeCustomAttributes, null,
769 LineHandling.InLine);
770 OutputType (method.ReturnType);
773 if (method.ImplementationTypes.Count > 0) {
774 OutputImplementationTypes (method.ImplementationTypes, method.Name);
775 } else if (method.PrivateImplementationType != null) {
776 output.Write (" Implements ");
777 OutputType (method.PrivateImplementationType);
779 output.Write (method.Name);
783 if (!IsCurrentInterface) {
784 if ((attributes & MemberAttributes.ScopeMask) != MemberAttributes.Abstract) {
786 GenerateStatements (method.Statements);
789 output.WriteLine ("End Sub");
791 output.WriteLine ("End Function");
796 protected override void GenerateProperty (CodeMemberProperty property, CodeTypeDeclaration declaration)
798 if (IsCurrentDelegate || IsCurrentEnum)
801 TextWriter output = Output;
803 OutputAttributes (property.CustomAttributes, null,
804 LineHandling.ContinueLine);
806 MemberAttributes attributes = property.Attributes;
808 if (!IsCurrentInterface) {
809 if (property.PrivateImplementationType == null) {
810 OutputMemberAccessModifier (attributes);
811 if (IsOverloaded (property, declaration)) {
812 output.Write ("Overloads ");
815 OutputVTableModifier (attributes);
816 OutputMemberScopeModifier (attributes);
818 OutputVTableModifier (attributes);
821 // mark property as default property if we're dealing with an indexer
822 if (string.Compare (GetPropertyName(property), "Item", true, CultureInfo.InvariantCulture) == 0 && property.Parameters.Count > 0) {
823 output.Write ("Default ");
826 if (property.HasGet && (!property.HasSet))
827 output.Write ("ReadOnly " );
829 if (property.HasSet && (!property.HasGet))
830 output.Write ("WriteOnly " );
832 output.Write ("Property ");
833 Output.Write (GetPropertyName (property));
834 // in .NET 2.0, always output parantheses (whether or not there
835 // are any parameters to output
837 OutputParameters (property.Parameters);
839 Output.Write (" As ");
840 Output.Write (GetTypeOutput(property.Type));
842 if (property.ImplementationTypes.Count > 0) {
843 OutputImplementationTypes (property.ImplementationTypes, property.Name);
844 } else if (property.PrivateImplementationType != null) {
845 output.Write (" Implements ");
846 OutputType (property.PrivateImplementationType);
848 output.Write (property.Name);
853 if (!IsCurrentInterface) {
855 if (property.HasGet) {
856 output.WriteLine ("Get");
857 if (!IsAbstract (property.Attributes)) {
859 GenerateStatements (property.GetStatements);
861 output.WriteLine ("End Get");
865 if (property.HasSet) {
866 output.WriteLine ("Set");
867 if (!IsAbstract (property.Attributes)) {
869 GenerateStatements (property.SetStatements);
871 output.WriteLine ("End Set");
876 output.WriteLine ("End Property");
880 protected override void GenerateConstructor (CodeConstructor constructor, CodeTypeDeclaration declaration)
882 if (IsCurrentDelegate || IsCurrentEnum || IsCurrentInterface)
885 OutputAttributes (constructor.CustomAttributes, null,
886 LineHandling.ContinueLine);
887 OutputMemberAccessModifier (constructor.Attributes);
888 Output.Write ("Sub New(");
889 OutputParameters (constructor.Parameters);
890 Output.WriteLine (")");
892 // check if ctor passes args on to other ctor in class
893 CodeExpressionCollection ctorArgs = constructor.ChainedConstructorArgs;
894 if (ctorArgs.Count > 0) {
895 Output.Write ("Me.New(");
896 OutputExpressionList (ctorArgs);
897 Output.WriteLine (")");
899 // check if ctor passes args on to ctor in base class
900 ctorArgs = constructor.BaseConstructorArgs;
901 if (ctorArgs.Count > 0) {
902 Output.Write ("MyBase.New(");
903 OutputExpressionList (ctorArgs);
904 Output.WriteLine (")");
905 } else if (IsCurrentClass) {
906 // call default base ctor
907 Output.WriteLine ("MyBase.New");
910 GenerateStatements (constructor.Statements);
912 Output.WriteLine ("End Sub");
915 protected override void GenerateTypeConstructor (CodeTypeConstructor constructor)
917 if (IsCurrentDelegate || IsCurrentEnum || IsCurrentInterface)
920 OutputAttributes (constructor.CustomAttributes, null,
921 LineHandling.ContinueLine);
923 Output.WriteLine ("Shared Sub New()");
925 GenerateStatements (constructor.Statements);
927 Output.WriteLine ("End Sub");
930 [MonoTODO ("partially implemented")]
931 protected override void GenerateTypeStart (CodeTypeDeclaration declaration)
933 TextWriter output = Output;
935 OutputAttributes (declaration.CustomAttributes, null,
936 LineHandling.ContinueLine);
938 TypeAttributes attributes = declaration.TypeAttributes;
940 if (IsCurrentDelegate) {
941 CodeTypeDelegate delegateDecl = (CodeTypeDelegate) declaration;
943 if ((attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public) {
944 output.Write ("Public ");
947 bool isSub = delegateDecl.ReturnType.BaseType == typeof (void).FullName;
949 output.Write ("Delegate Sub ");
951 output.Write ("Delegate Function ");
954 output.Write (CreateEscapedIdentifier (delegateDecl.Name));
955 OutputTypeParameters (delegateDecl.TypeParameters);
957 OutputParameters (delegateDecl.Parameters);
960 Output.Write (" As ");
961 OutputType (delegateDecl.ReturnType);
963 Output.WriteLine ("");
965 OutputTypeAttributes (declaration);
966 output.Write (CreateEscapedIdentifier (declaration.Name));
967 OutputTypeParameters (declaration.TypeParameters);
970 if (declaration.BaseTypes.Count > 0) {
971 output.Write (" As ");
972 OutputType (declaration.BaseTypes[0]);
979 bool firstInherits = true;
980 bool firstImplements = true;
982 for (int i = 0; i < declaration.BaseTypes.Count; i++) {
983 // a struct can only implement interfaces
984 // an interface can only inherit from other interface
986 CodeTypeReference typeRef = declaration.BaseTypes[i];
988 if (firstInherits && !declaration.IsStruct && !typeRef.IsInterface) {
990 output.Write ("Inherits ");
991 firstInherits = false;
992 } else if (!declaration.IsInterface && firstImplements) {
994 output.Write ("Implements ");
995 firstImplements = false;
999 OutputType (typeRef);
1001 output.WriteLine ();
1006 protected override void GenerateTypeEnd (CodeTypeDeclaration declaration)
1008 if (IsCurrentDelegate) {
1011 string output = string.Empty;
1014 if (declaration.IsStruct)
1015 output = "End Structure";
1016 if (declaration.IsInterface)
1017 output = "End Interface";
1018 if (declaration.IsEnum)
1019 output = "End Enum";
1020 if (declaration.IsClass)
1021 output = "End Class";
1023 Output.WriteLine (output);
1026 protected override void GenerateNamespace(CodeNamespace ns)
1028 GenerateNamespaceImports (ns);
1029 Output.WriteLine ();
1030 GenerateCommentStatements (ns.Comments);
1031 GenerateNamespaceStart (ns);
1033 GenerateNamespaceEnd (ns);
1037 protected override void GenerateNamespaceStart (CodeNamespace ns)
1039 TextWriter output = Output;
1041 string name = ns.Name;
1042 if (name != null && name != string.Empty) {
1043 output.Write ("Namespace ");
1044 output.WriteLine (name);
1049 protected override void GenerateNamespaceEnd (CodeNamespace ns)
1051 string name = ns.Name;
1052 if (name != null && name != string.Empty) {
1054 Output.WriteLine ("End Namespace");
1058 protected override void GenerateNamespaceImport (CodeNamespaceImport import)
1060 TextWriter output = Output;
1062 output.Write ("Imports ");
1063 output.Write (import.Namespace);
1064 output.WriteLine ();
1067 protected override void GenerateAttributeDeclarationsStart (CodeAttributeDeclarationCollection attributes)
1072 protected override void GenerateAttributeDeclarationsEnd (CodeAttributeDeclarationCollection attributes)
1077 private void OutputAttributes (CodeAttributeDeclarationCollection attributes, string prefix, LineHandling lineHandling) {
1078 if (attributes.Count == 0) {
1082 GenerateAttributeDeclarationsStart (attributes);
1084 IEnumerator enumerator = attributes.GetEnumerator ();
1085 if (enumerator.MoveNext ()) {
1086 CodeAttributeDeclaration att = (CodeAttributeDeclaration) enumerator.Current;
1087 if (prefix != null) {
1088 Output.Write (prefix);
1090 OutputAttributeDeclaration (att);
1092 while (enumerator.MoveNext ()) {
1093 Output.Write (", ");
1094 if (lineHandling != LineHandling.InLine) {
1095 ContinueOnNewLine ("");
1098 att = (CodeAttributeDeclaration) enumerator.Current;
1099 if (prefix != null) {
1100 Output.Write (prefix);
1102 OutputAttributeDeclaration (att);
1105 GenerateAttributeDeclarationsEnd (attributes);
1108 switch (lineHandling) {
1109 case LineHandling.ContinueLine:
1110 ContinueOnNewLine ("");
1112 case LineHandling.NewLine:
1113 Output.WriteLine ();
1118 protected override void OutputAttributeArgument (CodeAttributeArgument argument)
1120 string name = argument.Name;
1121 if (name != null && name.Length > 0) {
1122 Output.Write (name);
1123 Output.Write (":=");
1125 GenerateExpression (argument.Value);
1128 private void OutputAttributeDeclaration (CodeAttributeDeclaration attribute)
1130 Output.Write (attribute.Name.Replace ('+', '.'));
1132 IEnumerator enumerator = attribute.Arguments.GetEnumerator ();
1133 if (enumerator.MoveNext ()) {
1134 CodeAttributeArgument argument = (CodeAttributeArgument) enumerator.Current;
1135 OutputAttributeArgument (argument);
1137 while (enumerator.MoveNext ()) {
1138 Output.Write (", ");
1139 argument = (CodeAttributeArgument) enumerator.Current;
1140 OutputAttributeArgument (argument);
1146 protected override void OutputDirection (FieldDirection direction)
1148 switch (direction) {
1149 case FieldDirection.In:
1150 Output.Write ("ByVal ");
1152 case FieldDirection.Out:
1153 case FieldDirection.Ref:
1154 Output.Write ("ByRef ");
1159 protected override void OutputFieldScopeModifier (MemberAttributes attributes)
1161 switch (attributes & MemberAttributes.ScopeMask) {
1162 case MemberAttributes.Static:
1163 Output.Write ("Shared ");
1165 case MemberAttributes.Const:
1166 Output.Write ("Const ");
1171 private void OutputImplementationTypes (CodeTypeReferenceCollection implementationTypes, string member)
1173 IEnumerator enumerator = implementationTypes.GetEnumerator ();
1174 if (enumerator.MoveNext ()) {
1175 Output.Write (" Implements ");
1177 CodeTypeReference typeReference = (CodeTypeReference) enumerator.Current;
1178 OutputType (typeReference);
1180 OutputIdentifier (member);
1182 while (enumerator.MoveNext ()) {
1183 Output.Write (" , ");
1184 typeReference = (CodeTypeReference) enumerator.Current;
1185 OutputType (typeReference);
1187 OutputIdentifier (member);
1192 protected override void OutputMemberAccessModifier (MemberAttributes attributes)
1194 switch (attributes & MemberAttributes.AccessMask) {
1195 case MemberAttributes.Assembly:
1196 case MemberAttributes.FamilyAndAssembly:
1197 Output.Write ("Friend ");
1199 case MemberAttributes.Family:
1200 Output.Write ("Protected ");
1202 case MemberAttributes.FamilyOrAssembly:
1203 Output.Write ("Protected Friend ");
1205 case MemberAttributes.Private:
1206 Output.Write ("Private ");
1208 case MemberAttributes.Public:
1209 Output.Write ("Public ");
1214 private void OutputVTableModifier (MemberAttributes attributes)
1216 if ((attributes & MemberAttributes.VTableMask) == MemberAttributes.New)
1217 Output.Write ("Shadows ");
1220 protected override void OutputMemberScopeModifier (MemberAttributes attributes)
1222 switch (attributes & MemberAttributes.ScopeMask) {
1223 case MemberAttributes.Abstract:
1224 Output.Write ("MustOverride ");
1226 case MemberAttributes.Final:
1229 case MemberAttributes.Static:
1230 Output.Write ("Shared ");
1232 case MemberAttributes.Override:
1233 Output.Write ("Overrides ");
1235 case MemberAttributes.Overloaded:
1236 // based on http://gendotnet.com/Code%20Gen%20Articles/codedom.htm
1237 Output.Write ("Overloads ");
1239 MemberAttributes access_ovl = attributes & MemberAttributes.AccessMask;
1240 if (access_ovl == MemberAttributes.Public || access_ovl == MemberAttributes.Family)
1241 Output.Write ("Overridable ");
1245 // FUNNY! if the scope value is
1246 // rubbish (0 or >Const), and access
1247 // is public, protected make it
1250 // i'm not sure whether this is 100%
1251 // correct, but it seems to be MS
1254 // On MS.NET 2.0, internal properties
1255 // are also marked "virtual".
1257 MemberAttributes access = attributes & MemberAttributes.AccessMask;
1258 if (access == MemberAttributes.Public ||
1259 access == MemberAttributes.Family || access == MemberAttributes.Assembly)
1260 Output.Write ("Overridable ");
1265 protected override void OutputOperator (CodeBinaryOperatorType op)
1268 case CodeBinaryOperatorType.Add:
1271 case CodeBinaryOperatorType.Subtract:
1274 case CodeBinaryOperatorType.Multiply:
1277 case CodeBinaryOperatorType.Divide:
1280 case CodeBinaryOperatorType.Modulus:
1281 Output.Write ("Mod");
1283 case CodeBinaryOperatorType.Assign:
1286 case CodeBinaryOperatorType.IdentityInequality:
1287 Output.Write ("<>");
1289 case CodeBinaryOperatorType.IdentityEquality:
1290 Output.Write ("Is");
1292 case CodeBinaryOperatorType.ValueEquality:
1295 case CodeBinaryOperatorType.BitwiseOr:
1296 Output.Write ("Or");
1298 case CodeBinaryOperatorType.BitwiseAnd:
1299 Output.Write ("And");
1301 case CodeBinaryOperatorType.BooleanOr:
1302 Output.Write ("OrElse");
1304 case CodeBinaryOperatorType.BooleanAnd:
1305 Output.Write ("AndAlso");
1307 case CodeBinaryOperatorType.LessThan:
1310 case CodeBinaryOperatorType.LessThanOrEqual:
1311 Output.Write ("<=");
1313 case CodeBinaryOperatorType.GreaterThan:
1316 case CodeBinaryOperatorType.GreaterThanOrEqual:
1317 Output.Write (">=");
1322 private void OutputTypeAttributes (CodeTypeDeclaration declaration)
1324 TextWriter output = Output;
1325 TypeAttributes attributes = declaration.TypeAttributes;
1327 if (declaration.IsPartial)
1328 output.Write ("Partial ");
1330 switch (attributes & TypeAttributes.VisibilityMask) {
1331 case TypeAttributes.Public:
1332 case TypeAttributes.NestedPublic:
1333 output.Write ("Public ");
1335 case TypeAttributes.NestedPrivate:
1336 output.Write ("Private ");
1338 case TypeAttributes.NotPublic:
1339 case TypeAttributes.NestedFamANDAssem:
1340 case TypeAttributes.NestedAssembly:
1341 output.Write ("Friend ");
1343 case TypeAttributes.NestedFamily:
1344 output.Write ("Protected ");
1346 case TypeAttributes.NestedFamORAssem:
1347 output.Write ("Protected Friend ");
1351 if (declaration.IsStruct) {
1352 output.Write ("Structure ");
1353 } else if (declaration.IsEnum) {
1354 output.Write ("Enum ");
1356 if ((attributes & TypeAttributes.Interface) != 0) {
1357 output.Write ("Interface ");
1359 if ((attributes & TypeAttributes.Sealed) != 0)
1360 output.Write ("NotInheritable ");
1362 if ((attributes & TypeAttributes.Abstract) != 0)
1363 output.Write ("MustInherit ");
1365 output.Write ("Class ");
1370 void OutputTypeParameters (CodeTypeParameterCollection parameters)
1372 int count = parameters.Count;
1376 Output.Write ("(Of ");
1377 for (int i = 0; i < count; ++i) {
1379 Output.Write (", ");
1380 CodeTypeParameter p = parameters [i];
1381 Output.Write (p.Name);
1382 OutputTypeParameterConstraints (p);
1387 void OutputTypeParameterConstraints (CodeTypeParameter parameter)
1389 int constraint_count = parameter.Constraints.Count +
1390 (parameter.HasConstructorConstraint ? 1 : 0);
1392 if (constraint_count == 0)
1395 Output.Write (" As ");
1397 if (constraint_count > 1)
1398 Output.Write (" {");
1400 for (int i = 0; i < parameter.Constraints.Count; i++) {
1402 Output.Write (", ");
1403 OutputType (parameter.Constraints [i]);
1406 if (parameter.HasConstructorConstraint) {
1407 if (constraint_count > 1)
1408 Output.Write (", ");
1409 Output.Write ("New");
1412 if (constraint_count > 1)
1416 protected override void OutputTypeNamePair (CodeTypeReference typeRef, String name)
1418 if (name.Length == 0)
1419 name = "__exception";
1420 Output.Write (CreateEscapedIdentifier(name) + " As " + GetTypeOutput (typeRef));
1423 protected override void OutputType (CodeTypeReference type)
1425 Output.Write (GetTypeOutput (type));
1428 protected override string QuoteSnippetString (string value)
1430 StringBuilder mySBuilder = new StringBuilder(value.Length);
1431 mySBuilder.Append ("\"");
1432 bool inQuotes = true;
1433 for (int MyCounter = 0; MyCounter < value.Length; MyCounter++) {
1434 if (value[MyCounter] == 34) //quotation mark
1437 mySBuilder.Append ("&\"");
1440 mySBuilder.Append (value[MyCounter]);
1441 mySBuilder.Append (value[MyCounter]);
1443 else if (value[MyCounter] >= 32) //standard ansi/unicode characters
1446 mySBuilder.Append ("&\"");
1449 mySBuilder.Append (value[MyCounter]);
1451 else //special chars, e.g. line break
1454 mySBuilder.Append ("\"");
1457 mySBuilder.Append ("&Microsoft.VisualBasic.ChrW(");
1458 mySBuilder.Append ((int)value[MyCounter]);
1459 mySBuilder.Append (")");
1463 mySBuilder.Append ("\"");
1464 return mySBuilder.ToString();
1467 private void GenerateMemberReferenceExpression (CodeExpression targetObject, string memberName)
1469 GenerateExpression (targetObject);
1471 Output.Write (memberName);
1478 protected override string CreateEscapedIdentifier (string value)
1480 for (int x = 0; x < Keywords.Length; x++)
1481 if (value.ToLower().Equals (Keywords[x].ToLower()))
1482 return "[" + value + "]";
1486 protected override string CreateValidIdentifier (string value)
1488 for (int x = 0; x < Keywords.Length; x++)
1489 if (value.ToLower().Equals (Keywords[x].ToLower()))
1494 protected override string GetTypeOutput (CodeTypeReference type)
1497 CodeTypeReference arrayType;
1499 arrayType = type.ArrayElementType;
1500 if (arrayType != null)
1501 output = GetTypeOutput (arrayType);
1503 switch (type.BaseType) {
1504 case "System.DateTime":
1507 case "System.Decimal":
1510 case "System.Double":
1513 case "System.Single":
1519 case "System.Int32":
1522 case "System.Int64":
1525 case "System.Int16":
1528 case "System.Boolean":
1534 case "System.String":
1537 case "System.Object":
1540 case "System.SByte":
1543 case "System.UInt16":
1546 case "System.UInt32":
1547 output = "UInteger";
1549 case "System.UInt64":
1553 output = type.BaseType.Replace('+', '.');
1554 output = CreateEscapedIdentifier (output);
1559 int rank = type.ArrayRank;
1562 for (--rank; rank > 0; --rank)
1570 protected override bool IsValidIdentifier (string identifier)
1572 for (int x = 0; x < Keywords.Length; x++)
1573 if (identifier.ToLower().Equals (Keywords[x].ToLower()))
1578 protected override bool Supports (GeneratorSupport supports)
1583 private bool IsOverloaded (CodeMemberProperty property, CodeTypeDeclaration type)
1585 if ((property.Attributes & MemberAttributes.Overloaded) == MemberAttributes.Overloaded) {
1589 foreach (CodeTypeMember member in type.Members) {
1590 CodeMemberProperty p = member as CodeMemberProperty;
1592 // member is not a property
1596 if (p != property && p.Name == property.Name && p.PrivateImplementationType == null)
1602 private bool IsOverloaded (CodeMemberMethod method, CodeTypeDeclaration type)
1604 if ((method.Attributes & MemberAttributes.Overloaded) == MemberAttributes.Overloaded) {
1608 foreach (CodeTypeMember member in type.Members) {
1609 CodeMemberMethod m = member as CodeMemberMethod;
1611 // member is not a method
1615 if (!(m is CodeTypeConstructor) && !(m is CodeConstructor) && m != method && m.Name == method.Name && m.PrivateImplementationType == null)
1621 private string GetEventName (CodeMemberEvent evt)
1623 if (evt.PrivateImplementationType == null)
1626 string baseType = evt.PrivateImplementationType.BaseType.Replace ('.', '_');
1627 return baseType + "_" + evt.Name;
1630 private string GetMethodName (CodeMemberMethod method)
1632 if (method.PrivateImplementationType == null)
1635 string baseType = method.PrivateImplementationType.BaseType.Replace ('.', '_');
1636 return baseType + "_" + method.Name;
1639 private string GetPropertyName (CodeMemberProperty property)
1641 if (property.PrivateImplementationType == null)
1642 return property.Name;
1644 string baseType = property.PrivateImplementationType.BaseType.Replace ('.', '_');
1645 return baseType + "_" + property.Name;
1648 static bool IsAbstract (MemberAttributes attributes)
1650 return (attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract;
1653 private enum LineHandling