From ba47995db3c377a96ce701fa0ad3e3b6fed1decc Mon Sep 17 00:00:00 2001 From: Daniel Grunwald Date: Fri, 11 Feb 2011 23:10:52 +0100 Subject: [PATCH 1/5] Squashed 'NRefactory/' content from commit 5aa65b2 git-subtree-dir: NRefactory git-subtree-split: 5aa65b26686a556aa8625a9f866d6734667bdb22 --- .gitattributes | 2 + .gitignore | 2 + ICSharpCode.NRefactory.Demo/.gitignore | 3 + .../ICSharpCode.NRefactory.Demo.csproj | 87 + .../MainForm.Designer.cs | 221 + ICSharpCode.NRefactory.Demo/MainForm.cs | 228 + ICSharpCode.NRefactory.Demo/MainForm.resx | 123 + ICSharpCode.NRefactory.Demo/Program.cs | 25 + .../Properties/AssemblyInfo.cs | 31 + .../VBDemo.Designer.cs | 163 + ICSharpCode.NRefactory.Demo/VBDemo.cs | 78 + ICSharpCode.NRefactory.Demo/VBDemo.resx | 120 + .../VBDomView.Designer.cs | 59 + ICSharpCode.NRefactory.Demo/VBDomView.cs | 225 + ICSharpCode.NRefactory.Demo/VBDomView.resx | 120 + .../VBEditDialog.Designer.cs | 88 + ICSharpCode.NRefactory.Demo/VBEditDialog.cs | 18 + ICSharpCode.NRefactory.Demo/VBEditDialog.resx | 120 + ICSharpCode.NRefactory.Tests/.gitignore | 3 + .../CSharp/AstStructureTest.cs | 31 + .../AliasReferenceExpressionTests.cs | 36 + .../Parser/Expression/AnonymousMethodTests.cs | 55 + .../ArrayObjectCreateExpressionTests.cs | 36 + .../Expression/AssignmentExpressionTests.cs | 88 + .../BaseReferenceExpressionTests.cs | 19 + .../BinaryOperatorExpressionTests.cs | 227 + .../Parser/Expression/CastExpressionTests.cs | 140 + .../Expression/CheckedExpressionTests.cs | 26 + .../Expression/ConditionalExpressionTests.cs | 104 + .../Expression/DefaultValueExpressionTests.cs | 53 + .../Expression/IdentifierExpressionTests.cs | 78 + .../Expression/IndexerExpressionTests.cs | 29 + .../Expression/InvocationExpressionTests.cs | 155 + .../Parser/Expression/IsExpressionTests.cs | 45 + .../Expression/LambdaExpressionTests.cs | 89 + .../MemberReferenceExpressionTests.cs | 76 + .../ParenthesizedExpressionTests.cs | 21 + .../PointerReferenceExpressionTests.cs | 21 + .../Expression/PrimitiveExpressionTests.cs | 203 + .../Parser/Expression/QueryExpressionTests.cs | 109 + .../Expression/SizeOfExpressionTests.cs | 19 + .../Expression/StackAllocExpressionTests.cs | 19 + .../ThisReferenceExpressionTests.cs | 18 + .../Expression/TypeOfExpressionTests.cs | 91 + .../TypeReferenceExpressionTests.cs | 46 + .../UnaryOperatorExpressionTests.cs | 95 + .../GeneralScope/AttributeSectionTests.cs | 68 + .../GeneralScope/DelegateDeclarationTests.cs | 77 + .../GeneralScope/NamespaceDeclarationTests.cs | 36 + .../GeneralScope/TypeDeclarationTests.cs | 240 + .../GeneralScope/UsingDeclarationTests.cs | 102 + .../CSharp/Parser/ParseUtil.cs | 71 + .../Parser/Statements/BlockStatementTests.cs | 41 + .../Statements/CheckedStatementTests.cs | 45 + .../Parser/Statements/EmptyStatementTests.cs | 18 + .../Statements/ExpressionStatementTests.cs | 26 + .../Parser/Statements/FixedStatementTests.cs | 19 + .../Parser/Statements/ForStatementTests.cs | 59 + .../Parser/Statements/GotoStatementTests.cs | 48 + .../Parser/Statements/IfElseStatementTests.cs | 39 + .../Parser/Statements/LabelStatementTests.cs | 29 + .../Parser/Statements/LockStatementTests.cs | 19 + .../Parser/Statements/ReturnStatementTests.cs | 33 + .../Parser/Statements/SwitchStatementTests.cs | 20 + .../Parser/Statements/ThrowStatementTests.cs | 26 + .../Statements/TryCatchStatementTests.cs | 47 + .../Parser/Statements/UnsafeStatementTests.cs | 19 + .../Parser/Statements/UsingStatementTests.cs | 19 + .../VariableDeclarationStatementTests.cs | 226 + .../Parser/Statements/WhileStatementTests.cs | 30 + .../Parser/Statements/YieldStatementTests.cs | 41 + .../ConstructorDeclarationTests.cs | 52 + .../TypeMembers/DestructorDeclarationTests.cs | 32 + .../TypeMembers/EventDeclarationTests.cs | 84 + .../TypeMembers/FieldDeclarationTests.cs | 27 + .../TypeMembers/IndexerDeclarationTests.cs | 47 + .../TypeMembers/MethodDeclarationTests.cs | 303 + .../TypeMembers/OperatorDeclarationTests.cs | 53 + .../TypeMembers/PropertyDeclarationTests.cs | 93 + .../Parser/TypeSystemConvertVisitorTests.cs | 36 + .../CSharp/Resolver/AttributeTests.cs | 96 + .../CSharp/Resolver/BinaryOperatorTests.cs | 392 + .../CSharp/Resolver/CastTests.cs | 57 + .../CSharp/Resolver/ConversionsTest.cs | 336 + .../CSharp/Resolver/ExtensionMethodTests.cs | 89 + .../CSharp/Resolver/InvocationTests.cs | 268 + .../CSharp/Resolver/LambdaTests.cs | 278 + .../CSharp/Resolver/LinqTests.cs | 136 + .../Resolver/LocalTypeInferenceTests.cs | 55 + .../CSharp/Resolver/NameLookupTests.cs | 755 + .../CSharp/Resolver/ObjectCreationTests.cs | 135 + .../Resolver/OverloadResolutionTests.cs | 185 + .../CSharp/Resolver/ResolverTestBase.cs | 207 + .../CSharp/Resolver/TypeInferenceTests.cs | 158 + .../CSharp/Resolver/UnaryOperatorTests.cs | 147 + .../CSharp/Resolver/UnsafeCodeTests.cs | 29 + .../FormattingTests/TestBraceStlye.cs | 530 + .../FormattingTests/TestFormattingBugs.cs | 162 + .../FormattingTests/TestSpacingVisitor.cs | 1167 + .../TestStatementIndentation.cs | 1749 + .../TestTypeLevelIndentation.cs | 500 + .../ICSharpCode.NRefactory.Tests.csproj | 169 + .../Properties/AssemblyInfo.cs | 29 + .../TypeSystem/CecilLoaderTests.cs | 246 + .../TypeSystem/GetAllBaseTypesTest.cs | 128 + .../TypeSystem/GetMembersTests.cs | 75 + .../TypeSystem/ReflectionHelperTests.cs | 279 + .../TypeSystem/TestInterningProvider.cs | 171 + .../TypeSystem/TypeSystemTests.TestCase.cs | 68 + .../TypeSystem/TypeSystemTests.cs | 265 + ICSharpCode.NRefactory.Tests/Untested.cs | 41 + .../Utils/CSharpPrimitiveCastTests.cs | 68 + .../Utils/TreeTraversalTests.cs | 47 + ICSharpCode.NRefactory.VB.Tests/.gitignore | 3 + .../AssemblyInfo.cs | 35 + .../General/UnitTest.cs | 103 + .../ICSharpCode.NRefactory.VB.Tests.csproj | 154 + .../Lexer/CustomLexerTests.cs | 118 + .../Lexer/ImplicitLineContinuationTests.cs | 230 + .../Lexer/LATextReaderTests.cs | 35 + .../Lexer/LexerContextTests.cs | 572 + .../Lexer/LexerPositionTests.cs | 87 + .../Lexer/LexerTests.cs | 1538 + .../Lexer/LiteralsTests.cs | 194 + .../Lexer/TokenTests.cs | 23 + .../Lexer/XmlModeLexerTests.cs | 993 + .../CodeDOMParenthesizedExpressionTest.cs | 22 + .../CodeDOM/CodeDOMPrimitiveExpressionTest.cs | 23 + .../CodeDOM/CodeDOMTypeReferenceTest.cs | 30 + .../CodeDOM/InvocationExpressionTest.cs | 59 + .../Output/SpecialOutputVisitorTest.cs | 79 + .../Output/VBNet/VBNetOutputTest.cs | 670 + .../Parser/CheckParentVisitor.cs | 35 + .../Expressions/AddressOfExpressionTests.cs | 45 + .../Expressions/ArrayCreateExpressionTests.cs | 36 + .../Expressions/AssignmentExpressionTests.cs | 73 + .../BaseReferenceExpressionTests.cs | 24 + .../BinaryOperatorExpressionTests.cs | 310 + .../Parser/Expressions/CastExpressionTests.cs | 181 + .../ClassReferenceExpressionTests.cs | 24 + .../Expressions/ConditionalExpressionTests.cs | 29 + .../GlobalReferenceExpressionTests.cs | 32 + .../Expressions/IdentifierExpressionTests.cs | 40 + .../Expressions/InvocationExpressionTests.cs | 116 + .../Expressions/LambdaExpressionTests.cs | 137 + .../MemberReferenceExpressionTests.cs | 82 + .../ObjectCreateExpressionTests.cs | 114 + .../ParenthesizedExpressionTest.cs | 26 + .../Expressions/PrimitiveExpressionTests.cs | 23 + .../Expressions/QueryExpressionTests.cs | 635 + .../ThisReferenceExpressionTests.cs | 23 + .../Expressions/TypeOfExpressionTests.cs | 87 + .../Expressions/TypeOfIsExpressionTests.cs | 34 + .../TypeReferenceExpressionTests.cs | 47 + .../UnaryOperatorExpressionTests.cs | 61 + .../Parser/Expressions/XmlExpressionTests.cs | 255 + .../XmlMemberAccessExpressionTests.cs | 101 + .../GlobalScope/AttributeSectionTests.cs | 74 + .../GlobalScope/DelegateDeclarationTests.cs | 42 + .../GlobalScope/NamespaceDeclarationTests.cs | 43 + .../GlobalScope/OptionDeclarationTests.cs | 87 + .../GlobalScope/TypeDeclarationTests.cs | 203 + .../GlobalScope/UsingDeclarationTests.cs | 207 + .../Parser/LocationAssignmentCheckVisitor.cs | 26 + .../Parser/ParseUtil.cs | 92 + .../Parser/SnippetParserTests.cs | 22 + .../Statements/AddHandlerStatementTests.cs | 22 + .../Parser/Statements/BlockStatementTests.cs | 17 + .../Statements/ContinueStatementTests.cs | 17 + .../Parser/Statements/DoLoopStatementTests.cs | 17 + .../Parser/Statements/EndStatementTests.cs | 29 + .../Parser/Statements/EraseStatementTests.cs | 23 + .../Parser/Statements/ErrorStatementTests.cs | 23 + .../Statements/ExpressionStatementTests.cs | 17 + .../Statements/ForNextStatementTests.cs | 29 + .../Statements/ForeachStatementTests.cs | 25 + .../Parser/Statements/GotoStatementTests.cs | 24 + .../Parser/Statements/IfElseStatementTests.cs | 142 + .../Parser/Statements/LabelStatementTests.cs | 26 + .../LocalVariableDeclarationTests.cs | 204 + .../Parser/Statements/LockStatementTests.cs | 17 + .../Parser/Statements/OnErrorStatementTest.cs | 23 + .../Statements/RaiseEventStatementTest.cs | 23 + .../Parser/Statements/ReDimStatementTests.cs | 77 + .../Statements/RemoveHandlerStatement.cs | 23 + .../Parser/Statements/ResumeStatement.cs | 23 + .../Parser/Statements/ReturnStatementTests.cs | 32 + .../Parser/Statements/StopStatementTests.cs | 23 + .../Parser/Statements/SwitchStatementTests.cs | 34 + .../Parser/Statements/ThrowStatementTests.cs | 17 + .../Statements/TryCatchStatementTests.cs | 17 + .../Parser/Statements/UsingStatementTests.cs | 47 + .../Parser/Statements/WithStatementTests.cs | 23 + .../TypeLevel/ConstructorDeclarationTests.cs | 34 + .../Parser/TypeLevel/CustomEventTests.cs | 44 + .../TypeLevel/DeclareDeclarationTests.cs | 28 + .../Parser/TypeLevel/EventDeclarationTests.cs | 25 + .../Parser/TypeLevel/FieldDeclarationTests.cs | 74 + .../TypeLevel/MethodDeclarationTests.cs | 199 + .../TypeLevel/OperatorDeclarationTests.cs | 30 + .../TypeLevel/PropertyDeclarationTests.cs | 107 + ICSharpCode.NRefactory.VB/.gitignore | 3 + ICSharpCode.NRefactory.VB/Dom/AbstractNode.cs | 73 + ICSharpCode.NRefactory.VB/Dom/Enums.cs | 412 + .../Dom/General/BlockStatement.cs | 58 + .../Dom/General/CompilationUnit.cs | 24 + .../Dom/General/Expression.cs | 103 + .../Dom/General/LocalVariableDeclaration.cs | 99 + .../Dom/General/PrimitiveExpression.cs | 53 + .../Dom/General/Statement.cs | 62 + ICSharpCode.NRefactory.VB/Dom/Generated.cs | 5153 +++ ICSharpCode.NRefactory.VB/Dom/INode.cs | 51 + ICSharpCode.NRefactory.VB/Dom/INullable.cs | 12 + .../Dom/TypeReference.cs | 427 + .../DomBuilder/ExpressionBuilder.cs | 92 + .../DomBuilder/StatementBuilder.cs | 55 + .../EnvironmentInformationProvider.cs | 22 + .../ICSharpCode.NRefactory.VB.csproj | 148 + ICSharpCode.NRefactory.VB/IDomVisitor.cs | 242 + ICSharpCode.NRefactory.VB/Lexer/Block.cs | 57 + .../Lexer/ExpressionFinder.atg | 1361 + .../Lexer/ExpressionFinder.cs | 154 + .../Lexer/ExpressionFinderState.cs | 22 + ICSharpCode.NRefactory.VB/Lexer/Extensions.cs | 22 + .../Lexer/KeywordList.txt | 284 + ICSharpCode.NRefactory.VB/Lexer/Keywords.cs | 215 + .../Lexer/LATextReader.cs | 52 + .../Lexer/LookupTable.cs | 116 + ICSharpCode.NRefactory.VB/Lexer/Parser.cs | 8660 ++++ .../Lexer/PushParser.frame | 99 + .../Lexer/SavepointEventArgs.cs | 20 + .../Lexer/Special/BlankLine.cs | 19 + .../Lexer/Special/Comment.cs | 59 + .../Lexer/Special/CommentType.cs | 14 + .../Lexer/Special/ISpecial.cs | 52 + .../Lexer/Special/PreProcessingDirective.cs | 156 + .../Lexer/Special/SpecialTracker.cs | 71 + .../Lexer/Special/TagComment.cs | 29 + ICSharpCode.NRefactory.VB/Lexer/Token.cs | 111 + ICSharpCode.NRefactory.VB/Lexer/Tokens.cs | 527 + ICSharpCode.NRefactory.VB/Lexer/VBLexer.cs | 1489 + .../Lexer/VBLexerMemento.cs | 22 + .../Lexer/XmlModeInfo.cs | 29 + ICSharpCode.NRefactory.VB/Location.cs | 121 + .../OperatorPrecedence.cs | 84 + ICSharpCode.NRefactory.VB/Parser/Errors.cs | 50 + .../Parser/ModifierList.cs | 69 + .../Parser/ParamModifierList.cs | 49 + ICSharpCode.NRefactory.VB/Parser/Parser.cs | 5477 +++ ICSharpCode.NRefactory.VB/Parser/Parser.frame | 119 + ICSharpCode.NRefactory.VB/Parser/VBParser.cs | 455 + ICSharpCode.NRefactory.VB/Parser/vb.atg | 3811 ++ ICSharpCode.NRefactory.VB/ParserFactory.cs | 45 + .../PrettyPrinter/AbstractOutputFormatter.cs | 228 + .../AbstractPrettyPrintOptions.cs | 42 + .../PrettyPrinter/IOutputAstVisitor.cs | 50 + .../PrettyPrinter/SpecialNodesInserter.cs | 142 + .../VBNet/VBNetOutputFormatter.cs | 73 + .../PrettyPrinter/VBNet/VBNetOutputVisitor.cs | 3023 ++ .../VBNet/VBNetPrettyPrintOptions.cs | 18 + .../Properties/AssemblyInfo.cs | 33 + ICSharpCode.NRefactory.VB/SnippetParser.cs | 130 + .../Visitors/AbstractDomTransformer.cs | 2087 + .../Visitors/AbstractDomVisitor.cs | 1156 + .../Visitors/CodeDOMOutputVisitor.cs | 1534 + .../Visitors/CodeDOMVerboseOutputGenerator.cs | 356 + .../Visitors/LookupTableVisitor.cs | 273 + .../Visitors/NodeTrackingDomVisitor.cs | 1266 + .../Visitors/NotImplementedDomVisitor.cs | 469 + .../Visitors/PrefixFieldsVisitor.cs | 143 + .../Visitors/RenameIdentifierVisitor.cs | 61 + .../Visitors/SetParentVisitor.cs | 33 + .../Visitors/SetRegionInclusionVisitor.cs | 73 + ICSharpCode.NRefactory/.gitignore | 3 + .../CSharp/Ast/AstLocation.cs | 137 + ICSharpCode.NRefactory/CSharp/Ast/AstNode.cs | 575 + ICSharpCode.NRefactory/CSharp/Ast/AstType.cs | 32 + .../CSharp/Ast/CSharpModifierToken.cs | 114 + .../CSharp/Ast/CSharpTokenNode.cs | 89 + .../CSharp/Ast/CompilationUnit.cs | 105 + .../CSharp/Ast/ComposedType.cs | 131 + .../CSharp/Ast/DepthFirstAstVisitor.cs | 535 + .../Expressions/AnonymousMethodExpression.cs | 69 + .../Ast/Expressions/ArgListExpression.cs | 63 + .../Ast/Expressions/ArrayCreateExpression.cs | 43 + .../Expressions/ArrayInitializerExpression.cs | 73 + .../CSharp/Ast/Expressions/AsExpression.cs | 54 + .../Ast/Expressions/AssignmentExpression.cs | 124 + .../Expressions/BaseReferenceExpression.cs | 55 + .../Expressions/BinaryOperatorExpression.cs | 156 + .../CSharp/Ast/Expressions/CastExpression.cs | 58 + .../Ast/Expressions/CheckedExpression.cs | 56 + .../Ast/Expressions/ConditionalExpression.cs | 68 + .../Ast/Expressions/DefaultValueExpression.cs | 57 + .../Ast/Expressions/DirectionExpression.cs | 60 + .../CSharp/Ast/Expressions/Expression.cs | 105 + .../Ast/Expressions/IdentifierExpression.cs | 64 + .../Ast/Expressions/IndexerExpression.cs | 59 + .../Ast/Expressions/InvocationExpression.cs | 59 + .../CSharp/Ast/Expressions/IsExpression.cs | 54 + .../Ast/Expressions/LambdaExpression.cs | 58 + .../Expressions/MemberReferenceExpression.cs | 68 + .../Expressions/NamedArgumentExpression.cs | 32 + .../Expressions/NullReferenceExpression.cs | 39 + .../Ast/Expressions/ObjectCreateExpression.cs | 70 + .../Expressions/ParenthesizedExpression.cs | 49 + .../Expressions/PointerReferenceExpression.cs | 62 + .../Ast/Expressions/PrimitiveExpression.cs | 67 + .../CSharp/Ast/Expressions/QueryExpression.cs | 322 + .../Ast/Expressions/SizeOfExpression.cs | 56 + .../Ast/Expressions/StackAllocExpression.cs | 61 + .../Expressions/ThisReferenceExpression.cs | 52 + .../Ast/Expressions/TypeOfExpression.cs | 54 + .../Expressions/UnaryOperatorExpression.cs | 108 + .../Ast/Expressions/UncheckedExpression.cs | 56 + .../CSharp/Ast/GeneralScope/Attribute.cs | 57 + .../Ast/GeneralScope/AttributeSection.cs | 99 + .../CSharp/Ast/GeneralScope/Comment.cs | 85 + .../CSharp/Ast/GeneralScope/Constraint.cs | 67 + .../Ast/GeneralScope/DelegateDeclaration.cs | 85 + .../Ast/GeneralScope/NamespaceDeclaration.cs | 106 + .../Ast/GeneralScope/TypeDeclaration.cs | 95 + .../GeneralScope/TypeParameterDeclaration.cs | 42 + .../Ast/GeneralScope/UsingAliasDeclaration.cs | 74 + .../Ast/GeneralScope/UsingDeclaration.cs | 68 + .../CSharp/Ast/IAstVisitor.cs | 108 + .../CSharp/Ast/Identifier.cs | 95 + .../CSharp/Ast/MemberType.cs | 82 + .../CSharp/Ast/Modifiers.cs | 69 + ICSharpCode.NRefactory/CSharp/Ast/NodeType.cs | 48 + .../CSharp/Ast/PrimitiveType.cs | 59 + ICSharpCode.NRefactory/CSharp/Ast/Role.cs | 67 + .../CSharp/Ast/SimpleType.cs | 67 + .../CSharp/Ast/Statements/BlockStatement.cs | 95 + .../CSharp/Ast/Statements/BreakStatement.cs | 43 + .../CSharp/Ast/Statements/CheckedStatement.cs | 48 + .../Ast/Statements/ContinueStatement.cs | 43 + .../CSharp/Ast/Statements/EmptyStatement.cs | 56 + .../Ast/Statements/ExpressionStatement.cs | 48 + .../CSharp/Ast/Statements/FixedStatement.cs | 68 + .../CSharp/Ast/Statements/ForStatement.cs | 81 + .../CSharp/Ast/Statements/ForeachStatement.cs | 79 + .../CSharp/Ast/Statements/GotoStatement.cs | 88 + .../CSharp/Ast/Statements/IfElseStatement.cs | 77 + .../CSharp/Ast/Statements/LabelStatement.cs | 48 + .../CSharp/Ast/Statements/LockStatement.cs | 61 + .../CSharp/Ast/Statements/ReturnStatement.cs | 52 + .../CSharp/Ast/Statements/Statement.cs | 44 + .../CSharp/Ast/Statements/SwitchStatement.cs | 119 + .../CSharp/Ast/Statements/ThrowStatement.cs | 52 + .../Ast/Statements/TryCatchStatement.cs | 100 + .../Ast/Statements/UncheckedStatement.cs | 48 + .../CSharp/Ast/Statements/UnsafeStatement.cs | 48 + .../CSharp/Ast/Statements/UsingStatement.cs | 66 + .../VariableDeclarationStatement.cs | 60 + .../CSharp/Ast/Statements/WhileStatement.cs | 84 + .../CSharp/Ast/Statements/YieldStatement.cs | 61 + .../CSharp/Ast/TypeMembers/Accessor.cs | 63 + .../CSharp/Ast/TypeMembers/AttributedNode.cs | 59 + .../Ast/TypeMembers/ConstructorDeclaration.cs | 118 + .../Ast/TypeMembers/DestructorDeclaration.cs | 58 + .../Ast/TypeMembers/EnumMemberDeclaration.cs | 58 + .../Ast/TypeMembers/EventDeclaration.cs | 64 + .../Ast/TypeMembers/FieldDeclaration.cs | 44 + .../Ast/TypeMembers/IndexerDeclaration.cs | 44 + .../Ast/TypeMembers/MemberDeclaration.cs | 59 + .../Ast/TypeMembers/MethodDeclaration.cs | 75 + .../Ast/TypeMembers/OperatorDeclaration.cs | 112 + .../Ast/TypeMembers/ParameterDeclaration.cs | 87 + .../Ast/TypeMembers/PropertyDeclaration.cs | 57 + .../Ast/TypeMembers/VariableInitializer.cs | 61 + .../Formatter/CSharpFormattingPolicy.cs | 705 + .../CSharp/Formatter/DomIndentationVisitor.cs | 758 + .../CSharp/Formatter/DomSpacingVisitor.cs | 513 + .../CSharp/Formatter/Indent.cs | 79 + .../CSharp/OutputVisitor/IOutputFormatter.cs | 28 + .../CSharp/OutputVisitor/OutputVisitor.cs | 1663 + .../TextWriterOutputFormatter.cs | 96 + .../CSharp/Parser/CSharpParser.cs | 2531 ++ .../CSharp/Parser/ParsedFile.cs | 75 + .../CSharp/Parser/TypeSystemConvertVisitor.cs | 686 + .../CSharp/Parser/mcs/AssemblyInfo.cs | 43 + .../CSharp/Parser/mcs/ChangeLog | 34100 ++++++++++++++++ .../CSharp/Parser/mcs/CryptoConvert.cs | 754 + .../CSharp/Parser/mcs/Makefile | 126 + .../CSharp/Parser/mcs/MonoSymbolFile.cs | 723 + .../CSharp/Parser/mcs/MonoSymbolTable.cs | 1376 + .../CSharp/Parser/mcs/MonoSymbolWriter.cs | 403 + .../CSharp/Parser/mcs/NOTES | 38 + .../CSharp/Parser/mcs/OPTIMIZE | 26 + .../CSharp/Parser/mcs/OTODO | 239 + ICSharpCode.NRefactory/CSharp/Parser/mcs/PLAN | 66 + .../CSharp/Parser/mcs/README | 72 + ICSharpCode.NRefactory/CSharp/Parser/mcs/TODO | 223 + .../CSharp/Parser/mcs/anonymous.cs | 1989 + .../CSharp/Parser/mcs/argument.cs | 524 + .../CSharp/Parser/mcs/assembly.cs | 1173 + .../CSharp/Parser/mcs/assign.cs | 786 + .../CSharp/Parser/mcs/attribute.cs | 2120 + .../CSharp/Parser/mcs/cfold.cs | 1170 + .../CSharp/Parser/mcs/class.cs | 3525 ++ .../CSharp/Parser/mcs/codegen.cs | 640 + .../CSharp/Parser/mcs/compiler.doc | 116 + .../CSharp/Parser/mcs/complete.cs | 200 + .../CSharp/Parser/mcs/const.cs | 237 + .../CSharp/Parser/mcs/constant.cs | 2115 + .../CSharp/Parser/mcs/context.cs | 663 + .../CSharp/Parser/mcs/convert.cs | 2089 + .../CSharp/Parser/mcs/cs-parser.cs | 12547 ++++++ .../CSharp/Parser/mcs/cs-parser.jay | 6862 ++++ .../CSharp/Parser/mcs/cs-tokenizer.cs | 3511 ++ .../CSharp/Parser/mcs/decl.cs | 1516 + .../CSharp/Parser/mcs/delegate.cs | 768 + .../CSharp/Parser/mcs/dmcs.csproj | 154 + .../CSharp/Parser/mcs/dmcs.exe.config | 6 + .../CSharp/Parser/mcs/dmcs.exe.sources | 55 + .../CSharp/Parser/mcs/dmcs.sln | 20 + .../CSharp/Parser/mcs/doc-bootstrap.cs | 59 + .../CSharp/Parser/mcs/doc.cs | 934 + .../CSharp/Parser/mcs/driver.cs | 1689 + .../CSharp/Parser/mcs/dynamic.cs | 929 + .../CSharp/Parser/mcs/ecore.cs | 5910 +++ .../CSharp/Parser/mcs/enum.cs | 294 + .../CSharp/Parser/mcs/eval.cs | 1233 + .../CSharp/Parser/mcs/expression.cs | 9988 +++++ .../CSharp/Parser/mcs/field.cs | 676 + .../CSharp/Parser/mcs/flowanalysis.cs | 1760 + .../CSharp/Parser/mcs/generic.cs | 3242 ++ .../CSharp/Parser/mcs/gmcs.csproj | 111 + .../CSharp/Parser/mcs/gmcs.exe.config | 14 + .../CSharp/Parser/mcs/gmcs.exe.sources | 56 + .../CSharp/Parser/mcs/gmcs.sln | 20 + .../CSharp/Parser/mcs/gmcs.userprefs | 23 + .../CSharp/Parser/mcs/gmcs2.csproj | 29 + .../CSharp/Parser/mcs/hosting.cs | 0 .../CSharp/Parser/mcs/import.cs | 2067 + .../CSharp/Parser/mcs/iterators.cs | 945 + .../CSharp/Parser/mcs/lambda.cs | 224 + .../CSharp/Parser/mcs/lambda.todo | 24 + .../CSharp/Parser/mcs/linq.cs | 872 + .../CSharp/Parser/mcs/literal.cs | 239 + .../CSharp/Parser/mcs/location.cs | 904 + .../CSharp/Parser/mcs/membercache.cs | 1388 + .../CSharp/Parser/mcs/method.cs | 2616 ++ .../CSharp/Parser/mcs/modifiers.cs | 279 + .../CSharp/Parser/mcs/namespace.cs | 1236 + .../CSharp/Parser/mcs/nullable.cs | 1294 + .../CSharp/Parser/mcs/outline.cs | 1024 + .../CSharp/Parser/mcs/parameter.cs | 1263 + .../CSharp/Parser/mcs/pending.cs | 470 + .../CSharp/Parser/mcs/property.cs | 1679 + .../CSharp/Parser/mcs/reflection.cs | 575 + .../CSharp/Parser/mcs/repl.txt | 168 + .../CSharp/Parser/mcs/report.cs | 1214 + .../CSharp/Parser/mcs/rootcontext.cs | 264 + .../CSharp/Parser/mcs/roottypes.cs | 530 + .../CSharp/Parser/mcs/smcs.exe.sources | 53 + .../CSharp/Parser/mcs/smcs.exe.sources-xml | 384 + .../CSharp/Parser/mcs/statement.cs | 5956 +++ .../CSharp/Parser/mcs/support.cs | 305 + .../CSharp/Parser/mcs/symbolwriter.cs | 245 + .../CSharp/Parser/mcs/typemanager.cs | 929 + .../CSharp/Parser/mcs/typespec.cs | 1515 + .../CSharp/Parser/mcs/visit.cs | 590 + .../CSharp/Parser/mcs/y.output | 31920 +++++++++++++++ .../Resolver/AliasNamespaceReference.cs | 51 + .../CSharp/Resolver/AmbiguousResolveResult.cs | 33 + .../Resolver/ByReferenceResolveResult.cs | 32 + .../CSharp/Resolver/CSharpResolver.cs | 2083 + .../CSharp/Resolver/ConstantResolveResult.cs | 34 + .../CSharp/Resolver/Conversions.cs | 386 + .../CSharp/Resolver/ErrorResolveResult.cs | 22 + .../Resolver/IResolveVisitorNavigator.cs | 40 + .../Resolver/ITypeOrNamespaceReference.cs | 24 + .../CSharp/Resolver/LocalResolveResult.cs | 47 + .../CSharp/Resolver/MemberLookup.cs | 267 + .../CSharp/Resolver/MemberResolveResult.cs | 62 + .../MemberTypeOrNamespaceReference.cs | 68 + .../Resolver/MethodGroupResolveResult.cs | 61 + .../CSharp/Resolver/NamespaceResolveResult.cs | 30 + .../NodeListResolveVisitorNavigator.cs | 43 + .../CSharp/Resolver/OverloadResolution.cs | 550 + .../Resolver/OverloadResolutionErrors.cs | 54 + .../CSharp/Resolver/ResolveResult.cs | 45 + .../CSharp/Resolver/ResolveVisitor.cs | 1164 + .../SimpleTypeOrNamespaceReference.cs | 63 + .../CSharp/Resolver/TypeInference.cs | 920 + .../CSharp/Resolver/TypeResolveResult.cs | 19 + .../Resolver/UnknownMemberResolveResult.cs | 99 + .../CSharp/Resolver/UsingScope.cs | 150 + .../BinaryDocumentationProvider.cs | 231 + .../Documentation/XmlDocumentationProvider.cs | 179 + .../ICSharpCode.NRefactory.csproj | 337 + .../Properties/AssemblyInfo.cs | 31 + .../TypeSystem/Accessibility.cs | 46 + .../TypeSystem/ArrayType.cs | 173 + .../TypeSystem/ByReferenceType.cs | 82 + .../TypeSystem/CecilLoader.cs | 951 + .../TypeSystem/ClassType.cs | 17 + .../TypeSystem/DomRegion.cs | 139 + .../TypeSystem/EntityType.cs | 21 + .../TypeSystem/ExtensionMethods.cs | 219 + .../TypeSystem/IAccessor.cs | 29 + .../TypeSystem/IAttribute.cs | 66 + .../TypeSystem/IConstantValue.cs | 49 + .../TypeSystem/IConversions.cs | 16 + .../TypeSystem/IDocumentationProvider.cs | 19 + ICSharpCode.NRefactory/TypeSystem/IEntity.cs | 147 + ICSharpCode.NRefactory/TypeSystem/IEvent.cs | 19 + .../IExplicitInterfaceImplementation.cs | 43 + ICSharpCode.NRefactory/TypeSystem/IField.cs | 66 + .../TypeSystem/IFreezable.cs | 36 + .../TypeSystem/IInterningProvider.cs | 57 + ICSharpCode.NRefactory/TypeSystem/IMember.cs | 104 + ICSharpCode.NRefactory/TypeSystem/IMethod.cs | 73 + .../TypeSystem/INamedElement.cs | 97 + .../TypeSystem/IParameter.cs | 95 + .../TypeSystem/IParameterizedMember.cs | 29 + .../TypeSystem/IProjectContent.cs | 29 + .../TypeSystem/IProperty.cs | 21 + .../TypeSystem/ISupportsInterning.cs | 51 + .../ISynchronizedTypeResolveContext.cs | 27 + ICSharpCode.NRefactory/TypeSystem/IType.cs | 212 + .../TypeSystem/ITypeDefinition.cs | 184 + .../TypeSystem/ITypeParameter.cs | 181 + .../TypeSystem/ITypeReference.cs | 39 + .../TypeSystem/ITypeResolveContext.cs | 143 + .../TypeSystem/IVariable.cs | 65 + .../Implementation/AbstractFreezable.cs | 93 + .../Implementation/AbstractMember.cs | 273 + .../TypeSystem/Implementation/AbstractType.cs | 117 + .../CompositeTypeResolveContext.cs | 167 + .../Implementation/DefaultAccessor.cs | 94 + .../Implementation/DefaultAttribute.cs | 117 + .../TypeSystem/Implementation/DefaultEvent.cs | 75 + .../DefaultExplicitInterfaceImplementation.cs | 48 + .../TypeSystem/Implementation/DefaultField.cs | 76 + .../Implementation/DefaultMethod.cs | 131 + .../Implementation/DefaultParameter.cs | 196 + .../Implementation/DefaultProperty.cs | 83 + .../Implementation/DefaultTypeDefinition.cs | 600 + .../Implementation/DefaultTypeParameter.cs | 310 + .../Implementation/GetClassTypeReference.cs | 114 + .../MethodTypeParameterSubstitution.cs | 34 + .../Implementation/NestedTypeReference.cs | 76 + .../Implementation/ProxyTypeResolveContext.cs | 70 + .../Implementation/SimpleConstantValue.cs | 64 + .../Implementation/SimpleInterningProvider.cs | 129 + .../Implementation/SimpleProjectContent.cs | 208 + .../Implementation/SpecializedEvent.cs | 56 + .../Implementation/SpecializedField.cs | 56 + .../Implementation/SpecializedMethod.cs | 71 + .../Implementation/SpecializedProperty.cs | 71 + .../TypeSystem/Implementation/TypeStorage.cs | 295 + .../Implementation/TypeWithElementType.cs | 45 + .../Implementation/VoidTypeDefinition.cs | 47 + .../TypeSystem/IntersectionType.cs | 129 + .../TypeSystem/KnownTypeReference.cs | 103 + .../TypeSystem/NullableType.cs | 69 + .../TypeSystem/ParameterListComparer.cs | 38 + .../TypeSystem/ParameterizedType.cs | 448 + .../TypeSystem/PointerType.cs | 84 + .../TypeSystem/ReflectionHelper.cs | 407 + .../ReflectionNameParseException.cs | 45 + .../TypeSystem/SharedTypes.cs | 123 + .../TypeSystem/TypeVisitor.cs | 48 + ICSharpCode.NRefactory/Utils/BitVector16.cs | 65 + ICSharpCode.NRefactory/Utils/BusyManager.cs | 55 + .../Utils/CSharpPrimitiveCast.cs | 414 + ICSharpCode.NRefactory/Utils/CacheManager.cs | 137 + ICSharpCode.NRefactory/Utils/EmptyList.cs | 13 + .../Utils/ExtensionMethods.cs | 20 + ICSharpCode.NRefactory/Utils/TreeTraversal.cs | 97 + NRefactory.sln | 75 + README | 195 + VBDomGenerator/.gitignore | 3 + VBDomGenerator/AssemblyInfo.cs | 29 + VBDomGenerator/Attributes.cs | 176 + VBDomGenerator/Dom/Expressions.cs | 372 + VBDomGenerator/Dom/GlobalLevel.cs | 107 + VBDomGenerator/Dom/Node.cs | 68 + VBDomGenerator/Dom/Statements.cs | 262 + VBDomGenerator/Dom/TypeLevel.cs | 227 + VBDomGenerator/EasyCodeDom.cs | 382 + VBDomGenerator/KeywordGenerator.cs | 380 + VBDomGenerator/Main.cs | 591 + VBDomGenerator/VBDomGenerator.csproj | 63 + doc/TODO | 15 + doc/copyright.txt | 10 + doc/license.txt | 17 + 590 files changed, 270809 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 ICSharpCode.NRefactory.Demo/.gitignore create mode 100644 ICSharpCode.NRefactory.Demo/ICSharpCode.NRefactory.Demo.csproj create mode 100644 ICSharpCode.NRefactory.Demo/MainForm.Designer.cs create mode 100644 ICSharpCode.NRefactory.Demo/MainForm.cs create mode 100644 ICSharpCode.NRefactory.Demo/MainForm.resx create mode 100644 ICSharpCode.NRefactory.Demo/Program.cs create mode 100644 ICSharpCode.NRefactory.Demo/Properties/AssemblyInfo.cs create mode 100644 ICSharpCode.NRefactory.Demo/VBDemo.Designer.cs create mode 100644 ICSharpCode.NRefactory.Demo/VBDemo.cs create mode 100644 ICSharpCode.NRefactory.Demo/VBDemo.resx create mode 100644 ICSharpCode.NRefactory.Demo/VBDomView.Designer.cs create mode 100644 ICSharpCode.NRefactory.Demo/VBDomView.cs create mode 100644 ICSharpCode.NRefactory.Demo/VBDomView.resx create mode 100644 ICSharpCode.NRefactory.Demo/VBEditDialog.Designer.cs create mode 100644 ICSharpCode.NRefactory.Demo/VBEditDialog.cs create mode 100644 ICSharpCode.NRefactory.Demo/VBEditDialog.resx create mode 100644 ICSharpCode.NRefactory.Tests/.gitignore create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/AstStructureTest.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AliasReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AnonymousMethodTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ArrayObjectCreateExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AssignmentExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/BaseReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/BinaryOperatorExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/CastExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/CheckedExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ConditionalExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/DefaultValueExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IdentifierExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IndexerExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/InvocationExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IsExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/LambdaExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/MemberReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ParenthesizedExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/PointerReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/PrimitiveExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/QueryExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/SizeOfExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/StackAllocExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ThisReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/TypeOfExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/TypeReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/UnaryOperatorExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/AttributeSectionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/DelegateDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/NamespaceDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/TypeDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/UsingDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/ParseUtil.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/BlockStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/CheckedStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/EmptyStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ExpressionStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/FixedStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ForStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/GotoStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/IfElseStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/LabelStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/LockStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ReturnStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/SwitchStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ThrowStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/TryCatchStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/UnsafeStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/UsingStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/VariableDeclarationStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/WhileStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/YieldStatementTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/ConstructorDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/DestructorDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/EventDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/FieldDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/IndexerDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/MethodDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/OperatorDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/PropertyDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeSystemConvertVisitorTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/AttributeTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/BinaryOperatorTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/CastTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/ConversionsTest.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/ExtensionMethodTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/InvocationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/LambdaTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/LinqTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/LocalTypeInferenceTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/NameLookupTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/ObjectCreationTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/OverloadResolutionTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/ResolverTestBase.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/TypeInferenceTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/UnaryOperatorTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/CSharp/Resolver/UnsafeCodeTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/FormattingTests/TestBraceStlye.cs create mode 100644 ICSharpCode.NRefactory.Tests/FormattingTests/TestFormattingBugs.cs create mode 100644 ICSharpCode.NRefactory.Tests/FormattingTests/TestSpacingVisitor.cs create mode 100644 ICSharpCode.NRefactory.Tests/FormattingTests/TestStatementIndentation.cs create mode 100644 ICSharpCode.NRefactory.Tests/FormattingTests/TestTypeLevelIndentation.cs create mode 100644 ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj create mode 100644 ICSharpCode.NRefactory.Tests/Properties/AssemblyInfo.cs create mode 100644 ICSharpCode.NRefactory.Tests/TypeSystem/CecilLoaderTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/TypeSystem/GetAllBaseTypesTest.cs create mode 100644 ICSharpCode.NRefactory.Tests/TypeSystem/GetMembersTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/TypeSystem/ReflectionHelperTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/TypeSystem/TestInterningProvider.cs create mode 100644 ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemTests.TestCase.cs create mode 100644 ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/Untested.cs create mode 100644 ICSharpCode.NRefactory.Tests/Utils/CSharpPrimitiveCastTests.cs create mode 100644 ICSharpCode.NRefactory.Tests/Utils/TreeTraversalTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/.gitignore create mode 100644 ICSharpCode.NRefactory.VB.Tests/AssemblyInfo.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/General/UnitTest.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/ICSharpCode.NRefactory.VB.Tests.csproj create mode 100644 ICSharpCode.NRefactory.VB.Tests/Lexer/CustomLexerTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Lexer/ImplicitLineContinuationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Lexer/LATextReaderTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Lexer/LexerContextTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Lexer/LexerPositionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Lexer/LexerTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Lexer/LiteralsTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Lexer/TokenTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Lexer/XmlModeLexerTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMParenthesizedExpressionTest.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMPrimitiveExpressionTest.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMTypeReferenceTest.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/InvocationExpressionTest.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Output/SpecialOutputVisitorTest.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Output/VBNet/VBNetOutputTest.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/CheckParentVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/AddressOfExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ArrayCreateExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/AssignmentExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/BaseReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/BinaryOperatorExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/CastExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ClassReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ConditionalExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/GlobalReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/IdentifierExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/InvocationExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/LambdaExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/MemberReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ObjectCreateExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ParenthesizedExpressionTest.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/PrimitiveExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/QueryExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ThisReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeOfExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeOfIsExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeReferenceExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/UnaryOperatorExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/XmlExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/XmlMemberAccessExpressionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/AttributeSectionTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/DelegateDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/NamespaceDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/OptionDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/TypeDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/UsingDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/LocationAssignmentCheckVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/ParseUtil.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/SnippetParserTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/AddHandlerStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/BlockStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ContinueStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/DoLoopStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/EndStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/EraseStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ErrorStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ExpressionStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ForNextStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ForeachStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/GotoStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/IfElseStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LabelStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LocalVariableDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LockStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/OnErrorStatementTest.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/RaiseEventStatementTest.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ReDimStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/RemoveHandlerStatement.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ResumeStatement.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ReturnStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/StopStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/SwitchStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ThrowStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/TryCatchStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/UsingStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/Statements/WithStatementTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/ConstructorDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/CustomEventTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/DeclareDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/EventDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/FieldDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/MethodDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/OperatorDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/PropertyDeclarationTests.cs create mode 100644 ICSharpCode.NRefactory.VB/.gitignore create mode 100644 ICSharpCode.NRefactory.VB/Dom/AbstractNode.cs create mode 100644 ICSharpCode.NRefactory.VB/Dom/Enums.cs create mode 100644 ICSharpCode.NRefactory.VB/Dom/General/BlockStatement.cs create mode 100644 ICSharpCode.NRefactory.VB/Dom/General/CompilationUnit.cs create mode 100644 ICSharpCode.NRefactory.VB/Dom/General/Expression.cs create mode 100644 ICSharpCode.NRefactory.VB/Dom/General/LocalVariableDeclaration.cs create mode 100644 ICSharpCode.NRefactory.VB/Dom/General/PrimitiveExpression.cs create mode 100644 ICSharpCode.NRefactory.VB/Dom/General/Statement.cs create mode 100644 ICSharpCode.NRefactory.VB/Dom/Generated.cs create mode 100644 ICSharpCode.NRefactory.VB/Dom/INode.cs create mode 100644 ICSharpCode.NRefactory.VB/Dom/INullable.cs create mode 100644 ICSharpCode.NRefactory.VB/Dom/TypeReference.cs create mode 100644 ICSharpCode.NRefactory.VB/DomBuilder/ExpressionBuilder.cs create mode 100644 ICSharpCode.NRefactory.VB/DomBuilder/StatementBuilder.cs create mode 100644 ICSharpCode.NRefactory.VB/EnvironmentInformationProvider.cs create mode 100644 ICSharpCode.NRefactory.VB/ICSharpCode.NRefactory.VB.csproj create mode 100644 ICSharpCode.NRefactory.VB/IDomVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Block.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/ExpressionFinder.atg create mode 100644 ICSharpCode.NRefactory.VB/Lexer/ExpressionFinder.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/ExpressionFinderState.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Extensions.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/KeywordList.txt create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Keywords.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/LATextReader.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/LookupTable.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Parser.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/PushParser.frame create mode 100644 ICSharpCode.NRefactory.VB/Lexer/SavepointEventArgs.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Special/BlankLine.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Special/Comment.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Special/CommentType.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Special/ISpecial.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Special/PreProcessingDirective.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Special/SpecialTracker.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Special/TagComment.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Token.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/Tokens.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/VBLexer.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/VBLexerMemento.cs create mode 100644 ICSharpCode.NRefactory.VB/Lexer/XmlModeInfo.cs create mode 100644 ICSharpCode.NRefactory.VB/Location.cs create mode 100644 ICSharpCode.NRefactory.VB/OperatorPrecedence.cs create mode 100644 ICSharpCode.NRefactory.VB/Parser/Errors.cs create mode 100644 ICSharpCode.NRefactory.VB/Parser/ModifierList.cs create mode 100644 ICSharpCode.NRefactory.VB/Parser/ParamModifierList.cs create mode 100644 ICSharpCode.NRefactory.VB/Parser/Parser.cs create mode 100644 ICSharpCode.NRefactory.VB/Parser/Parser.frame create mode 100644 ICSharpCode.NRefactory.VB/Parser/VBParser.cs create mode 100644 ICSharpCode.NRefactory.VB/Parser/vb.atg create mode 100644 ICSharpCode.NRefactory.VB/ParserFactory.cs create mode 100644 ICSharpCode.NRefactory.VB/PrettyPrinter/AbstractOutputFormatter.cs create mode 100644 ICSharpCode.NRefactory.VB/PrettyPrinter/AbstractPrettyPrintOptions.cs create mode 100644 ICSharpCode.NRefactory.VB/PrettyPrinter/IOutputAstVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB/PrettyPrinter/SpecialNodesInserter.cs create mode 100644 ICSharpCode.NRefactory.VB/PrettyPrinter/VBNet/VBNetOutputFormatter.cs create mode 100644 ICSharpCode.NRefactory.VB/PrettyPrinter/VBNet/VBNetOutputVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB/PrettyPrinter/VBNet/VBNetPrettyPrintOptions.cs create mode 100644 ICSharpCode.NRefactory.VB/Properties/AssemblyInfo.cs create mode 100644 ICSharpCode.NRefactory.VB/SnippetParser.cs create mode 100644 ICSharpCode.NRefactory.VB/Visitors/AbstractDomTransformer.cs create mode 100644 ICSharpCode.NRefactory.VB/Visitors/AbstractDomVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB/Visitors/CodeDOMOutputVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB/Visitors/CodeDOMVerboseOutputGenerator.cs create mode 100644 ICSharpCode.NRefactory.VB/Visitors/LookupTableVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB/Visitors/NodeTrackingDomVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB/Visitors/NotImplementedDomVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB/Visitors/PrefixFieldsVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB/Visitors/RenameIdentifierVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB/Visitors/SetParentVisitor.cs create mode 100644 ICSharpCode.NRefactory.VB/Visitors/SetRegionInclusionVisitor.cs create mode 100644 ICSharpCode.NRefactory/.gitignore create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/AstLocation.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/AstNode.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/AstType.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/CSharpModifierToken.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/CSharpTokenNode.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/CompilationUnit.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/ComposedType.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/DepthFirstAstVisitor.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/AnonymousMethodExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/ArgListExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/ArrayCreateExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/ArrayInitializerExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/AsExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/AssignmentExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/BaseReferenceExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/BinaryOperatorExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/CastExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/CheckedExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/ConditionalExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/DefaultValueExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/DirectionExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/Expression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/IdentifierExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/IndexerExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/InvocationExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/IsExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/LambdaExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/MemberReferenceExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/NamedArgumentExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/NullReferenceExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/ObjectCreateExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/ParenthesizedExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/PointerReferenceExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/PrimitiveExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/QueryExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/SizeOfExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/StackAllocExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/ThisReferenceExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/TypeOfExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/UnaryOperatorExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Expressions/UncheckedExpression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/GeneralScope/Attribute.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/GeneralScope/AttributeSection.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/GeneralScope/Comment.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/GeneralScope/Constraint.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/GeneralScope/DelegateDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/GeneralScope/NamespaceDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/GeneralScope/TypeDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/GeneralScope/TypeParameterDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/GeneralScope/UsingAliasDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/GeneralScope/UsingDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/IAstVisitor.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Identifier.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/MemberType.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Modifiers.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/NodeType.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/PrimitiveType.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Role.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/SimpleType.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/BlockStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/BreakStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/CheckedStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/ContinueStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/EmptyStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/ExpressionStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/FixedStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/ForStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/ForeachStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/GotoStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/IfElseStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/LabelStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/LockStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/ReturnStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/Statement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/SwitchStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/ThrowStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/TryCatchStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/UncheckedStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/UnsafeStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/UsingStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/VariableDeclarationStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/WhileStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/Statements/YieldStatement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/Accessor.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/AttributedNode.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/ConstructorDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/DestructorDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/EnumMemberDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/EventDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/FieldDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/IndexerDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/MemberDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/MethodDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/OperatorDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/ParameterDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/PropertyDeclaration.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Ast/TypeMembers/VariableInitializer.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Formatter/CSharpFormattingPolicy.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Formatter/DomIndentationVisitor.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Formatter/DomSpacingVisitor.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Formatter/Indent.cs create mode 100644 ICSharpCode.NRefactory/CSharp/OutputVisitor/IOutputFormatter.cs create mode 100644 ICSharpCode.NRefactory/CSharp/OutputVisitor/OutputVisitor.cs create mode 100644 ICSharpCode.NRefactory/CSharp/OutputVisitor/TextWriterOutputFormatter.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/CSharpParser.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/ParsedFile.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/TypeSystemConvertVisitor.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/AssemblyInfo.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/ChangeLog create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/CryptoConvert.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/Makefile create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/MonoSymbolFile.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/MonoSymbolTable.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/MonoSymbolWriter.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/NOTES create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/OPTIMIZE create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/OTODO create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/PLAN create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/README create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/TODO create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/anonymous.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/argument.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/assembly.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/assign.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/attribute.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/cfold.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/class.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/codegen.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/compiler.doc create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/complete.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/const.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/constant.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/context.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/convert.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/cs-parser.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/cs-parser.jay create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/cs-tokenizer.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/decl.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/delegate.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/dmcs.csproj create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/dmcs.exe.config create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/dmcs.exe.sources create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/dmcs.sln create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/doc-bootstrap.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/doc.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/driver.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/dynamic.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/ecore.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/enum.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/eval.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/expression.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/field.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/flowanalysis.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/generic.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/gmcs.csproj create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/gmcs.exe.config create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/gmcs.exe.sources create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/gmcs.sln create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/gmcs.userprefs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/gmcs2.csproj create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/hosting.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/import.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/iterators.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/lambda.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/lambda.todo create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/linq.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/literal.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/location.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/membercache.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/method.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/modifiers.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/namespace.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/nullable.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/outline.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/parameter.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/pending.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/property.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/reflection.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/repl.txt create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/report.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/rootcontext.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/roottypes.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/smcs.exe.sources create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/smcs.exe.sources-xml create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/statement.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/support.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/symbolwriter.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/typemanager.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/typespec.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/visit.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Parser/mcs/y.output create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/AliasNamespaceReference.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/AmbiguousResolveResult.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/ByReferenceResolveResult.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/CSharpResolver.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/ConstantResolveResult.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/Conversions.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/ErrorResolveResult.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/IResolveVisitorNavigator.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/ITypeOrNamespaceReference.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/LocalResolveResult.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/MemberLookup.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/MemberResolveResult.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/MemberTypeOrNamespaceReference.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/MethodGroupResolveResult.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/NamespaceResolveResult.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/NodeListResolveVisitorNavigator.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/OverloadResolution.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/OverloadResolutionErrors.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/ResolveResult.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/ResolveVisitor.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/SimpleTypeOrNamespaceReference.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/TypeInference.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/TypeResolveResult.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/UnknownMemberResolveResult.cs create mode 100644 ICSharpCode.NRefactory/CSharp/Resolver/UsingScope.cs create mode 100644 ICSharpCode.NRefactory/Documentation/BinaryDocumentationProvider.cs create mode 100644 ICSharpCode.NRefactory/Documentation/XmlDocumentationProvider.cs create mode 100644 ICSharpCode.NRefactory/ICSharpCode.NRefactory.csproj create mode 100644 ICSharpCode.NRefactory/Properties/AssemblyInfo.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Accessibility.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ArrayType.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ByReferenceType.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/CecilLoader.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ClassType.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/DomRegion.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/EntityType.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ExtensionMethods.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IAccessor.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IAttribute.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IConstantValue.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IConversions.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IDocumentationProvider.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IEntity.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IEvent.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IExplicitInterfaceImplementation.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IField.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IFreezable.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IInterningProvider.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IMember.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IMethod.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/INamedElement.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IParameter.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IParameterizedMember.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IProjectContent.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IProperty.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ISupportsInterning.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ISynchronizedTypeResolveContext.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IType.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ITypeDefinition.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ITypeParameter.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ITypeReference.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ITypeResolveContext.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IVariable.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractFreezable.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractMember.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractType.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/CompositeTypeResolveContext.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAccessor.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAttribute.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultEvent.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultExplicitInterfaceImplementation.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultField.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultMethod.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultParameter.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultProperty.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultTypeDefinition.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultTypeParameter.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/GetClassTypeReference.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/MethodTypeParameterSubstitution.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/NestedTypeReference.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/ProxyTypeResolveContext.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleConstantValue.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleInterningProvider.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleProjectContent.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/SpecializedEvent.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/SpecializedField.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/SpecializedMethod.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/SpecializedProperty.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/TypeStorage.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/TypeWithElementType.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/Implementation/VoidTypeDefinition.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/IntersectionType.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/KnownTypeReference.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/NullableType.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ParameterListComparer.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ParameterizedType.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/PointerType.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ReflectionHelper.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/ReflectionNameParseException.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/SharedTypes.cs create mode 100644 ICSharpCode.NRefactory/TypeSystem/TypeVisitor.cs create mode 100644 ICSharpCode.NRefactory/Utils/BitVector16.cs create mode 100644 ICSharpCode.NRefactory/Utils/BusyManager.cs create mode 100644 ICSharpCode.NRefactory/Utils/CSharpPrimitiveCast.cs create mode 100644 ICSharpCode.NRefactory/Utils/CacheManager.cs create mode 100644 ICSharpCode.NRefactory/Utils/EmptyList.cs create mode 100644 ICSharpCode.NRefactory/Utils/ExtensionMethods.cs create mode 100644 ICSharpCode.NRefactory/Utils/TreeTraversal.cs create mode 100644 NRefactory.sln create mode 100644 README create mode 100644 VBDomGenerator/.gitignore create mode 100644 VBDomGenerator/AssemblyInfo.cs create mode 100644 VBDomGenerator/Attributes.cs create mode 100644 VBDomGenerator/Dom/Expressions.cs create mode 100644 VBDomGenerator/Dom/GlobalLevel.cs create mode 100644 VBDomGenerator/Dom/Node.cs create mode 100644 VBDomGenerator/Dom/Statements.cs create mode 100644 VBDomGenerator/Dom/TypeLevel.cs create mode 100644 VBDomGenerator/EasyCodeDom.cs create mode 100644 VBDomGenerator/KeywordGenerator.cs create mode 100644 VBDomGenerator/Main.cs create mode 100644 VBDomGenerator/VBDomGenerator.csproj create mode 100644 doc/TODO create mode 100644 doc/copyright.txt create mode 100644 doc/license.txt diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..1a1533024 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.sln -crlf +*.csproj -crlf \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..a5807eb16 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/lib/*.dll +/ICSharpCode.NRefactory.Tests/PartCover/* \ No newline at end of file diff --git a/ICSharpCode.NRefactory.Demo/.gitignore b/ICSharpCode.NRefactory.Demo/.gitignore new file mode 100644 index 000000000..9ce745d95 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/.gitignore @@ -0,0 +1,3 @@ + +bin/ +obj/ \ No newline at end of file diff --git a/ICSharpCode.NRefactory.Demo/ICSharpCode.NRefactory.Demo.csproj b/ICSharpCode.NRefactory.Demo/ICSharpCode.NRefactory.Demo.csproj new file mode 100644 index 000000000..36ea620c6 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/ICSharpCode.NRefactory.Demo.csproj @@ -0,0 +1,87 @@ + + + + {9C19E629-C93E-4ACB-9A4B-13072B5AEF9D} + Debug + x86 + WinExe + ICSharpCode.NRefactory.Demo + ICSharpCode.NRefactory.Demo + v4.0 + Client + Properties + + + x86 + + + bin\Debug\ + True + Full + False + True + DEBUG;TRACE + + + bin\Release\ + False + None + True + False + TRACE + + + + + 3.5 + + + + + + + + + VBEditDialog.cs + + + + VBDomView.cs + + + + MainForm.cs + + + + + + VBDemo.cs + + + + + {7B82B671-419F-45F4-B778-D9286F996EFA} + ICSharpCode.NRefactory.VB + + + {3B2A5653-EC97-4001-BB9B-D90F1AF2C371} + ICSharpCode.NRefactory + + + + + VBEditDialog.cs + + + VBDomView.cs + + + MainForm.cs + + + VBDemo.cs + + + + \ No newline at end of file diff --git a/ICSharpCode.NRefactory.Demo/MainForm.Designer.cs b/ICSharpCode.NRefactory.Demo/MainForm.Designer.cs new file mode 100644 index 000000000..c24f304ab --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/MainForm.Designer.cs @@ -0,0 +1,221 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) +namespace ICSharpCode.NRefactory.Demo +{ + partial class MainForm + { + /// + /// Designer variable used to keep track of non-visual components. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Disposes resources used by the form. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing) { + if (components != null) { + components.Dispose(); + } + } + base.Dispose(disposing); + } + + /// + /// This method is required for Windows Forms designer support. + /// Do not change the method contents inside the source code editor. The Forms designer might + /// not be able to load this method if it was changed manually. + /// + private void InitializeComponent() + { + this.tabPage2 = new System.Windows.Forms.TabPage(); + this.tabPage1 = new System.Windows.Forms.TabPage(); + this.splitContainer1 = new System.Windows.Forms.SplitContainer(); + this.csharpCodeTextBox = new System.Windows.Forms.TextBox(); + this.resolveButton = new System.Windows.Forms.Button(); + this.csharpTreeView = new System.Windows.Forms.TreeView(); + this.csharpGenerateCodeButton = new System.Windows.Forms.Button(); + this.csharpParseButton = new System.Windows.Forms.Button(); + this.tabControl1 = new System.Windows.Forms.TabControl(); + this.miniToolStrip = new System.Windows.Forms.ToolStrip(); + this.vbDemo1 = new ICSharpCode.NRefactory.Demo.VBDemo(); + this.tabPage2.SuspendLayout(); + this.tabPage1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); + this.splitContainer1.Panel1.SuspendLayout(); + this.splitContainer1.Panel2.SuspendLayout(); + this.splitContainer1.SuspendLayout(); + this.tabControl1.SuspendLayout(); + this.SuspendLayout(); + // + // tabPage2 + // + this.tabPage2.Controls.Add(this.vbDemo1); + this.tabPage2.Location = new System.Drawing.Point(4, 22); + this.tabPage2.Name = "tabPage2"; + this.tabPage2.Padding = new System.Windows.Forms.Padding(3); + this.tabPage2.Size = new System.Drawing.Size(507, 458); + this.tabPage2.TabIndex = 1; + this.tabPage2.Text = "VB"; + this.tabPage2.UseVisualStyleBackColor = true; + // + // tabPage1 + // + this.tabPage1.Controls.Add(this.splitContainer1); + this.tabPage1.Location = new System.Drawing.Point(4, 22); + this.tabPage1.Name = "tabPage1"; + this.tabPage1.Padding = new System.Windows.Forms.Padding(3); + this.tabPage1.Size = new System.Drawing.Size(507, 458); + this.tabPage1.TabIndex = 0; + this.tabPage1.Text = "C#"; + this.tabPage1.UseVisualStyleBackColor = true; + // + // splitContainer1 + // + this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; + this.splitContainer1.Location = new System.Drawing.Point(3, 3); + this.splitContainer1.Name = "splitContainer1"; + this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; + // + // splitContainer1.Panel1 + // + this.splitContainer1.Panel1.Controls.Add(this.csharpCodeTextBox); + // + // splitContainer1.Panel2 + // + this.splitContainer1.Panel2.Controls.Add(this.resolveButton); + this.splitContainer1.Panel2.Controls.Add(this.csharpTreeView); + this.splitContainer1.Panel2.Controls.Add(this.csharpGenerateCodeButton); + this.splitContainer1.Panel2.Controls.Add(this.csharpParseButton); + this.splitContainer1.Size = new System.Drawing.Size(501, 452); + this.splitContainer1.SplitterDistance = 201; + this.splitContainer1.TabIndex = 0; + // + // csharpCodeTextBox + // + this.csharpCodeTextBox.AcceptsReturn = true; + this.csharpCodeTextBox.AcceptsTab = true; + this.csharpCodeTextBox.Dock = System.Windows.Forms.DockStyle.Fill; + this.csharpCodeTextBox.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.csharpCodeTextBox.HideSelection = false; + this.csharpCodeTextBox.Location = new System.Drawing.Point(0, 0); + this.csharpCodeTextBox.Multiline = true; + this.csharpCodeTextBox.Name = "csharpCodeTextBox"; + this.csharpCodeTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both; + this.csharpCodeTextBox.Size = new System.Drawing.Size(501, 201); + this.csharpCodeTextBox.TabIndex = 0; + this.csharpCodeTextBox.Text = "using System;\r\nclass Test\r\n{\r\n public void Main(string[] args)\r\n {\r\n " + + " Console.WriteLine(\"Hello, World\");\r\n }\r\n}"; + this.csharpCodeTextBox.WordWrap = false; + this.csharpCodeTextBox.TextChanged += new System.EventHandler(this.CsharpCodeTextBoxTextChanged); + this.csharpCodeTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.CSharpCodeTextBoxKeyDown); + // + // resolveButton + // + this.resolveButton.Anchor = System.Windows.Forms.AnchorStyles.Top; + this.resolveButton.Location = new System.Drawing.Point(200, 3); + this.resolveButton.Name = "resolveButton"; + this.resolveButton.Size = new System.Drawing.Size(100, 23); + this.resolveButton.TabIndex = 3; + this.resolveButton.Text = "Resolve"; + this.resolveButton.UseVisualStyleBackColor = true; + this.resolveButton.Click += new System.EventHandler(this.ResolveButtonClick); + // + // csharpTreeView + // + this.csharpTreeView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.csharpTreeView.HideSelection = false; + this.csharpTreeView.Location = new System.Drawing.Point(3, 32); + this.csharpTreeView.Name = "csharpTreeView"; + this.csharpTreeView.Size = new System.Drawing.Size(493, 212); + this.csharpTreeView.TabIndex = 2; + this.csharpTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.CSharpTreeViewAfterSelect); + // + // csharpGenerateCodeButton + // + this.csharpGenerateCodeButton.Anchor = System.Windows.Forms.AnchorStyles.Top; + this.csharpGenerateCodeButton.Location = new System.Drawing.Point(306, 2); + this.csharpGenerateCodeButton.Name = "csharpGenerateCodeButton"; + this.csharpGenerateCodeButton.Size = new System.Drawing.Size(100, 23); + this.csharpGenerateCodeButton.TabIndex = 1; + this.csharpGenerateCodeButton.Text = "Generate"; + this.csharpGenerateCodeButton.UseVisualStyleBackColor = true; + this.csharpGenerateCodeButton.Click += new System.EventHandler(this.CSharpGenerateCodeButtonClick); + // + // csharpParseButton + // + this.csharpParseButton.Anchor = System.Windows.Forms.AnchorStyles.Top; + this.csharpParseButton.Location = new System.Drawing.Point(94, 3); + this.csharpParseButton.Name = "csharpParseButton"; + this.csharpParseButton.Size = new System.Drawing.Size(100, 23); + this.csharpParseButton.TabIndex = 0; + this.csharpParseButton.Text = "Parse"; + this.csharpParseButton.UseVisualStyleBackColor = true; + this.csharpParseButton.Click += new System.EventHandler(this.CSharpParseButtonClick); + // + // tabControl1 + // + this.tabControl1.Controls.Add(this.tabPage1); + this.tabControl1.Controls.Add(this.tabPage2); + this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; + this.tabControl1.Location = new System.Drawing.Point(0, 0); + this.tabControl1.Name = "tabControl1"; + this.tabControl1.SelectedIndex = 0; + this.tabControl1.Size = new System.Drawing.Size(515, 484); + this.tabControl1.TabIndex = 0; + // + // miniToolStrip + // + this.miniToolStrip.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.miniToolStrip.AutoSize = false; + this.miniToolStrip.CanOverflow = false; + this.miniToolStrip.Dock = System.Windows.Forms.DockStyle.None; + this.miniToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; + this.miniToolStrip.Location = new System.Drawing.Point(13, 3); + this.miniToolStrip.Name = "miniToolStrip"; + this.miniToolStrip.Size = new System.Drawing.Size(16, 25); + this.miniToolStrip.TabIndex = 3; + // + // vbDemo1 + // + this.vbDemo1.Dock = System.Windows.Forms.DockStyle.Fill; + this.vbDemo1.Location = new System.Drawing.Point(3, 3); + this.vbDemo1.Name = "vbDemo1"; + this.vbDemo1.Size = new System.Drawing.Size(501, 452); + this.vbDemo1.TabIndex = 0; + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(515, 484); + this.Controls.Add(this.tabControl1); + this.Name = "MainForm"; + this.Text = "NRefactory Demo"; + this.tabPage2.ResumeLayout(false); + this.tabPage1.ResumeLayout(false); + this.splitContainer1.Panel1.ResumeLayout(false); + this.splitContainer1.Panel1.PerformLayout(); + this.splitContainer1.Panel2.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); + this.splitContainer1.ResumeLayout(false); + this.tabControl1.ResumeLayout(false); + this.ResumeLayout(false); + } + private ICSharpCode.NRefactory.Demo.VBDemo vbDemo1; + private System.Windows.Forms.Button resolveButton; + private System.Windows.Forms.ToolStrip miniToolStrip; + private System.Windows.Forms.TreeView csharpTreeView; + private System.Windows.Forms.Button csharpParseButton; + private System.Windows.Forms.Button csharpGenerateCodeButton; + private System.Windows.Forms.TextBox csharpCodeTextBox; + private System.Windows.Forms.SplitContainer splitContainer1; + private System.Windows.Forms.TabPage tabPage2; + private System.Windows.Forms.TabPage tabPage1; + private System.Windows.Forms.TabControl tabControl1; + } +} diff --git a/ICSharpCode.NRefactory.Demo/MainForm.cs b/ICSharpCode.NRefactory.Demo/MainForm.cs new file mode 100644 index 000000000..43627de73 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/MainForm.cs @@ -0,0 +1,228 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using ICSharpCode.NRefactory.CSharp; +using ICSharpCode.NRefactory.CSharp.Resolver; +using ICSharpCode.NRefactory.TypeSystem; +using ICSharpCode.NRefactory.TypeSystem.Implementation; + +namespace ICSharpCode.NRefactory.Demo +{ + /// + /// Description of MainForm. + /// + public partial class MainForm : Form + { + public MainForm() + { + // + // The InitializeComponent() call is required for Windows Forms designer support. + // + InitializeComponent(); + + csharpCodeTextBox.SelectAll(); + CSharpParseButtonClick(null, null); + resolveButton.UseWaitCursor = true; + ThreadPool.QueueUserWorkItem( + delegate { + builtInLibs.Value.ToString(); + BeginInvoke(new Action(delegate { resolveButton.UseWaitCursor = false; })); + }); + } + + CompilationUnit compilationUnit; + + void CSharpParseButtonClick(object sender, EventArgs e) + { + CSharpParser parser = new CSharpParser(); + compilationUnit = parser.Parse(new StringReader(csharpCodeTextBox.Text)); + csharpTreeView.Nodes.Clear(); + foreach (var element in compilationUnit.Children) { + csharpTreeView.Nodes.Add(MakeTreeNode(element)); + } + SelectCurrentNode(csharpTreeView.Nodes); + resolveButton.Enabled = true; + } + + TreeNode MakeTreeNode(AstNode node) + { + TreeNode t = new TreeNode(GetNodeTitle(node)); + t.Tag = node; + foreach (AstNode child in node.Children) { + t.Nodes.Add(MakeTreeNode(child)); + } + return t; + } + + string GetNodeTitle(AstNode node) + { + StringBuilder b = new StringBuilder(); + b.Append(node.Role.ToString()); + b.Append(": "); + b.Append(node.GetType().Name); + bool hasProperties = false; + foreach (PropertyInfo p in node.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { + if (p.Name == "NodeType" || p.Name == "IsNull") + continue; + if (p.PropertyType == typeof(string) || p.PropertyType.IsEnum || p.PropertyType == typeof(bool)) { + if (!hasProperties) { + hasProperties = true; + b.Append(" ("); + } else { + b.Append(", "); + } + b.Append(p.Name); + b.Append(" = "); + try { + object val = p.GetValue(node, null); + b.Append(val != null ? val.ToString() : "**null**"); + } catch (TargetInvocationException ex) { + b.Append("**" + ex.InnerException.GetType().Name + "**"); + } + } + } + if (hasProperties) + b.Append(")"); + return b.ToString(); + } + + bool SelectCurrentNode(TreeNodeCollection c) + { + int selectionStart = csharpCodeTextBox.SelectionStart; + int selectionEnd = selectionStart + csharpCodeTextBox.SelectionLength; + foreach (TreeNode t in c) { + AstNode node = t.Tag as AstNode; + if (node != null + && selectionStart >= GetOffset(csharpCodeTextBox, node.StartLocation) + && selectionEnd <= GetOffset(csharpCodeTextBox, node.EndLocation)) + { + if (selectionStart == selectionEnd + && (selectionStart == GetOffset(csharpCodeTextBox, node.StartLocation) + || selectionStart == GetOffset(csharpCodeTextBox, node.EndLocation))) + { + // caret is on border of this node; don't expand + csharpTreeView.SelectedNode = t; + } else { + t.Expand(); + if (!SelectCurrentNode(t.Nodes)) + csharpTreeView.SelectedNode = t; + } + return true; + } + } + return false; + } + + void CSharpGenerateCodeButtonClick(object sender, EventArgs e) + { + StringWriter w = new StringWriter(); + OutputVisitor output = new OutputVisitor(w, new CSharpFormattingPolicy()); + compilationUnit.AcceptVisitor(output, null); + csharpCodeTextBox.Text = w.ToString(); + } + + int GetOffset(TextBox textBox, AstLocation location) + { + return textBox.GetFirstCharIndexFromLine(location.Line - 1) + location.Column - 1; + } + + void CSharpTreeViewAfterSelect(object sender, TreeViewEventArgs e) + { + AstNode node = e.Node.Tag as AstNode; + if (node != null) { + int startOffset = GetOffset(csharpCodeTextBox, node.StartLocation); + int endOffset = GetOffset(csharpCodeTextBox, node.EndLocation); + csharpCodeTextBox.Select(startOffset, endOffset - startOffset); + } + } + + Lazy> builtInLibs = new Lazy>( + delegate { + Assembly[] assemblies = { + typeof(object).Assembly, // mscorlib + typeof(Uri).Assembly, // System.dll + typeof(System.Linq.Enumerable).Assembly, // System.Core.dll +// typeof(System.Xml.XmlDocument).Assembly, // System.Xml.dll +// typeof(System.Drawing.Bitmap).Assembly, // System.Drawing.dll +// typeof(Form).Assembly, // System.Windows.Forms.dll + typeof(ICSharpCode.NRefactory.TypeSystem.IProjectContent).Assembly, + }; + IProjectContent[] projectContents = new IProjectContent[assemblies.Length]; + Stopwatch total = Stopwatch.StartNew(); + Parallel.For( + 0, assemblies.Length, + delegate (int i) { + Stopwatch w = Stopwatch.StartNew(); + CecilLoader loader = new CecilLoader(); + projectContents[i] = loader.LoadAssemblyFile(assemblies[i].Location); + Debug.WriteLine(Path.GetFileName(assemblies[i].Location) + ": " + w.Elapsed); + }); + Debug.WriteLine("Total: " + total.Elapsed); + return projectContents; + }); + + void ResolveButtonClick(object sender, EventArgs e) + { + SimpleProjectContent project = new SimpleProjectContent(); + TypeSystemConvertVisitor convertVisitor = new TypeSystemConvertVisitor(project, "dummy.cs"); + compilationUnit.AcceptVisitor(convertVisitor, null); + project.UpdateProjectContent(null, convertVisitor.ParsedFile.TopLevelTypeDefinitions, null, null); + + List projects = new List(); + projects.Add(project); + projects.AddRange(builtInLibs.Value); + + using (var context = new CompositeTypeResolveContext(projects).Synchronize()) { + CSharpResolver resolver = new CSharpResolver(context); + + IResolveVisitorNavigator navigator = null; + if (csharpTreeView.SelectedNode != null) { + navigator = new NodeListResolveVisitorNavigator(new[] { (AstNode)csharpTreeView.SelectedNode.Tag }); + } + ResolveVisitor visitor = new ResolveVisitor(resolver, convertVisitor.ParsedFile, navigator); + visitor.Scan(compilationUnit); + csharpTreeView.BeginUpdate(); + ShowResolveResultsInTree(csharpTreeView.Nodes, visitor); + csharpTreeView.EndUpdate(); + } + } + + void ShowResolveResultsInTree(TreeNodeCollection c, ResolveVisitor v) + { + foreach (TreeNode t in c) { + AstNode node = t.Tag as AstNode; + if (node != null) { + ResolveResult rr = v.GetResolveResult(node); + if (rr != null) + t.Text = GetNodeTitle(node) + " " + rr.ToString(); + else + t.Text = GetNodeTitle(node); + } + ShowResolveResultsInTree(t.Nodes, v); + } + } + + void CSharpCodeTextBoxKeyDown(object sender, KeyEventArgs e) + { + if (e.Control && e.KeyCode == Keys.A) { + e.Handled = true; + csharpCodeTextBox.SelectAll(); + } + } + + void CsharpCodeTextBoxTextChanged(object sender, EventArgs e) + { + resolveButton.Enabled = false; + } + } +} diff --git a/ICSharpCode.NRefactory.Demo/MainForm.resx b/ICSharpCode.NRefactory.Demo/MainForm.resx new file mode 100644 index 000000000..38d0f5c16 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/MainForm.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/ICSharpCode.NRefactory.Demo/Program.cs b/ICSharpCode.NRefactory.Demo/Program.cs new file mode 100644 index 000000000..7c176b1aa --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/Program.cs @@ -0,0 +1,25 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Windows.Forms; + +namespace ICSharpCode.NRefactory.Demo +{ + /// + /// Class with program entry point. + /// + internal sealed class Program + { + /// + /// Program entry point. + /// + [STAThread] + private static void Main(string[] args) + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm()); + } + } +} diff --git a/ICSharpCode.NRefactory.Demo/Properties/AssemblyInfo.cs b/ICSharpCode.NRefactory.Demo/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..2027632f7 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/Properties/AssemblyInfo.cs @@ -0,0 +1,31 @@ +#region Using directives + +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +#endregion + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ICSharpCode.NRefactory.Demo")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ICSharpCode.NRefactory.Demo")] +[assembly: AssemblyCopyright("Copyright 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all the values or you can use the default the Revision and +// Build Numbers by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.*")] diff --git a/ICSharpCode.NRefactory.Demo/VBDemo.Designer.cs b/ICSharpCode.NRefactory.Demo/VBDemo.Designer.cs new file mode 100644 index 000000000..88644b236 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/VBDemo.Designer.cs @@ -0,0 +1,163 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +namespace ICSharpCode.NRefactory.Demo +{ + partial class VBDemo + { + /// + /// Designer variable used to keep track of non-visual components. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Disposes resources used by the control. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing) { + if (components != null) { + components.Dispose(); + } + } + base.Dispose(disposing); + } + + /// + /// This method is required for Windows Forms designer support. + /// Do not change the method contents inside the source code editor. The Forms designer might + /// not be able to load this method if it was changed manually. + /// + private void InitializeComponent() + { + this.splitContainer1 = new System.Windows.Forms.SplitContainer(); + this.codeView = new System.Windows.Forms.TextBox(); + this.editNodeButton = new System.Windows.Forms.Button(); + this.clearSpecialsButton = new System.Windows.Forms.Button(); + this.syntaxTree = new ICSharpCode.NRefactory.Demo.VBDomView(); + this.generateCodeButton = new System.Windows.Forms.Button(); + this.parseButton = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); + this.splitContainer1.Panel1.SuspendLayout(); + this.splitContainer1.Panel2.SuspendLayout(); + this.splitContainer1.SuspendLayout(); + this.SuspendLayout(); + // + // splitContainer1 + // + this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; + this.splitContainer1.Location = new System.Drawing.Point(0, 0); + this.splitContainer1.Name = "splitContainer1"; + this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; + // + // splitContainer1.Panel1 + // + this.splitContainer1.Panel1.Controls.Add(this.codeView); + // + // splitContainer1.Panel2 + // + this.splitContainer1.Panel2.Controls.Add(this.editNodeButton); + this.splitContainer1.Panel2.Controls.Add(this.clearSpecialsButton); + this.splitContainer1.Panel2.Controls.Add(this.syntaxTree); + this.splitContainer1.Panel2.Controls.Add(this.generateCodeButton); + this.splitContainer1.Panel2.Controls.Add(this.parseButton); + this.splitContainer1.Size = new System.Drawing.Size(462, 391); + this.splitContainer1.SplitterDistance = 173; + this.splitContainer1.TabIndex = 1; + // + // codeView + // + this.codeView.AcceptsReturn = true; + this.codeView.AcceptsTab = true; + this.codeView.Dock = System.Windows.Forms.DockStyle.Fill; + this.codeView.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.codeView.HideSelection = false; + this.codeView.Location = new System.Drawing.Point(0, 0); + this.codeView.Multiline = true; + this.codeView.Name = "codeView"; + this.codeView.ScrollBars = System.Windows.Forms.ScrollBars.Both; + this.codeView.Size = new System.Drawing.Size(462, 173); + this.codeView.TabIndex = 0; + this.codeView.Text = "Imports System\r\nClass Test\r\n Public Sub Main(ByVal args As String())\r\n " + + " Console.WriteLine(\"Hello, World\")\r\n End Sub\r\nEnd Class"; + this.codeView.WordWrap = false; + // + // editNodeButton + // + this.editNodeButton.Anchor = System.Windows.Forms.AnchorStyles.Top; + this.editNodeButton.Location = new System.Drawing.Point(331, 2); + this.editNodeButton.Name = "editNodeButton"; + this.editNodeButton.Size = new System.Drawing.Size(100, 23); + this.editNodeButton.TabIndex = 4; + this.editNodeButton.Text = "Edit node"; + this.editNodeButton.UseVisualStyleBackColor = true; + this.editNodeButton.Click += new System.EventHandler(this.EditNodeButtonClick); + // + // clearSpecialsButton + // + this.clearSpecialsButton.Anchor = System.Windows.Forms.AnchorStyles.Top; + this.clearSpecialsButton.Location = new System.Drawing.Point(225, 2); + this.clearSpecialsButton.Name = "clearSpecialsButton"; + this.clearSpecialsButton.Size = new System.Drawing.Size(100, 23); + this.clearSpecialsButton.TabIndex = 3; + this.clearSpecialsButton.Text = "Clear 0 specials"; + this.clearSpecialsButton.UseVisualStyleBackColor = true; + this.clearSpecialsButton.Click += new System.EventHandler(this.ClearSpecialsButtonClick); + // + // syntaxTree + // + this.syntaxTree.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.syntaxTree.Location = new System.Drawing.Point(3, 32); + this.syntaxTree.Name = "syntaxTree"; + this.syntaxTree.Size = new System.Drawing.Size(459, 182); + this.syntaxTree.TabIndex = 2; + this.syntaxTree.Unit = null; + // + // generateCodeButton + // + this.generateCodeButton.Anchor = System.Windows.Forms.AnchorStyles.Top; + this.generateCodeButton.Location = new System.Drawing.Point(119, 2); + this.generateCodeButton.Name = "generateCodeButton"; + this.generateCodeButton.Size = new System.Drawing.Size(100, 23); + this.generateCodeButton.TabIndex = 1; + this.generateCodeButton.Text = "Generate"; + this.generateCodeButton.UseVisualStyleBackColor = true; + this.generateCodeButton.Click += new System.EventHandler(this.GenerateCodeButtonClick); + // + // parseButton + // + this.parseButton.Anchor = System.Windows.Forms.AnchorStyles.Top; + this.parseButton.Location = new System.Drawing.Point(13, 2); + this.parseButton.Name = "parseButton"; + this.parseButton.Size = new System.Drawing.Size(100, 23); + this.parseButton.TabIndex = 0; + this.parseButton.Text = "Parse"; + this.parseButton.UseVisualStyleBackColor = true; + this.parseButton.Click += new System.EventHandler(this.ParseButtonClick); + // + // VBDemo + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this.splitContainer1); + this.Name = "VBDemo"; + this.Size = new System.Drawing.Size(462, 391); + this.splitContainer1.Panel1.ResumeLayout(false); + this.splitContainer1.Panel1.PerformLayout(); + this.splitContainer1.Panel2.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); + this.splitContainer1.ResumeLayout(false); + this.ResumeLayout(false); + } + private System.Windows.Forms.Button clearSpecialsButton; + private System.Windows.Forms.Button editNodeButton; + private ICSharpCode.NRefactory.Demo.VBDomView syntaxTree; + private System.Windows.Forms.TextBox codeView; + private System.Windows.Forms.Button generateCodeButton; + private System.Windows.Forms.Button parseButton; + private System.Windows.Forms.SplitContainer splitContainer1; + } +} diff --git a/ICSharpCode.NRefactory.Demo/VBDemo.cs b/ICSharpCode.NRefactory.Demo/VBDemo.cs new file mode 100644 index 000000000..387921259 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/VBDemo.cs @@ -0,0 +1,78 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Windows.Forms; +using ICSharpCode.NRefactory.VB; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.PrettyPrinter; + +namespace ICSharpCode.NRefactory.Demo +{ + /// + /// Description of VBDemo. + /// + public partial class VBDemo : UserControl + { + public VBDemo() + { + // + // The InitializeComponent() call is required for Windows Forms designer support. + // + InitializeComponent(); + ParseButtonClick(null, null); + } + + IList savedSpecials; + + void ParseButtonClick(object sender, EventArgs e) + { + using (VBParser parser = new VBParser(new VBLexer(new StringReader(codeView.Text)))) { + parser.Parse(); + // this allows retrieving comments, preprocessor directives, etc. (stuff that isn't part of the syntax) + SetSpecials(parser.Lexer.SpecialTracker.RetrieveSpecials()); + // this retrieves the root node of the result DOM + if (parser.Errors.Count > 0) { + MessageBox.Show(parser.Errors.ErrorOutput); + } + syntaxTree.Unit = parser.CompilationUnit; + } + } + + void GenerateCodeButtonClick(object sender, EventArgs e) + { + if (syntaxTree.Unit != null) { + VBNetOutputVisitor visitor = new VBNetOutputVisitor(); + // re-insert the comments we saved from the parser into the output + using (SpecialNodesInserter.Install(savedSpecials, visitor)) { + syntaxTree.Unit.AcceptVisitor(visitor, null); + } + codeView.Text = visitor.Text.Replace("\t", " "); + } + } + + void ClearSpecialsButtonClick(object sender, EventArgs e) + { + SetSpecials(new ISpecial[0]); + } + + void EditNodeButtonClick(object sender, EventArgs e) + { + syntaxTree.EditSelectedNode(); + } + + void SetSpecials(IList specials) + { + savedSpecials = specials; + if (specials.Count == 1) + clearSpecialsButton.Text = "Clear 1 special"; + else + clearSpecialsButton.Text = "Clear " + specials.Count + " specials"; + } + } +} diff --git a/ICSharpCode.NRefactory.Demo/VBDemo.resx b/ICSharpCode.NRefactory.Demo/VBDemo.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/VBDemo.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ICSharpCode.NRefactory.Demo/VBDomView.Designer.cs b/ICSharpCode.NRefactory.Demo/VBDomView.Designer.cs new file mode 100644 index 000000000..d4d5d2d44 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/VBDomView.Designer.cs @@ -0,0 +1,59 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +namespace ICSharpCode.NRefactory.Demo +{ + partial class VBDomView : System.Windows.Forms.UserControl + { + /// + /// Designer variable used to keep track of non-visual components. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Disposes resources used by the control. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing) { + if (components != null) { + components.Dispose(); + } + } + base.Dispose(disposing); + } + + /// + /// This method is required for Windows Forms designer support. + /// Do not change the method contents inside the source code editor. The Forms designer might + /// not be able to load this method if it was changed manually. + /// + private void InitializeComponent() + { + this.tree = new System.Windows.Forms.TreeView(); + this.SuspendLayout(); + // + // tree + // + this.tree.Dock = System.Windows.Forms.DockStyle.Fill; + this.tree.HideSelection = false; + this.tree.Location = new System.Drawing.Point(0, 0); + this.tree.Name = "tree"; + this.tree.ShowRootLines = false; + this.tree.Size = new System.Drawing.Size(186, 182); + this.tree.TabIndex = 0; + this.tree.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TreeKeyDown); + // + // AstView + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this.tree); + this.Name = "AstView"; + this.Size = new System.Drawing.Size(186, 182); + this.ResumeLayout(false); + } + private System.Windows.Forms.TreeView tree; + } +} diff --git a/ICSharpCode.NRefactory.Demo/VBDomView.cs b/ICSharpCode.NRefactory.Demo/VBDomView.cs new file mode 100644 index 000000000..3a0ac9af1 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/VBDomView.cs @@ -0,0 +1,225 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections; +using System.Windows.Forms; +using System.Reflection; + +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB; + +namespace ICSharpCode.NRefactory.Demo +{ + public partial class VBDomView + { + CompilationUnit unit; + + public CompilationUnit Unit { + get { + return unit; + } + set { + if (value != null) { + unit = value; + UpdateTree(); + } + } + } + + void UpdateTree() + { + tree.Nodes.Clear(); + tree.Nodes.Add(new CollectionNode("CompilationUnit", unit.Children)); + tree.SelectedNode = tree.Nodes[0]; + } + + public VBDomView() + { + InitializeComponent(); + } + + public void DeleteSelectedNode() + { + if (tree.SelectedNode is ElementNode) { + INode element = (tree.SelectedNode as ElementNode).element; + if (tree.SelectedNode.Parent is CollectionNode) { + if (MessageBox.Show("Remove selected node from parent collection?", "Remove node", MessageBoxButtons.YesNo, MessageBoxIcon.Question) + == DialogResult.Yes) + { + IList col = (tree.SelectedNode.Parent as CollectionNode).collection; + col.Remove(element); + (tree.SelectedNode.Parent as CollectionNode).Update(); + } + } else if (tree.SelectedNode.Parent is ElementNode) { + if (MessageBox.Show("Set selected property to null?", "Remove node", MessageBoxButtons.YesNo, MessageBoxIcon.Question) + == DialogResult.Yes) + { + // get parent element + element = (tree.SelectedNode.Parent as ElementNode).element; + string propertyName = (string)tree.SelectedNode.Tag; + element.GetType().GetProperty(propertyName).SetValue(element, null, null); + (tree.SelectedNode.Parent as ElementNode).Update(); + } + } + } else if (tree.SelectedNode is CollectionNode) { + if (MessageBox.Show("Remove all elements from selected collection?", "Clear collection", MessageBoxButtons.YesNo, MessageBoxIcon.Question) + == DialogResult.Yes) + { + IList col = (tree.SelectedNode as CollectionNode).collection; + col.Clear(); + (tree.SelectedNode as CollectionNode).Update(); + } + } + } + + public void EditSelectedNode() + { + TreeNode node = tree.SelectedNode; + while (!(node is ElementNode)) { + if (node == null) { + return; + } + node = node.Parent; + } + INode element = ((ElementNode)node).element; + using (VBEditDialog dlg = new VBEditDialog(element)) { + dlg.ShowDialog(); + } + ((ElementNode)node).Update(); + } + + public void ApplyTransformation(IDomVisitor visitor) + { + if (tree.SelectedNode == tree.Nodes[0]) { + unit.AcceptVisitor(visitor, null); + UpdateTree(); + } else { + string name = visitor.GetType().Name; + ElementNode elementNode = tree.SelectedNode as ElementNode; + CollectionNode collectionNode = tree.SelectedNode as CollectionNode; + if (elementNode != null) { + if (MessageBox.Show(("Apply " + name + " to selected element '" + elementNode.Text + "'?"), + "Apply transformation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) + == DialogResult.Yes) + { + elementNode.element.AcceptVisitor(visitor, null); + elementNode.Update(); + } + } else if (collectionNode != null) { + if (MessageBox.Show(("Apply " + name + " to all elements in selected collection '" + collectionNode.Text + "'?"), + "Apply transformation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) + == DialogResult.Yes) + { + foreach (TreeNode subNode in collectionNode.Nodes) { + if (subNode is ElementNode) { + (subNode as ElementNode).element.AcceptVisitor(visitor, null); + } + } + collectionNode.Update(); + } + } + } + } + + static TreeNode CreateNode(object child) + { + if (child == null) { + return new TreeNode("*null reference*"); + } else if (child is INode) { + return new ElementNode(child as INode); + } else { + return new TreeNode(child.ToString()); + } + } + + class CollectionNode : TreeNode + { + internal IList collection; + string baseName; + + public CollectionNode(string text, IList children) : base(text) + { + this.baseName = text; + this.collection = children; + Update(); + } + + public void Update() + { + if (collection.Count == 0) { + Text = baseName + " (empty collection)"; + } else if (collection.Count == 1) { + Text = baseName + " (collection with 1 element)"; + } else { + Text = baseName + " (collection with " + collection.Count + " elements)"; + } + Nodes.Clear(); + foreach (object child in collection) { + Nodes.Add(CreateNode(child)); + } + Expand(); + } + } + + class ElementNode : TreeNode + { + internal INode element; + + public ElementNode(INode node) + { + this.element = node; + Update(); + } + + public void Update() + { + Nodes.Clear(); + Type type = element.GetType(); + Text = type.Name; + if (Tag != null) { // HACK: after editing property element + Text = Tag.ToString() + " = " + Text; + } + if (!(element is INullable && (element as INullable).IsNull)) { + AddProperties(type, element); + if (element.Children.Count > 0) { + Nodes.Add(new CollectionNode("Children", element.Children)); + } + } + } + + void AddProperties(Type type, INode node) + { + if (type == typeof(AbstractNode)) + return; + foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { + if (pi.DeclaringType != type) // don't add derived properties + continue; + if (pi.Name == "IsNull") + continue; + object value = pi.GetValue(node, null); + if (value is IList) { + Nodes.Add(new CollectionNode(pi.Name, (IList)value)); + } else if (value is string) { + Text += " " + pi.Name + "='" + value + "'"; + } else { + TreeNode treeNode = CreateNode(value); + treeNode.Text = pi.Name + " = " + treeNode.Text; + treeNode.Tag = pi.Name; + Nodes.Add(treeNode); + } + } + AddProperties(type.BaseType, node); + } + } + + void TreeKeyDown(object sender, KeyEventArgs e) + { + if (e.KeyData == Keys.Delete) { + DeleteSelectedNode(); + } else if (e.KeyData == Keys.Space || e.KeyData == Keys.Enter) { + EditSelectedNode(); + } + } + } +} diff --git a/ICSharpCode.NRefactory.Demo/VBDomView.resx b/ICSharpCode.NRefactory.Demo/VBDomView.resx new file mode 100644 index 000000000..7080a7d11 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/VBDomView.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ICSharpCode.NRefactory.Demo/VBEditDialog.Designer.cs b/ICSharpCode.NRefactory.Demo/VBEditDialog.Designer.cs new file mode 100644 index 000000000..6d4254497 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/VBEditDialog.Designer.cs @@ -0,0 +1,88 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +namespace ICSharpCode.NRefactory.Demo +{ + partial class VBEditDialog : System.Windows.Forms.Form + { + /// + /// Designer variable used to keep track of non-visual components. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Disposes resources used by the form. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing) { + if (components != null) { + components.Dispose(); + } + } + base.Dispose(disposing); + } + + /// + /// This method is required for Windows Forms designer support. + /// Do not change the method contents inside the source code editor. The Forms designer might + /// not be able to load this method if it was changed manually. + /// + private void InitializeComponent() + { + this.propertyGrid = new System.Windows.Forms.PropertyGrid(); + this.panel1 = new System.Windows.Forms.Panel(); + this.okButton = new System.Windows.Forms.Button(); + this.panel1.SuspendLayout(); + this.SuspendLayout(); + // + // propertyGrid + // + this.propertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; + this.propertyGrid.HelpVisible = false; + this.propertyGrid.Location = new System.Drawing.Point(0, 0); + this.propertyGrid.Name = "propertyGrid"; + this.propertyGrid.PropertySort = System.Windows.Forms.PropertySort.Alphabetical; + this.propertyGrid.Size = new System.Drawing.Size(477, 436); + this.propertyGrid.TabIndex = 0; + this.propertyGrid.ToolbarVisible = false; + // + // panel1 + // + this.panel1.Controls.Add(this.okButton); + this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; + this.panel1.Location = new System.Drawing.Point(0, 436); + this.panel1.Name = "panel1"; + this.panel1.Size = new System.Drawing.Size(477, 38); + this.panel1.TabIndex = 1; + // + // okButton + // + this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; + this.okButton.Location = new System.Drawing.Point(390, 6); + this.okButton.Name = "okButton"; + this.okButton.Size = new System.Drawing.Size(75, 23); + this.okButton.TabIndex = 0; + this.okButton.Text = "OK"; + this.okButton.UseVisualStyleBackColor = true; + // + // EditDialog + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = this.okButton; + this.ClientSize = new System.Drawing.Size(477, 474); + this.Controls.Add(this.propertyGrid); + this.Controls.Add(this.panel1); + this.Name = "EditDialog"; + this.Text = "EditDialog"; + this.panel1.ResumeLayout(false); + this.ResumeLayout(false); + } + private System.Windows.Forms.PropertyGrid propertyGrid; + private System.Windows.Forms.Button okButton; + private System.Windows.Forms.Panel panel1; + } +} diff --git a/ICSharpCode.NRefactory.Demo/VBEditDialog.cs b/ICSharpCode.NRefactory.Demo/VBEditDialog.cs new file mode 100644 index 000000000..031ab9971 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/VBEditDialog.cs @@ -0,0 +1,18 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace ICSharpCode.NRefactory.Demo +{ + public partial class VBEditDialog + { + public VBEditDialog(object element) + { + InitializeComponent(); + propertyGrid.SelectedObject = element; + } + } +} diff --git a/ICSharpCode.NRefactory.Demo/VBEditDialog.resx b/ICSharpCode.NRefactory.Demo/VBEditDialog.resx new file mode 100644 index 000000000..7080a7d11 --- /dev/null +++ b/ICSharpCode.NRefactory.Demo/VBEditDialog.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ICSharpCode.NRefactory.Tests/.gitignore b/ICSharpCode.NRefactory.Tests/.gitignore new file mode 100644 index 000000000..9ce745d95 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/.gitignore @@ -0,0 +1,3 @@ + +bin/ +obj/ \ No newline at end of file diff --git a/ICSharpCode.NRefactory.Tests/CSharp/AstStructureTest.cs b/ICSharpCode.NRefactory.Tests/CSharp/AstStructureTest.cs new file mode 100644 index 000000000..94e707f9d --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/AstStructureTest.cs @@ -0,0 +1,31 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Reflection; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp +{ + [TestFixture] + public class AstStructureTest + { + [Test] + public void RolesAreStaticReadOnly() + { + foreach (Type type in typeof(AstNode).Assembly.GetExportedTypes()) { + if (type.IsSubclassOf(typeof(AstNode))) { + foreach (FieldInfo field in type.GetFields()) { + if (field.FieldType.IsSubclassOf(typeof(Role))) { + Assert.IsTrue(field.IsPublic); + Assert.IsTrue(field.IsStatic); + Assert.IsTrue(field.IsInitOnly); + Assert.IsTrue(field.Name.EndsWith("Role", StringComparison.Ordinal)); + Assert.IsNotNull(field.GetValue(null)); + } + } + } + } + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AliasReferenceExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AliasReferenceExpressionTests.cs new file mode 100644 index 000000000..8b0298e60 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AliasReferenceExpressionTests.cs @@ -0,0 +1,36 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + + +using System; +using System.IO; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class AliasReferenceExpressionTests + { + [Test, Ignore] + public void GlobalReferenceExpressionTest() + { + CSharpParser parser = new CSharpParser(); + parser.ParseTypeReference(new StringReader("global::System")); + //Assert.IsTrue(tre.TypeReference.IsGlobal); + //Assert.AreEqual("System", tre.TypeReference.Type); + throw new NotImplementedException(); + } + + [Test, Ignore] + public void GlobalTypeDeclaration() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("global::System.String a;"); + //TypeReference typeRef = lvd.GetTypeForVariable(0); + //Assert.IsTrue(typeRef.IsGlobal); + //Assert.AreEqual("System.String", typeRef.Type); + throw new NotImplementedException(); + } + + // TODO: add tests for aliases other than 'global' + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AnonymousMethodTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AnonymousMethodTests.cs new file mode 100644 index 000000000..90e68d807 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AnonymousMethodTests.cs @@ -0,0 +1,55 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.IO; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class AnonymousMethodTests + { + AnonymousMethodExpression Parse(string expression) + { + return ParseUtilCSharp.ParseExpression(expression); + } + + [Test] + public void AnonymousMethodWithoutParameterList() + { + AnonymousMethodExpression ame = Parse("delegate {}"); + Assert.AreEqual(0, ame.Parameters.Count()); + Assert.AreEqual(0, ame.Body.Statements.Count()); + Assert.IsFalse(ame.HasParameterList); + } + + [Test] + public void AnonymousMethodAfterCast() + { + CastExpression c = ParseUtilCSharp.ParseExpression("(ThreadStart)delegate {}"); + AnonymousMethodExpression ame = (AnonymousMethodExpression)c.Expression; + Assert.AreEqual(0, ame.Parameters.Count()); + Assert.AreEqual(0, ame.Body.Statements.Count()); + } + + [Test, Ignore("Parameter list is broken")] + public void EmptyAnonymousMethod() + { + AnonymousMethodExpression ame = Parse("delegate() {}"); + Assert.AreEqual(0, ame.Parameters.Count()); + Assert.AreEqual(0, ame.Body.Statements.Count()); + Assert.IsTrue(ame.HasParameterList); + } + + [Test, Ignore("Parameter list is broken")] + public void SimpleAnonymousMethod() + { + AnonymousMethodExpression ame = Parse("delegate(int a, int b) { return a + b; }"); + Assert.AreEqual(2, ame.Parameters.Count()); + Assert.AreEqual(1, ame.Body.Statements.Count()); + Assert.IsTrue(ame.Body.Children.First() is ReturnStatement); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ArrayObjectCreateExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ArrayObjectCreateExpressionTests.cs new file mode 100644 index 000000000..e3173c8cd --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ArrayObjectCreateExpressionTests.cs @@ -0,0 +1,36 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture, Ignore("Needs to be ported to new NRefactory")] + public class ArrayObjectCreateExpressionTests + { + [Test] + public void ArrayCreateExpressionTest1() + { + /* + ArrayCreateExpression ace = ParseUtilCSharp.ParseExpression("new int[5]"); + Assert.AreEqual("System.Int32", ace.CreateType.Type); + Assert.IsTrue(ace.CreateType.IsKeyword); + Assert.AreEqual(1, ace.Arguments.Count); + Assert.AreEqual(new int[] {0}, ace.CreateType.RankSpecifier); + */ + throw new NotImplementedException(); + } + + [Test] + public void ImplicitlyTypedArrayCreateExpression() + { + /* + ArrayCreateExpression ace = ParseUtilCSharp.ParseExpression("new[] { 1, 10, 100, 1000 }"); + Assert.AreEqual("", ace.CreateType.Type); + Assert.AreEqual(0, ace.Arguments.Count); + Assert.AreEqual(4, ace.ArrayInitializer.CreateExpressions.Count);*/ + throw new NotImplementedException(); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AssignmentExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AssignmentExpressionTests.cs new file mode 100644 index 000000000..065b88bba --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AssignmentExpressionTests.cs @@ -0,0 +1,88 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class AssignmentExpressionTests + { + void TestAssignmentExpression(string program, AssignmentOperatorType op) + { + AssignmentExpression ae = ParseUtilCSharp.ParseExpression(program); + + Assert.AreEqual(op, ae.Operator); + + Assert.IsTrue(ae.Left is IdentifierExpression); + Assert.IsTrue(ae.Right is IdentifierExpression); + } + + [Test] + public void AssignTest() + { + TestAssignmentExpression("a = b", AssignmentOperatorType.Assign); + } + + [Test] + public void AddTest() + { + TestAssignmentExpression("a += b", AssignmentOperatorType.Add); + } + + [Test] + public void SubtractTest() + { + TestAssignmentExpression("a -= b", AssignmentOperatorType.Subtract); + } + + [Test] + public void MultiplyTest() + { + TestAssignmentExpression("a *= b", AssignmentOperatorType.Multiply); + } + + [Test] + public void DivideTest() + { + TestAssignmentExpression("a /= b", AssignmentOperatorType.Divide); + } + + [Test] + public void ModulusTest() + { + TestAssignmentExpression("a %= b", AssignmentOperatorType.Modulus); + } + + [Test] + public void ShiftLeftTest() + { + TestAssignmentExpression("a <<= b", AssignmentOperatorType.ShiftLeft); + } + + [Test] + public void ShiftRightTest() + { + TestAssignmentExpression("a >>= b", AssignmentOperatorType.ShiftRight); + } + + [Test] + public void BitwiseAndTest() + { + TestAssignmentExpression("a &= b", AssignmentOperatorType.BitwiseAnd); + } + + [Test] + public void BitwiseOrTest() + { + TestAssignmentExpression("a |= b", AssignmentOperatorType.BitwiseOr); + } + + [Test] + public void ExclusiveOrTest() + { + TestAssignmentExpression("a ^= b", AssignmentOperatorType.ExclusiveOr); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/BaseReferenceExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/BaseReferenceExpressionTests.cs new file mode 100644 index 000000000..4bde43b92 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/BaseReferenceExpressionTests.cs @@ -0,0 +1,19 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class BaseReferenceExpressionTests + { + [Test] + public void BaseReferenceExpressionTest1() + { + MemberReferenceExpression fre = ParseUtilCSharp.ParseExpression("base.myField"); + Assert.IsTrue(fre.Target is BaseReferenceExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/BinaryOperatorExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/BinaryOperatorExpressionTests.cs new file mode 100644 index 000000000..e77006405 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/BinaryOperatorExpressionTests.cs @@ -0,0 +1,227 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class BinaryOperatorExpressionTests + { + #region Precedence Tests + void OperatorPrecedenceTest(string strongOperator, BinaryOperatorType strongOperatorType, + string weakOperator, BinaryOperatorType weakOperatorType, bool vb) + { + string program = "a " + weakOperator + " b " + strongOperator + " c"; + BinaryOperatorExpression boe = ParseUtilCSharp.ParseExpression(program); + Assert.AreEqual(weakOperatorType, boe.Operator); + Assert.IsTrue(boe.Left is IdentifierExpression); + boe = (BinaryOperatorExpression)boe.Right; + Assert.AreEqual(strongOperatorType, boe.Operator); + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is IdentifierExpression); + + program = "a " + strongOperator + " b " + weakOperator + " c"; + + boe = ParseUtilCSharp.ParseExpression(program); + Assert.AreEqual(weakOperatorType, boe.Operator); + Assert.IsTrue(boe.Right is IdentifierExpression); + boe = (BinaryOperatorExpression)boe.Left; + Assert.AreEqual(strongOperatorType, boe.Operator); + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is IdentifierExpression); + } + + void SameOperatorPrecedenceTest(string firstOperator, BinaryOperatorType firstOperatorType, + string secondOperator, BinaryOperatorType secondOperatorType, bool vb) + { + string program = "a " + secondOperator + " b " + firstOperator + " c"; + BinaryOperatorExpression boe = ParseUtilCSharp.ParseExpression(program); + Assert.AreEqual(firstOperatorType, boe.Operator); + Assert.IsTrue(boe.Right is IdentifierExpression); + boe = (BinaryOperatorExpression)boe.Left; + Assert.AreEqual(secondOperatorType, boe.Operator); + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is IdentifierExpression); + + program = "a " + firstOperator + " b " + secondOperator + " c"; + boe = ParseUtilCSharp.ParseExpression(program); + Assert.AreEqual(secondOperatorType, boe.Operator); + Assert.IsTrue(boe.Right is IdentifierExpression); + boe = (BinaryOperatorExpression)boe.Left; + Assert.AreEqual(firstOperatorType, boe.Operator); + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is IdentifierExpression); + } + + [Test] + public void OperatorPrecedenceTest() + { + SameOperatorPrecedenceTest("*", BinaryOperatorType.Multiply, "/", BinaryOperatorType.Divide, false); + SameOperatorPrecedenceTest("*", BinaryOperatorType.Multiply, "%", BinaryOperatorType.Modulus, false); + OperatorPrecedenceTest("*", BinaryOperatorType.Multiply, "+", BinaryOperatorType.Add, false); + SameOperatorPrecedenceTest("-", BinaryOperatorType.Subtract, "+", BinaryOperatorType.Add, false); + OperatorPrecedenceTest("+", BinaryOperatorType.Add, "<<", BinaryOperatorType.ShiftLeft, false); + SameOperatorPrecedenceTest(">>", BinaryOperatorType.ShiftRight, "<<", BinaryOperatorType.ShiftLeft, false); + OperatorPrecedenceTest("<<", BinaryOperatorType.ShiftLeft, "==", BinaryOperatorType.Equality, false); + SameOperatorPrecedenceTest("!=", BinaryOperatorType.InEquality, "==", BinaryOperatorType.Equality, false); + OperatorPrecedenceTest("==", BinaryOperatorType.Equality, "&", BinaryOperatorType.BitwiseAnd, false); + OperatorPrecedenceTest("&", BinaryOperatorType.BitwiseAnd, "^", BinaryOperatorType.ExclusiveOr, false); + OperatorPrecedenceTest("^", BinaryOperatorType.ExclusiveOr, "|", BinaryOperatorType.BitwiseOr, false); + OperatorPrecedenceTest("|", BinaryOperatorType.BitwiseOr, "&&", BinaryOperatorType.LogicalAnd, false); + OperatorPrecedenceTest("&&", BinaryOperatorType.LogicalAnd, "||", BinaryOperatorType.LogicalOr, false); + OperatorPrecedenceTest("||", BinaryOperatorType.LogicalOr, "??", BinaryOperatorType.NullCoalescing, false); + } + #endregion + + void TestBinaryOperatorExpressionTest(string program, BinaryOperatorType op) + { + BinaryOperatorExpression boe = ParseUtilCSharp.ParseExpression(program); + Assert.AreEqual(op, boe.Operator); + + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is IdentifierExpression); + + } + + [Test] + public void SubtractionLeftToRight() + { + BinaryOperatorExpression boe = ParseUtilCSharp.ParseExpression("a - b - c"); + Assert.IsTrue(boe.Right is IdentifierExpression); + Assert.IsTrue(boe.Left is BinaryOperatorExpression); + } + + [Test] + public void NullCoalescingRightToLeft() + { + BinaryOperatorExpression boe = ParseUtilCSharp.ParseExpression("a ?? b ?? c"); + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is BinaryOperatorExpression); + } + + [Test] + public void BitwiseAndTest() + { + TestBinaryOperatorExpressionTest("a & b", BinaryOperatorType.BitwiseAnd); + } + + [Test] + public void BitwiseOrTest() + { + TestBinaryOperatorExpressionTest("a | b", BinaryOperatorType.BitwiseOr); + } + + [Test] + public void LogicalAndTest() + { + TestBinaryOperatorExpressionTest("a && b", BinaryOperatorType.LogicalAnd); + } + + [Test] + public void LogicalOrTest() + { + TestBinaryOperatorExpressionTest("a || b", BinaryOperatorType.LogicalOr); + } + + [Test] + public void ExclusiveOrTest() + { + TestBinaryOperatorExpressionTest("a ^ b", BinaryOperatorType.ExclusiveOr); + } + + + [Test] + public void GreaterThanTest() + { + TestBinaryOperatorExpressionTest("a > b", BinaryOperatorType.GreaterThan); + } + + [Test] + public void GreaterThanOrEqualTest() + { + TestBinaryOperatorExpressionTest("a >= b", BinaryOperatorType.GreaterThanOrEqual); + } + + [Test] + public void EqualityTest() + { + TestBinaryOperatorExpressionTest("a == b", BinaryOperatorType.Equality); + } + + [Test] + public void InEqualityTest() + { + TestBinaryOperatorExpressionTest("a != b", BinaryOperatorType.InEquality); + } + + [Test] + public void LessThanTest() + { + TestBinaryOperatorExpressionTest("a < b", BinaryOperatorType.LessThan); + } + + [Test] + public void LessThanOrEqualTest() + { + TestBinaryOperatorExpressionTest("a <= b", BinaryOperatorType.LessThanOrEqual); + } + + [Test] + public void AddTest() + { + TestBinaryOperatorExpressionTest("a + b", BinaryOperatorType.Add); + } + + [Test] + public void SubtractTest() + { + TestBinaryOperatorExpressionTest("a - b", BinaryOperatorType.Subtract); + } + + [Test] + public void MultiplyTest() + { + TestBinaryOperatorExpressionTest("a * b", BinaryOperatorType.Multiply); + } + + [Test] + public void DivideTest() + { + TestBinaryOperatorExpressionTest("a / b", BinaryOperatorType.Divide); + } + + [Test] + public void ModulusTest() + { + TestBinaryOperatorExpressionTest("a % b", BinaryOperatorType.Modulus); + } + + [Test] + public void ShiftLeftTest() + { + TestBinaryOperatorExpressionTest("a << b", BinaryOperatorType.ShiftLeft); + } + + [Test] + public void ShiftRightTest() + { + TestBinaryOperatorExpressionTest("a >> b", BinaryOperatorType.ShiftRight); + } + + [Test] + public void NullCoalescingTest() + { + TestBinaryOperatorExpressionTest("a ?? b", BinaryOperatorType.NullCoalescing); + } + + [Test] + public void LessThanOrGreaterTest() + { + const string expr = "i1 < 0 || i1 > (Count - 1)"; + BinaryOperatorExpression boe = ParseUtilCSharp.ParseExpression(expr); + Assert.AreEqual(BinaryOperatorType.LogicalOr, boe.Operator); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/CastExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/CastExpressionTests.cs new file mode 100644 index 000000000..a55d27c3a --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/CastExpressionTests.cs @@ -0,0 +1,140 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture, Ignore("Port unit tests to new DOM")] + public class CastExpressionTests + { + /* + [Test] + public void SimpleCastExpression() + { + CastExpression ce = ParseUtilCSharp.ParseExpression("(MyObject)o"); + Assert.AreEqual("MyObject", ce.CastTo.Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.Cast, ce.CastType); + } + + [Test] + public void ArrayCastExpression() + { + CastExpression ce = ParseUtilCSharp.ParseExpression("(MyType[])o"); + Assert.AreEqual("MyType", ce.CastTo.Type); + Assert.AreEqual(new int[] { 0 }, ce.CastTo.RankSpecifier); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.Cast, ce.CastType); + } + + [Test] + public void NullablePrimitiveCastExpression() + { + CastExpression ce = ParseUtilCSharp.ParseExpression("(int?)o"); + Assert.AreEqual("System.Nullable", ce.CastTo.Type); + Assert.AreEqual("System.Int32", ce.CastTo.GenericTypes[0].Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.Cast, ce.CastType); + } + + [Test] + public void NullableCastExpression() + { + CastExpression ce = ParseUtilCSharp.ParseExpression("(MyType?)o"); + Assert.AreEqual("System.Nullable", ce.CastTo.Type); + Assert.AreEqual("MyType", ce.CastTo.GenericTypes[0].Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.Cast, ce.CastType); + } + + [Test] + public void NullableTryCastExpression() + { + CastExpression ce = ParseUtilCSharp.ParseExpression("o as int?"); + Assert.AreEqual("System.Nullable", ce.CastTo.Type); + Assert.IsTrue(ce.CastTo.IsKeyword); + Assert.AreEqual("System.Int32", ce.CastTo.GenericTypes[0].Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.TryCast, ce.CastType); + } + + [Test] + public void GenericCastExpression() + { + CastExpression ce = ParseUtilCSharp.ParseExpression("(List)o"); + Assert.AreEqual("List", ce.CastTo.Type); + Assert.AreEqual("System.String", ce.CastTo.GenericTypes[0].Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.Cast, ce.CastType); + } + + [Test] + public void GenericArrayCastExpression() + { + CastExpression ce = ParseUtilCSharp.ParseExpression("(List[])o"); + Assert.AreEqual("List", ce.CastTo.Type); + Assert.AreEqual("System.String", ce.CastTo.GenericTypes[0].Type); + Assert.AreEqual(new int[] { 0 }, ce.CastTo.RankSpecifier); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.Cast, ce.CastType); + } + + [Test] + public void GenericArrayAsCastExpression() + { + CastExpression ce = ParseUtilCSharp.ParseExpression("o as List[]"); + Assert.AreEqual("List", ce.CastTo.Type); + Assert.AreEqual("System.String", ce.CastTo.GenericTypes[0].Type); + Assert.AreEqual(new int[] { 0 }, ce.CastTo.RankSpecifier); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.TryCast, ce.CastType); + } + + [Test] + public void CastMemberReferenceOnParenthesizedExpression() + { + // yes, we really wanted to evaluate .Member on expr and THEN cast the result to MyType + CastExpression ce = ParseUtilCSharp.ParseExpression("(MyType)(expr).Member"); + Assert.AreEqual("MyType", ce.CastTo.Type); + Assert.IsTrue(ce.Expression is MemberReferenceExpression); + Assert.AreEqual(CastType.Cast, ce.CastType); + } + + [Test] + public void TryCastParenthesizedExpression() + { + CastExpression ce = ParseUtilCSharp.ParseExpression("(o) as string"); + Assert.AreEqual("System.String", ce.CastTo.ToString()); + Assert.IsTrue(ce.Expression is ParenthesizedExpression); + Assert.AreEqual(CastType.TryCast, ce.CastType); + } + + [Test] + public void CastNegation() + { + CastExpression ce = ParseUtilCSharp.ParseExpression("(uint)-negativeValue"); + Assert.AreEqual("System.UInt32", ce.CastTo.ToString()); + Assert.IsTrue(ce.Expression is UnaryOperatorExpression); + Assert.AreEqual(CastType.Cast, ce.CastType); + } + */ + + [Test] + public void SubtractionIsNotCast() + { + BinaryOperatorExpression boe = ParseUtilCSharp.ParseExpression("(BigInt)-negativeValue"); + Assert.IsTrue(boe.Left is ParenthesizedExpression); + Assert.IsTrue(boe.Right is IdentifierExpression); + } + + [Test] + public void IntMaxValueToBigInt() + { + CastExpression ce = ParseUtilCSharp.ParseExpression("(BigInt)int.MaxValue"); + Assert.AreEqual("BigInt", ce.CastTo.ToString()); + Assert.IsTrue(ce.Expression is MemberReferenceExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/CheckedExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/CheckedExpressionTests.cs new file mode 100644 index 000000000..696a28b7a --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/CheckedExpressionTests.cs @@ -0,0 +1,26 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class CheckedExpressionTests + { + [Test] + public void CheckedExpressionTest() + { + CheckedExpression ce = ParseUtilCSharp.ParseExpression("checked(a)"); + Assert.IsTrue(ce.Expression is IdentifierExpression); + } + + [Test] + public void UncheckedExpressionTest() + { + UncheckedExpression ce = ParseUtilCSharp.ParseExpression("unchecked(a)"); + Assert.IsTrue(ce.Expression is IdentifierExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ConditionalExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ConditionalExpressionTests.cs new file mode 100644 index 000000000..21c8a5d94 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ConditionalExpressionTests.cs @@ -0,0 +1,104 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class ConditionalExpressionTests + { + [Test] + public void ConditionalExpressionTest() + { + ConditionalExpression ce = ParseUtilCSharp.ParseExpression("a == b ? a() : a.B"); + + Assert.IsTrue(ce.Condition is BinaryOperatorExpression); + Assert.IsTrue(ce.TrueExpression is InvocationExpression); + Assert.IsTrue(ce.FalseExpression is MemberReferenceExpression); + } + + [Test] + public void ConditionalIsExpressionTest() + { + // (as is b?) ERROR (conflict with nullables, SD-419) + ConditionalExpression ce = ParseUtilCSharp.ParseExpression("a is b ? a() : a.B"); + + Assert.IsTrue(ce.Condition is IsExpression); + Assert.IsTrue(ce.TrueExpression is InvocationExpression); + Assert.IsTrue(ce.FalseExpression is MemberReferenceExpression); + } + + [Test, Ignore("crashes the parser")] + public void ConditionalIsWithNullableExpressionTest() + { + ConditionalExpression ce = ParseUtilCSharp.ParseExpression("a is b? ? a() : a.B"); + + Assert.IsTrue(ce.Condition is IsExpression); + Assert.IsTrue(ce.TrueExpression is InvocationExpression); + Assert.IsTrue(ce.FalseExpression is MemberReferenceExpression); + } + + [Test] + public void ConditionalIsExpressionTest2() + { + ConditionalExpression ce = ParseUtilCSharp.ParseExpression("a is b ? (a()) : a.B"); + + Assert.IsTrue(ce.Condition is IsExpression); + Assert.IsTrue(ce.TrueExpression is ParenthesizedExpression); + Assert.IsTrue(ce.FalseExpression is MemberReferenceExpression); + } + + [Test] + public void ConditionalExpressionNegativeValue() + { + ConditionalExpression ce = ParseUtilCSharp.ParseExpression("isNegative ? -1 : 1"); + + Assert.IsTrue(ce.Condition is IdentifierExpression); + Assert.IsTrue(ce.TrueExpression is UnaryOperatorExpression); + Assert.IsTrue(ce.FalseExpression is PrimitiveExpression); + } + + + [Test] + public void ConditionalIsWithNegativeValue() + { + ConditionalExpression ce = ParseUtilCSharp.ParseExpression("a is b ? -1 : 1"); + + Assert.IsTrue(ce.Condition is IsExpression); + Assert.IsTrue(ce.TrueExpression is UnaryOperatorExpression); + Assert.IsTrue(ce.FalseExpression is PrimitiveExpression); + } + + [Test] + public void ConditionalIsWithExplicitPositiveValue() + { + ConditionalExpression ce = ParseUtilCSharp.ParseExpression("a is b ? +1 : 1"); + + Assert.IsTrue(ce.Condition is IsExpression); + Assert.IsTrue(ce.TrueExpression is UnaryOperatorExpression); + Assert.IsTrue(ce.FalseExpression is PrimitiveExpression); + } + + [Test] + public void RepeatedConditionalExpr() + { + ConditionalExpression ce = ParseUtilCSharp.ParseExpression("a ? b : c ? d : e"); + + Assert.AreEqual("a", ((IdentifierExpression)ce.Condition).Identifier); + Assert.AreEqual("b", ((IdentifierExpression)ce.TrueExpression).Identifier); + Assert.IsTrue(ce.FalseExpression is ConditionalExpression); + } + + [Test] + public void NestedConditionalExpr() + { + ConditionalExpression ce = ParseUtilCSharp.ParseExpression("a ? b ? c : d : e"); + + Assert.AreEqual("a", ((IdentifierExpression)ce.Condition).Identifier); + Assert.AreEqual("e", ((IdentifierExpression)ce.FalseExpression).Identifier); + Assert.IsTrue(ce.TrueExpression is ConditionalExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/DefaultValueExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/DefaultValueExpressionTests.cs new file mode 100644 index 000000000..7419740ff --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/DefaultValueExpressionTests.cs @@ -0,0 +1,53 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture, Ignore("tests need to be ported")] + public class DefaultValueExpressionTests + { + [Test] + public void SimpleDefaultValue() + { + DefaultValueExpression toe = ParseUtilCSharp.ParseExpression("default(T)"); + Assert.AreEqual("T", toe.Type); + } + + /* + [Test] + public void FullQualifiedDefaultValue() + { + DefaultValueExpression toe = ParseUtilCSharp.ParseExpression("default(global::MyNamespace.N1.MyType)"); + Assert.IsTrue(toe.TypeReference.IsGlobal); + Assert.AreEqual("MyNamespace.N1.MyType", toe.TypeReference.Type); + } + + [Test] + public void GenericDefaultValue() + { + DefaultValueExpression toe = ParseUtilCSharp.ParseExpression("default(MyNamespace.N1.MyType)"); + Assert.AreEqual("MyNamespace.N1.MyType", toe.TypeReference.Type); + Assert.AreEqual("System.String", toe.TypeReference.GenericTypes[0].Type); + } + + [Test] + public void DefaultValueAsIntializer() + { + // This test is failing because we need a resolver for the "default:" / "default(" conflict. + LocalVariableDeclaration lvd = ParseUtilCSharp.ParseStatement("T a = default(T);"); + DefaultValueExpression dve = (DefaultValueExpression)lvd.Variables[0].Initializer; + Assert.AreEqual("T", dve.TypeReference.Type); + } + + [Test] + public void DefaultValueInReturnStatement() + { + ReturnStatement rs = ParseUtilCSharp.ParseStatement("return default(T);"); + DefaultValueExpression dve = (DefaultValueExpression)rs.Expression; + Assert.AreEqual("T", dve.TypeReference.Type); + }*/ + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IdentifierExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IdentifierExpressionTests.cs new file mode 100644 index 000000000..6cd54f521 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IdentifierExpressionTests.cs @@ -0,0 +1,78 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class IdentifierExpressionTests + { + void CheckIdentifier(string sourceCode, string identifier) + { + IdentifierExpression ident = ParseUtilCSharp.ParseExpression(sourceCode); + Assert.AreEqual(identifier, ident.Identifier); + } + + [Test] + public void TestIdentifier() + { + CheckIdentifier("a_Bc05", "a_Bc05"); + } + + [Test] + public void TestIdentifierStartingWithUnderscore() + { + CheckIdentifier("_Bc05", "_Bc05"); + } + + [Test] + public void TestIdentifierStartingWithEscapeSequence() + { + CheckIdentifier(@"\u006cexer", "lexer"); + } + + [Test, Ignore("Mono parser bug?")] + public void TestIdentifierContainingEscapeSequence() + { + CheckIdentifier(@"l\U00000065xer", "lexer"); + } + + [Test] + public void TestKeyWordAsIdentifier() + { + CheckIdentifier("@int", "int"); + } + + [Test, Ignore("Mono parser bug?")] + public void TestKeywordWithEscapeSequenceIsIdentifier() + { + CheckIdentifier(@"i\u006et", "int"); + } + + [Test] + public void TestKeyWordAsIdentifierStartingWithUnderscore() + { + CheckIdentifier("@_int", "_int"); + } + + [Test, Ignore] + public void GenericMethodReference() + { + IdentifierExpression ident = ParseUtilCSharp.ParseExpression("M"); + Assert.AreEqual("M", ident.Identifier); + //Assert.AreEqual(1, ident.TypeArguments.Count); + throw new NotImplementedException(); + } + + [Test, Ignore] + public void GenericMethodReference2() + { + IdentifierExpression ident = ParseUtilCSharp.ParseExpression("TargetMethod"); + Assert.AreEqual("TargetMethod", ident.Identifier); + //Assert.AreEqual(1, ident.TypeArguments.Count); + throw new NotImplementedException(); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IndexerExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IndexerExpressionTests.cs new file mode 100644 index 000000000..1a46dc63f --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IndexerExpressionTests.cs @@ -0,0 +1,29 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class IndexerExpressionTests + { + [Test] + public void IndexerExpressionTest() + { + IndexerExpression ie = ParseUtilCSharp.ParseExpression("field[1, \"Hello\", 'a']"); + Assert.IsTrue(ie.Target is IdentifierExpression); + + Assert.AreEqual(3, ie.Arguments.Count()); + + Assert.IsTrue(ie.Arguments.ElementAt(0) is PrimitiveExpression); + Assert.AreEqual(1, (int)((PrimitiveExpression)ie.Arguments.ElementAt(0)).Value); + Assert.IsTrue(ie.Arguments.ElementAt(1) is PrimitiveExpression); + Assert.AreEqual("Hello", (string)((PrimitiveExpression)ie.Arguments.ElementAt(1)).Value); + Assert.IsTrue(ie.Arguments.ElementAt(2) is PrimitiveExpression); + Assert.AreEqual('a', (char)((PrimitiveExpression)ie.Arguments.ElementAt(2)).Value); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/InvocationExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/InvocationExpressionTests.cs new file mode 100644 index 000000000..f3a39b6fd --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/InvocationExpressionTests.cs @@ -0,0 +1,155 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture, Ignore("Port unit tests to new DOM")] + public class InvocationExpressionTests + { + [Test] + public void SimpleInvocationExpressionTest() + { + var ie = ParseUtilCSharp.ParseExpression("myMethod()"); + Assert.AreEqual(0, ie.Arguments.Count()); + Assert.IsTrue(ie.Target is IdentifierExpression); + Assert.AreEqual("myMethod", ((IdentifierExpression)ie.Target).Identifier); + } + + /* TODO port unit tests to new DOM + [Test] + public void GenericInvocationExpressionTest() + { + var expr = ParseUtilCSharp.ParseExpression("myMethod('a')"); + Assert.AreEqual(1, expr.Arguments.Count()); + Assert.IsTrue(expr.TargetObject is IdentifierExpression); + IdentifierExpression ident = (IdentifierExpression)expr.TargetObject; + Assert.AreEqual("myMethod", ident.Identifier); + Assert.AreEqual(1, ident.TypeArguments.Count); + Assert.AreEqual("System.Char", ident.TypeArguments[0].Type); + } + + [Test] + public void GenericInvocation2ExpressionTest() + { + var expr = ParseUtilCSharp.ParseExpression("myMethod()"); + Assert.AreEqual(0, expr.Arguments.Count); + Assert.IsTrue(expr.TargetObject is IdentifierExpression); + IdentifierExpression ident = (IdentifierExpression)expr.TargetObject; + Assert.AreEqual("myMethod", ident.Identifier); + Assert.AreEqual(2, ident.TypeArguments.Count); + Assert.AreEqual("T", ident.TypeArguments[0].Type); + Assert.IsFalse(ident.TypeArguments[0].IsKeyword); + Assert.AreEqual("System.Boolean", ident.TypeArguments[1].Type); + Assert.IsTrue(ident.TypeArguments[1].IsKeyword); + } + + [Test] + public void AmbiguousGrammarGenericMethodCall() + { + InvocationExpression ie = ParseUtilCSharp.ParseExpression("F(G(7))"); + Assert.IsTrue(ie.TargetObject is IdentifierExpression); + Assert.AreEqual(1, ie.Arguments.Count); + ie = (InvocationExpression)ie.Arguments[0]; + Assert.AreEqual(1, ie.Arguments.Count); + Assert.IsTrue(ie.Arguments[0] is PrimitiveExpression); + IdentifierExpression ident = (IdentifierExpression)ie.TargetObject; + Assert.AreEqual("G", ident.Identifier); + Assert.AreEqual(2, ident.TypeArguments.Count); + } + + [Test] + public void AmbiguousGrammarNotAGenericMethodCall() + { + BinaryOperatorExpression boe = ParseUtilCSharp.ParseExpression("F+y"); + Assert.AreEqual(BinaryOperatorType.GreaterThan, boe.Op); + Assert.IsTrue(boe.Left is BinaryOperatorExpression); + Assert.IsTrue(boe.Right is UnaryOperatorExpression); + } + + [Test] + public void InvalidNestedInvocationExpressionTest() + { + // this test was written because this bug caused the AbstractASTVisitor to crash + + InvocationExpression expr = ParseUtilCSharp.ParseExpression("WriteLine(myMethod(,))", true); + Assert.IsTrue(expr.TargetObject is IdentifierExpression); + Assert.AreEqual("WriteLine", ((IdentifierExpression)expr.TargetObject).Identifier); + + Assert.AreEqual(1, expr.Arguments.Count); // here a second null parameter was added incorrectly + + Assert.IsTrue(expr.Arguments[0] is InvocationExpression); + CheckSimpleInvoke((InvocationExpression)expr.Arguments[0]); + } + + [Test] + public void NestedInvocationPositions() + { + InvocationExpression expr = ParseUtilCSharp.ParseExpression("a.B().C(args)"); + Assert.AreEqual(new Location(8, 1), expr.StartLocation); + Assert.AreEqual(new Location(14, 1), expr.EndLocation); + MemberReferenceExpression mre = (MemberReferenceExpression)expr.TargetObject; + Assert.AreEqual(new Location(6, 1), mre.StartLocation); + Assert.AreEqual(new Location(8, 1), mre.EndLocation); + + Assert.AreEqual(new Location(4, 1), mre.TargetObject.StartLocation); + Assert.AreEqual(new Location(6, 1), mre.TargetObject.EndLocation); + } + + [Test] + public void InvocationOnGenericType() + { + InvocationExpression expr = ParseUtilCSharp.ParseExpression("A.Foo()"); + MemberReferenceExpression mre = (MemberReferenceExpression)expr.TargetObject; + Assert.AreEqual("Foo", mre.MemberName); + TypeReferenceExpression tre = (TypeReferenceExpression)mre.TargetObject; + Assert.AreEqual("A", tre.TypeReference.Type); + Assert.AreEqual("T", tre.TypeReference.GenericTypes[0].Type); + } + + [Test] + public void InvocationOnInnerClassInGenericType() + { + InvocationExpression expr = ParseUtilCSharp.ParseExpression("A.B.Foo()"); + MemberReferenceExpression mre = (MemberReferenceExpression)expr.TargetObject; + Assert.AreEqual("Foo", mre.MemberName); + MemberReferenceExpression mre2 = (MemberReferenceExpression)mre.TargetObject; + Assert.AreEqual("B", mre2.MemberName); + TypeReferenceExpression tre = (TypeReferenceExpression)mre2.TargetObject; + Assert.AreEqual("A", tre.TypeReference.Type); + Assert.AreEqual("T", tre.TypeReference.GenericTypes[0].Type); + } + + [Test] + public void InvocationOnGenericInnerClassInGenericType() + { + InvocationExpression expr = ParseUtilCSharp.ParseExpression("A.B.C.Foo()"); + MemberReferenceExpression mre = (MemberReferenceExpression)expr.TargetObject; + Assert.AreEqual("Foo", mre.MemberName); + TypeReferenceExpression tre = (TypeReferenceExpression)mre.TargetObject; + InnerClassTypeReference ictr = (InnerClassTypeReference)tre.TypeReference; + Assert.AreEqual("B.C", ictr.Type); + Assert.AreEqual(1, ictr.GenericTypes.Count); + Assert.AreEqual("U", ictr.GenericTypes[0].Type); + + Assert.AreEqual("A", ictr.BaseType.Type); + Assert.AreEqual(1, ictr.BaseType.GenericTypes.Count); + Assert.AreEqual("T", ictr.BaseType.GenericTypes[0].Type); + } + + [Test] + public void InvocationWithNamedArgument() + { + InvocationExpression expr = ParseUtilCSharp.ParseExpression("a(arg: ref v)"); + Assert.AreEqual(1, expr.Arguments.Count); + NamedArgumentExpression nae = (NamedArgumentExpression)expr.Arguments[0]; + Assert.AreEqual("arg", nae.Name); + DirectionExpression dir = (DirectionExpression)nae.Expression; + Assert.AreEqual(FieldDirection.Ref, dir.FieldDirection); + Assert.IsInstanceOf(dir.Expression); + }*/ + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IsExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IsExpressionTests.cs new file mode 100644 index 000000000..4b5039565 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/IsExpressionTests.cs @@ -0,0 +1,45 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class IsExpressionTests + { + [Test, Ignore] + public void GenericArrayIsExpression() + { + /* TODO + TypeOfIsExpression ce = ParseUtilCSharp.ParseExpression("o is List[]"); + Assert.AreEqual("List", ce.TypeReference.Type); + Assert.AreEqual("System.String", ce.TypeReference.GenericTypes[0].Type); + Assert.AreEqual(new int[] { 0 }, ce.TypeReference.RankSpecifier); + Assert.IsTrue(ce.Expression is IdentifierExpression);*/ + } + + [Test] + public void NullableIsExpression() + { + IsExpression ce = ParseUtilCSharp.ParseExpression("o is int?"); + ComposedType type = (ComposedType)ce.Type; + Assert.IsTrue(type.HasNullableSpecifier); + Assert.AreEqual("int", ((PrimitiveType)type.BaseType).Keyword); + Assert.IsTrue(ce.Expression is IdentifierExpression); + } + + [Test] + public void NullableIsExpressionInBinaryOperatorExpression() + { + BinaryOperatorExpression boe; + boe = ParseUtilCSharp.ParseExpression("o is int? == true"); + IsExpression ce = (IsExpression)boe.Left; + ComposedType type = (ComposedType)ce.Type; + Assert.IsTrue(type.HasNullableSpecifier); + Assert.AreEqual("int", ((PrimitiveType)type.BaseType).Keyword); + Assert.IsTrue(ce.Expression is IdentifierExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/LambdaExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/LambdaExpressionTests.cs new file mode 100644 index 000000000..5f4addd3e --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/LambdaExpressionTests.cs @@ -0,0 +1,89 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture, Ignore("Port unit tests")] + public class LambdaExpressionTests + { + static LambdaExpression ParseCSharp(string program) + { + return ParseUtilCSharp.ParseExpression(program); + } + + [Test] + public void ImplicitlyTypedExpressionBody() + { + /* + LambdaExpression e = ParseCSharp("(x) => x + 1"); + Assert.AreEqual("x", e.Parameters[0].ParameterName); + Assert.IsTrue(e.Parameters[0].TypeReference.IsNull); + Assert.IsTrue(e.ExpressionBody is BinaryOperatorExpression); + Assert.IsTrue(e.ReturnType.IsNull);*/ + throw new NotImplementedException(); + } + + /* TODO Port unit tests + [Test] + public void ImplicitlyTypedExpressionBodyWithoutParenthesis() + { + LambdaExpression e = ParseCSharp("x => x + 1"); + Assert.AreEqual("x", e.Parameters[0].ParameterName); + Assert.IsTrue(e.Parameters[0].TypeReference.IsNull); + Assert.IsTrue(e.ExpressionBody is BinaryOperatorExpression); + Assert.IsTrue(e.ReturnType.IsNull); + } + + [Test] + public void ImplicitlyTypedStatementBody() + { + LambdaExpression e = ParseCSharp("(x) => { return x + 1; }"); + Assert.AreEqual("x", e.Parameters[0].ParameterName); + Assert.IsTrue(e.Parameters[0].TypeReference.IsNull); + Assert.IsTrue(e.StatementBody.Children[0] is ReturnStatement); + Assert.IsTrue(e.ReturnType.IsNull); + } + + [Test] + public void ImplicitlyTypedStatementBodyWithoutParenthesis() + { + LambdaExpression e = ParseCSharp("x => { return x + 1; }"); + Assert.AreEqual("x", e.Parameters[0].ParameterName); + Assert.IsTrue(e.Parameters[0].TypeReference.IsNull); + Assert.IsTrue(e.StatementBody.Children[0] is ReturnStatement); + Assert.IsTrue(e.ReturnType.IsNull); + } + + [Test] + public void ExplicitlyTypedStatementBody() + { + LambdaExpression e = ParseCSharp("(int x) => { return x + 1; }"); + Assert.AreEqual("x", e.Parameters[0].ParameterName); + Assert.AreEqual("System.Int32", e.Parameters[0].TypeReference.Type); + Assert.IsTrue(e.StatementBody.Children[0] is ReturnStatement); + Assert.IsTrue(e.ReturnType.IsNull); + } + + [Test] + public void ExplicitlyTypedStatementBodyWithRefParameter() + { + LambdaExpression e = ParseCSharp("(ref int i) => i = 1"); + Assert.AreEqual("i", e.Parameters[0].ParameterName); + Assert.IsTrue((e.Parameters[0].ParamModifier & ParameterModifiers.Ref) == ParameterModifiers.Ref); + Assert.AreEqual("System.Int32", e.Parameters[0].TypeReference.Type); + Assert.IsTrue(e.ReturnType.IsNull); + } + + [Test] + public void LambdaExpressionContainingConditionalExpression() + { + LambdaExpression e = ParseCSharp("rr => rr != null ? rr.ResolvedType : null"); + Assert.AreEqual("rr", e.Parameters[0].ParameterName); + Assert.IsTrue(e.ExpressionBody is ConditionalExpression); + Assert.IsTrue(e.ReturnType.IsNull); + }*/ + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/MemberReferenceExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/MemberReferenceExpressionTests.cs new file mode 100644 index 000000000..3f9ce69eb --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/MemberReferenceExpressionTests.cs @@ -0,0 +1,76 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture, Ignore] + public class MemberReferenceExpressionTests + { + [Test] + public void SimpleFieldReferenceExpressionTest() + { + MemberReferenceExpression fre = ParseUtilCSharp.ParseExpression("myTargetObject.myField"); + //Assert.AreEqual("myField", fre.MemberName); + //Assert.IsTrue(fre.TargetObject is IdentifierExpression); + //Assert.AreEqual("myTargetObject", ((IdentifierExpression)fre.TargetObject).Identifier); + throw new NotImplementedException(); + } + + /* TODO port unit tests + [Test] + public void GenericFieldReferenceExpressionTest() + { + MemberReferenceExpression fre = ParseUtilCSharp.ParseExpression("SomeClass.myField"); + Assert.AreEqual("myField", fre.MemberName); + Assert.IsTrue(fre.TargetObject is TypeReferenceExpression); + TypeReference tr = ((TypeReferenceExpression)fre.TargetObject).TypeReference; + Assert.AreEqual("SomeClass", tr.Type); + Assert.AreEqual(1, tr.GenericTypes.Count); + Assert.AreEqual("System.String", tr.GenericTypes[0].Type); + } + + [Test] + public void FullNamespaceGenericFieldReferenceExpressionTest() + { + MemberReferenceExpression fre = ParseUtilCSharp.ParseExpression("Namespace.Subnamespace.SomeClass.myField"); + Assert.AreEqual("myField", fre.MemberName); + Assert.IsTrue(fre.TargetObject is TypeReferenceExpression); + TypeReference tr = ((TypeReferenceExpression)fre.TargetObject).TypeReference; + Assert.AreEqual("Namespace.Subnamespace.SomeClass", tr.Type); + Assert.AreEqual(1, tr.GenericTypes.Count); + Assert.AreEqual("System.String", tr.GenericTypes[0].Type); + } + + [Test] + public void GlobalFullNamespaceGenericFieldReferenceExpressionTest() + { + MemberReferenceExpression fre = ParseUtilCSharp.ParseExpression("global::Namespace.Subnamespace.SomeClass.myField"); + Assert.AreEqual("myField", fre.MemberName); + Assert.IsTrue(fre.TargetObject is TypeReferenceExpression); + TypeReference tr = ((TypeReferenceExpression)fre.TargetObject).TypeReference; + Assert.IsFalse(tr is InnerClassTypeReference); + Assert.AreEqual("Namespace.Subnamespace.SomeClass", tr.Type); + Assert.AreEqual(1, tr.GenericTypes.Count); + Assert.AreEqual("System.String", tr.GenericTypes[0].Type); + Assert.IsTrue(tr.IsGlobal); + } + + [Test] + public void NestedGenericFieldReferenceExpressionTest() + { + MemberReferenceExpression fre = ParseUtilCSharp.ParseExpression("MyType.InnerClass.myField"); + Assert.AreEqual("myField", fre.MemberName); + Assert.IsTrue(fre.TargetObject is TypeReferenceExpression); + InnerClassTypeReference ic = (InnerClassTypeReference)((TypeReferenceExpression)fre.TargetObject).TypeReference; + Assert.AreEqual("InnerClass", ic.Type); + Assert.AreEqual(1, ic.GenericTypes.Count); + Assert.AreEqual("System.Int32", ic.GenericTypes[0].Type); + Assert.AreEqual("MyType", ic.BaseType.Type); + Assert.AreEqual(1, ic.BaseType.GenericTypes.Count); + Assert.AreEqual("System.String", ic.BaseType.GenericTypes[0].Type); + }*/ + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ParenthesizedExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ParenthesizedExpressionTests.cs new file mode 100644 index 000000000..c60bcbf1f --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ParenthesizedExpressionTests.cs @@ -0,0 +1,21 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class ParenthesizedExpressionTests + { + [Test] + public void PrimitiveParenthesizedExpression() + { + ParenthesizedExpression p = ParseUtilCSharp.ParseExpression("((1))"); + Assert.IsTrue(p.Expression is ParenthesizedExpression); + p = (ParenthesizedExpression)p.Expression; + Assert.IsTrue(p.Expression is PrimitiveExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/PointerReferenceExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/PointerReferenceExpressionTests.cs new file mode 100644 index 000000000..f02c795e2 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/PointerReferenceExpressionTests.cs @@ -0,0 +1,21 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class PointerReferenceExpressionTests + { + [Test, Ignore("where did PointerReferenceExpression.MemberName go?")] + public void PointerReferenceExpressionTest() + { + PointerReferenceExpression pre = ParseUtilCSharp.ParseExpression("myObj.field->b"); + Assert.IsTrue(pre.Target is MemberReferenceExpression); + //Assert.AreEqual("b", pre.MemberName); + throw new NotImplementedException(); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/PrimitiveExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/PrimitiveExpressionTests.cs new file mode 100644 index 000000000..9b4b1efcc --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/PrimitiveExpressionTests.cs @@ -0,0 +1,203 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class PrimitiveExpressionTests + { + [Test] + public void HexIntegerTest1() + { + InvocationExpression invExpr = ParseUtilCSharp.ParseExpression("0xAFFE.ToString()"); + Assert.AreEqual(0, invExpr.Arguments.Count()); + Assert.IsTrue(invExpr.Target is MemberReferenceExpression); + MemberReferenceExpression fre = invExpr.Target as MemberReferenceExpression; + Assert.AreEqual("ToString", fre.MemberName); + + Assert.IsTrue(fre.Target is PrimitiveExpression); + PrimitiveExpression pe = fre.Target as PrimitiveExpression; + + Assert.AreEqual(0xAFFE, (int)pe.Value); + + } + + void CheckLiteral(string code, object value) + { + PrimitiveExpression pe = ParseUtilCSharp.ParseExpression(code); + Assert.AreEqual(value.GetType(), pe.Value.GetType()); + Assert.AreEqual(value, pe.Value); + } + + [Test] + public void DoubleTest1() + { + CheckLiteral(".5e-06", .5e-06); + } + + [Test] + public void CharTest1() + { + CheckLiteral("'\\u0356'", '\u0356'); + } + + [Test, Ignore("this special case isn't implemented yet")] + public void IntMinValueTest() + { + CheckLiteral("-2147483648", -2147483648); + } + + [Test] + public void IntMaxValueTest() + { + CheckLiteral("2147483647", 2147483647); // int + CheckLiteral("2147483648", 2147483648); // uint + } + + [Test, Ignore("this special case isn't implemented yet")] + public void LongMinValueTest() + { + CheckLiteral("-9223372036854775808", -9223372036854775808); + } + + [Test] + public void LongMaxValueTest() + { + CheckLiteral("9223372036854775807", 9223372036854775807); // long + CheckLiteral("9223372036854775808", 9223372036854775808); // ulong + } + + [Test] + public void StringTest1() + { + CheckLiteral("\"\\n\\t\\u0005 Hello World !!!\"", "\n\t\u0005 Hello World !!!"); + } + + [Test] + public void TestSingleDigit() + { + CheckLiteral("5", 5); + } + + [Test] + public void TestZero() + { + CheckLiteral("0", 0); + } + + [Test] + public void TestInteger() + { + CheckLiteral("66", 66); + } + + [Test] + public void TestNonOctalInteger() + { + // C# does not have octal integers, so 077 should parse to 77 + Assert.IsTrue(077 == 77); + + CheckLiteral("077", 077); + CheckLiteral("056", 056); + } + + [Test] + public void TestHexadecimalInteger() + { + CheckLiteral("0x99F", 0x99F); + CheckLiteral("0xAB1f", 0xAB1f); + CheckLiteral("0xffffffff", 0xffffffff); + CheckLiteral("0xffffffffL", 0xffffffffL); + CheckLiteral("0xffffffffuL", 0xffffffffuL); + } + + [Test] + public void InvalidHexadecimalInteger() + { + // don't check result, just make sure there is no exception + ParseUtilCSharp.ParseExpression("0x2GF", expectErrors: true); + ParseUtilCSharp.ParseExpression("0xG2F", expectErrors: true); + ParseUtilCSharp.ParseExpression("0x", expectErrors: true); // SD-457 + // hexadecimal integer >ulong.MaxValue + ParseUtilCSharp.ParseExpression("0xfedcba98765432100", expectErrors: true); + } + + [Test] + public void TestLongHexadecimalInteger() + { + CheckLiteral("0x4244636f446c6d58", 0x4244636f446c6d58); + CheckLiteral("0xf244636f446c6d58", 0xf244636f446c6d58); + } + + [Test] + public void TestLongInteger() + { + CheckLiteral("9223372036854775807", 9223372036854775807); // long.MaxValue + CheckLiteral("9223372036854775808", 9223372036854775808); // long.MaxValue+1 + CheckLiteral("18446744073709551615", 18446744073709551615); // ulong.MaxValue + } + + [Test] + public void TestTooLongInteger() + { + // ulong.MaxValue+1 + ParseUtilCSharp.ParseExpression("18446744073709551616", expectErrors: true); + + CheckLiteral("18446744073709551616f", 18446744073709551616f); // ulong.MaxValue+1 as float + CheckLiteral("18446744073709551616d", 18446744073709551616d); // ulong.MaxValue+1 as double + CheckLiteral("18446744073709551616m", 18446744073709551616m); // ulong.MaxValue+1 as decimal + } + + [Test] + public void TestDouble() + { + CheckLiteral("1.0", 1.0); + CheckLiteral("1.1", 1.1); + CheckLiteral("1.1e-2", 1.1e-2); + } + + [Test] + public void TestFloat() + { + CheckLiteral("1f", 1f); + CheckLiteral("1.0f", 1.0f); + CheckLiteral("1.1f", 1.1f); + CheckLiteral("1.1e-2f", 1.1e-2f); + } + + [Test] + public void TestDecimal() + { + CheckLiteral("1m", 1m); + CheckLiteral("1.0m", 1.0m); + CheckLiteral("1.1m", 1.1m); + CheckLiteral("1.1e-2m", 1.1e-2m); + CheckLiteral("2.0e-5m", 2.0e-5m); + } + + [Test] + public void TestString() + { + CheckLiteral(@"@""-->""""<--""", @"-->""<--"); + CheckLiteral(@"""-->\""<--""", "-->\"<--"); + + CheckLiteral(@"""\U00000041""", "\U00000041"); + CheckLiteral(@"""\U00010041""", "\U00010041"); + } + + [Test] + public void TestCharLiteral() + { + CheckLiteral(@"'a'", 'a'); + CheckLiteral(@"'\u0041'", '\u0041'); + CheckLiteral(@"'\x41'", '\x41'); + CheckLiteral(@"'\x041'", '\x041'); + CheckLiteral(@"'\x0041'", '\x0041'); + CheckLiteral(@"'\U00000041'", '\U00000041'); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/QueryExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/QueryExpressionTests.cs new file mode 100644 index 000000000..7b1d18e03 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/QueryExpressionTests.cs @@ -0,0 +1,109 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture, Ignore] + public class QueryExpressionTests + { + [Test] + public void SimpleExpression() + { + /* + QueryExpression qe = ParseUtilCSharp.ParseExpression( + "from c in customers where c.City == \"London\" select c" + ); + Assert.AreEqual("c", qe.FromClause.Sources.First().Identifier); + Assert.AreEqual("customers", ((IdentifierExpression)qe.FromClause.Sources.First().Expression).Identifier); + Assert.AreEqual(1, qe.MiddleClauses.Count); + Assert.IsInstanceOf(typeof(QueryExpressionWhereClause), qe.MiddleClauses[0]); + QueryExpressionWhereClause wc = (QueryExpressionWhereClause)qe.MiddleClauses[0]; + Assert.IsInstanceOf(typeof(BinaryOperatorExpression), wc.Condition); + Assert.IsInstanceOf(typeof(QueryExpressionSelectClause), qe.SelectOrGroupClause);*/ + throw new NotImplementedException(); + } + + /* TODO port unit tests + [Test] + public void ExpressionWithType1() + { + QueryExpression qe = ParseUtilCSharp.ParseExpression( + "from Customer c in customers select c" + ); + Assert.AreEqual("c", qe.FromClause.Sources.First().Identifier); + Assert.AreEqual("Customer", qe.FromClause.Sources.First().Type.ToString()); + Assert.AreEqual("customers", ((IdentifierExpression)qe.FromClause.Sources.First().Expression).Identifier); + Assert.IsInstanceOf(typeof(QueryExpressionSelectClause), qe.SelectOrGroupClause); + } + + [Test] + public void ExpressionWithType2() + { + QueryExpression qe = ParseUtilCSharp.ParseExpression( + "from int c in customers select c" + ); + Assert.AreEqual("c", qe.FromClause.Sources.First().Identifier); + Assert.AreEqual("System.Int32", qe.FromClause.Sources.First().Type.Type); + Assert.AreEqual("customers", ((IdentifierExpression)qe.FromClause.Sources.First().Expression).Identifier); + Assert.IsInstanceOf(typeof(QueryExpressionSelectClause), qe.SelectOrGroupClause); + } + + + [Test] + public void ExpressionWithType3() + { + QueryExpression qe = ParseUtilCSharp.ParseExpression( + "from S? c in customers select c" + ); + Assert.AreEqual("c", qe.FromClause.Sources.First().Identifier); + Assert.AreEqual("System.Nullable>", qe.FromClause.Sources.First().Type.ToString()); + Assert.AreEqual("customers", ((IdentifierExpression)qe.FromClause.Sources.First().Expression).Identifier); + Assert.IsInstanceOf(typeof(QueryExpressionSelectClause), qe.SelectOrGroupClause); + } + + [Test] + public void MultipleGenerators() + { + QueryExpression qe = ParseUtilCSharp.ParseExpression(@" +from c in customers +where c.City == ""London"" +from o in c.Orders +where o.OrderDate.Year == 2005 +select new { c.Name, o.OrderID, o.Total }"); + Assert.AreEqual(3, qe.MiddleClauses.Count); + Assert.IsInstanceOf(typeof(QueryExpressionWhereClause), qe.MiddleClauses[0]); + Assert.IsInstanceOf(typeof(QueryExpressionFromClause), qe.MiddleClauses[1]); + Assert.IsInstanceOf(typeof(QueryExpressionWhereClause), qe.MiddleClauses[2]); + + Assert.IsInstanceOf(typeof(QueryExpressionSelectClause), qe.SelectOrGroupClause); + } + + [Test] + public void ExpressionWithOrderBy() + { + QueryExpression qe = ParseUtilCSharp.ParseExpression( + "from c in customers orderby c.Name select c" + ); + Assert.AreEqual("c", qe.FromClause.Sources.First().Identifier); + Assert.AreEqual("customers", ((IdentifierExpression)qe.FromClause.Sources.First().Expression).Identifier); + Assert.IsInstanceOf(typeof(QueryExpressionOrderClause), qe.MiddleClauses[0]); + Assert.IsInstanceOf(typeof(QueryExpressionSelectClause), qe.SelectOrGroupClause); + } + + [Test] + public void ExpressionWithOrderByAndLet() + { + QueryExpression qe = ParseUtilCSharp.ParseExpression( + "from c in customers orderby c.Name let x = c select x" + ); + Assert.AreEqual("c", qe.FromClause.Sources.First().Identifier); + Assert.AreEqual("customers", ((IdentifierExpression)qe.FromClause.Sources.First().Expression).Identifier); + Assert.IsInstanceOf(typeof(QueryExpressionOrderClause), qe.MiddleClauses[0]); + Assert.IsInstanceOf(typeof(QueryExpressionLetClause), qe.MiddleClauses[1]); + Assert.IsInstanceOf(typeof(QueryExpressionSelectClause), qe.SelectOrGroupClause); + }*/ + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/SizeOfExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/SizeOfExpressionTests.cs new file mode 100644 index 000000000..a50c1b77f --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/SizeOfExpressionTests.cs @@ -0,0 +1,19 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class SizeOfExpressionTests + { + [Test, Ignore("type references not implemented yet")] + public void SizeOfExpressionTest() + { + SizeOfExpression soe = ParseUtilCSharp.ParseExpression("sizeof(MyType)"); + Assert.AreEqual("MyType", soe.Type); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/StackAllocExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/StackAllocExpressionTests.cs new file mode 100644 index 000000000..038925a42 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/StackAllocExpressionTests.cs @@ -0,0 +1,19 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class StackAllocExpressionTests + { + [Test, Ignore] + public void StackAllocExpressionTest() + { + var sae = ParseUtilCSharp.ParseExpression("stackalloc int[100]"); + throw new NotImplementedException(); // TODO: verify type + length expression + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ThisReferenceExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ThisReferenceExpressionTests.cs new file mode 100644 index 000000000..7c547adea --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ThisReferenceExpressionTests.cs @@ -0,0 +1,18 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class ThisReferenceExpressionTests + { + [Test] + public void TestMethod() + { + ParseUtilCSharp.ParseExpression("this"); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/TypeOfExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/TypeOfExpressionTests.cs new file mode 100644 index 000000000..599aae19f --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/TypeOfExpressionTests.cs @@ -0,0 +1,91 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture, Ignore] + public class TypeOfExpressionTests + { + [Test] + public void SimpleTypeOfExpressionTest() + { + //TypeOfExpression toe = ParseUtilCSharp.ParseExpression("typeof(MyNamespace.N1.MyType)"); + //Assert.AreEqual("MyNamespace.N1.MyType", toe.TypeReference.Type); + throw new NotImplementedException(); + } + + /* TODO + [Test] + public void GlobalTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtilCSharp.ParseExpression("typeof(global::System.Console)"); + Assert.AreEqual("System.Console", toe.TypeReference.Type); + } + + [Test] + public void PrimitiveTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtilCSharp.ParseExpression("typeof(int)"); + Assert.AreEqual("System.Int32", toe.TypeReference.Type); + } + + [Test] + public void VoidTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtilCSharp.ParseExpression("typeof(void)"); + Assert.AreEqual("System.Void", toe.TypeReference.Type); + } + + [Test] + public void ArrayTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtilCSharp.ParseExpression("typeof(MyType[])"); + Assert.AreEqual("MyType", toe.TypeReference.Type); + Assert.AreEqual(new int[] {0}, toe.TypeReference.RankSpecifier); + } + + [Test] + public void GenericTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtilCSharp.ParseExpression("typeof(MyNamespace.N1.MyType)"); + Assert.AreEqual("MyNamespace.N1.MyType", toe.TypeReference.Type); + Assert.AreEqual("System.String", toe.TypeReference.GenericTypes[0].Type); + } + + [Test] + public void NestedGenericTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtilCSharp.ParseExpression("typeof(MyType.InnerClass.InnerInnerClass)"); + InnerClassTypeReference ic = (InnerClassTypeReference)toe.TypeReference; + Assert.AreEqual("InnerInnerClass", ic.Type); + Assert.AreEqual(0, ic.GenericTypes.Count); + ic = (InnerClassTypeReference)ic.BaseType; + Assert.AreEqual("InnerClass", ic.Type); + Assert.AreEqual(1, ic.GenericTypes.Count); + Assert.AreEqual("System.Int32", ic.GenericTypes[0].Type); + Assert.AreEqual("MyType", ic.BaseType.Type); + Assert.AreEqual(1, ic.BaseType.GenericTypes.Count); + Assert.AreEqual("System.String", ic.BaseType.GenericTypes[0].Type); + } + + [Test] + public void NullableTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtilCSharp.ParseExpression("typeof(MyStruct?)"); + Assert.AreEqual("System.Nullable", toe.TypeReference.Type); + Assert.AreEqual("MyStruct", toe.TypeReference.GenericTypes[0].Type); + } + + [Test] + public void UnboundTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtilCSharp.ParseExpression("typeof(MyType<,>)"); + Assert.AreEqual("MyType", toe.TypeReference.Type); + Assert.IsTrue(toe.TypeReference.GenericTypes[0].IsNull); + Assert.IsTrue(toe.TypeReference.GenericTypes[1].IsNull); + }*/ + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/TypeReferenceExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/TypeReferenceExpressionTests.cs new file mode 100644 index 000000000..cf32e089d --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/TypeReferenceExpressionTests.cs @@ -0,0 +1,46 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture, Ignore] + public class TypeReferenceExpressionTests + { + [Test] + public void GlobalTypeReferenceExpression() + { + /*TypeReferenceExpression tr = ParseUtilCSharp.ParseExpression("global::System"); + Assert.AreEqual("System", tr.TypeReference.Type); + Assert.IsTrue(tr.TypeReference.IsGlobal);*/ + throw new NotImplementedException(); + } + + /* TODO + [Test] + public void GlobalTypeReferenceExpressionWithoutTypeName() + { + TypeReferenceExpression tr = ParseUtilCSharp.ParseExpression("global::", true); + Assert.AreEqual("?", tr.TypeReference.Type); + Assert.IsTrue(tr.TypeReference.IsGlobal); + } + + [Test] + public void IntReferenceExpression() + { + MemberReferenceExpression fre = ParseUtilCSharp.ParseExpression("int.MaxValue"); + Assert.AreEqual("MaxValue", fre.MemberName); + Assert.AreEqual("System.Int32", ((TypeReferenceExpression)fre.TargetObject).TypeReference.Type); + } + + [Test] + public void StandaloneIntReferenceExpression() + { + TypeReferenceExpression tre = ParseUtilCSharp.ParseExpression("int"); + Assert.AreEqual("System.Int32", tre.TypeReference.Type); + } + */ + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/UnaryOperatorExpressionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/UnaryOperatorExpressionTests.cs new file mode 100644 index 000000000..c704b8857 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/UnaryOperatorExpressionTests.cs @@ -0,0 +1,95 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Expression +{ + [TestFixture] + public class UnaryOperatorExpressionTests + { + void TestUnaryOperatorExpressionTest(string program, UnaryOperatorType op) + { + UnaryOperatorExpression uoe = ParseUtilCSharp.ParseExpression(program); + Assert.AreEqual(op, uoe.Operator); + + Assert.IsTrue(uoe.Expression is IdentifierExpression); + } + + [Test] + public void NotTest() + { + TestUnaryOperatorExpressionTest("!a", UnaryOperatorType.Not); + } + + [Test] + public void BitNotTest() + { + TestUnaryOperatorExpressionTest("~a", UnaryOperatorType.BitNot); + } + + [Test] + public void MinusTest() + { + TestUnaryOperatorExpressionTest("-a", UnaryOperatorType.Minus); + } + + [Test] + public void PlusTest() + { + TestUnaryOperatorExpressionTest("+a", UnaryOperatorType.Plus); + } + + [Test] + public void IncrementTest() + { + TestUnaryOperatorExpressionTest("++a", UnaryOperatorType.Increment); + } + + [Test] + public void DecrementTest() + { + TestUnaryOperatorExpressionTest("--a", UnaryOperatorType.Decrement); + } + + [Test] + public void PostIncrementTest() + { + TestUnaryOperatorExpressionTest("a++", UnaryOperatorType.PostIncrement); + } + + [Test] + public void PostDecrementTest() + { + TestUnaryOperatorExpressionTest("a--", UnaryOperatorType.PostDecrement); + } + + [Test] + public void StarTest() + { + TestUnaryOperatorExpressionTest("*a", UnaryOperatorType.Dereference); + } + + [Test] + public void BitWiseAndTest() + { + TestUnaryOperatorExpressionTest("&a", UnaryOperatorType.AddressOf); + } + + [Test] + public void DereferenceAfterCast() + { + UnaryOperatorExpression uoe = ParseUtilCSharp.ParseExpression("*((SomeType*) &w)"); + Assert.AreEqual(UnaryOperatorType.Dereference, uoe.Operator); + ParenthesizedExpression pe = (ParenthesizedExpression)uoe.Expression; + CastExpression ce = (CastExpression)pe.Expression; + //Assert.AreEqual("SomeType", ce.CastTo.Type); + //Assert.AreEqual(1, ce.CastTo.PointerNestingLevel); + Assert.Ignore("need to check target type"); // TODO + + UnaryOperatorExpression adrOf = (UnaryOperatorExpression)ce.Expression; + Assert.AreEqual(UnaryOperatorType.AddressOf, adrOf.Operator); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/AttributeSectionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/AttributeSectionTests.cs new file mode 100644 index 000000000..ce21addc4 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/AttributeSectionTests.cs @@ -0,0 +1,68 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.GeneralScope +{ + [TestFixture, Ignore] + public class AttributeSectionTests + { + [Test, Ignore] + public void GlobalAttributeCSharp() + { + string program = @"[global::Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] +[someprefix::DesignerGenerated()] +public class Form1 { +}"; + // TODO This old NRefactory test checked that [global] attributes are incorrectly applied to the following type??? + + //TypeDeclaration decl = ParseUtilCSharp.ParseGlobal(program); + //Assert.AreEqual("Microsoft.VisualBasic.CompilerServices.DesignerGenerated", decl.Attributes.First().Attributes.Single().Name); + //Assert.AreEqual("someprefix.DesignerGenerated", decl.Attributes.Last().Attributes.Single().Name); + } + + [Test] + public void AssemblyAttributeCSharp() + { + string program = @"[assembly: System.Attribute()]"; + AttributeSection decl = ParseUtilCSharp.ParseGlobal(program); + Assert.AreEqual(new AstLocation(1, 1), decl.StartLocation); + Assert.AreEqual("assembly", decl.AttributeTarget); + } + + [Test] + public void AssemblyAttributeCSharpWithNamedArguments() + { + string program = @"[assembly: Foo(1, namedArg: 2, prop = 3)]"; + AttributeSection decl = ParseUtilCSharp.ParseGlobal(program); + Assert.AreEqual("assembly", decl.AttributeTarget); + var a = decl.Attributes.Single(); + Assert.AreEqual("Foo", a.Type); + Assert.AreEqual(3, a.Arguments.Count()); + + // TODO: check arguments + } + + [Test] + public void ModuleAttributeCSharp() + { + string program = @"[module: System.Attribute()]"; + AttributeSection decl = ParseUtilCSharp.ParseGlobal(program); + Assert.AreEqual(new AstLocation(1, 1), decl.StartLocation); + Assert.AreEqual(AttributeTarget.Module, decl.AttributeTarget); + } + + [Test] + public void TypeAttributeCSharp() + { + string program = @"[type: System.Attribute()] class Test {}"; + TypeDeclaration type = ParseUtilCSharp.ParseGlobal(program); + AttributeSection decl = type.Attributes.Single(); + Assert.AreEqual(new AstLocation(1, 1), decl.StartLocation); + Assert.AreEqual(AttributeTarget.Type, decl.AttributeTarget); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/DelegateDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/DelegateDeclarationTests.cs new file mode 100644 index 000000000..51e046976 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/DelegateDeclarationTests.cs @@ -0,0 +1,77 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.GeneralScope +{ + [TestFixture, Ignore("delegates are completely broken at the moment")] + public class DelegateDeclarationTests + { + void TestParameters(DelegateDeclaration dd) + { + Assert.AreEqual(3, dd.Parameters.Count()); + + Assert.AreEqual("a", ((ParameterDeclaration)dd.Parameters.ElementAt(0)).Name); + //Assert.AreEqual("System.Int32", ((ParameterDeclaration)dd.Parameters.ElementAt(0)).TypeReference.Type); + Assert.Ignore("check types"); // TODO + Assert.AreEqual("secondParam", ((ParameterDeclaration)dd.Parameters.ElementAt(1)).Name); + //Assert.AreEqual("System.Int32", ((ParameterDeclaration)dd.Parameters.ElementAt(1)).TypeReference.Type); + + Assert.AreEqual("lastParam", ((ParameterDeclaration)dd.Parameters.ElementAt(2)).Name); + //Assert.AreEqual("MyObj", ((ParameterDeclaration)dd.Parameters.ElementAt(2)).TypeReference.Type); + } + + [Test] + public void SimpleCSharpDelegateDeclarationTest() + { + string program = "public delegate void MyDelegate(int a, int secondParam, MyObj lastParam);\n"; + DelegateDeclaration dd = ParseUtilCSharp.ParseGlobal(program); + Assert.AreEqual("MyDelegate", dd.Name); + //Assert.AreEqual("System.Void", dd.ReturnType.Type); + TestParameters(dd); + } + + [Test, Ignore] + public void DelegateWithoutNameDeclarationTest() + { + string program = "public delegate void(int a, int secondParam, MyObj lastParam);\n"; + DelegateDeclaration dd = ParseUtilCSharp.ParseGlobal(program, true); + //Assert.AreEqual("System.Void", dd.ReturnType.Type); + //Assert.AreEqual("?", dd.Name); + TestParameters(dd); + } + + [Test, Ignore] + public void GenericDelegateDeclarationTest() + { + string program = "public delegate T CreateObject() where T : ICloneable;\n"; + DelegateDeclaration dd = ParseUtilCSharp.ParseGlobal(program); + Assert.AreEqual("CreateObject", dd.Name); + //Assert.AreEqual("T", dd.ReturnType.Type); + Assert.AreEqual(0, dd.Parameters.Count()); + /*Assert.AreEqual(1, dd.Templates.Count); + Assert.AreEqual("T", dd.Templates[0].Name); + Assert.AreEqual(1, dd.Templates[0].Bases.Count); + Assert.AreEqual("ICloneable", dd.Templates[0].Bases[0].Type);*/ throw new NotImplementedException(); + } + + [Test] + public void DelegateDeclarationInNamespace() + { + string program = "namespace N { delegate void MyDelegate(); }"; + NamespaceDeclaration nd = ParseUtilCSharp.ParseGlobal(program); + Assert.AreEqual("MyDelegate", ((DelegateDeclaration)nd.Members.Single()).Name); + } + + [Test, Ignore("inner classes not yet implemented")] + public void DelegateDeclarationInClass() + { + string program = "class Outer { delegate void Inner(); }"; + TypeDeclaration td = ParseUtilCSharp.ParseGlobal(program); + Assert.AreEqual("Inner", ((DelegateDeclaration)td.Members.Single()).Name); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/NamespaceDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/NamespaceDeclarationTests.cs new file mode 100644 index 000000000..bec573270 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/NamespaceDeclarationTests.cs @@ -0,0 +1,36 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.GeneralScope +{ + [TestFixture] + public class NamespaceDeclarationTests + { + [Test] + public void SimpleNamespaceTest() + { + string program = "namespace TestNamespace {\n" + + "}\n"; + NamespaceDeclaration ns = ParseUtilCSharp.ParseGlobal(program); + Assert.AreEqual("TestNamespace", ns.Name); + } + + [Test] + public void NestedNamespaceTest() + { + string program = "namespace N1 {//TestNamespace\n" + + " namespace N2 {// Declares a namespace named N2 within N1.\n" + + " }\n" + + "}\n"; + NamespaceDeclaration ns = ParseUtilCSharp.ParseGlobal(program); + + Assert.AreEqual("N1", ns.Name); + + Assert.AreEqual("N2", ns.Children.OfType().Single().Name); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/TypeDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/TypeDeclarationTests.cs new file mode 100644 index 000000000..525306bd6 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/TypeDeclarationTests.cs @@ -0,0 +1,240 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.GeneralScope +{ + [TestFixture] + public class TypeDeclarationTests + { + [Test] + public void SimpleClassTypeDeclarationTest() + { + TypeDeclaration td = ParseUtilCSharp.ParseGlobal("class MyClass : My.Base.Class { }"); + + Assert.AreEqual(ClassType.Class, td.ClassType); + Assert.AreEqual("MyClass", td.Name); + //Assert.AreEqual("My.Base.Class", td.BaseTypes[0].Type); + Assert.Ignore("need to check base type"); // TODO + Assert.AreEqual(Modifiers.None, td.Modifiers); + } + + [Test] + public void SimpleClassRegionTest() + { + const string program = "class MyClass\n{\n}\n"; + TypeDeclaration td = ParseUtilCSharp.ParseGlobal(program); + Assert.AreEqual(1, td.StartLocation.Line, "StartLocation.Y"); + Assert.AreEqual(1, td.StartLocation.Column, "StartLocation.X"); + AstLocation bodyStartLocation = td.GetChildByRole(AstNode.Roles.LBrace).PrevSibling.EndLocation; + Assert.AreEqual(1, bodyStartLocation.Line, "BodyStartLocation.Y"); + Assert.AreEqual(14, bodyStartLocation.Column, "BodyStartLocation.X"); + Assert.AreEqual(3, td.EndLocation.Line, "EndLocation.Y"); + Assert.AreEqual(2, td.EndLocation.Column, "EndLocation.Y"); + } + + [Test, Ignore("partial modifier is broken")] + public void SimplePartialClassTypeDeclarationTest() + { + TypeDeclaration td = ParseUtilCSharp.ParseGlobal("partial class MyClass { }"); + Assert.IsFalse(td.IsNull); + Assert.AreEqual(ClassType.Class, td.ClassType); + Assert.AreEqual("MyClass", td.Name); + Assert.AreEqual(Modifiers.Partial, td.Modifiers); + } + + [Test, Ignore("nested classes are broken")] + public void NestedClassesTest() + { + TypeDeclaration td = ParseUtilCSharp.ParseGlobal("class MyClass { partial class P1 {} public partial class P2 {} static class P3 {} internal static class P4 {} }"); + Assert.IsFalse(td.IsNull); + Assert.AreEqual(ClassType.Class, td.ClassType); + Assert.AreEqual("MyClass", td.Name); + Assert.AreEqual(Modifiers.Partial, ((TypeDeclaration)td.Members.ElementAt(0)).Modifiers); + Assert.AreEqual(Modifiers.Partial | Modifiers.Public, ((TypeDeclaration)td.Members.ElementAt(1)).Modifiers); + Assert.AreEqual(Modifiers.Static, ((TypeDeclaration)td.Members.ElementAt(2)).Modifiers); + Assert.AreEqual(Modifiers.Static | Modifiers.Internal, ((TypeDeclaration)td.Members.ElementAt(3)).Modifiers); + } + + [Test] + public void SimpleStaticClassTypeDeclarationTest() + { + TypeDeclaration td = ParseUtilCSharp.ParseGlobal("static class MyClass { }"); + Assert.IsFalse(td.IsNull); + Assert.AreEqual(ClassType.Class, td.ClassType); + Assert.AreEqual("MyClass", td.Name); + Assert.AreEqual(Modifiers.Static, td.Modifiers); + } + + [Test, Ignore] + public void GenericClassTypeDeclarationTest() + { + TypeDeclaration td = ParseUtilCSharp.ParseGlobal("public class G {}"); + + Assert.AreEqual(ClassType.Class, td.ClassType); + Assert.AreEqual("G", td.Name); + Assert.AreEqual(Modifiers.Public, td.Modifiers); + /*Assert.AreEqual(0, td.BaseTypes.Count); + Assert.AreEqual(1, td.TypeArguments.Count()); + Assert.AreEqual("T", td.TypeArguments.Single().Name);*/ throw new NotImplementedException(); + } + + + [Test, Ignore] + public void GenericClassWithWhere() + { + string declr = @" +public class Test where T : IMyInterface +{ +} +"; + TypeDeclaration td = ParseUtilCSharp.ParseGlobal(declr); + + Assert.AreEqual(ClassType.Class, td.ClassType); + Assert.AreEqual("Test", td.Name); + + /*Assert.AreEqual(1, td.Templates.Count); + Assert.AreEqual("T", td.Templates[0].Name); + Assert.AreEqual("IMyInterface", td.Templates[0].Bases[0].Type);*/ throw new NotImplementedException(); + } + + [Test, Ignore] + public void ComplexGenericClassTypeDeclarationTest() + { + string declr = @" +public class Generic : System.IComparable where S : G where T : MyNamespace.IMyInterface +{ +} +"; + TypeDeclaration td = ParseUtilCSharp.ParseGlobal(declr); + + Assert.AreEqual(ClassType.Class, td.ClassType); + Assert.AreEqual("Generic", td.Name); + Assert.AreEqual(Modifiers.Public, td.Modifiers); + /*Assert.AreEqual(1, td.BaseTypes.Count); + Assert.AreEqual("System.IComparable", td.BaseTypes[0].Type); + + Assert.AreEqual(2, td.Templates.Count); + Assert.AreEqual("T", td.Templates[0].Name); + Assert.AreEqual("MyNamespace.IMyInterface", td.Templates[0].Bases[0].Type); + + Assert.AreEqual("S", td.Templates[1].Name); + Assert.AreEqual("G", td.Templates[1].Bases[0].Type); + Assert.AreEqual(1, td.Templates[1].Bases[0].GenericTypes.Count); + Assert.IsTrue(td.Templates[1].Bases[0].GenericTypes[0].IsArrayType); + Assert.AreEqual("T", td.Templates[1].Bases[0].GenericTypes[0].Type); + Assert.AreEqual(new int[] {0}, td.Templates[1].Bases[0].GenericTypes[0].RankSpecifier);*/ throw new NotImplementedException(); + } + + [Test, Ignore] + public void ComplexClassTypeDeclarationTest() + { + string declr = @" +[MyAttr()] +public abstract class MyClass : MyBase, Interface1, My.Test.Interface2 +{ +} +"; + TypeDeclaration td = ParseUtilCSharp.ParseGlobal(declr); + + Assert.AreEqual(ClassType.Class, td.ClassType); + Assert.AreEqual("MyClass", td.Name); + Assert.AreEqual(Modifiers.Public | Modifiers.Abstract, td.Modifiers); + Assert.AreEqual(1, td.Attributes.Count()); + /* Assert.AreEqual(3, td.BaseTypes.Count); + Assert.AreEqual("MyBase", td.BaseTypes[0].Type); + Assert.AreEqual("Interface1", td.BaseTypes[1].Type); + Assert.AreEqual("My.Test.Interface2", td.BaseTypes[2].Type);*/ throw new NotImplementedException(); + } + + [Test] + public void SimpleStructTypeDeclarationTest() + { + TypeDeclaration td = ParseUtilCSharp.ParseGlobal("struct MyStruct {}"); + + Assert.AreEqual(ClassType.Struct, td.ClassType); + Assert.AreEqual("MyStruct", td.Name); + } + + [Test] + public void SimpleInterfaceTypeDeclarationTest() + { + TypeDeclaration td = ParseUtilCSharp.ParseGlobal("interface MyInterface {}"); + + Assert.AreEqual(ClassType.Interface, td.ClassType); + Assert.AreEqual("MyInterface", td.Name); + } + + [Test] + public void SimpleEnumTypeDeclarationTest() + { + TypeDeclaration td = ParseUtilCSharp.ParseGlobal("enum MyEnum {}"); + + Assert.AreEqual(ClassType.Enum, td.ClassType); + Assert.AreEqual("MyEnum", td.Name); + } + + [Test, Ignore] + public void ContextSensitiveKeywordTest() + { + TypeDeclaration td = ParseUtilCSharp.ParseGlobal("partial class partial<[partial: where] where> where where : partial { }"); + + Assert.AreEqual(Modifiers.Partial, td.Modifiers); + Assert.AreEqual("partial", td.Name); + + /* + Assert.AreEqual(1, td.Templates.Count); + TemplateDefinition tp = td.Templates[0]; + Assert.AreEqual("where", tp.Name); + + Assert.AreEqual(1, tp.Attributes.Count); + Assert.AreEqual("partial", tp.Attributes[0].AttributeTarget); + Assert.AreEqual(1, tp.Attributes[0].Attributes.Count); + Assert.AreEqual("where", tp.Attributes[0].Attributes[0].Name); + + Assert.AreEqual(1, tp.Bases.Count); + Assert.AreEqual("partial", tp.Bases[0].Type); + Assert.AreEqual("where", tp.Bases[0].GenericTypes[0].Type);*/ throw new NotImplementedException(); + } + + [Test] + public void TypeInNamespaceTest() + { + NamespaceDeclaration ns = ParseUtilCSharp.ParseGlobal("namespace N { class MyClass { } }"); + + Assert.AreEqual("N", ns.Name); + Assert.AreEqual("MyClass", ((TypeDeclaration)ns.Members.Single()).Name); + } + + [Test] + public void StructInNamespaceTest() + { + NamespaceDeclaration ns = ParseUtilCSharp.ParseGlobal("namespace N { struct MyClass { } }"); + + Assert.AreEqual("N", ns.Name); + Assert.AreEqual("MyClass", ((TypeDeclaration)ns.Members.Single()).Name); + } + + [Test] + public void EnumInNamespaceTest() + { + NamespaceDeclaration ns = ParseUtilCSharp.ParseGlobal("namespace N { enum MyClass { } }"); + + Assert.AreEqual("N", ns.Name); + Assert.AreEqual("MyClass", ((TypeDeclaration)ns.Members.Single()).Name); + } + + [Test] + public void InterfaceInNamespaceTest() + { + NamespaceDeclaration ns = ParseUtilCSharp.ParseGlobal("namespace N { interface MyClass { } }"); + + Assert.AreEqual("N", ns.Name); + Assert.AreEqual("MyClass", ((TypeDeclaration)ns.Members.Single()).Name); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/UsingDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/UsingDeclarationTests.cs new file mode 100644 index 000000000..d79e33fe2 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/UsingDeclarationTests.cs @@ -0,0 +1,102 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.IO; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.GeneralScope +{ + [TestFixture] + public class UsingDeclarationTests + { + [Test] + [Ignore("error reporting not yet implemented")] + public void WrongUsingTest() + { + string program = "using\n"; + CSharpParser parser = new CSharpParser(); + CompilationUnit cu = parser.Parse(new StringReader(program)); + Assert.AreEqual(0, cu.Children.Count()); + Assert.IsTrue(parser.HasErrors); + } + + [Test] + public void DeclarationTest() + { + string program = "using System;\n" + + "using My.Name.Space;\n"; + CSharpParser parser = new CSharpParser(); + CompilationUnit cu = parser.Parse(new StringReader(program)); + Assert.IsFalse(parser.HasErrors); + + Assert.AreEqual(2, cu.Children.Count()); + Assert.IsTrue(cu.Children.ElementAt(0) is UsingDeclaration); + Assert.IsFalse(cu.Children.ElementAt(0) is UsingAliasDeclaration); + UsingDeclaration ud = (UsingDeclaration)cu.Children.ElementAt(0); + Assert.AreEqual("System", ud.Namespace); + + Assert.IsTrue(cu.Children.ElementAt(1) is UsingDeclaration); + Assert.IsFalse(cu.Children.ElementAt(1) is UsingAliasDeclaration); + ud = (UsingDeclaration)cu.Children.ElementAt(1); + Assert.AreEqual("My.Name.Space", ud.Namespace); + } + + [Test] + public void UsingAliasDeclarationTest() + { + string program = "using TESTME=System;\n" + + "using myAlias=My.Name.Space;\n" + + "using StringCollection = System.Collections.Generic.List;\n"; + CSharpParser parser = new CSharpParser(); + CompilationUnit cu = parser.Parse(new StringReader(program)); + Assert.IsFalse(parser.HasErrors); + + Assert.AreEqual(3, cu.Children.Count()); + + Assert.IsTrue(cu.Children.ElementAt(0) is UsingAliasDeclaration); + UsingAliasDeclaration ud = (UsingAliasDeclaration)cu.Children.ElementAt(0); + Assert.AreEqual("TESTME", ud.Alias); + Assert.AreEqual("System", ud.Import.ToString()); + + Assert.IsTrue(cu.Children.ElementAt(1) is UsingAliasDeclaration); + ud = (UsingAliasDeclaration)cu.Children.ElementAt(1); + Assert.AreEqual("myAlias", ud.Alias); + Assert.AreEqual("My.Name.Space", ud.Import.ToString()); + + Assert.IsTrue(cu.Children.ElementAt(2) is UsingAliasDeclaration); + ud = (UsingAliasDeclaration)cu.Children.ElementAt(2); + Assert.AreEqual("StringCollection", ud.Alias); + Assert.AreEqual("System.Collections.Generic.List", ud.Import.ToString()); + } + + [Test] + public void UsingWithAliasing() + { + string program = "using global::System;\n" + + "using myAlias=global::My.Name.Space;\n" + + "using a::b.c;\n"; + CSharpParser parser = new CSharpParser(); + CompilationUnit cu = parser.Parse(new StringReader(program)); + Assert.IsFalse(parser.HasErrors); + + Assert.AreEqual(3, cu.Children.Count()); + + Assert.IsTrue(cu.Children.ElementAt(0) is UsingDeclaration); + Assert.IsFalse(cu.Children.ElementAt(0) is UsingAliasDeclaration); + UsingDeclaration ud = (UsingDeclaration)cu.Children.ElementAt(0); + Assert.AreEqual("global::System", ud.Namespace); + + Assert.IsTrue(cu.Children.ElementAt(1) is UsingAliasDeclaration); + UsingAliasDeclaration uad = (UsingAliasDeclaration)cu.Children.ElementAt(1); + Assert.AreEqual("myAlias", uad.Alias); + Assert.AreEqual("global::My.Name.Space", uad.Import.ToString()); + + Assert.IsTrue(cu.Children.ElementAt(2) is UsingDeclaration); + Assert.IsFalse(cu.Children.ElementAt(2) is UsingAliasDeclaration); + ud = (UsingDeclaration)cu.Children.ElementAt(2); + Assert.AreEqual("a::b.c", ud.Namespace); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/ParseUtil.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/ParseUtil.cs new file mode 100644 index 000000000..94b282539 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/ParseUtil.cs @@ -0,0 +1,71 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.IO; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser +{ + /// + /// Helper methods for parser unit tests. + /// + public class ParseUtilCSharp + { + public static T ParseGlobal(string code, bool expectErrors = false) where T : AstNode + { + CSharpParser parser = new CSharpParser(); + CompilationUnit cu = parser.Parse(new StringReader(code)); + + Assert.AreEqual(expectErrors, parser.HasErrors, "HasErrors"); + + AstNode node = cu.Children.Single(); + Type type = typeof(T); + Assert.IsTrue(type.IsAssignableFrom(node.GetType()), String.Format("Parsed node was {0} instead of {1} ({2})", node.GetType(), type, node)); + return (T)node; + } + + public static T ParseStatement(string stmt, bool expectErrors = false) where T : AstNode + { + CSharpParser parser = new CSharpParser(); + var statements = parser.ParseStatements(new StringReader(stmt)); + + Assert.AreEqual(expectErrors, parser.HasErrors, "HasErrors"); + + AstNode statement = statements.Single(); + Type type = typeof(T); + Assert.IsTrue(type.IsAssignableFrom(statement.GetType()), String.Format("Parsed statement was {0} instead of {1} ({2})", statement.GetType(), type, statement)); + return (T)statement; + } + + public static T ParseExpression(string expr, bool expectErrors = false) where T : AstNode + { + if (expectErrors) Assert.Ignore("errors not yet implemented"); + + CSharpParser parser = new CSharpParser(); + AstNode parsedExpression = parser.ParseExpression(new StringReader(expr)); + + Assert.AreEqual(expectErrors, parser.HasErrors, "HasErrors"); + + Type type = typeof(T); + Assert.IsTrue(type.IsAssignableFrom(parsedExpression.GetType()), String.Format("Parsed expression was {0} instead of {1} ({2})", parsedExpression.GetType(), type, parsedExpression)); + return (T)parsedExpression; + } + + public static T ParseTypeMember(string expr, bool expectErrors = false) where T : AttributedNode + { + if (expectErrors) Assert.Ignore("errors not yet implemented"); + + CSharpParser parser = new CSharpParser(); + var members = parser.ParseTypeMembers(new StringReader(expr)); + + Assert.AreEqual(expectErrors, parser.HasErrors, "HasErrors"); + + AttributedNode m = members.Single(); + Type type = typeof(T); + Assert.IsTrue(type.IsAssignableFrom(m.GetType()), String.Format("Parsed member was {0} instead of {1} ({2})", m.GetType(), type, m)); + return (T)m; + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/BlockStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/BlockStatementTests.cs new file mode 100644 index 000000000..f0fb9885e --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/BlockStatementTests.cs @@ -0,0 +1,41 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class BlockStatementTests + { + [Test] + public void BlockStatementTest() + { + BlockStatement blockStmt = ParseUtilCSharp.ParseStatement("{}"); + Assert.AreEqual(0, blockStmt.Statements.Count()); + } + + [Test, Ignore("position isn't correct when only parsing a block")] + public void ComplexBlockStatementPositionTest() + { + string code = @"{ + WebClient wc = new WebClient(); + wc.Test(); + wc.UploadStringCompleted += delegate { + output.BeginInvoke((MethodInvoker)delegate { + output.Text += newText; + }); + }; +}"; + BlockStatement blockStmt = ParseUtilCSharp.ParseStatement(code); + Assert.AreEqual(1, blockStmt.StartLocation.Column); + Assert.AreEqual(1, blockStmt.StartLocation.Line); + Assert.AreEqual(2, blockStmt.EndLocation.Column); + Assert.AreEqual(9, blockStmt.EndLocation.Line); + + Assert.AreEqual(3, blockStmt.Statements.Count()); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/CheckedStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/CheckedStatementTests.cs new file mode 100644 index 000000000..15628db47 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/CheckedStatementTests.cs @@ -0,0 +1,45 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class CheckedStatementTests + { + [Test] + public void CheckedStatementTest() + { + CheckedStatement checkedStatement = ParseUtilCSharp.ParseStatement("checked { }"); + Assert.IsFalse(checkedStatement.Body.IsNull); + } + + [Test] + public void CheckedStatementAndExpressionTest() + { + CheckedStatement checkedStatement = ParseUtilCSharp.ParseStatement("checked { checked(++i).ToString(); }"); + ExpressionStatement es = (ExpressionStatement)checkedStatement.Body.Statements.Single(); + CheckedExpression ce = (CheckedExpression)((MemberReferenceExpression)((InvocationExpression)es.Expression).Target).Target; + Assert.IsTrue(ce.Expression is UnaryOperatorExpression); + } + + [Test] + public void UncheckedStatementTest() + { + UncheckedStatement uncheckedStatement = ParseUtilCSharp.ParseStatement("unchecked { }"); + Assert.IsFalse(uncheckedStatement.Body.IsNull); + } + + [Test] + public void UncheckedStatementAndExpressionTest() + { + UncheckedStatement uncheckedStatement = ParseUtilCSharp.ParseStatement("unchecked { unchecked(++i).ToString(); }"); + ExpressionStatement es = (ExpressionStatement)uncheckedStatement.Body.Statements.Single(); + UncheckedExpression ce = (UncheckedExpression)((MemberReferenceExpression)((InvocationExpression)es.Expression).Target).Target; + Assert.IsTrue(ce.Expression is UnaryOperatorExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/EmptyStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/EmptyStatementTests.cs new file mode 100644 index 000000000..b492b21ed --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/EmptyStatementTests.cs @@ -0,0 +1,18 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class EmptyStatementTests + { + [Test] + public void EmptyStatementTest() + { + EmptyStatement emptyStmt = ParseUtilCSharp.ParseStatement(";"); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ExpressionStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ExpressionStatementTests.cs new file mode 100644 index 000000000..9489deffc --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ExpressionStatementTests.cs @@ -0,0 +1,26 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class ExpressionStatementTests + { + [Test] + public void StatementExpressionTest() + { + ExpressionStatement stmtExprStmt = ParseUtilCSharp.ParseStatement("a = my.Obj.PropCall;"); + Assert.IsTrue(stmtExprStmt.Expression is AssignmentExpression); + } + + [Test] + public void StatementExpressionTest1() + { + ExpressionStatement stmtExprStmt = ParseUtilCSharp.ParseStatement("yield.yield();"); + Assert.IsTrue(stmtExprStmt.Expression is InvocationExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/FixedStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/FixedStatementTests.cs new file mode 100644 index 000000000..08ff938b8 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/FixedStatementTests.cs @@ -0,0 +1,19 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class FixedStatementTests + { + [Test] + public void FixedStatementTest() + { + FixedStatement fixedStmt = ParseUtilCSharp.ParseStatement("fixed (int* ptr = &myIntArr) { }"); + // TODO : Extend test. + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ForStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ForStatementTests.cs new file mode 100644 index 000000000..1d0324f4a --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ForStatementTests.cs @@ -0,0 +1,59 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class ForStatementTests + { + [Test] + public void ForeachStatementTest() + { + ForeachStatement foreachStmt = ParseUtilCSharp.ParseStatement("foreach (int i in myColl) {} "); + // TODO : Extend test. + } + + [Test, Ignore("for statement is broken when Initializers.Count()!=1")] + public void EmptyForStatementTest() + { + ForStatement forStmt = ParseUtilCSharp.ParseStatement("for (;;) ;"); + Assert.AreEqual(0, forStmt.Initializers.Count()); + Assert.AreEqual(0, forStmt.Iterators.Count()); + Assert.IsTrue(forStmt.Condition.IsNull); + Assert.IsTrue(forStmt.EmbeddedStatement is EmptyStatement); + } + + [Test] + public void ForStatementTest() + { + ForStatement forStmt = ParseUtilCSharp.ParseStatement("for (int i = 5; i < 6; ++i) {} "); + var init = (VariableDeclarationStatement)forStmt.Initializers.Single(); + Assert.AreEqual("i", init.Variables.Single().Name); + + Assert.IsTrue(forStmt.Condition is BinaryOperatorExpression); + + var inc = (ExpressionStatement)forStmt.Iterators.Single(); + Assert.IsTrue(inc.Expression is UnaryOperatorExpression); + } + + [Test, Ignore("for statement is broken when Initializers.Count()!=1")] + public void ForStatementTestMultipleInitializers() + { + ForStatement forStmt = ParseUtilCSharp.ParseStatement("for (i = 0, j = 1; i < 6; ++i) {} "); + Assert.AreEqual(2, forStmt.Initializers.Count()); + Assert.IsTrue(forStmt.Iterators.All(i => i is ExpressionStatement)); + } + + [Test, Ignore("for statement is broken when Iterators.Count()!=1")] + public void ForStatementTestMultipleIterators() + { + ForStatement forStmt = ParseUtilCSharp.ParseStatement("for (int i = 5; i < 6; ++i, j--) {} "); + Assert.AreEqual(2, forStmt.Iterators.Count()); + Assert.IsTrue(forStmt.Iterators.All(i => i is ExpressionStatement)); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/GotoStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/GotoStatementTests.cs new file mode 100644 index 000000000..e8db13cb6 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/GotoStatementTests.cs @@ -0,0 +1,48 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class GotoStatementTests + { + [Test, Ignore("regular goto statement is broken")] + public void GotoStatementTest() + { + GotoStatement gotoStmt = ParseUtilCSharp.ParseStatement("goto myLabel;"); + Assert.AreEqual(GotoType.Label, gotoStmt.GotoType); + Assert.AreEqual("myLabel", gotoStmt.Label); + } + + [Test] + public void GotoDefaultStatementTest() + { + GotoStatement gotoCaseStmt = ParseUtilCSharp.ParseStatement("goto default;"); + Assert.AreEqual(GotoType.CaseDefault, gotoCaseStmt.GotoType); + } + + [Test] + public void GotoCaseStatementTest() + { + GotoStatement gotoCaseStmt = ParseUtilCSharp.ParseStatement("goto case 6;"); + Assert.AreEqual(GotoType.Case, gotoCaseStmt.GotoType); + Assert.IsTrue(gotoCaseStmt.LabelExpression is PrimitiveExpression); + } + + [Test] + public void BreakStatementTest() + { + BreakStatement breakStmt = ParseUtilCSharp.ParseStatement("break;"); + } + + [Test] + public void ContinueStatementTest() + { + ContinueStatement continueStmt = ParseUtilCSharp.ParseStatement("continue;"); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/IfElseStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/IfElseStatementTests.cs new file mode 100644 index 000000000..e0daaba5f --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/IfElseStatementTests.cs @@ -0,0 +1,39 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class IfElseStatementTests + { + [Test] + public void SimpleIfStatementTest() + { + IfElseStatement ifElseStatement = ParseUtilCSharp.ParseStatement("if (true) { }"); + Assert.IsTrue(ifElseStatement.Condition is PrimitiveExpression); + Assert.IsTrue(ifElseStatement.TrueStatement is BlockStatement); + Assert.IsTrue(ifElseStatement.FalseStatement.IsNull); + } + + [Test] + public void SimpleIfElseStatementTest() + { + IfElseStatement ifElseStatement = ParseUtilCSharp.ParseStatement("if (true) { } else { }"); + Assert.IsTrue(ifElseStatement.Condition is PrimitiveExpression); + Assert.IsTrue(ifElseStatement.TrueStatement is BlockStatement); + Assert.IsTrue(ifElseStatement.FalseStatement is BlockStatement); + } + + [Test] + public void IfElseIfStatementTest() + { + IfElseStatement ifElseStatement = ParseUtilCSharp.ParseStatement("if (1) { } else if (2) { } else if (3) { } else { }"); + Assert.IsTrue(ifElseStatement.Condition is PrimitiveExpression); + Assert.IsTrue(ifElseStatement.TrueStatement is BlockStatement); + Assert.IsTrue(ifElseStatement.FalseStatement is IfElseStatement); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/LabelStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/LabelStatementTests.cs new file mode 100644 index 000000000..3ce3339fd --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/LabelStatementTests.cs @@ -0,0 +1,29 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class LabelStatementTests + { + [Test] + public void LabelStatementTest() + { + BlockStatement block = ParseUtilCSharp.ParseStatement("{ myLabel: ; }"); + LabelStatement labelStmt = (LabelStatement)block.Statements.First(); + Assert.AreEqual("myLabel", labelStmt.Label); + } + + [Test] + public void Label2StatementTest() + { + BlockStatement block = ParseUtilCSharp.ParseStatement("{ yield: ; }"); + LabelStatement labelStmt = (LabelStatement)block.Statements.First(); + Assert.AreEqual("yield", labelStmt.Label); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/LockStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/LockStatementTests.cs new file mode 100644 index 000000000..a85dc06c9 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/LockStatementTests.cs @@ -0,0 +1,19 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class LockStatementTests + { + [Test] + public void LockStatementTest() + { + LockStatement lockStmt = ParseUtilCSharp.ParseStatement("lock (myObj) {}"); + // TODO : Extend test. + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ReturnStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ReturnStatementTests.cs new file mode 100644 index 000000000..3747198ee --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ReturnStatementTests.cs @@ -0,0 +1,33 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class ReturnStatementTests + { + [Test] + public void EmptyReturnStatementTest() + { + ReturnStatement returnStatement = ParseUtilCSharp.ParseStatement("return;"); + Assert.IsTrue(returnStatement.Expression.IsNull); + } + + [Test] + public void ReturnStatementTest() + { + ReturnStatement returnStatement = ParseUtilCSharp.ParseStatement("return 5;"); + Assert.IsTrue(returnStatement.Expression is PrimitiveExpression); + } + + [Test] + public void ReturnStatementTest1() + { + ReturnStatement returnStatement = ParseUtilCSharp.ParseStatement("return yield;"); + Assert.IsTrue(returnStatement.Expression is IdentifierExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/SwitchStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/SwitchStatementTests.cs new file mode 100644 index 000000000..0800ffb61 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/SwitchStatementTests.cs @@ -0,0 +1,20 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class SwitchStatementTests + { + [Test] + public void SwitchStatementTest() + { + SwitchStatement switchStmt = ParseUtilCSharp.ParseStatement("switch (a) { case 4: case 5: break; case 6: break; default: break; }"); + Assert.AreEqual("a", ((IdentifierExpression)switchStmt.Expression).Identifier); + // TODO: Extend test + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ThrowStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ThrowStatementTests.cs new file mode 100644 index 000000000..4ec682f00 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/ThrowStatementTests.cs @@ -0,0 +1,26 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class ThrowStatementTests + { + [Test] + public void EmptyThrowStatementTest() + { + ThrowStatement throwStmt = ParseUtilCSharp.ParseStatement("throw;"); + Assert.IsTrue(throwStmt.Expression.IsNull); + } + + [Test] + public void ThrowStatementTest() + { + ThrowStatement throwStmt = ParseUtilCSharp.ParseStatement("throw new Exception();"); + Assert.IsTrue(throwStmt.Expression is ObjectCreateExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/TryCatchStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/TryCatchStatementTests.cs new file mode 100644 index 000000000..202b7f0ae --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/TryCatchStatementTests.cs @@ -0,0 +1,47 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture, Ignore] + public class TryCatchStatementTests + { + [Test] + public void SimpleTryCatchStatementTest() + { + TryCatchStatement tryCatchStatement = ParseUtilCSharp.ParseStatement("try { } catch { } "); + Assert.IsTrue(tryCatchStatement.FinallyBlock.IsNull); + Assert.AreEqual(1, tryCatchStatement.CatchClauses.Count()); + Assert.IsTrue(tryCatchStatement.CatchClauses.Single().Type.IsNull); + Assert.AreEqual(string.Empty, tryCatchStatement.CatchClauses.Single().VariableName); + } + + /* TODO port tests + [Test] + public void SimpleTryCatchStatementTest2() + { + TryCatchStatement tryCatchStatement = ParseUtilCSharp.ParseStatement("try { } catch (Exception e) { } "); + Assert.IsTrue(tryCatchStatement.FinallyBlock.IsNull); + Assert.AreEqual(1, tryCatchStatement.CatchClauses.Count); + Assert.AreEqual("Exception", tryCatchStatement.CatchClauses[0].TypeReference.Type); + Assert.AreEqual("e", tryCatchStatement.CatchClauses[0].VariableName); + } + + [Test] + public void SimpleTryCatchFinallyStatementTest() + { + TryCatchStatement tryCatchStatement = ParseUtilCSharp.ParseStatement("try { } catch (Exception) { } catch { } finally { } "); + Assert.IsFalse(tryCatchStatement.FinallyBlock.IsNull); + Assert.AreEqual(2, tryCatchStatement.CatchClauses.Count); + Assert.AreEqual("Exception", tryCatchStatement.CatchClauses[0].TypeReference.Type); + Assert.IsEmpty(tryCatchStatement.CatchClauses[0].VariableName); + Assert.IsTrue(tryCatchStatement.CatchClauses[1].TypeReference.IsNull); + Assert.IsEmpty(tryCatchStatement.CatchClauses[1].VariableName); + } + */ + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/UnsafeStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/UnsafeStatementTests.cs new file mode 100644 index 000000000..bdeed271f --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/UnsafeStatementTests.cs @@ -0,0 +1,19 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class UnsafeStatementTests + { + [Test] + public void UnsafeStatementTest() + { + UnsafeStatement unsafeStatement = ParseUtilCSharp.ParseStatement("unsafe { }"); + Assert.IsFalse(unsafeStatement.Body.IsNull); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/UsingStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/UsingStatementTests.cs new file mode 100644 index 000000000..785b91355 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/UsingStatementTests.cs @@ -0,0 +1,19 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class UsingStatementTests + { + [Test] + public void UsingStatementTest() + { + UsingStatement usingStmt = ParseUtilCSharp.ParseStatement("using (MyVar var = new MyVar()) { } "); + // TODO : Extend test. + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/VariableDeclarationStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/VariableDeclarationStatementTests.cs new file mode 100644 index 000000000..e9217e189 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/VariableDeclarationStatementTests.cs @@ -0,0 +1,226 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture, Ignore] + public class VariableDeclarationStatementTests + { + [Test] + public void VariableDeclarationStatementTest() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("int a = 5;"); + Assert.AreEqual(1, lvd.Variables.Count()); + /*Assert.AreEqual("a", ((VariableDeclaration)lvd.Variables[0]).Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.Int32", type.Type); + Assert.AreEqual(5, ((PrimitiveExpression)lvd.Variables[0].Initializer).Value);*/ throw new NotImplementedException(); + } + + /* TODO port unit tests + [Test] + public void VoidPointerVariableDeclarationTest() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("void *a;"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("a", ((VariableDeclaration)lvd.Variables[0]).Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.Void", type.Type); + Assert.AreEqual(1, type.PointerNestingLevel); + } + + [Test] + public void ComplexGenericVariableDeclarationStatementTest() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("Generic > where = new Generic>();"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("where", ((VariableDeclaration)lvd.Variables[0]).Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("Generic", type.Type); + Assert.AreEqual(2, type.GenericTypes.Count); + Assert.AreEqual("Namespace.Printable", type.GenericTypes[0].Type); + Assert.AreEqual(0, type.GenericTypes[0].GenericTypes.Count); + Assert.AreEqual("G", type.GenericTypes[1].Type); + Assert.AreEqual(1, type.GenericTypes[1].GenericTypes.Count); + Assert.AreEqual("Printable", type.GenericTypes[1].GenericTypes[0].Type); + + // TODO: Check initializer + } + + [Test] + public void NestedGenericVariableDeclarationStatementTest() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("MyType.InnerClass.InnerInnerClass a;"); + Assert.AreEqual(1, lvd.Variables.Count); + InnerClassTypeReference ic = (InnerClassTypeReference)lvd.GetTypeForVariable(0); + Assert.AreEqual("InnerInnerClass", ic.Type); + Assert.AreEqual(0, ic.GenericTypes.Count); + ic = (InnerClassTypeReference)ic.BaseType; + Assert.AreEqual("InnerClass", ic.Type); + Assert.AreEqual(1, ic.GenericTypes.Count); + Assert.AreEqual("System.Int32", ic.GenericTypes[0].Type); + Assert.AreEqual("MyType", ic.BaseType.Type); + Assert.AreEqual(1, ic.BaseType.GenericTypes.Count); + Assert.AreEqual("System.String", ic.BaseType.GenericTypes[0].Type); + } + + [Test] + public void GenericWithArrayVariableDeclarationStatementTest1() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("G[] a;"); + Assert.AreEqual(1, lvd.Variables.Count); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("G", type.Type); + Assert.AreEqual(1, type.GenericTypes.Count); + Assert.AreEqual("System.Int32", type.GenericTypes[0].Type); + Assert.AreEqual(0, type.GenericTypes[0].GenericTypes.Count); + Assert.IsFalse(type.GenericTypes[0].IsArrayType); + Assert.AreEqual(new int[] {0}, type.RankSpecifier); + } + + [Test] + public void GenericWithArrayVariableDeclarationStatementTest2() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("G a;"); + Assert.AreEqual(1, lvd.Variables.Count); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("G", type.Type); + Assert.AreEqual(1, type.GenericTypes.Count); + Assert.AreEqual("System.Int32", type.GenericTypes[0].Type); + Assert.AreEqual(0, type.GenericTypes[0].GenericTypes.Count); + Assert.IsFalse(type.IsArrayType); + Assert.AreEqual(new int[] {0}, type.GenericTypes[0].RankSpecifier); + } + + [Test] + public void GenericVariableDeclarationStatementTest2() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("G > a;"); + Assert.AreEqual(1, lvd.Variables.Count); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("G", type.Type); + Assert.AreEqual(1, type.GenericTypes.Count); + Assert.AreEqual("G", type.GenericTypes[0].Type); + Assert.AreEqual(1, type.GenericTypes[0].GenericTypes.Count); + Assert.AreEqual("System.Int32", type.GenericTypes[0].GenericTypes[0].Type); + } + + [Test] + public void GenericVariableDeclarationStatementTest2WithoutSpace() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("G> a;"); + Assert.AreEqual(1, lvd.Variables.Count); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("G", type.Type); + Assert.AreEqual(1, type.GenericTypes.Count); + Assert.AreEqual("G", type.GenericTypes[0].Type); + Assert.AreEqual(1, type.GenericTypes[0].GenericTypes.Count); + Assert.AreEqual("System.Int32", type.GenericTypes[0].GenericTypes[0].Type); + } + + [Test] + public void GenericVariableDeclarationStatementTest() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("G a;"); + Assert.AreEqual(1, lvd.Variables.Count); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("G", type.Type); + Assert.AreEqual(1, type.GenericTypes.Count); + Assert.AreEqual("System.Int32", type.GenericTypes[0].Type); + } + + [Test] + public void SimpleVariableDeclarationStatementTest() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("MyVar var = new MyVar();"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("var", ((VariableDeclaration)lvd.Variables[0]).Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("MyVar", type.Type); + // TODO: Check initializer + } + + [Test] + public void SimpleVariableDeclarationStatementTest1() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("yield yield = new yield();"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("yield", ((VariableDeclaration)lvd.Variables[0]).Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("yield", type.Type); + // TODO: Check initializer + } + + [Test] + public void NullableVariableDeclarationStatementTest1() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("int? a;"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("a", ((VariableDeclaration)lvd.Variables[0]).Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.Nullable", type.Type); + Assert.AreEqual("System.Int32", type.GenericTypes[0].Type); + } + + [Test] + public void NullableVariableDeclarationStatementTest2() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("DateTime? a;"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("a", ((VariableDeclaration)lvd.Variables[0]).Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.Nullable", type.Type); + Assert.AreEqual("DateTime", type.GenericTypes[0].Type); + } + + [Test] + public void NullableVariableDeclarationStatementTest3() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("DateTime?[] a;"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("a", ((VariableDeclaration)lvd.Variables[0]).Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.IsTrue(type.IsArrayType); + Assert.AreEqual("System.Nullable", type.Type); + Assert.AreEqual("DateTime", type.GenericTypes[0].Type); + } + + [Test] + public void NullableVariableDeclarationStatementTest4() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("SomeStruct? a;"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("a", ((VariableDeclaration)lvd.Variables[0]).Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.Nullable", type.Type); + Assert.AreEqual("SomeStruct", type.GenericTypes[0].Type); + Assert.AreEqual("System.Nullable", type.GenericTypes[0].GenericTypes[0].Type); + Assert.AreEqual("System.Int32", type.GenericTypes[0].GenericTypes[0].GenericTypes[0].Type); + } + + [Test] + public void PositionTestWithoutModifier() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("\ndouble w = 7;"); + Assert.AreEqual(2, lvd.StartLocation.Line); + Assert.AreEqual(1, lvd.StartLocation.Column); + Assert.AreEqual(2, lvd.EndLocation.Line); + Assert.AreEqual(14, lvd.EndLocation.Column); + } + + [Test] + public void PositionTestWithModifier() + { + VariableDeclarationStatement lvd = ParseUtilCSharp.ParseStatement("\nconst double w = 7;"); + Assert.AreEqual(Modifiers.Const, lvd.Modifier); + Assert.AreEqual(2, lvd.StartLocation.Line); + Assert.AreEqual(1, lvd.StartLocation.Column); + Assert.AreEqual(2, lvd.EndLocation.Line); + Assert.AreEqual(20, lvd.EndLocation.Column); + }*/ + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/WhileStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/WhileStatementTests.cs new file mode 100644 index 000000000..6ad09465d --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/WhileStatementTests.cs @@ -0,0 +1,30 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class WhileStatementTests + { + [Test] + public void WhileStatementTest() + { + WhileStatement loopStmt = ParseUtilCSharp.ParseStatement("while (true) { }"); + Assert.AreEqual(WhilePosition.Begin, loopStmt.WhilePosition); + Assert.IsTrue(loopStmt.Condition is PrimitiveExpression); + Assert.IsTrue(loopStmt.EmbeddedStatement is BlockStatement); + } + + [Test] + public void DoWhileStatementTest() + { + WhileStatement loopStmt = ParseUtilCSharp.ParseStatement("do { } while (true);"); + Assert.AreEqual(WhilePosition.End, loopStmt.WhilePosition); + Assert.IsTrue(loopStmt.Condition is PrimitiveExpression); + Assert.IsTrue(loopStmt.EmbeddedStatement is BlockStatement); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/YieldStatementTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/YieldStatementTests.cs new file mode 100644 index 000000000..ae5598f2c --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/Statements/YieldStatementTests.cs @@ -0,0 +1,41 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.Statements +{ + [TestFixture] + public class YieldStatementTests + { + [Test] + public void YieldReturnStatementTest() + { + YieldStatement yieldStmt = ParseUtilCSharp.ParseStatement("yield return \"Foo\";"); + PrimitiveExpression expr = (PrimitiveExpression)yieldStmt.Expression; + Assert.AreEqual("Foo", expr.Value); + } + + [Test] + public void YieldBreakStatementTest() + { + YieldStatement yieldStmt = ParseUtilCSharp.ParseStatement("yield break;"); + Assert.IsTrue(yieldStmt.Expression.IsNull); + } + + [Test] + public void YieldAsVariableTest() + { + ExpressionStatement se = ParseUtilCSharp.ParseStatement("yield = 3;"); + AssignmentExpression ae = se.Expression as AssignmentExpression; + + Assert.AreEqual(AssignmentOperatorType.Assign, ae.Operator); + + Assert.IsTrue(ae.Left is IdentifierExpression); + Assert.AreEqual("yield", ((IdentifierExpression)ae.Left).Identifier); + Assert.IsTrue(ae.Right is PrimitiveExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/ConstructorDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/ConstructorDeclarationTests.cs new file mode 100644 index 000000000..340c43430 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/ConstructorDeclarationTests.cs @@ -0,0 +1,52 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.TypeMembers +{ + [TestFixture] + public class ConstructorDeclarationTests + { + [Test] + public void ConstructorDeclarationTest1() + { + ConstructorDeclaration cd = ParseUtilCSharp.ParseTypeMember("MyClass() {}"); + Assert.IsTrue(cd.Initializer.IsNull); + } + + [Test, Ignore("Constructor initializer is broken")] + public void ConstructorDeclarationTest2() + { + ConstructorDeclaration cd = ParseUtilCSharp.ParseTypeMember("MyClass() : this(5) {}"); + Assert.AreEqual(ConstructorInitializerType.This, cd.Initializer.ConstructorInitializerType); + Assert.AreEqual(1, cd.Initializer.Arguments.Count()); + } + + [Test, Ignore("Constructor initializer is broken")] + public void ConstructorDeclarationTest3() + { + ConstructorDeclaration cd = ParseUtilCSharp.ParseTypeMember("MyClass() : base(1, 2, 3) {}"); + Assert.AreEqual(ConstructorInitializerType.Base, cd.Initializer.ConstructorInitializerType); + Assert.AreEqual(3, cd.Initializer.Arguments.Count()); + } + + [Test] + public void StaticConstructorDeclarationTest1() + { + ConstructorDeclaration cd = ParseUtilCSharp.ParseTypeMember("static MyClass() {}"); + Assert.IsTrue(cd.Initializer.IsNull); + Assert.AreEqual(Modifiers.Static, cd.Modifiers); + } + + [Test] + public void ExternStaticConstructorDeclarationTest() + { + ConstructorDeclaration cd = ParseUtilCSharp.ParseTypeMember("extern static MyClass();"); + Assert.IsTrue(cd.Initializer.IsNull); + Assert.AreEqual(Modifiers.Static | Modifiers.Extern, cd.Modifiers); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/DestructorDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/DestructorDeclarationTests.cs new file mode 100644 index 000000000..25ba714f7 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/DestructorDeclarationTests.cs @@ -0,0 +1,32 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.TypeMembers +{ + [TestFixture] + public class DestructorDeclarationTests + { + [Test] + public void DestructorDeclarationTest() + { + DestructorDeclaration dd = ParseUtilCSharp.ParseTypeMember("~MyClass() {}"); + } + + [Test] + public void ExternDestructorDeclarationTest() + { + DestructorDeclaration dd = ParseUtilCSharp.ParseTypeMember("extern ~MyClass();"); + Assert.AreEqual(Modifiers.Extern, dd.Modifiers); + } + + [Test] + public void UnsafeDestructorDeclarationTest() + { + DestructorDeclaration dd = ParseUtilCSharp.ParseTypeMember("unsafe ~MyClass() {}"); + Assert.AreEqual(Modifiers.Unsafe, dd.Modifiers); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/EventDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/EventDeclarationTests.cs new file mode 100644 index 000000000..fe1bd468c --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/EventDeclarationTests.cs @@ -0,0 +1,84 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.TypeMembers +{ + [TestFixture, Ignore] + public class EventDeclarationTests + { + [Test] + public void SimpleEventDeclarationTest() + { + CustomEventDeclaration ed = ParseUtilCSharp.ParseTypeMember("event System.EventHandler MyEvent;"); + Assert.AreEqual("MyEvent", ed.Name); + //Assert.AreEqual("System.EventHandler", ed.TypeReference.Type); + Assert.Ignore(); // check type + + Assert.IsTrue(ed.AddAccessor.IsNull); + Assert.IsTrue(ed.RemoveAccessor.IsNull); + } + + /* TODO Port tests + [Test] + public void MultipleEventDeclarationTest() + { + TypeDeclaration t = ParseUtilCSharp.ParseGlobal("class C { public event EventHandler A, B; }"); + Assert.AreEqual(2, t.Children.Count); + + EventDeclaration ed = (EventDeclaration)t.Children[0]; + Assert.AreEqual(Modifiers.Public, ed.Modifier); + Assert.AreEqual("EventHandler", ed.TypeReference.Type); + Assert.AreEqual("A", ed.Name); + + ed = (EventDeclaration)t.Children[1]; + Assert.AreEqual(Modifiers.Public, ed.Modifier); + Assert.AreEqual("EventHandler", ed.TypeReference.Type); + Assert.AreEqual("B", ed.Name); + } + + [Test] + public void EventImplementingInterfaceDeclarationTest() + { + EventDeclaration ed = ParseUtilCSharp.ParseTypeMember("event EventHandler MyInterface.MyEvent;"); + + Assert.AreEqual("MyEvent", ed.Name); + Assert.AreEqual("EventHandler", ed.TypeReference.Type); + + Assert.IsFalse(ed.HasAddRegion); + Assert.IsFalse(ed.HasRemoveRegion); + + Assert.AreEqual("MyInterface", ed.InterfaceImplementations[0].InterfaceType.Type); + Assert.AreEqual("MyEvent", ed.InterfaceImplementations[0].MemberName); + } + + [Test] + public void EventImplementingGenericInterfaceDeclarationTest() + { + EventDeclaration ed = ParseUtilCSharp.ParseTypeMember("event EventHandler MyInterface.MyEvent;"); + + Assert.AreEqual("MyEvent", ed.Name); + Assert.AreEqual("EventHandler", ed.TypeReference.Type); + + Assert.IsFalse(ed.HasAddRegion); + Assert.IsFalse(ed.HasRemoveRegion); + + Assert.AreEqual("MyInterface", ed.InterfaceImplementations[0].InterfaceType.Type); + Assert.AreEqual("System.String", ed.InterfaceImplementations[0].InterfaceType.GenericTypes[0].Type); + Assert.AreEqual("MyEvent", ed.InterfaceImplementations[0].MemberName); + } + + [Test] + public void AddRemoveEventDeclarationTest() + { + EventDeclaration ed = ParseUtilCSharp.ParseTypeMember("event System.EventHandler MyEvent { add { } remove { } }"); + Assert.AreEqual("MyEvent", ed.Name); + Assert.AreEqual("System.EventHandler", ed.TypeReference.Type); + + Assert.IsTrue(ed.HasAddRegion); + Assert.IsTrue(ed.HasRemoveRegion); + }*/ + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/FieldDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/FieldDeclarationTests.cs new file mode 100644 index 000000000..f91cbed4a --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/FieldDeclarationTests.cs @@ -0,0 +1,27 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.TypeMembers +{ + [TestFixture, Ignore] + public class FieldDeclarationTests + { + [Test] + public void SimpleFieldDeclarationTest() + { + throw new NotImplementedException(); + /* + FieldDeclaration fd = ParseUtilCSharp.ParseTypeMember("int[,,,] myField;"); + Assert.AreEqual("System.Int32", fd.TypeReference.Type); + Assert.AreEqual(new int[] { 3 } , fd.TypeReference.RankSpecifier); + Assert.AreEqual(1, fd.Fields.Count); + + Assert.AreEqual("myField", ((VariableDeclaration)fd.Fields[0]).Name);*/ + } + + // TODO add more tests + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/IndexerDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/IndexerDeclarationTests.cs new file mode 100644 index 000000000..90f14b26e --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/IndexerDeclarationTests.cs @@ -0,0 +1,47 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.TypeMembers +{ + [TestFixture] + public class IndexerDeclarationTests + { + [Test] + public void IndexerDeclarationTest() + { + IndexerDeclaration id = ParseUtilCSharp.ParseTypeMember("int this[int a, string b] { get { } set { } }"); + Assert.AreEqual(2, id.Parameters.Count()); + Assert.IsNotNull(id.Getter, "No get region found!"); + Assert.IsNotNull(id.Setter, "No set region found!"); + } + + [Test, Ignore("type reference is not yet implemented")] + public void IndexerImplementingInterfaceTest() + { + IndexerDeclaration id = ParseUtilCSharp.ParseTypeMember("int MyInterface.this[int a, string b] { get { } set { } }"); + Assert.AreEqual(2, id.Parameters.Count()); + Assert.IsNotNull(id.Getter, "No get region found!"); + Assert.IsNotNull(id.Setter, "No set region found!"); + + Assert.AreEqual("MyInterface", id.PrivateImplementationType); + } + + [Test, Ignore] + public void IndexerImplementingGenericInterfaceTest() + { + throw new NotImplementedException(); + /* + IndexerDeclaration id = ParseUtilCSharp.ParseTypeMember("int MyInterface.this[int a, string b] { get { } set { } }"); + Assert.AreEqual(2, id.Parameters.Count); + Assert.IsNotNull(id.GetAccessor, "No get region found!"); + Assert.IsNotNull(id.SetAccessor, "No set region found!"); + + Assert.AreEqual("MyInterface", id.InterfaceImplementations[0].InterfaceType.Type); + Assert.AreEqual("System.String", id.InterfaceImplementations[0].InterfaceType.GenericTypes[0].Type);*/ + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/MethodDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/MethodDeclarationTests.cs new file mode 100644 index 000000000..53e0f3138 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/MethodDeclarationTests.cs @@ -0,0 +1,303 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.TypeMembers +{ + [TestFixture] + public class MethodDeclarationTests + { + [Test, Ignore("type references not yet implemented")] + public void SimpleMethodDeclarationTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember("void MyMethod() {} "); + Assert.AreEqual("System.Void", md.ReturnType); + Assert.AreEqual(0, md.Parameters.Count()); + Assert.IsFalse(md.IsExtensionMethod); + } + + [Test, Ignore("type references not yet implemented")] + public void AbstractMethodDeclarationTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember("abstract void MyMethod();"); + Assert.AreEqual("System.Void", md.ReturnType); + Assert.AreEqual(0, md.Parameters.Count()); + Assert.IsFalse(md.IsExtensionMethod); + Assert.IsTrue(md.Body.IsNull); + Assert.AreEqual(Modifiers.Abstract, md.Modifiers); + } + + [Test, Ignore("type references not yet implemented")] + public void DefiningPartialMethodDeclarationTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember("partial void MyMethod();"); + Assert.AreEqual("System.Void", md.ReturnType); + Assert.AreEqual(0, md.Parameters.Count()); + Assert.IsFalse(md.IsExtensionMethod); + Assert.IsTrue(md.Body.IsNull); + Assert.AreEqual(Modifiers.Partial, md.Modifiers); + } + + [Test, Ignore("type references not yet implemented")] + public void ImplementingPartialMethodDeclarationTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember("partial void MyMethod() { }"); + Assert.AreEqual("System.Void", md.ReturnType); + Assert.AreEqual(0, md.Parameters.Count()); + Assert.IsFalse(md.IsExtensionMethod); + Assert.IsFalse(md.Body.IsNull); + Assert.AreEqual(Modifiers.Partial, md.Modifiers); + } + + [Test] + public void SimpleMethodRegionTest() + { + const string program = @" + void MyMethod() + { + OtherMethod(); + } +"; + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember(program); + Assert.AreEqual(2, md.StartLocation.Line, "StartLocation.Y"); + Assert.AreEqual(5, md.EndLocation.Line, "EndLocation.Y"); + Assert.AreEqual(3, md.StartLocation.Column, "StartLocation.X"); + Assert.AreEqual(4, md.EndLocation.Column, "EndLocation.X"); + } + + [Test] + public void MethodWithModifiersRegionTest() + { + const string program = @" + public static void MyMethod() + { + OtherMethod(); + } +"; + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember(program); + Assert.AreEqual(2, md.StartLocation.Line, "StartLocation.Y"); + Assert.AreEqual(5, md.EndLocation.Line, "EndLocation.Y"); + Assert.AreEqual(3, md.StartLocation.Column, "StartLocation.X"); + } + + [Test] + public void MethodWithUnnamedParameterDeclarationTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember("void MyMethod(int) {} ", true); + Assert.AreEqual("System.Void", md.ReturnType); + Assert.AreEqual(1, md.Parameters.Count()); + //Assert.AreEqual("?", ((ParameterDeclarationExpression)md.Parameters[0]).ParameterName); + } + + /* TODO: port unit tests + [Test] + public void GenericVoidMethodDeclarationTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember("void MyMethod(T a) {} "); + Assert.AreEqual("System.Void", md.ReturnType); + Assert.AreEqual(1, md.Parameters.Count()); + Assert.AreEqual("T", md.Parameters.Single().Type); + Assert.AreEqual("a", md.Parameters.Single().Name); + + Assert.AreEqual(1, md.TypeParameters.Count()); + Assert.AreEqual("T", md.Templates[0].Name); + } + + [Test] + public void GenericMethodDeclarationTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember("T MyMethod(T a) {} "); + Assert.AreEqual("T", md.TypeReference.Type); + Assert.AreEqual(1, md.Parameters.Count); + Assert.AreEqual("T", ((ParameterDeclarationExpression)md.Parameters[0]).TypeReference.Type); + Assert.AreEqual("a", ((ParameterDeclarationExpression)md.Parameters[0]).ParameterName); + + Assert.AreEqual(1, md.Templates.Count); + Assert.AreEqual("T", md.Templates[0].Name); + } + + [Test] + public void GenericMethodDeclarationWithConstraintTest() + { + string program = "T MyMethod(T a) where T : ISomeInterface {} "; + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember(program); + Assert.AreEqual("T", md.TypeReference.Type); + Assert.AreEqual(1, md.Parameters.Count); + Assert.AreEqual("T", ((ParameterDeclarationExpression)md.Parameters[0]).TypeReference.Type); + Assert.AreEqual("a", ((ParameterDeclarationExpression)md.Parameters[0]).ParameterName); + + Assert.AreEqual(1, md.Templates.Count); + Assert.AreEqual("T", md.Templates[0].Name); + Assert.AreEqual(1, md.Templates[0].Bases.Count); + Assert.AreEqual("ISomeInterface", md.Templates[0].Bases[0].Type); + } + + [Test] + public void GenericMethodInInterface() + { + const string program = @"interface MyInterface { + T MyMethod(T a) where T : ISomeInterface; +} +"; + TypeDeclaration td = ParseUtilCSharp.ParseGlobal(program); + MethodDeclaration md = (MethodDeclaration)td.Children[0]; + Assert.AreEqual("T", md.TypeReference.Type); + Assert.AreEqual(1, md.Parameters.Count); + Assert.AreEqual("T", ((ParameterDeclarationExpression)md.Parameters[0]).TypeReference.Type); + Assert.AreEqual("a", ((ParameterDeclarationExpression)md.Parameters[0]).ParameterName); + + Assert.AreEqual(1, md.Templates.Count); + Assert.AreEqual("T", md.Templates[0].Name); + Assert.AreEqual(1, md.Templates[0].Bases.Count); + Assert.AreEqual("ISomeInterface", md.Templates[0].Bases[0].Type); + } + + [Test] + public void GenericVoidMethodInInterface() + { + const string program = @"interface MyInterface { + void MyMethod(T a) where T : ISomeInterface; +} +"; + TypeDeclaration td = ParseUtilCSharp.ParseGlobal(program); + MethodDeclaration md = (MethodDeclaration)td.Children[0]; + Assert.AreEqual("System.Void", md.TypeReference.Type); + Assert.AreEqual(1, md.Parameters.Count); + Assert.AreEqual("T", ((ParameterDeclarationExpression)md.Parameters[0]).TypeReference.Type); + Assert.AreEqual("a", ((ParameterDeclarationExpression)md.Parameters[0]).ParameterName); + + Assert.AreEqual(1, md.Templates.Count); + Assert.AreEqual("T", md.Templates[0].Name); + Assert.AreEqual(1, md.Templates[0].Bases.Count); + Assert.AreEqual("ISomeInterface", md.Templates[0].Bases[0].Type); + } + + [Test] + public void ShadowingMethodInInterface() + { + const string program = @"interface MyInterface : IDisposable { + new void Dispose(); +} +"; + TypeDeclaration td = ParseUtilCSharp.ParseGlobal(program); + MethodDeclaration md = (MethodDeclaration)td.Children[0]; + Assert.AreEqual("System.Void", md.TypeReference.Type); + Assert.AreEqual(0, md.Parameters.Count); + Assert.AreEqual(Modifiers.New, md.Modifier); + } + + [Test] + public void MethodImplementingInterfaceTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember("int MyInterface.MyMethod() {} "); + Assert.AreEqual("System.Int32", md.TypeReference.Type); + + Assert.AreEqual("MyInterface", md.InterfaceImplementations[0].InterfaceType.Type); + } + + [Test] + public void MethodImplementingGenericInterfaceTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember("int MyInterface.MyMethod() {} "); + Assert.AreEqual("System.Int32", md.TypeReference.Type); + + Assert.AreEqual("MyInterface", md.InterfaceImplementations[0].InterfaceType.Type); + Assert.AreEqual("System.String", md.InterfaceImplementations[0].InterfaceType.GenericTypes[0].Type); + } + + [Test] + public void VoidMethodImplementingInterfaceTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember("void MyInterface.MyMethod() {} "); + Assert.AreEqual("System.Void", md.TypeReference.Type); + + Assert.AreEqual("MyInterface", md.InterfaceImplementations[0].InterfaceType.Type); + } + + [Test] + public void VoidMethodImplementingGenericInterfaceTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember("void MyInterface.MyMethod() {} "); + Assert.AreEqual("System.Void", md.TypeReference.Type); + + Assert.AreEqual("MyInterface", md.InterfaceImplementations[0].InterfaceType.Type); + Assert.AreEqual("System.String", md.InterfaceImplementations[0].InterfaceType.GenericTypes[0].Type); + } + + [Test] + public void IncompleteConstraintsTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember( + "void a() where T { }", true // expect errors + ); + Assert.AreEqual("a", md.Name); + Assert.AreEqual(1, md.Templates.Count); + Assert.AreEqual("T", md.Templates[0].Name); + Assert.AreEqual(0, md.Templates[0].Bases.Count); + } + + [Test] + public void ExtensionMethodTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember( + "public static int ToInt32(this string s) { return int.Parse(s); }" + ); + Assert.AreEqual("ToInt32", md.Name); + Assert.IsTrue(md.IsExtensionMethod); + Assert.AreEqual("s", md.Parameters[0].ParameterName); + Assert.AreEqual("System.String", md.Parameters[0].TypeReference.Type); + } + */ + + [Test] + public void VoidExtensionMethodTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember( + "public static void Print(this string s) { Console.WriteLine(s); }" + ); + Assert.AreEqual("Print", md.Name); + Assert.AreEqual("s", md.Parameters.First().Name); + Assert.AreEqual(ParameterModifier.This, md.Parameters.First().ParameterModifier); + Assert.AreEqual("string", ((PrimitiveType)md.Parameters.First().Type).Keyword); + Assert.IsTrue(md.IsExtensionMethod); + } + + /* TODO + [Test] + public void MethodWithEmptyAssignmentErrorInBody() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember( + "void A\n" + + "{\n" + + "int a = 3;\n" + + " = 4;\n" + + "}", true // expect errors + ); + Assert.AreEqual("A", md.Name); + Assert.AreEqual(new Location(1, 2), md.Body.StartLocation); + Assert.AreEqual(new Location(2, 5), md.Body.EndLocation); + } + + [Test] + public void OptionalParameterTest() + { + MethodDeclaration md = ParseUtilCSharp.ParseTypeMember( + "public void Foo(string bar = null, int baz = 0) { }" + ); + Assert.AreEqual("Foo", md.Name); + + Assert.AreEqual("bar", md.Parameters[0].ParameterName); + Assert.AreEqual("System.String", md.Parameters[0].TypeReference.Type); + Assert.AreEqual(ParameterModifiers.In | ParameterModifiers.Optional, md.Parameters[0].ParamModifier); + Assert.IsNull(((PrimitiveExpression)md.Parameters[0].DefaultValue).Value); + + Assert.AreEqual("baz", md.Parameters[1].ParameterName); + Assert.AreEqual("System.Int32", md.Parameters[1].TypeReference.Type); + Assert.AreEqual(ParameterModifiers.In | ParameterModifiers.Optional, md.Parameters[1].ParamModifier); + Assert.AreEqual(0, ((PrimitiveExpression)md.Parameters[1].DefaultValue).Value); + }*/ + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/OperatorDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/OperatorDeclarationTests.cs new file mode 100644 index 000000000..e2901f54e --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/OperatorDeclarationTests.cs @@ -0,0 +1,53 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.TypeMembers +{ + [TestFixture] + public class OperatorDeclarationTests + { + [Test, Ignore("type references not yet implemented")] + public void ImplictOperatorDeclarationTest() + { + OperatorDeclaration od = ParseUtilCSharp.ParseTypeMember("public static implicit operator double(MyObject f) { return 0.5d; }"); + Assert.AreEqual(OperatorType.Implicit, od.OperatorType); + Assert.AreEqual(1, od.Parameters.Count()); + Assert.AreEqual("System.Double", od.ReturnType); + Assert.AreEqual("op_Implicit", od.Name); + } + + [Test, Ignore("type references not yet implemented")] + public void ExplicitOperatorDeclarationTest() + { + OperatorDeclaration od = ParseUtilCSharp.ParseTypeMember("public static explicit operator double(MyObject f) { return 0.5d; }"); + Assert.AreEqual(OperatorType.Explicit, od.OperatorType); + Assert.AreEqual(1, od.Parameters.Count()); + Assert.AreEqual("System.Double", od.ReturnType); + Assert.AreEqual("op_Explicit", od.Name); + } + + [Test, Ignore("type references not yet implemented")] + public void BinaryPlusOperatorDeclarationTest() + { + OperatorDeclaration od = ParseUtilCSharp.ParseTypeMember("public static MyObject operator +(MyObject a, MyObject b) {}"); + Assert.AreEqual(OperatorType.Addition, od.OperatorType); + Assert.AreEqual(2, od.Parameters.Count()); + Assert.AreEqual("MyObject", od.ReturnType); + Assert.AreEqual("op_Addition", od.Name); + } + + [Test, Ignore("type references not yet implemented")] + public void UnaryPlusOperatorDeclarationTest() + { + OperatorDeclaration od = ParseUtilCSharp.ParseTypeMember("public static MyObject operator +(MyObject a) {}"); + Assert.AreEqual(OperatorType.UnaryPlus, od.OperatorType); + Assert.AreEqual(1, od.Parameters.Count()); + Assert.AreEqual("MyObject", od.ReturnType); + Assert.AreEqual("op_UnaryPlus", od.Name); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/PropertyDeclarationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/PropertyDeclarationTests.cs new file mode 100644 index 000000000..5c4bebed3 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/PropertyDeclarationTests.cs @@ -0,0 +1,93 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.IO; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser.TypeMembers +{ + [TestFixture] + public class PropertyDeclarationTests + { + [Test] + public void SimpleGetSetPropertyDeclarationTest() + { + PropertyDeclaration pd = ParseUtilCSharp.ParseTypeMember("int MyProperty { get {} set {} } "); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsFalse(pd.Getter.IsNull); + Assert.IsFalse(pd.Setter.IsNull); + } + + [Test] + public void GetSetPropertyDeclarationWithAccessorModifiers() + { + PropertyDeclaration pd = ParseUtilCSharp.ParseTypeMember("int MyProperty { private get {} protected internal set {} } "); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsFalse(pd.Getter.IsNull); + Assert.IsFalse(pd.Setter.IsNull); + } + + [Test] + public void SimpleGetPropertyDeclarationTest() + { + PropertyDeclaration pd = ParseUtilCSharp.ParseTypeMember("int MyProperty { get {} } "); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsFalse(pd.Getter.IsNull); + Assert.IsTrue(pd.Setter.IsNull); + } + + [Test] + public void SimpleSetPropertyDeclarationTest() + { + PropertyDeclaration pd = ParseUtilCSharp.ParseTypeMember("int MyProperty { set {} } "); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsTrue(pd.Getter.IsNull); + Assert.IsFalse(pd.Setter.IsNull); + } + + [Test] + public void PropertyRegionTest() + { + const string code = "class T {\n\tint Prop {\n\t\tget { return f; }\n\t\tset { f = value; }\n\t}\n}\n"; + int line2Pos = code.IndexOf("\tint Prop"); + int line3Pos = code.IndexOf("\t\tget"); + int line4Pos = code.IndexOf("\t\tset"); + + CSharpParser parser = new CSharpParser(); + CompilationUnit cu = parser.Parse(new StringReader(code)); + PropertyDeclaration pd = (PropertyDeclaration)cu.Children.Single().GetChildByRole(TypeDeclaration.MemberRole); + Assert.AreEqual(new AstLocation(2, code.IndexOf("{\n\t\tget") - line2Pos + 1), pd.GetChildByRole(AstNode.Roles.LBrace).StartLocation); + Assert.AreEqual(new AstLocation(5, 3), pd.EndLocation); + Assert.AreEqual(new AstLocation(3, code.IndexOf("{ return") - line3Pos + 1), pd.Getter.Body.StartLocation); + Assert.AreEqual(new AstLocation(3, code.IndexOf("}\n\t\tset") + 1 - line3Pos + 1), pd.Getter.Body.EndLocation); + Assert.AreEqual(new AstLocation(4, code.IndexOf("{ f =") - line4Pos + 1), pd.Setter.Body.StartLocation); + Assert.AreEqual(new AstLocation(4, code.IndexOf("}\n\t}") + 1 - line4Pos + 1), pd.Setter.Body.EndLocation); + } + + [Test, Ignore("type references not yet implemented")] + public void PropertyImplementingInterfaceTest() + { + PropertyDeclaration pd = ParseUtilCSharp.ParseTypeMember("int MyInterface.MyProperty { get {} } "); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsFalse(pd.Getter.IsNull); + Assert.IsTrue(pd.Setter.IsNull); + + Assert.AreEqual("MyInterface", pd.PrivateImplementationType); + } + + [Test, Ignore("type references not yet implemented")] + public void PropertyImplementingGenericInterfaceTest() + { + PropertyDeclaration pd = ParseUtilCSharp.ParseTypeMember("int MyInterface.MyProperty { get {} } "); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsFalse(pd.Getter.IsNull); + Assert.IsTrue(pd.Setter.IsNull); + + throw new NotImplementedException(); + //Assert.AreEqual("MyInterface", pd.InterfaceImplementations[0].InterfaceType.Type); + //Assert.AreEqual("System.String", pd.InterfaceImplementations[0].InterfaceType.GenericTypes[0].Type); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeSystemConvertVisitorTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeSystemConvertVisitorTests.cs new file mode 100644 index 000000000..6b52a8dc9 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeSystemConvertVisitorTests.cs @@ -0,0 +1,36 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + + +using System; +using System.IO; +using ICSharpCode.NRefactory.TypeSystem; +using ICSharpCode.NRefactory.TypeSystem.Implementation; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Parser +{ + [TestFixture, Ignore("TypeSystemConvertVisitor is not complete yet")] + public class TypeSystemConvertVisitorTests : TypeSystemTests + { + ITypeResolveContext ctx = CecilLoaderTests.Mscorlib; + + [TestFixtureSetUp] + public void FixtureSetUp() + { + const string fileName = "TypeSystemTests.TestCase.cs"; + + CSharpParser parser = new CSharpParser(); + CompilationUnit cu; + using (Stream s = typeof(TypeSystemTests).Assembly.GetManifestResourceStream(typeof(TypeSystemTests), fileName)) { + cu = parser.Parse(s); + } + + testCasePC = new SimpleProjectContent(); + TypeSystemConvertVisitor visitor = new TypeSystemConvertVisitor(testCasePC, fileName); + cu.AcceptVisitor(visitor, null); + ParsedFile parsedFile = visitor.ParsedFile; + ((SimpleProjectContent)testCasePC).UpdateProjectContent(null, parsedFile.TopLevelTypeDefinitions, null, null); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/AttributeTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/AttributeTests.cs new file mode 100644 index 000000000..dc5768803 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/AttributeTests.cs @@ -0,0 +1,96 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + [TestFixture, Ignore("DOM for attributes is incomplete")] + public class AttributeTests : ResolverTestBase + { + [Test] + public void NamespaceInAttributeContext() + { + string program = "using System; [$System.Runtime$.CompilerServices.IndexerName(\"bla\")] class Test { }"; + NamespaceResolveResult result = Resolve(program); + Assert.AreEqual("System.Runtime", result.NamespaceName); + } + + [Test] + public void AttributeWithShortName() + { + string program = "using System; [$Obsolete$] class Test {}"; + + TypeResolveResult result = Resolve(program); + Assert.AreEqual("System.ObsoleteAttribute", result.Type.FullName); + } + + [Test] + public void QualifiedAttributeWithShortName() + { + string program = "using System; [$System.Obsolete$] class Test {}"; + + TypeResolveResult result = Resolve(program); + Assert.AreEqual("System.ObsoleteAttribute", result.Type.FullName); + } + + [Test] + public void AttributeConstructor1() + { + string program = "using System; [$LoaderOptimization(3)$] class Test { }"; + var mrr = Resolve(program); + Assert.AreEqual("System.LoaderOptimization.#ctor", mrr.Member.FullName); + Assert.AreEqual("System.Byte", (mrr.Member as IMethod).Parameters[0].Type.Resolve(context).FullName); + } + + [Test] + public void AttributeConstructor2() + { + string program = "using System; [$LoaderOptimization(LoaderOptimization.NotSpecified)$] class Test { }"; + var mrr = Resolve(program); + Assert.AreEqual("System.LoaderOptimization.#ctor", mrr.Member.FullName); + Assert.AreEqual("System.LoaderOptimization", (mrr.Member as IMethod).Parameters[0].Type.Resolve(context).FullName); + } + + [Test] + public void AttributeArgumentInClassContext1() + { + string program = @"using System; +[AttributeUsage($XXX$)] class MyAttribute : Attribute { + public const AttributeTargets XXX = AttributeTargets.All; +} +"; + MemberResolveResult result = Resolve(program); + Assert.AreEqual("MyAttribute.XXX", result.Member.FullName); + } + + [Test] + public void AttributeArgumentInClassContext2() + { + string program = @"using System; namespace MyNamespace { +[SomeAttribute($E.A$)] class Test { } +enum E { A, B } +} +"; + MemberResolveResult result = Resolve(program); + Assert.AreEqual("MyNamespace.E.A", result.Member.FullName); + } + + [Test] + public void SD_1384() + { + string program = @"using System; +class Flags { + [Flags] + enum $Test$ { } +}"; + TypeResolveResult result = Resolve(program); + Assert.AreEqual("Flags.Test", result.Type.FullName); + + var rt = result.Type.GetDefinition().Attributes[0].AttributeType.Resolve(context); + Assert.AreEqual("System.FlagsAttribute", rt.FullName); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/BinaryOperatorTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/BinaryOperatorTests.cs new file mode 100644 index 000000000..8e058940c --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/BinaryOperatorTests.cs @@ -0,0 +1,392 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + // assign short name to the fake reflection type + using dynamic = ICSharpCode.NRefactory.TypeSystem.ReflectionHelper.Dynamic; + + [TestFixture] + public unsafe class BinaryOperatorTests : ResolverTestBase + { + [Test] + public void Multiplication() + { + AssertType(typeof(int), resolver.ResolveBinaryOperator( + BinaryOperatorType.Multiply, MakeResult(typeof(int)), MakeResult(typeof(int)))); + + AssertType(typeof(float), resolver.ResolveBinaryOperator( + BinaryOperatorType.Multiply, MakeResult(typeof(int)), MakeConstant(0.0f))); + + AssertConstant(3.0f, resolver.ResolveBinaryOperator( + BinaryOperatorType.Multiply, MakeConstant(1.5f), MakeConstant(2))); + + AssertConstant(6, resolver.ResolveBinaryOperator( + BinaryOperatorType.Multiply, MakeConstant((byte)2), MakeConstant((byte)3))); + + AssertType(typeof(long?), resolver.ResolveBinaryOperator( + BinaryOperatorType.Multiply, MakeResult(typeof(uint?)), MakeResult(typeof(int?)))); + + AssertError(typeof(decimal), resolver.ResolveBinaryOperator( + BinaryOperatorType.Multiply, MakeResult(typeof(float)), MakeResult(typeof(decimal)))); + } + + [Test] + public void Addition() + { + AssertType(typeof(int?), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeResult(typeof(short)), MakeResult(typeof(byte?)))); + + AssertConstant(3.0, resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeConstant(1.0f), MakeConstant(2.0))); + + AssertConstant(StringComparison.Ordinal, resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeConstant(StringComparison.InvariantCulture), MakeConstant(2))); + + AssertConstant(StringComparison.OrdinalIgnoreCase, resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeConstant((short)3), MakeConstant(StringComparison.InvariantCulture))); + + AssertConstant("Text", resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeConstant("Te"), MakeConstant("xt"))); + + AssertConstant("", resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeConstant(null), resolver.ResolveCast(ResolveType(typeof(string)), MakeConstant(null)))); + + AssertError(typeof(ReflectionHelper.Null), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeConstant(null), MakeConstant(null))); + + AssertType(typeof(Action), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeResult(typeof(Action)), MakeResult(typeof(Action)))); + + AssertType(typeof(Action), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeResult(typeof(Action)), MakeResult(typeof(Action)))); + + Assert.IsTrue(resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeResult(typeof(Action)), MakeResult(typeof(Action))).IsError); + + AssertType(typeof(StringComparison?), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeResult(typeof(StringComparison?)), MakeResult(typeof(int)))); + + AssertType(typeof(StringComparison?), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeResult(typeof(int?)), MakeResult(typeof(StringComparison)))); + + AssertType(typeof(long?), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeResult(typeof(int?)), MakeResult(typeof(uint?)))); + + AssertType(typeof(int?), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeResult(typeof(ushort?)), MakeResult(typeof(ushort?)))); + + Assert.IsTrue(resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeConstant(null), MakeConstant(null)).IsError); + + AssertType(typeof(int?), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeConstant(1), MakeConstant(null))); + + AssertType(typeof(int*), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeResult(typeof(int*)), MakeConstant(1))); + + AssertType(typeof(byte*), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeResult(typeof(long)), MakeResult(typeof(byte*)))); + } + + [Test] + public void AdditionWithOverflow() + { + resolver.CheckForOverflow = false; + AssertConstant(int.MinValue, resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeConstant(int.MaxValue), MakeConstant(1))); + + resolver.CheckForOverflow = true; + AssertError(typeof(int), resolver.ResolveBinaryOperator( + BinaryOperatorType.Add, MakeConstant(int.MaxValue), MakeConstant(1))); + } + + + [Test] + public void Subtraction() + { + AssertType(typeof(int?), resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeResult(typeof(short)), MakeResult(typeof(byte?)))); + + AssertConstant(-1.0, resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeConstant(1.0f), MakeConstant(2.0))); + + AssertConstant(StringComparison.InvariantCulture, resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeConstant(StringComparison.Ordinal), MakeConstant(2))); + + AssertConstant(3, resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeConstant(StringComparison.OrdinalIgnoreCase), MakeConstant(StringComparison.InvariantCulture))); + + Assert.IsTrue(resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeConstant("Te"), MakeConstant("xt")).IsError); + + AssertType(typeof(Action), resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeResult(typeof(Action)), MakeResult(typeof(Action)))); + + AssertType(typeof(Action), resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeResult(typeof(Action)), MakeResult(typeof(Action)))); + + Assert.IsTrue(resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeResult(typeof(Action)), MakeResult(typeof(Action))).IsError); + + AssertType(typeof(StringComparison?), resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeResult(typeof(StringComparison?)), MakeResult(typeof(int)))); + + AssertType(typeof(int?), resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeResult(typeof(StringComparison?)), MakeResult(typeof(StringComparison)))); + + Assert.IsTrue(resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeResult(typeof(int?)), MakeResult(typeof(StringComparison))).IsError); + + AssertType(typeof(byte*), resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeResult(typeof(byte*)), MakeResult(typeof(uint)))); + + AssertType(typeof(long), resolver.ResolveBinaryOperator( + BinaryOperatorType.Subtract, MakeResult(typeof(byte*)), MakeResult(typeof(byte*)))); + } + + [Test] + public void ShiftTest() + { + AssertConstant(6, resolver.ResolveBinaryOperator( + BinaryOperatorType.ShiftLeft, MakeConstant(3), MakeConstant(1))); + + AssertConstant(ulong.MaxValue >> 2, resolver.ResolveBinaryOperator( + BinaryOperatorType.ShiftRight, MakeConstant(ulong.MaxValue), MakeConstant(2))); + + AssertType(typeof(int?), resolver.ResolveBinaryOperator( + BinaryOperatorType.ShiftLeft, MakeResult(typeof(ushort?)), MakeConstant(1))); + + AssertType(typeof(int?), resolver.ResolveBinaryOperator( + BinaryOperatorType.ShiftLeft, MakeConstant(null), MakeConstant(1))); + + AssertType(typeof(int?), resolver.ResolveBinaryOperator( + BinaryOperatorType.ShiftLeft, MakeConstant(null), MakeConstant(null))); + } + + [Test] + public void Equality() + { + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(3), MakeConstant(3))); + + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(3), MakeConstant(3.0))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(2.9), MakeConstant(3))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(double.NaN), MakeConstant(double.NaN))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(float.NaN), MakeConstant(float.NaN))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant("A"), MakeConstant("B"))); + + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant("A"), MakeConstant("A"))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(""), MakeConstant(null))); + + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(null), MakeConstant(null))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(1), MakeConstant(null))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(null), MakeConstant('a'))); + + AssertType(typeof(bool), resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeResult(typeof(int*)), MakeResult(typeof(uint*)))); + } + + [Test] + public void Inequality() + { + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant(3), MakeConstant(3))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant(3), MakeConstant(3.0))); + + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant(2.9), MakeConstant(3))); + + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant(double.NaN), MakeConstant(double.NaN))); + + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant(float.NaN), MakeConstant(double.NaN))); + + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant(float.NaN), MakeConstant(float.NaN))); + + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant("A"), MakeConstant("B"))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant("A"), MakeConstant("A"))); + + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant(""), MakeConstant(null))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant(null), MakeConstant(null))); + + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant(1), MakeConstant(null))); + + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeConstant(null), MakeConstant('a'))); + + AssertType(typeof(bool), resolver.ResolveBinaryOperator( + BinaryOperatorType.InEquality, MakeResult(typeof(int*)), MakeResult(typeof(uint*)))); + } + + [Test] + public void EqualityEnum() + { + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(0), MakeConstant(StringComparison.Ordinal))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(0), MakeConstant(StringComparison.Ordinal))); + + Assert.IsFalse(resolver.ResolveBinaryOperator( + BinaryOperatorType.Equality, MakeConstant(StringComparison.Ordinal), MakeConstant(1)).IsCompileTimeConstant); + } + + [Test] + public void RelationalOperators() + { + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.LessThan, MakeConstant(0), MakeConstant(0))); + + AssertType(typeof(bool), resolver.ResolveBinaryOperator( + BinaryOperatorType.LessThan, MakeResult(typeof(int*)), MakeResult(typeof(uint*)))); + } + + [Test] + public void RelationalEnum() + { + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.LessThan, MakeConstant(0), MakeConstant(StringComparison.Ordinal))); + + AssertError(typeof(bool), resolver.ResolveBinaryOperator( + BinaryOperatorType.LessThanOrEqual, MakeConstant(1), MakeConstant(StringComparison.Ordinal))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.GreaterThan, MakeConstant(StringComparison.CurrentCultureIgnoreCase), MakeConstant(StringComparison.Ordinal))); + + AssertType(typeof(bool), resolver.ResolveBinaryOperator( + BinaryOperatorType.GreaterThan, MakeResult(typeof(StringComparison?)), MakeResult(typeof(StringComparison?)))); + } + + [Test] + public void BitAnd() + { + AssertConstant(5, resolver.ResolveBinaryOperator( + BinaryOperatorType.BitwiseAnd, MakeConstant(7), MakeConstant(13))); + + AssertType(typeof(int?), resolver.ResolveBinaryOperator( + BinaryOperatorType.BitwiseAnd, MakeConstant(null), MakeConstant((short)13))); + + AssertType(typeof(long?), resolver.ResolveBinaryOperator( + BinaryOperatorType.BitwiseAnd, MakeResult(typeof(uint?)), MakeConstant((short)13))); + + AssertType(typeof(uint?), resolver.ResolveBinaryOperator( + BinaryOperatorType.BitwiseAnd, MakeResult(typeof(uint?)), MakeConstant((int)13))); + + AssertType(typeof(ulong?), resolver.ResolveBinaryOperator( + BinaryOperatorType.BitwiseAnd, MakeResult(typeof(ulong?)), MakeConstant((long)13))); + + Assert.IsTrue(resolver.ResolveBinaryOperator( + BinaryOperatorType.BitwiseAnd, MakeResult(typeof(ulong?)), MakeConstant((short)13)).IsError); + } + + [Test] + public void BitXor() + { + AssertConstant(6L ^ 3, resolver.ResolveBinaryOperator( + BinaryOperatorType.ExclusiveOr, MakeConstant(6L), MakeConstant(3))); + + AssertConstant(6UL ^ 3L, resolver.ResolveBinaryOperator( + BinaryOperatorType.ExclusiveOr, MakeConstant(6UL), MakeConstant(3L))); + + AssertError(typeof(ulong), resolver.ResolveBinaryOperator( + BinaryOperatorType.ExclusiveOr, MakeConstant(6UL), MakeConstant(-3L))); + } + + [Test] + public void BitwiseEnum() + { + AssertConstant(AttributeTargets.Field | AttributeTargets.Property, resolver.ResolveBinaryOperator( + BinaryOperatorType.BitwiseOr, MakeConstant(AttributeTargets.Field), MakeConstant(AttributeTargets.Property))); + + AssertConstant(AttributeTargets.Field & AttributeTargets.All, resolver.ResolveBinaryOperator( + BinaryOperatorType.BitwiseAnd, MakeConstant(AttributeTargets.Field), MakeConstant(AttributeTargets.All))); + + AssertConstant(AttributeTargets.Field & 0, resolver.ResolveBinaryOperator( + BinaryOperatorType.BitwiseAnd, MakeConstant(AttributeTargets.Field), MakeConstant(0))); + + AssertConstant(0 | AttributeTargets.Field, resolver.ResolveBinaryOperator( + BinaryOperatorType.BitwiseOr, MakeConstant(0), MakeConstant(AttributeTargets.Field))); + } + + [Test] + public void LogicalAnd() + { + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.LogicalAnd, MakeConstant(true), MakeConstant(true))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.LogicalAnd, MakeConstant(false), MakeConstant(true))); + + AssertError(typeof(bool), resolver.ResolveBinaryOperator( + BinaryOperatorType.LogicalAnd, MakeConstant(false), MakeResult(typeof(bool?)))); + } + + [Test] + public void LogicalOr() + { + AssertConstant(true, resolver.ResolveBinaryOperator( + BinaryOperatorType.LogicalOr, MakeConstant(false), MakeConstant(true))); + + AssertConstant(false, resolver.ResolveBinaryOperator( + BinaryOperatorType.LogicalOr, MakeConstant(false), MakeConstant(false))); + + AssertError(typeof(bool), resolver.ResolveBinaryOperator( + BinaryOperatorType.LogicalOr, MakeConstant(false), MakeResult(typeof(bool?)))); + } + + [Test] + public void NullCoalescing() + { + AssertType(typeof(int), resolver.ResolveBinaryOperator( + BinaryOperatorType.NullCoalescing, MakeResult(typeof(int?)), MakeResult(typeof(short)))); + + AssertType(typeof(int?), resolver.ResolveBinaryOperator( + BinaryOperatorType.NullCoalescing, MakeResult(typeof(int?)), MakeResult(typeof(short?)))); + + AssertType(typeof(object), resolver.ResolveBinaryOperator( + BinaryOperatorType.NullCoalescing, MakeResult(typeof(string)), MakeResult(typeof(object)))); + + AssertError(typeof(string), resolver.ResolveBinaryOperator( + BinaryOperatorType.NullCoalescing, MakeResult(typeof(string)), MakeResult(typeof(int)))); + + AssertType(typeof(dynamic), resolver.ResolveBinaryOperator( + BinaryOperatorType.NullCoalescing, MakeResult(typeof(dynamic)), MakeResult(typeof(string)))); + + AssertType(typeof(dynamic), resolver.ResolveBinaryOperator( + BinaryOperatorType.NullCoalescing, MakeResult(typeof(string)), MakeResult(typeof(dynamic)))); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/CastTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/CastTests.cs new file mode 100644 index 000000000..a961a9b8c --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/CastTests.cs @@ -0,0 +1,57 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + // assign short name to the fake reflection type + using dynamic = ICSharpCode.NRefactory.TypeSystem.ReflectionHelper.Dynamic; + + [TestFixture] + public class CastTests : ResolverTestBase + { + [Test] + public void SimpleCast() + { + AssertType(typeof(int), resolver.ResolveCast(ResolveType(typeof(int)), MakeResult(typeof(float)))); + AssertType(typeof(string), resolver.ResolveCast(ResolveType(typeof(string)), MakeResult(typeof(object)))); + AssertType(typeof(byte), resolver.ResolveCast(ResolveType(typeof(byte)), MakeResult(typeof(dynamic)))); + AssertType(typeof(dynamic), resolver.ResolveCast(ResolveType(typeof(dynamic)), MakeResult(typeof(double)))); + } + + [Test] + public void ConstantValueCast() + { + AssertConstant("Hello", resolver.ResolveCast(ResolveType(typeof(string)), MakeConstant("Hello"))); + AssertConstant((byte)1L, resolver.ResolveCast(ResolveType(typeof(byte)), MakeConstant(1L))); + AssertConstant(3, resolver.ResolveCast(ResolveType(typeof(int)), MakeConstant(3.1415))); + AssertConstant(3, resolver.ResolveCast(ResolveType(typeof(int)), MakeConstant(3.99))); + AssertConstant((short)-3, resolver.ResolveCast(ResolveType(typeof(short)), MakeConstant(-3.99f))); + AssertConstant(-3L, resolver.ResolveCast(ResolveType(typeof(long)), MakeConstant(-3.5))); + } + + [Test] + public void OverflowingCast() + { + resolver.CheckForOverflow = false; + AssertConstant(uint.MaxValue, resolver.ResolveCast(ResolveType(typeof(uint)), MakeConstant(-1.6))); + resolver.CheckForOverflow = true; + AssertError(typeof(uint), resolver.ResolveCast(ResolveType(typeof(uint)), MakeConstant(-1.6))); + } + + [Test] + public void FailingStringCast() + { + AssertError(typeof(string), resolver.ResolveCast(ResolveType(typeof(string)), MakeConstant(1))); + } + + [Test] + public void OverflowingCastToEnum() + { + resolver.CheckForOverflow = true; + AssertError(typeof(StringComparison), resolver.ResolveCast(ResolveType(typeof(StringComparison)), MakeConstant(long.MaxValue))); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ConversionsTest.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ConversionsTest.cs new file mode 100644 index 000000000..a63ba562c --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ConversionsTest.cs @@ -0,0 +1,336 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections; +using System.Collections.Generic; +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + // assign short names to the fake reflection types + using Null = ICSharpCode.NRefactory.TypeSystem.ReflectionHelper.Null; + using dynamic = ICSharpCode.NRefactory.TypeSystem.ReflectionHelper.Dynamic; + + [TestFixture] + public unsafe class ConversionsTest + { + IProjectContent mscorlib = CecilLoaderTests.Mscorlib; + Conversions conversions = new Conversions(CecilLoaderTests.Mscorlib); + + bool ImplicitConversion(Type from, Type to) + { + IType from2 = from.ToTypeReference().Resolve(mscorlib); + IType to2 = to.ToTypeReference().Resolve(mscorlib); + return conversions.ImplicitConversion(from2, to2); + } + + [Test] + public void IdentityConversions() + { + Assert.IsTrue(ImplicitConversion(typeof(char), typeof(char))); + Assert.IsTrue(ImplicitConversion(typeof(string), typeof(string))); + Assert.IsTrue(ImplicitConversion(typeof(object), typeof(object))); + Assert.IsFalse(ImplicitConversion(typeof(bool), typeof(char))); + + Assert.IsTrue(conversions.ImplicitConversion(SharedTypes.Dynamic, SharedTypes.Dynamic)); + Assert.IsTrue(conversions.ImplicitConversion(SharedTypes.UnknownType, SharedTypes.UnknownType)); + Assert.IsTrue(conversions.ImplicitConversion(SharedTypes.Null, SharedTypes.Null)); + } + + [Test] + public void DynamicIdentityConversions() + { + Assert.IsTrue(ImplicitConversion(typeof(object), typeof(ReflectionHelper.Dynamic))); + Assert.IsTrue(ImplicitConversion(typeof(ReflectionHelper.Dynamic), typeof(object))); + } + + [Test] + public void ComplexDynamicIdentityConversions() + { + Assert.IsTrue(ImplicitConversion(typeof(List), typeof(List))); + Assert.IsTrue(ImplicitConversion(typeof(List), typeof(List))); + Assert.IsFalse(ImplicitConversion(typeof(List), typeof(List))); + Assert.IsFalse(ImplicitConversion(typeof(List), typeof(List))); + + Assert.IsTrue(ImplicitConversion(typeof(List[]>), typeof(List[]>))); + Assert.IsTrue(ImplicitConversion(typeof(List[]>), typeof(List[]>))); + Assert.IsFalse(ImplicitConversion(typeof(List[,]>), typeof(List[]>))); + } + + [Test] + public void PrimitiveConversions() + { + Assert.IsTrue(ImplicitConversion(typeof(char), typeof(ushort))); + Assert.IsFalse(ImplicitConversion(typeof(byte), typeof(char))); + Assert.IsTrue(ImplicitConversion(typeof(int), typeof(long))); + Assert.IsFalse(ImplicitConversion(typeof(long), typeof(int))); + Assert.IsTrue(ImplicitConversion(typeof(int), typeof(float))); + Assert.IsFalse(ImplicitConversion(typeof(bool), typeof(float))); + Assert.IsTrue(ImplicitConversion(typeof(float), typeof(double))); + Assert.IsFalse(ImplicitConversion(typeof(float), typeof(decimal))); + Assert.IsTrue(ImplicitConversion(typeof(char), typeof(long))); + Assert.IsTrue(ImplicitConversion(typeof(uint), typeof(long))); + } + + [Test] + public void NullableConversions() + { + Assert.IsTrue(ImplicitConversion(typeof(char), typeof(ushort?))); + Assert.IsFalse(ImplicitConversion(typeof(byte), typeof(char?))); + Assert.IsTrue(ImplicitConversion(typeof(int), typeof(long?))); + Assert.IsFalse(ImplicitConversion(typeof(long), typeof(int?))); + Assert.IsTrue(ImplicitConversion(typeof(int), typeof(float?))); + Assert.IsFalse(ImplicitConversion(typeof(bool), typeof(float?))); + Assert.IsTrue(ImplicitConversion(typeof(float), typeof(double?))); + Assert.IsFalse(ImplicitConversion(typeof(float), typeof(decimal?))); + } + + [Test] + public void NullableConversions2() + { + Assert.IsTrue(ImplicitConversion(typeof(char?), typeof(ushort?))); + Assert.IsFalse(ImplicitConversion(typeof(byte?), typeof(char?))); + Assert.IsTrue(ImplicitConversion(typeof(int?), typeof(long?))); + Assert.IsFalse(ImplicitConversion(typeof(long?), typeof(int?))); + Assert.IsTrue(ImplicitConversion(typeof(int?), typeof(float?))); + Assert.IsFalse(ImplicitConversion(typeof(bool?), typeof(float?))); + Assert.IsTrue(ImplicitConversion(typeof(float?), typeof(double?))); + Assert.IsFalse(ImplicitConversion(typeof(float?), typeof(decimal?))); + } + + [Test] + public void NullLiteralConversions() + { + Assert.IsTrue(ImplicitConversion(typeof(Null), typeof(int?))); + Assert.IsTrue(ImplicitConversion(typeof(Null), typeof(char?))); + Assert.IsFalse(ImplicitConversion(typeof(Null), typeof(int))); + Assert.IsTrue(ImplicitConversion(typeof(Null), typeof(object))); + Assert.IsTrue(ImplicitConversion(typeof(Null), typeof(dynamic))); + Assert.IsTrue(ImplicitConversion(typeof(Null), typeof(string))); + Assert.IsTrue(ImplicitConversion(typeof(Null), typeof(int[]))); + } + + [Test] + public void SimpleReferenceConversions() + { + Assert.IsTrue(ImplicitConversion(typeof(string), typeof(object))); + Assert.IsTrue(ImplicitConversion(typeof(BitArray), typeof(ICollection))); + Assert.IsTrue(ImplicitConversion(typeof(IList), typeof(IEnumerable))); + Assert.IsFalse(ImplicitConversion(typeof(object), typeof(string))); + Assert.IsFalse(ImplicitConversion(typeof(ICollection), typeof(BitArray))); + Assert.IsFalse(ImplicitConversion(typeof(IEnumerable), typeof(IList))); + } + + [Test] + public void SimpleDynamicConversions() + { + Assert.IsTrue(ImplicitConversion(typeof(string), typeof(dynamic))); + Assert.IsTrue(ImplicitConversion(typeof(dynamic), typeof(string))); + Assert.IsTrue(ImplicitConversion(typeof(int), typeof(dynamic))); + Assert.IsTrue(ImplicitConversion(typeof(dynamic), typeof(int))); + } + + [Test] + public void ParameterizedTypeConversions() + { + Assert.IsTrue(ImplicitConversion(typeof(List), typeof(ICollection))); + Assert.IsTrue(ImplicitConversion(typeof(IList), typeof(ICollection))); + Assert.IsFalse(ImplicitConversion(typeof(List), typeof(ICollection))); + Assert.IsFalse(ImplicitConversion(typeof(IList), typeof(ICollection))); + } + + [Test] + public void ArrayConversions() + { + Assert.IsTrue(ImplicitConversion(typeof(string[]), typeof(object[]))); + Assert.IsTrue(ImplicitConversion(typeof(string[,]), typeof(object[,]))); + Assert.IsFalse(ImplicitConversion(typeof(string[]), typeof(object[,]))); + Assert.IsFalse(ImplicitConversion(typeof(object[]), typeof(string[]))); + + Assert.IsTrue(ImplicitConversion(typeof(string[]), typeof(IList))); + Assert.IsFalse(ImplicitConversion(typeof(string[,]), typeof(IList))); + Assert.IsTrue(ImplicitConversion(typeof(string[]), typeof(IList))); + + Assert.IsTrue(ImplicitConversion(typeof(string[]), typeof(Array))); + Assert.IsTrue(ImplicitConversion(typeof(string[]), typeof(ICloneable))); + Assert.IsFalse(ImplicitConversion(typeof(Array), typeof(string[]))); + Assert.IsFalse(ImplicitConversion(typeof(object), typeof(object[]))); + } + + [Test] + public void VarianceConversions() + { + Assert.IsTrue(ImplicitConversion(typeof(List), typeof(IEnumerable))); + Assert.IsFalse(ImplicitConversion(typeof(List), typeof(IEnumerable))); + Assert.IsTrue(ImplicitConversion(typeof(IEnumerable), typeof(IEnumerable))); + Assert.IsFalse(ImplicitConversion(typeof(ICollection), typeof(ICollection))); + + Assert.IsTrue(ImplicitConversion(typeof(Comparer), typeof(IComparer))); + Assert.IsTrue(ImplicitConversion(typeof(Comparer), typeof(IComparer))); + Assert.IsFalse(ImplicitConversion(typeof(Comparer), typeof(Comparer))); + + Assert.IsFalse(ImplicitConversion(typeof(List), typeof(IEnumerable))); + Assert.IsTrue(ImplicitConversion(typeof(IEnumerable), typeof(IEnumerable))); + + Assert.IsTrue(ImplicitConversion(typeof(Func), typeof(Func))); + Assert.IsTrue(ImplicitConversion(typeof(Func), typeof(Func))); + Assert.IsFalse(ImplicitConversion(typeof(Func), typeof(Func))); + Assert.IsFalse(ImplicitConversion(typeof(Func), typeof(Func))); + } + + [Test] + public void PointerConversion() + { + Assert.IsTrue(ImplicitConversion(typeof(Null), typeof(int*))); + Assert.IsTrue(ImplicitConversion(typeof(int*), typeof(void*))); + } + + [Test] + public void NoConversionFromPointerTypeToObject() + { + Assert.IsFalse(ImplicitConversion(typeof(int*), typeof(object))); + Assert.IsFalse(ImplicitConversion(typeof(int*), typeof(dynamic))); + } + + [Test, Ignore] + public void TypeParameterConversions() + { + // TODO: write tests for conversions of type parameters + throw new NotImplementedException(); + } + + bool IntegerLiteralConversion(object value, Type to) + { + IType fromType = value.GetType().ToTypeReference().Resolve(mscorlib); + ConstantResolveResult crr = new ConstantResolveResult(fromType, value); + IType to2 = to.ToTypeReference().Resolve(mscorlib); + return conversions.ImplicitConversion(crr, to2); + } + + [Test] + public void IntegerLiteralToEnumConversions() + { + Assert.IsTrue(IntegerLiteralConversion(0, typeof(LoaderOptimization))); + Assert.IsTrue(IntegerLiteralConversion(0L, typeof(LoaderOptimization))); + Assert.IsTrue(IntegerLiteralConversion(0, typeof(LoaderOptimization?))); + Assert.IsFalse(IntegerLiteralConversion(0, typeof(string))); + Assert.IsFalse(IntegerLiteralConversion(1, typeof(LoaderOptimization))); + } + + [Test] + public void ImplicitConstantExpressionConversion() + { + Assert.IsTrue(IntegerLiteralConversion(0, typeof(int))); + Assert.IsTrue(IntegerLiteralConversion(0, typeof(ushort))); + Assert.IsTrue(IntegerLiteralConversion(0, typeof(sbyte))); + + Assert.IsTrue (IntegerLiteralConversion(-1, typeof(int))); + Assert.IsFalse(IntegerLiteralConversion(-1, typeof(ushort))); + Assert.IsTrue (IntegerLiteralConversion(-1, typeof(sbyte))); + + Assert.IsTrue (IntegerLiteralConversion(200, typeof(int))); + Assert.IsTrue (IntegerLiteralConversion(200, typeof(ushort))); + Assert.IsFalse(IntegerLiteralConversion(200, typeof(sbyte))); + } + + [Test] + public void ImplicitLongConstantExpressionConversion() + { + Assert.IsFalse(IntegerLiteralConversion(0L, typeof(int))); + Assert.IsTrue(IntegerLiteralConversion(0L, typeof(long))); + Assert.IsTrue(IntegerLiteralConversion(0L, typeof(ulong))); + + Assert.IsTrue(IntegerLiteralConversion(-1L, typeof(long))); + Assert.IsFalse(IntegerLiteralConversion(-1L, typeof(ulong))); + } + + [Test] + public void ImplicitConstantExpressionConversionToNullable() + { + Assert.IsTrue(IntegerLiteralConversion(0, typeof(uint?))); + Assert.IsTrue(IntegerLiteralConversion(0, typeof(short?))); + Assert.IsTrue(IntegerLiteralConversion(0, typeof(byte?))); + + Assert.IsFalse(IntegerLiteralConversion(-1, typeof(uint?))); + Assert.IsTrue (IntegerLiteralConversion(-1, typeof(short?))); + Assert.IsFalse(IntegerLiteralConversion(-1, typeof(byte?))); + + Assert.IsTrue(IntegerLiteralConversion(200, typeof(uint?))); + Assert.IsTrue(IntegerLiteralConversion(200, typeof(short?))); + Assert.IsTrue(IntegerLiteralConversion(200, typeof(byte?))); + + Assert.IsFalse(IntegerLiteralConversion(0L, typeof(uint?))); + Assert.IsTrue (IntegerLiteralConversion(0L, typeof(long?))); + Assert.IsTrue (IntegerLiteralConversion(0L, typeof(ulong?))); + + Assert.IsTrue(IntegerLiteralConversion(-1L, typeof(long?))); + Assert.IsFalse(IntegerLiteralConversion(-1L, typeof(ulong?))); + } + + [Test] + public void ImplicitConstantExpressionConversionNumberInterfaces() + { + Assert.IsTrue(IntegerLiteralConversion(0, typeof(IFormattable))); + Assert.IsTrue(IntegerLiteralConversion(0, typeof(IComparable))); + Assert.IsFalse(IntegerLiteralConversion(0, typeof(IComparable))); + Assert.IsFalse(IntegerLiteralConversion(0, typeof(IComparable))); + } + + int BetterConversion(Type s, Type t1, Type t2) + { + IType sType = s.ToTypeReference().Resolve(mscorlib); + IType t1Type = t1.ToTypeReference().Resolve(mscorlib); + IType t2Type = t2.ToTypeReference().Resolve(mscorlib); + return conversions.BetterConversion(sType, t1Type, t2Type); + } + + int BetterConversion(object value, Type t1, Type t2) + { + IType fromType = value.GetType().ToTypeReference().Resolve(mscorlib); + ConstantResolveResult crr = new ConstantResolveResult(fromType, value); + IType t1Type = t1.ToTypeReference().Resolve(mscorlib); + IType t2Type = t2.ToTypeReference().Resolve(mscorlib); + return conversions.BetterConversion(crr, t1Type, t2Type); + } + + [Test] + public void BetterConversion() + { + Assert.AreEqual(1, BetterConversion(typeof(string), typeof(string), typeof(object))); + Assert.AreEqual(2, BetterConversion(typeof(string), typeof(object), typeof(IComparable))); + Assert.AreEqual(0, BetterConversion(typeof(string), typeof(IEnumerable), typeof(IComparable))); + } + + [Test] + public void BetterPrimitiveConversion() + { + Assert.AreEqual(1, BetterConversion(typeof(short), typeof(int), typeof(long))); + Assert.AreEqual(1, BetterConversion(typeof(short), typeof(int), typeof(uint))); + Assert.AreEqual(2, BetterConversion(typeof(ushort), typeof(uint), typeof(int))); + Assert.AreEqual(1, BetterConversion(typeof(char), typeof(short), typeof(int))); + Assert.AreEqual(1, BetterConversion(typeof(char), typeof(ushort), typeof(int))); + Assert.AreEqual(1, BetterConversion(typeof(sbyte), typeof(long), typeof(ulong))); + Assert.AreEqual(2, BetterConversion(typeof(byte), typeof(ushort), typeof(short))); + + Assert.AreEqual(1, BetterConversion(1, typeof(sbyte), typeof(byte))); + Assert.AreEqual(2, BetterConversion(1, typeof(ushort), typeof(sbyte))); + } + + [Test] + public void BetterNullableConversion() + { + Assert.AreEqual(0, BetterConversion(typeof(byte), typeof(int), typeof(uint?))); + Assert.AreEqual(0, BetterConversion(typeof(byte?), typeof(int?), typeof(uint?))); + Assert.AreEqual(1, BetterConversion(typeof(byte), typeof(ushort?), typeof(uint?))); + Assert.AreEqual(2, BetterConversion(typeof(byte?), typeof(ulong?), typeof(uint?))); + Assert.AreEqual(0, BetterConversion(typeof(byte), typeof(ushort?), typeof(uint))); + Assert.AreEqual(0, BetterConversion(typeof(byte), typeof(ushort?), typeof(int))); + Assert.AreEqual(2, BetterConversion(typeof(byte), typeof(ulong?), typeof(uint))); + Assert.AreEqual(0, BetterConversion(typeof(byte), typeof(ulong?), typeof(int))); + Assert.AreEqual(2, BetterConversion(typeof(ushort?), typeof(long?), typeof(int?))); + Assert.AreEqual(0, BetterConversion(typeof(sbyte), typeof(int?), typeof(uint?))); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ExtensionMethodTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ExtensionMethodTests.cs new file mode 100644 index 000000000..00e531387 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ExtensionMethodTests.cs @@ -0,0 +1,89 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + [TestFixture] + public class ExtensionMethodTests : ResolverTestBase + { + [Test] + public void ExtensionMethodsTest() + { + string program = @"using XN; +class TestClass { + static void Test(A a, B b, C c) { + $; + } +} +class A { } +class B { + public void F(int i) { } +} +class C { + public void F(object obj) { } +} +namespace XN { + public static class XC { + public static void F(this object obj, int i) { } + public static void F(this object obj, string s) { } + } +} +"; + MemberResolveResult mrr; + + mrr = Resolve(program.Replace("$", "$a.F(1)$")); + Assert.AreEqual("XN.XC.F", mrr.Member.FullName); + Assert.AreEqual("System.Int32", ((IMethod)mrr.Member).Parameters[1].Type.Resolve(context).FullName); + + mrr = Resolve(program.Replace("$", "$a.F(\"text\")$")); + Assert.AreEqual("XN.XC.F", mrr.Member.FullName); + Assert.AreEqual("System.String", ((IMethod)mrr.Member).Parameters[1].Type.Resolve(context).FullName); + + mrr = Resolve(program.Replace("$", "$b.F(1)$")); + Assert.AreEqual("B.F", mrr.Member.FullName); + + mrr = Resolve(program.Replace("$", "$b.F(\"text\")$")); + Assert.AreEqual("XN.XC.F", mrr.Member.FullName); + Assert.AreEqual("System.String", ((IMethod)mrr.Member).Parameters[1].Type.Resolve(context).FullName); + + mrr = Resolve(program.Replace("$", "$c.F(1)$")); + Assert.AreEqual("C.F", mrr.Member.FullName); + + mrr = Resolve(program.Replace("$", "$c.F(\"text\")$")); + Assert.AreEqual("C.F", mrr.Member.FullName); + } + + [Test, Ignore("Test fails due to parser returning incorrect position")] + public void ExtensionMethodsTest2() + { + string program = @"using System; using System.Collections.Generic; +class TestClass { + static void Test(string[] args) { + $; + } +} +public static class XC { + public static int ToInt32(this string s) { return int.Parse(s); } + public static T[] Slice(this T[] source, int index, int count) { throw new NotImplementedException(); } + public static IEnumerable Filter(this IEnumerable source, Predicate predicate) { throw new NotImplementedException(); } +} +"; + MemberResolveResult mrr; + + mrr = Resolve(program.Replace("$", "$\"text\".ToInt32()$")); + Assert.AreEqual("XC.ToInt32", mrr.Member.FullName); + + mrr = Resolve(program.Replace("$", "$args.Slice(1, 2)$")); + Assert.AreEqual("XC.Slice", mrr.Member.FullName); + Assert.AreEqual("System.String[]", mrr.Type.ReflectionName); + + mrr = Resolve(program.Replace("$", "$args.Filter(delegate { return true; })$")); + Assert.AreEqual("XC.Filter", mrr.Member.FullName); + Assert.AreEqual("System.Collections.Generic.IEnumerable{System.String}", mrr.Type.ReflectionName); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/InvocationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/InvocationTests.cs new file mode 100644 index 000000000..11ab8c47c --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/InvocationTests.cs @@ -0,0 +1,268 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + [TestFixture] + public class InvocationTests : ResolverTestBase + { + // TODO: do we want to return the MemberResolveResult for the InvocationExpression, or only for it's target? + + [Test] + public void MethodCallTest() + { + string program = @"class A { + void Method() { + $TargetMethod()$; + } + + int TargetMethod() { + return 3; + } +} +"; + MemberResolveResult result = Resolve(program); + Assert.AreEqual("A.TargetMethod", result.Member.FullName); + Assert.AreEqual("System.Int32", result.Type.ReflectionName); + } + + [Test] + public void InvalidMethodCall() + { + string program = @"class A { + void Method(string b) { + $b.ThisMethodDoesNotExistOnString(b)$; + } +} +"; + UnknownMethodResolveResult result = Resolve(program); + Assert.AreEqual("ThisMethodDoesNotExistOnString", result.MemberName); + Assert.AreEqual("System.String", result.TargetType.FullName); + Assert.AreEqual(1, result.Parameters.Count); + Assert.AreEqual("b", result.Parameters[0].Name); + Assert.AreEqual("System.String", result.Parameters[0].Type.Resolve(context).ReflectionName); + + Assert.AreSame(SharedTypes.UnknownType, result.Type); + } + + [Test, Ignore("Inheritance not supported in parser")] + public void OverriddenMethodCall() + { + string program = @"class A { + void Method() { + $new B().GetRandomNumber()$; + } + + public abstract int GetRandomNumber(); +} +class B : A { + public override int GetRandomNumber() { + return 4; // chosen by fair dice roll. + // guaranteed to be random + } +} +"; + MemberResolveResult result = Resolve(program); + Assert.AreEqual("B.GetRandomNumber", result.Member.FullName); + } + + [Test, Ignore("Inheritance not supported in parser")] + public void OverriddenMethodCall2() + { + string program = @"class A { + void Method() { + $new B().GetRandomNumber(""x"", this)$; + } + + public abstract int GetRandomNumber(string a, A b); +} +class B : A { + public override int GetRandomNumber(string b, A a) { + return 4; // chosen by fair dice roll. + // guaranteed to be random + } +} +"; + MemberResolveResult result = Resolve(program); + Assert.AreEqual("B.GetRandomNumber", result.Member.FullName); + } + + [Test] + public void ThisMethodCallTest() + { + string program = @"class A { + void Method() { + $this.TargetMethod()$; + } + + int TargetMethod() { + return 3; + } +} +"; + MemberResolveResult result = Resolve(program); + Assert.AreEqual("A.TargetMethod", result.Member.FullName); + Assert.AreEqual("System.Int32", result.Type.ReflectionName); + } + + [Test] + public void VoidTest() + { + string program = @"using System; +class A { + void TestMethod() { + $TestMethod()$; + } +} +"; + Assert.AreEqual("System.Void", Resolve(program).Type.ReflectionName); + } + + [Test] + public void EventCallTest() + { + string program = @"using System; +class A { + void Method() { + $TestEvent(this, EventArgs.Empty)$; + } + + public event EventHandler TestEvent; +} +"; + Assert.AreEqual("System.Void", Resolve(program).Type.ReflectionName); + } + + [Test] + public void DelegateCallTest() + { + string program = @"using System; using System.Reflection; +class A { + void Method(ModuleResolveEventHandler eh) { + $eh(this, new ResolveEventArgs())$; + } +} +"; + Assert.AreEqual("System.Reflection.Module", Resolve(program).Type.ReflectionName); + } + + [Test] + public void DelegateReturnedFromMethodCallTest() + { + string program = @"using System; +class A { + void Method() { + $GetHandler()(abc)$; + } + abstract Predicate GetHandler(); +} +"; + Assert.AreEqual("System.Boolean", Resolve(program).Type.ReflectionName); + } + + /* TODO + [Test] + public void MethodGroupResolveTest() + { + string program = @"class A { + void Method() { + + } + + void TargetMethod(int a) { } + void TargetMethod(T a) { } +} +"; + MethodGroupResolveResult result = Resolve(program, "TargetMethod", 3); + Assert.AreEqual("TargetMethod", result.Name); + Assert.AreEqual(2, result.Methods.Count); + + result = Resolve(program, "TargetMethod", 3); + Assert.AreEqual("TargetMethod", result.Name); + Assert.AreEqual(1, result.Methods[0].Count); + Assert.AreEqual("System.String", result.GetMethodIfSingleOverload().Parameters[0].ReturnType.FullyQualifiedName); + } + */ + + [Test] + public void TestOverloadingByRef() + { + string program = @"using System; +class Program { + public static void Main() { + int a = 42; + T(a); + T(ref a); + } + static void T(int x) {} + static void T(ref int y) {} +}"; + + MemberResolveResult mrr = Resolve(program, "T(a)"); + Assert.IsFalse(((IMethod)mrr.Member).Parameters[0].IsRef); + + mrr = Resolve(program, "T(ref a)"); + Assert.IsTrue(((IMethod)mrr.Member).Parameters[0].IsRef); + } + + [Test, Ignore("Inheritance not supported in parser")] + public void AddedOverload() + { + string program = @"class BaseClass { + static void Main(DerivedClass d) { + $d.Test(3)$; + } + public void Test(int a) { } +} +class DerivedClass : BaseClass { + public void Test(object a) { } +}"; + MemberResolveResult mrr = Resolve(program); + Assert.AreEqual("DerivedClass.Test", mrr.Member.FullName); + } + + [Test, Ignore("Inheritance not supported in parser")] + public void AddedNonApplicableOverload() + { + string program = @"class BaseClass { + static void Main(DerivedClass d) { + $d.Test(3)$; + } + public void Test(int a) { } +} +class DerivedClass : BaseClass { + public void Test(string a) { } +}"; + MemberResolveResult mrr = Resolve(program); + Assert.AreEqual("BaseClass.Test", mrr.Member.FullName); + + mrr = Resolve(program.Replace("(3)", "(\"3\")")); + Assert.AreEqual("DerivedClass.Test", mrr.Member.FullName); + } + + [Test, Ignore("Inheritance not supported in parser")] + public void OverrideShadowed() + { + string program = @"using System; +class BaseClass { + static void Main() { + $new DerivedClass().Test(3)$; + } + public virtual void Test(int a) { } +} +class MiddleClass : BaseClass { + public void Test(object a) { } +} +class DerivedClass : MiddleClass { + public override void Test(int a) { } +}"; + + MemberResolveResult mrr = Resolve(program); + Assert.AreEqual("MiddleClass.Test", mrr.Member.FullName); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/LambdaTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/LambdaTests.cs new file mode 100644 index 000000000..f98155d96 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/LambdaTests.cs @@ -0,0 +1,278 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + [TestFixture, Ignore("Expression Lambdas not supported by parser")] + public class LambdaTests : ResolverTestBase + { + [Test] + public void SimpleLambdaTest() + { + string program = @"using System; +class TestClass { + static void Main() { + Test(i => Console.WriteLine(i)); + } + public void Test(Action ac) { ac(42); } +}"; + var lrr = Resolve(program.Replace("(i)", "($i$)")); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + + lrr = Resolve(program.Replace("i =>", "$i$ =>")); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaInConstructorTest() + { + string program = @"using System; +class TestClass { + static void Main() { + TestClass t = new TestClass(i => Console.WriteLine($i$)); + } + public TestClass(Action ac) { ac(42); } +}"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaInGenericConstructorTest() + { + string program = @"using System; +class TestClass { + static void Main() { + var t = new SomeClass(i => Console.WriteLine($i$)); + } +} +class SomeClass { + public SomeClass(Action ac) { } +}"; + var lrr = Resolve(program); + Assert.AreEqual("System.String", lrr.Type.ReflectionName); + } + + #region Lambda In Initializer + [Test] + public void LambdaInCollectionInitializerTest1() + { + string program = @"using System; +class TestClass { + static void Main() { + Converter[] arr = { + i => $i$.ToString() + }; + } +} +"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaInCollectionInitializerTest2() + { + string program = @"using System; using System.Collections.Generic; +class TestClass { + static void Main() { + a = new List> { + i => $i$.ToString() + }; + } +} +"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaInCollectionInitializerTest3() + { + string program = @"using System; +class TestClass { + static void Main() { + a = new Converter[] { + i => $i$.ToString() + }; + } +} +"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaInCollectionInitializerTest4() + { + string program = @"using System; +class TestClass { + Converter[] field = new Converter[] { + i => $i$.ToString() + }; +} +"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaInCollectionInitializerTest5() + { + string program = @"using System; +class TestClass { + Converter[] field = { + i => $i$.ToString() + }; +} +"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaInObjectInitializerTest() + { + string program = @"using System; +class X { + void SomeMethod() { + Helper h = new Helper { + F = i => $i$.ToString() + }; + } +} +class Helper { + public Converter F; +} +"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + #endregion + + [Test] + public void LambdaExpressionInCastExpression() + { + string program = @"using System; +static class TestClass { + static void Main(string[] args) { + var f = (Func) ( i => $i$ ); + } + public delegate R Func(T arg); +}"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaExpressionInReturnStatement() + { + string program = @"using System; +static class TestClass { + static Converter GetToString() { + return i => $i$.ToString(); + } +}"; + var lrr = Resolve(program, "i"); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaExpressionInReturnStatementInStatementLambda() + { + string program = @"using System; +static class TestClass { + static void SomeMethod() { + Func> getStringTransformer = () => { + return s => $s$.ToUpper(); + }; + } + public delegate R Func(T arg); + public delegate R Func(); +}"; + var lrr = Resolve(program); + Assert.AreEqual("System.String", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaExpressionInReturnStatementInAnonymousMethod() + { + string program = @"using System; +static class TestClass { + static void SomeMethod() { + Func> getStringTransformer = delegate { + return s => $s$.ToUpper(); + }; + } + public delegate R Func(T arg); + public delegate R Func(); +}"; + var lrr = Resolve(program); + Assert.AreEqual("System.String", lrr.Type.ReflectionName); + } + + [Test] + public void CurriedLambdaExpressionInCastExpression() + { + string program = @"using System; +static class TestClass { + static void Main(string[] args) { + var f = (Func>) ( a => b => 0 ); + } + public delegate R Func(T arg); +}"; + var lrr = Resolve(program.Replace("a =>", "$a$ =>")); + Assert.AreEqual("System.Char", lrr.Type.ReflectionName); + + lrr = Resolve(program.Replace("b =>", "$b$ =>")); + Assert.AreEqual("System.String", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaExpressionInVariableInitializer() + { + string program = @"using System; +static class TestClass { + static void Main() { + Func f = $i$ => i.ToString(); + } + public delegate R Func(T arg); +}"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaExpressionInVariableAssignment() + { + string program = @"using System; +static class TestClass { + static void Main() { + Func f; + f = $i$ => i.ToString(); + } + public delegate R Func(T arg); +}"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + + [Test] + public void LambdaInDelegateCall() + { + string program = @"using System; +class TestClass { + static void Main() { + Func, char> f; + f($i$ => i.ToString()); + } + public delegate R Func(T arg); +}"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/LinqTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/LinqTests.cs new file mode 100644 index 000000000..9f5f4eaef --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/LinqTests.cs @@ -0,0 +1,136 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + [TestFixture, Ignore("LINQ not yet implemented")] + public class LinqTests : ResolverTestBase + { + [Test] + public void SimpleLinqTest() + { + string program = @"using System; using System.Linq; +class TestClass { + void Test(string[] input) { + var r = from e in input + where e.StartsWith(""/"") + select e.Trim(); + r.ToString(); + } +} +"; + LocalResolveResult lrr = Resolve(program.Replace("where e", "where $e$")); + Assert.AreEqual("System.String", lrr.Type.ReflectionName); + lrr = Resolve(program.Replace("select e", "select $e$")); + Assert.AreEqual("System.String", lrr.Type.ReflectionName); + lrr = Resolve(program.Replace("from e", "from $e$")); + Assert.AreEqual("System.String", lrr.Type.ReflectionName); + + lrr = Resolve(program.Replace("r.ToString", "$r$.ToString")); + Assert.AreEqual("System.Collections.Generic.IEnumerable", lrr.Type.FullName); + Assert.AreEqual("System.String", ((ParameterizedType)lrr.Type).TypeArguments[0].FullName); + } + + [Test] + public void LinqGroupTest() + { + string program = @"using System; using System.Linq; +class TestClass { + void Test(string[] input) { + var r = from e in input + group e.ToUpper() by e.Length; + $r$.ToString(); + } +} +"; + LocalResolveResult lrr = Resolve(program); + Assert.AreEqual("System.Collections.Generic.IEnumerable", lrr.Type.FullName); + ParameterizedType rt = (ParameterizedType)((ParameterizedType)lrr.Type).TypeArguments[0]; + Assert.AreEqual("System.Linq.IGrouping", rt.FullName); + Assert.AreEqual("System.Int32", rt.TypeArguments[0].FullName); + Assert.AreEqual("System.String", rt.TypeArguments[1].FullName); + } + + [Test] + public void LinqQueryableGroupTest() + { + string program = @"using System; using System.Linq; +class TestClass { + void Test(IQueryable input) { + var r = from e in input + group e.ToUpper() by e.Length; + $r$.ToString(); + } +} +"; + LocalResolveResult lrr = Resolve(program); + Assert.AreEqual("System.Linq.IQueryable", lrr.Type.FullName); + ParameterizedType rt = (ParameterizedType)((ParameterizedType)lrr.Type).TypeArguments[0]; + Assert.AreEqual("System.Linq.IGrouping", rt.FullName); + Assert.AreEqual("System.Int32", rt.TypeArguments[0].FullName); + Assert.AreEqual("System.String", rt.TypeArguments[1].FullName); + } + + [Test] + public void ParenthesizedLinqTest() + { + string program = @"using System; using System.Linq; +class TestClass { + void Test(string[] input) { + $(from e in input select e.Length)$.ToArray(); + } +} +"; + ResolveResult rr = Resolve(program); + Assert.AreEqual("System.Collections.Generic.IEnumerable", rr.Type.FullName); + Assert.AreEqual("System.Int32", ((ParameterizedType)rr.Type).TypeArguments[0].FullName); + } + + [Test] + public void LinqSelectReturnTypeTest() + { + string program = @"using System; +class TestClass { static void M() { + $(from a in new XYZ() select a.ToUpper())$.ToString(); +}} +class XYZ { + public int Select(Func f) { return 42; } +}"; + ResolveResult rr = Resolve(program); + Assert.AreEqual("System.Int32", rr.Type.FullName); + } + + [Test] + public void LinqQueryContinuationTest() + { + string program = @"using System; using System.Linq; +class TestClass { + void Test(string[] input) { + var r = from x in input + select x.GetHashCode() into x + where x == 42 + select x * x; + r.ToString(); + } +} +"; + LocalResolveResult lrr = Resolve(program.Replace("from x", "from $x$")); + Assert.AreEqual("System.String", lrr.Type.ReflectionName); + lrr = Resolve(program.Replace("select x.G", "select $x$.G")); + Assert.AreEqual("System.String", lrr.Type.ReflectionName); + lrr = Resolve(program.Replace("into x", "into $x$")); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + lrr = Resolve(program.Replace("where x", "where $x$")); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + lrr = Resolve(program.Replace("select x * x", "select x * $x$")); + Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); + + lrr = Resolve(program.Replace("r.ToString", "$r$.ToString")); + Assert.AreEqual("System.Collections.Generic.IEnumerable`1[[System.Int32]]", lrr.Type.ReflectionName); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/LocalTypeInferenceTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/LocalTypeInferenceTests.cs new file mode 100644 index 000000000..def97c563 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/LocalTypeInferenceTests.cs @@ -0,0 +1,55 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + [TestFixture] + public class LocalTypeInferenceTests : ResolverTestBase + { + [Test] + public void TypeInferenceTest() + { + string program = @"class TestClass { + static void Test() { + var a = 3; + $a$.ToString(); + } +} +"; + var lrr = Resolve(program); + Assert.AreEqual("System.Int32", lrr.Type.FullName); + } + + [Test] + public void TypeInferenceCycleTest() + { + string program = @"class TestClass { + static void Test() { + var a = a; + $a$.ToString(); + } +} +"; + var lrr = Resolve(program); + Assert.AreSame(SharedTypes.UnknownType, lrr.Type); + } + + [Test] + public void InvalidAnonymousTypeDeclaration() + { + // see SD-1393 + string program = @"using System; +class TestClass { + static void Main() { + var contact = {id = 54321}; + $contact$.ToString(); + } }"; + var lrr = Resolve(program); + Assert.AreEqual(SharedTypes.UnknownType, lrr.Type); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/NameLookupTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/NameLookupTests.cs new file mode 100644 index 000000000..374817f4d --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/NameLookupTests.cs @@ -0,0 +1,755 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Linq; + +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + [TestFixture] + public class NameLookupTests : ResolverTestBase + { + [Test] + public void SimpleNameLookupWithoutContext() + { + // nothing should be found without specifying any UsingScope - however, the resolver also must not crash + resolver.UsingScope = null; + Assert.IsTrue(resolver.ResolveSimpleName("System", new IType[0]).IsError); + } + + [Test] + public void SimpleNamespaceLookup() + { + NamespaceResolveResult nrr = (NamespaceResolveResult)resolver.ResolveSimpleName("System", new IType[0]); + Assert.AreEqual("System", nrr.NamespaceName); + Assert.AreSame(SharedTypes.UnknownType, nrr.Type); + } + + [Test] + public void NamespaceInParentNamespaceLookup() + { + resolver.UsingScope = MakeUsingScope("System.Collections.Generic"); + NamespaceResolveResult nrr = (NamespaceResolveResult)resolver.ResolveSimpleName("Text", new IType[0]); + Assert.AreEqual("System.Text", nrr.NamespaceName); + } + + [Test] + public void NamespacesAreNotImported() + { + AddUsing("System"); + Assert.IsTrue(resolver.ResolveSimpleName("Collections", new IType[0]).IsError); + } + + [Test] + public void ImportedType() + { + AddUsing("System"); + TypeResolveResult trr = (TypeResolveResult)resolver.ResolveSimpleName("String", new IType[0]); + Assert.AreEqual("System.String", trr.Type.FullName); + } + + [Test] + public void UnknownIdentifierTest() + { + UnknownIdentifierResolveResult uirr = (UnknownIdentifierResolveResult)resolver.ResolveSimpleName("xyz", new IType[0]); + Assert.IsTrue(uirr.IsError); + Assert.AreEqual("xyz", uirr.Identifier); + } + + [Test] + public void GlobalIsUnknownIdentifier() + { + Assert.IsTrue(resolver.ResolveSimpleName("global", new IType[0]).IsError); + } + + [Test] + public void GlobalIsAlias() + { + NamespaceResolveResult nrr = (NamespaceResolveResult)resolver.ResolveAlias("global"); + Assert.AreEqual("", nrr.NamespaceName); + } + + [Test] + public void AliasToImportedType() + { + AddUsing("System"); + AddUsingAlias("x", "String"); + TypeResolveResult trr = (TypeResolveResult)resolver.ResolveSimpleName("x", new IType[0]); + // Unknown type (as String isn't looked up in System) + Assert.AreSame(SharedTypes.UnknownType, trr.Type); + } + + [Test] + public void AliasToImportedType2() + { + AddUsing("System"); + resolver.UsingScope = new UsingScope(resolver.UsingScope, "SomeNamespace"); + AddUsingAlias("x", "String"); + TypeResolveResult trr = (TypeResolveResult)resolver.ResolveSimpleName("x", new IType[0]); + Assert.AreEqual("System.String", trr.Type.FullName); + } + + [Test] + public void AliasOperatorOnTypeAlias() + { + AddUsingAlias("x", "System.String"); + Assert.IsTrue(resolver.ResolveAlias("x").IsError); + } + + [Test] + public void AliasOperatorOnNamespaceAlias() + { + AddUsingAlias("x", "System.Collections.Generic"); + NamespaceResolveResult nrr = (NamespaceResolveResult)resolver.ResolveAlias("x"); + Assert.AreEqual("System.Collections.Generic", nrr.NamespaceName); + } + + [Test] + public void AliasOperatorOnNamespace() + { + Assert.IsTrue(resolver.ResolveAlias("System").IsError); + } + + [Test] + public void FindClassInCurrentNamespace() + { + resolver.UsingScope = MakeUsingScope("System.Collections"); + TypeResolveResult trr = (TypeResolveResult)resolver.ResolveSimpleName("String", new IType[0]); + Assert.AreEqual("System.String", trr.Type.FullName); + } + + [Test] + public void FindNeighborNamespace() + { + resolver.UsingScope = MakeUsingScope("System.Collections"); + NamespaceResolveResult nrr = (NamespaceResolveResult)resolver.ResolveSimpleName("Text", new IType[0]); + Assert.AreEqual("System.Text", nrr.NamespaceName); + } + + [Test] + public void FindTypeParameters() + { + resolver.UsingScope = MakeUsingScope("System.Collections.Generic"); + resolver.CurrentTypeDefinition = context.GetClass(typeof(List<>)); + resolver.CurrentMember = resolver.CurrentTypeDefinition.Methods.Single(m => m.Name == "ConvertAll"); + + TypeResolveResult trr; + trr = (TypeResolveResult)resolver.ResolveSimpleName("TOutput", new IType[0]); + Assert.AreSame(((IMethod)resolver.CurrentMember).TypeParameters[0], trr.Type); + + trr = (TypeResolveResult)resolver.ResolveSimpleName("T", new IType[0]); + Assert.AreSame(resolver.CurrentTypeDefinition.TypeParameters[0], trr.Type); + } + + [Test] + public void SimpleParameter() + { + string program = @"class A { + void Method(string a) { + string b = $a$; + } +} +"; + LocalResolveResult result = Resolve(program); + Assert.AreEqual("a", result.Variable.Name); + Assert.IsTrue(result.IsParameter); + Assert.AreEqual("System.String", result.Type.FullName); + } + + [Test] + public void SimpleLocalVariable() + { + string program = @"class A { + void Method() { + string a; + string b = $a$; + } +} +"; + LocalResolveResult result = Resolve(program); + Assert.AreEqual("a", result.Variable.Name); + Assert.IsFalse(result.IsParameter); + + Assert.AreEqual("System.String", result.Type.FullName); + } + + [Test] + public void UnknownTypeTest() + { + string program = @"class A { + void Method($StringBuilder$ b) { + } +} +"; + UnknownIdentifierResolveResult result = Resolve(program); + Assert.AreEqual("StringBuilder", result.Identifier); + + Assert.AreSame(SharedTypes.UnknownType, result.Type); + } + + [Test, Ignore("not yet implemented (depends on distuishing types and expressions in the DOM)")] + public void PropertyNameAmbiguousWithTypeName() + { + string program = @"class A { + public Color Color { get; set; } + + void Method() { + $ + } +} +class Color { public static readonly Color Empty = null; } +"; + TypeResolveResult trr = Resolve(program.Replace("$", "$Color$ c;")); + Assert.AreEqual("Color", trr.Type.Name); + + MemberResolveResult mrr = Resolve(program.Replace("$", "x = $Color$;")); + Assert.AreEqual("Color", mrr.Member.Name); + + Resolve(program.Replace("$", "$Color$ = Color.Empty;")); + Resolve(program.Replace("$", "Color = $Color$.Empty;")); + Resolve(program.Replace("$", "x = $Color$.ToString();")); + } + + [Test] + public void ValueInsideSetterTest() + { + string program = @"class A { + public string Property { + set { + var a = $value$; + } + } +} +"; + LocalResolveResult result = Resolve(program); + Assert.AreEqual("System.String", result.Type.FullName); + Assert.AreEqual("value", result.Variable.Name); + } + + [Test, Ignore("type references not supported")] + public void ValueInsideEventTest() + { + string program = @"using System; class A { + public event EventHandler Ev { + add { + var a = $value$; + } + remove {} + } +} +"; + LocalResolveResult result = Resolve(program); + Assert.AreEqual("System.EventHandler", result.Type.FullName); + Assert.AreEqual("value", result.Variable.Name); + } + + [Test] + public void ValueInsideIndexerSetterTest() + { + string program = @"using System; class A { + public string this[int arg] { + set { + var a = $value$; + } + } +} +"; + LocalResolveResult result = Resolve(program); + Assert.AreEqual("System.String", result.Type.FullName); + Assert.AreEqual("value", result.Variable.Name); + } + + [Test, Ignore("Anonymous method parameters not supported by parser")] + public void AnonymousMethodParameters() + { + string program = @"using System; +class A { + void Method() { + SomeEvent += delegate(object sender, EventArgs e) { + $e$.ToString(); + }; + } } +"; + LocalResolveResult result = Resolve(program); + Assert.AreEqual("System.EventArgs", result.Type.FullName); + Assert.AreEqual("e", result.Variable.Name); + } + + [Test] + public void DefaultTypeCSharp() + { + string program = @"class A { + void Method() { + $int$ a; + } } +"; + TypeResolveResult result = Resolve(program); + Assert.AreEqual("System.Int32", result.Type.FullName); + } + + [Test] + public void LoopVariableScopeTest() + { + string program = @"using System; +class TestClass { + void Test() { + for (int i = 0; i < 10; i++) { + $1$.ToString(); + } + for (long i = 0; i < 10; i++) { + $2$.ToString(); + } + } +} +"; + LocalResolveResult lr = Resolve(program.Replace("$1$", "$i$").Replace("$2$", "i")); + Assert.AreEqual("System.Int32", lr.Type.ReflectionName); + + lr = Resolve(program.Replace("$1$", "i").Replace("$2$", "$i$")); + Assert.AreEqual("System.Int64", lr.Type.ReflectionName); + } + + [Test] + public void NamespacePreferenceTest() + { + // Classes in the current namespace are preferred over classes from + // imported namespaces + string program = @"using System; +namespace Testnamespace { +class A { + $Activator$ a; +} + +class Activator { + +} +} +"; + var result = Resolve(program); + Assert.AreEqual("Testnamespace.Activator", result.Type.FullName); + } + + [Test] + public void ParentNamespaceTypeLookup() + { + string program = @"using System; +namespace Root { + class Alpha {} +} +namespace Root.Child { + class Beta { + $Alpha$ a; + } +} +"; + var result = Resolve(program); + Assert.AreEqual("Root.Alpha", result.Type.FullName); + } + + [Test, Ignore("type references not implemented")] + public void ImportAliasTest() + { + string program = @"using COL = System.Collections; +class TestClass { + COL.ArrayList ff; +} +"; + TypeResolveResult type = Resolve(program, "COL.ArrayList"); + Assert.IsNotNull(type, "COL.ArrayList should resolve to a type"); + Assert.AreEqual("System.Collections.ArrayList", type.Type.FullName, "TypeResolveResult"); + + MemberResolveResult member = Resolve(program, "ff"); + Assert.AreEqual("System.Collections.ArrayList", member.Type.FullName, "the full type should be resolved"); + } + + [Test] + public void ImportAliasNamespaceResolveTest() + { + NamespaceResolveResult ns; + string program = "using COL = System.Collections;\r\nclass A {\r\n$.ArrayList a;\r\n}\r\n"; + ns = Resolve(program.Replace("$", "$COL$")); + Assert.AreEqual("System.Collections", ns.NamespaceName, "COL"); + ns = Resolve(program.Replace("$", "$COL.Generic$")); + Assert.AreEqual("System.Collections.Generic", ns.NamespaceName, "COL.Generic"); + } + + [Test, Ignore("Cannot resolve type references")] + public void ImportAliasClassResolveTest() + { + string program = @"using COL = System.Collections.ArrayList; +class TestClass { + void Test() { + COL a = new COL(); + + } +} +"; + TypeResolveResult trr = Resolve(program.Replace("COL a", "$COL$ a")); + Assert.AreEqual("System.Collections.ArrayList", trr.Type.FullName, "COL"); + ResolveResult rr = Resolve(program.Replace("new COL()", "$new COL()$")); + Assert.AreEqual("System.Collections.ArrayList", rr.Type.FullName, "a"); + } + + [Test] + public void ResolveNamespaceSD_863() + { + string program = @"using System; +namespace A.C { class D {} } +namespace A.B.C { class D {} } +namespace A.B { + class TestClass { + void Test() { + C.D x; + } + } +} +"; + NamespaceResolveResult nrr = Resolve(program.Replace("C.D", "$C$.D")); + Assert.AreEqual("A.B.C", nrr.NamespaceName, "nrr.Name"); + TypeResolveResult trr = Resolve(program.Replace("C.D", "$C.D$")); + Assert.AreEqual("A.B.C.D", trr.Type.FullName); + } + + [Test, Ignore("Broken due to parser returning incorrect positions")] + public void ResolveTypeSD_863() + { + string program = @"using System; +namespace A { class C {} } +namespace A.B { + class C {} + class TestClass { + void Test() { + $C$ a; + } + } +} +"; + TypeResolveResult trr = Resolve(program); + Assert.AreEqual("A.B.C", trr.Type.FullName); + } + + [Test] + public void ShortMaxValueTest() + { + string program = @"using System; +class TestClass { + object a = $short.MaxValue$; +} +"; + MemberResolveResult rr = Resolve(program); + Assert.AreEqual("System.Int16", rr.Type.FullName); + Assert.AreEqual("System.Int16.MaxValue", rr.Member.FullName); + Assert.AreEqual(short.MaxValue, rr.ConstantValue); + } + + [Test, Ignore("Parser produces incorrect positions for :: operator")] + public void ClassWithSameNameAsNamespace() + { + string program = @"using System; namespace XX { + class Test { + static void X() { + a = $; + } + } + class XX { + public static void Test() {} + } }"; + TypeResolveResult trr = Resolve(program.Replace("$", "$XX$")); + Assert.AreEqual("XX.XX", trr.Type.FullName); + + NamespaceResolveResult nrr = Resolve(program.Replace("$", "$global::XX$.T")); + Assert.AreEqual("XX", nrr.NamespaceName); + + trr = Resolve(program.Replace("$", "$global::XX.XX$")); + Assert.AreEqual("XX.XX", trr.Type.FullName); + + MemberResolveResult mrr = Resolve(program.Replace("$", "$XX.Test()$")); + Assert.AreEqual("XX.XX.Test", mrr.Member.FullName); + } + + [Test] + public void ClassNameLookup1() + { + string program = @"namespace MainNamespace { + using Test.Subnamespace; + class Program { + static void M($Test.TheClass$ c) {} + } +} + +namespace Test { public class TheClass { } } +namespace Test.Subnamespace { + public class Test { public class TheClass { } } +} +"; + TypeResolveResult trr = Resolve(program); + Assert.AreEqual("Test.Subnamespace.Test.TheClass", trr.Type.FullName); + } + + [Test] + public void ClassNameLookup2() + { + string program = @"using Test.Subnamespace; +namespace MainNamespace { + class Program { + static void M($Test.TheClass$ c) {} + } +} + +namespace Test { public class TheClass { } } +namespace Test.Subnamespace { + public class Test { public class TheClass { } } +} +"; + TypeResolveResult trr = Resolve(program); + Assert.AreEqual("Test.TheClass", trr.Type.FullName); + } + + [Test] + public void ClassNameLookup3() + { + string program = @"namespace MainNamespace { + using Test.Subnamespace; + class Program { + static void M($Test$ c) {} + } +} + +namespace Test { public class TheClass { } } +namespace Test.Subnamespace { + public class Test { public class TheClass { } } +} +"; + TypeResolveResult trr = Resolve(program); + Assert.AreEqual("Test.Subnamespace.Test", trr.Type.FullName); + } + + [Test] + public void ClassNameLookup4() + { + string program = @"using Test.Subnamespace; +namespace MainNamespace { + class Program { + static void M($Test$ c) {} + } +} + +namespace Test { public class TheClass { } } +namespace Test.Subnamespace { + public class Test { public class TheClass { } } +} +"; + NamespaceResolveResult nrr = Resolve(program); + Assert.AreEqual("Test", nrr.NamespaceName); + } + + [Test] + public void ClassNameLookup5() + { + string program = @"namespace MainNamespace { + using A; + + class M { + void X($Test$ a) {} + } + namespace Test { class B {} } +} + +namespace A { + class Test {} +}"; + NamespaceResolveResult nrr = Resolve(program); + Assert.AreEqual("MainNamespace.Test", nrr.NamespaceName); + } + + [Test, Ignore("Fails because parser does not support base type references")] + public void InvocableRule() + { + string program = @"using System; + class DerivedClass : BaseClass { + static void X() { + a = $; + } + private static new int Test; + } + class BaseClass { + public static string Test() {} + }"; + MemberResolveResult mrr = Resolve(program.Replace("$", "$BaseClass.Test()$")); + Assert.AreEqual("BaseClass.Test", mrr.Member.FullName); + + mrr = Resolve(program.Replace("$", "$Test$")); + Assert.AreEqual("DerivedClass.Test", mrr.Member.FullName); + + mrr = Resolve(program.Replace("$", "$DerivedClass.Test$")); + Assert.AreEqual("DerivedClass.Test", mrr.Member.FullName); + + // returns BaseClass.Test because DerivedClass.Test is not invocable + mrr = Resolve(program.Replace("$", "$DerivedClass.Test()$")); + Assert.AreEqual("BaseClass.Test", mrr.Member.FullName); + } + + [Test, Ignore("Fails because parser does not support base type references")] + public void InvocableRule2() + { + string program = @"using System; + class DerivedClass : BaseClass { + static void X() { + a = $; + } + private static new int Test; + } + delegate string SomeDelegate(); + class BaseClass { + public static SomeDelegate Test; + }"; + MemberResolveResult mrr = Resolve(program.Replace("$", "$BaseClass.Test$()")); + Assert.AreEqual("BaseClass.Test", mrr.Member.FullName); + + mrr = Resolve(program.Replace("$", "$Test$")); + Assert.AreEqual("DerivedClass.Test", mrr.Member.FullName); + + mrr = Resolve(program.Replace("$", "$DerivedClass.Test$")); + Assert.AreEqual("DerivedClass.Test", mrr.Member.FullName); + + // returns BaseClass.Test because DerivedClass.Test is not invocable + mrr = Resolve(program.Replace("$", "$DerivedClass.Test$()")); + Assert.AreEqual("BaseClass.Test", mrr.Member.FullName); + } + + [Test, Ignore("Fails because parser does not support base type references")] + public void AccessibleRule() + { + string program = @"using System; + class BaseClass { + static void X() { + a = $DerivedClass.Test$; + } + public static int Test; + } + class DerivedClass : BaseClass { + private static new int Test; + } + "; + // returns BaseClass.Test because DerivedClass.Test is not accessible + MemberResolveResult mrr = Resolve(program); + Assert.AreEqual("BaseClass.Test", mrr.Member.FullName); + } + + [Test] + public void FieldHidingProperty() + { + string program = @"using System; + class DerivedClass : BaseClass { + static void X() { + a = $Test$; + } + public static new int Test; + } + class BaseClass { + public static int Test { get { return 0; } } + } + "; + MemberResolveResult mrr = Resolve(program); + Assert.AreEqual("DerivedClass.Test", mrr.Member.FullName); + } + + [Test] + public void PropertyHidingField() + { + string program = @"using System; + class DerivedClass : BaseClass { + static void X() { + a = $Test$; + } + public static new int Test { get { return 0; } } + } + class BaseClass { + public static int Test; + } + "; + MemberResolveResult mrr = Resolve(program); + Assert.AreEqual("DerivedClass.Test", mrr.Member.FullName); + } + + [Test, Ignore("Parser doesn't support inheritance")] + public void SD_1487() + { + string program = @"using System; +class C2 : C1 { + public static void M() { + a = $; + } +} +class C1 { + protected static int Field; +}"; + MemberResolveResult mrr; + mrr = Resolve(program.Replace("$", "$Field$")); + Assert.AreEqual("C1.Field", mrr.Member.FullName); + + mrr = Resolve(program.Replace("$", "$C1.Field$")); + Assert.AreEqual("C1.Field", mrr.Member.FullName); + + mrr = Resolve(program.Replace("$", "$C2.Field$")); + Assert.AreEqual("C1.Field", mrr.Member.FullName); + } + + [Test] + public void NullableValue() + { + string program = @"using System; +class Test { + public static void M(int? a) { + $a.Value$.ToString(); + } +}"; + MemberResolveResult rr = Resolve(program); + Assert.AreEqual("System.Nullable.Value", rr.Member.FullName); + Assert.AreEqual("System.Int32", rr.Member.ReturnType.Resolve(context).FullName); + } + + [Test, Ignore("Parser doesn't support inheritance")] + public void MethodHidesEvent() + { + // see SD-1542 + string program = @"using System; +class Test : Form { + public Test() { + a = $base.KeyDown$; + } + void KeyDown(object sender, EventArgs e) {} +} +class Form { + public event EventHandler KeyDown; +}"; + var mrr = Resolve(program); + Assert.AreEqual("Form.KeyDown", mrr.Member.FullName); + + var mgrr = Resolve(program.Replace("base", "this")); + Assert.AreEqual("Test.KeyDown", mgrr.Methods.Single().FullName); + } + + [Test, Ignore("partial classes not yet supported")] + public void ProtectedMemberVisibleWhenBaseTypeReferenceIsInOtherPart() + { + string program = @"using System; +partial class A { + void M1() { + $x$ = 0; + } +} +partial class A : B { } +class B +{ + protected int x; +}"; + var mrr = Resolve(program); + Assert.AreEqual("B.x", mrr.Member.FullName); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ObjectCreationTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ObjectCreationTests.cs new file mode 100644 index 000000000..4fa54b288 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ObjectCreationTests.cs @@ -0,0 +1,135 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + [TestFixture] + public class ObjectCreationTests : ResolverTestBase + { + [Test] + public void GenericObjectCreation() + { + string program = @"using System.Collections.Generic; +class A { + static void Main() { + var a = $new List()$; + } +} +"; + MemberResolveResult result = Resolve(program); + Assert.AreEqual("System.Collections.Generic.List..ctor", result.Member.FullName); + + Assert.AreEqual("System.Collections.Generic.List`1[[System.String]]", result.Type.ReflectionName); + } + + [Test] + public void NonExistingClass() + { + string program = @"class A { + void Method() { + var a = $new ThisClassDoesNotExist()$; + } +} +"; + ResolveResult result = Resolve(program); + Assert.AreSame(SharedTypes.UnknownType, result.Type); + } + + [Test] + public void NonExistingClassTypeName() + { + string program = @"class A { + void Method() { + var a = new $ThisClassDoesNotExist$(); + } +} +"; + UnknownIdentifierResolveResult result = Resolve(program); + Assert.AreEqual("ThisClassDoesNotExist", result.Identifier); + Assert.AreSame(SharedTypes.UnknownType, result.Type); + } + + [Test] + public void CTorOverloadLookupTest() + { + string program = @"class A { + void Method() { + $; + } + + static A() {} + A() {} + A(int intVal) {} + A(double dblVal) {} +} +"; + MemberResolveResult result = Resolve(program.Replace("$", "$new A()$")); + IMethod m = (IMethod)result.Member; + Assert.IsFalse(m.IsStatic, "new A() is static"); + Assert.AreEqual(0, m.Parameters.Count, "new A() parameter count"); + Assert.AreEqual("A", result.Type.FullName); + + result = Resolve(program.Replace("$", "$new A(10)$")); + m = (IMethod)result.Member; + Assert.AreEqual(1, m.Parameters.Count, "new A(10) parameter count"); + Assert.AreEqual("intVal", m.Parameters[0].Name, "new A(10) parameter"); + + result = Resolve(program.Replace("$", "$new A(11.1)$")); + m = (IMethod)result.Member; + Assert.AreEqual(1, m.Parameters.Count, "new A(11.1) parameter count"); + Assert.AreEqual("dblVal", m.Parameters[0].Name, "new A(11.1) parameter"); + } + + [Test] + public void DefaultCTorOverloadLookupTest() + { + string program = @"class A { + void Method() { + $new A()$; + } +} +"; + MemberResolveResult result = Resolve(program); + IMethod m = (IMethod)result.Member; + Assert.IsNotNull(m); + Assert.AreEqual("A", result.Type.ReflectionName); + Assert.AreEqual(0, m.Parameters.Count); + } + + [Test, Ignore("parser doesn't produce any nodes for base constructor calls")] + public void ChainedConstructorCall() + { + string program = @"using System; +class A { + public A(int a) {} +} +class B : A { + public B(int b) + : base(b) + {} +} +class C : B { + public C(int c) + : base(c) + {} + + public C() + : this(0) + {} +} +"; + MemberResolveResult mrr = Resolve(program, "base(b)"); + Assert.AreEqual("A..ctor", mrr.Member.FullName); + + mrr = Resolve(program, "base(c)"); + Assert.AreEqual("B..ctor", mrr.Member.FullName); + + mrr = Resolve(program, "this(0)"); + Assert.AreEqual("C..ctor", mrr.Member.FullName); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/OverloadResolutionTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/OverloadResolutionTests.cs new file mode 100644 index 000000000..eaf63795b --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/OverloadResolutionTests.cs @@ -0,0 +1,185 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using ICSharpCode.NRefactory.TypeSystem; +using ICSharpCode.NRefactory.TypeSystem.Implementation; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + [TestFixture] + public class OverloadResolutionTests + { + readonly ITypeResolveContext context = CecilLoaderTests.Mscorlib; + readonly DefaultTypeDefinition dummyClass = new DefaultTypeDefinition(CecilLoaderTests.Mscorlib, string.Empty, "DummyClass"); + + ResolveResult[] MakeArgumentList(params Type[] argumentTypes) + { + return argumentTypes.Select(t => new ResolveResult(t.ToTypeReference().Resolve(context))).ToArray(); + } + + DefaultMethod MakeMethod(params object[] parameterTypesOrDefaultValues) + { + DefaultMethod m = new DefaultMethod(dummyClass, "Method"); + foreach (var typeOrDefaultValue in parameterTypesOrDefaultValues) { + Type type = typeOrDefaultValue as Type; + if (type != null) + m.Parameters.Add(new DefaultParameter(type.ToTypeReference(), string.Empty)); + else if (Type.GetTypeCode(typeOrDefaultValue.GetType()) > TypeCode.Object) + m.Parameters.Add(new DefaultParameter(typeOrDefaultValue.GetType().ToTypeReference(), string.Empty) { + DefaultValue = new SimpleConstantValue(typeOrDefaultValue.GetType().ToTypeReference(), typeOrDefaultValue) + }); + else + throw new ArgumentException(typeOrDefaultValue.ToString()); + } + return m; + } + + DefaultMethod MakeParamsMethod(params object[] parameterTypesOrDefaultValues) + { + DefaultMethod m = MakeMethod(parameterTypesOrDefaultValues); + ((DefaultParameter)m.Parameters.Last()).IsParams = true; + return m; + } + + DefaultParameter MakeOptionalParameter(IType type, string name) + { + return new DefaultParameter(type, name) { + DefaultValue = new SimpleConstantValue(type, null) + }; + } + + [Test] + public void PreferIntOverUInt() + { + OverloadResolution r = new OverloadResolution(context, MakeArgumentList(typeof(ushort))); + var c1 = MakeMethod(typeof(int)); + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(c1)); + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeMethod(typeof(uint)))); + Assert.IsFalse(r.IsAmbiguous); + Assert.AreSame(c1, r.BestCandidate); + } + + [Test] + public void NullableIntAndNullableUIntIsAmbiguous() + { + OverloadResolution r = new OverloadResolution(context, MakeArgumentList(typeof(ushort?))); + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeMethod(typeof(int?)))); + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeMethod(typeof(uint?)))); + Assert.AreEqual(OverloadResolutionErrors.AmbiguousMatch, r.BestCandidateErrors); + + // then adding a matching overload solves the ambiguity: + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeMethod(typeof(ushort?)))); + Assert.AreEqual(OverloadResolutionErrors.None, r.BestCandidateErrors); + Assert.IsNull(r.BestCandidateAmbiguousWith); + } + + [Test] + public void ParamsMethodMatchesEmptyArgumentList() + { + OverloadResolution r = new OverloadResolution(context, MakeArgumentList()); + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeParamsMethod(typeof(int[])))); + Assert.IsTrue(r.BestCandidateIsExpandedForm); + } + + [Test] + public void ParamsMethodMatchesOneArgumentInExpandedForm() + { + OverloadResolution r = new OverloadResolution(context, MakeArgumentList(typeof(int))); + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeParamsMethod(typeof(int[])))); + Assert.IsTrue(r.BestCandidateIsExpandedForm); + } + + [Test] + public void ParamsMethodMatchesInUnexpandedForm() + { + OverloadResolution r = new OverloadResolution(context, MakeArgumentList(typeof(int[]))); + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeParamsMethod(typeof(int[])))); + Assert.IsFalse(r.BestCandidateIsExpandedForm); + } + + [Test] + public void LessArgumentsPassedToParamsIsBetter() + { + OverloadResolution r = new OverloadResolution(context, MakeArgumentList(typeof(int), typeof(int), typeof(int))); + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeParamsMethod(typeof(int[])))); + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(MakeParamsMethod(typeof(int), typeof(int[])))); + Assert.IsFalse(r.IsAmbiguous); + Assert.AreEqual(2, r.BestCandidate.Parameters.Count); + } + + [Test] + public void CallInvalidParamsDeclaration() + { + OverloadResolution r = new OverloadResolution(context, MakeArgumentList(typeof(int[,]))); + Assert.AreEqual(OverloadResolutionErrors.ArgumentTypeMismatch, r.AddCandidate(MakeParamsMethod(typeof(int)))); + Assert.IsFalse(r.BestCandidateIsExpandedForm); + } + + [Test] + public void PreferMethodWithoutOptionalParameters() + { + var m1 = MakeMethod(); + var m2 = MakeMethod(1); + + OverloadResolution r = new OverloadResolution(context, MakeArgumentList()); + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(m1)); + Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(m2)); + Assert.IsFalse(r.IsAmbiguous); + Assert.AreSame(m1, r.BestCandidate); + } + + [Test] + public void SkeetEvilOverloadResolution() + { + // http://msmvps.com/blogs/jon_skeet/archive/2010/11/02/evil-code-overload-resolution-workaround.aspx + + // static void Foo(T? ignored = default(T?)) where T : struct + var m1 = MakeMethod(); + m1.TypeParameters.Add(new DefaultTypeParameter(m1, 0, "T") { HasValueTypeConstraint = true }); + m1.Parameters.Add(MakeOptionalParameter( + NullableType.Create(m1.TypeParameters[0], context), + "ignored" + )); + + // class ClassConstraint where T : class {} + DefaultTypeDefinition classConstraint = new DefaultTypeDefinition(dummyClass, "ClassConstraint"); + classConstraint.TypeParameters.Add(new DefaultTypeParameter(classConstraint, 0, "T") { HasReferenceTypeConstraint = true }); + + // static void Foo(ClassConstraint ignored = default(ClassConstraint)) + // where T : class + var m2 = MakeMethod(); + m2.TypeParameters.Add(new DefaultTypeParameter(m2, 0, "T") { HasReferenceTypeConstraint = true }); + m2.Parameters.Add(MakeOptionalParameter( + new ParameterizedType(classConstraint, new[] { m2.TypeParameters[0] }), + "ignored" + )); + + // static void Foo() + var m3 = MakeMethod(); + m3.TypeParameters.Add(new DefaultTypeParameter(m3, 0, "T")); + + // Call: Foo(); + OverloadResolution o; + o = new OverloadResolution(context, new ResolveResult[0], typeArguments: new[] { typeof(int).ToTypeReference().Resolve(context) }); + Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(m1)); + Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(m2)); + Assert.AreSame(m1, o.BestCandidate); + + // Call: Foo(); + o = new OverloadResolution(context, new ResolveResult[0], typeArguments: new[] { typeof(string).ToTypeReference().Resolve(context) }); + Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(m1)); + Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(m2)); + Assert.AreSame(m2, o.BestCandidate); + + // Call: Foo(); + o = new OverloadResolution(context, new ResolveResult[0], typeArguments: new[] { typeof(int?).ToTypeReference().Resolve(context) }); + Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(m1)); + Assert.AreEqual(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint, o.AddCandidate(m2)); + Assert.AreEqual(OverloadResolutionErrors.None, o.AddCandidate(m3)); + Assert.AreSame(m3, o.BestCandidate); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ResolverTestBase.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ResolverTestBase.cs new file mode 100644 index 000000000..db7de9560 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ResolverTestBase.cs @@ -0,0 +1,207 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +using ICSharpCode.NRefactory.CSharp.Parser; +using ICSharpCode.NRefactory.TypeSystem; +using ICSharpCode.NRefactory.TypeSystem.Implementation; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + /// + /// Base class with helper functions for resolver unit tests. + /// + public abstract class ResolverTestBase + { + protected readonly IProjectContent mscorlib = CecilLoaderTests.Mscorlib; + protected SimpleProjectContent project; + protected ITypeResolveContext context; + protected CSharpResolver resolver; + + [SetUp] + public virtual void SetUp() + { + project = new SimpleProjectContent(); + context = new CompositeTypeResolveContext(new [] { project, mscorlib }); + resolver = new CSharpResolver(context); + resolver.UsingScope = MakeUsingScope(""); + } + + protected UsingScope MakeUsingScope(string namespaceName) + { + UsingScope u = new UsingScope(project); + if (!string.IsNullOrEmpty(namespaceName)) { + foreach (string element in namespaceName.Split('.')) { + u = new UsingScope(u, string.IsNullOrEmpty(u.NamespaceName) ? element : u.NamespaceName + "." + element); + } + } + return u; + } + + /// + /// Adds a using to the current using scope. + /// + protected void AddUsing(string namespaceName) + { + resolver.UsingScope.Usings.Add(MakeReference(namespaceName)); + } + + /// + /// Adds a using alias to the current using scope. + /// + protected void AddUsingAlias(string alias, string target) + { + resolver.UsingScope.UsingAliases.Add(new KeyValuePair(alias, MakeReference(target))); + } + + protected ITypeOrNamespaceReference MakeReference(string namespaceName) + { + string[] nameParts = namespaceName.Split('.'); + ITypeOrNamespaceReference r = new SimpleTypeOrNamespaceReference(nameParts[0], new ITypeReference[0], resolver.CurrentTypeDefinition, resolver.UsingScope, true); + for (int i = 1; i < nameParts.Length; i++) { + r = new MemberTypeOrNamespaceReference(r, nameParts[i], new ITypeReference[0], resolver.CurrentTypeDefinition, resolver.UsingScope); + } + return r; + } + + protected IType ResolveType(Type type) + { + IType t = type.ToTypeReference().Resolve(context); + if (t == SharedTypes.UnknownType) + throw new InvalidOperationException("Could not resolve type"); + return t; + } + + protected ConstantResolveResult MakeConstant(object value) + { + if (value == null) + return new ConstantResolveResult(SharedTypes.Null, null); + IType type = ResolveType(value.GetType()); + if (type.IsEnum()) + value = Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType())); + return new ConstantResolveResult(type, value); + } + + protected ResolveResult MakeResult(Type type) + { + return new ResolveResult(ResolveType(type)); + } + + protected void AssertConstant(object expectedValue, ResolveResult rr) + { + Assert.IsFalse(rr.IsError, rr.ToString() + " is an error"); + Assert.IsTrue(rr.IsCompileTimeConstant, rr.ToString() + " is not a compile-time constant"); + Type expectedType = expectedValue.GetType(); + Assert.AreEqual(ResolveType(expectedType), rr.Type, "ResolveResult.Type is wrong"); + if (expectedType.IsEnum) { + Assert.AreEqual(Enum.GetUnderlyingType(expectedType), rr.ConstantValue.GetType(), "ResolveResult.ConstantValue has wrong Type"); + Assert.AreEqual(Convert.ChangeType(expectedValue, Enum.GetUnderlyingType(expectedType)), rr.ConstantValue); + } else { + Assert.AreEqual(expectedType, rr.ConstantValue.GetType(), "ResolveResult.ConstantValue has wrong Type"); + Assert.AreEqual(expectedValue, rr.ConstantValue); + } + } + + protected void AssertType(Type expectedType, ResolveResult rr) + { + Assert.IsFalse(rr.IsError, rr.ToString() + " is an error"); + Assert.IsFalse(rr.IsCompileTimeConstant, rr.ToString() + " is a compile-time constant"); + Assert.AreEqual(expectedType.ToTypeReference().Resolve(context), rr.Type); + } + + protected void AssertError(Type expectedType, ResolveResult rr) + { + Assert.IsTrue(rr.IsError, rr.ToString() + " is not an error, but an error was expected"); + Assert.IsFalse(rr.IsCompileTimeConstant, rr.ToString() + " is a compile-time constant"); + Assert.AreEqual(expectedType.ToTypeReference().Resolve(context), rr.Type); + } + + IEnumerable FindDollarSigns(string code) + { + int line = 1; + int col = 1; + foreach (char c in code) { + if (c == '$') { + yield return new AstLocation(line, col); + } else if (c == '\n') { + line++; + col = 1; + } else { + col++; + } + } + } + + protected ResolveResult Resolve(string code) + { + CompilationUnit cu = new CSharpParser().Parse(new StringReader(code.Replace("$", ""))); + + AstLocation[] dollars = FindDollarSigns(code).ToArray(); + Assert.AreEqual(2, dollars.Length, "Expected 2 dollar signs marking start+end of desired node"); + + UsingScope rootUsingScope = resolver.UsingScope; + while (rootUsingScope.Parent != null) + rootUsingScope = rootUsingScope.Parent; + + ParsedFile parsedFile = new ParsedFile("test.cs", rootUsingScope); + TypeSystemConvertVisitor convertVisitor = new TypeSystemConvertVisitor(parsedFile, resolver.UsingScope, null); + cu.AcceptVisitor(convertVisitor, null); + project.UpdateProjectContent(null, convertVisitor.ParsedFile.TopLevelTypeDefinitions, null, null); + + FindNodeVisitor fnv = new FindNodeVisitor(dollars[0], dollars[1]); + cu.AcceptVisitor(fnv, null); + Assert.IsNotNull(fnv.ResultNode, "Did not find DOM node at the specified location"); + + var navigator = new NodeListResolveVisitorNavigator(new[] { fnv.ResultNode }); + ResolveResult rr; + using (var context = this.context.Synchronize()) { + ResolveVisitor rv = new ResolveVisitor(new CSharpResolver(context), convertVisitor.ParsedFile, navigator); + rv.Scan(cu); + rr = rv.GetResolveResult(fnv.ResultNode); + } + Assert.IsNotNull(rr, "ResolveResult is null - did something go wrong while navigating to the target node?"); + return rr; + } + + protected T Resolve(string code) where T : ResolveResult + { + ResolveResult rr = Resolve(code); + Assert.IsInstanceOf(typeof(T), rr); + return (T)rr; + } + + protected T Resolve(string code, string exprToResolve) where T : ResolveResult + { + return Resolve(code.Replace(exprToResolve, "$" + exprToResolve + "$")); + } + + sealed class FindNodeVisitor : DepthFirstAstVisitor + { + readonly AstLocation start; + readonly AstLocation end; + public AstNode ResultNode; + + public FindNodeVisitor(AstLocation start, AstLocation end) + { + this.start = start; + this.end = end; + } + + protected override object VisitChildren(AstNode node, object data) + { + if (node.StartLocation == start && node.EndLocation == end) { + if (ResultNode != null) + throw new InvalidOperationException("found multiple nodes with same start+end"); + return ResultNode = node; + } else { + return base.VisitChildren(node, data); + } + } + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/TypeInferenceTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/TypeInferenceTests.cs new file mode 100644 index 000000000..8391d40a3 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/TypeInferenceTests.cs @@ -0,0 +1,158 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; + +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + [TestFixture] + public class TypeInferenceTests + { + TypeInference ti; + + [SetUp] + public void Setup() + { + ti = new TypeInference(CecilLoaderTests.Mscorlib); + } + + IType[] Resolve(params Type[] types) + { + IType[] r = new IType[types.Length]; + for (int i = 0; i < types.Length; i++) { + r[i] = types[i].ToTypeReference().Resolve(CecilLoaderTests.Mscorlib); + Assert.AreNotSame(r[i], SharedTypes.UnknownType); + } + Array.Sort(r, (a,b)=>a.ReflectionName.CompareTo(b.ReflectionName)); + return r; + } + + IType[] FindAllTypesInBounds(IList lowerBounds, IList upperBounds = null) + { + ti.Algorithm = TypeInferenceAlgorithm.ImprovedReturnAllResults; + IType type = ti.FindTypeInBounds(lowerBounds, upperBounds ?? new IType[0]); + return ExpandIntersections(type).OrderBy(t => t.ReflectionName).ToArray(); + } + + static IEnumerable ExpandIntersections(IType type) + { + IntersectionType it = type as IntersectionType; + if (it != null) { + return it.Types.SelectMany(t => ExpandIntersections(t)); + } + ParameterizedType pt = type as ParameterizedType; + if (pt != null) { + IType[][] typeArguments = new IType[pt.TypeArguments.Count][]; + for (int i = 0; i < typeArguments.Length; i++) { + typeArguments[i] = ExpandIntersections(pt.TypeArguments[i]).ToArray(); + } + return AllCombinations(typeArguments).Select(ta => new ParameterizedType(pt.GetDefinition(), ta)); + } + return new [] { type }; + } + + /// + /// Performs the combinatorial explosion. + /// + static IEnumerable AllCombinations(IType[][] typeArguments) + { + int[] index = new int[typeArguments.Length]; + index[typeArguments.Length - 1] = -1; + while (true) { + int i; + for (i = index.Length - 1; i >= 0; i--) { + if (++index[i] == typeArguments[i].Length) + index[i] = 0; + else + break; + } + if (i < 0) + break; + IType[] r = new IType[typeArguments.Length]; + for (i = 0; i < r.Length; i++) { + r[i] = typeArguments[i][index[i]]; + } + yield return r; + } + } + + [Test] + public void ListOfShortAndInt() + { + Assert.AreEqual( + Resolve(typeof(IList)), + FindAllTypesInBounds(Resolve(typeof(List), typeof(List)))); + } + + [Test] + public void ListOfStringAndObject() + { + Assert.AreEqual( + Resolve(typeof(IList), typeof(IEnumerable)), + FindAllTypesInBounds(Resolve(typeof(List), typeof(List)))); + } + + [Test] + public void ListOfListOfStringAndObject() + { + Assert.AreEqual( + Resolve(typeof(IList), typeof(IEnumerable), typeof(IEnumerable>)), + FindAllTypesInBounds(Resolve(typeof(List>), typeof(List>)))); + } + + [Test] + public void ShortAndInt() + { + Assert.AreEqual( + Resolve(typeof(int)), + FindAllTypesInBounds(Resolve(typeof(short), typeof(int)))); + } + + [Test] + public void StringAndVersion() + { + Assert.AreEqual( + Resolve(typeof(ICloneable), typeof(IComparable)), + FindAllTypesInBounds(Resolve(typeof(string), typeof(Version)))); + } + + [Test] + public void CommonSubTypeClonableComparable() + { + Assert.AreEqual( + Resolve(typeof(string), typeof(Version)), + FindAllTypesInBounds(Resolve(), Resolve(typeof(ICloneable), typeof(IComparable)))); + } + + [Test] + public void EnumerableOfStringAndVersion() + { + Assert.AreEqual( + Resolve(typeof(IEnumerable), typeof(IEnumerable)), + FindAllTypesInBounds(Resolve(typeof(IList), typeof(IList)))); + } + + [Test] + public void CommonSubTypeIEnumerableClonableIEnumerableComparable() + { + Assert.AreEqual( + Resolve(typeof(IEnumerable), typeof(IEnumerable)), + FindAllTypesInBounds(Resolve(), Resolve(typeof(IEnumerable), typeof(IEnumerable)))); + } + + [Test] + public void CommonSubTypeIEnumerableClonableIEnumerableComparableList() + { + Assert.AreEqual( + Resolve(typeof(List), typeof(List), typeof(Collection), typeof(Collection), typeof(ReadOnlyCollection), typeof(ReadOnlyCollection)), + FindAllTypesInBounds(Resolve(), Resolve(typeof(IEnumerable), typeof(IEnumerable), typeof(IList)))); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/UnaryOperatorTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/UnaryOperatorTests.cs new file mode 100644 index 000000000..7793efc31 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/UnaryOperatorTests.cs @@ -0,0 +1,147 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.TypeSystem; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + // assign short name to the fake reflection type + using dynamic = ICSharpCode.NRefactory.TypeSystem.ReflectionHelper.Dynamic; + + [TestFixture] + public unsafe class UnaryOperatorTests : ResolverTestBase + { + [Test] + public void TestAddressOf() + { + AssertType(typeof(int*), resolver.ResolveUnaryOperator(UnaryOperatorType.AddressOf, MakeResult(typeof(int)))); + AssertType(typeof(byte**), resolver.ResolveUnaryOperator(UnaryOperatorType.AddressOf, MakeResult(typeof(byte*)))); + AssertType(typeof(dynamic), resolver.ResolveUnaryOperator(UnaryOperatorType.AddressOf, MakeResult(typeof(dynamic)))); + } + + [Test] + public void TestDereference() + { + AssertType(typeof(int), resolver.ResolveUnaryOperator(UnaryOperatorType.Dereference, MakeResult(typeof(int*)))); + AssertType(typeof(long*), resolver.ResolveUnaryOperator(UnaryOperatorType.Dereference, MakeResult(typeof(long**)))); + Assert.IsTrue(resolver.ResolveUnaryOperator(UnaryOperatorType.Dereference, MakeResult(typeof(int))).IsError); + AssertType(typeof(dynamic), resolver.ResolveUnaryOperator(UnaryOperatorType.Dereference, MakeResult(typeof(dynamic)))); + } + + [Test] + public void TestIncrementDecrement() + { + AssertType(typeof(byte), resolver.ResolveUnaryOperator(UnaryOperatorType.Increment, MakeResult(typeof(byte)))); + AssertType(typeof(ulong), resolver.ResolveUnaryOperator(UnaryOperatorType.Decrement, MakeResult(typeof(ulong)))); + AssertType(typeof(short?), resolver.ResolveUnaryOperator(UnaryOperatorType.PostDecrement, MakeResult(typeof(short?)))); + AssertType(typeof(TypeCode), resolver.ResolveUnaryOperator(UnaryOperatorType.PostIncrement, MakeResult(typeof(TypeCode)))); + AssertType(typeof(TypeCode?), resolver.ResolveUnaryOperator(UnaryOperatorType.PostIncrement, MakeResult(typeof(TypeCode?)))); + AssertType(typeof(dynamic), resolver.ResolveUnaryOperator(UnaryOperatorType.PostIncrement, MakeResult(typeof(dynamic)))); + AssertError(typeof(object), resolver.ResolveUnaryOperator(UnaryOperatorType.Increment, MakeResult(typeof(object)))); + + AssertType(typeof(int*), resolver.ResolveUnaryOperator(UnaryOperatorType.Increment, MakeResult(typeof(int*)))); + AssertType(typeof(uint*), resolver.ResolveUnaryOperator(UnaryOperatorType.PostDecrement, MakeResult(typeof(uint*)))); + } + + [Test] + public void TestUnaryPlus() + { + AssertConstant(1, resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeConstant((sbyte)1))); + AssertConstant(1, resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeConstant((byte)1))); + AssertConstant(1, resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeConstant((short)1))); + AssertConstant(1, resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeConstant((ushort)1))); + AssertConstant(65, resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeConstant('A'))); + AssertConstant(1, resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeConstant(1))); + AssertConstant((uint)1, resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeConstant((uint)1))); + AssertConstant(1L, resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeConstant((long)1))); + AssertConstant((ulong)1, resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeConstant((ulong)1))); + + AssertType(typeof(dynamic), resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeResult(typeof(dynamic)))); + AssertType(typeof(int?), resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeResult(typeof(ushort?)))); + } + + [Test] + public void TestUnaryMinus() + { + AssertConstant(-1, resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeConstant(1))); + AssertConstant(-1L, resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeConstant((uint)1))); + AssertConstant(-2147483648L, resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeConstant(2147483648))); + AssertConstant(-1.0f, resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeConstant(1.0f))); + AssertConstant(-1.0, resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeConstant(1.0))); + AssertConstant(1m, resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeConstant(-1m))); + AssertConstant(-65, resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeConstant('A'))); + + AssertType(typeof(dynamic), resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeResult(typeof(dynamic)))); + AssertType(typeof(long?), resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeResult(typeof(uint?)))); + } + + [Test] + public void TestUnaryMinusUncheckedOverflow() + { + AssertConstant(-2147483648, resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeConstant(-2147483648))); + } + + [Test] + public void TestUnaryMinusCheckedOverflow() + { + resolver.CheckForOverflow = true; + AssertError(typeof(int), resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeConstant(-2147483648))); + } + + [Test] + public void TestBitwiseNot() + { + AssertConstant(1, resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant(-2))); + AssertConstant(~'A', resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant('A'))); + AssertConstant(~(sbyte)1, resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant((sbyte)1))); + AssertConstant(~(byte)1, resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant((byte)1))); + AssertConstant(~(short)1, resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant((short)1))); + AssertConstant(~(ushort)1, resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant((ushort)1))); + AssertConstant(~(uint)1, resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant((uint)1))); + AssertConstant(~(long)1, resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant((long)1))); + AssertConstant(~(ulong)1, resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant((ulong)1))); + Assert.IsTrue(resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant(1.0)).IsError); + + AssertType(typeof(dynamic), resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeResult(typeof(dynamic)))); + AssertType(typeof(uint), resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeResult(typeof(uint)))); + AssertType(typeof(int?), resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeResult(typeof(ushort?)))); + } + + [Test] + public void TestLogicalNot() + { + AssertConstant(true, resolver.ResolveUnaryOperator(UnaryOperatorType.Not, MakeConstant(false))); + AssertConstant(false, resolver.ResolveUnaryOperator(UnaryOperatorType.Not, MakeConstant(true))); + AssertType(typeof(dynamic), resolver.ResolveUnaryOperator(UnaryOperatorType.Not, MakeResult(typeof(dynamic)))); + AssertType(typeof(bool), resolver.ResolveUnaryOperator(UnaryOperatorType.Not, MakeResult(typeof(bool)))); + AssertType(typeof(bool?), resolver.ResolveUnaryOperator(UnaryOperatorType.Not, MakeResult(typeof(bool?)))); + } + + [Test] + public void TestInvalidUnaryOperatorsOnEnum() + { + Assert.IsTrue(resolver.ResolveUnaryOperator(UnaryOperatorType.Not, MakeConstant(StringComparison.Ordinal)).IsError); + Assert.IsTrue(resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeConstant(StringComparison.Ordinal)).IsError); + Assert.IsTrue(resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeConstant(StringComparison.Ordinal)).IsError); + + Assert.IsTrue(resolver.ResolveUnaryOperator(UnaryOperatorType.Not, MakeResult(typeof(StringComparison))).IsError); + Assert.IsTrue(resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeResult(typeof(StringComparison))).IsError); + Assert.IsTrue(resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeResult(typeof(StringComparison))).IsError); + + Assert.IsTrue(resolver.ResolveUnaryOperator(UnaryOperatorType.Not, MakeResult(typeof(StringComparison?))).IsError); + Assert.IsTrue(resolver.ResolveUnaryOperator(UnaryOperatorType.Plus, MakeResult(typeof(StringComparison?))).IsError); + Assert.IsTrue(resolver.ResolveUnaryOperator(UnaryOperatorType.Minus, MakeResult(typeof(StringComparison?))).IsError); + } + + [Test] + public void TestBitwiseNotOnEnum() + { + AssertConstant(~StringComparison.Ordinal, resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant(StringComparison.Ordinal))); + AssertConstant(~StringComparison.CurrentCultureIgnoreCase, resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeConstant(StringComparison.CurrentCultureIgnoreCase))); + AssertType(typeof(StringComparison), resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeResult(typeof(StringComparison)))); + AssertType(typeof(StringComparison?), resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, MakeResult(typeof(StringComparison?)))); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/CSharp/Resolver/UnsafeCodeTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/UnsafeCodeTests.cs new file mode 100644 index 000000000..bf77b15c9 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/CSharp/Resolver/UnsafeCodeTests.cs @@ -0,0 +1,29 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.CSharp.Resolver +{ + [TestFixture] + public class UnsafeCodeTests : ResolverTestBase + { + [Test, Ignore("Parser produces parse tree that doesn't match DOM definition??")] + public void FixedStatement() + { + string program = @"using System; +class TestClass { + static void Main(byte[] a) { + fixed (byte* p = a) { + a = $p$; + } } }"; + + var lrr = Resolve(program); + Assert.AreEqual("System.Byte*", lrr.Type.ReflectionName); + + var rr = Resolve(program.Replace("$p$", "$*p$")); + Assert.AreEqual("System.Byte", lrr.Type.ReflectionName); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/FormattingTests/TestBraceStlye.cs b/ICSharpCode.NRefactory.Tests/FormattingTests/TestBraceStlye.cs new file mode 100644 index 000000000..23cc5e8dd --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/FormattingTests/TestBraceStlye.cs @@ -0,0 +1,530 @@ +// +// TestBraceStyle.cs +// +// Author: +// Mike Krüger +// +// Copyright (c) 2010 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +/* +using System; +using NUnit.Framework; +using MonoDevelop.Ide.Gui; +using MonoDevelop.Projects; +using MonoDevelop.Core; +using MonoDevelop.Ide.CodeCompletion; +using MonoDevelop.Ide.Gui.Content; +using MonoDevelop.Projects.Dom.Parser; +using MonoDevelop.CSharp.Parser; +using MonoDevelop.CSharp.Resolver; +using MonoDevelop.CSharp.Completion; +using Mono.TextEditor; +using MonoDevelop.CSharp.Formatting; + +namespace MonoDevelop.CSharpBinding.FormattingTests +{ + [TestFixture()] + public class TestBraceStyle : UnitTests.TestBase + { + [Test()] + [Ignore("currently failing because namespaces are not inserted")] + public void TestNamespaceBraceStyle () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"namespace A +{ +namespace B { + class Test {} +} +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.NamespaceBraceStyle = BraceStyle.EndOfLine; + policy.ClassBraceStyle = BraceStyle.DoNotChange; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"namespace A { + namespace B { + class Test {} + } +}", data.Document.Text); + + policy.NamespaceBraceStyle = BraceStyle.NextLineShifted; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"namespace A + { + namespace B + { + class Test {} + } + }", data.Document.Text); + } + + + [Test()] + public void TestClassBraceStlye () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test {}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.ClassBraceStyle = BraceStyle.EndOfLine; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { +}", data.Document.Text); + } + + [Test()] + public void TestStructBraceStyle () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"struct Test {}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.StructBraceStyle = BraceStyle.NextLine; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"struct Test +{ +}", data.Document.Text); + } + + [Test()] + public void TestInterfaceBraceStyle () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"interface Test {}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.InterfaceBraceStyle = BraceStyle.NextLine; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"interface Test +{ +}", data.Document.Text); + } + + [Test()] + public void TestEnumBraceStyle () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"enum Test { + A +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.EnumBraceStyle = BraceStyle.NextLineShifted; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"enum Test + { + A + }", data.Document.Text); + } + + [Test()] + public void TestMethodBraceStlye () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test MyMethod() {} +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.MethodBraceStyle = BraceStyle.NextLine; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test MyMethod() + { + } +}", data.Document.Text); + } + + [Test()] + public void TestConstructorBraceStyle () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test() {} +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.ConstructorBraceStyle = BraceStyle.NextLine; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test() + { + } +}", data.Document.Text); + } + + [Test()] + public void TestDestructorBraceStyle () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + ~Test() {} +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.DestructorBraceStyle = BraceStyle.NextLine; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + ~Test() + { + } +}", data.Document.Text); + } + + [Test()] + public void TestPropertyBraceStyle () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test A { + get; + set; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.PropertyBraceStyle = BraceStyle.NextLine; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test A + { + get; + set; + } +}", data.Document.Text); + } + + [Test()] + public void TestPropertyGetBraceStyle () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test A { + get { + return null; + } + set; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.PropertyGetBraceStyle = BraceStyle.NextLine; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test A { + get + { + return null; + } + set; + } +}", data.Document.Text); + } + + [Test()] + public void TestAllowPropertyGetBlockInline () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test A { + get { return null; } + set { ; } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.PropertyBraceStyle = BraceStyle.DoNotChange; + policy.AllowPropertyGetBlockInline = true; + policy.AllowPropertySetBlockInline = false; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test A { + get { return null; } + set { + ; + } + } +}", data.Document.Text); + + policy.AllowPropertyGetBlockInline = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Assert.AreEqual (@"class Test +{ + Test A { + get { + return null; + } + set { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestAllowPropertySetBlockInline () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test A { + get { return null; } + set { ; } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.PropertyBraceStyle = BraceStyle.DoNotChange; + policy.AllowPropertyGetBlockInline = false; + policy.AllowPropertySetBlockInline = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test A { + get { + return null; + } + set { ; } + } +}", data.Document.Text); + + policy.AllowPropertySetBlockInline = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Assert.AreEqual (@"class Test +{ + Test A { + get { + return null; + } + set { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestPropertySetBraceStyle () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test A { + get; + set { + ; + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.PropertySetBraceStyle = BraceStyle.NextLine; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test A { + get; + set + { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestEventBraceStyle () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + public event EventHandler Handler { + add { +} + remove { +} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.EventBraceStyle = BraceStyle.NextLine; + policy.EventAddBraceStyle = BraceStyle.NextLine; + policy.EventRemoveBraceStyle = BraceStyle.NextLine; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + public event EventHandler Handler + { + add + { + } + remove + { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestAllowEventAddBlockInline () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + public event EventHandler Handler { + add { ; } + remove { ; } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.AllowEventAddBlockInline = true; + policy.AllowEventRemoveBlockInline = false; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + public event EventHandler Handler { + add { ; } + remove { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestAllowEventRemoveBlockInline () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + public event EventHandler Handler { + add { ; } + remove { ; } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.AllowEventAddBlockInline = false; + policy.AllowEventRemoveBlockInline = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + public event EventHandler Handler { + add { + ; + } + remove { ; } + } +}", data.Document.Text); + } + + + + } +}*/ diff --git a/ICSharpCode.NRefactory.Tests/FormattingTests/TestFormattingBugs.cs b/ICSharpCode.NRefactory.Tests/FormattingTests/TestFormattingBugs.cs new file mode 100644 index 000000000..0a6a2d6f8 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/FormattingTests/TestFormattingBugs.cs @@ -0,0 +1,162 @@ +// +// TestFormattingBugs.cs +// +// Author: +// Mike Krüger +// +// Copyright (c) 2010 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +/* +using System; +using NUnit.Framework; +using MonoDevelop.Ide.Gui; +using MonoDevelop.Projects; +using MonoDevelop.Core; +using MonoDevelop.Ide.CodeCompletion; +using MonoDevelop.Ide.Gui.Content; +using MonoDevelop.Projects.Dom.Parser; +using MonoDevelop.CSharp.Parser; +using MonoDevelop.CSharp.Resolver; +using MonoDevelop.CSharp.Completion; +using Mono.TextEditor; +using MonoDevelop.CSharp.Formatting; +using System.Collections.Generic; +using MonoDevelop.Refactoring; + +namespace MonoDevelop.CSharpBinding.FormattingTests +{ + [TestFixture()] + public class TestFormattingBugs : UnitTests.TestBase + { + /// + /// Bug 325187 - Bug in smart indent + /// + [Test()] + public void TestBug325187 () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.PlaceElseOnNewLine = true; + + TestStatementFormatting (policy, +@"foreach (int i in myints) +if (i == 6) +Console.WriteLine (""Yeah""); +else +Console.WriteLine (""Bad indent"");", +@"foreach (int i in myints) + if (i == 6) + Console.WriteLine (""Yeah""); + else + Console.WriteLine (""Bad indent"");"); + } + + /// + /// Bug 415469 - return ternary in a switch is not tabbed properly + /// + [Test()] + [Ignore("currently failing because of 'string' has the wrong offset - mcs bug")] + public void TestBug415469 () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + TestStatementFormatting (policy, +@"switch (condition) { +case CONDITION1: +return foo != null ? foo.Bar : null; +case CONDITION2: +string goo = foo != null ? foo.Bar : null; +return ""Should be indented like this""; +}", @"switch (condition) { +case CONDITION1: + return foo != null ? foo.Bar : null; +case CONDITION2: + string goo = foo != null ? foo.Bar : null; + return ""Should be indented like this""; +}"); + } + + /// + /// Bug 540043 - Format option for alignment of using-statements + /// + [Test()] + public void TestBug540043 () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + TestStatementFormatting (policy, +@"using (IDisposable a = null) + using (IDisposable b = null) { + int c; + } +", @"using (IDisposable a = null) +using (IDisposable b = null) { + int c; +}"); + } + + + + + + static void TestStatementFormatting (CSharpFormattingPolicy policy, string input, string expectedOutput) + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"class Test +{ + MyType TestMethod () + { + " + input + @" + } +}"; + + Console.WriteLine (data.Document.Text); + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + DomSpacingVisitor domSpacingVisitor = new DomSpacingVisitor (policy, data); + domSpacingVisitor.AutoAcceptChanges = false; + compilationUnit.AcceptVisitor (domSpacingVisitor, null); + + DomIndentationVisitor domIndentationVisitor = new DomIndentationVisitor (policy, data); + domIndentationVisitor.AutoAcceptChanges = false; + compilationUnit.AcceptVisitor (domIndentationVisitor, null); + + List changes = new List (); + changes.AddRange (domSpacingVisitor.Changes); + changes.AddRange (domIndentationVisitor.Changes); + RefactoringService.AcceptChanges (null, null, changes); + + for (int i = 0; i < data.Document.LineCount; i++) { + LineSegment line = data.Document.GetLine (i); + if (line.EditableLength < 2) + continue; + data.Remove (line.Offset, 2); + } + string text = data.Document.GetTextBetween (data.Document.GetLine (4).Offset, + data.Document.GetLine (data.Document.LineCount - 2).Offset).Trim (); + Console.WriteLine (text); + Assert.AreEqual (expectedOutput, text); + } + + + } +} +*/ diff --git a/ICSharpCode.NRefactory.Tests/FormattingTests/TestSpacingVisitor.cs b/ICSharpCode.NRefactory.Tests/FormattingTests/TestSpacingVisitor.cs new file mode 100644 index 000000000..9a2cdc821 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/FormattingTests/TestSpacingVisitor.cs @@ -0,0 +1,1167 @@ +// +// TestFormattingVisitor.cs +// +// Author: +// Mike Krüger +// +// Copyright (c) 2010 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +/* +using System; +using NUnit.Framework; +using MonoDevelop.Ide.Gui; +using MonoDevelop.Projects; +using MonoDevelop.Core; +using MonoDevelop.Ide.CodeCompletion; +using MonoDevelop.Ide.Gui.Content; +using MonoDevelop.Projects.Dom.Parser; +using MonoDevelop.CSharp.Parser; +using MonoDevelop.CSharp.Resolver; +using MonoDevelop.CSharp.Completion; +using Mono.TextEditor; +using MonoDevelop.CSharp.Formatting; + +namespace MonoDevelop.CSharpBinding.FormattingTests +{ + [TestFixture()] + public class TestSpacingVisitor : UnitTests.TestBase + { + [Test()] + public void TestFieldSpacesBeforeComma1 () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + int a , b, c; +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.ClassBraceStyle = BraceStyle.EndOfLine; + policy.SpacesAfterComma = false; + policy.SpacesBeforeComma = false; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + int a,b,c; +}", data.Document.Text); + } + + [Test()] + public void TestFieldSpacesBeforeComma2 () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + int a , b, c; +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.ClassBraceStyle = BraceStyle.EndOfLine; + policy.SpacesAfterComma = true; + policy.SpacesBeforeComma = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + int a , b , c; +}", data.Document.Text); + } + + [Test()] + public void TestFixedFieldSpacesBeforeComma () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + fixed int a[10] , b[10], c[10]; +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.ClassBraceStyle = BraceStyle.EndOfLine; + policy.SpacesAfterComma = true; + policy.SpacesBeforeComma = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + fixed int a[10] , b[10] , c[10]; +}", data.Document.Text); + } + + [Test()] + public void TestConstFieldSpacesBeforeComma () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + const int a = 1 , b = 2, c = 3; +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.ClassBraceStyle = BraceStyle.EndOfLine; + policy.SpacesAfterComma = false; + policy.SpacesBeforeComma = false; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + const int a = 1,b = 2,c = 3; +}", data.Document.Text); + } + + [Test()] + public void TestBeforeDelegateDeclarationParentheses () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = "delegate void TestDelegate();"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.BeforeDelegateDeclarationParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + Assert.AreEqual (@"delegate void TestDelegate ();", data.Document.Text); + } + + [Test()] + public void TestBeforeDelegateDeclarationParenthesesComplex () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = "delegate void TestDelegate\n\t\t\t();"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.BeforeDelegateDeclarationParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + Assert.AreEqual (@"delegate void TestDelegate ();", data.Document.Text); + } + + [Test()] + public void TestBeforeMethodDeclarationParentheses () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"public abstract class Test +{ + public abstract Test TestMethod(); +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.BeforeMethodDeclarationParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"public abstract class Test +{ + public abstract Test TestMethod (); +}", data.Document.Text); + } + + [Test()] + public void TestBeforeConstructorDeclarationParentheses () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test() + { + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.BeforeConstructorDeclarationParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test () + { + } +}", data.Document.Text); + } + + + + [Test()] + public void TestBeforeConstructorDeclarationParenthesesDestructorCase () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + ~Test() + { + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.BeforeConstructorDeclarationParentheses = true; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + ~Test () + { + } +}", data.Document.Text); + } + + + + static void TestBinaryOperator (CSharpFormattingPolicy policy, string op) + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = "class Test { void TestMe () { result = left" +op+"right; } }"; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("left"); + int i2 = data.Document.Text.IndexOf ("right") + "right".Length; + if (i1 < 0 || i2 < 0) + Assert.Fail ("text invalid:" + data.Document.Text); + Assert.AreEqual ("left " + op + " right", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestSpacesAroundMultiplicativeOperator () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.AroundMultiplicativeOperatorParentheses = true; + + TestBinaryOperator (policy, "*"); + TestBinaryOperator (policy, "/"); + } + + [Test()] + public void TestSpacesAroundShiftOperator () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.AroundShiftOperatorParentheses = true; + TestBinaryOperator (policy, "<<"); + TestBinaryOperator (policy, ">>"); + } + + [Test()] + public void TestSpacesAroundAdditiveOperator () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.AroundAdditiveOperatorParentheses = true; + + TestBinaryOperator (policy, "+"); + TestBinaryOperator (policy, "-"); + } + + [Test()] + public void TestSpacesAroundBitwiseOperator () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.AroundBitwiseOperatorParentheses = true; + + TestBinaryOperator (policy, "&"); + TestBinaryOperator (policy, "|"); + TestBinaryOperator (policy, "^"); + } + + [Test()] + public void TestSpacesAroundRelationalOperator () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.AroundRelationalOperatorParentheses = true; + + TestBinaryOperator (policy, "<"); + TestBinaryOperator (policy, "<="); + TestBinaryOperator (policy, ">"); + TestBinaryOperator (policy, ">="); + } + + [Test()] + public void TestSpacesAroundEqualityOperator () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.AroundEqualityOperatorParentheses = true; + + TestBinaryOperator (policy, "=="); + TestBinaryOperator (policy, "!="); + } + + [Test()] + public void TestSpacesAroundLogicalOperator () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.AroundLogicalOperatorParentheses = true; + + TestBinaryOperator (policy, "&&"); + TestBinaryOperator (policy, "||"); + } + + [Test()] + public void TestConditionalOperator () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + result = condition?trueexpr:falseexpr; + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.ConditionalOperatorAfterConditionSpace = true; + policy.ConditionalOperatorAfterSeparatorSpace = true; + policy.ConditionalOperatorBeforeConditionSpace = true; + policy.ConditionalOperatorBeforeSeparatorSpace = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + + int i1 = data.Document.Text.IndexOf ("condition"); + int i2 = data.Document.Text.IndexOf ("falseexpr") + "falseexpr".Length; + Assert.AreEqual (@"condition ? trueexpr : falseexpr", data.Document.GetTextBetween (i1, i2)); + + + data.Document.Text = @"class Test { + void TestMe () + { + result = true ? trueexpr : falseexpr; + } +}"; + policy.ConditionalOperatorAfterConditionSpace = false; + policy.ConditionalOperatorAfterSeparatorSpace = false; + policy.ConditionalOperatorBeforeConditionSpace = false; + policy.ConditionalOperatorBeforeSeparatorSpace = false; + + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + i1 = data.Document.Text.IndexOf ("true"); + i2 = data.Document.Text.IndexOf ("falseexpr") + "falseexpr".Length; + Assert.AreEqual (@"true?trueexpr:falseexpr", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestBeforeMethodCallParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + MethodCall(); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.BeforeMethodCallParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("MethodCall"); + int i2 = data.Document.Text.IndexOf (";") + ";".Length; + Assert.AreEqual (@"MethodCall ();", data.Document.GetTextBetween (i1, i2)); + + + data.Document.Text = @"class Test { + void TestMe () + { + MethodCall (); + } +}"; + policy.BeforeMethodCallParentheses = false; + + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + i1 = data.Document.Text.IndexOf ("MethodCall"); + i2 = data.Document.Text.IndexOf (";") + ";".Length; + Assert.AreEqual (@"MethodCall();", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinMethodCallParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + MethodCall(true); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinMethodCallParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( true )", data.Document.GetTextBetween (i1, i2)); + + + data.Document.Text = @"class Test { + void TestMe () + { + MethodCall( true ); + } +}"; + policy.WithinMethodCallParentheses = false; + + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + i1 = data.Document.Text.LastIndexOf ("("); + i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"(true)", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestBeforeIfParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + if(true); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.IfParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("if"); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"if (true)", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinIfParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + if (true); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinIfParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( true )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestBeforeWhileParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + while(true); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WhileParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("while"); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"while (true)", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinWhileParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + while (true); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinWhileParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( true )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestBeforeForParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + for(;;); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.ForParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("for"); + int i2 = data.Document.Text.LastIndexOf ("(") + "(".Length; + Assert.AreEqual (@"for (", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinForParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + for(;;); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinForParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( ;; )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestBeforeForeachParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + foreach(var o in list); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.ForeachParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("foreach"); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"foreach (var o in list)", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinForeachParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + foreach(var o in list); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinForEachParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( var o in list )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestBeforeCatchParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + try {} catch(Exception) {} + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.CatchParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("catch"); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"catch (Exception)", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinCatchParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + try {} catch(Exception) {} + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinCatchParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( Exception )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestBeforeLockParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + lock(this) {} + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.LockParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("lock"); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"lock (this)", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinLockParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + lock(this) {} + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinLockParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( this )", data.Document.GetTextBetween (i1, i2)); + } + + + [Test()] + public void TestSpacesAfterSemicolon () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + for (int i;true;i++) ; + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.SpacesAfterSemicolon = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("for"); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + + Assert.AreEqual (@"for (int i; true; i++)", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestSpacesAfterTypecast () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMe () + { +return (Test)null; + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.SpacesAfterTypecast = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("return"); + int i2 = data.Document.Text.LastIndexOf ("null") + "null".Length; + + Assert.AreEqual (@"return (Test) null", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestBeforeUsingParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + using(a) {} + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.UsingParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("using"); + int i2 = data.Document.Text.LastIndexOf ("(") + "(".Length; + Assert.AreEqual (@"using (", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinUsingParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + using(a) {} + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinUsingParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( a )", data.Document.GetTextBetween (i1, i2)); + } + + static void TestAssignmentOperator (CSharpFormattingPolicy policy, string op) + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = "class Test { void TestMe () { left" +op+"right; } }"; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("left"); + int i2 = data.Document.Text.IndexOf ("right") + "right".Length; + if (i1 < 0 || i2 < 0) + Assert.Fail ("text invalid:" + data.Document.Text); + Assert.AreEqual ("left " + op + " right", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestAroundAssignmentSpace () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.AroundAssignmentParentheses = true; + + TestAssignmentOperator (policy, "="); + TestAssignmentOperator (policy, "*="); + TestAssignmentOperator (policy, "/="); + TestAssignmentOperator (policy, "+="); + TestAssignmentOperator (policy, "%="); + TestAssignmentOperator (policy, "-="); + TestAssignmentOperator (policy, "<<="); + TestAssignmentOperator (policy, ">>="); + TestAssignmentOperator (policy, "&="); + TestAssignmentOperator (policy, "|="); + TestAssignmentOperator (policy, "^="); + } + + [Test()] + public void TestAroundAssignmentSpaceInDeclarations () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + int left=right; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.AroundAssignmentParentheses = true; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("left"); + int i2 = data.Document.Text.LastIndexOf ("right") + "right".Length; + Assert.AreEqual (@"left = right", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestBeforeSwitchParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + switch (test) { default: break; } + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.SwitchParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("switch"); + int i2 = data.Document.Text.LastIndexOf ("(") + "(".Length; + Assert.AreEqual (@"switch (", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinSwitchParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + switch (test) { default: break; } + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinSwitchParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( test )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + c = (test); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( test )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinMethodDeclarationParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe (int a) + { + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinMethodDeclarationParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( int a )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinCastParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + a = (int)b; + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinCastParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( int )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinSizeOfParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + a = sizeof(int); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinSizeOfParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( int )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinTypeOfParenthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + a = typeof(int); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinTypeOfParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( int )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestWithinCheckedExpressionParanthesesSpace () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + a = checked(a + b); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinCheckedExpressionParantheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("("); + int i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( a + b )", data.Document.GetTextBetween (i1, i2)); + + data.Document.Text = @"class Test { + void TestMe () + { + a = unchecked(a + b); + } +}"; + + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + i1 = data.Document.Text.LastIndexOf ("("); + i2 = data.Document.Text.LastIndexOf (")") + ")".Length; + Assert.AreEqual (@"( a + b )", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestSpacesWithinBrackets () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test this[int i] { + get {} + set {} + } + + void TestMe () + { + this[0] = 5; + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.SpacesWithinBrackets = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + + Assert.AreEqual (@"class Test { + Test this[ int i ] { + get {} + set {} + } + + void TestMe () + { + this[ 0 ] = 5; + } +}", data.Document.Text); + + policy.SpacesWithinBrackets = false; + + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + + Assert.AreEqual (@"class Test { + Test this[int i] { + get {} + set {} + } + + void TestMe () + { + this[0] = 5; + } +}", data.Document.Text); + } + + + [Test()] + public void TestSpaceBeforeNewParentheses () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + new Test(); + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.NewParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("new"); + int i2 = data.Document.Text.LastIndexOf (";") + ";".Length; + Assert.AreEqual (@"new Test ();", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestSpacesBeforeComma () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + int[] i = new int[] { 1,3,3,7 }; + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.SpacesBeforeComma = true; + policy.SpacesAfterComma = false; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("new"); + int i2 = data.Document.Text.LastIndexOf (";") + ";".Length; + Assert.AreEqual (@"new int[] { 1 ,3 ,3 ,7 };", data.Document.GetTextBetween (i1, i2)); + policy.SpacesBeforeComma = false; + + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + i1 = data.Document.Text.LastIndexOf ("new"); + i2 = data.Document.Text.LastIndexOf (";") + ";".Length; + Assert.AreEqual (@"new int[] { 1,3,3,7 };", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestSpacesAfterComma () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + int[] i = new int[] { 1,3,3,7 }; + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.SpacesBeforeComma = false; + policy.SpacesAfterComma = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.LastIndexOf ("new"); + int i2 = data.Document.Text.LastIndexOf (";") + ";".Length; + Assert.AreEqual (@"new int[] { 1, 3, 3, 7 };", data.Document.GetTextBetween (i1, i2)); + policy.SpacesAfterComma = false; + + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + i1 = data.Document.Text.LastIndexOf ("new"); + i2 = data.Document.Text.LastIndexOf (";") + ";".Length; + Assert.AreEqual (@"new int[] { 1,3,3,7 };", data.Document.GetTextBetween (i1, i2)); + } + + [Test()] + public void TestSpacesInLambdaExpression () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + void TestMe () + { + var v = x=>x!=null; + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.WithinWhileParentheses = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomSpacingVisitor (policy, data), null); + int i1 = data.Document.Text.IndexOf ("x"); + int i2 = data.Document.Text.LastIndexOf ("null") + "null".Length; + Assert.AreEqual (@"x => x != null", data.Document.GetTextBetween (i1, i2)); + } + + } +} + */ \ No newline at end of file diff --git a/ICSharpCode.NRefactory.Tests/FormattingTests/TestStatementIndentation.cs b/ICSharpCode.NRefactory.Tests/FormattingTests/TestStatementIndentation.cs new file mode 100644 index 000000000..6d483a6c7 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/FormattingTests/TestStatementIndentation.cs @@ -0,0 +1,1749 @@ +// +// TestStatementIndentation.cs +// +// Author: +// Mike Krüger +// +// Copyright (c) 2010 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +/* +using System; +using NUnit.Framework; +using MonoDevelop.Ide.Gui; +using MonoDevelop.Projects; +using MonoDevelop.Core; +using MonoDevelop.Ide.CodeCompletion; +using MonoDevelop.Ide.Gui.Content; +using MonoDevelop.Projects.Dom.Parser; +using MonoDevelop.CSharp.Parser; +using MonoDevelop.CSharp.Resolver; +using MonoDevelop.CSharp.Completion; +using Mono.TextEditor; +using MonoDevelop.CSharp.Formatting; + +namespace MonoDevelop.CSharpBinding.FormattingTests +{ + [TestFixture()] + public class TestStatementIndentation : UnitTests.TestBase + { + [Test()] + public void TestInvocationIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +this.TestMethod (); + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + this.TestMethod (); + } +}", data.Document.Text); + } + + [Test()] + public void TestIndentBlocks () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +{ +{} +} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.IndentBlocks = true; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + { + {} + } + } +}", data.Document.Text); + policy.IndentBlocks = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + { + {} + } + } +}", data.Document.Text); + policy.IndentBlocks = false; + } + + [Test()] + public void TestBreakIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { + break; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + break; + } +}", data.Document.Text); + } + + [Test()] + public void TestCheckedIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +checked { +} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + checked { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestBaseIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { + base.FooBar(); + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + base.FooBar(); + } +}", data.Document.Text); + } + + [Test()] + public void TestUncheckedIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +unchecked { +} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + unchecked { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestContinueIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +continue; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + continue; + } +}", data.Document.Text); + } + + [Test()] + public void TestEmptyStatementIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + ; + } +}", data.Document.Text); + } + + [Test()] + public void TestFixedStatementIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +fixed (object* obj = &obj) +; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + fixed (object* obj = &obj) + ; + } +}", data.Document.Text); + } + + [Test()] + public void TestFixedForcementAdd () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + fixed (object* obj = &obj) { + } + fixed (object* obj = &obj) ; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + policy.FixedBraceForcement = BraceForcement.AddBraces; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + fixed (object* obj = &obj) { + } + fixed (object* obj = &obj) { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestForeachIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { +foreach (var obj in col) { +} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + foreach (var obj in col) { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestForIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +for (;;) { +} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + for (;;) { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestGotoIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +goto label; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + goto label; + } +}", data.Document.Text); + } + + [Test()] + public void TestReturnIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +return; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + return; + } +}", data.Document.Text); + } + + [Test()] + public void TestLockIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +lock (this) { +} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + lock (this) { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestThrowIndentation () + { + + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +throw new NotSupportedException (); + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + throw new NotSupportedException (); + } +}", data.Document.Text); + } + + [Test()] + public void TestUnsafeIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +unsafe { +} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + unsafe { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestUsingIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +using (var o = new MyObj()) { +} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + using (var o = new MyObj()) { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestUsingForcementAdd () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + using (var o = new MyObj()) { + } + using (var o = new MyObj()) ; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + policy.UsingBraceForcement = BraceForcement.AddBraces; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + using (var o = new MyObj()) { + } + using (var o = new MyObj()) { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestUsingForcementDoNotChange () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + using (var o = new MyObj()) { + } + using (var o = new MyObj()) ; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + policy.UsingBraceForcement = BraceForcement.DoNotChange; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + using (var o = new MyObj()) { + } + using (var o = new MyObj()) + ; + } +}", data.Document.Text); + } + + + [Test()] + public void TestVariableDeclarationIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +Test a; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + Console.WriteLine (data.Document.Text); + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + Test a; + } +}", data.Document.Text); + } + + + [Test()] + public void TestYieldIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +yield return null; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + yield return null; + } +}", data.Document.Text); + } + + [Test()] + public void TestWhileIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +while (true) +; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + while (true) + ; + } +}", data.Document.Text); + } + + [Test()] + public void TestDoWhileIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test { + Test TestMethod () + { +do { +} while (true); + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.ClassBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test { + Test TestMethod () + { + do { + } while (true); + } +}", data.Document.Text); + } + + + [Test()] + public void TestForeachBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + foreach (var obj in col) {} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + foreach (var obj in col) { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestForeachBracketPlacement2 () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + foreach (var obj in col) {;} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.NextLineShifted2; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + foreach (var obj in col) + { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestForEachBraceForcementAdd () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + foreach (var obj in col) + { + } + foreach (var obj in col) ; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.NextLine; + policy.ForEachBraceForcement = BraceForcement.AddBraces; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + foreach (var obj in col) + { + } + foreach (var obj in col) + { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestForBraceForcementAdd () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + for (;;) + { + } + for (;;) ; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.NextLine; + policy.ForBraceForcement = BraceForcement.AddBraces; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + for (;;) + { + } + for (;;) + { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestForEachBraceForcementRemove () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + foreach (var obj in col) + { + ; + ; + } + foreach (var obj in col) + { + ; + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.NextLine; + policy.ForEachBraceForcement = BraceForcement.RemoveBraces; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + foreach (var obj in col) + { + ; + ; + } + foreach (var obj in col) + ; + } +}", data.Document.Text); + } + + + [Test()] + public void TestIfBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + if (true) {} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + if (true) { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestAllowIfBlockInline () + { + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.StatementBraceStyle = BraceStyle.EndOfLine; + policy.AllowIfBlockInline = true; + + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + if (true) {} + } +}"; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + if (true) {} + } +}", data.Document.Text); + + + data.Document.Text = @"class Test +{ + Test TestMethod () + { + if (true) { Foo (); } + } +}"; + + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + if (true) { Foo (); } + } +}", data.Document.Text); + + + data.Document.Text = @"class Test +{ + Test TestMethod () + { + if (true) Foo (); + } +}"; + + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + if (true) Foo (); + } +}", data.Document.Text); + + + data.Document.Text = @"class Test +{ + Test TestMethod () + { + if (true) + Foo (); + } +}"; + + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + if (true) + Foo (); + } +}", data.Document.Text); + + + } + + [Test()] + public void TestIfElseBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + if (true) {} else {} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + if (true) { + } else { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestIfForcementRemove () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + if (true) + { + ; + ; + } + if (true) + { + ; + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.NextLine; + policy.IfElseBraceForcement = BraceForcement.RemoveBraces; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + if (true) + { + ; + ; + } + if (true) + ; + } +}", data.Document.Text); + } + + [Test()] + public void TestElseOnNewLine () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + if (true) { + ; + } else if (false) { + ; + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.PlaceElseOnNewLine = true; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + if (true) { + ; + } + else if (false) { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestElseIfOnNewLine () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + if (true) { + ; + } else if (false) { + ; + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.PlaceElseIfOnNewLine = true; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + if (true) { + ; + } else + if (false) { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestElseOnNewLineOff () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + if (true) { + ; + } + else if (false) { + ; + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.PlaceElseOnNewLine = false; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + if (true) { + ; + } else if (false) { + ; + } + } +}", data.Document.Text); + } + + + [Test()] + public void TestWhileForcementRemove () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + while (true) + { + ; + ; + } + while (true) + { + ; + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.NextLine; + policy.WhileBraceForcement = BraceForcement.RemoveBraces; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + while (true) + { + ; + ; + } + while (true) + ; + } +}", data.Document.Text); + } + + [Test()] + public void TestFixedBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + fixed (object* obj = &obj) + +; + } +}"; + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.NextLineShifted; + policy.FixedBraceForcement = BraceForcement.AddBraces; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + fixed (object* obj = &obj) + { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestForBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + for (;;) {;} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLineWithoutSpace; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + for (;;){ + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestCheckedBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + checked {;} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLineWithoutSpace; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + checked{ + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestUncheckedBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + unchecked {;} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLineWithoutSpace; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + unchecked{ + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestLockBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + lock (this) + { + ; + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + lock (this) { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestUnsafeBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + unsafe + { + ; + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + unsafe { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestUsingBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + using (var e = new E()) + { + ; + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + using (var e = new E()) { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestWhileBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + while (true) + { + ; + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + while (true) { + ; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestDoWhileBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + do + { + ; + } while (true); + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + do { + ; + } while (true); + } +}", data.Document.Text); + } + + [Test()] + public void TestSwitchFormatting1 () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + switch (a) { case 1: case 2: DoSomething(); break; default: Foo (); break;} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.IndentSwitchBody = true; + policy.IndentCaseBody = true; + policy.IndentBreakStatements = true; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + switch (a) { + case 1: + case 2: + DoSomething(); + break; + default: + Foo (); + break; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestSwitchFormatting2 () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + switch (a) { case 1: case 2: DoSomething(); break; default: Foo (); break;} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.IndentSwitchBody = false; + policy.IndentCaseBody = false; + policy.IndentBreakStatements = false; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + switch (a) { + case 1: + case 2: + DoSomething(); + break; + default: + Foo (); + break; + } + } +}", data.Document.Text); + } + + [Test()] + public void TestTryCatchBracketPlacement () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + try { ; } catch (Exception e) { } finally { } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.StatementBraceStyle = BraceStyle.EndOfLine; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + try { + ; + } catch (Exception e) { + } finally { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestPlaceCatchOnNewLine () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + try { + ; + } catch (Exception e) { + } finally { + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.PlaceCatchOnNewLine = true; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + try { + ; + } + catch (Exception e) { + } finally { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestPlaceFinallyOnNewLine () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + try { + ; + } catch (Exception e) { + } finally { + } + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.PlaceFinallyOnNewLine = true; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + try { + ; + } catch (Exception e) { + } + finally { + } + } +}", data.Document.Text); + } + + [Test()] + public void TestPlaceWhileOnNewLine () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = @"class Test +{ + Test TestMethod () + { + do { + ; + } while (true); + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + policy.PlaceWhileOnNewLine = true; + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + + Console.WriteLine (data.Document.Text); + Assert.AreEqual (@"class Test +{ + Test TestMethod () + { + do { + ; + } + while (true); + } +}", data.Document.Text); + } + + } +}*/ diff --git a/ICSharpCode.NRefactory.Tests/FormattingTests/TestTypeLevelIndentation.cs b/ICSharpCode.NRefactory.Tests/FormattingTests/TestTypeLevelIndentation.cs new file mode 100644 index 000000000..c41489eb5 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/FormattingTests/TestTypeLevelIndentation.cs @@ -0,0 +1,500 @@ +// +// TestTypeLevelIndentation.cs +// +// Author: +// Mike Krüger +// +// Copyright (c) 2010 Novell, Inc (http://www.novell.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +/* +using System; +using NUnit.Framework; +using MonoDevelop.Ide.Gui; +using MonoDevelop.Projects; +using MonoDevelop.Core; +using MonoDevelop.Ide.CodeCompletion; +using MonoDevelop.Ide.Gui.Content; +using MonoDevelop.Projects.Dom.Parser; +using MonoDevelop.CSharp.Parser; +using MonoDevelop.CSharp.Resolver; +using MonoDevelop.CSharp.Completion; +using Mono.TextEditor; +using MonoDevelop.CSharp.Formatting; + +namespace MonoDevelop.CSharpBinding.FormattingTests +{ + [TestFixture()] + public class TestTypeLevelIndentation : UnitTests.TestBase + { + [Test()] + public void TestClassIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@" class Test {}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.ClassBraceStyle = BraceStyle.DoNotChange; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test {}", data.Document.Text); + } + + [Test()] + public void TestIndentClassBody () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"class Test +{ + Test a; +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.IndentClassBody = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test a; +}", data.Document.Text); + policy.IndentClassBody = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ +Test a; +}", data.Document.Text); + } + + [Test()] + public void TestIndentInterfaceBody () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"interface Test +{ + Test Foo (); +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.IndentInterfaceBody = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"interface Test +{ + Test Foo (); +}", data.Document.Text); + policy.IndentInterfaceBody = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"interface Test +{ +Test Foo (); +}", data.Document.Text); + } + + [Test()] + public void TestIndentStructBody () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"struct Test +{ + Test a; +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.IndentStructBody = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"struct Test +{ + Test a; +}", data.Document.Text); + policy.IndentStructBody = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"struct Test +{ +Test a; +}", data.Document.Text); + } + + [Test()] + public void TestIndentEnumBody () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"enum Test +{ + A +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.IndentEnumBody = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"enum Test +{ + A +}", data.Document.Text); + policy.IndentEnumBody = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"enum Test +{ +A +}", data.Document.Text); + } + + [Test()] + public void TestIndentMethodBody () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"class Test +{ + Test Foo () + { +; + ; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.IndentMethodBody = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test Foo () + { + ; + ; + } +}", data.Document.Text); + policy.IndentMethodBody = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test Foo () + { + ; + ; + } +}", data.Document.Text); + } + + [Test()] + public void TestIndentMethodBodyOperatorCase () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"class Test +{ + static Test operator+(Test left, Test right) + { +; + ; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.IndentMethodBody = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + static Test operator+(Test left, Test right) + { + ; + ; + } +}", data.Document.Text); + policy.IndentMethodBody = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + static Test operator+(Test left, Test right) + { + ; + ; + } +}", data.Document.Text); + } + + [Test()] + public void TestIndentPropertyBody () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"class Test +{ + Test TestMe { + get; +set; + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.IndentPropertyBody = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMe { + get; + set; + } +}", data.Document.Text); + policy.IndentPropertyBody = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test TestMe { + get; + set; + } +}", data.Document.Text); + } + + [Test()] + public void TestIndentPropertyBodyIndexerCase () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"class Test +{ + Test this[int a] { + get { + return null; +} +set { + ; +} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.IndentPropertyBody = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test this[int a] { + get { + return null; + } + set { + ; + } + } +}", data.Document.Text); + policy.IndentPropertyBody = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + Test this[int a] { + get { + return null; + } + set { + ; + } + } +}", data.Document.Text); + } + + + [Test()] + [Ignore("currently failing because namespaces are not inserted")] + public void TestIndentNamespaceBody () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@" namespace Test { +class FooBar {} + }"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.ClassBraceStyle = BraceStyle.DoNotChange; + policy.IndentNamespaceBody = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"namespace Test { + class FooBar {} +}", data.Document.Text); + + policy.IndentNamespaceBody = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"namespace Test { +class FooBar {} +}", data.Document.Text); + } + + [Test()] + public void TestMethodIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"class Test +{ +MyType TestMethod () {} +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.MethodBraceStyle = BraceStyle.DoNotChange; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + MyType TestMethod () {} +}", data.Document.Text); + } + + [Test()] + public void TestPropertyIndentation () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"class Test +{ + public int Prop { get; set; } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.PropertyBraceStyle = BraceStyle.DoNotChange; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + public int Prop { get; set; } +}", data.Document.Text); + } + + [Test()] + public void TestPropertyIndentationCase2 () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"class Test +{ + public int Prop { + get; +set; +} +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + public int Prop { + get; + set; + } +}", data.Document.Text); + } + + + [Test()] + public void TestIndentEventBody () + { + TextEditorData data = new TextEditorData (); + data.Document.FileName = "a.cs"; + data.Document.Text = +@"class Test +{ + public event EventHandler TestMe { + add { + ; + } +remove { + ; +} + } +}"; + + CSharpFormattingPolicy policy = new CSharpFormattingPolicy (); + policy.IndentEventBody = true; + + CSharp.Dom.CompilationUnit compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + public event EventHandler TestMe { + add { + ; + } + remove { + ; + } + } +}", data.Document.Text); + policy.IndentEventBody = false; + compilationUnit = new CSharpParser ().Parse (data); + compilationUnit.AcceptVisitor (new DomIndentationVisitor (policy, data), null); + Assert.AreEqual (@"class Test +{ + public event EventHandler TestMe { + add { + ; + } + remove { + ; + } + } +}", data.Document.Text); + } + } +}*/ diff --git a/ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj b/ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj new file mode 100644 index 000000000..b4c71a86f --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj @@ -0,0 +1,169 @@ + + + + {63D3B27A-D966-4902-90B3-30290E1692F1} + Debug + AnyCPU + Library + ICSharpCode.NRefactory + ICSharpCode.NRefactory.Tests + v4.0 + Properties + 10.0.0 + 2.0 + + + x86 + + + bin\Debug\ + True + Full + False + True + DEBUG;TRACE + + + bin\Release\ + False + None + True + False + TRACE + + + true + full + false + 4 + true + true + + + none + true + 4 + true + + + + + ..\lib\nunit.framework.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {3B2A5653-EC97-4001-BB9B-D90F1AF2C371} + ICSharpCode.NRefactory + + + + + + + + + + \ No newline at end of file diff --git a/ICSharpCode.NRefactory.Tests/Properties/AssemblyInfo.cs b/ICSharpCode.NRefactory.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..4d1c47558 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,29 @@ +#region Using directives + +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +#endregion + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ICSharpCode.NRefactory.Tests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// This sets the default COM visibility of types in the assembly to invisible. +// If you need to expose a type to COM, use [ComVisible(true)] on that type. +[assembly: ComVisible(false)] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all the values or you can use the default the Revision and +// Build Numbers by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.*")] diff --git a/ICSharpCode.NRefactory.Tests/TypeSystem/CecilLoaderTests.cs b/ICSharpCode.NRefactory.Tests/TypeSystem/CecilLoaderTests.cs new file mode 100644 index 000000000..b380c1cd8 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/TypeSystem/CecilLoaderTests.cs @@ -0,0 +1,246 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using ICSharpCode.NRefactory.TypeSystem.Implementation; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.TypeSystem +{ + [TestFixture] + public class CecilLoaderTests : TypeSystemTests + { + public static readonly IProjectContent Mscorlib = new CecilLoader().LoadAssemblyFile(typeof(object).Assembly.Location); + ITypeResolveContext ctx = Mscorlib; + + [TestFixtureSetUp] + public void FixtureSetUp() + { + // use "IncludeInternalMembers" so that Cecil results match C# parser results + CecilLoader loader = new CecilLoader() { IncludeInternalMembers = true }; + testCasePC = loader.LoadAssemblyFile(typeof(TestCase.SimplePublicClass).Assembly.Location); + } + + [Test] + public void InheritanceTest() + { + ITypeDefinition c = Mscorlib.GetClass(typeof(SystemException)); + ITypeDefinition c2 = Mscorlib.GetClass(typeof(Exception)); + Assert.IsNotNull(c, "c is null"); + Assert.IsNotNull(c2, "c2 is null"); + //Assert.AreEqual(3, c.BaseTypes.Count); // Inherited interfaces are not reported by Cecil + // which matches the behaviour of our C#/VB parsers + Assert.AreEqual("System.Exception", c.BaseTypes[0].Resolve(ctx).FullName); + Assert.AreSame(c2, c.BaseTypes[0]); + + string[] superTypes = c.GetAllBaseTypes(ctx).Select(t => t.ToString()).ToArray(); + Assert.AreEqual(new string[] { + "System.SystemException", "System.Exception", "System.Object", + "System.Runtime.Serialization.ISerializable", "System.Runtime.InteropServices._Exception" + }, superTypes); + } + + [Test] + public void GenericPropertyTest() + { + ITypeDefinition c = Mscorlib.GetClass(typeof(Comparer<>)); + IProperty def = c.Properties.Single(p => p.Name == "Default"); + ParameterizedType pt = (ParameterizedType)def.ReturnType.Resolve(ctx); + Assert.AreEqual("System.Collections.Generic.Comparer", pt.FullName); + Assert.AreSame(c.TypeParameters[0], pt.TypeArguments[0]); + } + + [Test] + public void PointerTypeTest() + { + ITypeDefinition c = Mscorlib.GetClass(typeof(IntPtr)); + IMethod toPointer = c.Methods.Single(p => p.Name == "ToPointer"); + Assert.AreEqual("System.Void*", toPointer.ReturnType.Resolve(ctx).ReflectionName); + Assert.IsTrue (toPointer.ReturnType.Resolve(ctx) is PointerType); + Assert.AreEqual("System.Void", ((PointerType)toPointer.ReturnType.Resolve(ctx)).ElementType.FullName); + } + + [Test] + public void DateTimeDefaultConstructor() + { + ITypeDefinition c = Mscorlib.GetClass(typeof(DateTime)); + Assert.IsFalse(c.Methods.Any(m => m.IsConstructor && m.Parameters.Count == 0)); // struct ctor isn't declared + // but it is implicit: + Assert.IsTrue(c.GetConstructors(ctx).Any(m => m.Parameters.Count == 0)); + } + + [Test] + public void NoEncodingInfoDefaultConstructor() + { + ITypeDefinition c = Mscorlib.GetClass(typeof(EncodingInfo)); + // EncodingInfo only has an internal constructor + Assert.IsFalse(c.Methods.Any(m => m.IsConstructor)); + // and no implicit ctor should be added: + Assert.AreEqual(0, c.GetConstructors(ctx).Count()); + } + + [Test] + public void StaticModifierTest() + { + ITypeDefinition c = Mscorlib.GetClass(typeof(Environment)); + Assert.IsNotNull(c, "System.Environment not found"); + Assert.IsTrue(c.IsAbstract, "class should be abstract"); + Assert.IsTrue(c.IsSealed, "class should be sealed"); + Assert.IsTrue(c.IsStatic, "class should be static"); + } + + [Test] + public void InnerClassReferenceTest() + { + ITypeDefinition c = Mscorlib.GetClass(typeof(Environment)); + Assert.IsNotNull(c, "System.Environment not found"); + ITypeReference rt = c.Methods.First(m => m.Name == "GetFolderPath").Parameters[0].Type; + Assert.AreSame(c.InnerClasses.Single(ic => ic.Name == "SpecialFolder"), rt.Resolve(ctx)); + } + + [Test] + public void InnerClassesTest() + { + ITypeDefinition c = Mscorlib.GetClass(typeof(Environment.SpecialFolder)); + Assert.IsNotNull(c, "c is null"); + Assert.AreEqual("System.Environment.SpecialFolder", c.FullName); + Assert.AreEqual("System.Environment+SpecialFolder", c.ReflectionName); + } + + [Test] + public void VoidTest() + { + ITypeDefinition c = Mscorlib.GetClass(typeof(void)); + Assert.IsNotNull(c, "System.Void not found"); + Assert.AreEqual(0, c.GetMethods(ctx).Count()); + Assert.AreEqual(0, c.GetProperties(ctx).Count()); + Assert.AreEqual(0, c.GetEvents(ctx).Count()); + Assert.AreEqual(0, c.GetFields(ctx).Count()); + Assert.AreEqual( + new string[] { + "[System.SerializableAttribute]", + "[System.Runtime.InteropServices.StructLayoutAttribute(0, Size=1)]", + "[System.Runtime.InteropServices.ComVisibleAttribute(true)]" + }, + c.Attributes.Select(a => a.ToString()).ToArray()); + } + + [Test] + public void NestedClassInGenericClassTest() + { + ITypeDefinition dictionary = Mscorlib.GetClass(typeof(Dictionary<,>)); + Assert.IsNotNull(dictionary); + ITypeDefinition valueCollection = Mscorlib.GetClass(typeof(Dictionary<,>.ValueCollection)); + Assert.IsNotNull(valueCollection); + var dictionaryRT = new ParameterizedType(dictionary, new[] { Mscorlib.GetClass(typeof(string)), Mscorlib.GetClass(typeof(int)) }); + IProperty valueProperty = dictionaryRT.GetProperties(ctx).Single(p => p.Name == "Values"); + IType parameterizedValueCollection = valueProperty.ReturnType.Resolve(ctx); + Assert.AreEqual("System.Collections.Generic.Dictionary`2+ValueCollection[[System.String],[System.Int32]]", parameterizedValueCollection.ReflectionName); + Assert.AreSame(valueCollection, parameterizedValueCollection.GetDefinition()); + } + + [Test] + public void ValueCollectionCountModifiers() + { + ITypeDefinition valueCollection = Mscorlib.GetClass(typeof(Dictionary<,>.ValueCollection)); + Assert.AreEqual(Accessibility.Public, valueCollection.Accessibility); + Assert.IsTrue(valueCollection.IsSealed); + Assert.IsFalse(valueCollection.IsAbstract); + Assert.IsFalse(valueCollection.IsStatic); + + IProperty count = valueCollection.Properties.Single(p => p.Name == "Count"); + Assert.AreEqual(Accessibility.Public, count.Accessibility); + Assert.IsTrue(count.IsSealed); + Assert.IsFalse(count.IsVirtual); + Assert.IsFalse(count.IsAbstract); + } + + [Test] + public void MathAcosModifiers() + { + ITypeDefinition math = Mscorlib.GetClass(typeof(Math)); + Assert.AreEqual(Accessibility.Public, math.Accessibility); + Assert.IsTrue(math.IsSealed); + Assert.IsTrue(math.IsAbstract); + Assert.IsTrue(math.IsStatic); + + IMethod acos = math.Methods.Single(p => p.Name == "Acos"); + Assert.AreEqual(Accessibility.Public, acos.Accessibility); + Assert.IsTrue(acos.IsStatic); + Assert.IsFalse(acos.IsAbstract); + Assert.IsFalse(acos.IsSealed); + Assert.IsFalse(acos.IsVirtual); + Assert.IsFalse(acos.IsOverride); + } + + [Test] + public void EncodingModifiers() + { + ITypeDefinition encoding = Mscorlib.GetClass(typeof(Encoding)); + Assert.AreEqual(Accessibility.Public, encoding.Accessibility); + Assert.IsFalse(encoding.IsSealed); + Assert.IsTrue(encoding.IsAbstract); + + IMethod getDecoder = encoding.Methods.Single(p => p.Name == "GetDecoder"); + Assert.AreEqual(Accessibility.Public, getDecoder.Accessibility); + Assert.IsFalse(getDecoder.IsStatic); + Assert.IsFalse(getDecoder.IsAbstract); + Assert.IsFalse(getDecoder.IsSealed); + Assert.IsTrue(getDecoder.IsVirtual); + Assert.IsFalse(getDecoder.IsOverride); + + IMethod getMaxByteCount = encoding.Methods.Single(p => p.Name == "GetMaxByteCount"); + Assert.AreEqual(Accessibility.Public, getMaxByteCount.Accessibility); + Assert.IsFalse(getMaxByteCount.IsStatic); + Assert.IsTrue(getMaxByteCount.IsAbstract); + Assert.IsFalse(getMaxByteCount.IsSealed); + Assert.IsFalse(getMaxByteCount.IsVirtual); + Assert.IsFalse(getMaxByteCount.IsOverride); + + IProperty encoderFallback = encoding.Properties.Single(p => p.Name == "EncoderFallback"); + Assert.AreEqual(Accessibility.Public, encoderFallback.Accessibility); + Assert.IsFalse(encoderFallback.IsStatic); + Assert.IsFalse(encoderFallback.IsAbstract); + Assert.IsFalse(encoderFallback.IsSealed); + Assert.IsFalse(encoderFallback.IsVirtual); + Assert.IsFalse(encoderFallback.IsOverride); + } + + [Test] + public void UnicodeEncodingModifiers() + { + ITypeDefinition encoding = Mscorlib.GetClass(typeof(UnicodeEncoding)); + Assert.AreEqual(Accessibility.Public, encoding.Accessibility); + Assert.IsFalse(encoding.IsSealed); + Assert.IsFalse(encoding.IsAbstract); + + IMethod getDecoder = encoding.Methods.Single(p => p.Name == "GetDecoder"); + Assert.AreEqual(Accessibility.Public, getDecoder.Accessibility); + Assert.IsFalse(getDecoder.IsStatic); + Assert.IsFalse(getDecoder.IsAbstract); + Assert.IsFalse(getDecoder.IsSealed); + Assert.IsFalse(getDecoder.IsVirtual); + Assert.IsTrue(getDecoder.IsOverride); + } + + [Test] + public void UTF32EncodingModifiers() + { + ITypeDefinition encoding = Mscorlib.GetClass(typeof(UTF32Encoding)); + Assert.AreEqual(Accessibility.Public, encoding.Accessibility); + Assert.IsTrue(encoding.IsSealed); + Assert.IsFalse(encoding.IsAbstract); + + IMethod getDecoder = encoding.Methods.Single(p => p.Name == "GetDecoder"); + Assert.AreEqual(Accessibility.Public, getDecoder.Accessibility); + Assert.IsFalse(getDecoder.IsStatic); + Assert.IsFalse(getDecoder.IsAbstract); + Assert.IsFalse(getDecoder.IsSealed); + Assert.IsFalse(getDecoder.IsVirtual); + Assert.IsTrue(getDecoder.IsOverride); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/TypeSystem/GetAllBaseTypesTest.cs b/ICSharpCode.NRefactory.Tests/TypeSystem/GetAllBaseTypesTest.cs new file mode 100644 index 000000000..88e9cb8b1 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/TypeSystem/GetAllBaseTypesTest.cs @@ -0,0 +1,128 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using ICSharpCode.NRefactory.TypeSystem.Implementation; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.TypeSystem +{ + [TestFixture] + public class GetAllBaseTypesTest + { + IProjectContent mscorlib = CecilLoaderTests.Mscorlib; + ITypeResolveContext context = CecilLoaderTests.Mscorlib; + + IType[] GetAllBaseTypes(Type type) + { + return type.ToTypeReference().Resolve(context).GetAllBaseTypes(context).OrderBy(t => t.ReflectionName).ToArray(); + } + + IType[] GetTypes(params Type[] types) + { + return types.Select(t => t.ToTypeReference().Resolve(context)).OrderBy(t => t.ReflectionName).ToArray();; + } + + [Test] + public void ObjectBaseTypes() + { + Assert.AreEqual(GetTypes(typeof(object)), GetAllBaseTypes(typeof(object))); + } + + [Test] + public void StringBaseTypes() + { + Assert.AreEqual(GetTypes(typeof(string), typeof(object), typeof(IComparable), typeof(ICloneable), typeof(IConvertible), + typeof(IComparable), typeof(IEquatable), typeof(IEnumerable), typeof(IEnumerable)), + GetAllBaseTypes(typeof(string))); + } + + [Test] + public void ArrayOfString() + { + Assert.AreEqual(GetTypes(typeof(string[]), typeof(Array), typeof(object), + typeof(IList), typeof(ICollection), typeof(IEnumerable), + typeof(IList), typeof(ICollection), typeof(IEnumerable), + typeof(IStructuralEquatable), typeof(IStructuralComparable), typeof(ICloneable)), + GetAllBaseTypes(typeof(string[]))); + } + + [Test] + public void MultidimensionalArrayOfString() + { + Assert.AreEqual(GetTypes(typeof(string[,]), typeof(Array), typeof(object), + typeof(IList), typeof(ICollection), typeof(IEnumerable), + typeof(IStructuralEquatable), typeof(IStructuralComparable), typeof(ICloneable)), + GetAllBaseTypes(typeof(string[,]))); + } + + [Test] + public void ClassDerivingFromItself() + { + // class C : C {} + DefaultTypeDefinition c = new DefaultTypeDefinition(mscorlib, string.Empty, "C"); + c.BaseTypes.Add(c); + Assert.AreEqual(new [] { c }, c.GetAllBaseTypes(context).ToArray()); + } + + [Test] + public void TwoClassesDerivingFromEachOther() + { + // class C1 : C2 {} class C2 : C1 {} + DefaultTypeDefinition c1 = new DefaultTypeDefinition(mscorlib, string.Empty, "C1"); + DefaultTypeDefinition c2 = new DefaultTypeDefinition(mscorlib, string.Empty, "C2"); + c1.BaseTypes.Add(c2); + c2.BaseTypes.Add(c1); + Assert.AreEqual(new [] { c1, c2 }, c1.GetAllBaseTypes(context).ToArray()); + } + + [Test] + public void ClassDerivingFromParameterizedVersionOfItself() + { + // class C : C> {} + DefaultTypeDefinition c = new DefaultTypeDefinition(mscorlib, string.Empty, "C"); + c.TypeParameters.Add(new DefaultTypeParameter(c, 0, "X")); + c.BaseTypes.Add(new ParameterizedType(c, new [] { new ParameterizedType(c, new [] { c.TypeParameters[0] }) })); + Assert.AreEqual(new [] { c }, c.GetAllBaseTypes(context).ToArray()); + } + + [Test] + public void ClassDerivingFromTwoInstanciationsOfIEnumerable() + { + // class C : IEnumerable, IEnumerable {} + DefaultTypeDefinition c = new DefaultTypeDefinition(mscorlib, string.Empty, "C"); + c.BaseTypes.Add(typeof(IEnumerable).ToTypeReference()); + c.BaseTypes.Add(typeof(IEnumerable).ToTypeReference()); + IType[] expected = { + c, + c.BaseTypes[0].Resolve(context), + c.BaseTypes[1].Resolve(context), + mscorlib.GetClass(typeof(IEnumerable)), + mscorlib.GetClass(typeof(object)) + }; + Assert.AreEqual(expected, + c.GetAllBaseTypes(context).OrderBy(t => t.ReflectionName).ToArray()); + } + + [Test] + public void StructImplementingIEquatable() + { + // struct S : IEquatable {} + // don't use a Cecil-loaded struct for this test; we're testing the implicit addition of System.ValueType + DefaultTypeDefinition s = new DefaultTypeDefinition(mscorlib, string.Empty, "S"); + s.ClassType = ClassType.Struct; + s.BaseTypes.Add(new ParameterizedType(mscorlib.GetClass(typeof(IEquatable<>)), new[] { s })); + IType[] expected = { + s, + s.BaseTypes[0].Resolve(context), + mscorlib.GetClass(typeof(object)), + mscorlib.GetClass(typeof(ValueType)) + }; + Assert.AreEqual(expected, + s.GetAllBaseTypes(context).OrderBy(t => t.ReflectionName).ToArray()); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/TypeSystem/GetMembersTests.cs b/ICSharpCode.NRefactory.Tests/TypeSystem/GetMembersTests.cs new file mode 100644 index 000000000..6e0d9dc8b --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/TypeSystem/GetMembersTests.cs @@ -0,0 +1,75 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using ICSharpCode.NRefactory.TypeSystem.Implementation; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.TypeSystem +{ + [TestFixture] + public class GetMembersTests + { + IProjectContent mscorlib = CecilLoaderTests.Mscorlib; + + [Test] + public void EmptyClassHasToString() + { + DefaultTypeDefinition c = new DefaultTypeDefinition(mscorlib, string.Empty, "C"); + Assert.AreEqual("System.Object.ToString", c.GetMethods(mscorlib, m => m.Name == "ToString").Single().FullName); + } + + [Test] + public void MultipleInheritanceTest() + { + DefaultTypeDefinition b1 = new DefaultTypeDefinition(mscorlib, string.Empty, "B1"); + b1.ClassType = ClassType.Interface; + b1.Properties.Add(new DefaultProperty(b1, "P1")); + + DefaultTypeDefinition b2 = new DefaultTypeDefinition(mscorlib, string.Empty, "B1"); + b2.ClassType = ClassType.Interface; + b2.Properties.Add(new DefaultProperty(b1, "P2")); + + DefaultTypeDefinition c = new DefaultTypeDefinition(mscorlib, string.Empty, "C"); + c.ClassType = ClassType.Interface; + c.BaseTypes.Add(b1); + c.BaseTypes.Add(b2); + + Assert.AreEqual(new[] { "P1", "P2" }, c.GetProperties(mscorlib).Select(p => p.Name).ToArray()); + // Test that there's only one copy of ToString(): + Assert.AreEqual(1, c.GetMethods(mscorlib, m => m.Name == "ToString").Count()); + } + + [Test] + public void ArrayType() + { + IType arrayType = typeof(string[]).ToTypeReference().Resolve(mscorlib); + // Array inherits ToString() from System.Object + Assert.AreEqual("System.Object.ToString", arrayType.GetMethods(mscorlib, m => m.Name == "ToString").Single().FullName); + Assert.AreEqual("System.Array.GetLowerBound", arrayType.GetMethods(mscorlib, m => m.Name == "GetLowerBound").Single().FullName); + Assert.AreEqual("System.Array.Length", arrayType.GetProperties(mscorlib, p => p.Name == "Length").Single().FullName); + + // test indexer + IProperty indexer = arrayType.GetProperties(mscorlib, p => p.IsIndexer).Single(); + Assert.AreEqual("System.Array.Items", indexer.FullName); + Assert.AreEqual("System.String", indexer.ReturnType.Resolve(mscorlib).ReflectionName); + Assert.AreEqual(1, indexer.Parameters.Count); + Assert.AreEqual("System.Int32", indexer.Parameters[0].Type.Resolve(mscorlib).ReflectionName); + } + + [Test] + public void MultidimensionalArrayType() + { + IType arrayType = typeof(string[,][]).ToTypeReference().Resolve(mscorlib); + + // test indexer + IProperty indexer = arrayType.GetProperties(mscorlib, p => p.IsIndexer).Single(); + Assert.AreEqual("System.Array.Items", indexer.FullName); + Assert.AreEqual("System.String[]", indexer.ReturnType.Resolve(mscorlib).ReflectionName); + Assert.AreEqual(2, indexer.Parameters.Count); + Assert.AreEqual("System.Int32", indexer.Parameters[0].Type.Resolve(mscorlib).ReflectionName); + Assert.AreEqual("System.Int32", indexer.Parameters[1].Type.Resolve(mscorlib).ReflectionName); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/TypeSystem/ReflectionHelperTests.cs b/ICSharpCode.NRefactory.Tests/TypeSystem/ReflectionHelperTests.cs new file mode 100644 index 000000000..64662a999 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/TypeSystem/ReflectionHelperTests.cs @@ -0,0 +1,279 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.TypeSystem +{ + [TestFixture] + public unsafe class ReflectionHelperTests + { + ITypeResolveContext context = CecilLoaderTests.Mscorlib; + + void TestGetClass(Type type) + { + ITypeDefinition t = CecilLoaderTests.Mscorlib.GetClass(type); + Assert.IsNotNull(t, type.FullName); + Assert.AreEqual(type.FullName, t.ReflectionName); + } + + [Test] + public void TestGetInnerClass() + { + TestGetClass(typeof(Environment.SpecialFolder)); + } + + [Test] + public void TestGetGenericClass1() + { + TestGetClass(typeof(Action<>)); + } + + [Test] + public void TestGetGenericClass2() + { + TestGetClass(typeof(Action<,>)); + } + + [Test] + public void TestGetInnerClassInGenericClass1() + { + TestGetClass(typeof(Dictionary<,>.ValueCollection)); + } + + [Test] + public void TestGetInnerClassInGenericClass2() + { + TestGetClass(typeof(Dictionary<,>.ValueCollection.Enumerator)); + } + + [Test] + public void TestToTypeReferenceInnerClass() + { + Assert.AreEqual("System.Environment+SpecialFolder", + typeof(Environment.SpecialFolder).ToTypeReference().Resolve(context).ReflectionName); + } + + [Test] + public void TestToTypeReferenceUnboundGenericClass() + { + Assert.AreEqual("System.Action`1", + typeof(Action<>).ToTypeReference().Resolve(context).ReflectionName); + Assert.AreEqual("System.Action`2", + typeof(Action<,>).ToTypeReference().Resolve(context).ReflectionName); + } + + [Test] + public void TestToTypeReferenceBoundGenericClass() + { + Assert.AreEqual("System.Action`1[[System.String]]", + typeof(Action).ToTypeReference().Resolve(context).ReflectionName); + Assert.AreEqual("System.Action`2[[System.Int32],[System.Int16]]", + typeof(Action).ToTypeReference().Resolve(context).ReflectionName); + } + + + [Test] + public void TestToTypeReferenceNullableType() + { + Assert.AreEqual("System.Nullable`1[[System.Int32]]", + typeof(int?).ToTypeReference().Resolve(context).ReflectionName); + } + + [Test] + public void TestToTypeReferenceInnerClassInUnboundGenericType() + { + Assert.AreEqual("System.Collections.Generic.Dictionary`2+ValueCollection", + typeof(Dictionary<,>.ValueCollection).ToTypeReference().Resolve(context).ReflectionName); + } + + [Test] + public void TestToTypeReferenceInnerClassInBoundGenericType() + { + Assert.AreEqual("System.Collections.Generic.Dictionary`2+KeyCollection[[System.String],[System.Int32]]", + typeof(Dictionary.KeyCollection).ToTypeReference().Resolve(context).ReflectionName); + } + + [Test] + public void TestToTypeReferenceArrayType() + { + Assert.AreEqual(typeof(int[]).FullName, + typeof(int[]).ToTypeReference().Resolve(context).ReflectionName); + } + + [Test] + public void TestToTypeReferenceMultidimensionalArrayType() + { + Assert.AreEqual(typeof(int[,]).FullName, + typeof(int[,]).ToTypeReference().Resolve(context).ReflectionName); + } + + [Test] + public void TestToTypeReferenceJaggedMultidimensionalArrayType() + { + Assert.AreEqual(typeof(int[,][,,]).FullName, + typeof(int[,][,,]).ToTypeReference().Resolve(context).ReflectionName); + } + + [Test] + public void TestToTypeReferencePointerType() + { + Assert.AreEqual(typeof(int*).FullName, + typeof(int*).ToTypeReference().Resolve(context).ReflectionName); + } + + [Test] + public void TestToTypeReferenceByReferenceType() + { + Assert.AreEqual(typeof(int).MakeByRefType().FullName, + typeof(int).MakeByRefType().ToTypeReference().Resolve(context).ReflectionName); + } + + [Test] + public void TestToTypeReferenceGenericType() + { + MethodInfo convertAllInfo = typeof(List<>).GetMethod("ConvertAll"); + Type parameterType = convertAllInfo.GetParameters()[0].ParameterType; // Converter[[`0],[``0]] + // cannot resolve generic types without knowing the parent entity: + Assert.AreEqual("System.Converter`2[[?],[?]]", + parameterType.ToTypeReference().Resolve(context).ReflectionName); + // now try with parent entity: + IMethod convertAll = context.GetClass(typeof(List<>)).Methods.Single(m => m.Name == "ConvertAll"); + Assert.AreEqual("System.Converter`2[[`0],[``0]]", + parameterType.ToTypeReference(entity: convertAll).Resolve(context).ReflectionName); + } + + [Test] + public void ParseReflectionName() + { + Assert.AreEqual("System.Int32", ReflectionHelper.ParseReflectionName("System.Int32").Resolve(context).ReflectionName); + Assert.AreEqual("System.Int32&", ReflectionHelper.ParseReflectionName("System.Int32&").Resolve(context).ReflectionName); + Assert.AreEqual("System.Int32*&", ReflectionHelper.ParseReflectionName("System.Int32*&").Resolve(context).ReflectionName); + Assert.AreEqual("System.Int32", ReflectionHelper.ParseReflectionName(typeof(int).AssemblyQualifiedName).Resolve(context).ReflectionName); + Assert.AreEqual("System.Action`1[[System.String]]", ReflectionHelper.ParseReflectionName("System.Action`1[[System.String]]").Resolve(context).ReflectionName); + Assert.AreEqual("System.Action`1[[System.String]]", ReflectionHelper.ParseReflectionName("System.Action`1[[System.String, mscorlib]]").Resolve(context).ReflectionName); + Assert.AreEqual("System.Int32[,,][,]", ReflectionHelper.ParseReflectionName(typeof(int[,][,,]).AssemblyQualifiedName).Resolve(context).ReflectionName); + Assert.AreEqual("System.Environment+SpecialFolder", ReflectionHelper.ParseReflectionName("System.Environment+SpecialFolder").Resolve(context).ReflectionName); + } + + [Test] + public void ParseOpenGenericReflectionName() + { + IMethod convertAll = context.GetClass(typeof(List<>)).Methods.Single(m => m.Name == "ConvertAll"); + Assert.AreEqual("System.Converter`2[[?],[?]]", ReflectionHelper.ParseReflectionName("System.Converter`2[[`0],[``0]]").Resolve(context).ReflectionName); + Assert.AreEqual("System.Converter`2[[`0],[``0]]", ReflectionHelper.ParseReflectionName("System.Converter`2[[`0],[``0]]", convertAll).Resolve(context).ReflectionName); + } + + [Test, ExpectedException(typeof(ArgumentNullException))] + public void ParseNullReflectionName() + { + ReflectionHelper.ParseReflectionName(null); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName1() + { + ReflectionHelper.ParseReflectionName(string.Empty); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName2() + { + ReflectionHelper.ParseReflectionName("`"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName3() + { + ReflectionHelper.ParseReflectionName("``"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName4() + { + ReflectionHelper.ParseReflectionName("System.Action`A"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName5() + { + ReflectionHelper.ParseReflectionName("System.Environment+"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName5b() + { + ReflectionHelper.ParseReflectionName("System.Environment+`"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName6() + { + ReflectionHelper.ParseReflectionName("System.Int32["); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName7() + { + ReflectionHelper.ParseReflectionName("System.Int32[`]"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName8() + { + ReflectionHelper.ParseReflectionName("System.Int32[,"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName9() + { + ReflectionHelper.ParseReflectionName("System.Int32]"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName10() + { + ReflectionHelper.ParseReflectionName("System.Int32*a"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName11() + { + ReflectionHelper.ParseReflectionName("System.Action`1[[]]"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName12() + { + ReflectionHelper.ParseReflectionName("System.Action`1[[System.Int32]a]"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName13() + { + ReflectionHelper.ParseReflectionName("System.Action`1[[System.Int32],]"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName14() + { + ReflectionHelper.ParseReflectionName("System.Action`1[[System.Int32]"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName15() + { + ReflectionHelper.ParseReflectionName("System.Action`1[[System.Int32"); + } + + [Test, ExpectedException(typeof(ReflectionNameParseException))] + public void ParseInvalidReflectionName16() + { + ReflectionHelper.ParseReflectionName("System.Action`1[[System.Int32],[System.String"); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/TypeSystem/TestInterningProvider.cs b/ICSharpCode.NRefactory.Tests/TypeSystem/TestInterningProvider.cs new file mode 100644 index 000000000..098298bb7 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/TypeSystem/TestInterningProvider.cs @@ -0,0 +1,171 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; +using ICSharpCode.NRefactory.TypeSystem.Implementation; +using ICSharpCode.NRefactory.Utils; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.TypeSystem +{ + //* Not a real unit test + [TestFixture] + public class TestInterningProvider + { + sealed class ReferenceComparer : IEqualityComparer + { + public new bool Equals(object a, object b) + { + return ReferenceEquals(a, b); + } + + public int GetHashCode(object obj) + { + return RuntimeHelpers.GetHashCode(obj); + } + } + + sealed class InterningComparer : IEqualityComparer + { + public bool Equals(ISupportsInterning x, ISupportsInterning y) + { + return x.EqualsForInterning(y); + } + + public int GetHashCode(ISupportsInterning obj) + { + return obj.GetHashCodeForInterning(); + } + } + + sealed class ListComparer : IEqualityComparer> + { + public bool Equals(IEnumerable a, IEnumerable b) + { + if (a.GetType() != b.GetType()) + return false; + return Enumerable.SequenceEqual(a, b, new ReferenceComparer()); + } + + public int GetHashCode(IEnumerable obj) + { + int hashCode = obj.GetType().GetHashCode(); + unchecked { + foreach (object o in obj) { + hashCode *= 27; + hashCode += RuntimeHelpers.GetHashCode(o); + } + } + return hashCode; + } + } + + sealed class InterningProvider : IInterningProvider + { + internal HashSet uniqueObjectsPreIntern = new HashSet(new ReferenceComparer()); + internal HashSet uniqueObjectsPostIntern = new HashSet(new ReferenceComparer()); + internal Dictionary byValueDict = new Dictionary(); + internal Dictionary supportsInternDict = new Dictionary(new InterningComparer()); + internal Dictionary, IEnumerable> listDict = new Dictionary, IEnumerable>(new ListComparer()); + + public T Intern(T obj) where T : class + { + if (obj == null) + return null; + uniqueObjectsPreIntern.Add(obj); + ISupportsInterning s = obj as ISupportsInterning; + if (s != null) { + ISupportsInterning output; + if (supportsInternDict.TryGetValue(s, out output)) { + obj = (T)output; + } else { + s.PrepareForInterning(this); + if (supportsInternDict.TryGetValue(s, out output)) + obj = (T)output; + else + supportsInternDict.Add(s, s); + } + } else if (obj is IType || Type.GetTypeCode(obj.GetType()) >= TypeCode.Boolean) { + object output; + if (byValueDict.TryGetValue(obj, out output)) + obj = (T)output; + else + byValueDict.Add(obj, obj); + } + uniqueObjectsPostIntern.Add(obj); + return obj; + } + + public IList InternList(IList list) where T : class + { + if (list == null) + return null; + uniqueObjectsPreIntern.Add(list); + for (int i = 0; i < list.Count; i++) { + T oldItem = list[i]; + T newItem = Intern(oldItem); + if (oldItem != newItem) { + if (list.IsReadOnly) + list = new T[list.Count]; + list[i] = newItem; + } + } + if (!list.IsReadOnly) + list = new ReadOnlyCollection(list); + IEnumerable output; + if (listDict.TryGetValue(list, out output)) + list = (IList)output; + else + listDict.Add(list, list); + uniqueObjectsPostIntern.Add(list); + return list; + } + + public void InternProject(IProjectContent pc) + { + foreach (var c in TreeTraversal.PreOrder(pc.GetClasses(), c => c.InnerClasses)) { + Intern(c.Namespace); + Intern(c.Name); + foreach (IMember m in c.Members) { + Intern(m); + } + } + } + } + + [Test] + public void PrintStatistics() + { + long startMemory = GC.GetTotalMemory(true); + IProjectContent pc = new CecilLoader().LoadAssemblyFile(typeof(object).Assembly.Location); + long memoryWithFullPC = GC.GetTotalMemory(true) - startMemory; + InterningProvider p = new InterningProvider(); + p.InternProject(pc); + PrintStatistics(p); + p = null; + long memoryWithInternedPC = GC.GetTotalMemory(true) - startMemory; + GC.KeepAlive(pc); + Console.WriteLine(memoryWithInternedPC / 1024 + " KB / " + memoryWithFullPC / 1024 + " KB"); + } + + void PrintStatistics(InterningProvider p) + { + var stats = + from obj in p.uniqueObjectsPreIntern + group 1 by obj.GetType() into g + join g2 in (from obj in p.uniqueObjectsPostIntern group 1 by obj.GetType()) on g.Key equals g2.Key + orderby g.Key.FullName + select new { Type = g.Key, PreCount = g.Count(), PostCount = g2.Count() }; + foreach (var element in stats) { + Console.WriteLine(element.Type + ": " + element.PostCount + "/" + element.PreCount); + } + } + }//*/ +} diff --git a/ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemTests.TestCase.cs b/ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemTests.TestCase.cs new file mode 100644 index 000000000..cfce62245 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemTests.TestCase.cs @@ -0,0 +1,68 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; + +[assembly: ICSharpCode.NRefactory.TypeSystem.TestCase.TypeTestAttribute( + 42, typeof(System.Action<>), typeof(IDictionary>))] + +namespace ICSharpCode.NRefactory.TypeSystem.TestCase +{ + public class SimplePublicClass + { + public void Method() {} + } + + public class TypeTestAttribute : Attribute + { + public TypeTestAttribute(int a1, Type a2, Type a3) {} + } + + public unsafe class DynamicTest + { + public dynamic SimpleProperty { get; set; } + + public List DynamicGenerics1(Action param) { return null; } + public void DynamicGenerics2(Action param) { } + public void DynamicGenerics3(Action param) { } + public void DynamicGenerics4(Action param) { } + public void DynamicGenerics5(Action param) { } + public void DynamicGenerics6(ref Action param) { } + public void DynamicGenerics7(Action param) { } + } + + public class GenericClass where A : B + { + public void TestMethod(string param) where V: K where K: IComparable {} + public void GetIndex(T element) where T : IEquatable {} + } + + public class PropertyTest + { + public int PropertyWithProtectedSetter { get; protected set; } + + public object PropertyWithPrivateSetter { get; private set; } + + public string this[int index] { get { return "Test"; } } + } + + public enum MyEnum : short + { + First, + Second, + Flag1 = 0x10, + Flag2 = 0x20, + CombinedFlags = Flag1 | Flag2 + } + + public class Base { + public class Nested {} + } + public class Derived : Base {} + + public struct MyStructWithCtor + { + public MyStructWithCtor(int a) {} + } +} diff --git a/ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemTests.cs b/ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemTests.cs new file mode 100644 index 000000000..ba43e776d --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemTests.cs @@ -0,0 +1,265 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Linq; +using ICSharpCode.NRefactory.TypeSystem.Implementation; +using ICSharpCode.NRefactory.TypeSystem.TestCase; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.TypeSystem +{ + /// + /// Base class for the type system tests. + /// Test fixtures for specific APIs (Cecil, C# Parser) derive from this class. + /// + public abstract class TypeSystemTests + { + protected IProjectContent testCasePC; + + ITypeResolveContext ctx; + + [SetUpAttribute] + public void SetUp() + { + ctx = CompositeTypeResolveContext.Combine(testCasePC, CecilLoaderTests.Mscorlib); + } + + ITypeDefinition GetClass(Type type) + { + return testCasePC.GetClass(type); + } + + [Test] + public void SimplePublicClassTest() + { + ITypeDefinition c = testCasePC.GetClass(typeof(SimplePublicClass)); + Assert.AreEqual(typeof(SimplePublicClass).Name, c.Name); + Assert.AreEqual(typeof(SimplePublicClass).FullName, c.FullName); + Assert.AreEqual(typeof(SimplePublicClass).Namespace, c.Namespace); + Assert.AreEqual(typeof(SimplePublicClass).FullName, c.ReflectionName); + + Assert.AreEqual(Accessibility.Public, c.Accessibility); + Assert.IsFalse(c.IsAbstract); + Assert.IsFalse(c.IsSealed); + Assert.IsFalse(c.IsStatic); + Assert.IsFalse(c.IsShadowing); + } + + [Test] + public void SimplePublicClassMethodTest() + { + ITypeDefinition c = testCasePC.GetClass(typeof(SimplePublicClass)); + Assert.AreEqual(2, c.Methods.Count); + + IMethod method = c.Methods.Single(m => m.Name == "Method"); + Assert.AreEqual(typeof(SimplePublicClass).FullName + ".Method", method.FullName); + Assert.AreSame(c, method.DeclaringType); + Assert.AreEqual(Accessibility.Public, method.Accessibility); + Assert.AreEqual(EntityType.Method, method.EntityType); + Assert.IsFalse(method.IsVirtual); + Assert.IsFalse(method.IsStatic); + Assert.IsTrue(method.IsFrozen); + Assert.AreEqual(0, method.Parameters.Count); + Assert.AreEqual(0, method.Attributes.Count); + } + + [Test] + public void DynamicType() + { + ITypeDefinition testClass = testCasePC.GetClass(typeof(DynamicTest)); + Assert.AreSame(SharedTypes.Dynamic, testClass.Properties.Single().ReturnType.Resolve(ctx)); + Assert.AreEqual(0, testClass.Properties.Single().Attributes.Count); + } + + [Test] + public void DynamicTypeInGenerics() + { + ITypeDefinition testClass = testCasePC.GetClass(typeof(DynamicTest)); + + IMethod m1 = testClass.Methods.Single(me => me.Name == "DynamicGenerics1"); + Assert.AreEqual("System.Collections.Generic.List`1[[dynamic]]", m1.ReturnType.Resolve(ctx).ReflectionName); + Assert.AreEqual("System.Action`3[[System.Object],[dynamic[]],[System.Object]]", m1.Parameters[0].Type.Resolve(ctx).ReflectionName); + + IMethod m2 = testClass.Methods.Single(me => me.Name == "DynamicGenerics2"); + Assert.AreEqual("System.Action`3[[System.Object],[dynamic],[System.Object]]", m2.Parameters[0].Type.Resolve(ctx).ReflectionName); + + IMethod m3 = testClass.Methods.Single(me => me.Name == "DynamicGenerics3"); + Assert.AreEqual("System.Action`3[[System.Int32],[dynamic],[System.Object]]", m3.Parameters[0].Type.Resolve(ctx).ReflectionName); + + IMethod m4 = testClass.Methods.Single(me => me.Name == "DynamicGenerics4"); + Assert.AreEqual("System.Action`3[[System.Int32[]],[dynamic],[System.Object]]", m4.Parameters[0].Type.Resolve(ctx).ReflectionName); + + IMethod m5 = testClass.Methods.Single(me => me.Name == "DynamicGenerics5"); + Assert.AreEqual("System.Action`3[[System.Int32*[]],[dynamic],[System.Object]]", m5.Parameters[0].Type.Resolve(ctx).ReflectionName); + + IMethod m6 = testClass.Methods.Single(me => me.Name == "DynamicGenerics6"); + Assert.AreEqual("System.Action`3[[System.Object],[dynamic],[System.Object]]&", m6.Parameters[0].Type.Resolve(ctx).ReflectionName); + + IMethod m7 = testClass.Methods.Single(me => me.Name == "DynamicGenerics7"); + Assert.AreEqual("System.Action`3[[System.Int32[][,]],[dynamic],[System.Object]]", m7.Parameters[0].Type.Resolve(ctx).ReflectionName); + } + + [Test] + public void DynamicParameterHasNoAttributes() + { + ITypeDefinition testClass = testCasePC.GetClass(typeof(DynamicTest)); + IMethod m1 = testClass.Methods.Single(me => me.Name == "DynamicGenerics1"); + Assert.AreEqual(0, m1.Parameters[0].Attributes.Count); + } + + [Test] + public void AssemblyAttribute() + { + var attributes = testCasePC.AssemblyAttributes; + var typeTest = attributes.First(a => a.AttributeType.Resolve(ctx).FullName == typeof(TypeTestAttribute).FullName); + Assert.AreEqual(3, typeTest.PositionalArguments.Count); + // first argument is (int)42 + Assert.AreEqual(42, (int)typeTest.PositionalArguments[0].GetValue(ctx)); + // second argument is typeof(System.Action<>) + IType rt = (IType)typeTest.PositionalArguments[1].GetValue(ctx); + Assert.IsFalse(rt is ParameterizedType); // rt must not be constructed - it's just an unbound type + Assert.AreEqual("System.Action", rt.FullName); + Assert.AreEqual(1, rt.TypeParameterCount); + // third argument is typeof(IDictionary>) + ParameterizedType crt = (ParameterizedType)typeTest.PositionalArguments[2].GetValue(ctx); + Assert.AreEqual("System.Collections.Generic.IDictionary", crt.FullName); + Assert.AreEqual("System.String", crt.TypeArguments[0].FullName); + // ? for NUnit.TestAttribute (because that assembly isn't in ctx) + Assert.AreEqual("System.Collections.Generic.IList`1[[?]]", crt.TypeArguments[1].ReflectionName); + } + + [Test] + public void TestClassTypeParameters() + { + var testClass = testCasePC.GetClass(typeof(GenericClass<,>)); + Assert.AreSame(testClass, testClass.TypeParameters[0].ParentClass); + Assert.AreSame(testClass, testClass.TypeParameters[1].ParentClass); + Assert.AreSame(testClass.TypeParameters[1], testClass.TypeParameters[0].Constraints[0].Resolve(ctx)); + } + + [Test] + public void TestMethod() + { + var testClass = testCasePC.GetClass(typeof(GenericClass<,>)); + + IMethod m = testClass.Methods.Single(me => me.Name == "TestMethod"); + Assert.AreEqual("K", m.TypeParameters[0].Name); + Assert.AreEqual("V", m.TypeParameters[1].Name); + Assert.AreSame(m, m.TypeParameters[0].ParentMethod); + Assert.AreSame(m, m.TypeParameters[1].ParentMethod); + + Assert.AreEqual("System.IComparable`1[[``1]]", m.TypeParameters[0].Constraints[0].Resolve(ctx).ReflectionName); + Assert.AreSame(m.TypeParameters[0], m.TypeParameters[1].Constraints[0].Resolve(ctx)); + } + + [Test] + public void GetIndex() + { + var testClass = testCasePC.GetClass(typeof(GenericClass<,>)); + + IMethod m = testClass.Methods.Single(me => me.Name == "GetIndex"); + Assert.AreEqual("T", m.TypeParameters[0].Name); + Assert.AreSame(m, m.TypeParameters[0].ParentMethod); + + ParameterizedType constraint = (ParameterizedType)m.TypeParameters[0].Constraints[0].Resolve(ctx); + Assert.AreEqual("IEquatable", constraint.Name); + Assert.AreEqual(1, constraint.TypeParameterCount); + Assert.AreEqual(1, constraint.TypeArguments.Count); + Assert.AreSame(m.TypeParameters[0], constraint.TypeArguments[0]); + } + + [Test] + public void PropertyWithProtectedSetter() + { + var testClass = testCasePC.GetClass(typeof(PropertyTest)); + IProperty p = testClass.Properties.Single(pr => pr.Name == "PropertyWithProtectedSetter"); + Assert.IsTrue(p.CanGet); + Assert.IsTrue(p.CanSet); + Assert.AreEqual(Accessibility.Public, p.Accessibility); + Assert.AreEqual(Accessibility.Public, p.Getter.Accessibility); + Assert.AreEqual(Accessibility.Protected, p.Setter.Accessibility); + } + + [Test] + public void PropertyWithPrivateSetter() + { + var testClass = testCasePC.GetClass(typeof(PropertyTest)); + IProperty p = testClass.Properties.Single(pr => pr.Name == "PropertyWithPrivateSetter"); + Assert.IsTrue(p.CanGet); + Assert.IsTrue(p.CanSet); + Assert.AreEqual(Accessibility.Public, p.Accessibility); + Assert.AreEqual(Accessibility.Public, p.Getter.Accessibility); + Assert.AreEqual(Accessibility.Private, p.Setter.Accessibility); + } + + [Test] + public void Indexer() + { + var testClass = testCasePC.GetClass(typeof(PropertyTest)); + IProperty p = testClass.Properties.Single(pr => pr.IsIndexer); + Assert.IsTrue(p.CanGet); + Assert.AreEqual(Accessibility.Public, p.Accessibility); + Assert.AreEqual(Accessibility.Public, p.Getter.Accessibility); + Assert.IsFalse(p.CanSet); + Assert.IsNull(p.Setter); + } + + [Test] + public void EnumTest() + { + var e = testCasePC.GetClass(typeof(MyEnum)); + Assert.AreEqual(ClassType.Enum, e.ClassType); + Assert.AreEqual(false, e.IsReferenceType); + Assert.AreEqual("System.Int16", e.BaseTypes[0].Resolve(ctx).ReflectionName); + Assert.AreEqual(new[] { "System.Enum" }, e.GetBaseTypes(ctx).Select(t => t.ReflectionName).ToArray()); + } + + [Test] + public void EnumFieldsTest() + { + var e = testCasePC.GetClass(typeof(MyEnum)); + Assert.AreEqual(5, e.Fields.Count); + + foreach (IField f in e.Fields) { + Assert.IsTrue(f.IsStatic); + Assert.IsTrue(f.IsConst); + Assert.AreEqual(Accessibility.Public, f.Accessibility); + Assert.AreSame(e, f.ConstantValue.GetValueType(ctx)); + Assert.AreEqual(typeof(short), f.ConstantValue.GetValue(ctx).GetType()); + } + + Assert.AreEqual("First", e.Fields[0].Name); + Assert.AreEqual(0, e.Fields[0].ConstantValue.GetValue(ctx)); + + Assert.AreEqual("Second", e.Fields[1].Name); + Assert.AreSame(e, e.Fields[1].ConstantValue.GetValueType(ctx)); + Assert.AreEqual(1, e.Fields[1].ConstantValue.GetValue(ctx)); + + Assert.AreEqual("Flag1", e.Fields[2].Name); + Assert.AreEqual(0x10, e.Fields[2].ConstantValue.GetValue(ctx)); + + Assert.AreEqual("Flag2", e.Fields[3].Name); + Assert.AreEqual(0x20, e.Fields[3].ConstantValue.GetValue(ctx)); + + Assert.AreEqual("CombinedFlags", e.Fields[4].Name); + Assert.AreEqual(0x30, e.Fields[4].ConstantValue.GetValue(ctx)); + } + + [Test] + public void ParameterizedTypeGetNestedTypesFromBaseClassTest() + { + var d = typeof(Derived).ToTypeReference().Resolve(ctx); + Assert.AreEqual(new[] { typeof(Base<>.Nested).FullName + "[[System.Int32]]" }, + d.GetNestedTypes(ctx).Select(n => n.ReflectionName).ToArray()); + } + + [Test] + public void DefaultConstructorAddedToStruct() + { + var ctors = typeof(MyStructWithCtor).ToTypeReference().Resolve(ctx).GetConstructors(ctx); + Assert.AreEqual(2, ctors.Count()); + Assert.IsFalse(ctors.Any(c => c.IsStatic)); + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/Untested.cs b/ICSharpCode.NRefactory.Tests/Untested.cs new file mode 100644 index 000000000..3555418c4 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/Untested.cs @@ -0,0 +1,41 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory +{ + // This file contains unit tests from SharpDevelop 4.0 which are not (yet) ported to NRefactory + + /* + + class ReflectionOrCecilLayerTests { + [Test] + public void ParameterComparisonTest() + { + DefaultParameter p1 = new DefaultParameter("a", mscorlib.GetClass("System.String", 0).DefaultReturnType, DomRegion.Empty); + DefaultParameter p2 = new DefaultParameter("b", new GetClassReturnType(mscorlib, "System.String", 0), DomRegion.Empty); + IList a1 = new List(); + IList a2 = new List(); + a1.Add(p1); + a2.Add(p2); + Assert.AreEqual(0, DiffUtility.Compare(a1, a2)); + } + + [Test] + public void GenericDocumentationTagNamesTest() + { + DefaultClass c = (DefaultClass)mscorlib.GetClass("System.Collections.Generic.List", 1); + Assert.AreEqual("T:System.Collections.Generic.List`1", + c.DocumentationTag); + Assert.AreEqual("M:System.Collections.Generic.List`1.Add(`0)", + GetMethod(c, "Add").DocumentationTag); + Assert.AreEqual("M:System.Collections.Generic.List`1.AddRange(System.Collections.Generic.IEnumerable{`0})", + GetMethod(c, "AddRange").DocumentationTag); + Assert.AreEqual("M:System.Collections.Generic.List`1.ConvertAll``1(System.Converter{`0,``0})", + GetMethod(c, "ConvertAll").DocumentationTag); + } + } + + */ +} diff --git a/ICSharpCode.NRefactory.Tests/Utils/CSharpPrimitiveCastTests.cs b/ICSharpCode.NRefactory.Tests/Utils/CSharpPrimitiveCastTests.cs new file mode 100644 index 000000000..fc73adcd7 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/Utils/CSharpPrimitiveCastTests.cs @@ -0,0 +1,68 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.Utils +{ + [TestFixture] + public class CSharpPrimitiveCastTests + { + // I know, these tests aren't really clever, more of a way to fake code coverage... + // Well, at least they should ensure the 'tables' in CSharpPrimitiveCast don't contain any typos. + + [Test] + public void FloatToInteger() + { + for (int checkedMode = 0; checkedMode < 2; checkedMode++) { + for (TypeCode to = TypeCode.Char; to <= TypeCode.UInt64; to++) { + object val = CSharpPrimitiveCast.Cast(to, 3.9f, checkedMode == 1); + Assert.AreEqual(to, Type.GetTypeCode(val.GetType())); + Assert.AreEqual(3, Convert.ToInt64(val)); + } + } + } + + [Test] + public void DoubleToInteger() + { + for (int checkedMode = 0; checkedMode < 2; checkedMode++) { + for (TypeCode to = TypeCode.Char; to <= TypeCode.UInt64; to++) { + object val = CSharpPrimitiveCast.Cast(to, 3.9, checkedMode == 1); + Assert.AreEqual(to, Type.GetTypeCode(val.GetType())); + Assert.AreEqual(3, Convert.ToInt64(val)); + } + } + } + + [Test] + public void DecimalToInteger() + { + for (int checkedMode = 0; checkedMode < 2; checkedMode++) { + for (TypeCode to = TypeCode.Char; to <= TypeCode.UInt64; to++) { + object val = CSharpPrimitiveCast.Cast(to, 3.9m, checkedMode == 1); + Assert.AreEqual(to, Type.GetTypeCode(val.GetType())); + Assert.AreEqual(3, Convert.ToInt64(val)); + } + } + } + + [Test] + public void IntegerToInteger() + { + for (int checkedMode = 0; checkedMode < 2; checkedMode++) { + for (TypeCode to = TypeCode.Char; to <= TypeCode.UInt64; to++) { + for (TypeCode to2 = TypeCode.Char; to2 <= TypeCode.Decimal; to2++) { + object val = CSharpPrimitiveCast.Cast(to, 3, checkedMode == 1); + Assert.AreEqual(to, Type.GetTypeCode(val.GetType())); + Assert.AreEqual(3, Convert.ToInt64(val)); + object val2 = CSharpPrimitiveCast.Cast(to2, val, checkedMode == 1); + Assert.AreEqual(to2, Type.GetTypeCode(val2.GetType())); + Assert.AreEqual(3, Convert.ToInt64(val2)); + } + } + } + } + } +} diff --git a/ICSharpCode.NRefactory.Tests/Utils/TreeTraversalTests.cs b/ICSharpCode.NRefactory.Tests/Utils/TreeTraversalTests.cs new file mode 100644 index 000000000..dae0f43c8 --- /dev/null +++ b/ICSharpCode.NRefactory.Tests/Utils/TreeTraversalTests.cs @@ -0,0 +1,47 @@ +// Copyright (c) 2010 AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under MIT X11 license (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.Utils +{ + [TestFixture] + public class TreeTraversalTests + { + sealed class Node + { + public int Data; + public List Children = new List(); + } + + Node tree = new Node { + Data = 1, + Children = { + new Node { Data = 2 }, + new Node { Data = 3, + Children = { + new Node { Data = 4 }, + new Node { Data = 5 } + } }, + new Node { Data = 6, Children = null } + } + }; + + [Test] + public void PreOrder() + { + Assert.AreEqual(new int[] { 1, 2, 3, 4, 5, 6 }, + TreeTraversal.PreOrder(tree, n => n.Children).Select(n => n.Data).ToArray()); + } + + [Test] + public void PostOrder() + { + Assert.AreEqual(new int[] { 2, 4, 5, 3, 6, 1 }, + TreeTraversal.PostOrder(tree, n => n.Children).Select(n => n.Data).ToArray()); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/.gitignore b/ICSharpCode.NRefactory.VB.Tests/.gitignore new file mode 100644 index 000000000..9ce745d95 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/.gitignore @@ -0,0 +1,3 @@ + +bin/ +obj/ \ No newline at end of file diff --git a/ICSharpCode.NRefactory.VB.Tests/AssemblyInfo.cs b/ICSharpCode.NRefactory.VB.Tests/AssemblyInfo.cs new file mode 100644 index 000000000..065e001fe --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/AssemblyInfo.cs @@ -0,0 +1,35 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System.Reflection; +using System.Runtime.CompilerServices; + +// Information about this assembly is defined by the following +// attributes. +// +// change them to the information which is associated with the assembly +// you compile. + +[assembly: AssemblyTitle("NRefactory Test")] +[assembly: AssemblyDescription("Unit tests for the parser and refactoring library for C# and VB.NET")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("ic#code")] +[assembly: AssemblyProduct("SharpDevelop")] +[assembly: AssemblyCopyright("2004-2006 AlphaSierraPapa")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// The assembly version has following format : +// +// Major.Minor.Build.Revision +// +// You can specify all values by your own or you can build default build and revision +// numbers with the '*' character (the default): + +[assembly: AssemblyVersion("2.0.0.1")] + +// The following attributes specify the key for the sign of your assembly. See the +// .NET Framework documentation for more information about signing. +// This is not required, if you don't want signing let these attributes like they're. +[assembly: AssemblyDelaySign(false)] +[assembly: AssemblyKeyFile("")] diff --git a/ICSharpCode.NRefactory.VB.Tests/General/UnitTest.cs b/ICSharpCode.NRefactory.VB.Tests/General/UnitTest.cs new file mode 100644 index 000000000..3dfc9c2aa --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/General/UnitTest.cs @@ -0,0 +1,103 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Reflection; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Visitors; + +namespace ICSharpCode.NRefactory.VB.Tests +{ + [TestFixture] + public class StructuralTest + { + [Test] + public void TestToStringMethods() + { + Type[] allTypes = typeof(INode).Assembly.GetTypes(); + + foreach (Type type in allTypes) { + if (type.IsClass && !type.IsAbstract && !type.IsNested && type.GetInterface(typeof(INode).FullName) != null) { + MethodInfo methodInfo = type.GetMethod("ToString", BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public); + Assert.IsNotNull(methodInfo, "ToString() not found in " + type.FullName); + } + } + } + + [Test] + public void TestUnitTests() + { + Type[] allTypes = typeof(StructuralTest).Assembly.GetTypes(); + + foreach (Type type in allTypes) { + if (type.GetCustomAttributes(typeof(TestFixtureAttribute), true).Length > 0) { + foreach (MethodInfo m in type.GetMethods()) { + if (m.IsPublic && m.ReturnType == typeof(void) && m.GetParameters().Length == 0) { + if (m.GetCustomAttributes(typeof(TestAttribute), true).Length == 0) { + Assert.Fail(type.Name + "." + m.Name + " should have the [Test] attribute!"); + } + } + } + } + } + } + +// [Test] +// public void TestAcceptVisitorMethods() +// { +// Type[] allTypes = typeof(AbstractNode).Assembly.GetTypes(); +// +// foreach (Type type in allTypes) { +// if (type.IsClass && !type.IsAbstract && type.GetInterface(typeof(INode).FullName) != null) { +// MethodInfo methodInfo = type.GetMethod("AcceptVisitor", BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public); +// Assertion.AssertNotNull("AcceptVisitor() not found in " + type.FullName, methodInfo); +// } +// } +// } + + [Test] + public void TestIDomVisitor() + { + Type[] allTypes = typeof(AbstractNode).Assembly.GetTypes(); + Type visitor = typeof(IDomVisitor); + + foreach (Type type in allTypes) { + if (type.IsClass && !type.IsAbstract && !type.IsNested && type.GetInterface(typeof(INode).FullName) != null && !type.Name.StartsWith("Null")) { + MethodInfo methodInfo = visitor.GetMethod("Visit" + type.Name, BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.ExactBinding, null, new Type[] {type, typeof(object)}, null); + Assert.IsNotNull(methodInfo, "Visit with parameter " + type.FullName + " not found"); + Assert.AreEqual(2, methodInfo.GetParameters().Length); + ParameterInfo first = methodInfo.GetParameters()[0]; + Assert.AreEqual(Char.ToLower(first.ParameterType.Name[0]) + first.ParameterType.Name.Substring(1), first.Name); + + ParameterInfo second = methodInfo.GetParameters()[1]; + Assert.AreEqual(typeof(System.Object), second.ParameterType); + Assert.AreEqual("data", second.Name); + } + } + } + + [Test] + public void TestAbstractDomVisitorVisitor() + { + Type[] allTypes = typeof(AbstractNode).Assembly.GetTypes(); + Type visitor = typeof(AbstractDomVisitor); + + foreach (Type type in allTypes) { + if (type.IsClass && !type.IsAbstract && !type.IsNested && type.GetInterface(typeof(INode).FullName) != null && !type.Name.StartsWith("Null")) { + MethodInfo methodInfo = visitor.GetMethod("Visit" + type.Name, BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.ExactBinding, null, new Type[] {type, typeof(object)}, null); + Assert.IsNotNull(methodInfo, "Visit with parameter " + type.FullName + " not found"); + + Assert.AreEqual(2, methodInfo.GetParameters().Length); + ParameterInfo first = methodInfo.GetParameters()[0]; + Assert.AreEqual(Char.ToLower(first.ParameterType.Name[0]) + first.ParameterType.Name.Substring(1), first.Name); + + ParameterInfo second = methodInfo.GetParameters()[1]; + Assert.AreEqual(typeof(System.Object), second.ParameterType); + Assert.AreEqual("data", second.Name); + } + } + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/ICSharpCode.NRefactory.VB.Tests.csproj b/ICSharpCode.NRefactory.VB.Tests/ICSharpCode.NRefactory.VB.Tests.csproj new file mode 100644 index 000000000..db980b370 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/ICSharpCode.NRefactory.VB.Tests.csproj @@ -0,0 +1,154 @@ + + + + Debug + AnyCPU + 8.0.50215 + 2.0 + {870115DD-960A-4406-A6B9-600BCDC36A03} + ICSharpCode.NRefactory.VB.Tests + ICSharpCode.NRefactory.VB.Tests + Library + False + False + OnBuildSuccess + Library + ..\..\..\..\bin\UnitTests\ + False + x86 + 4 + v4.0 + false + + + True + DEBUG + False + + + True + False + + + Full + true + Project + + + False + + + False + Auto + 4194304 + 4096 + + + + ..\lib\nunit.framework.dll + True + + + + 3.5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {7B82B671-419F-45F4-B778-D9286F996EFA} + ICSharpCode.NRefactory.VB + + + + \ No newline at end of file diff --git a/ICSharpCode.NRefactory.VB.Tests/Lexer/CustomLexerTests.cs b/ICSharpCode.NRefactory.VB.Tests/Lexer/CustomLexerTests.cs new file mode 100644 index 000000000..ce697d143 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Lexer/CustomLexerTests.cs @@ -0,0 +1,118 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; + +namespace ICSharpCode.NRefactory.VB.Tests.Lexer +{ + [TestFixture] + public class CustomLexerTests + { + VBLexer GenerateLexer(StringReader sr) + { + return ParserFactory.CreateLexer(sr); + } + + [Test] + public void TestSingleEOLForMulitpleLines() + { + VBLexer lexer = GenerateLexer(new StringReader("Stop\n\n\nEnd")); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Stop)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.End)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); + } + + [Test] + public void TestSingleEOLForMulitpleLinesWithContinuation() + { + VBLexer lexer = GenerateLexer(new StringReader("Stop\n _\n\nEnd")); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Stop)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.End)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); + } + + [Test] + public void EscapedIdentifier() + { + VBLexer lexer = GenerateLexer(new StringReader("[Stop]")); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); + } + + [Test] + public void IdentifierWithTypeCharacter() + { + VBLexer lexer = GenerateLexer(new StringReader("Stop$")); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); + } + + [Test] + public void ExclamationMarkIsTypeCharacter() + { + VBLexer lexer = GenerateLexer(new StringReader("a!=b")); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Assign)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); + } + + [Test] + public void ExclamationMarkIsTypeCharacter2() + { + VBLexer lexer = GenerateLexer(new StringReader("a! b")); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); + } + + [Test] + public void ExclamationMarkIsIdentifier() + { + VBLexer lexer = GenerateLexer(new StringReader("a!b")); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.ExclamationMark)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); + } + + [Test] + public void ExclamationMarkIsIdentifier2() + { + VBLexer lexer = GenerateLexer(new StringReader("a![b]")); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.ExclamationMark)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); + } + + [Test] + public void RemCommentTest() + { + VBLexer lexer = GenerateLexer(new StringReader("a rem b")); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.Identifier)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOL)); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); + } + + [Test] + public void RemCommentTest2() + { + VBLexer lexer = GenerateLexer(new StringReader("REM c")); + Assert.That(lexer.NextToken().Kind, Is.EqualTo(Tokens.EOF)); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Lexer/ImplicitLineContinuationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Lexer/ImplicitLineContinuationTests.cs new file mode 100644 index 000000000..0c24c847f --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Lexer/ImplicitLineContinuationTests.cs @@ -0,0 +1,230 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using ICSharpCode.NRefactory.VB.Parser; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Lexer +{ + [TestFixture] + public class ImplicitLineContinuationTests + { + [Test] + public void Example1() + { + string code = @"Module Test + Sub Print( + Param1 As Integer, + Param2 As Integer) + + If (Param1 < Param2) Or + (Param1 > Param2) Then + Console.WriteLine(""Not equal"") + End If + End Sub +End Module"; + + VBLexer lexer = GenerateLexer(new StringReader(code)); + + CheckTokens(lexer, Tokens.Module, Tokens.Identifier, Tokens.EOL, + Tokens.Sub, Tokens.Identifier, Tokens.OpenParenthesis, + Tokens.Identifier, Tokens.As, Tokens.Integer, Tokens.Comma, + Tokens.Identifier, Tokens.As, Tokens.Integer, Tokens.CloseParenthesis, Tokens.EOL, + Tokens.If, Tokens.OpenParenthesis, Tokens.Identifier, Tokens.LessThan, Tokens.Identifier, Tokens.CloseParenthesis, Tokens.Or, + Tokens.OpenParenthesis, Tokens.Identifier, Tokens.GreaterThan, Tokens.Identifier, Tokens.CloseParenthesis, Tokens.Then, Tokens.EOL, + Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.OpenParenthesis, Tokens.LiteralString, Tokens.CloseParenthesis, Tokens.EOL, + Tokens.End, Tokens.If, Tokens.EOL, + Tokens.End, Tokens.Sub, Tokens.EOL, + Tokens.End, Tokens.Module); + } + + [Test] + public void QualifierInWith() + { + string code = @"Module Test + Sub Print + With xml + Dim a = b. + d + Dim c = . + Count + End With + End Sub +End Module"; + + VBLexer lexer = GenerateLexer(new StringReader(code)); + + CheckTokens(lexer, Tokens.Module, Tokens.Identifier, Tokens.EOL, + Tokens.Sub, Tokens.Identifier, Tokens.EOL, + Tokens.With, Tokens.Identifier, Tokens.EOL, + Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.EOL, + Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.Dot, Tokens.EOL, + Tokens.Identifier, Tokens.EOL, + Tokens.End, Tokens.With, Tokens.EOL, + Tokens.End, Tokens.Sub, Tokens.EOL, + Tokens.End, Tokens.Module); + } + + [Test] + public void Example2() + { + string code = @"Module Test + Sub Print + Dim a = _ + + y + End Sub +End Module"; + + VBLexer lexer = GenerateLexer(new StringReader(code)); + + CheckTokens(lexer, Tokens.Module, Tokens.Identifier, Tokens.EOL, + Tokens.Sub, Tokens.Identifier, Tokens.EOL, + Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.EOL, Tokens.Identifier, Tokens.EOL, + Tokens.End, Tokens.Sub, Tokens.EOL, + Tokens.End, Tokens.Module); + } + + [Test] + public void Query() + { + string code = @"Module Test + Sub A + Dim q = From x In a + Select x + End Sub +End Module"; + + VBLexer lexer = GenerateLexer(new StringReader(code)); + + CheckTokens(lexer, Tokens.Module, Tokens.Identifier, Tokens.EOL, + Tokens.Sub, Tokens.Identifier, Tokens.EOL, + Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.From, Tokens.Identifier, Tokens.In, Tokens.Identifier, + Tokens.Select, Tokens.Identifier, Tokens.EOL, + Tokens.End, Tokens.Sub, Tokens.EOL, + Tokens.End, Tokens.Module); + } + + [Test] + public void Query1() + { + string code = @"Module Test + Sub A + Dim actions = From a in b Select Sub() + Dim i = 1 + Select Case i + End Select + End Sub + End Sub +End Module"; + + VBLexer lexer = GenerateLexer(new StringReader(code)); + + CheckTokens(lexer, Tokens.Module, Tokens.Identifier, Tokens.EOL, + Tokens.Sub, Tokens.Identifier, Tokens.EOL, + Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.From, Tokens.Identifier, Tokens.In, Tokens.Identifier, Tokens.Select, Tokens.Sub, Tokens.OpenParenthesis, Tokens.CloseParenthesis, Tokens.EOL, + Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.LiteralInteger, Tokens.EOL, + Tokens.Select, Tokens.Case, Tokens.Identifier, Tokens.EOL, + Tokens.End, Tokens.Select, Tokens.EOL, + Tokens.End, Tokens.Sub, Tokens.EOL, + Tokens.End, Tokens.Sub, Tokens.EOL, + Tokens.End, Tokens.Module); + } + + /// tests http://community.sharpdevelop.net/forums/p/12068/32893.aspx#32893 + [Test] + public void Bug_Thread12068() + { + string code = @"Class MainClass + Public Shared Sub Main() + Dim categoryNames = From p In AList _ + Select p.AFunction(1,2,3) _ + Distinct + End Sub +End Class"; + + VBLexer lexer = GenerateLexer(new StringReader(code)); + + CheckTokens( + lexer, Tokens.Class, Tokens.Identifier, Tokens.EOL, + Tokens.Public, Tokens.Shared, Tokens.Sub, Tokens.Identifier, Tokens.OpenParenthesis, Tokens.CloseParenthesis, Tokens.EOL, + Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.From, Tokens.Identifier, Tokens.In, Tokens.Identifier, + Tokens.Select, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.OpenParenthesis, Tokens.LiteralInteger, + Tokens.Comma, Tokens.LiteralInteger, Tokens.Comma, Tokens.LiteralInteger, Tokens.CloseParenthesis, + Tokens.Distinct, Tokens.EOL, + Tokens.End, Tokens.Sub, Tokens.EOL, + Tokens.End, Tokens.Class + ); + } + + [Test] + public void LineContinuationAfterAttributes() + { + string code = @" +Public Class TestContinuation + + Public Sub TestMethod + Assert.Fail + End Sub + + _ + Public Sub TestMethod2 + Assert.Fail + End Sub +End Class"; + + VBLexer lexer = GenerateLexer(new StringReader(code)); + + CheckTokens( + lexer, Tokens.LessThan, Tokens.Identifier, Tokens.GreaterThan, + Tokens.Public, Tokens.Class, Tokens.Identifier, Tokens.EOL, + Tokens.LessThan, Tokens.Identifier, Tokens.GreaterThan, + Tokens.Public, Tokens.Sub, Tokens.Identifier, Tokens.EOL, + Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.EOL, + Tokens.End, Tokens.Sub, Tokens.EOL, + Tokens.LessThan, Tokens.Identifier, Tokens.GreaterThan, + Tokens.Public, Tokens.Sub, Tokens.Identifier, Tokens.EOL, + Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.EOL, + Tokens.End, Tokens.Sub, Tokens.EOL, + Tokens.End, Tokens.Class + ); + } + + [Test] + public void NoILCAfterGlobalAttributes() + { + string code = "" + Environment.NewLine + + ""; + + VBLexer lexer = GenerateLexer(new StringReader(code)); + + CheckTokens( + lexer, Tokens.LessThan, Tokens.Assembly, Tokens.Colon, + Tokens.Identifier, Tokens.OpenParenthesis, Tokens.LiteralString, + Tokens.CloseParenthesis, Tokens.GreaterThan, Tokens.EOL, + Tokens.LessThan, Tokens.Assembly, Tokens.Colon, + Tokens.Identifier, Tokens.OpenParenthesis, Tokens.LiteralString, + Tokens.CloseParenthesis, Tokens.GreaterThan + ); + } + + #region Helpers + VBLexer GenerateLexer(StringReader sr) + { + return ParserFactory.CreateLexer(sr); + } + + void CheckTokens(VBLexer lexer, params int[] tokens) + { + for (int i = 0; i < tokens.Length; i++) { + int token = tokens[i]; + Token t = lexer.NextToken(); + int next = t.Kind; + Assert.AreEqual(token, next, "{2} of {3}: {0} != {1}; at {4}", Tokens.GetTokenString(token), Tokens.GetTokenString(next), i + 1, tokens.Length, t.Location); + } + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Lexer/LATextReaderTests.cs b/ICSharpCode.NRefactory.VB.Tests/Lexer/LATextReaderTests.cs new file mode 100644 index 000000000..2671dad2e --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Lexer/LATextReaderTests.cs @@ -0,0 +1,35 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using ICSharpCode.NRefactory.VB.Parser; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Lexer +{ + [TestFixture] + public class LATextReaderTests + { + [Test] + public void TestPeek() + { + LATextReader reader = new LATextReader(new StringReader("abcd")); + + CheckPeek(reader, 0, 'a'); + CheckPeek(reader, 2, 'c'); + CheckPeek(reader, 3, 'd'); + CheckPeek(reader, 1, 'b'); + CheckPeek(reader, 0, 'a'); + Assert.AreEqual((int)'a', reader.Read()); + CheckPeek(reader, 1, 'c'); + CheckPeek(reader, 2, 'd'); + CheckPeek(reader, 0, 'b'); + } + + void CheckPeek(LATextReader reader, int num1, char char2) + { + Assert.AreEqual((int)char2, reader.Peek(num1)); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerContextTests.cs b/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerContextTests.cs new file mode 100644 index 000000000..760c7372a --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerContextTests.cs @@ -0,0 +1,572 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; + +namespace ICSharpCode.NRefactory.VB.Tests.Lexer +{ + [TestFixture] + public class LexerContextTests + { + [Test] + public void SimpleGlobal() + { + RunTest( + @"Option Explicit", + @"enter Global +exit Global +" + ); + } + + [Test] + public void VariableWithXmlLiteral() + { + RunTest( + @"Class Test + Public Sub New() + Dim x = + End Sub +End Class +", + @"enter Global + enter TypeDeclaration + enter Identifier + exit Identifier + enter Member + enter Identifier + exit Identifier + enter Body + enter Identifier + exit Identifier + enter Expression + enter Expression + enter Expression + enter Xml + enter Xml + exit Xml + exit Xml + exit Expression + exit Expression + exit Expression + exit Body + exit Member + exit TypeDeclaration +exit Global +" + ); + } + + [Test] + public void MemberWithXmlLiteral() + { + RunTest( + @"Class Test + Private xml As XElement = + + Public Sub New() + Dim x = + End Sub +End Class +", + @"enter Global + enter TypeDeclaration + enter Identifier + exit Identifier + enter Member + enter Identifier + exit Identifier + enter Type + exit Type + enter Expression + enter Expression + enter Expression + enter Xml + enter Xml + exit Xml + exit Xml + exit Expression + exit Expression + exit Expression + exit Member + enter Member + enter Identifier + exit Identifier + enter Body + enter Identifier + exit Identifier + enter Expression + enter Expression + enter Expression + enter Xml + enter Xml + exit Xml + exit Xml + exit Expression + exit Expression + exit Expression + exit Body + exit Member + exit TypeDeclaration +exit Global +" + ); + } + + [Test] + public void GlobalAttributeTest() + { + RunTest( + @" +Class Test + Public Sub New() + Dim x = 5 + End Sub +End Class +", + @"enter Global + enter Attribute + exit Attribute + enter TypeDeclaration + enter Identifier + exit Identifier + enter Member + enter Identifier + exit Identifier + enter Body + enter Identifier + exit Identifier + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + exit Body + exit Member + exit TypeDeclaration +exit Global +" + ); + } + + [Test] + public void ClassAttributeTest() + { + RunTest( + @" +Class Test + Public Sub New() + Dim x = 5 + End Sub +End Class +", + @"enter Global + enter Attribute + exit Attribute + enter TypeDeclaration + enter Identifier + exit Identifier + enter Member + enter Identifier + exit Identifier + enter Body + enter Identifier + exit Identifier + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + exit Body + exit Member + exit TypeDeclaration +exit Global +" + ); + } + + [Test] + public void MethodAttributeTest() + { + RunTest( + @"Class Test + + Public Sub New() + Dim x = 5 + End Sub +End Class +", + @"enter Global + enter TypeDeclaration + enter Identifier + exit Identifier + enter Attribute + exit Attribute + enter Member + enter Identifier + exit Identifier + enter Body + enter Identifier + exit Identifier + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + exit Body + exit Member + exit TypeDeclaration +exit Global +" + ); + } + + [Test] + public void WithBlockTest() + { + RunTest( + @"Class Test + Public Sub New() + With x + + End With + End Sub +End Class +", + @"enter Global + enter TypeDeclaration + enter Identifier + exit Identifier + enter Member + enter Identifier + exit Identifier + enter Body + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + enter Body + exit Body + exit Body + exit Member + exit TypeDeclaration +exit Global +" + ); + } + + [Test] + public void StatementsTest() + { + RunTest( + @"Class Test + Public Sub New() + For i As Integer = 0 To 10 + + Next + + For Each x As Integer In list + + Next + + Try + + Catch e As Exception + + End Try + End Sub +End Class +", + @"enter Global + enter TypeDeclaration + enter Identifier + exit Identifier + enter Member + enter Identifier + exit Identifier + enter Body + enter Identifier + enter Expression + exit Expression + exit Identifier + enter Type + exit Type + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + enter Body + exit Body + enter Identifier + enter Expression + exit Expression + exit Identifier + enter Type + exit Type + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + enter Body + exit Body + enter Body + exit Body + enter Identifier + exit Identifier + enter Type + exit Type + enter Body + exit Body + exit Body + exit Member + exit TypeDeclaration +exit Global +" + ); + } + + [Test] + public void ClassTest() + { + RunTest( + @"Class MainClass ' a comment + Dim under_score_field As Integer + Sub SomeMethod() + simple += 1 + For Each loopVarName In collection + Next + End Sub +End Class", + @"enter Global + enter TypeDeclaration + enter Identifier + exit Identifier + enter Member + enter Identifier + exit Identifier + enter Type + exit Type + exit Member + enter Member + enter Identifier + exit Identifier + enter Body + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + enter Identifier + enter Expression + exit Expression + exit Identifier + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + enter Body + exit Body + exit Body + exit Member + exit TypeDeclaration +exit Global +"); + } + + [Test] + public void CollectionInitializer() + { + RunTest(@"' +' Created by SharpDevelop. +' User: Siegfried +' Date: 22.06.2010 +' Time: 21:29 +' +' To change this template use Tools | Options | Coding | Edit Standard Headers. +' + +Option Infer On + +Imports System.Linq +Imports System.Xml.Linq + +Module Program + Sub Main() + Console.WriteLine(""Hello World!"") + + Dim name = ""Test"" + Dim content = { 4, 5, New XAttribute(""a"", 3) } + + Dim xml = <<%= name %> <%= content %> /> + + Console.ReadKey() + End Sub +End Module", + @"enter Global + enter Importable + exit Importable + enter Importable + exit Importable + enter TypeDeclaration + enter Identifier + exit Identifier + enter Member + enter Identifier + exit Identifier + enter Body + enter Expression + enter Expression + enter Expression + exit Expression + enter Expression + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + exit Expression + exit Expression + exit Expression + enter Identifier + exit Identifier + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + enter Identifier + exit Identifier + enter Expression + enter Expression + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + enter Expression + enter Expression + enter ObjectCreation + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + exit ObjectCreation + exit Expression + exit Expression + exit Expression + exit Expression + enter Identifier + exit Identifier + enter Expression + enter Expression + enter Expression + enter Xml + enter Xml + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + enter Expression + enter Expression + enter Expression + exit Expression + exit Expression + exit Expression + exit Xml + exit Xml + exit Expression + exit Expression + exit Expression + enter Expression + enter Expression + enter Expression + exit Expression + enter Expression + exit Expression + exit Expression + exit Expression + exit Body + exit Member + exit TypeDeclaration +exit Global +"); + } + + [Test] + public void Imports() + { + RunTest(@"Imports System +Imports System.Linq +Imports System.Collections.Generic", + @"enter Global + enter Importable + exit Importable + enter Importable + exit Importable + enter Importable + exit Importable +exit Global +"); + } + + void RunTest(string code, string expectedOutput) + { + ExpressionFinder p = new ExpressionFinder(); + VBLexer lexer = ParserFactory.CreateLexer(new StringReader(code)); + Token t; + + do { + t = lexer.NextToken(); + p.InformToken(t); + } while (t.Kind != Tokens.EOF); + + Console.WriteLine(p.Output); + + Assert.IsEmpty(p.Errors); + + Assert.AreEqual(expectedOutput, p.Output); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerPositionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerPositionTests.cs new file mode 100644 index 000000000..f227c5c8a --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerPositionTests.cs @@ -0,0 +1,87 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using ICSharpCode.NRefactory.VB.Parser; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Lexer +{ + [TestFixture] + public class LexerPositionTests + { + VBLexer GenerateLexer(string s) + { + return ParserFactory.CreateLexer(new StringReader(s)); + } + + [Test] + public void TestNewLine() + { + VBLexer l = GenerateLexer("public\nstatic"); + Token t = l.NextToken(); + Assert.AreEqual(Tokens.Public, t.Kind); + Assert.AreEqual(new Location(1, 1), t.Location); + Assert.AreEqual(new Location(7, 1), t.EndLocation); + t = l.NextToken(); + Assert.AreEqual(Tokens.EOL, t.Kind); + Assert.AreEqual(new Location(7, 1), t.Location); + Assert.AreEqual(new Location(1, 2), t.EndLocation); + t = l.NextToken(); + Assert.AreEqual(Tokens.Static, t.Kind); + Assert.AreEqual(new Location(1, 2), t.Location); + Assert.AreEqual(new Location(7, 2), t.EndLocation); + } + + [Test] + public void TestCarriageReturnNewLine() + { + VBLexer l = GenerateLexer("public\r\nstatic"); + Token t = l.NextToken(); + Assert.AreEqual(Tokens.Public, t.Kind); + Assert.AreEqual(new Location(1, 1), t.Location); + Assert.AreEqual(new Location(7, 1), t.EndLocation); + t = l.NextToken(); + Assert.AreEqual(Tokens.EOL, t.Kind); + Assert.AreEqual(new Location(7, 1), t.Location); + Assert.AreEqual(new Location(1, 2), t.EndLocation); + t = l.NextToken(); + Assert.AreEqual(Tokens.Static, t.Kind); + Assert.AreEqual(new Location(1, 2), t.Location); + Assert.AreEqual(new Location(7, 2), t.EndLocation); + } + + [Test] + public void TestPositionOfEOF1() + { + VBLexer l = GenerateLexer("public"); + l.NextToken(); // public + Token t = l.NextToken(); + Assert.AreEqual(Tokens.EOL, t.Kind); + Assert.AreEqual(new Location(7, 1), t.Location); + Assert.AreEqual(new Location(7, 1), t.EndLocation); + + t = l.NextToken(); + Assert.AreEqual(Tokens.EOF, t.Kind); + Assert.AreEqual(new Location(7, 1), t.Location); + Assert.AreEqual(new Location(7, 1), t.EndLocation); + } + + [Test] + public void TestPositionOfEOF2() + { + VBLexer l = GenerateLexer("public _\n "); + l.NextToken(); // public + Token t = l.NextToken(); + Assert.AreEqual(Tokens.EOL, t.Kind); + Assert.AreEqual(new Location(2, 2), t.Location); + Assert.AreEqual(new Location(2, 2), t.EndLocation); + + t = l.NextToken(); + Assert.AreEqual(Tokens.EOF, t.Kind); + Assert.AreEqual(new Location(2, 2), t.Location); + Assert.AreEqual(new Location(2, 2), t.EndLocation); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerTests.cs b/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerTests.cs new file mode 100644 index 000000000..b181f4851 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Lexer/LexerTests.cs @@ -0,0 +1,1538 @@ +// this file was autogenerated by a tool. +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.PrettyPrinter; + +namespace ICSharpCode.NRefactory.VB.Tests.Lexer +{ + [TestFixture] + public sealed class LexerTests + { + VBLexer GenerateLexer(StringReader sr) + { + return ParserFactory.CreateLexer(sr); + } + + [Test] + public void TestAssign() + { + VBLexer lexer = GenerateLexer(new StringReader("=")); + Assert.AreEqual(Tokens.Assign, lexer.NextToken().Kind); + } + + [Test] + public void TestColon() + { + VBLexer lexer = GenerateLexer(new StringReader(":")); + Assert.AreEqual(Tokens.Colon, lexer.NextToken().Kind); + } + + [Test] + public void TestComma() + { + VBLexer lexer = GenerateLexer(new StringReader(",")); + Assert.AreEqual(Tokens.Comma, lexer.NextToken().Kind); + } + + [Test] + public void TestConcatString() + { + VBLexer lexer = GenerateLexer(new StringReader("&")); + Assert.AreEqual(Tokens.ConcatString, lexer.NextToken().Kind); + } + + [Test] + public void TestDiv() + { + VBLexer lexer = GenerateLexer(new StringReader("/")); + Assert.AreEqual(Tokens.Div, lexer.NextToken().Kind); + } + + [Test] + public void TestDivInteger() + { + VBLexer lexer = GenerateLexer(new StringReader("\\")); + Assert.AreEqual(Tokens.DivInteger, lexer.NextToken().Kind); + } + + [Test] + public void TestDot() + { + VBLexer lexer = GenerateLexer(new StringReader(".")); + Assert.AreEqual(Tokens.Dot, lexer.NextToken().Kind); + } + + [Test] + public void TestTripleDot() + { + VBLexer lexer = GenerateLexer(new StringReader("...")); + Assert.AreEqual(Tokens.TripleDot, lexer.NextToken().Kind); + } + + [Test] + public void TestDotAt() + { + VBLexer lexer = GenerateLexer(new StringReader(".@")); + Assert.AreEqual(Tokens.DotAt, lexer.NextToken().Kind); + } + + [Test] + public void TestExclamationMark() + { + VBLexer lexer = GenerateLexer(new StringReader("!")); + Assert.AreEqual(Tokens.ExclamationMark, lexer.NextToken().Kind); + } + + [Test] + public void TestMinus() + { + VBLexer lexer = GenerateLexer(new StringReader("-")); + Assert.AreEqual(Tokens.Minus, lexer.NextToken().Kind); + } + + [Test] + public void TestPlus() + { + VBLexer lexer = GenerateLexer(new StringReader("+")); + Assert.AreEqual(Tokens.Plus, lexer.NextToken().Kind); + } + + [Test] + public void TestPower() + { + VBLexer lexer = GenerateLexer(new StringReader("^")); + Assert.AreEqual(Tokens.Power, lexer.NextToken().Kind); + } + + [Test] + public void TestQuestionMark() + { + VBLexer lexer = GenerateLexer(new StringReader("?")); + Assert.AreEqual(Tokens.QuestionMark, lexer.NextToken().Kind); + } + + [Test] + public void TestTimes() + { + VBLexer lexer = GenerateLexer(new StringReader("*")); + Assert.AreEqual(Tokens.Times, lexer.NextToken().Kind); + } + + [Test] + public void TestOpenCurlyBrace() + { + VBLexer lexer = GenerateLexer(new StringReader("{")); + Assert.AreEqual(Tokens.OpenCurlyBrace, lexer.NextToken().Kind); + } + + [Test] + public void TestCloseCurlyBrace() + { + VBLexer lexer = GenerateLexer(new StringReader("}")); + Assert.AreEqual(Tokens.CloseCurlyBrace, lexer.NextToken().Kind); + } + + [Test] + public void TestOpenParenthesis() + { + VBLexer lexer = GenerateLexer(new StringReader("(")); + Assert.AreEqual(Tokens.OpenParenthesis, lexer.NextToken().Kind); + } + + [Test] + public void TestCloseParenthesis() + { + VBLexer lexer = GenerateLexer(new StringReader(")")); + Assert.AreEqual(Tokens.CloseParenthesis, lexer.NextToken().Kind); + } + + [Test] + public void TestGreaterThan() + { + VBLexer lexer = GenerateLexer(new StringReader(">")); + Assert.AreEqual(Tokens.GreaterThan, lexer.NextToken().Kind); + } + + [Test] + public void TestLessThan() + { + VBLexer lexer = GenerateLexer(new StringReader("<")); + Assert.AreEqual(Tokens.LessThan, lexer.NextToken().Kind); + } + + [Test] + public void TestNotEqual() + { + VBLexer lexer = GenerateLexer(new StringReader("<>")); + Assert.AreEqual(Tokens.NotEqual, lexer.NextToken().Kind); + } + + [Test] + public void TestGreaterEqual() + { + VBLexer lexer = GenerateLexer(new StringReader(">=")); + Assert.AreEqual(Tokens.GreaterEqual, lexer.NextToken().Kind); + } + + [Test] + public void TestLessEqual() + { + VBLexer lexer = GenerateLexer(new StringReader("<=")); + Assert.AreEqual(Tokens.LessEqual, lexer.NextToken().Kind); + } + + [Test] + public void TestShiftLeft() + { + VBLexer lexer = GenerateLexer(new StringReader("<<")); + Assert.AreEqual(Tokens.ShiftLeft, lexer.NextToken().Kind); + } + + [Test] + public void TestShiftRight() + { + VBLexer lexer = GenerateLexer(new StringReader(">>")); + Assert.AreEqual(Tokens.ShiftRight, lexer.NextToken().Kind); + } + + [Test] + public void TestPlusAssign() + { + VBLexer lexer = GenerateLexer(new StringReader("+=")); + Assert.AreEqual(Tokens.PlusAssign, lexer.NextToken().Kind); + } + + [Test] + public void TestPowerAssign() + { + VBLexer lexer = GenerateLexer(new StringReader("^=")); + Assert.AreEqual(Tokens.PowerAssign, lexer.NextToken().Kind); + } + + [Test] + public void TestMinusAssign() + { + VBLexer lexer = GenerateLexer(new StringReader("-=")); + Assert.AreEqual(Tokens.MinusAssign, lexer.NextToken().Kind); + } + + [Test] + public void TestTimesAssign() + { + VBLexer lexer = GenerateLexer(new StringReader("*=")); + Assert.AreEqual(Tokens.TimesAssign, lexer.NextToken().Kind); + } + + [Test] + public void TestDivAssign() + { + VBLexer lexer = GenerateLexer(new StringReader("/=")); + Assert.AreEqual(Tokens.DivAssign, lexer.NextToken().Kind); + } + + [Test] + public void TestDivIntegerAssign() + { + VBLexer lexer = GenerateLexer(new StringReader("\\=")); + Assert.AreEqual(Tokens.DivIntegerAssign, lexer.NextToken().Kind); + } + + [Test] + public void TestShiftLeftAssign() + { + VBLexer lexer = GenerateLexer(new StringReader("<<=")); + Assert.AreEqual(Tokens.ShiftLeftAssign, lexer.NextToken().Kind); + } + + [Test] + public void TestShiftRightAssign() + { + VBLexer lexer = GenerateLexer(new StringReader(">>=")); + Assert.AreEqual(Tokens.ShiftRightAssign, lexer.NextToken().Kind); + } + + [Test] + public void TestConcatStringAssign() + { + VBLexer lexer = GenerateLexer(new StringReader("&=")); + Assert.AreEqual(Tokens.ConcatStringAssign, lexer.NextToken().Kind); + } + + [Test] + public void TestColonAssign() + { + VBLexer lexer = GenerateLexer(new StringReader(":=")); + Assert.AreEqual(Tokens.ColonAssign, lexer.NextToken().Kind); + } + + [Test] + public void TestAddHandler() + { + VBLexer lexer = GenerateLexer(new StringReader("AddHandler")); + Assert.AreEqual(Tokens.AddHandler, lexer.NextToken().Kind); + } + + [Test] + public void TestAddressOf() + { + VBLexer lexer = GenerateLexer(new StringReader("AddressOf")); + Assert.AreEqual(Tokens.AddressOf, lexer.NextToken().Kind); + } + + [Test] + public void TestAggregate() + { + VBLexer lexer = GenerateLexer(new StringReader("Aggregate")); + Assert.AreEqual(Tokens.Aggregate, lexer.NextToken().Kind); + } + + [Test] + public void TestAlias() + { + VBLexer lexer = GenerateLexer(new StringReader("Alias")); + Assert.AreEqual(Tokens.Alias, lexer.NextToken().Kind); + } + + [Test] + public void TestAnd() + { + VBLexer lexer = GenerateLexer(new StringReader("And")); + Assert.AreEqual(Tokens.And, lexer.NextToken().Kind); + } + + [Test] + public void TestAndAlso() + { + VBLexer lexer = GenerateLexer(new StringReader("AndAlso")); + Assert.AreEqual(Tokens.AndAlso, lexer.NextToken().Kind); + } + + [Test] + public void TestAnsi() + { + VBLexer lexer = GenerateLexer(new StringReader("Ansi")); + Assert.AreEqual(Tokens.Ansi, lexer.NextToken().Kind); + } + + [Test] + public void TestAs() + { + VBLexer lexer = GenerateLexer(new StringReader("As")); + Assert.AreEqual(Tokens.As, lexer.NextToken().Kind); + } + + [Test] + public void TestAscending() + { + VBLexer lexer = GenerateLexer(new StringReader("Ascending")); + Assert.AreEqual(Tokens.Ascending, lexer.NextToken().Kind); + } + + [Test] + public void TestAssembly() + { + VBLexer lexer = GenerateLexer(new StringReader("Assembly")); + Assert.AreEqual(Tokens.Assembly, lexer.NextToken().Kind); + } + + [Test] + public void TestAuto() + { + VBLexer lexer = GenerateLexer(new StringReader("Auto")); + Assert.AreEqual(Tokens.Auto, lexer.NextToken().Kind); + } + + [Test] + public void TestBinary() + { + VBLexer lexer = GenerateLexer(new StringReader("Binary")); + Assert.AreEqual(Tokens.Binary, lexer.NextToken().Kind); + } + + [Test] + public void TestBoolean() + { + VBLexer lexer = GenerateLexer(new StringReader("Boolean")); + Assert.AreEqual(Tokens.Boolean, lexer.NextToken().Kind); + } + + [Test] + public void TestByRef() + { + VBLexer lexer = GenerateLexer(new StringReader("ByRef")); + Assert.AreEqual(Tokens.ByRef, lexer.NextToken().Kind); + } + + [Test] + public void TestBy() + { + VBLexer lexer = GenerateLexer(new StringReader("By")); + Assert.AreEqual(Tokens.By, lexer.NextToken().Kind); + } + + [Test] + public void TestByte() + { + VBLexer lexer = GenerateLexer(new StringReader("Byte")); + Assert.AreEqual(Tokens.Byte, lexer.NextToken().Kind); + } + + [Test] + public void TestByVal() + { + VBLexer lexer = GenerateLexer(new StringReader("ByVal")); + Assert.AreEqual(Tokens.ByVal, lexer.NextToken().Kind); + } + + [Test] + public void TestCall() + { + VBLexer lexer = GenerateLexer(new StringReader("Call")); + Assert.AreEqual(Tokens.Call, lexer.NextToken().Kind); + } + + [Test] + public void TestCase() + { + VBLexer lexer = GenerateLexer(new StringReader("Case")); + Assert.AreEqual(Tokens.Case, lexer.NextToken().Kind); + } + + [Test] + public void TestCatch() + { + VBLexer lexer = GenerateLexer(new StringReader("Catch")); + Assert.AreEqual(Tokens.Catch, lexer.NextToken().Kind); + } + + [Test] + public void TestCBool() + { + VBLexer lexer = GenerateLexer(new StringReader("CBool")); + Assert.AreEqual(Tokens.CBool, lexer.NextToken().Kind); + } + + [Test] + public void TestCByte() + { + VBLexer lexer = GenerateLexer(new StringReader("CByte")); + Assert.AreEqual(Tokens.CByte, lexer.NextToken().Kind); + } + + [Test] + public void TestCChar() + { + VBLexer lexer = GenerateLexer(new StringReader("CChar")); + Assert.AreEqual(Tokens.CChar, lexer.NextToken().Kind); + } + + [Test] + public void TestCDate() + { + VBLexer lexer = GenerateLexer(new StringReader("CDate")); + Assert.AreEqual(Tokens.CDate, lexer.NextToken().Kind); + } + + [Test] + public void TestCDbl() + { + VBLexer lexer = GenerateLexer(new StringReader("CDbl")); + Assert.AreEqual(Tokens.CDbl, lexer.NextToken().Kind); + } + + [Test] + public void TestCDec() + { + VBLexer lexer = GenerateLexer(new StringReader("CDec")); + Assert.AreEqual(Tokens.CDec, lexer.NextToken().Kind); + } + + [Test] + public void TestChar() + { + VBLexer lexer = GenerateLexer(new StringReader("Char")); + Assert.AreEqual(Tokens.Char, lexer.NextToken().Kind); + } + + [Test] + public void TestCInt() + { + VBLexer lexer = GenerateLexer(new StringReader("CInt")); + Assert.AreEqual(Tokens.CInt, lexer.NextToken().Kind); + } + + [Test] + public void TestClass() + { + VBLexer lexer = GenerateLexer(new StringReader("Class")); + Assert.AreEqual(Tokens.Class, lexer.NextToken().Kind); + } + + [Test] + public void TestCLng() + { + VBLexer lexer = GenerateLexer(new StringReader("CLng")); + Assert.AreEqual(Tokens.CLng, lexer.NextToken().Kind); + } + + [Test] + public void TestCObj() + { + VBLexer lexer = GenerateLexer(new StringReader("CObj")); + Assert.AreEqual(Tokens.CObj, lexer.NextToken().Kind); + } + + [Test] + public void TestCompare() + { + VBLexer lexer = GenerateLexer(new StringReader("Compare")); + Assert.AreEqual(Tokens.Compare, lexer.NextToken().Kind); + } + + [Test] + public void TestConst() + { + VBLexer lexer = GenerateLexer(new StringReader("Const")); + Assert.AreEqual(Tokens.Const, lexer.NextToken().Kind); + } + + [Test] + public void TestContinue() + { + VBLexer lexer = GenerateLexer(new StringReader("Continue")); + Assert.AreEqual(Tokens.Continue, lexer.NextToken().Kind); + } + + [Test] + public void TestCSByte() + { + VBLexer lexer = GenerateLexer(new StringReader("CSByte")); + Assert.AreEqual(Tokens.CSByte, lexer.NextToken().Kind); + } + + [Test] + public void TestCShort() + { + VBLexer lexer = GenerateLexer(new StringReader("CShort")); + Assert.AreEqual(Tokens.CShort, lexer.NextToken().Kind); + } + + [Test] + public void TestCSng() + { + VBLexer lexer = GenerateLexer(new StringReader("CSng")); + Assert.AreEqual(Tokens.CSng, lexer.NextToken().Kind); + } + + [Test] + public void TestCStr() + { + VBLexer lexer = GenerateLexer(new StringReader("CStr")); + Assert.AreEqual(Tokens.CStr, lexer.NextToken().Kind); + } + + [Test] + public void TestCType() + { + VBLexer lexer = GenerateLexer(new StringReader("CType")); + Assert.AreEqual(Tokens.CType, lexer.NextToken().Kind); + } + + [Test] + public void TestCUInt() + { + VBLexer lexer = GenerateLexer(new StringReader("CUInt")); + Assert.AreEqual(Tokens.CUInt, lexer.NextToken().Kind); + } + + [Test] + public void TestCULng() + { + VBLexer lexer = GenerateLexer(new StringReader("CULng")); + Assert.AreEqual(Tokens.CULng, lexer.NextToken().Kind); + } + + [Test] + public void TestCUShort() + { + VBLexer lexer = GenerateLexer(new StringReader("CUShort")); + Assert.AreEqual(Tokens.CUShort, lexer.NextToken().Kind); + } + + [Test] + public void TestCustom() + { + VBLexer lexer = GenerateLexer(new StringReader("Custom")); + Assert.AreEqual(Tokens.Custom, lexer.NextToken().Kind); + } + + [Test] + public void TestDate() + { + VBLexer lexer = GenerateLexer(new StringReader("Date")); + Assert.AreEqual(Tokens.Date, lexer.NextToken().Kind); + } + + [Test] + public void TestDecimal() + { + VBLexer lexer = GenerateLexer(new StringReader("Decimal")); + Assert.AreEqual(Tokens.Decimal, lexer.NextToken().Kind); + } + + [Test] + public void TestDeclare() + { + VBLexer lexer = GenerateLexer(new StringReader("Declare")); + Assert.AreEqual(Tokens.Declare, lexer.NextToken().Kind); + } + + [Test] + public void TestDefault() + { + VBLexer lexer = GenerateLexer(new StringReader("Default")); + Assert.AreEqual(Tokens.Default, lexer.NextToken().Kind); + } + + [Test] + public void TestDelegate() + { + VBLexer lexer = GenerateLexer(new StringReader("Delegate")); + Assert.AreEqual(Tokens.Delegate, lexer.NextToken().Kind); + } + + [Test] + public void TestDescending() + { + VBLexer lexer = GenerateLexer(new StringReader("Descending")); + Assert.AreEqual(Tokens.Descending, lexer.NextToken().Kind); + } + + [Test] + public void TestDim() + { + VBLexer lexer = GenerateLexer(new StringReader("Dim")); + Assert.AreEqual(Tokens.Dim, lexer.NextToken().Kind); + } + + [Test] + public void TestDirectCast() + { + VBLexer lexer = GenerateLexer(new StringReader("DirectCast")); + Assert.AreEqual(Tokens.DirectCast, lexer.NextToken().Kind); + } + + [Test] + public void TestDistinct() + { + VBLexer lexer = GenerateLexer(new StringReader("Distinct")); + Assert.AreEqual(Tokens.Distinct, lexer.NextToken().Kind); + } + + [Test] + public void TestDo() + { + VBLexer lexer = GenerateLexer(new StringReader("Do")); + Assert.AreEqual(Tokens.Do, lexer.NextToken().Kind); + } + + [Test] + public void TestDouble() + { + VBLexer lexer = GenerateLexer(new StringReader("Double")); + Assert.AreEqual(Tokens.Double, lexer.NextToken().Kind); + } + + [Test] + public void TestEach() + { + VBLexer lexer = GenerateLexer(new StringReader("Each")); + Assert.AreEqual(Tokens.Each, lexer.NextToken().Kind); + } + + [Test] + public void TestElse() + { + VBLexer lexer = GenerateLexer(new StringReader("Else")); + Assert.AreEqual(Tokens.Else, lexer.NextToken().Kind); + } + + [Test] + public void TestElseIf() + { + VBLexer lexer = GenerateLexer(new StringReader("ElseIf")); + Assert.AreEqual(Tokens.ElseIf, lexer.NextToken().Kind); + } + + [Test] + public void TestEnd() + { + VBLexer lexer = GenerateLexer(new StringReader("End")); + Assert.AreEqual(Tokens.End, lexer.NextToken().Kind); + } + + [Test] + public void TestEndIf() + { + VBLexer lexer = GenerateLexer(new StringReader("EndIf")); + Assert.AreEqual(Tokens.EndIf, lexer.NextToken().Kind); + } + + [Test] + public void TestEnum() + { + VBLexer lexer = GenerateLexer(new StringReader("Enum")); + Assert.AreEqual(Tokens.Enum, lexer.NextToken().Kind); + } + + [Test] + public void TestEquals() + { + VBLexer lexer = GenerateLexer(new StringReader("Equals")); + Assert.AreEqual(Tokens.Equals, lexer.NextToken().Kind); + } + + [Test] + public void TestErase() + { + VBLexer lexer = GenerateLexer(new StringReader("Erase")); + Assert.AreEqual(Tokens.Erase, lexer.NextToken().Kind); + } + + [Test] + public void TestError() + { + VBLexer lexer = GenerateLexer(new StringReader("Error")); + Assert.AreEqual(Tokens.Error, lexer.NextToken().Kind); + } + + [Test] + public void TestEvent() + { + VBLexer lexer = GenerateLexer(new StringReader("Event")); + Assert.AreEqual(Tokens.Event, lexer.NextToken().Kind); + } + + [Test] + public void TestExit() + { + VBLexer lexer = GenerateLexer(new StringReader("Exit")); + Assert.AreEqual(Tokens.Exit, lexer.NextToken().Kind); + } + + [Test] + public void TestExplicit() + { + VBLexer lexer = GenerateLexer(new StringReader("Explicit")); + Assert.AreEqual(Tokens.Explicit, lexer.NextToken().Kind); + } + + [Test] + public void TestFalse() + { + VBLexer lexer = GenerateLexer(new StringReader("False")); + Assert.AreEqual(Tokens.False, lexer.NextToken().Kind); + } + + [Test] + public void TestFinally() + { + VBLexer lexer = GenerateLexer(new StringReader("Finally")); + Assert.AreEqual(Tokens.Finally, lexer.NextToken().Kind); + } + + [Test] + public void TestFor() + { + VBLexer lexer = GenerateLexer(new StringReader("For")); + Assert.AreEqual(Tokens.For, lexer.NextToken().Kind); + } + + [Test] + public void TestFriend() + { + VBLexer lexer = GenerateLexer(new StringReader("Friend")); + Assert.AreEqual(Tokens.Friend, lexer.NextToken().Kind); + } + + [Test] + public void TestFrom() + { + VBLexer lexer = GenerateLexer(new StringReader("From")); + Assert.AreEqual(Tokens.From, lexer.NextToken().Kind); + } + + [Test] + public void TestFunction() + { + VBLexer lexer = GenerateLexer(new StringReader("Function")); + Assert.AreEqual(Tokens.Function, lexer.NextToken().Kind); + } + + [Test] + public void TestGet() + { + VBLexer lexer = GenerateLexer(new StringReader("Get")); + Assert.AreEqual(Tokens.Get, lexer.NextToken().Kind); + } + + [Test] + public void TestGetType() + { + VBLexer lexer = GenerateLexer(new StringReader("GetType")); + Assert.AreEqual(Tokens.GetType, lexer.NextToken().Kind); + } + + [Test] + public void TestGlobal() + { + VBLexer lexer = GenerateLexer(new StringReader("Global")); + Assert.AreEqual(Tokens.Global, lexer.NextToken().Kind); + } + + [Test] + public void TestGoSub() + { + VBLexer lexer = GenerateLexer(new StringReader("GoSub")); + Assert.AreEqual(Tokens.GoSub, lexer.NextToken().Kind); + } + + [Test] + public void TestGoTo() + { + VBLexer lexer = GenerateLexer(new StringReader("GoTo")); + Assert.AreEqual(Tokens.GoTo, lexer.NextToken().Kind); + } + + [Test] + public void TestGroup() + { + VBLexer lexer = GenerateLexer(new StringReader("Group")); + Assert.AreEqual(Tokens.Group, lexer.NextToken().Kind); + } + + [Test] + public void TestHandles() + { + VBLexer lexer = GenerateLexer(new StringReader("Handles")); + Assert.AreEqual(Tokens.Handles, lexer.NextToken().Kind); + } + + [Test] + public void TestIf() + { + VBLexer lexer = GenerateLexer(new StringReader("If")); + Assert.AreEqual(Tokens.If, lexer.NextToken().Kind); + } + + [Test] + public void TestImplements() + { + VBLexer lexer = GenerateLexer(new StringReader("Implements")); + Assert.AreEqual(Tokens.Implements, lexer.NextToken().Kind); + } + + [Test] + public void TestImports() + { + VBLexer lexer = GenerateLexer(new StringReader("Imports")); + Assert.AreEqual(Tokens.Imports, lexer.NextToken().Kind); + } + + [Test] + public void TestIn() + { + VBLexer lexer = GenerateLexer(new StringReader("In")); + Assert.AreEqual(Tokens.In, lexer.NextToken().Kind); + } + + [Test] + public void TestInfer() + { + VBLexer lexer = GenerateLexer(new StringReader("Infer")); + Assert.AreEqual(Tokens.Infer, lexer.NextToken().Kind); + } + + [Test] + public void TestInherits() + { + VBLexer lexer = GenerateLexer(new StringReader("Inherits")); + Assert.AreEqual(Tokens.Inherits, lexer.NextToken().Kind); + } + + [Test] + public void TestInteger() + { + VBLexer lexer = GenerateLexer(new StringReader("Integer")); + Assert.AreEqual(Tokens.Integer, lexer.NextToken().Kind); + } + + [Test] + public void TestInterface() + { + VBLexer lexer = GenerateLexer(new StringReader("Interface")); + Assert.AreEqual(Tokens.Interface, lexer.NextToken().Kind); + } + + [Test] + public void TestInto() + { + VBLexer lexer = GenerateLexer(new StringReader("Into")); + Assert.AreEqual(Tokens.Into, lexer.NextToken().Kind); + } + + [Test] + public void TestIs() + { + VBLexer lexer = GenerateLexer(new StringReader("Is")); + Assert.AreEqual(Tokens.Is, lexer.NextToken().Kind); + } + + [Test] + public void TestIsNot() + { + VBLexer lexer = GenerateLexer(new StringReader("IsNot")); + Assert.AreEqual(Tokens.IsNot, lexer.NextToken().Kind); + } + + [Test] + public void TestJoin() + { + VBLexer lexer = GenerateLexer(new StringReader("Join")); + Assert.AreEqual(Tokens.Join, lexer.NextToken().Kind); + } + + [Test] + public void TestKey() + { + VBLexer lexer = GenerateLexer(new StringReader("Key")); + Assert.AreEqual(Tokens.Key, lexer.NextToken().Kind); + } + + [Test] + public void TestLet() + { + VBLexer lexer = GenerateLexer(new StringReader("Let")); + Assert.AreEqual(Tokens.Let, lexer.NextToken().Kind); + } + + [Test] + public void TestLib() + { + VBLexer lexer = GenerateLexer(new StringReader("Lib")); + Assert.AreEqual(Tokens.Lib, lexer.NextToken().Kind); + } + + [Test] + public void TestLike() + { + VBLexer lexer = GenerateLexer(new StringReader("Like")); + Assert.AreEqual(Tokens.Like, lexer.NextToken().Kind); + } + + [Test] + public void TestLong() + { + VBLexer lexer = GenerateLexer(new StringReader("Long")); + Assert.AreEqual(Tokens.Long, lexer.NextToken().Kind); + } + + [Test] + public void TestLoop() + { + VBLexer lexer = GenerateLexer(new StringReader("Loop")); + Assert.AreEqual(Tokens.Loop, lexer.NextToken().Kind); + } + + [Test] + public void TestMe() + { + VBLexer lexer = GenerateLexer(new StringReader("Me")); + Assert.AreEqual(Tokens.Me, lexer.NextToken().Kind); + } + + [Test] + public void TestMod() + { + VBLexer lexer = GenerateLexer(new StringReader("Mod")); + Assert.AreEqual(Tokens.Mod, lexer.NextToken().Kind); + } + + [Test] + public void TestModule() + { + VBLexer lexer = GenerateLexer(new StringReader("Module")); + Assert.AreEqual(Tokens.Module, lexer.NextToken().Kind); + } + + [Test] + public void TestMustInherit() + { + VBLexer lexer = GenerateLexer(new StringReader("MustInherit")); + Assert.AreEqual(Tokens.MustInherit, lexer.NextToken().Kind); + } + + [Test] + public void TestMustOverride() + { + VBLexer lexer = GenerateLexer(new StringReader("MustOverride")); + Assert.AreEqual(Tokens.MustOverride, lexer.NextToken().Kind); + } + + [Test] + public void TestMyBase() + { + VBLexer lexer = GenerateLexer(new StringReader("MyBase")); + Assert.AreEqual(Tokens.MyBase, lexer.NextToken().Kind); + } + + [Test] + public void TestMyClass() + { + VBLexer lexer = GenerateLexer(new StringReader("MyClass")); + Assert.AreEqual(Tokens.MyClass, lexer.NextToken().Kind); + } + + [Test] + public void TestNamespace() + { + VBLexer lexer = GenerateLexer(new StringReader("Namespace")); + Assert.AreEqual(Tokens.Namespace, lexer.NextToken().Kind); + } + + [Test] + public void TestNarrowing() + { + VBLexer lexer = GenerateLexer(new StringReader("Narrowing")); + Assert.AreEqual(Tokens.Narrowing, lexer.NextToken().Kind); + } + + [Test] + public void TestNew() + { + VBLexer lexer = GenerateLexer(new StringReader("New")); + Assert.AreEqual(Tokens.New, lexer.NextToken().Kind); + } + + [Test] + public void TestNext() + { + VBLexer lexer = GenerateLexer(new StringReader("Next")); + Assert.AreEqual(Tokens.Next, lexer.NextToken().Kind); + } + + [Test] + public void TestNot() + { + VBLexer lexer = GenerateLexer(new StringReader("Not")); + Assert.AreEqual(Tokens.Not, lexer.NextToken().Kind); + } + + [Test] + public void TestNothing() + { + VBLexer lexer = GenerateLexer(new StringReader("Nothing")); + Assert.AreEqual(Tokens.Nothing, lexer.NextToken().Kind); + } + + [Test] + public void TestNotInheritable() + { + VBLexer lexer = GenerateLexer(new StringReader("NotInheritable")); + Assert.AreEqual(Tokens.NotInheritable, lexer.NextToken().Kind); + } + + [Test] + public void TestNotOverridable() + { + VBLexer lexer = GenerateLexer(new StringReader("NotOverridable")); + Assert.AreEqual(Tokens.NotOverridable, lexer.NextToken().Kind); + } + + [Test] + public void TestObject() + { + VBLexer lexer = GenerateLexer(new StringReader("Object")); + Assert.AreEqual(Tokens.Object, lexer.NextToken().Kind); + } + + [Test] + public void TestOf() + { + VBLexer lexer = GenerateLexer(new StringReader("Of")); + Assert.AreEqual(Tokens.Of, lexer.NextToken().Kind); + } + + [Test] + public void TestOff() + { + VBLexer lexer = GenerateLexer(new StringReader("Off")); + Assert.AreEqual(Tokens.Off, lexer.NextToken().Kind); + } + + [Test] + public void TestOn() + { + VBLexer lexer = GenerateLexer(new StringReader("On")); + Assert.AreEqual(Tokens.On, lexer.NextToken().Kind); + } + + [Test] + public void TestOperator() + { + VBLexer lexer = GenerateLexer(new StringReader("Operator")); + Assert.AreEqual(Tokens.Operator, lexer.NextToken().Kind); + } + + [Test] + public void TestOption() + { + VBLexer lexer = GenerateLexer(new StringReader("Option")); + Assert.AreEqual(Tokens.Option, lexer.NextToken().Kind); + } + + [Test] + public void TestOptional() + { + VBLexer lexer = GenerateLexer(new StringReader("Optional")); + Assert.AreEqual(Tokens.Optional, lexer.NextToken().Kind); + } + + [Test] + public void TestOr() + { + VBLexer lexer = GenerateLexer(new StringReader("Or")); + Assert.AreEqual(Tokens.Or, lexer.NextToken().Kind); + } + + [Test] + public void TestOrder() + { + VBLexer lexer = GenerateLexer(new StringReader("Order")); + Assert.AreEqual(Tokens.Order, lexer.NextToken().Kind); + } + + [Test] + public void TestOrElse() + { + VBLexer lexer = GenerateLexer(new StringReader("OrElse")); + Assert.AreEqual(Tokens.OrElse, lexer.NextToken().Kind); + } + + [Test] + public void TestOut() + { + VBLexer lexer = GenerateLexer(new StringReader("Out")); + Assert.AreEqual(Tokens.Out, lexer.NextToken().Kind); + } + + [Test] + public void TestOverloads() + { + VBLexer lexer = GenerateLexer(new StringReader("Overloads")); + Assert.AreEqual(Tokens.Overloads, lexer.NextToken().Kind); + } + + [Test] + public void TestOverridable() + { + VBLexer lexer = GenerateLexer(new StringReader("Overridable")); + Assert.AreEqual(Tokens.Overridable, lexer.NextToken().Kind); + } + + [Test] + public void TestOverrides() + { + VBLexer lexer = GenerateLexer(new StringReader("Overrides")); + Assert.AreEqual(Tokens.Overrides, lexer.NextToken().Kind); + } + + [Test] + public void TestParamArray() + { + VBLexer lexer = GenerateLexer(new StringReader("ParamArray")); + Assert.AreEqual(Tokens.ParamArray, lexer.NextToken().Kind); + } + + [Test] + public void TestPartial() + { + VBLexer lexer = GenerateLexer(new StringReader("Partial")); + Assert.AreEqual(Tokens.Partial, lexer.NextToken().Kind); + } + + [Test] + public void TestPreserve() + { + VBLexer lexer = GenerateLexer(new StringReader("Preserve")); + Assert.AreEqual(Tokens.Preserve, lexer.NextToken().Kind); + } + + [Test] + public void TestPrivate() + { + VBLexer lexer = GenerateLexer(new StringReader("Private")); + Assert.AreEqual(Tokens.Private, lexer.NextToken().Kind); + } + + [Test] + public void TestProperty() + { + VBLexer lexer = GenerateLexer(new StringReader("Property")); + Assert.AreEqual(Tokens.Property, lexer.NextToken().Kind); + } + + [Test] + public void TestProtected() + { + VBLexer lexer = GenerateLexer(new StringReader("Protected")); + Assert.AreEqual(Tokens.Protected, lexer.NextToken().Kind); + } + + [Test] + public void TestPublic() + { + VBLexer lexer = GenerateLexer(new StringReader("Public")); + Assert.AreEqual(Tokens.Public, lexer.NextToken().Kind); + } + + [Test] + public void TestRaiseEvent() + { + VBLexer lexer = GenerateLexer(new StringReader("RaiseEvent")); + Assert.AreEqual(Tokens.RaiseEvent, lexer.NextToken().Kind); + } + + [Test] + public void TestReadOnly() + { + VBLexer lexer = GenerateLexer(new StringReader("ReadOnly")); + Assert.AreEqual(Tokens.ReadOnly, lexer.NextToken().Kind); + } + + [Test] + public void TestReDim() + { + VBLexer lexer = GenerateLexer(new StringReader("ReDim")); + Assert.AreEqual(Tokens.ReDim, lexer.NextToken().Kind); + } + + [Test] + public void TestRemoveHandler() + { + VBLexer lexer = GenerateLexer(new StringReader("RemoveHandler")); + Assert.AreEqual(Tokens.RemoveHandler, lexer.NextToken().Kind); + } + + [Test] + public void TestResume() + { + VBLexer lexer = GenerateLexer(new StringReader("Resume")); + Assert.AreEqual(Tokens.Resume, lexer.NextToken().Kind); + } + + [Test] + public void TestReturn() + { + VBLexer lexer = GenerateLexer(new StringReader("Return")); + Assert.AreEqual(Tokens.Return, lexer.NextToken().Kind); + } + + [Test] + public void TestSByte() + { + VBLexer lexer = GenerateLexer(new StringReader("SByte")); + Assert.AreEqual(Tokens.SByte, lexer.NextToken().Kind); + } + + [Test] + public void TestSelect() + { + VBLexer lexer = GenerateLexer(new StringReader("Select")); + Assert.AreEqual(Tokens.Select, lexer.NextToken().Kind); + } + + [Test] + public void TestSet() + { + VBLexer lexer = GenerateLexer(new StringReader("Set")); + Assert.AreEqual(Tokens.Set, lexer.NextToken().Kind); + } + + [Test] + public void TestShadows() + { + VBLexer lexer = GenerateLexer(new StringReader("Shadows")); + Assert.AreEqual(Tokens.Shadows, lexer.NextToken().Kind); + } + + [Test] + public void TestShared() + { + VBLexer lexer = GenerateLexer(new StringReader("Shared")); + Assert.AreEqual(Tokens.Shared, lexer.NextToken().Kind); + } + + [Test] + public void TestShort() + { + VBLexer lexer = GenerateLexer(new StringReader("Short")); + Assert.AreEqual(Tokens.Short, lexer.NextToken().Kind); + } + + [Test] + public void TestSingle() + { + VBLexer lexer = GenerateLexer(new StringReader("Single")); + Assert.AreEqual(Tokens.Single, lexer.NextToken().Kind); + } + + [Test] + public void TestSkip() + { + VBLexer lexer = GenerateLexer(new StringReader("Skip")); + Assert.AreEqual(Tokens.Skip, lexer.NextToken().Kind); + } + + [Test] + public void TestStatic() + { + VBLexer lexer = GenerateLexer(new StringReader("Static")); + Assert.AreEqual(Tokens.Static, lexer.NextToken().Kind); + } + + [Test] + public void TestStep() + { + VBLexer lexer = GenerateLexer(new StringReader("Step")); + Assert.AreEqual(Tokens.Step, lexer.NextToken().Kind); + } + + [Test] + public void TestStop() + { + VBLexer lexer = GenerateLexer(new StringReader("Stop")); + Assert.AreEqual(Tokens.Stop, lexer.NextToken().Kind); + } + + [Test] + public void TestStrict() + { + VBLexer lexer = GenerateLexer(new StringReader("Strict")); + Assert.AreEqual(Tokens.Strict, lexer.NextToken().Kind); + } + + [Test] + public void TestString() + { + VBLexer lexer = GenerateLexer(new StringReader("String")); + Assert.AreEqual(Tokens.String, lexer.NextToken().Kind); + } + + [Test] + public void TestStructure() + { + VBLexer lexer = GenerateLexer(new StringReader("Structure")); + Assert.AreEqual(Tokens.Structure, lexer.NextToken().Kind); + } + + [Test] + public void TestSub() + { + VBLexer lexer = GenerateLexer(new StringReader("Sub")); + Assert.AreEqual(Tokens.Sub, lexer.NextToken().Kind); + } + + [Test] + public void TestSyncLock() + { + VBLexer lexer = GenerateLexer(new StringReader("SyncLock")); + Assert.AreEqual(Tokens.SyncLock, lexer.NextToken().Kind); + } + + [Test] + public void TestTake() + { + VBLexer lexer = GenerateLexer(new StringReader("Take")); + Assert.AreEqual(Tokens.Take, lexer.NextToken().Kind); + } + + [Test] + public void TestText() + { + VBLexer lexer = GenerateLexer(new StringReader("Text")); + Assert.AreEqual(Tokens.Text, lexer.NextToken().Kind); + } + + [Test] + public void TestThen() + { + VBLexer lexer = GenerateLexer(new StringReader("Then")); + Assert.AreEqual(Tokens.Then, lexer.NextToken().Kind); + } + + [Test] + public void TestThrow() + { + VBLexer lexer = GenerateLexer(new StringReader("Throw")); + Assert.AreEqual(Tokens.Throw, lexer.NextToken().Kind); + } + + [Test] + public void TestTo() + { + VBLexer lexer = GenerateLexer(new StringReader("To")); + Assert.AreEqual(Tokens.To, lexer.NextToken().Kind); + } + + [Test] + public void TestTrue() + { + VBLexer lexer = GenerateLexer(new StringReader("True")); + Assert.AreEqual(Tokens.True, lexer.NextToken().Kind); + } + + [Test] + public void TestTry() + { + VBLexer lexer = GenerateLexer(new StringReader("Try")); + Assert.AreEqual(Tokens.Try, lexer.NextToken().Kind); + } + + [Test] + public void TestTryCast() + { + VBLexer lexer = GenerateLexer(new StringReader("TryCast")); + Assert.AreEqual(Tokens.TryCast, lexer.NextToken().Kind); + } + + [Test] + public void TestTypeOf() + { + VBLexer lexer = GenerateLexer(new StringReader("TypeOf")); + Assert.AreEqual(Tokens.TypeOf, lexer.NextToken().Kind); + } + + [Test] + public void TestUInteger() + { + VBLexer lexer = GenerateLexer(new StringReader("UInteger")); + Assert.AreEqual(Tokens.UInteger, lexer.NextToken().Kind); + } + + [Test] + public void TestULong() + { + VBLexer lexer = GenerateLexer(new StringReader("ULong")); + Assert.AreEqual(Tokens.ULong, lexer.NextToken().Kind); + } + + [Test] + public void TestUnicode() + { + VBLexer lexer = GenerateLexer(new StringReader("Unicode")); + Assert.AreEqual(Tokens.Unicode, lexer.NextToken().Kind); + } + + [Test] + public void TestUntil() + { + VBLexer lexer = GenerateLexer(new StringReader("Until")); + Assert.AreEqual(Tokens.Until, lexer.NextToken().Kind); + } + + [Test] + public void TestUShort() + { + VBLexer lexer = GenerateLexer(new StringReader("UShort")); + Assert.AreEqual(Tokens.UShort, lexer.NextToken().Kind); + } + + [Test] + public void TestUsing() + { + VBLexer lexer = GenerateLexer(new StringReader("Using")); + Assert.AreEqual(Tokens.Using, lexer.NextToken().Kind); + } + + [Test] + public void TestVariant() + { + VBLexer lexer = GenerateLexer(new StringReader("Variant")); + Assert.AreEqual(Tokens.Variant, lexer.NextToken().Kind); + } + + [Test] + public void TestWend() + { + VBLexer lexer = GenerateLexer(new StringReader("Wend")); + Assert.AreEqual(Tokens.Wend, lexer.NextToken().Kind); + } + + [Test] + public void TestWhen() + { + VBLexer lexer = GenerateLexer(new StringReader("When")); + Assert.AreEqual(Tokens.When, lexer.NextToken().Kind); + } + + [Test] + public void TestWhere() + { + VBLexer lexer = GenerateLexer(new StringReader("Where")); + Assert.AreEqual(Tokens.Where, lexer.NextToken().Kind); + } + + [Test] + public void TestWhile() + { + VBLexer lexer = GenerateLexer(new StringReader("While")); + Assert.AreEqual(Tokens.While, lexer.NextToken().Kind); + } + + [Test] + public void TestWidening() + { + VBLexer lexer = GenerateLexer(new StringReader("Widening")); + Assert.AreEqual(Tokens.Widening, lexer.NextToken().Kind); + } + + [Test] + public void TestWith() + { + VBLexer lexer = GenerateLexer(new StringReader("With")); + Assert.AreEqual(Tokens.With, lexer.NextToken().Kind); + } + + [Test] + public void TestWithEvents() + { + VBLexer lexer = GenerateLexer(new StringReader("WithEvents")); + Assert.AreEqual(Tokens.WithEvents, lexer.NextToken().Kind); + } + + [Test] + public void TestWriteOnly() + { + VBLexer lexer = GenerateLexer(new StringReader("WriteOnly")); + Assert.AreEqual(Tokens.WriteOnly, lexer.NextToken().Kind); + } + + [Test] + public void TestXor() + { + VBLexer lexer = GenerateLexer(new StringReader("Xor")); + Assert.AreEqual(Tokens.Xor, lexer.NextToken().Kind); + } + + [Test] + public void TestGetXmlNamespace() + { + VBLexer lexer = GenerateLexer(new StringReader("GetXmlNamespace")); + Assert.AreEqual(Tokens.GetXmlNamespace, lexer.NextToken().Kind); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Lexer/LiteralsTests.cs b/ICSharpCode.NRefactory.VB.Tests/Lexer/LiteralsTests.cs new file mode 100644 index 000000000..c1f32fbaf --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Lexer/LiteralsTests.cs @@ -0,0 +1,194 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using ICSharpCode.NRefactory.VB.Parser; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Lexer +{ + [TestFixture] + public sealed class LiteralsTests + { + VBLexer GenerateLexer(StringReader sr) + { + return ParserFactory.CreateLexer(sr); + } + + Token GetSingleToken(string text) + { + VBLexer lexer = GenerateLexer(new StringReader(text)); + Token t = lexer.NextToken(); + Assert.AreEqual(Tokens.EOL, lexer.NextToken().Kind, "Tokens.EOL"); + Assert.AreEqual(Tokens.EOF, lexer.NextToken().Kind, "Tokens.EOF"); + Assert.AreEqual("", lexer.Errors.ErrorOutput); + return t; + } + + void CheckToken(string text, int tokenType, object val) + { + Token t = GetSingleToken(text); + Assert.AreEqual(tokenType, t.Kind, "Tokens.Literal"); + Assert.IsNotNull(t.LiteralValue, "literalValue is null"); + Assert.AreEqual(val.GetType(), t.LiteralValue.GetType(), "literalValue.GetType()"); + Assert.AreEqual(val, t.LiteralValue, "literalValue"); + } + + [Test] + public void TestSingleDigit() + { + CheckToken("5", Tokens.LiteralInteger, 5); + } + + [Test] + public void TestZero() + { + CheckToken("0", Tokens.LiteralInteger, 0); + } + + [Test] + public void TestInteger() + { + CheckToken("15", Tokens.LiteralInteger, 15); + CheckToken("8581", Tokens.LiteralInteger, 8581); + } + + [Test] + public void InvalidTypeCharacter() + { + // just check that we don't get exceptions: + GenerateLexer(new StringReader(".5s")).NextToken(); + GenerateLexer(new StringReader(".5ul")).NextToken(); + } + + [Test] + public void TestHexadecimalInteger() + { + CheckToken("&H10", Tokens.LiteralInteger, 0x10); + CheckToken("&H10&", Tokens.LiteralInteger, (long)0x10); + CheckToken("&h3ff%", Tokens.LiteralInteger, 0x3ff); + CheckToken("&h8000s", Tokens.LiteralInteger, short.MinValue); + CheckToken("&h8000us", Tokens.LiteralInteger, (ushort)0x8000); + CheckToken("&HffffFFFF", Tokens.LiteralInteger, -1); + CheckToken("&HffffFFFF%", Tokens.LiteralInteger, -1); + CheckToken("&HffffFFFFui", Tokens.LiteralInteger, uint.MaxValue); + CheckToken("&HffffFFFF&", Tokens.LiteralInteger, (long)uint.MaxValue); + } + + [Test] + public void TestLongHexadecimalInteger() + { + CheckToken("&H4244636f446c6d58", Tokens.LiteralInteger, 0x4244636f446c6d58); + CheckToken("&hf244636f446c6d58", Tokens.LiteralInteger, -989556688574190248); + CheckToken("&hf244636f446c6d58&", Tokens.LiteralInteger, -989556688574190248); + CheckToken("&hf244636f446c6d58ul", Tokens.LiteralInteger, 0xf244636f446c6d58); + } + + [Test] + public void InvalidHexadecimalInteger() + { + // just check that we don't get exceptions: + GenerateLexer(new StringReader("&H")).NextToken(); + // >ulong.MaxValue + GenerateLexer(new StringReader("&hff244636f446c6d58")).NextToken(); + // needs an ulong, but "i" postfix specified integer + GenerateLexer(new StringReader("&hf244636f446c6d58i")).NextToken(); + GenerateLexer(new StringReader("&hf244636f446c6d58ui")).NextToken(); + } + + [Test] + public void TestIncompleteHexadecimal() + { + VBLexer lexer = GenerateLexer(new StringReader("&H\r\nabc")); + Token t = lexer.NextToken(); + Assert.AreEqual(Tokens.LiteralInteger, t.Kind); + Assert.AreEqual(0, (int)t.LiteralValue); + Assert.AreEqual(Tokens.EOL, lexer.NextToken().Kind, "Tokens.EOL (1)"); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind, "Tokens.Identifier"); + Assert.AreEqual(Tokens.EOL, lexer.NextToken().Kind, "Tokens.EOL (2)"); + Assert.AreEqual(Tokens.EOF, lexer.NextToken().Kind, "Tokens.EOF"); + Assert.AreNotEqual("", lexer.Errors.ErrorOutput); + } + + [Test] + public void TestStringLiterals() + { + CheckToken("\"\"", Tokens.LiteralString, ""); + CheckToken("\"Hello, World!\"", Tokens.LiteralString, "Hello, World!"); + CheckToken("\"\"\"\"", Tokens.LiteralString, "\""); + } + + [Test] + public void TestCharacterLiterals() + { + CheckToken("\" \"c", Tokens.LiteralCharacter, ' '); + CheckToken("\"!\"c", Tokens.LiteralCharacter, '!'); + CheckToken("\"\"\"\"c", Tokens.LiteralCharacter, '"'); + } + + [Test] + public void TestDateLiterals() + { + CheckToken("# 8/23/1970 #", Tokens.LiteralDate, new DateTime(1970, 8, 23, 0, 0, 0)); + CheckToken("#8/23/1970#", Tokens.LiteralDate, new DateTime(1970, 8, 23, 0, 0, 0)); + CheckToken("# 8/23/1970 3:45:39AM #", Tokens.LiteralDate, new DateTime(1970, 8, 23, 3, 45, 39)); + CheckToken("# 3:45:39AM #", Tokens.LiteralDate, new DateTime(1, 1, 1, 3, 45, 39)); + CheckToken("# 3:45:39 PM #", Tokens.LiteralDate, new DateTime(1, 1, 1, 15, 45, 39)); + CheckToken("# 3:45:39 #", Tokens.LiteralDate, new DateTime(1, 1, 1, 3, 45, 39)); + CheckToken("# 13:45:39 #", Tokens.LiteralDate, new DateTime(1, 1, 1, 13, 45, 39)); + CheckToken("# 1AM #", Tokens.LiteralDate, new DateTime(1, 1, 1, 1, 0, 0)); + } + + [Test] + public void TestDouble() + { + CheckToken("1.0", Tokens.LiteralDouble, 1.0); + CheckToken("1.1", Tokens.LiteralDouble, 1.1); + CheckToken("2e-5", Tokens.LiteralDouble, 2e-5); + CheckToken("2.0e-5", Tokens.LiteralDouble, 2e-5); + CheckToken("2e5", Tokens.LiteralDouble, 2e5); + CheckToken("2.2e5", Tokens.LiteralDouble, 2.2e5); + CheckToken("2e+5", Tokens.LiteralDouble, 2e5); + CheckToken("2.2e+5", Tokens.LiteralDouble, 2.2e5); + + CheckToken("1r", Tokens.LiteralDouble, 1.0); + CheckToken("1.0r", Tokens.LiteralDouble, 1.0); + CheckToken("1.1r", Tokens.LiteralDouble, 1.1); + CheckToken("2e-5r", Tokens.LiteralDouble, 2e-5); + CheckToken("2.0e-5r", Tokens.LiteralDouble, 2e-5); + CheckToken("2e5r", Tokens.LiteralDouble, 2e5); + CheckToken("2.2e5r", Tokens.LiteralDouble, 2.2e5); + CheckToken("2e+5r", Tokens.LiteralDouble, 2e5); + CheckToken("2.2e+5r", Tokens.LiteralDouble, 2.2e5); + } + + [Test] + public void TestSingle() + { + CheckToken("1f", Tokens.LiteralSingle, 1.0f); + CheckToken("1.0f", Tokens.LiteralSingle, 1.0f); + CheckToken("1.1f", Tokens.LiteralSingle, 1.1f); + CheckToken("2e-5f", Tokens.LiteralSingle, 2e-5f); + CheckToken("2.0e-5f", Tokens.LiteralSingle, 2e-5f); + CheckToken("2e5f", Tokens.LiteralSingle, 2e5f); + CheckToken("2.2e5f", Tokens.LiteralSingle, 2.2e5f); + CheckToken("2e+5f", Tokens.LiteralSingle, 2e5f); + CheckToken("2.2e+5f", Tokens.LiteralSingle, 2.2e5f); + } + + [Test] + public void TestDecimal() + { + CheckToken("1d", Tokens.LiteralDecimal, 1m); + CheckToken("1.0d", Tokens.LiteralDecimal, 1.0m); + CheckToken("1.1d", Tokens.LiteralDecimal, 1.1m); + CheckToken("2e-5d", Tokens.LiteralDecimal, 2e-5m); + CheckToken("2.0e-5d", Tokens.LiteralDecimal, 2.0e-5m); + CheckToken("2e5d", Tokens.LiteralDecimal, 2e5m); + CheckToken("2.2e5d", Tokens.LiteralDecimal, 2.2e5m); + CheckToken("2e+5d", Tokens.LiteralDecimal, 2e5m); + CheckToken("2.2e+5d", Tokens.LiteralDecimal, 2.2e5m); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Lexer/TokenTests.cs b/ICSharpCode.NRefactory.VB.Tests/Lexer/TokenTests.cs new file mode 100644 index 000000000..5b21fe89a --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Lexer/TokenTests.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.VB.Parser; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Lexer +{ + [TestFixture] + public class TokenTests + { + [Test] + public void TokenToStringDoesNotThrowException() + { + Assert.DoesNotThrow( + () => { + string text = new Token(71, 1, 1).ToString(); + } + ); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Lexer/XmlModeLexerTests.cs b/ICSharpCode.NRefactory.VB.Tests/Lexer/XmlModeLexerTests.cs new file mode 100644 index 000000000..e582bd2a1 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Lexer/XmlModeLexerTests.cs @@ -0,0 +1,993 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using ICSharpCode.NRefactory.VB; +using ICSharpCode.NRefactory.VB.Parser; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Lexer +{ + [TestFixture] + public class XmlModeLexerTests + { + #region Xml Tests + [Test] + public void TagWithContent() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("Dim x = Hello World"))); + + CheckHead(lexer); + + Assert.AreEqual(Tokens.Dim, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Assign, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlOpenTag, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlCloseTag, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlContent, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlOpenEndTag, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlCloseTag, lexer.NextToken().Kind); + + CheckFoot(lexer); + } + + [Test] + public void HtmlText() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("Dim x =

Title

" + + "

test test
test

"))); + + CheckHead(lexer); + + Assert.AreEqual(Tokens.Dim, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Assign, lexer.NextToken().Kind); + + //
+ Assert.AreEqual(Tokens.XmlOpenTag, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlCloseTag, lexer.NextToken().Kind); + + //

+ Assert.AreEqual(Tokens.XmlOpenTag, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlCloseTag, lexer.NextToken().Kind); + + // Title + Assert.AreEqual(Tokens.XmlContent, lexer.NextToken().Kind); + + //

+ Assert.AreEqual(Tokens.XmlOpenEndTag, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlCloseTag, lexer.NextToken().Kind); + + //

+ Assert.AreEqual(Tokens.XmlOpenTag, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlCloseTag, lexer.NextToken().Kind); + + // test test + Assert.AreEqual(Tokens.XmlContent, lexer.NextToken().Kind); + + //
+ Assert.AreEqual(Tokens.XmlOpenTag, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlCloseTagEmptyElement, lexer.NextToken().Kind); + + // test + Assert.AreEqual(Tokens.XmlContent, lexer.NextToken().Kind); + + //

+ Assert.AreEqual(Tokens.XmlOpenEndTag, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlCloseTag, lexer.NextToken().Kind); + + //
+ Assert.AreEqual(Tokens.XmlOpenEndTag, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.Identifier, lexer.NextToken().Kind); + Assert.AreEqual(Tokens.XmlCloseTag, lexer.NextToken().Kind); + + CheckFoot(lexer); + } + + [Test] + public void XmlLiteralsExample1() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("Dim xml = \n" + + " \n" + + " Shrimp Cocktail\n" + + " Escargot\n" + + " \n" + + " \n" + + " Filet Mignon\n" + + " Garlic Potatoes\n" + + " Broccoli\n" + + " \n" + + " \n" + + " Chocolate Cheesecake\n" + + " \n" + + " "))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, + // + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // Shrimp Cocktail + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // Escargot + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // + Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // Filet Mignon + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // Garlic Potatoes + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // Broccoli + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // + Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // Chocolate Cheesecake + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // + Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + // whitespaces + Tokens.XmlContent, + // + Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag + ); + + CheckFoot(lexer); + } + + [Test] + public void SimpleXmlWithComments() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(@"Dim x = + + + + + + + "))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, + Tokens.XmlProcessingInstruction, Tokens.XmlContent, Tokens.XmlComment, Tokens.XmlContent, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, + Tokens.XmlContent, Tokens.XmlComment, Tokens.XmlContent, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, + Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlComment, Tokens.XmlComment, Tokens.XmlProcessingInstruction); + + CheckFoot(lexer); + } + + [Test] + public void SimpleEmptyTag() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("Dim x = "))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement); + + CheckFoot(lexer); + } + + [Test] + public void SimpleTag() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("Dim x = "))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.XmlOpenTag, + Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlOpenEndTag, + Tokens.Identifier, Tokens.XmlCloseTag); + + CheckFoot(lexer); + } + + [Test] + public void XmlImport() + { + string code = @"Imports System +Imports System.Linq + +Imports +Imports + +Class TestClass + Sub TestSub() + Dim xml = + + 1. Cell + + + End Sub +End Class"; + + VBLexer lexer = GenerateLexer(new StringReader(code)); + + CheckTokens(lexer, Tokens.Imports, Tokens.Identifier, Tokens.EOL, + Tokens.Imports, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.EOL, + Tokens.Imports, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.XmlCloseTag, Tokens.EOL, + Tokens.Imports, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.XmlCloseTag, Tokens.EOL, + Tokens.Class, Tokens.Identifier, Tokens.EOL, Tokens.Sub, Tokens.Identifier, Tokens.OpenParenthesis, Tokens.CloseParenthesis, Tokens.EOL, + Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, + Tokens.XmlContent, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, + Tokens.XmlContent, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + Tokens.EOL, Tokens.End, Tokens.Sub, Tokens.EOL, Tokens.End, Tokens.Class + ); + } + + [Test] + public void CDataSection() + { + string xml = @"Dim xml = + "; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(xml))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, // 2 + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, // 6 + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, // 10 + Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, // 14 + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, // 18 + Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, // 22 + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.XmlCloseTag, // 28 + Tokens.XmlContent, Tokens.XmlCData, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, // 34 + Tokens.XmlContent, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.XmlCloseTag, + Tokens.XmlContent, Tokens.XmlCData, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, + Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag + ); + + + CheckFoot(lexer); + } + + [Test] + public void InlineVB() + { + string code = @"Dim xml = + + + <%= From m In menu _ + Where m.Course = ""appetizer"" _ + Select <%= m.Food %> _ + %> + + + <%= From m In menu _ + Where m.Course = ""main"" _ + Select <%= m.Food %> _ + %> + + + <%= From m In menu _ + Where m.Course = ""dessert"" _ + Select <%= m.Food %> _ + %> + + "; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(code))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.XmlProcessingInstruction, Tokens.XmlContent, + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenTag, Tokens.Identifier, + Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlStartInlineVB, + Tokens.From, Tokens.Identifier, Tokens.In, Tokens.Identifier, Tokens.Where, Tokens.Identifier, Tokens.Dot, + Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.Select, Tokens.XmlOpenTag, Tokens.Identifier, + Tokens.XmlCloseTag, Tokens.XmlStartInlineVB, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.XmlEndInlineVB, + Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlEndInlineVB, Tokens.XmlContent, Tokens.XmlOpenEndTag, + Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenTag, Tokens.Identifier, + Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlStartInlineVB, + Tokens.From, Tokens.Identifier, Tokens.In, Tokens.Identifier, Tokens.Where, Tokens.Identifier, Tokens.Dot, + Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.Select, Tokens.XmlOpenTag, Tokens.Identifier, + Tokens.XmlCloseTag, Tokens.XmlStartInlineVB, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.XmlEndInlineVB, + Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlEndInlineVB, Tokens.XmlContent, Tokens.XmlOpenEndTag, + Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenTag, Tokens.Identifier, + Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlStartInlineVB, + Tokens.From, Tokens.Identifier, Tokens.In, Tokens.Identifier, Tokens.Where, Tokens.Identifier, Tokens.Dot, + Tokens.Identifier, Tokens.Assign, Tokens.LiteralString, Tokens.Select, Tokens.XmlOpenTag, Tokens.Identifier, + Tokens.XmlCloseTag, Tokens.XmlStartInlineVB, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.XmlEndInlineVB, + Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlEndInlineVB, Tokens.XmlContent, Tokens.XmlOpenEndTag, + Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag + ); + + CheckFoot(lexer); + } + + [Test] + public void InlineVB2() + { + string code = @"Dim contact As XElement = <<%=elementName %>> + <%= MyName %> + "; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(code))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.As, Tokens.Identifier, Tokens.Assign, Tokens.XmlOpenTag, + Tokens.XmlStartInlineVB, Tokens.Identifier, Tokens.XmlEndInlineVB, Tokens.XmlCloseTag, Tokens.XmlContent, + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlStartInlineVB, Tokens.Identifier, Tokens.XmlEndInlineVB, + Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenEndTag, Tokens.XmlCloseTag); + + CheckFoot(lexer); + } + + [Test] + public void XmlAccessOperators() + { + string code = @"Dim childAxis = xml.
. +Dim course3 = xml...(2) +Dim childAxis = xml... +For Each item In childAxis + Console.WriteLine(item.@name) +Next"; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(code))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.Identifier, Tokens.Dot, Tokens.XmlOpenTag, + Tokens.Identifier, Tokens.XmlCloseTag, Tokens.Dot, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, + Tokens.EOL, Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.Identifier, Tokens.TripleDot, Tokens.XmlOpenTag, + Tokens.Identifier, Tokens.XmlCloseTag, Tokens.OpenParenthesis, Tokens.LiteralInteger, Tokens.CloseParenthesis, + Tokens.EOL, Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.Identifier, Tokens.TripleDot, Tokens.XmlOpenTag, + Tokens.Identifier, Tokens.XmlCloseTag, Tokens.EOL, Tokens.For, Tokens.Each, Tokens.Identifier, Tokens.In, Tokens.Identifier, Tokens.EOL, + Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.OpenParenthesis, Tokens.Identifier, Tokens.DotAt, Tokens.Identifier, Tokens.CloseParenthesis, Tokens.EOL, + Tokens.Next); + + CheckFoot(lexer); + } + + [Test] + public void GetXmlNamespace() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("Dim name = GetXmlNamespace(x)"))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, + Tokens.GetXmlNamespace, Tokens.OpenParenthesis, Tokens.Identifier, Tokens.CloseParenthesis); + + CheckFoot(lexer); + } + + [Test] + public void GetXmlNamespace2() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("Dim name = GetXmlNamespace(db-name)"))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, + Tokens.GetXmlNamespace, Tokens.OpenParenthesis, Tokens.Identifier, Tokens.CloseParenthesis); + + + CheckFoot(lexer); + } + + [Test] + public void XmlInSelect() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("Dim data = From x In list Select x"))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, + Tokens.From, Tokens.Identifier, Tokens.In, Tokens.Identifier, Tokens.Select, + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, Tokens.XmlOpenEndTag, + Tokens.Identifier, Tokens.XmlCloseTag); + + CheckFoot(lexer); + } + + [Test] + public void IfExpressionTest() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("Dim name = If(a <> 2, 4, 8)"))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, + Tokens.If, Tokens.OpenParenthesis, Tokens.Identifier, Tokens.NotEqual, Tokens.LiteralInteger, + Tokens.Comma, Tokens.LiteralInteger, Tokens.Comma, Tokens.LiteralInteger, Tokens.CloseParenthesis); + + CheckFoot(lexer); + } + + [Test] + public void IfStatementTest() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("If a <> 2 Then Return"))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.If, Tokens.Identifier, Tokens.NotEqual, Tokens.LiteralInteger, + Tokens.Then, Tokens.Return); + + + CheckFoot(lexer); + } + + [Test] + public void Bug1() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(@"Dim xml = "))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.XmlComment); + + CheckFoot(lexer); + } + + [Test] + public void Bug2() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(@"Dim xml = "))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, + Tokens.XmlProcessingInstruction, Tokens.XmlOpenTag, Tokens.Identifier, + Tokens.XmlCloseTagEmptyElement, Tokens.XmlComment); + + CheckFoot(lexer); + } + + [Test] + public void Bug3() + { + VBLexer lexer = GenerateLexerForSnippet(new StringReader("New String() {}"), SnippetType.Expression); + + CheckTokens(lexer, Tokens.New, Tokens.String, Tokens.OpenParenthesis, + Tokens.CloseParenthesis, Tokens.OpenCurlyBrace, Tokens.CloseCurlyBrace); + } + + [Test] + public void Bug4() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(@"Dim x = From kvp As KeyValuePair(Of String, DataGridViewCellStyle) In styleCache.CellStyleCache _ + Select includeStyle(kvp.Key, kvp.Value)"))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Dim, Tokens.Identifier, Tokens.Assign, Tokens.From, Tokens.Identifier, Tokens.As, Tokens.Identifier, + Tokens.OpenParenthesis, Tokens.Of, Tokens.String, Tokens.Comma, Tokens.Identifier, Tokens.CloseParenthesis, + Tokens.In, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, + Tokens.Select, Tokens.Identifier, Tokens.OpenParenthesis, Tokens.Identifier, Tokens.Dot, Tokens.Key, Tokens.Comma, + Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.CloseParenthesis); + + CheckFoot(lexer); + } + + [Test] + public void LessThanCheck() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(@"Dim xml = , True)"))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Identifier, Tokens.OpenParenthesis, Tokens.XmlOpenTag, + Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.Comma, Tokens.True, + Tokens.CloseParenthesis); + + CheckFoot(lexer); + } + + [Test] + public void AddHandlerStatement() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("AddHandler , True"))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.AddHandler, Tokens.XmlOpenTag, + Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.Comma, Tokens.True); + + CheckFoot(lexer); + } + + [Test] + public void AddHandlerStatement2() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("AddHandler , "))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.AddHandler, Tokens.XmlOpenTag, + Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.Comma, Tokens.XmlOpenTag, + Tokens.Identifier, Tokens.XmlCloseTagEmptyElement); + + CheckFoot(lexer); + } + + [Test] + public void RemoveHandlerStatement() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("RemoveHandler , 5"))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.RemoveHandler, Tokens.XmlOpenTag, + Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.Comma, + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlContent, + Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag + ); + + CheckFoot(lexer); + } + + [Test] + public void ErrorHandlingStatement() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("On Error Resume Next\n" + + "On Error GoTo -1\n" + + "On Error GoTo 0\n" + + "On Error GoTo Test\n" + + "Error 5\n" + + "Error \n" + + "Resume Next\n" + + "Resume Label\n" + + "Resume 4"))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.On, Tokens.Error, Tokens.Resume, Tokens.Next, Tokens.EOL, + Tokens.On, Tokens.Error, Tokens.GoTo, Tokens.Minus, Tokens.LiteralInteger, Tokens.EOL, + Tokens.On, Tokens.Error, Tokens.GoTo, Tokens.LiteralInteger, Tokens.EOL, + Tokens.On, Tokens.Error, Tokens.GoTo, Tokens.Identifier, Tokens.EOL, + Tokens.Error, Tokens.LiteralInteger, Tokens.EOL, + Tokens.Error, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.Resume, Tokens.Next, Tokens.EOL, + Tokens.Resume, Tokens.Identifier, Tokens.EOL, + Tokens.Resume, Tokens.LiteralInteger + ); + + CheckFoot(lexer); + } + + [Test] + public void ForLoopStatement() + { + string statement = @"For = To Step +Next , + +For Each In +Next "; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.For, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, + Tokens.Assign, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, + Tokens.To, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, + Tokens.Step, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.Next, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.Comma, + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.For, Tokens.Each, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, + Tokens.In, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.Next, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement + ); + + CheckFoot(lexer); + } + + [Test] + public void WhileLoopStatement() + { + string statement = @"While +End While"; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.While, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.End, Tokens.While + ); + + CheckFoot(lexer); + } + + [Test] + public void WhileLoopStatement2() + { + string statement = @"Do While +Loop"; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Do, Tokens.While, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.Loop + ); + + CheckFoot(lexer); + } + + [Test] + public void WhileLoopStatement3() + { + string statement = @"Do +Loop While "; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Do, Tokens.EOL, + Tokens.Loop, Tokens.While, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement + ); + + CheckFoot(lexer); + } + + [Test] + public void UntilLoopStatement() + { + string statement = @"Do Until +Loop"; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Do, Tokens.Until, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.Loop + ); + + CheckFoot(lexer); + } + + [Test] + public void UntilLoopStatement2() + { + string statement = @"Do +Loop Until "; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Do, Tokens.EOL, + Tokens.Loop, Tokens.Until, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement + ); + + CheckFoot(lexer); + } + + [Test] + public void IfStatementLarge() + { + string statement = @"If Then +Else If Then +ElseIf Then +Else +End If"; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.If, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.Then, Tokens.EOL, + Tokens.Else, Tokens.If, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.Then, Tokens.EOL, + Tokens.ElseIf, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.XmlOpenEndTag, Tokens.Identifier, Tokens.XmlCloseTag, Tokens.Then, Tokens.EOL, + Tokens.Else, Tokens.EOL, + Tokens.End, Tokens.If + ); + + CheckFoot(lexer); + } + + [Test] + public void SelectStatement() + { + string statement = @"Select Case + Case , + Case Else +End Select"; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Select, Tokens.Case, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.Case, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.Comma, + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.Case, Tokens.Else, Tokens.EOL, + Tokens.End, Tokens.Select + ); + + CheckFoot(lexer); + } + + [Test] + public void TryStatement() + { + string statement = @"Try + Catch x + Catch y As Exception + Catch When + Finally +End Try"; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Try, Tokens.EOL, + Tokens.Catch, Tokens.Identifier, Tokens.EOL, + Tokens.Catch, Tokens.Identifier, Tokens.As, Tokens.Identifier, Tokens.EOL, + Tokens.Catch, Tokens.When, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.Finally, Tokens.EOL, + Tokens.End, Tokens.Try + ); + + CheckFoot(lexer); + } + + [Test] + public void ThrowStatement() + { + VBLexer lexer = GenerateLexer(new StringReader(TestStatement("Throw "))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Throw, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement); + + CheckFoot(lexer); + } + + [Test] + public void BranchStatements() + { + string statement = @"GoTo 5 +GoTo LabelName +Exit Do +Exit For +Exit While +Exit Select +Exit Sub +Exit Function +Exit Property +Exit Try +Continue Do +Continue For +Continue While +Stop +End +Return +Return 5 +Return "; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.GoTo, Tokens.LiteralInteger, Tokens.EOL, + Tokens.GoTo, Tokens.Identifier, Tokens.EOL, + Tokens.Exit, Tokens.Do, Tokens.EOL, + Tokens.Exit, Tokens.For, Tokens.EOL, + Tokens.Exit, Tokens.While, Tokens.EOL, + Tokens.Exit, Tokens.Select, Tokens.EOL, + Tokens.Exit, Tokens.Sub, Tokens.EOL, + Tokens.Exit, Tokens.Function, Tokens.EOL, + Tokens.Exit, Tokens.Property, Tokens.EOL, + Tokens.Exit, Tokens.Try, Tokens.EOL, + Tokens.Continue, Tokens.Do, Tokens.EOL, + Tokens.Continue, Tokens.For, Tokens.EOL, + Tokens.Continue, Tokens.While, Tokens.EOL, + Tokens.Stop, Tokens.EOL, + Tokens.End, Tokens.EOL, + Tokens.Return, Tokens.EOL, + Tokens.Return, Tokens.LiteralInteger, Tokens.EOL, + Tokens.Return, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement + ); + + CheckFoot(lexer); + } + + [Test] + public void ArrayHandlingStatements() + { + string statement = @"Erase +Erase , +ReDim Preserve "; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Erase, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.Erase, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.Comma, + Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.ReDim, Tokens.Preserve, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement + ); + + CheckFoot(lexer); + } + + [Test] + public void UsingStatement() + { + string statement = @"Using +End Using"; + + VBLexer lexer = GenerateLexer(new StringReader(TestStatement(statement))); + + CheckHead(lexer); + + CheckTokens(lexer, Tokens.Using, Tokens.XmlOpenTag, Tokens.Identifier, Tokens.XmlCloseTagEmptyElement, Tokens.EOL, + Tokens.End, Tokens.Using + ); + + CheckFoot(lexer); + } + + [Test] + public void NewExpressionWithObjectInitializer() + { + string code = @"New Common.ComboBoxItem With {.Item = _ + Localizer.GetString(""Month"" & initParameters.SelectedDate.FirstDayOfPreviousMonth.Month) & "" "" & + initParameters.SelectedDate.FirstDayOfPreviousMonth.Year, .Value = New Date(2010, initParameters.SelectedDate.FirstDayOfPreviousMonth.Month, 1)}"; + + VBLexer lexer = GenerateLexerForSnippet(new StringReader(code), SnippetType.Expression); + + CheckTokens(lexer, Tokens.New, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, + Tokens.With, Tokens.OpenCurlyBrace, Tokens.Dot, Tokens.Identifier, Tokens.Assign, + Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.OpenParenthesis, Tokens.LiteralString, + Tokens.ConcatString, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.Dot, + Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.CloseParenthesis, Tokens.ConcatString, + Tokens.LiteralString, Tokens.ConcatString, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, + Tokens.Dot, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.Comma, Tokens.Dot, + Tokens.Identifier, Tokens.Assign, Tokens.New, Tokens.Date, Tokens.OpenParenthesis, Tokens.LiteralInteger, + Tokens.Comma, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.Dot, Tokens.Identifier, Tokens.Dot, + Tokens.Identifier, Tokens.Comma, Tokens.LiteralInteger, Tokens.CloseParenthesis, Tokens.CloseCurlyBrace); + } + #endregion + + #region Helpers + VBLexer GenerateLexer(StringReader sr) + { + return ParserFactory.CreateLexer(sr); + } + + VBLexer GenerateLexerForSnippet(StringReader sr, SnippetType type) + { + var lexer = ParserFactory.CreateLexer(sr); + lexer.SetInitialContext(type); + return lexer; + } + + string TestStatement(string stmt) + { + return "Class Test\n" + + "Sub A\n" + + stmt + "\n" + + "End Sub\n" + + "End Class"; + } + + void CheckFoot(VBLexer lexer) + { + CheckTokens(lexer, Tokens.EOL, Tokens.End, Tokens.Sub, Tokens.EOL, Tokens.End, Tokens.Class); + } + + void CheckHead(VBLexer lexer) + { + CheckTokens(lexer, Tokens.Class, Tokens.Identifier, Tokens.EOL, + Tokens.Sub, Tokens.Identifier, Tokens.EOL); + } + + void CheckTokens(VBLexer lexer, params int[] tokens) + { + for (int i = 0; i < tokens.Length; i++) { + int token = tokens[i]; + Token t = lexer.NextToken(); + int next = t.Kind; + Assert.IsEmpty(lexer.Errors.ErrorOutput); + Assert.AreEqual(token, next, "{2} of {3}: expected: \"{0}\", was: \"{1}\"; at {4}", Tokens.GetTokenString(token), Tokens.GetTokenString(next), i + 1, tokens.Length, t.Location); + } + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMParenthesizedExpressionTest.cs b/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMParenthesizedExpressionTest.cs new file mode 100644 index 000000000..948948e57 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMParenthesizedExpressionTest.cs @@ -0,0 +1,22 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.CodeDom; +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Visitors; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Output.CodeDom.Tests +{ + [TestFixture] + public class CodeDOMParenthesizedExpressionTest + { + [Test] + public void TestParenthesizedExpression() + { + object output = new ParenthesizedExpression(new PrimitiveExpression(5, "5")).AcceptVisitor(new CodeDomVisitor(), null); + Assert.IsTrue(output is CodePrimitiveExpression); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMPrimitiveExpressionTest.cs b/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMPrimitiveExpressionTest.cs new file mode 100644 index 000000000..366ac4cea --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMPrimitiveExpressionTest.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.CodeDom; +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Visitors; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Output.CodeDom.Tests +{ + [TestFixture] + public class CodeDOMPrimitiveExpressionsTests + { + [Test] + public void TestPrimitiveExpression() + { + object output = new PrimitiveExpression(5, "5").AcceptVisitor(new CodeDomVisitor(), null); + Assert.IsTrue(output is CodePrimitiveExpression); + Assert.AreEqual(((CodePrimitiveExpression)output).Value, 5); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMTypeReferenceTest.cs b/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMTypeReferenceTest.cs new file mode 100644 index 000000000..86d23d13f --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/CodeDOMTypeReferenceTest.cs @@ -0,0 +1,30 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.CodeDom; +using System.Collections.Generic; + +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Visitors; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Output.CodeDom.Tests +{ + [TestFixture] + public class CodeDOMTypeReferenceTest + { + [TestAttribute] + public void InnerClassTypeReferencTest() + { + InnerClassTypeReference ictr = new InnerClassTypeReference( + new TypeReference("OuterClass", new List { new TypeReference("String") }), + "InnerClass", + new List { new TypeReference("Int32"), new TypeReference("Int64") }); + Assert.AreEqual("OuterClass+InnerClass", ictr.ToString()); + CodeTypeOfExpression result = (CodeTypeOfExpression)new TypeOfExpression(ictr).AcceptVisitor(new CodeDomVisitor(), null); + Assert.AreEqual("OuterClass`1+InnerClass`2", result.Type.BaseType); + Assert.AreEqual(3, result.Type.TypeArguments.Count); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/InvocationExpressionTest.cs b/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/InvocationExpressionTest.cs new file mode 100644 index 000000000..63fd43775 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Output/CodeDOM/InvocationExpressionTest.cs @@ -0,0 +1,59 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.CodeDom; +using System.Collections.Generic; + +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Visitors; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Output.CodeDom.Tests +{ + [TestFixture] + public class InvocationExpressionsTests + { + [Test] + public void IdentifierOnlyInvocation() + { + // InitializeComponents(); + IdentifierExpression identifier = new IdentifierExpression("InitializeComponents"); + InvocationExpression invocation = new InvocationExpression(identifier, new List()); + object output = invocation.AcceptVisitor(new CodeDomVisitor(), null); + Assert.IsTrue(output is CodeMethodInvokeExpression); + CodeMethodInvokeExpression mie = (CodeMethodInvokeExpression)output; + Assert.AreEqual("InitializeComponents", mie.Method.MethodName); + Assert.IsTrue(mie.Method.TargetObject is CodeThisReferenceExpression); + } + + [Test] + public void MethodOnThisReferenceInvocation() + { + // InitializeComponents(); + MemberReferenceExpression field = new MemberReferenceExpression(new ThisReferenceExpression(), "InitializeComponents"); + InvocationExpression invocation = new InvocationExpression(field, new List()); + object output = invocation.AcceptVisitor(new CodeDomVisitor(), null); + Assert.IsTrue(output is CodeMethodInvokeExpression); + CodeMethodInvokeExpression mie = (CodeMethodInvokeExpression)output; + Assert.AreEqual("InitializeComponents", mie.Method.MethodName); + Assert.IsTrue(mie.Method.TargetObject is CodeThisReferenceExpression); + } + + [Test] + public void InvocationOfStaticMethod() + { + // System.Drawing.Color.FromArgb(); + MemberReferenceExpression field = new MemberReferenceExpression(new IdentifierExpression("System"), "Drawing"); + field = new MemberReferenceExpression(field, "Color"); + field = new MemberReferenceExpression(field, "FromArgb"); + InvocationExpression invocation = new InvocationExpression(field, new List()); + object output = invocation.AcceptVisitor(new CodeDomVisitor(), null); + Assert.IsTrue(output is CodeMethodInvokeExpression); + CodeMethodInvokeExpression mie = (CodeMethodInvokeExpression)output; + Assert.AreEqual("FromArgb", mie.Method.MethodName); + Assert.IsTrue(mie.Method.TargetObject is CodeTypeReferenceExpression); + Assert.AreEqual("System.Drawing.Color", (mie.Method.TargetObject as CodeTypeReferenceExpression).Type.BaseType); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Output/SpecialOutputVisitorTest.cs b/ICSharpCode.NRefactory.VB.Tests/Output/SpecialOutputVisitorTest.cs new file mode 100644 index 000000000..d92b7899e --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Output/SpecialOutputVisitorTest.cs @@ -0,0 +1,79 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.IO; + +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.PrettyPrinter; +using ICSharpCode.NRefactory.VB.Visitors; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.PrettyPrinter +{ + [TestFixture] + public class SpecialOutputVisitorTest + { + void TestProgram(string program) + { + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + Assert.AreEqual("", parser.Errors.ErrorOutput); + VBNetOutputVisitor outputVisitor = new VBNetOutputVisitor(); + outputVisitor.Options.IndentationChar = ' '; + outputVisitor.Options.TabSize = 2; + outputVisitor.Options.IndentSize = 2; + using (SpecialNodesInserter.Install(parser.Lexer.SpecialTracker.RetrieveSpecials(), + outputVisitor)) { + outputVisitor.VisitCompilationUnit(parser.CompilationUnit, null); + } + Assert.AreEqual("", outputVisitor.Errors.ErrorOutput); + Assert.AreEqual(program.Replace("\r", ""), outputVisitor.Text.TrimEnd().Replace("\r", "")); + parser.Dispose(); + } + + [Test] + public void Enum() + { + TestProgram("Enum Test\n" + + " ' a\n" + + " m1\n" + + " ' b\n" + + " m2\n" + + " ' c\n" + + "End Enum\n" + + "' d"); + } + + [Test] + public void CommentsInsideMethod() + { + TestProgram(@"Public Class Class1 + Private Function test(l As Integer, lvw As Integer) As Boolean + ' Begin + Dim i As Integer = 1 + Return False + ' End of method + End Function +End Class"); + } + + [Test] + public void BlankLines() + { + TestProgram("Imports System\n" + + "\n" + + "Imports System.IO"); + TestProgram("Imports System\n" + + "\n" + + "\n" + + "Imports System.IO"); + TestProgram("\n" + + "' Some comment\n" + + "\n" + + "Imports System.IO"); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Output/VBNet/VBNetOutputTest.cs b/ICSharpCode.NRefactory.VB.Tests/Output/VBNet/VBNetOutputTest.cs new file mode 100644 index 000000000..6a6b9f461 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Output/VBNet/VBNetOutputTest.cs @@ -0,0 +1,670 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.PrettyPrinter; +using ICSharpCode.NRefactory.VB.Visitors; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.PrettyPrinter +{ + [TestFixture] + public class VBNetOutputTest + { + void TestProgram(string program) + { + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + Assert.AreEqual("", parser.Errors.ErrorOutput); + VBNetOutputVisitor outputVisitor = new VBNetOutputVisitor(); + outputVisitor.Options.OutputByValModifier = true; + outputVisitor.VisitCompilationUnit(parser.CompilationUnit, null); + Assert.AreEqual("", outputVisitor.Errors.ErrorOutput); + Assert.AreEqual(StripWhitespace(program), StripWhitespace(outputVisitor.Text)); + } + + string StripWhitespace(string text) + { + text = text.Trim().Replace("\t", "").Replace("\r", "").Replace("\n", " ").Replace(" ", " "); + while (text.Contains(" ")) { + text = text.Replace(" ", " "); + } + return text; + } + + void TestTypeMember(string program) + { + TestProgram("Class A\n" + program + "\nEnd Class"); + } + + void TestStatement(string statement) + { + TestTypeMember("Sub Method()\n" + statement + "\nEnd Sub"); + } + + void TestExpression(string expression) + { + VBParser parser = ParserFactory.CreateParser(new StringReader(expression)); + Expression e = parser.ParseExpression(); + Assert.AreEqual("", parser.Errors.ErrorOutput); + VBNetOutputVisitor outputVisitor = new VBNetOutputVisitor(); + e.AcceptVisitor(outputVisitor, null); + Assert.AreEqual("", outputVisitor.Errors.ErrorOutput); + Assert.AreEqual(StripWhitespace(expression), StripWhitespace(outputVisitor.Text)); + } + + [Test] + public void Field() + { + TestTypeMember("Private a As Integer"); + } + + [Test] + public void Method() + { + TestTypeMember("Sub Method()\nEnd Sub"); + } + + [Test] + public void EnumWithBaseType() + { + TestProgram("Public Enum Foo As UShort\nEnd Enum"); + } + + [Test] + public void PartialModifier() + { + TestProgram("Public Partial Class Foo\nEnd Class"); + } + + [Test] + public void MustInheritClass() + { + TestProgram("Public MustInherit Class Foo\nEnd Class"); + } + + [Test] + public void GenericClassDefinition() + { + TestProgram("Public Class Foo(Of T As {IDisposable, ICloneable})\nEnd Class"); + } + + [Test] + public void GenericClassDefinitionWithBaseType() + { + TestProgram("Public Class Foo(Of T As IDisposable)\nInherits BaseType\nEnd Class"); + } + + [Test] + public void GenericMethodDefinition() + { + TestTypeMember("Public Sub Foo(Of T As {IDisposable, ICloneable})(ByVal arg As T)\nEnd Sub"); + } + + [Test] + public void ArrayRank() + { + TestStatement("Dim a As Object(,,)"); + } + + [Test] + public void ArrayInitialization() + { + TestStatement("Dim a As Object() = New Object(10) {}"); + TestTypeMember("Private MultiDim As Integer(,) = {{1, 2}, {1, 3}}"); + TestExpression("New Integer(, ) {{1, 1}, {1, 1}}"); + TestTypeMember("Private _titles As String() = New String() {}"); + } + + [Test] + public void MethodCallWithOptionalArguments() + { + TestExpression("M(, )"); + } + + [Test] + public void IfStatement() + { + TestStatement("If a Then\n" + + "\tm1()\n" + + "ElseIf b Then\n" + + "\tm2()\n" + + "Else\n" + + "\tm3()\n" + + "End If"); + } + + [Test] + public void ForNextLoop() + { + TestStatement("For i = 0 To 10\n" + + "Next"); + TestStatement("For i As Long = 10 To 0 Step -1\n" + + "Next"); + } + + [Test] + public void DoLoop() + { + TestStatement("Do\n" + + "Loop"); + TestStatement("Do\n" + + "Loop While Not (i = 10)"); + } + + [Test] + public void SelectCase() + { + TestStatement(@"Select Case i + Case 0 + Case 1 To 4 + Case Else +End Select"); + } + + [Test] + public void UsingStatement() + { + TestStatement(@"Using nf As New Font(), nf2 As New List(Of Font)(), nf3 = Nothing + Bla(nf) +End Using"); + } + + [Test] + public void UntypedVariable() + { + TestStatement("Dim x = 0"); + } + + [Test] + public void UntypedField() + { + TestTypeMember("Dim x = 0"); + } + + [Test] + public void Assignment() + { + TestExpression("a = b"); + } + + [Test] + public void SpecialIdentifiers() + { + // Assembly, Ansi and Until are contextual keywords + // Custom is valid inside methods, but not valid for field names + TestExpression("Assembly = Ansi * [For] + Until - [Custom]"); + } + + [Test] + public void DictionaryAccess() + { + TestExpression("c!key"); + } + + [Test] + public void GenericMethodInvocation() + { + TestExpression("GenericMethod(Of T)(arg)"); + } + + [Test] + public void SpecialIdentifierName() + { + TestExpression("[Class]"); + } + + [Test] + public void GenericDelegate() + { + TestProgram("Public Delegate Function Predicate(Of T)(ByVal item As T) As String"); + } + + [Test] + public void Enum() + { + TestProgram("Enum MyTest\nRed\n Green\n Blue\nYellow\n End Enum"); + } + + [Test] + public void EnumWithInitializers() + { + TestProgram("Enum MyTest\nRed = 1\n Green = 2\n Blue = 4\n Yellow = 8\n End Enum"); + } + + [Test] + public void SyncLock() + { + TestStatement("SyncLock a\nWork()\nEnd SyncLock"); + } + + [Test] + public void Using() + { + TestStatement("Using a As New A()\na.Work()\nEnd Using"); + } + + [Test] + public void Cast() + { + TestExpression("CType(a, T)"); + } + + [Test] + public void DirectCast() + { + TestExpression("DirectCast(a, T)"); + } + + [Test] + public void TryCast() + { + TestExpression("TryCast(a, T)"); + } + + [Test] + public void PrimitiveCast() + { + TestExpression("CStr(a)"); + } + + [Test] + public void TypeOfIs() + { + TestExpression("TypeOf a Is String"); + } + + [Test] + public void PropertyWithAccessorAccessModifiers() + { + TestTypeMember("Public Property ExpectsValue() As Boolean\n" + + "\tPublic Get\n" + + "\tEnd Get\n" + + "\tProtected Set\n" + + "\tEnd Set\n" + + "End Property"); + } + + [Test] + public void AutoProperty() + { + TestTypeMember("Public Property Value()"); + TestTypeMember("Public Property Value() As Integer"); + TestTypeMember("Public Property Value() As Integer = 5"); + TestTypeMember("Public Property Value() As New List()"); + } + + [Test] + public void AbstractProperty() + { + TestTypeMember("Public MustOverride Property ExpectsValue() As Boolean"); + TestTypeMember("Public MustOverride ReadOnly Property ExpectsValue() As Boolean"); + TestTypeMember("Public MustOverride WriteOnly Property ExpectsValue() As Boolean"); + } + + [Test] + public void AbstractMethod() + { + TestTypeMember("Public MustOverride Sub Run()"); + TestTypeMember("Public MustOverride Function Run() As Boolean"); + } + + [Test] + public void InterfaceImplementingMethod() + { + TestTypeMember("Public Sub Run() Implements SomeInterface.Run\nEnd Sub"); + TestTypeMember("Public Function Run() As Boolean Implements SomeInterface.Bla\nEnd Function"); + } + + [Test] + public void NamedAttributeArgument() + { + TestProgram(" _\n" + + "Class Test\n" + + "End Class"); + } + + [Test] + public void ReturnTypeAttribute() + { + TestTypeMember("Function A() As String\n" + + "End Function"); + } + + [Test] + public void AssemblyAttribute() + { + TestProgram(""); + } + + [Test] + public void ModuleAttribute() + { + TestProgram(""); + } + + [Test] + public void Interface() + { + TestProgram("Interface ITest\n" + + "Property GetterAndSetter() As Boolean\n" + + "ReadOnly Property GetterOnly() As Boolean\n" + + "WriteOnly Property SetterOnly() As Boolean\n" + + "Sub InterfaceMethod()\n" + + "Function InterfaceMethod2() As String\n" + + "End Interface"); + } + + [Test] + public void OnErrorStatement() + { + TestStatement("On Error Resume Next"); + } + + [Test] + public void OverloadedConversionOperators() + { + TestTypeMember("Public Shared Narrowing Operator CType(ByVal xmlNode As XmlNode) As TheBug\nEnd Operator"); + TestTypeMember("Public Shared Widening Operator CType(ByVal bugNode As TheBug) As XmlNode\nEnd Operator"); + } + + [Test] + public void OverloadedTrueFalseOperators() + { + TestTypeMember("Public Shared Operator IsTrue(ByVal a As TheBug) As Boolean\nEnd Operator"); + TestTypeMember("Public Shared Operator IsFalse(ByVal a As TheBug) As Boolean\nEnd Operator"); + } + + [Test] + public void OverloadedOperators() + { + TestTypeMember("Public Shared Operator +(ByVal bugNode As TheBug, ByVal bugNode2 As TheBug) As TheBug\nEnd Operator"); + TestTypeMember("Public Shared Operator >>(ByVal bugNode As TheBug, ByVal b As Integer) As TheBug\nEnd Operator"); + } + + [Test] + public void AttributeOnParameter() + { + TestTypeMember("Sub Main(ByRef one As Integer, ByRef two As Integer, ByRef three As Integer)\nEnd Sub"); + } + + [Test] + public void FieldWithoutType() + { + TestTypeMember("Dim X"); + } + + [Test] + public void UsingStatementForExistingVariable() + { + TestStatement("Using obj\nEnd Using"); + } + + [Test] + public void ContinueFor() + { + TestStatement("Continue For"); + } + + [Test] + public void ForNextStatementWithFieldLoopVariable() + { + TestStatement("For Me.Field = 0 To 10\n" + + "Next Me.Field"); + } + + [Test] + public void WithStatement() + { + TestStatement("With Ejes\n" + + "\t.AddLine(New Point(Me.ClientSize.Width / 2, 0), (New Point(Me.ClientSize.Width / 2, Me.ClientSize.Height)))\n" + + "End With"); + } + + [Test] + public void NewConstraint() + { + TestProgram("Public Class Rational(Of T, O As {IRationalMath(Of T), New})\nEnd Class"); + } + + [Test] + public void StructConstraint() + { + TestProgram("Public Class Rational(Of T, O As {IRationalMath(Of T), Structure})\nEnd Class"); + } + + [Test] + public void ClassConstraint() + { + TestProgram("Public Class Rational(Of T, O As {IRationalMath(Of T), Class})\nEnd Class"); + } + + [Test] + public void Integer() + { + TestExpression("16"); + } + + [Test] + public void Double() + { + TestExpression("1.0"); + } + + [Test] + public void HexadecimalInteger() + { + TestExpression("&H10"); + } + + [Test] + public void HexadecimalMinusOne() + { + TestExpression("&Hffffffff"); + } + + [Test] + public void TypeCharacters() + { + TestExpression("347S"); + TestExpression("347L"); + TestExpression("347D"); + TestExpression("347F"); + TestExpression("347US"); + TestExpression("347UI"); + TestExpression("347UL"); + TestExpression("\".\"C"); + } + + [Test] + public void AddressOf() + { + TestExpression("AddressOf Abc"); + } + + [Test] + public void ChainedConstructorCall() + { + TestExpression("MyBase.New()"); + TestExpression("Me.New()"); + TestExpression("MyClass.New()"); + } + + [Test] + public void NewMethodCall() + { + TestExpression("something.[New]()"); + } + + [Test] + public void ObjectInitializer() + { + TestExpression("New StringWriter() With { _\n" + + " .NewLine = Environment.NewLine, _\n" + + " .Encoding = Encoding.UTF8 _\n" + + "}"); + } + + [Test] + public void EventDefinition() + { + TestTypeMember("Public Event MyEvent(ByVal sender As Object)"); + } + + [Test] + public void Options() + { + TestProgram("Option Strict On\n" + + "Option Explicit On\n" + + "Option Infer On\n" + + "Option Compare Text"); + } + + [Test] + public void UntypedForeach() + { + TestStatement("For Each x In myGuidArray\nNext"); + } + + [Test] + public void MethodDefinitionWithOptionalParameter() + { + TestTypeMember("Sub M(Optional ByVal msg As String = Nothing, Optional ByRef output As String = Nothing)\nEnd Sub"); + } + + [Test] + public void Module() + { + TestProgram("Module Test\n" + + " Sub M()\n" + + " End Sub\n" + + "End Module"); + } + + [Test] + public void WithEvents() + { + TestTypeMember("Dim WithEvents a As Button"); + } + + [Test] + public void FriendWithEventsField() + { + TestTypeMember("Friend WithEvents Button1 As System.Windows.Forms.Button"); + } + + [Test] + public void SimpleFunctionLambda() + { + TestExpression("Function(x) x * x"); + } + + [Test] + public void SimpleFunctionLambdaWithType() + { + TestExpression("Function(x As Integer) x * x"); + } + + [Test] + public void SimpleSubLambdaWithType() + { + TestExpression("Sub(x As Integer) Console.WriteLine(x)"); + } + + [Test] + public void BlockSubLambdaWithType() + { + TestExpression("Sub(x As Integer)\n" + + " Console.WriteLine(x)\n" + + "End Sub"); + } + + [Test] + public void BlockFunctionLambdaWithType() + { + TestExpression("Function(x As Integer) As Integer\n" + + " If x < 2 Then\n" + + " Return x\n" + + " End If\n" + + " Return x * x\n" + + "End Function"); + } + + [Test] + public void XmlSimple() + { + TestExpression("\n" + + "\n" + + "\n" + + " \n" + + " />\n" + + ""); + } + + [Test] + public void XmlNested() + { + TestExpression(@" + + Shrimp Cocktail + Escargot + + + Filet Mignon + Garlic Potatoes + Broccoli + + + Chocolate Cheesecake + + "); + } + + [Test] + public void XmlDocument() + { + TestExpression(@" + + + Shrimp Cocktail + Escargot + + "); + } + + [Test] + public void XmlNestedWithExpressions() + { + TestExpression(@" + + + <%= From m In menu _ + Where m.Course = ""appetizer"" _ + Select <%= m.Food %> %> + + + <%= From m In menu _ + Where m.Course = ""main"" _ + Select <%= m.Food %> %> + + + <%= From m In menu _ + Where m.Course = ""dessert"" _ + Select <%= m.Food %> %> + + "); + } + + [Test] + public void XmlAccessExpressions() + { + TestExpression("xml.."); + TestExpression("xml..."); + TestExpression("xml...(2)"); + TestExpression("item.@name"); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/CheckParentVisitor.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/CheckParentVisitor.cs new file mode 100644 index 000000000..a24409327 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/CheckParentVisitor.cs @@ -0,0 +1,35 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using NUnit.Framework; +using System; +using System.Collections.Generic; +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Visitors; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + /// + /// Ensures that all nodes have the Parent property correctly set. + /// + public class CheckParentVisitor : NodeTrackingDomVisitor + { + Stack nodeStack = new Stack(); + + public CheckParentVisitor() + { + nodeStack.Push(null); + } + + protected override void BeginVisit(INode node) + { + nodeStack.Push(node); + } + + protected override void EndVisit(INode node) + { + Assert.AreSame(node, nodeStack.Pop(), "nodeStack was corrupted!"); + Assert.AreSame(nodeStack.Peek(), node.Parent, "node " + node + " is missing parent: " + nodeStack.Peek()); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/AddressOfExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/AddressOfExpressionTests.cs new file mode 100644 index 000000000..364d041e7 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/AddressOfExpressionTests.cs @@ -0,0 +1,45 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class AddressOfExpressionTests + { + [Test] + public void SimpleAddressOfExpressionTest() + { + AddressOfExpression ae = ParseUtil.ParseExpression("AddressOf t"); + Assert.IsNotNull(ae); + Assert.IsInstanceOf(typeof(IdentifierExpression), ae.Expression); + Assert.AreEqual("t", ((IdentifierExpression)ae.Expression).Identifier, "t"); + } + + [Test] + public void GenericAddressOfExpressionTest() + { + AddressOfExpression ae = ParseUtil.ParseExpression("AddressOf t(Of X)"); + Assert.IsNotNull(ae); + Assert.IsInstanceOf(typeof(IdentifierExpression), ae.Expression); + Assert.AreEqual("t", ((IdentifierExpression)ae.Expression).Identifier, "t"); + Assert.AreEqual(1, ((IdentifierExpression)ae.Expression).TypeArguments.Count); + Assert.AreEqual("X", ((IdentifierExpression)ae.Expression).TypeArguments[0].Type); + } + + [Test] + public void MemberReferenceAddressOfExpressionTest() + { + AddressOfExpression ae = ParseUtil.ParseExpression("AddressOf Me.t(Of X)"); + Assert.IsNotNull(ae); + Assert.IsInstanceOf(typeof(MemberReferenceExpression), ae.Expression); + Assert.AreEqual("t", ((MemberReferenceExpression)ae.Expression).MemberName, "t"); + Assert.IsInstanceOf(typeof(ThisReferenceExpression), ((MemberReferenceExpression)ae.Expression).TargetObject); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ArrayCreateExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ArrayCreateExpressionTests.cs new file mode 100644 index 000000000..91288f82b --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ArrayCreateExpressionTests.cs @@ -0,0 +1,36 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ArrayCreateExpressionTests + { + [Test] + public void ArrayCreateExpressionTest1() + { + ArrayCreateExpression ace = ParseUtil.ParseExpression("new Integer() {1, 2, 3, 4}"); + + Assert.AreEqual("System.Int32", ace.CreateType.Type); + Assert.AreEqual(0, ace.Arguments.Count); + Assert.AreEqual(new int[] {0}, ace.CreateType.RankSpecifier); + } + + [Test] + public void ArrayCreateExpressionTest2() + { + ArrayCreateExpression ace = ParseUtil.ParseExpression("New Integer(0 To 5){0, 1, 2, 3, 4, 5}"); + + Assert.AreEqual("System.Int32", ace.CreateType.Type); + Assert.AreEqual(1, ace.Arguments.Count); + Assert.AreEqual(5, (ace.Arguments[0] as PrimitiveExpression).Value); + Assert.AreEqual(new int[] {0}, ace.CreateType.RankSpecifier); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/AssignmentExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/AssignmentExpressionTests.cs new file mode 100644 index 000000000..31f67e0e9 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/AssignmentExpressionTests.cs @@ -0,0 +1,73 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class AssignmentExpressionTests + { + void TestAssignmentExpression(string program, AssignmentOperatorType op) + { + ExpressionStatement se = ParseUtil.ParseStatement(program); + AssignmentExpression ae = se.Expression as AssignmentExpression; + Assert.AreEqual(op, ae.Op); + + Assert.IsTrue(ae.Left is IdentifierExpression); + Assert.IsTrue(ae.Right is IdentifierExpression); + } + + [Test] + public void AssignTest() + { + TestAssignmentExpression("a = b", AssignmentOperatorType.Assign); + } + + [Test] + public void AddTest() + { + TestAssignmentExpression("a += b", AssignmentOperatorType.Add); + } + + [Test] + public void SubtractTest() + { + TestAssignmentExpression("a -= b", AssignmentOperatorType.Subtract); + } + + [Test] + public void MultiplyTest() + { + TestAssignmentExpression("a *= b", AssignmentOperatorType.Multiply); + } + + [Test] + public void DivideTest() + { + TestAssignmentExpression("a /= b", AssignmentOperatorType.Divide); + } + + [Test] + public void ExclusiveOrTest() + { + TestAssignmentExpression("a ^= b", AssignmentOperatorType.Power); + } + + [Test] + public void StringConcatTest() + { + TestAssignmentExpression("a &= b", AssignmentOperatorType.ConcatString); + } + + [Test] + public void ModulusTest() + { + TestAssignmentExpression("a \\= b", AssignmentOperatorType.DivideInteger); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/BaseReferenceExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/BaseReferenceExpressionTests.cs new file mode 100644 index 000000000..6d7b4a451 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/BaseReferenceExpressionTests.cs @@ -0,0 +1,24 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class BaseReferenceExpressionTests + { + #region VB.NET + [Test] + public void VBNetBaseReferenceExpressionTest1() + { + MemberReferenceExpression fre = ParseUtil.ParseExpression("MyBase.myField"); + Assert.IsTrue(fre.TargetObject is BaseReferenceExpression); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/BinaryOperatorExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/BinaryOperatorExpressionTests.cs new file mode 100644 index 000000000..a96353f4a --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/BinaryOperatorExpressionTests.cs @@ -0,0 +1,310 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.PrettyPrinter; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class BinaryOperatorExpressionTests + { + void OperatorPrecedenceTest(string strongOperator, BinaryOperatorType strongOperatorType, + string weakOperator, BinaryOperatorType weakOperatorType) + { + string program = "a " + weakOperator + " b " + strongOperator + " c"; + BinaryOperatorExpression boe; + boe = ParseUtil.ParseExpression(program); + Assert.AreEqual(weakOperatorType, boe.Op); + Assert.IsTrue(boe.Left is IdentifierExpression); + boe = (BinaryOperatorExpression)boe.Right; + Assert.AreEqual(strongOperatorType, boe.Op); + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is IdentifierExpression); + + program = "a " + strongOperator + " b " + weakOperator + " c"; + boe = ParseUtil.ParseExpression(program); + Assert.AreEqual(weakOperatorType, boe.Op); + Assert.IsTrue(boe.Right is IdentifierExpression); + boe = (BinaryOperatorExpression)boe.Left; + Assert.AreEqual(strongOperatorType, boe.Op); + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is IdentifierExpression); + } + + void SameOperatorPrecedenceTest(string firstOperator, BinaryOperatorType firstOperatorType, + string secondOperator, BinaryOperatorType secondOperatorType) + { + string program = "a " + secondOperator + " b " + firstOperator + " c"; + BinaryOperatorExpression boe; + boe = ParseUtil.ParseExpression(program); + Assert.AreEqual(firstOperatorType, boe.Op); + Assert.IsTrue(boe.Right is IdentifierExpression); + boe = (BinaryOperatorExpression)boe.Left; + Assert.AreEqual(secondOperatorType, boe.Op); + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is IdentifierExpression); + + program = "a " + firstOperator + " b " + secondOperator + " c"; + boe = ParseUtil.ParseExpression(program); + Assert.AreEqual(secondOperatorType, boe.Op); + Assert.IsTrue(boe.Right is IdentifierExpression); + boe = (BinaryOperatorExpression)boe.Left; + Assert.AreEqual(firstOperatorType, boe.Op); + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is IdentifierExpression); + } + + #region VB.NET + void VBNetTestBinaryOperatorExpressionTest(string program, BinaryOperatorType op) + { + BinaryOperatorExpression boe = ParseUtil.ParseExpression(program); + Assert.AreEqual(op, boe.Op); + + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is IdentifierExpression); + } + + [Test] + public void VBOperatorPrecedenceTest() + { + OperatorPrecedenceTest("^", BinaryOperatorType.Power, "*", BinaryOperatorType.Multiply); + SameOperatorPrecedenceTest("*", BinaryOperatorType.Multiply, "/", BinaryOperatorType.Divide); + OperatorPrecedenceTest("/", BinaryOperatorType.Divide, "\\", BinaryOperatorType.DivideInteger); + OperatorPrecedenceTest("\\", BinaryOperatorType.DivideInteger, "Mod", BinaryOperatorType.Modulus); + OperatorPrecedenceTest("Mod", BinaryOperatorType.Modulus, "+", BinaryOperatorType.Add); + SameOperatorPrecedenceTest("+", BinaryOperatorType.Add, "-", BinaryOperatorType.Subtract); + OperatorPrecedenceTest("-", BinaryOperatorType.Subtract, "&", BinaryOperatorType.Concat); + OperatorPrecedenceTest("&", BinaryOperatorType.Concat, "<<", BinaryOperatorType.ShiftLeft); + SameOperatorPrecedenceTest("<<", BinaryOperatorType.ShiftLeft, ">>", BinaryOperatorType.ShiftRight); + OperatorPrecedenceTest("<<", BinaryOperatorType.ShiftLeft, "=", BinaryOperatorType.Equality); + SameOperatorPrecedenceTest("<>", BinaryOperatorType.InEquality, "=", BinaryOperatorType.Equality); + SameOperatorPrecedenceTest("<", BinaryOperatorType.LessThan, "=", BinaryOperatorType.Equality); + SameOperatorPrecedenceTest("<=", BinaryOperatorType.LessThanOrEqual, "=", BinaryOperatorType.Equality); + SameOperatorPrecedenceTest(">", BinaryOperatorType.GreaterThan, "=", BinaryOperatorType.Equality); + SameOperatorPrecedenceTest(">=", BinaryOperatorType.GreaterThanOrEqual, "=", BinaryOperatorType.Equality); + SameOperatorPrecedenceTest("Like", BinaryOperatorType.Like, "=", BinaryOperatorType.Equality); + SameOperatorPrecedenceTest("Is", BinaryOperatorType.ReferenceEquality, "=", BinaryOperatorType.Equality); + SameOperatorPrecedenceTest("IsNot", BinaryOperatorType.ReferenceInequality, "=", BinaryOperatorType.Equality); + OperatorPrecedenceTest("=", BinaryOperatorType.Equality, "And", BinaryOperatorType.BitwiseAnd); + SameOperatorPrecedenceTest("And", BinaryOperatorType.BitwiseAnd, "AndAlso", BinaryOperatorType.LogicalAnd); + OperatorPrecedenceTest("And", BinaryOperatorType.BitwiseAnd, "Or", BinaryOperatorType.BitwiseOr); + SameOperatorPrecedenceTest("Or", BinaryOperatorType.BitwiseOr, "OrElse", BinaryOperatorType.LogicalOr); + SameOperatorPrecedenceTest("Or", BinaryOperatorType.BitwiseOr, "Xor", BinaryOperatorType.ExclusiveOr); + } + + [Test] + public void VBNetPowerTest() + { + VBNetTestBinaryOperatorExpressionTest("a ^ b", BinaryOperatorType.Power); + } + + [Test] + public void VBNetConcatTest() + { + VBNetTestBinaryOperatorExpressionTest("a & b", BinaryOperatorType.Concat); + } + + [Test] + public void VBNetLogicalAndTest() + { + VBNetTestBinaryOperatorExpressionTest("a AndAlso b", BinaryOperatorType.LogicalAnd); + } + [Test] + public void VBNetLogicalAndNotLazyTest() + { + VBNetTestBinaryOperatorExpressionTest("a And b", BinaryOperatorType.BitwiseAnd); + } + + [Test] + public void VBNetLogicalOrTest() + { + VBNetTestBinaryOperatorExpressionTest("a OrElse b", BinaryOperatorType.LogicalOr); + } + [Test] + public void VBNetLogicalOrNotLazyTest() + { + VBNetTestBinaryOperatorExpressionTest("a Or b", BinaryOperatorType.BitwiseOr); + } + + [Test] + public void VBNetExclusiveOrTest() + { + VBNetTestBinaryOperatorExpressionTest("a Xor b", BinaryOperatorType.ExclusiveOr); + } + + + [Test] + public void VBNetGreaterThanTest() + { + VBNetTestBinaryOperatorExpressionTest("a > b", BinaryOperatorType.GreaterThan); + } + + [Test] + public void VBNetGreaterThanOrEqualTest() + { + VBNetTestBinaryOperatorExpressionTest("a >= b", BinaryOperatorType.GreaterThanOrEqual); + } + + [Test] + public void VBNetEqualityTest() + { + VBNetTestBinaryOperatorExpressionTest("a = b", BinaryOperatorType.Equality); + } + + [Test] + public void VBNetInEqualityTest() + { + VBNetTestBinaryOperatorExpressionTest("a <> b", BinaryOperatorType.InEquality); + } + + [Test] + public void VBNetLessThanTest() + { + VBNetTestBinaryOperatorExpressionTest("a < b", BinaryOperatorType.LessThan); + } + + [Test] + public void VBNetLessThanOrEqualTest() + { + VBNetTestBinaryOperatorExpressionTest("a <= b", BinaryOperatorType.LessThanOrEqual); + } + + [Test] + public void VBNetAddTest() + { + VBNetTestBinaryOperatorExpressionTest("a + b", BinaryOperatorType.Add); + } + + [Test] + public void VBNetSubtractTest() + { + VBNetTestBinaryOperatorExpressionTest("a - b", BinaryOperatorType.Subtract); + } + + [Test] + public void VBNetMultiplyTest() + { + VBNetTestBinaryOperatorExpressionTest("a * b", BinaryOperatorType.Multiply); + } + + [Test] + public void VBNetDivideTest() + { + VBNetTestBinaryOperatorExpressionTest("a / b", BinaryOperatorType.Divide); + } + + [Test] + public void VBNetDivideIntegerTest() + { + VBNetTestBinaryOperatorExpressionTest("a \\ b", BinaryOperatorType.DivideInteger); + } + + [Test] + public void VBNetModulusTest() + { + VBNetTestBinaryOperatorExpressionTest("a Mod b", BinaryOperatorType.Modulus); + } + + [Test] + public void VBNetShiftLeftTest() + { + VBNetTestBinaryOperatorExpressionTest("a << b", BinaryOperatorType.ShiftLeft); + } + + [Test] + public void VBNetShiftRightTest() + { + VBNetTestBinaryOperatorExpressionTest("a >> b", BinaryOperatorType.ShiftRight); + } + + [Test] + public void VBNetISTest() + { + VBNetTestBinaryOperatorExpressionTest("a is b", BinaryOperatorType.ReferenceEquality); + } + + [Test] + public void VBNetISNotTest() + { + VBNetTestBinaryOperatorExpressionTest("a IsNot b", BinaryOperatorType.ReferenceInequality); + } + + [Test] + public void VBNetLikeTest() + { + VBNetTestBinaryOperatorExpressionTest("a Like b", BinaryOperatorType.Like); + } + + [Test] + public void VBNetNullCoalescingTest() + { + VBNetTestBinaryOperatorExpressionTest("If(a, b)", BinaryOperatorType.NullCoalescing); + } + + [Test] + public void VBNetDictionaryAccess() + { + BinaryOperatorExpression boe = ParseUtil.ParseExpression("a!b"); + Assert.AreEqual(BinaryOperatorType.DictionaryAccess, boe.Op); + Assert.IsTrue(boe.Left is IdentifierExpression); + Assert.IsTrue(boe.Right is PrimitiveExpression); + } + + [Test] + public void VBNetWithDictionaryAccess() + { + BinaryOperatorExpression boe = ParseUtil.ParseExpression("!b"); + Assert.AreEqual(BinaryOperatorType.DictionaryAccess, boe.Op); + Assert.IsTrue(boe.Left.IsNull); + Assert.IsTrue(boe.Right is PrimitiveExpression); + } + #endregion + + #region AddIntegerTests + string AddIntegerToBoe(string input, int number) + { + return AddInteger(input, number); + } + + string AddInteger(string input, int number) where T : Expression + { + Expression e = ParseUtil.ParseExpression(input); + e = Expression.AddInteger(e, number); + VBNetOutputVisitor v = new VBNetOutputVisitor(); + e.AcceptVisitor(v, null); + return v.Text; + } + + [Test] + public void AddInteger() + { + Assert.AreEqual("a + 2", AddIntegerToBoe("a + 1", 1)); + Assert.AreEqual("a + 2", AddIntegerToBoe("a + 3", -1)); + Assert.AreEqual("a + b + c + 2", AddIntegerToBoe("a + b + c + 1", 1)); + Assert.AreEqual("a", AddIntegerToBoe("a + 1", -1)); + Assert.AreEqual("2", AddInteger("1", 1)); + Assert.AreEqual("-1", AddInteger("1", -2)); + Assert.AreEqual("0", AddInteger("1", -1)); + Assert.AreEqual("a + 1", AddInteger("a", 1)); + } + + [Test] + public void AddIntegerWithNegativeResult() + { + Assert.AreEqual("a - 1", AddIntegerToBoe("a + 1", -2)); + Assert.AreEqual("a - 2", AddIntegerToBoe("a - 1", -1)); + Assert.AreEqual("a + b + c - 2", AddIntegerToBoe("a + b + c + 2", -4)); + Assert.AreEqual("a + b + c - 6", AddIntegerToBoe("a + b + c - 2", -4)); + Assert.AreEqual("a + b + c", AddIntegerToBoe("a + b + c + 2", -2)); + Assert.AreEqual("a", AddIntegerToBoe("a - 1", 1)); + Assert.AreEqual("a + 1", AddIntegerToBoe("a - 2", 3)); + Assert.AreEqual("a - 1", AddInteger("a", -1)); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/CastExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/CastExpressionTests.cs new file mode 100644 index 000000000..0968fdac6 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/CastExpressionTests.cs @@ -0,0 +1,181 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class CastExpressionTests + { + #region VB.NET + void TestSpecializedCast(string castExpression, Type castType) + { + CastExpression ce = ParseUtil.ParseExpression(castExpression); + Assert.AreEqual(castType.FullName, ce.CastTo.Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.PrimitiveConversion, ce.CastType); + } + + + [Test] + public void VBNetSimpleCastExpression() + { + CastExpression ce = ParseUtil.ParseExpression("CType(o, MyObject)"); + Assert.AreEqual("MyObject", ce.CastTo.Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.Conversion, ce.CastType); + } + + [Test] + public void VBNetGenericCastExpression() + { + CastExpression ce = ParseUtil.ParseExpression("CType(o, List(of T))"); + Assert.AreEqual("List", ce.CastTo.Type); + Assert.AreEqual("T", ce.CastTo.GenericTypes[0].Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.Conversion, ce.CastType); + } + + [Test] + public void VBNetSimpleDirectCastExpression() + { + CastExpression ce = ParseUtil.ParseExpression("DirectCast(o, MyObject)"); + Assert.AreEqual("MyObject", ce.CastTo.Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.Cast, ce.CastType); + } + + [Test] + public void VBNetGenericDirectCastExpression() + { + CastExpression ce = ParseUtil.ParseExpression("DirectCast(o, List(of T))"); + Assert.AreEqual("List", ce.CastTo.Type); + Assert.AreEqual("T", ce.CastTo.GenericTypes[0].Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.Cast, ce.CastType); + } + + [Test] + public void VBNetSimpleTryCastExpression() + { + CastExpression ce = ParseUtil.ParseExpression("TryCast(o, MyObject)"); + Assert.AreEqual("MyObject", ce.CastTo.Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.TryCast, ce.CastType); + } + + [Test] + public void VBNetGenericTryCastExpression() + { + CastExpression ce = ParseUtil.ParseExpression("TryCast(o, List(of T))"); + Assert.AreEqual("List", ce.CastTo.Type); + Assert.AreEqual("T", ce.CastTo.GenericTypes[0].Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + Assert.AreEqual(CastType.TryCast, ce.CastType); + } + + [Test] + public void VBNetSpecializedBoolCastExpression() + { + TestSpecializedCast("CBool(o)", typeof(System.Boolean)); + } + + [Test] + public void VBNetSpecializedCharCastExpression() + { + TestSpecializedCast("CChar(o)", typeof(System.Char)); + } + + + [Test] + public void VBNetSpecializedStringCastExpression() + { + TestSpecializedCast("CStr(o)", typeof(System.String)); + } + + [Test] + public void VBNetSpecializedDateTimeCastExpression() + { + TestSpecializedCast("CDate(o)", typeof(System.DateTime)); + } + + [Test] + public void VBNetSpecializedDecimalCastExpression() + { + TestSpecializedCast("CDec(o)", typeof(System.Decimal)); + } + + [Test] + public void VBNetSpecializedSingleCastExpression() + { + TestSpecializedCast("CSng(o)", typeof(System.Single)); + } + + [Test] + public void VBNetSpecializedDoubleCastExpression() + { + TestSpecializedCast("CDbl(o)", typeof(System.Double)); + } + + [Test] + public void VBNetSpecializedByteCastExpression() + { + TestSpecializedCast("CByte(o)", typeof(System.Byte)); + } + + [Test] + public void VBNetSpecializedInt16CastExpression() + { + TestSpecializedCast("CShort(o)", typeof(System.Int16)); + } + + [Test] + public void VBNetSpecializedInt32CastExpression() + { + TestSpecializedCast("CInt(o)", typeof(System.Int32)); + } + + [Test] + public void VBNetSpecializedInt64CastExpression() + { + TestSpecializedCast("CLng(o)", typeof(System.Int64)); + } + + [Test] + public void VBNetSpecializedSByteCastExpression() + { + TestSpecializedCast("CSByte(o)", typeof(System.SByte)); + } + + [Test] + public void VBNetSpecializedUInt16CastExpression() + { + TestSpecializedCast("CUShort(o)", typeof(System.UInt16)); + } + + [Test] + public void VBNetSpecializedUInt32CastExpression() + { + TestSpecializedCast("CUInt(o)", typeof(System.UInt32)); + } + + [Test] + public void VBNetSpecializedUInt64CastExpression() + { + TestSpecializedCast("CULng(o)", typeof(System.UInt64)); + } + + + [Test] + public void VBNetSpecializedObjectCastExpression() + { + TestSpecializedCast("CObj(o)", typeof(System.Object)); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ClassReferenceExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ClassReferenceExpressionTests.cs new file mode 100644 index 000000000..1d8b43f7d --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ClassReferenceExpressionTests.cs @@ -0,0 +1,24 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ClassReferenceExpressionTests + { + #region VB.NET + [Test] + public void VBNetClassReferenceExpressionTest1() + { + MemberReferenceExpression fre = ParseUtil.ParseExpression("MyClass.myField"); + Assert.IsTrue(fre.TargetObject is ClassReferenceExpression); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ConditionalExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ConditionalExpressionTests.cs new file mode 100644 index 000000000..33e6095dd --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ConditionalExpressionTests.cs @@ -0,0 +1,29 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ConditionalExpressionTests + { + #region VB.NET + + [Test] + public void VBNetConditionalExpressionTest() + { + ConditionalExpression ce = ParseUtil.ParseExpression("If(x IsNot Nothing, x.Test, \"nothing\")"); + + Assert.IsTrue(ce.Condition is BinaryOperatorExpression); + Assert.IsTrue(ce.TrueExpression is MemberReferenceExpression); + Assert.IsTrue(ce.FalseExpression is PrimitiveExpression); + } + + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/GlobalReferenceExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/GlobalReferenceExpressionTests.cs new file mode 100644 index 000000000..08e52a285 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/GlobalReferenceExpressionTests.cs @@ -0,0 +1,32 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class GlobalReferenceExpressionTests + { + [Test] + public void VBNetGlobalReferenceExpressionTest() + { + TypeReferenceExpression tre = ParseUtil.ParseExpression("Global.System"); + Assert.IsTrue(tre.TypeReference.IsGlobal); + Assert.AreEqual("System", tre.TypeReference.Type); + } + + [Test] + public void VBNetGlobalTypeDeclaration() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a As Global.System.String"); + TypeReference typeRef = lvd.GetTypeForVariable(0); + Assert.IsTrue(typeRef.IsGlobal); + Assert.AreEqual("System.String", typeRef.Type); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/IdentifierExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/IdentifierExpressionTests.cs new file mode 100644 index 000000000..26ce34f97 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/IdentifierExpressionTests.cs @@ -0,0 +1,40 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class IdentifierExpressionTests + { + #region VB.NET + [Test] + public void VBNetIdentifierExpressionTest1() + { + IdentifierExpression ie = ParseUtil.ParseExpression("MyIdentifier"); + Assert.AreEqual("MyIdentifier", ie.Identifier); + } + + [Test] + public void VBNetIdentifierExpressionTest2() + { + IdentifierExpression ie = ParseUtil.ParseExpression("[Public]"); + Assert.AreEqual("Public", ie.Identifier); + } + + [Test] + public void VBNetContextKeywordsTest() + { + Assert.AreEqual("Assembly", ParseUtil.ParseExpression("Assembly").Identifier); + Assert.AreEqual("Custom", ParseUtil.ParseExpression("Custom").Identifier); + Assert.AreEqual("Off", ParseUtil.ParseExpression("Off").Identifier); + Assert.AreEqual("Explicit", ParseUtil.ParseExpression("Explicit").Identifier); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/InvocationExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/InvocationExpressionTests.cs new file mode 100644 index 000000000..00ef8bb3c --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/InvocationExpressionTests.cs @@ -0,0 +1,116 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class InvocationExpressionTests + { + void CheckSimpleInvoke(InvocationExpression ie) + { + Assert.AreEqual(0, ie.Arguments.Count); + Assert.IsTrue(ie.TargetObject is IdentifierExpression); + Assert.AreEqual("myMethod", ((IdentifierExpression)ie.TargetObject).Identifier); + } + + void CheckGenericInvoke(InvocationExpression expr) + { + Assert.AreEqual(1, expr.Arguments.Count); + Assert.IsTrue(expr.TargetObject is IdentifierExpression); + IdentifierExpression ident = (IdentifierExpression)expr.TargetObject; + Assert.AreEqual("myMethod", ident.Identifier); + Assert.AreEqual(1, ident.TypeArguments.Count); + Assert.AreEqual("System.Char", ident.TypeArguments[0].Type); + } + + void CheckGenericInvoke2(InvocationExpression expr) + { + Assert.AreEqual(0, expr.Arguments.Count); + Assert.IsTrue(expr.TargetObject is IdentifierExpression); + IdentifierExpression ident = (IdentifierExpression)expr.TargetObject; + Assert.AreEqual("myMethod", ident.Identifier); + Assert.AreEqual(2, ident.TypeArguments.Count); + Assert.AreEqual("T", ident.TypeArguments[0].Type); + Assert.IsFalse(ident.TypeArguments[0].IsKeyword); + Assert.AreEqual("System.Boolean", ident.TypeArguments[1].Type); + Assert.IsTrue(ident.TypeArguments[1].IsKeyword); + } + + #region VB.NET + [Test] + public void VBNetSimpleInvocationExpressionTest() + { + CheckSimpleInvoke(ParseUtil.ParseExpression("myMethod()")); + } + + [Test] + public void VBNetGenericInvocationExpressionTest() + { + CheckGenericInvoke(ParseUtil.ParseExpression("myMethod(Of Char)(\"a\"c)")); + } + + [Test] + public void VBNetGenericInvocation2ExpressionTest() + { + CheckGenericInvoke2(ParseUtil.ParseExpression("myMethod(Of T, Boolean)()")); + } + + [Test] + public void PrimitiveExpression1Test() + { + InvocationExpression ie = ParseUtil.ParseExpression("546.ToString()"); + Assert.AreEqual(0, ie.Arguments.Count); + } + + [Test] + public void VBInvocationOnGenericType() + { + InvocationExpression expr = ParseUtil.ParseExpression("A(Of T).Foo()"); + MemberReferenceExpression mre = (MemberReferenceExpression)expr.TargetObject; + Assert.AreEqual("Foo", mre.MemberName); + IdentifierExpression tre = (IdentifierExpression)mre.TargetObject; + Assert.AreEqual("A", tre.Identifier); + Assert.AreEqual("T", tre.TypeArguments[0].Type); + } + + [Test] + public void VBInvocationOnInnerClassInGenericType() + { + InvocationExpression expr = ParseUtil.ParseExpression("A(Of T).B.Foo()"); + MemberReferenceExpression mre = (MemberReferenceExpression)expr.TargetObject; + Assert.AreEqual("Foo", mre.MemberName); + MemberReferenceExpression mre2 = (MemberReferenceExpression)mre.TargetObject; + Assert.AreEqual("B", mre2.MemberName); + IdentifierExpression tre = (IdentifierExpression)mre2.TargetObject; + Assert.AreEqual("A", tre.Identifier); + Assert.AreEqual("T", tre.TypeArguments[0].Type); + } + + [Test] + public void VBInvocationOnGenericInnerClassInGenericType() + { + InvocationExpression expr = ParseUtil.ParseExpression("A(Of T).B.C(Of U).Foo()"); + MemberReferenceExpression mre = (MemberReferenceExpression)expr.TargetObject; + Assert.AreEqual("Foo", mre.MemberName); + + MemberReferenceExpression mre2 = (MemberReferenceExpression)mre.TargetObject; + Assert.AreEqual("C", mre2.MemberName); + Assert.AreEqual("U", mre2.TypeArguments[0].Type); + + MemberReferenceExpression mre3 = (MemberReferenceExpression)mre2.TargetObject; + Assert.AreEqual("B", mre3.MemberName); + + IdentifierExpression tre = (IdentifierExpression)mre3.TargetObject; + Assert.AreEqual("A", tre.Identifier); + Assert.AreEqual("T", tre.TypeArguments[0].Type); + } + + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/LambdaExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/LambdaExpressionTests.cs new file mode 100644 index 000000000..7afe3ed54 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/LambdaExpressionTests.cs @@ -0,0 +1,137 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class LambdaExpressionTests + { + static LambdaExpression Parse(string program) + { + return ParseUtil.ParseExpression(program); + } + + [Test] + public void LambdaWithParameters() + { + LambdaExpression e = Parse("Function(x As Boolean) x Or True"); + Assert.AreEqual(1, e.Parameters.Count); + Assert.AreEqual("x", e.Parameters[0].ParameterName); + Assert.AreEqual("System.Boolean", e.Parameters[0].TypeReference.Type); + Assert.IsTrue(e.ExpressionBody is BinaryOperatorExpression); + Assert.IsTrue(e.ReturnType.IsNull); + } + + [Test] + public void LambdaWithoutParameters() + { + LambdaExpression e = Parse("Function() x Or True"); + Assert.AreEqual(0, e.Parameters.Count); + Assert.IsTrue(e.ExpressionBody is BinaryOperatorExpression); + Assert.IsTrue(e.ReturnType.IsNull, "ReturnType"); + } + + [Test] + public void NestedLambda() + { + LambdaExpression e = Parse("Function(x As Boolean) Function(y As Boolean) x And y"); + Assert.AreEqual(1, e.Parameters.Count); + Assert.IsTrue(e.ExpressionBody is LambdaExpression); + Assert.IsTrue(e.ReturnType.IsNull, "ReturnType"); + } + + [Test] + public void SubLambda() + { + LambdaExpression e = Parse("Sub(x As Integer) Console.WriteLine(x)"); + Assert.AreEqual(1, e.Parameters.Count); + Assert.IsTrue(e.StatementBody is ExpressionStatement); + Assert.IsNotNull(e.ReturnType); + Assert.AreEqual("System.Void", e.ReturnType.Type); + Assert.IsTrue(e.ReturnType.IsKeyword); + } + + [Test] + public void SubWithStatementLambda() + { + LambdaExpression e = Parse("Sub(x As Integer) Call Console.WriteLine(x)"); + Assert.AreEqual(1, e.Parameters.Count); + Assert.IsTrue(e.StatementBody is ExpressionStatement); + Assert.IsNotNull(e.ReturnType); + Assert.AreEqual("System.Void", e.ReturnType.Type); + Assert.IsTrue(e.ReturnType.IsKeyword); + } + + [Test] + public void MultilineSubLambda() + { + LambdaExpression e = Parse("Sub(x As Integer)\n" + + " For i As Integer = 0 To x\n" + + " Console.WriteLine(i)\n" + + " Next\n" + + "End Sub"); + Assert.AreEqual(1, e.Parameters.Count); + Assert.IsTrue(e.StatementBody is BlockStatement); + Assert.IsNotNull(e.ReturnType); + Assert.AreEqual("System.Void", e.ReturnType.Type); + Assert.IsTrue(e.ReturnType.IsKeyword); + + BlockStatement b = e.StatementBody as BlockStatement; + + Assert.AreEqual(1, b.Children.Count); + Assert.IsTrue(b.Children[0] is ForNextStatement); + } + + [Test] + public void MultilineFunctionLambda() + { + LambdaExpression e = Parse("Function(x As Integer)\n" + + " Dim prod As Integer = 1\n" + + " For i As Integer = 1 To x\n" + + " prod = prod * i\n" + + " Next\n" + + " Return prod\n" + + "End Function"); + Assert.AreEqual(1, e.Parameters.Count); + Assert.IsTrue(e.StatementBody is BlockStatement); + Assert.IsTrue(e.ReturnType.IsNull); + + BlockStatement b = e.StatementBody as BlockStatement; + + Assert.AreEqual(3, b.Children.Count); + Assert.IsTrue(b.Children[0] is LocalVariableDeclaration); + Assert.IsTrue(b.Children[1] is ForNextStatement); + Assert.IsTrue(b.Children[2] is ReturnStatement); + } + + [Test] + public void MultilineFunctionWithReturnTypeLambda() + { + LambdaExpression e = Parse("Function(x As Integer) As Integer\n" + + " Dim prod As Integer = 1\n" + + " For i As Integer = 1 To x\n" + + " prod = prod * i\n" + + " Next\n" + + " Return prod\n" + + "End Function"); + Assert.AreEqual(1, e.Parameters.Count); + Assert.IsTrue(e.StatementBody is BlockStatement); + Assert.IsNotNull(e.ReturnType); + Assert.AreEqual("System.Int32", e.ReturnType.Type); + Assert.IsTrue(e.ReturnType.IsKeyword); + + BlockStatement b = e.StatementBody as BlockStatement; + + Assert.AreEqual(3, b.Children.Count); + Assert.IsTrue(b.Children[0] is LocalVariableDeclaration); + Assert.IsTrue(b.Children[1] is ForNextStatement); + Assert.IsTrue(b.Children[2] is ReturnStatement); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/MemberReferenceExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/MemberReferenceExpressionTests.cs new file mode 100644 index 000000000..fdf3f263e --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/MemberReferenceExpressionTests.cs @@ -0,0 +1,82 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class MemberReferenceExpressionTests + { + #region VB.NET + [Test] + public void VBNetSimpleFieldReferenceExpressionTest() + { + MemberReferenceExpression fre = ParseUtil.ParseExpression("myTargetObject.myField"); + Assert.AreEqual("myField", fre.MemberName); + Assert.IsTrue(fre.TargetObject is IdentifierExpression); + Assert.AreEqual("myTargetObject", ((IdentifierExpression)fre.TargetObject).Identifier); + } + + [Test] + public void VBNetFieldReferenceExpressionWithoutTargetTest() + { + MemberReferenceExpression fre = ParseUtil.ParseExpression(".myField"); + Assert.AreEqual("myField", fre.MemberName); + Assert.IsTrue(fre.TargetObject.IsNull); + } + + [Test] + public void VBNetGenericFieldReferenceExpressionTest() + { + MemberReferenceExpression fre = ParseUtil.ParseExpression("SomeClass(of string).myField"); + Assert.AreEqual("myField", fre.MemberName); + Assert.IsInstanceOf(typeof(IdentifierExpression), fre.TargetObject); + TypeReference tr = ((IdentifierExpression)fre.TargetObject).TypeArguments[0]; + Assert.AreEqual("System.String", tr.Type); + } + + [Test] + public void VBNetFullNamespaceGenericFieldReferenceExpressionTest() + { + MemberReferenceExpression fre = ParseUtil.ParseExpression("System.Subnamespace.SomeClass(of string).myField"); + Assert.AreEqual("myField", fre.MemberName); + Assert.IsInstanceOf(typeof(MemberReferenceExpression), fre.TargetObject); + + MemberReferenceExpression inner = (MemberReferenceExpression)fre.TargetObject; + Assert.AreEqual("SomeClass", inner.MemberName); + Assert.AreEqual(1, inner.TypeArguments.Count); + Assert.AreEqual("System.String", inner.TypeArguments[0].Type); + } + + [Test] + public void VBNetGlobalFullNamespaceGenericFieldReferenceExpressionTest() + { + MemberReferenceExpression fre = ParseUtil.ParseExpression("Global.System.Subnamespace.SomeClass(of string).myField"); + Assert.AreEqual("myField", fre.MemberName); + Assert.IsInstanceOf(typeof(MemberReferenceExpression), fre.TargetObject); + MemberReferenceExpression inner = (MemberReferenceExpression)fre.TargetObject; + + Assert.AreEqual("SomeClass", inner.MemberName); + Assert.AreEqual(1, inner.TypeArguments.Count); + Assert.AreEqual("System.String", inner.TypeArguments[0].Type); + } + + [Test] + public void VBNetNestedGenericFieldReferenceExpressionTest() + { + MemberReferenceExpression fre = ParseUtil.ParseExpression("MyType(of string).InnerClass(of integer).myField"); + Assert.AreEqual("myField", fre.MemberName); + Assert.IsInstanceOf(typeof(MemberReferenceExpression), fre.TargetObject); + + MemberReferenceExpression inner = (MemberReferenceExpression)fre.TargetObject; + Assert.AreEqual("InnerClass", inner.MemberName); + } + + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ObjectCreateExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ObjectCreateExpressionTests.cs new file mode 100644 index 000000000..416e716b6 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ObjectCreateExpressionTests.cs @@ -0,0 +1,114 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ObjectCreateExpressionTests + { + void CheckSimpleObjectCreateExpression(ObjectCreateExpression oce) + { + Assert.AreEqual("MyObject", oce.CreateType.Type); + Assert.AreEqual(3, oce.Parameters.Count); + Assert.IsTrue(oce.ObjectInitializer.IsNull); + + for (int i = 0; i < oce.Parameters.Count; ++i) { + Assert.IsTrue(oce.Parameters[i] is PrimitiveExpression); + } + } + + Expression CheckPropertyInitializationExpression(Expression e, string name) + { + Assert.IsInstanceOf(typeof(MemberInitializerExpression), e); + Assert.AreEqual(name, ((MemberInitializerExpression)e).Name); + return ((MemberInitializerExpression)e).Expression; + } + + [Test] + public void VBNetAnonymousType() + { + ObjectCreateExpression oce = ParseUtil.ParseExpression( + "New With {.Id = 1, .Name= \"Bill Gates\" }"); + + Assert.IsTrue(oce.CreateType.IsNull); + Assert.AreEqual(0, oce.Parameters.Count); + Assert.AreEqual(2, oce.ObjectInitializer.CreateExpressions.Count); + + Assert.IsInstanceOf(typeof(PrimitiveExpression), CheckPropertyInitializationExpression(oce.ObjectInitializer.CreateExpressions[0], "Id")); + Assert.IsInstanceOf(typeof(MemberInitializerExpression), oce.ObjectInitializer.CreateExpressions[1]); + } + + [Test] + public void VBNetAnonymousTypeWithoutProperty() + { + ObjectCreateExpression oce = ParseUtil.ParseExpression("New With { c }"); + + Assert.IsTrue(oce.CreateType.IsNull); + Assert.AreEqual(0, oce.Parameters.Count); + Assert.AreEqual(1, oce.ObjectInitializer.CreateExpressions.Count); + + Assert.IsInstanceOf(typeof(IdentifierExpression), oce.ObjectInitializer.CreateExpressions[0]); + Assert.AreEqual("c", (oce.ObjectInitializer.CreateExpressions[0] as IdentifierExpression).Identifier); + } + + [Test] + public void VBNetSimpleObjectCreateExpressionTest() + { + CheckSimpleObjectCreateExpression(ParseUtil.ParseExpression("New MyObject(1, 2, 3)")); + } + + [Test] + public void VBNetInvalidTypeArgumentListObjectCreateExpressionTest() + { + // this test was written because this bug caused the AbstractDomVisitor to crash + + InvocationExpression expr = ParseUtil.ParseExpression("WriteLine(New SomeGenericType(Of Integer, )())", true); + Assert.IsTrue(expr.TargetObject is IdentifierExpression); + Assert.AreEqual("WriteLine", ((IdentifierExpression)expr.TargetObject).Identifier); + Assert.AreEqual(1, expr.Arguments.Count); // here a second null parameter was added incorrectly + + Assert.IsTrue(expr.Arguments[0] is ObjectCreateExpression); + TypeReference typeRef = ((ObjectCreateExpression)expr.Arguments[0]).CreateType; + Assert.AreEqual("SomeGenericType", typeRef.Type); + Assert.AreEqual(1, typeRef.GenericTypes.Count); + Assert.AreEqual("System.Int32", typeRef.GenericTypes[0].Type); + } + + [Test] + public void VBNetMemberInitializationTest() + { + ObjectCreateExpression oce = ParseUtil.ParseExpression("new Contact() With { .FirstName = \"Bill\", .LastName = \"Gates\" }"); + Assert.AreEqual(2, oce.ObjectInitializer.CreateExpressions.Count); + + Assert.AreEqual("FirstName", ((MemberInitializerExpression)oce.ObjectInitializer.CreateExpressions[0]).Name); + Assert.AreEqual("LastName", ((MemberInitializerExpression)oce.ObjectInitializer.CreateExpressions[1]).Name); + + Assert.IsInstanceOf(typeof(PrimitiveExpression), ((MemberInitializerExpression)oce.ObjectInitializer.CreateExpressions[0]).Expression); + Assert.IsInstanceOf(typeof(PrimitiveExpression), ((MemberInitializerExpression)oce.ObjectInitializer.CreateExpressions[1]).Expression); + } + + [Test] + public void VBNetNullableObjectCreateExpressionTest() + { + ObjectCreateExpression oce = ParseUtil.ParseExpression("New Integer?"); + Assert.AreEqual("System.Nullable", oce.CreateType.Type); + Assert.AreEqual(1, oce.CreateType.GenericTypes.Count); + Assert.AreEqual("System.Int32", oce.CreateType.GenericTypes[0].Type); + } + + [Test] + public void VBNetNullableObjectArrayCreateExpressionTest() + { + ObjectCreateExpression oce = ParseUtil.ParseExpression("New Integer?()"); + Assert.AreEqual("System.Nullable", oce.CreateType.Type); + Assert.AreEqual(1, oce.CreateType.GenericTypes.Count); + Assert.AreEqual("System.Int32", oce.CreateType.GenericTypes[0].Type); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ParenthesizedExpressionTest.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ParenthesizedExpressionTest.cs new file mode 100644 index 000000000..50c2292b2 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ParenthesizedExpressionTest.cs @@ -0,0 +1,26 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ParenthesizedExpressionTests + { + #region VB.NET + [Test] + public void VBNetPrimitiveParenthesizedExpression() + { + ParenthesizedExpression p = ParseUtil.ParseExpression("((1))"); + Assert.IsTrue(p.Expression is ParenthesizedExpression); + p = p.Expression as ParenthesizedExpression;; + Assert.IsTrue(p.Expression is PrimitiveExpression); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/PrimitiveExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/PrimitiveExpressionTests.cs new file mode 100644 index 000000000..7aba4aba3 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/PrimitiveExpressionTests.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class PrimitiveExpressionTests + { + #region VB.NET + [Test] + public void PrimitiveExpression1Test() + { + InvocationExpression ie = ParseUtil.ParseExpression("546.ToString()"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/QueryExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/QueryExpressionTests.cs new file mode 100644 index 000000000..cfc27dfbf --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/QueryExpressionTests.cs @@ -0,0 +1,635 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using System.Linq; + +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Parser; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class QueryExpressionTests + { + void RunTest(string expression, int expectedCount, Action constraint, params Type[] expectedTypes) + { + var expr = ParseUtil.ParseExpression(expression); + + Assert.AreEqual(expectedCount, expr.Clauses.Count); + + for (int i = 0; i < expectedTypes.Length; i++) { + Assert.IsTrue(expectedTypes[i] == expr.Clauses[i].GetType()); + } + + constraint(expr); + } + + [Test] + public void SimpleQueryTest() + { + RunTest("From o In db.Orders Select o.OrderID", 2, + expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var selectClause = expr.Clauses[1] as QueryExpressionSelectVBClause; + + Assert.AreEqual(1, fromClause.Sources.Count); + + var var1 = fromClause.Sources.First(); + + Assert.AreEqual("o", var1.Identifier); + Assert.IsTrue(var1.Expression is MemberReferenceExpression); + var inExpr = var1.Expression as MemberReferenceExpression; + Assert.IsTrue(inExpr.MemberName == "Orders" && inExpr.TargetObject is IdentifierExpression && (inExpr.TargetObject as IdentifierExpression).Identifier == "db"); + + Assert.AreEqual(1, selectClause.Variables.Count); + Assert.IsTrue(selectClause.Variables[0].Expression is MemberReferenceExpression); + var member = selectClause.Variables[0].Expression as MemberReferenceExpression; + + Assert.IsTrue(member.MemberName == "OrderID" && member.TargetObject is IdentifierExpression && (member.TargetObject as IdentifierExpression).Identifier == "o"); + }, + typeof(QueryExpressionFromClause), typeof(QueryExpressionSelectVBClause) + ); + } + + [Test] + public void SkipTakeQueryTest() + { + RunTest("From o In db.Orders Select o.OrderID Skip 10 Take 5", 4, + expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var selectClause = expr.Clauses[1] as QueryExpressionSelectVBClause; + var skipClause = expr.Clauses[2] as QueryExpressionPartitionVBClause; + var takeClause = expr.Clauses[3] as QueryExpressionPartitionVBClause; + + Assert.AreEqual(1, fromClause.Sources.Count); + + var var1 = fromClause.Sources.First(); + + Assert.AreEqual("o", var1.Identifier); + Assert.IsTrue(var1.Expression is MemberReferenceExpression); + var inExpr = var1.Expression as MemberReferenceExpression; + Assert.IsTrue(inExpr.MemberName == "Orders" && inExpr.TargetObject is IdentifierExpression && (inExpr.TargetObject as IdentifierExpression).Identifier == "db"); + + Assert.AreEqual(1, selectClause.Variables.Count); + Assert.IsTrue(selectClause.Variables[0].Expression is MemberReferenceExpression); + var member = selectClause.Variables[0].Expression as MemberReferenceExpression; + + Assert.IsTrue(member.MemberName == "OrderID" && member.TargetObject is IdentifierExpression && (member.TargetObject as IdentifierExpression).Identifier == "o"); + + Assert.AreEqual(QueryExpressionPartitionType.Skip, skipClause.PartitionType); + Assert.IsTrue(skipClause.Expression is PrimitiveExpression && + (skipClause.Expression as PrimitiveExpression).StringValue == "10"); + + Assert.AreEqual(QueryExpressionPartitionType.Take, takeClause.PartitionType); + Assert.IsTrue(takeClause.Expression is PrimitiveExpression && + (takeClause.Expression as PrimitiveExpression).StringValue == "5"); + }, + typeof(QueryExpressionFromClause), typeof(QueryExpressionSelectVBClause), + typeof(QueryExpressionPartitionVBClause), typeof(QueryExpressionPartitionVBClause) + ); + } + + [Test] + public void SkipWhileTakeWhileQueryTest() + { + RunTest("From o In db.Orders Select o.OrderID Skip While o.OrderId > 2 Take While o.OrderId < 5", 4, + expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var selectClause = expr.Clauses[1] as QueryExpressionSelectVBClause; + var skipClause = expr.Clauses[2] as QueryExpressionPartitionVBClause; + var takeClause = expr.Clauses[3] as QueryExpressionPartitionVBClause; + + Assert.AreEqual(1, fromClause.Sources.Count); + + var var1 = fromClause.Sources.First(); + + Assert.AreEqual("o", var1.Identifier); + Assert.IsTrue(var1.Expression is MemberReferenceExpression); + var inExpr = var1.Expression as MemberReferenceExpression; + Assert.IsTrue(inExpr.MemberName == "Orders" && inExpr.TargetObject is IdentifierExpression && (inExpr.TargetObject as IdentifierExpression).Identifier == "db"); + + Assert.AreEqual(1, selectClause.Variables.Count); + Assert.IsTrue(selectClause.Variables[0].Expression is MemberReferenceExpression); + var member = selectClause.Variables[0].Expression as MemberReferenceExpression; + + Assert.IsTrue(member.MemberName == "OrderID" && member.TargetObject is IdentifierExpression && (member.TargetObject as IdentifierExpression).Identifier == "o"); + + Assert.AreEqual(QueryExpressionPartitionType.SkipWhile, skipClause.PartitionType); + Assert.IsTrue(skipClause.Expression is BinaryOperatorExpression); + + Assert.AreEqual(QueryExpressionPartitionType.TakeWhile, takeClause.PartitionType); + Assert.IsTrue(takeClause.Expression is BinaryOperatorExpression); + }, + typeof(QueryExpressionFromClause), typeof(QueryExpressionSelectVBClause), + typeof(QueryExpressionPartitionVBClause), typeof(QueryExpressionPartitionVBClause) + ); + } + + [Test] + public void MultipleValuesSelectTest() + { + RunTest(@"From i In list Select i, x2 = i^2", + 2, expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var selectClause = expr.Clauses[1] as QueryExpressionSelectVBClause; + + Assert.AreEqual(1, fromClause.Sources.Count); + + var var1 = fromClause.Sources.First(); + + Assert.AreEqual("i", var1.Identifier); + Assert.IsTrue(var1.Expression is IdentifierExpression); + Assert.IsTrue((var1.Expression as IdentifierExpression).Identifier == "list"); + + Assert.AreEqual(2, selectClause.Variables.Count); + + var selectExpr1 = selectClause.Variables[0]; + var selectExpr2 = selectClause.Variables[1]; + + Assert.IsEmpty(selectExpr1.Identifier); + Assert.IsTrue(selectExpr1.Expression is IdentifierExpression && + (selectExpr1.Expression as IdentifierExpression).Identifier == "i"); + + Assert.AreEqual("x2", selectExpr2.Identifier); + Assert.IsTrue(selectExpr2.Type.IsNull); + Assert.IsTrue(selectExpr2.Expression is BinaryOperatorExpression); + + var binOp = selectExpr2.Expression as BinaryOperatorExpression; + + Assert.AreEqual(BinaryOperatorType.Power, binOp.Op); + Assert.IsTrue(binOp.Left is IdentifierExpression && (binOp.Left as IdentifierExpression).Identifier == "i"); + Assert.IsTrue(binOp.Right is PrimitiveExpression && (binOp.Right as PrimitiveExpression).StringValue == "2"); + }, + typeof(QueryExpressionFromClause), typeof(QueryExpressionSelectVBClause) + ); + } + + [Test] + public void GroupTest() + { + Action constraint = expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var groupClause = expr.Clauses[1] as QueryExpressionGroupVBClause; + var selectClause = expr.Clauses[2] as QueryExpressionSelectVBClause; + + Assert.AreEqual(1, fromClause.Sources.Count); + + var fromVar1 = fromClause.Sources.First(); + + Assert.AreEqual("p", fromVar1.Identifier); + Assert.IsTrue(fromVar1.Expression is IdentifierExpression); + Assert.IsTrue((fromVar1.Expression as IdentifierExpression).Identifier == "products"); + + Assert.AreEqual(1, groupClause.GroupVariables.Count); + Assert.AreEqual(1, groupClause.ByVariables.Count); + Assert.AreEqual(1, groupClause.IntoVariables.Count); + + var gv = groupClause.GroupVariables.First(); + var bv = groupClause.ByVariables.First(); + var iv = groupClause.IntoVariables.First(); + + Assert.IsTrue(gv.Expression is IdentifierExpression && (gv.Expression as IdentifierExpression).Identifier == "p"); + Assert.IsTrue(bv.Expression is MemberReferenceExpression && + (bv.Expression as MemberReferenceExpression).MemberName == "Category"); + Assert.IsTrue((bv.Expression as MemberReferenceExpression).TargetObject is IdentifierExpression && + ((bv.Expression as MemberReferenceExpression).TargetObject as IdentifierExpression).Identifier == "p"); + Assert.IsTrue(iv.Expression is IdentifierExpression && + (iv.Expression as IdentifierExpression).Identifier == "Group"); + + Assert.AreEqual(2, selectClause.Variables.Count); + + var var1 = selectClause.Variables.First(); + var var2 = selectClause.Variables.Skip(1).First(); + + Assert.IsTrue(var1.Expression is IdentifierExpression && + (var1.Expression as IdentifierExpression).Identifier == "Category"); + Assert.IsTrue(var2.Expression is InvocationExpression && + (var2.Expression as InvocationExpression).TargetObject is MemberReferenceExpression && + ((var2.Expression as InvocationExpression).TargetObject as MemberReferenceExpression).MemberName == "Average" && + ((var2.Expression as InvocationExpression).TargetObject as MemberReferenceExpression).TargetObject is IdentifierExpression && + (((var2.Expression as InvocationExpression).TargetObject as MemberReferenceExpression).TargetObject as IdentifierExpression).Identifier == "Group"); + }; + + RunTest(@"From p In products _ + Group p By p.Category Into Group _ + Select Category, AveragePrice = Group.Average(Function(p) p.UnitPrice)", 3, constraint, + typeof(QueryExpressionFromClause), typeof(QueryExpressionGroupVBClause), typeof(QueryExpressionSelectVBClause)); + } + + [Test] + public void LetTest() + { + Action constraint = expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var groupClause = expr.Clauses[1] as QueryExpressionGroupVBClause; + var letClause = expr.Clauses[2] as QueryExpressionLetVBClause; + var selectClause = expr.Clauses[3] as QueryExpressionSelectVBClause; + + // From + Assert.AreEqual(1, fromClause.Sources.Count); + + var fromVar1 = fromClause.Sources.First(); + + Assert.AreEqual("p", fromVar1.Identifier); + Assert.IsTrue(fromVar1.Expression is IdentifierExpression); + Assert.IsTrue((fromVar1.Expression as IdentifierExpression).Identifier == "products"); + + // Group By Into + Assert.AreEqual(1, groupClause.GroupVariables.Count); + Assert.AreEqual(1, groupClause.ByVariables.Count); + Assert.AreEqual(1, groupClause.IntoVariables.Count); + + var gv = groupClause.GroupVariables.First(); + var bv = groupClause.ByVariables.First(); + var iv = groupClause.IntoVariables.First(); + + Assert.IsTrue(gv.Expression is IdentifierExpression && (gv.Expression as IdentifierExpression).Identifier == "p"); + CheckMemberReferenceExpression(bv.Expression, "Category", "p"); + Assert.IsTrue(iv.Expression is IdentifierExpression && + (iv.Expression as IdentifierExpression).Identifier == "Group"); + + // Let + Assert.AreEqual(1, letClause.Variables.Count); + + var letVariable = letClause.Variables.First(); + + Assert.AreEqual("minPrice", letVariable.Identifier); + Assert.IsTrue(letVariable.Expression is InvocationExpression); + CheckMemberReferenceExpression((letVariable.Expression as InvocationExpression).TargetObject, "Min", "Group"); + + // Select + Assert.AreEqual(2, selectClause.Variables.Count); + + var var1 = selectClause.Variables.First(); + var var2 = selectClause.Variables.Skip(1).First(); + + Assert.IsTrue(var1.Expression is IdentifierExpression && + (var1.Expression as IdentifierExpression).Identifier == "Category"); + Assert.IsTrue(var2.Expression is InvocationExpression); + CheckMemberReferenceExpression((var2.Expression as InvocationExpression).TargetObject, "Where", "Group"); + }; + + RunTest(@"From p In products _ + Group p By p.Category Into Group _ + Let minPrice = Group.Min(Function(p) p.UnitPrice) _ + Select Category, CheapestProducts = Group.Where(Function(p) p.UnitPrice = minPrice)", 4, constraint, + typeof(QueryExpressionFromClause), typeof(QueryExpressionGroupVBClause), typeof(QueryExpressionLetVBClause), typeof(QueryExpressionSelectVBClause)); + } + + [Test] + public void CrossJoinTest() + { + Action constraint = expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var joinClause = expr.Clauses[1] as QueryExpressionJoinVBClause; + var selectClause = expr.Clauses[2] as QueryExpressionSelectVBClause; + + // From + Assert.AreEqual(1, fromClause.Sources.Count); + + var fromVar1 = fromClause.Sources.First(); + + Assert.AreEqual("c", fromVar1.Identifier); + Assert.IsTrue(fromVar1.Expression is IdentifierExpression); + Assert.IsTrue((fromVar1.Expression as IdentifierExpression).Identifier == "categories"); + + // Join In On Equals + var inClause = joinClause.JoinVariable as CollectionRangeVariable; + + Assert.AreEqual("p", inClause.Identifier); + Assert.IsTrue(inClause.Expression is IdentifierExpression && + (inClause.Expression as IdentifierExpression).Identifier == "products"); + + Assert.IsTrue(joinClause.SubJoin.IsNull); + + Assert.AreEqual(1, joinClause.Conditions.Count); + + var condition1 = joinClause.Conditions.First(); + + Assert.IsTrue(condition1.LeftSide is IdentifierExpression && (condition1.LeftSide as IdentifierExpression).Identifier == "c"); + + CheckMemberReferenceExpression(condition1.RightSide, "Category", "p"); + + // Select + Assert.AreEqual(2, selectClause.Variables.Count); + + var var1 = selectClause.Variables.First(); + var var2 = selectClause.Variables.Skip(1).First(); + + Assert.AreEqual("Category", var1.Identifier); + Assert.IsEmpty(var2.Identifier); + + Assert.IsTrue(var1.Expression is IdentifierExpression && + (var1.Expression as IdentifierExpression).Identifier == "c"); + CheckMemberReferenceExpression(var2.Expression, "ProductName", "p"); + }; + + RunTest(@"From c In categories _ + Join p In products On c Equals p.Category _ + Select Category = c, p.ProductName", 3, constraint, + typeof(QueryExpressionFromClause), typeof(QueryExpressionJoinVBClause), typeof(QueryExpressionSelectVBClause)); + } + + [Test] + public void OrderByTest() + { + Action constraint = expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var orderClause = expr.Clauses[1] as QueryExpressionOrderClause; + + // From + Assert.AreEqual(1, fromClause.Sources.Count); + + var var1 = fromClause.Sources.First(); + + Assert.AreEqual("i", var1.Identifier); + Assert.IsTrue(var1.Expression is IdentifierExpression); + Assert.IsTrue((var1.Expression as IdentifierExpression).Identifier == "list"); + + // Order By + Assert.AreEqual(1, orderClause.Orderings.Count); + + var ordering1 = orderClause.Orderings.First(); + + Assert.IsTrue(ordering1.Criteria is IdentifierExpression && + (ordering1.Criteria as IdentifierExpression).Identifier == "i"); + Assert.AreEqual(QueryExpressionOrderingDirection.None, ordering1.Direction); + }; + + RunTest(@"From i In list Order By i", 2, constraint, typeof(QueryExpressionFromClause), typeof(QueryExpressionOrderClause)); + } + + [Test] + public void OrderByTest2() + { + Action constraint = expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var orderClause = expr.Clauses[1] as QueryExpressionOrderClause; + + // From + Assert.AreEqual(1, fromClause.Sources.Count); + + var var1 = fromClause.Sources.First(); + + Assert.AreEqual("i", var1.Identifier); + Assert.IsTrue(var1.Expression is IdentifierExpression); + Assert.IsTrue((var1.Expression as IdentifierExpression).Identifier == "list"); + + // Order By + Assert.AreEqual(1, orderClause.Orderings.Count); + + var ordering1 = orderClause.Orderings.First(); + + Assert.IsTrue(ordering1.Criteria is IdentifierExpression && + (ordering1.Criteria as IdentifierExpression).Identifier == "i"); + Assert.AreEqual(QueryExpressionOrderingDirection.Ascending, ordering1.Direction); + }; + + RunTest(@"From i In list Order By i Ascending", 2, constraint, typeof(QueryExpressionFromClause), typeof(QueryExpressionOrderClause)); + } + + [Test] + public void OrderByTest3() + { + Action constraint = expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var orderClause = expr.Clauses[1] as QueryExpressionOrderClause; + + // From + Assert.AreEqual(1, fromClause.Sources.Count); + + var var1 = fromClause.Sources.First(); + + Assert.AreEqual("i", var1.Identifier); + Assert.IsTrue(var1.Expression is IdentifierExpression); + Assert.IsTrue((var1.Expression as IdentifierExpression).Identifier == "list"); + + // Order By + Assert.AreEqual(1, orderClause.Orderings.Count); + + var ordering1 = orderClause.Orderings.First(); + + Assert.IsTrue(ordering1.Criteria is IdentifierExpression && + (ordering1.Criteria as IdentifierExpression).Identifier == "i"); + Assert.AreEqual(QueryExpressionOrderingDirection.Descending, ordering1.Direction); + }; + + RunTest(@"From i In list Order By i Descending", 2, constraint, typeof(QueryExpressionFromClause), typeof(QueryExpressionOrderClause)); + } + + [Test] + public void OrderByThenByTest() + { + Action constraint = expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var orderClause = expr.Clauses[1] as QueryExpressionOrderClause; + + // From + Assert.AreEqual(1, fromClause.Sources.Count); + + var var1 = fromClause.Sources.First(); + + Assert.AreEqual("d", var1.Identifier); + Assert.IsTrue(var1.Expression is IdentifierExpression); + Assert.IsTrue((var1.Expression as IdentifierExpression).Identifier == "digits"); + + // Order By + Assert.AreEqual(2, orderClause.Orderings.Count); + + var ordering1 = orderClause.Orderings.First(); + var ordering2 = orderClause.Orderings.Skip(1).First(); + + CheckMemberReferenceExpression(ordering1.Criteria, "Length", "d"); + + Assert.IsTrue(ordering2.Criteria is IdentifierExpression && + (ordering2.Criteria as IdentifierExpression).Identifier == "d"); + + Assert.AreEqual(QueryExpressionOrderingDirection.None, ordering1.Direction); + Assert.AreEqual(QueryExpressionOrderingDirection.None, ordering2.Direction); + + }; + + RunTest(@"From d In digits _ + Order By d.Length, d", 2, constraint, + typeof(QueryExpressionFromClause), typeof(QueryExpressionOrderClause)); + } + + [Test] + public void DistinctTest() + { + Action constraint = expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + + // From + Assert.AreEqual(1, fromClause.Sources.Count); + + var var1 = fromClause.Sources.First(); + + Assert.AreEqual("d", var1.Identifier); + Assert.IsTrue(var1.Expression is IdentifierExpression); + Assert.IsTrue((var1.Expression as IdentifierExpression).Identifier == "digits"); + }; + + RunTest(@"From d In digits Distinct", 2, constraint, + typeof(QueryExpressionFromClause), typeof(QueryExpressionDistinctClause)); + } + + [Test] + public void AggregateTest() + { + Action constraint = expr => { + var clause = expr.Clauses[0] as QueryExpressionAggregateClause; + + Assert.AreEqual("p", clause.Source.Identifier); + CheckMemberReferenceExpression(clause.Source.Expression, "GetProcesses", "Process"); + + Assert.AreEqual(1, clause.IntoVariables.Count); + + var into1 = clause.IntoVariables.First(); + + Assert.AreEqual("virtualMemory", into1.Identifier); + + Assert.IsTrue(into1.Expression is InvocationExpression && + (into1.Expression as InvocationExpression).TargetObject is IdentifierExpression && + ((into1.Expression as InvocationExpression).TargetObject as IdentifierExpression).Identifier == "Sum"); + Assert.AreEqual(1, (into1.Expression as InvocationExpression).Arguments.Count); + CheckMemberReferenceExpression((into1.Expression as InvocationExpression).Arguments.First(), "VirtualMemorySize64", "p"); + }; + + RunTest(@"Aggregate p In Process.GetProcesses _ + Into virtualMemory = Sum(p.VirtualMemorySize64)", 1, constraint, typeof(QueryExpressionAggregateClause)); + } + + [Test] + public void GroupJoinTest() + { + Action constraint = expr => { + var fromClause1 = expr.Clauses[0] as QueryExpressionFromClause; + var groupJoinClause = expr.Clauses[1] as QueryExpressionGroupJoinVBClause; + var fromClause2 = expr.Clauses[2] as QueryExpressionFromClause; + var selectClause = expr.Clauses[3] as QueryExpressionSelectVBClause; + + // From 1 + Assert.AreEqual(1, fromClause1.Sources.Count); + + var var1 = fromClause1.Sources.First(); + + Assert.AreEqual("s", var1.Identifier); + Assert.IsTrue(var1.Expression is IdentifierExpression && + (var1.Expression as IdentifierExpression).Identifier == "fileList"); + + // From 2 + Assert.AreEqual(1, fromClause2.Sources.Count); + + var var2 = fromClause2.Sources.First(); + + Assert.AreEqual("p", var2.Identifier); + Assert.IsTrue(var2.Expression is IdentifierExpression && + (var2.Expression as IdentifierExpression).Identifier == "Group"); + + // Select + Assert.AreEqual(1, selectClause.Variables.Count); + + var var3 = selectClause.Variables.First(); + + Assert.IsEmpty(var3.Identifier); + Assert.IsTrue(var3.Expression is IdentifierExpression && + (var3.Expression as IdentifierExpression).Identifier == "s"); + + // Group Join + var joinClause = groupJoinClause.JoinClause; + + // Join In On Equals + var inClause = joinClause.JoinVariable as CollectionRangeVariable; + + Assert.AreEqual("p", inClause.Identifier); + Assert.IsTrue(inClause.Expression is IdentifierExpression && + (inClause.Expression as IdentifierExpression).Identifier == "IMAGES"); + + Assert.IsTrue(joinClause.SubJoin.IsNull); + + Assert.AreEqual(1, joinClause.Conditions.Count); + + var condition1 = joinClause.Conditions.First(); + + Assert.IsTrue(condition1.LeftSide is InvocationExpression); + Assert.IsTrue((condition1.LeftSide as InvocationExpression).TargetObject is MemberReferenceExpression); + Assert.IsTrue(((condition1.LeftSide as InvocationExpression).TargetObject as MemberReferenceExpression).MemberName == "ToUpper"); + Assert.IsTrue(((condition1.LeftSide as InvocationExpression).TargetObject as MemberReferenceExpression).TargetObject is MemberReferenceExpression); + Assert.IsTrue((((condition1.LeftSide as InvocationExpression).TargetObject as MemberReferenceExpression).TargetObject as MemberReferenceExpression).MemberName == "Extension"); + Assert.IsTrue((((condition1.LeftSide as InvocationExpression).TargetObject as MemberReferenceExpression).TargetObject as MemberReferenceExpression).TargetObject is IdentifierExpression); + Assert.IsTrue(((((condition1.LeftSide as InvocationExpression).TargetObject as MemberReferenceExpression).TargetObject as MemberReferenceExpression).TargetObject as IdentifierExpression).Identifier == "s"); + + Assert.IsTrue(condition1.RightSide is InvocationExpression); + Assert.IsTrue((condition1.RightSide as InvocationExpression).TargetObject is MemberReferenceExpression); + Assert.IsTrue(((condition1.RightSide as InvocationExpression).TargetObject as MemberReferenceExpression).MemberName == "ToUpper"); + Assert.IsTrue(((condition1.RightSide as InvocationExpression).TargetObject as MemberReferenceExpression).TargetObject is IdentifierExpression); + Assert.IsTrue((((condition1.RightSide as InvocationExpression).TargetObject as MemberReferenceExpression).TargetObject as IdentifierExpression).Identifier == "p"); + }; + + RunTest(@"From s In fileList _ +Group Join p In IMAGES On s.Extension.ToUpper() Equals p.ToUpper() Into Group _ +From p In Group _ +Select s", 4, constraint, + typeof(QueryExpressionFromClause), typeof(QueryExpressionGroupJoinVBClause), typeof(QueryExpressionFromClause), typeof(QueryExpressionSelectVBClause)); + } + + [Test] + public void SelectManyTest() + { + Action constraint = expr => { + var fromClause = expr.Clauses[0] as QueryExpressionFromClause; + var whereClause = expr.Clauses[1] as QueryExpressionWhereClause; + var selectClause = expr.Clauses[2] as QueryExpressionSelectVBClause; + + // From + Assert.AreEqual(2, fromClause.Sources.Count); + + var fromVar1 = fromClause.Sources.First(); + var fromVar2 = fromClause.Sources.Skip(1).First(); + + Assert.AreEqual("c", fromVar1.Identifier); + Assert.IsTrue(fromVar1.Expression is IdentifierExpression); + Assert.IsTrue((fromVar1.Expression as IdentifierExpression).Identifier == "customers"); + + Assert.AreEqual("o", fromVar2.Identifier); + CheckMemberReferenceExpression(fromVar2.Expression, "Orders", "c"); + + // Where + Assert.IsTrue(whereClause.Condition is BinaryOperatorExpression); + Assert.IsTrue((whereClause.Condition as BinaryOperatorExpression).Op == BinaryOperatorType.LessThan); + CheckMemberReferenceExpression((whereClause.Condition as BinaryOperatorExpression).Left, "Total", "o"); + Assert.IsTrue((whereClause.Condition as BinaryOperatorExpression).Right is PrimitiveExpression); + Assert.IsTrue((double)((whereClause.Condition as BinaryOperatorExpression).Right as PrimitiveExpression).Value == 500.0); + + // Select + foreach (var v in selectClause.Variables) { + Assert.IsEmpty(v.Identifier); + } + + var var1 = selectClause.Variables.First(); + var var2 = selectClause.Variables.Skip(1).First(); + var var3 = selectClause.Variables.Skip(2).First(); + + CheckMemberReferenceExpression(var1.Expression, "CustomerID", "c"); + CheckMemberReferenceExpression(var2.Expression, "OrderID", "o"); + CheckMemberReferenceExpression(var3.Expression, "Total", "o"); + }; + + RunTest(@"From c In customers, o In c.Orders _ + Where o.Total < 500.0 _ + Select c.CustomerID, o.OrderID, o.Total", 3, constraint, typeof(QueryExpressionFromClause), typeof(QueryExpressionWhereClause), typeof(QueryExpressionSelectVBClause)); + } + + void CheckMemberReferenceExpression(Expression expr, string memberName, string targetObjectIdentifier) + { + Assert.IsTrue(expr is MemberReferenceExpression); + Assert.IsTrue((expr as MemberReferenceExpression).MemberName == memberName && + (expr as MemberReferenceExpression).TargetObject is IdentifierExpression && + ((expr as MemberReferenceExpression).TargetObject as IdentifierExpression).Identifier == targetObjectIdentifier); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ThisReferenceExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ThisReferenceExpressionTests.cs new file mode 100644 index 000000000..b5c736ba1 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/ThisReferenceExpressionTests.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ThisReferenceExpressionTests + { + #region VB.NET + [Test] + public void VBNetThisReferenceExpressionTest1() + { + ThisReferenceExpression ie = ParseUtil.ParseExpression("Me"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeOfExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeOfExpressionTests.cs new file mode 100644 index 000000000..87f1ca03a --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeOfExpressionTests.cs @@ -0,0 +1,87 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class TypeOfExpressionTests + { + #region VB.NET + [Test] + public void VBSimpleTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtil.ParseExpression("GetType(MyNamespace.N1.MyType)"); + Assert.AreEqual("MyNamespace.N1.MyType", toe.TypeReference.Type); + } + + + [Test] + public void VBGlobalTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtil.ParseExpression("GetType(Global.System.Console)"); + Assert.AreEqual("System.Console", toe.TypeReference.Type); + } + + [Test] + public void VBPrimitiveTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtil.ParseExpression("GetType(integer)"); + Assert.AreEqual("System.Int32", toe.TypeReference.Type); + } + + [Test] + public void VBVoidTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtil.ParseExpression("GetType(void)"); + Assert.AreEqual("void", toe.TypeReference.Type); + } + + [Test] + public void VBArrayTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtil.ParseExpression("GetType(MyType())"); + Assert.AreEqual("MyType", toe.TypeReference.Type); + Assert.AreEqual(new int[] {0}, toe.TypeReference.RankSpecifier); + } + + [Test] + public void VBGenericTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtil.ParseExpression("GetType(MyNamespace.N1.MyType(Of string))"); + Assert.AreEqual("MyNamespace.N1.MyType", toe.TypeReference.Type); + Assert.AreEqual("System.String", toe.TypeReference.GenericTypes[0].Type); + } + + [Test] + public void VBUnboundTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtil.ParseExpression("GetType(MyType(Of ,))"); + Assert.AreEqual("MyType", toe.TypeReference.Type); + Assert.IsTrue(toe.TypeReference.GenericTypes[0].IsNull); + Assert.IsTrue(toe.TypeReference.GenericTypes[1].IsNull); + } + + [Test] + public void VBNestedGenericTypeOfExpressionTest() + { + TypeOfExpression toe = ParseUtil.ParseExpression("GetType(MyType(Of string).InnerClass(of integer).InnerInnerClass)"); + InnerClassTypeReference ic = (InnerClassTypeReference)toe.TypeReference; + Assert.AreEqual("InnerInnerClass", ic.Type); + Assert.AreEqual(0, ic.GenericTypes.Count); + ic = (InnerClassTypeReference)ic.BaseType; + Assert.AreEqual("InnerClass", ic.Type); + Assert.AreEqual(1, ic.GenericTypes.Count); + Assert.AreEqual("System.Int32", ic.GenericTypes[0].Type); + Assert.AreEqual("MyType", ic.BaseType.Type); + Assert.AreEqual(1, ic.BaseType.GenericTypes.Count); + Assert.AreEqual("System.String", ic.BaseType.GenericTypes[0].Type); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeOfIsExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeOfIsExpressionTests.cs new file mode 100644 index 000000000..6af478d8e --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeOfIsExpressionTests.cs @@ -0,0 +1,34 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class TypeOfIsExpressionTests + { + #region VB.NET + [Test] + public void VBNetSimpleTypeOfIsExpression() + { + TypeOfIsExpression ce = ParseUtil.ParseExpression("TypeOf o Is MyObject"); + Assert.AreEqual("MyObject", ce.TypeReference.Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + } + + [Test] + public void VBNetGenericTypeOfIsExpression() + { + TypeOfIsExpression ce = ParseUtil.ParseExpression("TypeOf o Is List(of T)"); + Assert.AreEqual("List", ce.TypeReference.Type); + Assert.AreEqual("T", ce.TypeReference.GenericTypes[0].Type); + Assert.IsTrue(ce.Expression is IdentifierExpression); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeReferenceExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeReferenceExpressionTests.cs new file mode 100644 index 000000000..d3d816ba0 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/TypeReferenceExpressionTests.cs @@ -0,0 +1,47 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class TypeReferenceExpressionTests + { + #region VB.NET + [Test] + public void VBIntReferenceExpression() + { + MemberReferenceExpression fre = ParseUtil.ParseExpression("inTeGer.MaxValue"); + Assert.AreEqual("MaxValue", fre.MemberName); + Assert.AreEqual("System.Int32", ((TypeReferenceExpression)fre.TargetObject).TypeReference.Type); + } + + [Test] + public void VBStandaloneIntReferenceExpression() + { + TypeReferenceExpression tre = ParseUtil.ParseExpression("inTeGer"); + Assert.AreEqual("System.Int32", tre.TypeReference.Type); + } + + [Test] + public void VBObjectReferenceExpression() + { + MemberReferenceExpression fre = ParseUtil.ParseExpression("Object.ReferenceEquals"); + Assert.AreEqual("ReferenceEquals", fre.MemberName); + Assert.AreEqual("System.Object", ((TypeReferenceExpression)fre.TargetObject).TypeReference.Type); + } + + [Test] + public void VBStandaloneObjectReferenceExpression() + { + TypeReferenceExpression tre = ParseUtil.ParseExpression("obJect"); + Assert.AreEqual("System.Object", tre.TypeReference.Type); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/UnaryOperatorExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/UnaryOperatorExpressionTests.cs new file mode 100644 index 000000000..771291c38 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/UnaryOperatorExpressionTests.cs @@ -0,0 +1,61 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class UnaryOperatorExpressionTests + { + #region VB.NET + void VBNetTestUnaryOperatorExpressionTest(string program, UnaryOperatorType op) + { + UnaryOperatorExpression uoe = ParseUtil.ParseExpression(program); + Assert.AreEqual(op, uoe.Op); + + Assert.IsTrue(uoe.Expression is IdentifierExpression); + } + + [Test] + public void VBNetNotTest() + { + VBNetTestUnaryOperatorExpressionTest("Not a", UnaryOperatorType.Not); + } + + [Test] + public void VBNetInEqualsNotTest() + { + BinaryOperatorExpression e = ParseUtil.ParseExpression("b <> Not a"); + Assert.AreEqual(BinaryOperatorType.InEquality, e.Op); + UnaryOperatorExpression ue = (UnaryOperatorExpression)e.Right; + Assert.AreEqual(UnaryOperatorType.Not, ue.Op); + } + + [Test] + public void VBNetNotEqualTest() + { + UnaryOperatorExpression e = ParseUtil.ParseExpression("Not a = b"); + Assert.AreEqual(UnaryOperatorType.Not, e.Op); + BinaryOperatorExpression boe = (BinaryOperatorExpression)e.Expression; + Assert.AreEqual(BinaryOperatorType.Equality, boe.Op); + } + + [Test] + public void VBNetPlusTest() + { + VBNetTestUnaryOperatorExpressionTest("+a", UnaryOperatorType.Plus); + } + + [Test] + public void VBNetMinusTest() + { + VBNetTestUnaryOperatorExpressionTest("-a", UnaryOperatorType.Minus); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/XmlExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/XmlExpressionTests.cs new file mode 100644 index 000000000..9c5602dc7 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/XmlExpressionTests.cs @@ -0,0 +1,255 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class XmlExpressionTests + { + #region VB.NET + [Test] + public void VBNetSimpleCommentTest() + { + XmlContentExpression content = ParseUtil.ParseExpression(""); + Assert.AreEqual(XmlContentType.Comment, content.Type); + Assert.AreEqual(" test ", content.Content); + Assert.AreEqual(new Location(1,1), content.StartLocation); + Assert.AreEqual(new Location(14,1), content.EndLocation); + } + + [Test] + public void VBNetSimplePreprocessingInstructionTest() + { + XmlContentExpression content = ParseUtil.ParseExpression(""); + Assert.AreEqual(XmlContentType.ProcessingInstruction, content.Type); + Assert.AreEqual("xml version='1.0'", content.Content); + Assert.AreEqual(new Location(1,1), content.StartLocation); + Assert.AreEqual(new Location(22,1), content.EndLocation); + } + + [Test] + public void VBNetSimpleCDataTest() + { + XmlContentExpression content = ParseUtil.ParseExpression(" ]]>"); + Assert.AreEqual(XmlContentType.CData, content.Type); + Assert.AreEqual(" ", content.Content); + Assert.AreEqual(new Location(1,1), content.StartLocation); + Assert.AreEqual(new Location(29,1), content.EndLocation); + } + + [Test] + public void VBNetSimpleEmptyElementTest() + { + XmlElementExpression element = ParseUtil.ParseExpression(""); + Assert.IsFalse(element.NameIsExpression); + Assert.AreEqual("Test", element.XmlName); + Assert.IsEmpty(element.Attributes); + Assert.IsEmpty(element.Children); + Assert.AreEqual(new Location(1,1), element.StartLocation); + Assert.AreEqual(new Location(9,1), element.EndLocation); + } + + [Test] + public void VBNetSimpleEmptyElementWithAttributeTest() + { + XmlElementExpression element = ParseUtil.ParseExpression(""); + Assert.IsFalse(element.NameIsExpression); + Assert.AreEqual("Test", element.XmlName); + Assert.IsNotEmpty(element.Attributes); + Assert.AreEqual(1, element.Attributes.Count); + Assert.IsTrue(element.Attributes[0] is XmlAttributeExpression); + XmlAttributeExpression attribute = element.Attributes[0] as XmlAttributeExpression; + Assert.AreEqual("id", attribute.Name); + Assert.IsTrue(attribute.IsLiteralValue); + Assert.IsTrue(attribute.ExpressionValue.IsNull); + Assert.AreEqual("0", attribute.LiteralValue); + Assert.AreEqual(new Location(7,1), attribute.StartLocation); + Assert.AreEqual(new Location(13,1), attribute.EndLocation); + Assert.IsEmpty(element.Children); + Assert.AreEqual(new Location(1,1), element.StartLocation); + Assert.AreEqual(new Location(16,1), element.EndLocation); + } + + [Test] + public void VBNetSimpleEmptyElementWithAttributesTest() + { + XmlElementExpression element = ParseUtil.ParseExpression(" <%= contentData %> />"); Assert.IsFalse(element.NameIsExpression); + Assert.AreEqual("Test", element.XmlName); + Assert.IsNotEmpty(element.Attributes); + Assert.AreEqual(3, element.Attributes.Count); + + Assert.IsTrue(element.Attributes[0] is XmlAttributeExpression); + XmlAttributeExpression attribute = element.Attributes[0] as XmlAttributeExpression; + Assert.AreEqual("id", attribute.Name); + Assert.IsTrue(attribute.IsLiteralValue); + Assert.IsTrue(attribute.ExpressionValue.IsNull); + Assert.AreEqual("0", attribute.LiteralValue); + Assert.AreEqual(new Location(7,1), attribute.StartLocation); + Assert.AreEqual(new Location(13,1), attribute.EndLocation); + + Assert.IsTrue(element.Attributes[1] is XmlAttributeExpression); + XmlAttributeExpression attribute2 = element.Attributes[1] as XmlAttributeExpression; + Assert.AreEqual("name", attribute2.Name); + Assert.IsFalse(attribute2.IsLiteralValue); + Assert.IsFalse(attribute2.ExpressionValue.IsNull); + + Assert.IsTrue(attribute2.ExpressionValue is IdentifierExpression); + IdentifierExpression identifier = attribute2.ExpressionValue as IdentifierExpression; + Assert.AreEqual("name", identifier.Identifier); + Assert.AreEqual(new Location(23,1), identifier.StartLocation); + Assert.AreEqual(new Location(27,1), identifier.EndLocation); + + Assert.AreEqual(new Location(14,1), attribute2.StartLocation); + Assert.AreEqual(new Location(30,1), attribute2.EndLocation); + + Assert.IsTrue(element.Attributes[2] is XmlEmbeddedExpression); + XmlEmbeddedExpression attribute3 = element.Attributes[2] as XmlEmbeddedExpression; + + Assert.IsTrue(attribute3.InlineVBExpression is IdentifierExpression); + IdentifierExpression identifier2 = attribute3.InlineVBExpression as IdentifierExpression; + + Assert.AreEqual("contentData", identifier2.Identifier); + Assert.AreEqual(new Location(35,1), identifier2.StartLocation); + Assert.AreEqual(new Location(46,1), identifier2.EndLocation); + + Assert.AreEqual(new Location(31,1), attribute3.StartLocation); + Assert.AreEqual(new Location(49,1), attribute3.EndLocation); + + Assert.IsEmpty(element.Children); + Assert.AreEqual(new Location(1,1), element.StartLocation); + Assert.AreEqual(new Location(52,1), element.EndLocation); + } + + [Test] + public void VBNetElementWithAttributeTest() + { + XmlElementExpression element = ParseUtil.ParseExpression("\n" + + " \n" + + " \n" + + ""); + Assert.IsFalse(element.NameIsExpression); + Assert.AreEqual("Test", element.XmlName); + + Assert.IsNotEmpty(element.Attributes); + Assert.AreEqual(1, element.Attributes.Count); + Assert.IsTrue(element.Attributes[0] is XmlAttributeExpression); + XmlAttributeExpression attribute = element.Attributes[0] as XmlAttributeExpression; + Assert.AreEqual("id", attribute.Name); + Assert.IsTrue(attribute.IsLiteralValue); + Assert.IsTrue(attribute.ExpressionValue.IsNull); + Assert.AreEqual("0", attribute.LiteralValue); + Assert.AreEqual(new Location(7,1), attribute.StartLocation); + Assert.AreEqual(new Location(13,1), attribute.EndLocation); + + Assert.IsNotEmpty(element.Children); + Assert.AreEqual(5, element.Children.Count); + + CheckContent(element.Children[0], "\n\t", XmlContentType.Text, new Location(14,1), new Location(2,2)); + CheckContent(element.Children[2], "\n\t", XmlContentType.Text, new Location(10,2), new Location(2,3)); + CheckContent(element.Children[4], "\n", XmlContentType.Text, new Location(10,3), new Location(1,4)); + + CheckElement(element.Children[1], "Item", new Location(2,2), new Location(10,2)); + CheckElement(element.Children[3], "Item", new Location(2,3), new Location(10,3)); + + Assert.AreEqual(new Location(1,1), element.StartLocation); + Assert.AreEqual(new Location(8,4), element.EndLocation); + } + + [Test] + public void VBNetElementWithMixedContentTest() + { + XmlElementExpression element = ParseUtil.ParseExpression("\n" + + " \n" + + " \n" + + " \n" + + " section]]>\n" + + ""); + Assert.IsFalse(element.NameIsExpression); + Assert.AreEqual("Test", element.XmlName); + + Assert.IsNotEmpty(element.Attributes); + Assert.AreEqual(1, element.Attributes.Count); + Assert.IsTrue(element.Attributes[0] is XmlAttributeExpression); + XmlAttributeExpression attribute = element.Attributes[0] as XmlAttributeExpression; + Assert.AreEqual("id", attribute.Name); + Assert.IsTrue(attribute.IsLiteralValue); + Assert.IsTrue(attribute.ExpressionValue.IsNull); + Assert.AreEqual("0", attribute.LiteralValue); + Assert.AreEqual(new Location(7,1), attribute.StartLocation); + Assert.AreEqual(new Location(13,1), attribute.EndLocation); + + Assert.IsNotEmpty(element.Children); + Assert.AreEqual(9, element.Children.Count); + + CheckContent(element.Children[0], "\n\t", XmlContentType.Text, new Location(14,1), new Location(2,2)); + CheckContent(element.Children[2], "\n\t", XmlContentType.Text, new Location(15,2), new Location(2,3)); + CheckContent(element.Children[4], "\n\t", XmlContentType.Text, new Location(10,3), new Location(2,4)); + CheckContent(element.Children[6], "\n\t", XmlContentType.Text, new Location(10,4), new Location(2,5)); + CheckContent(element.Children[7], " section", XmlContentType.CData, new Location(2,5), new Location(29,5)); + CheckContent(element.Children[8], "\n", XmlContentType.Text, new Location(29,5), new Location(1,6)); + + CheckContent(element.Children[1], " test ", XmlContentType.Comment, new Location(2,2), new Location(15,2)); + CheckElement(element.Children[3], "Item", new Location(2,3), new Location(10,3)); + CheckElement(element.Children[5], "Item", new Location(2,4), new Location(10,4)); + + Assert.AreEqual(new Location(1,1), element.StartLocation); + Assert.AreEqual(new Location(8,6), element.EndLocation); + } + + [Test] + public void VBNetElementWithMixedContentTest2() + { + XmlElementExpression element = ParseUtil.ParseExpression(" aaaa "); + Assert.IsFalse(element.NameIsExpression); + Assert.AreEqual("Test", element.XmlName); + + Assert.IsNotEmpty(element.Children); + Assert.AreEqual(1, element.Children.Count); + + CheckContent(element.Children[0], " aaaa ", XmlContentType.Text, new Location(7,1), new Location(14,1)); + } + + [Test] + public void VBNetProcessingInstructionAndCommentAtEndTest() + { + XmlDocumentExpression document = ParseUtil.ParseExpression("\n" + + "\n" + + ""); + Assert.IsNotEmpty(document.Expressions); + Assert.AreEqual(3, document.Expressions.Count); + + CheckElement(document.Expressions[0], "Test", new Location(1,1), new Location(9,1)); + CheckContent(document.Expressions[1], " test ", XmlContentType.Comment, new Location(1,2), new Location(14,2)); + CheckContent(document.Expressions[2], "target some text", XmlContentType.ProcessingInstruction, new Location(1,3), new Location(21,3)); + } + #endregion + + void CheckElement(INode node, string name, Location start, Location end) + { + Assert.IsTrue(node is XmlElementExpression); + XmlElementExpression expr = node as XmlElementExpression; + Assert.IsEmpty(expr.Attributes); + Assert.IsEmpty(expr.Children); + Assert.IsFalse(expr.NameIsExpression); + Assert.AreEqual(name, expr.XmlName); + Assert.AreEqual(start, expr.StartLocation); + Assert.AreEqual(end, expr.EndLocation); + } + + void CheckContent(INode node, string content, XmlContentType type, Location start, Location end) + { + Assert.IsTrue(node is XmlContentExpression); + XmlContentExpression expr = node as XmlContentExpression; + Assert.AreEqual(type, expr.Type); + Assert.AreEqual(content, expr.Content); + Assert.AreEqual(start, expr.StartLocation); + Assert.AreEqual(end, expr.EndLocation); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/XmlMemberAccessExpressionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/XmlMemberAccessExpressionTests.cs new file mode 100644 index 000000000..09d074fa4 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Expressions/XmlMemberAccessExpressionTests.cs @@ -0,0 +1,101 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class XmlMemberAccessExpressionTests + { + #region VB.NET + [Test] + public void VBNetSimpleElementReferenceTest() + { + XmlMemberAccessExpression xmae = ParseUtil.ParseExpression("xml."); + Assert.AreEqual("ns:MyElement", xmae.Identifier); + Assert.IsTrue(xmae.IsXmlIdentifier); + Assert.AreEqual(XmlAxisType.Element, xmae.AxisType); + Assert.IsTrue(xmae.TargetObject is IdentifierExpression); + Assert.AreEqual("xml", ((IdentifierExpression)xmae.TargetObject).Identifier); + } + + [Test] + public void VBNetSimpleAttributeReferenceTest() + { + XmlMemberAccessExpression xmae = ParseUtil.ParseExpression("xml.@attribute"); + Assert.AreEqual("attribute", xmae.Identifier); + Assert.IsFalse(xmae.IsXmlIdentifier); + Assert.AreEqual(XmlAxisType.Attribute, xmae.AxisType); + Assert.IsTrue(xmae.TargetObject is IdentifierExpression); + Assert.AreEqual("xml", ((IdentifierExpression)xmae.TargetObject).Identifier); + } + + [Test] + public void VBNetXmlNameAttributeReferenceTest() + { + XmlMemberAccessExpression xmae = ParseUtil.ParseExpression("xml.@"); + Assert.AreEqual("ns:attribute", xmae.Identifier); + Assert.IsTrue(xmae.IsXmlIdentifier); + Assert.AreEqual(XmlAxisType.Attribute, xmae.AxisType); + Assert.IsTrue(xmae.TargetObject is IdentifierExpression); + Assert.AreEqual("xml", ((IdentifierExpression)xmae.TargetObject).Identifier); + } + + [Test] + public void VBNetSimpleDescendentsReferenceTest() + { + XmlMemberAccessExpression xmae = ParseUtil.ParseExpression("xml..."); + Assert.AreEqual("ns:Element", xmae.Identifier); + Assert.IsTrue(xmae.IsXmlIdentifier); + Assert.AreEqual(XmlAxisType.Descendents, xmae.AxisType); + Assert.IsTrue(xmae.TargetObject is IdentifierExpression); + Assert.AreEqual("xml", ((IdentifierExpression)xmae.TargetObject).Identifier); + } + + [Test] + public void VBNetSimpleElementReferenceWithDotTest() + { + XmlMemberAccessExpression xmae = ParseUtil.ParseExpression("."); + Assert.AreEqual("ns:MyElement", xmae.Identifier); + Assert.IsTrue(xmae.IsXmlIdentifier); + Assert.AreEqual(XmlAxisType.Element, xmae.AxisType); + Assert.IsTrue(xmae.TargetObject.IsNull); + } + + [Test] + public void VBNetSimpleAttributeReferenceWithDotTest() + { + XmlMemberAccessExpression xmae = ParseUtil.ParseExpression(".@attribute"); + Assert.AreEqual("attribute", xmae.Identifier); + Assert.IsFalse(xmae.IsXmlIdentifier); + Assert.AreEqual(XmlAxisType.Attribute, xmae.AxisType); + Assert.IsTrue(xmae.TargetObject.IsNull); + } + + [Test] + public void VBNetXmlNameAttributeReferenceWithDotTest() + { + XmlMemberAccessExpression xmae = ParseUtil.ParseExpression(".@"); + Assert.AreEqual("ns:attribute", xmae.Identifier); + Assert.IsTrue(xmae.IsXmlIdentifier); + Assert.AreEqual(XmlAxisType.Attribute, xmae.AxisType); + Assert.IsTrue(xmae.TargetObject.IsNull); + } + + [Test] + public void VBNetSimpleDescendentsReferenceWithDotTest() + { + XmlMemberAccessExpression xmae = ParseUtil.ParseExpression("..."); + Assert.AreEqual("ns:Element", xmae.Identifier); + Assert.IsTrue(xmae.IsXmlIdentifier); + Assert.AreEqual(XmlAxisType.Descendents, xmae.AxisType); + Assert.IsTrue(xmae.TargetObject.IsNull); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/AttributeSectionTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/AttributeSectionTests.cs new file mode 100644 index 000000000..b7f3cf94e --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/AttributeSectionTests.cs @@ -0,0 +1,74 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class AttributeSectionTests + { + [Test] + public void AttributeOnStructure() + { + string program = @" + _ +Public Structure MyUnion + + Public i As Integer + < FieldOffset( 0 )> Public d As Double + +End Structure 'MyUnion +"; + TypeDeclaration decl = ParseUtil.ParseGlobal(program); + Assert.AreEqual("StructLayout", decl.Attributes[0].Attributes[0].Name); + } + + [Test] + public void AttributeOnModule() + { + string program = @" + _ +Public Module MyExtra + + Public i As Integer + Public d As Double + +End Module +"; + TypeDeclaration decl = ParseUtil.ParseGlobal(program); + Assert.AreEqual("HideModule", decl.Attributes[0].Attributes[0].Name); + } + + [Test] + public void GlobalAttribute() + { + string program = @" _ +Public Class Form1 + +End Class"; + TypeDeclaration decl = ParseUtil.ParseGlobal(program); + Assert.AreEqual("Microsoft.VisualBasic.CompilerServices.DesignerGenerated", decl.Attributes[0].Attributes[0].Name); + } + + [Test] + public void AssemblyAttribute() + { + string program = @""; + AttributeSection decl = ParseUtil.ParseGlobal(program); + Assert.AreEqual(new Location(1, 1), decl.StartLocation); + Assert.AreEqual("assembly", decl.AttributeTarget); + } + + [Test] + public void ModuleAttributeTargetEscaped() + { + // check that this doesn't crash the parser: + ParseUtil.ParseGlobal("<[Module]: SuppressMessageAttribute>", true); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/DelegateDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/DelegateDeclarationTests.cs new file mode 100644 index 000000000..24489603e --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/DelegateDeclarationTests.cs @@ -0,0 +1,42 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class DelegateDeclarationTests + { + void TestDelegateDeclaration(DelegateDeclaration dd) + { + Assert.AreEqual("System.Void", dd.ReturnType.Type); + Assert.AreEqual("MyDelegate", dd.Name); + } + + void TestParameters(DelegateDeclaration dd) + { + Assert.AreEqual(3, dd.Parameters.Count); + + Assert.AreEqual("a", ((ParameterDeclarationExpression)dd.Parameters[0]).ParameterName); + Assert.AreEqual("System.Int32", ((ParameterDeclarationExpression)dd.Parameters[0]).TypeReference.Type); + + Assert.AreEqual("secondParam", ((ParameterDeclarationExpression)dd.Parameters[1]).ParameterName); + Assert.AreEqual("System.Int32", ((ParameterDeclarationExpression)dd.Parameters[1]).TypeReference.Type); + + Assert.AreEqual("lastParam", ((ParameterDeclarationExpression)dd.Parameters[2]).ParameterName); + Assert.AreEqual("MyObj", ((ParameterDeclarationExpression)dd.Parameters[2]).TypeReference.Type); + } + + #region VB.NET + [Test] + public void SimpleVBNetDelegateDeclarationTest() + { + string program = "Public Delegate Sub MyDelegate(ByVal a As Integer, ByVal secondParam As Integer, ByVal lastParam As MyObj)\n"; + TestDelegateDeclaration(ParseUtil.ParseGlobal(program)); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/NamespaceDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/NamespaceDeclarationTests.cs new file mode 100644 index 000000000..a06be924b --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/NamespaceDeclarationTests.cs @@ -0,0 +1,43 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class NamespaceDeclarationTests + { + #region VB.NET + [Test] + public void VBNetSimpleNamespaceTest() + { + string program = "Namespace TestNamespace" + Environment.NewLine + + "End Namespace" +Environment.NewLine; + NamespaceDeclaration ns = ParseUtil.ParseGlobal(program); + Assert.AreEqual("TestNamespace", ns.Name); + } + + [Test] + public void VBNetJuggedNamespaceTest() + { + string program = "Namespace N1 'TestNamespace\n" + + " Namespace N2 ' Declares a namespace named N2 within N1.\n" + + " End Namespace\n" + + "End Namespace\n"; + + NamespaceDeclaration ns = ParseUtil.ParseGlobal(program); + + Assert.AreEqual("N1", ns.Name); + + Assert.IsTrue(ns.Children[0] is NamespaceDeclaration); + + ns = (NamespaceDeclaration)ns.Children[0]; + + Assert.AreEqual("N2", ns.Name); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/OptionDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/OptionDeclarationTests.cs new file mode 100644 index 000000000..1c2c0ac30 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/OptionDeclarationTests.cs @@ -0,0 +1,87 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class OptionDeclarationTests + { + [Test] + public void VBNetStrictOptionDeclarationTest() + { + string program = "Option Strict On\n"; + OptionDeclaration opDec = ParseUtil.ParseGlobal(program); + Assert.AreEqual(OptionType.Strict, opDec.OptionType); + Assert.IsTrue(opDec.OptionValue); + } + + [Test] + public void VBNetExplicitOptionDeclarationTest() + { + string program = "Option Explicit Off\n"; + OptionDeclaration opDec = ParseUtil.ParseGlobal(program); + Assert.AreEqual(OptionType.Explicit, opDec.OptionType); + Assert.IsFalse(opDec.OptionValue, "Off option value excepted!"); + } + + [Test] + public void VBNetCompareBinaryOptionDeclarationTest() + { + string program = "Option Compare Binary\n"; + OptionDeclaration opDec = ParseUtil.ParseGlobal(program); + Assert.AreEqual(OptionType.CompareBinary, opDec.OptionType); + Assert.IsTrue(opDec.OptionValue); + } + + [Test] + public void VBNetCompareTextOptionDeclarationTest() + { + string program = "Option Compare Text\n"; + OptionDeclaration opDec = ParseUtil.ParseGlobal(program); + Assert.AreEqual(OptionType.CompareText, opDec.OptionType); + Assert.IsTrue(opDec.OptionValue); + } + + [Test] + public void VBNetInferOnOptionDeclarationTest() + { + string program = "Option Infer On\n"; + OptionDeclaration opDec = ParseUtil.ParseGlobal(program); + Assert.AreEqual(OptionType.Infer, opDec.OptionType); + Assert.IsTrue(opDec.OptionValue); + } + + [Test] + public void VBNetInferOffOptionDeclarationTest() + { + string program = "Option Infer\n"; + OptionDeclaration opDec = ParseUtil.ParseGlobal(program); + Assert.AreEqual(OptionType.Infer, opDec.OptionType); + Assert.IsTrue(opDec.OptionValue); + } + + [Test] + public void VBNetInferOptionDeclarationTest() + { + string program = "Option Infer\n"; + OptionDeclaration opDec = ParseUtil.ParseGlobal(program); + Assert.AreEqual(OptionType.Infer, opDec.OptionType); + Assert.IsTrue(opDec.OptionValue); + } + + [Test] + public void VBNetInvalidOptionDeclarationTest() + { + string program = "Option\n"; + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + Assert.IsFalse(parser.Errors.ErrorOutput.Length == 0, "Expected errors, but operation completed successfully"); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/TypeDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/TypeDeclarationTests.cs new file mode 100644 index 000000000..9528799cf --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/TypeDeclarationTests.cs @@ -0,0 +1,203 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class TypeDeclarationTests + { + #region VB.NET + [Test] + public void VBNetSimpleClassTypeDeclarationTest() + { + string program = "Class TestClass\n" + + "End Class\n"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + + Assert.AreEqual("TestClass", td.Name); + Assert.AreEqual(ClassType.Class, td.Type); + Assert.AreEqual(1, td.StartLocation.Line, "start line"); + Assert.AreEqual(1, td.BodyStartLocation.Line, "bodystart line"); + Assert.AreEqual(16, td.BodyStartLocation.Column, "bodystart col"); + Assert.AreEqual(2, td.EndLocation.Line, "end line"); + Assert.AreEqual(10, td.EndLocation.Column, "end col"); + } + + [Test] + public void VBNetMissingBaseClassTest() + { + // SD2-1499: test that this invalid code doesn't crash + TypeDeclaration td = ParseUtil.ParseGlobal("public class test inherits", true); + Assert.AreEqual(0, td.BaseTypes.Count); + } + + [Test] + public void VBNetEnumWithBaseClassDeclarationTest() + { + string program = "Enum TestEnum As Byte\n" + + "End Enum\n"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + + Assert.AreEqual("TestEnum", td.Name); + Assert.AreEqual(ClassType.Enum, td.Type); + Assert.AreEqual("System.Byte", td.BaseTypes[0].Type); + Assert.AreEqual(0, td.Children.Count); + } + + [Test] + public void VBNetEnumOnSingleLine() + { + string program = "Enum TestEnum : A : B = 1 : C : End Enum"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + + Assert.AreEqual("TestEnum", td.Name); + Assert.AreEqual(ClassType.Enum, td.Type); + Assert.AreEqual(3, td.Children.Count); + } + + [Test] + public void VBNetEnumOnSingleLine2() + { + string program = "Enum TestEnum : A : : B = 1 :: C : End Enum"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + + Assert.AreEqual("TestEnum", td.Name); + Assert.AreEqual(ClassType.Enum, td.Type); + Assert.AreEqual(3, td.Children.Count); + } + + + [Test] + public void VBNetEnumWithSystemBaseClassDeclarationTest() + { + string program = "Enum TestEnum As System.UInt16\n" + + "End Enum\n"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + + Assert.AreEqual("TestEnum", td.Name); + Assert.AreEqual(ClassType.Enum, td.Type); + Assert.AreEqual("System.UInt16", td.BaseTypes[0].Type); + Assert.AreEqual(0, td.Children.Count); + } + + [Test] + public void VBNetSimpleClassTypeDeclarationWithoutLastNewLineTest() + { + string program = "Class TestClass\n" + + "End Class"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + + Assert.AreEqual("TestClass", td.Name); + Assert.AreEqual(ClassType.Class, td.Type); + Assert.AreEqual(1, td.StartLocation.Line, "start line"); + Assert.AreEqual(2, td.EndLocation.Line, "end line"); + } + + [Test] + public void VBNetSimpleClassTypeDeclarationWithColon() + { + string program = "Class TestClass\n" + + " : \n" + + "End Class"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + + Assert.AreEqual("TestClass", td.Name); + Assert.AreEqual(ClassType.Class, td.Type); + } + + [Test] + public void VBNetSimplePartialClassTypeDeclarationTest() + { + string program = "Partial Class TestClass\n" + + "End Class\n"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + + Assert.AreEqual("TestClass", td.Name); + Assert.AreEqual(ClassType.Class, td.Type); + Assert.AreEqual(Modifiers.Partial, td.Modifier); + } + + [Test] + public void VBNetPartialPublicClass() + { + string program = "Partial Public Class TestClass\nEnd Class\n"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + + Assert.AreEqual("TestClass", td.Name); + Assert.AreEqual(ClassType.Class, td.Type); + Assert.AreEqual(Modifiers.Partial | Modifiers.Public, td.Modifier); + } + + [Test] + public void VBNetGenericClassTypeDeclarationTest() + { + string declr = @" +Public Class Test(Of T) + +End Class +"; + TypeDeclaration td = ParseUtil.ParseGlobal(declr); + + Assert.AreEqual(ClassType.Class, td.Type); + Assert.AreEqual("Test", td.Name); + Assert.AreEqual(Modifiers.Public, td.Modifier); + Assert.AreEqual(0, td.BaseTypes.Count); + Assert.AreEqual(1, td.Templates.Count); + Assert.AreEqual("T", td.Templates[0].Name); + } + + [Test] + public void VBNetGenericClassWithConstraint() + { + string declr = @" +Public Class Test(Of T As IMyInterface) + +End Class +"; + TypeDeclaration td = ParseUtil.ParseGlobal(declr); + + Assert.AreEqual(ClassType.Class, td.Type); + Assert.AreEqual("Test", td.Name); + + Assert.AreEqual(1, td.Templates.Count); + Assert.AreEqual("T", td.Templates[0].Name); + Assert.AreEqual("IMyInterface", td.Templates[0].Bases[0].Type); + } + + [Test] + public void VBNetComplexGenericClassTypeDeclarationTest() + { + string declr = @" +Public Class Generic(Of T As MyNamespace.IMyInterface, S As {G(Of T()), IAnotherInterface}) + Implements System.IComparable + +End Class +"; + TypeDeclaration td = ParseUtil.ParseGlobal(declr); + + Assert.AreEqual(ClassType.Class, td.Type); + Assert.AreEqual("Generic", td.Name); + Assert.AreEqual(Modifiers.Public, td.Modifier); + Assert.AreEqual(1, td.BaseTypes.Count); + Assert.AreEqual("System.IComparable", td.BaseTypes[0].Type); + + Assert.AreEqual(2, td.Templates.Count); + Assert.AreEqual("T", td.Templates[0].Name); + Assert.AreEqual("MyNamespace.IMyInterface", td.Templates[0].Bases[0].Type); + + Assert.AreEqual("S", td.Templates[1].Name); + Assert.AreEqual(2, td.Templates[1].Bases.Count); + Assert.AreEqual("G", td.Templates[1].Bases[0].Type); + Assert.AreEqual(1, td.Templates[1].Bases[0].GenericTypes.Count); + Assert.IsTrue(td.Templates[1].Bases[0].GenericTypes[0].IsArrayType); + Assert.AreEqual("T", td.Templates[1].Bases[0].GenericTypes[0].Type); + Assert.AreEqual(new int[] {0}, td.Templates[1].Bases[0].GenericTypes[0].RankSpecifier); + Assert.AreEqual("IAnotherInterface", td.Templates[1].Bases[1].Type); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/UsingDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/UsingDeclarationTests.cs new file mode 100644 index 000000000..7cce8b7b3 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/GlobalScope/UsingDeclarationTests.cs @@ -0,0 +1,207 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class UsingDeclarationTests + { + void CheckTwoSimpleUsings(CompilationUnit u) + { + Assert.AreEqual(2, u.Children.Count); + Assert.IsTrue(u.Children[0] is UsingDeclaration); + UsingDeclaration ud = (UsingDeclaration)u.Children[0]; + Assert.AreEqual(1, ud.Usings.Count); + Assert.IsTrue(!ud.Usings[0].IsAlias); + Assert.AreEqual("System", ud.Usings[0].Name); + + + Assert.IsTrue(u.Children[1] is UsingDeclaration); + ud = (UsingDeclaration)u.Children[1]; + Assert.AreEqual(1, ud.Usings.Count); + Assert.IsTrue(!ud.Usings[0].IsAlias); + Assert.AreEqual("My.Name.Space", ud.Usings[0].Name); + } + + void CheckAliases(CompilationUnit u) + { + Assert.AreEqual(3, u.Children.Count); + + Assert.IsTrue(u.Children[0] is UsingDeclaration); + UsingDeclaration ud = (UsingDeclaration)u.Children[0]; + Assert.AreEqual(1, ud.Usings.Count); + Assert.IsTrue(((Using)ud.Usings[0]).IsAlias); + Assert.AreEqual("TESTME", ud.Usings[0].Name); + Assert.AreEqual("System", ud.Usings[0].Alias.Type); + + Assert.IsTrue(u.Children[1] is UsingDeclaration); + ud = (UsingDeclaration)u.Children[1]; + Assert.AreEqual(1, ud.Usings.Count); + Assert.IsTrue(((Using)ud.Usings[0]).IsAlias); + Assert.AreEqual("myAlias", ud.Usings[0].Name); + Assert.AreEqual("My.Name.Space", ud.Usings[0].Alias.Type); + + Assert.IsTrue(u.Children[2] is UsingDeclaration); + ud = (UsingDeclaration)u.Children[2]; + Assert.AreEqual(1, ud.Usings.Count); + Assert.IsTrue(((Using)ud.Usings[0]).IsAlias); + Assert.AreEqual("StringCollection", ud.Usings[0].Name); + Assert.AreEqual("System.Collections.Generic.List", ud.Usings[0].Alias.Type); + Assert.AreEqual("System.String", ud.Usings[0].Alias.GenericTypes[0].Type); + } + + #region VB.NET + [Test] + public void VBNetWrongUsingTest() + { + string program = "Imports\n"; + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + Assert.IsTrue(parser.Errors.Count > 0); + UsingDeclaration u = (UsingDeclaration)parser.CompilationUnit.Children[0]; + foreach (Using us in u.Usings) { + Assert.IsNotNull(us); + } + } + + [Test] + public void VBNetWrongUsing2Test() + { + string program = "Imports ,\n"; + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + Assert.IsTrue(parser.Errors.Count > 0); + UsingDeclaration u = (UsingDeclaration)parser.CompilationUnit.Children[0]; + foreach (Using us in u.Usings) { + Assert.IsNotNull(us); + } + } + + [Test] + public void VBNetDeclarationTest() + { + string program = "Imports System\n" + + "Imports My.Name.Space\n"; + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + + Assert.AreEqual("", parser.Errors.ErrorOutput); + CheckTwoSimpleUsings(parser.CompilationUnit); + } + + [Test] + public void VBNetUsingAliasDeclarationTest() + { + string program = "Imports TESTME=System\n" + + "Imports myAlias=My.Name.Space\n" + + "Imports StringCollection = System.Collections.Generic.List(Of string)\n"; + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + + Assert.AreEqual("", parser.Errors.ErrorOutput); + CheckAliases(parser.CompilationUnit); + } + + [Test] + public void VBNetComplexUsingAliasDeclarationTest() + { + string program = "Imports NS1, AL=NS2, NS3, AL2=NS4, NS5\n"; + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + + Assert.AreEqual("", parser.Errors.ErrorOutput); + // TODO : Extend test ... + } + + [Test] + public void VBNetXmlNamespaceUsingTest() + { + string program = "Imports "; + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + + Assert.AreEqual("", parser.Errors.ErrorOutput); + CompilationUnit unit = parser.CompilationUnit; + + Assert.AreEqual(1, unit.Children.Count); + Assert.IsTrue(unit.Children[0] is UsingDeclaration); + UsingDeclaration ud = (UsingDeclaration)unit.Children[0]; + Assert.AreEqual(1, ud.Usings.Count); + Assert.IsFalse(ud.Usings[0].IsAlias); + Assert.IsTrue(ud.Usings[0].IsXml); + + Assert.AreEqual("xmlns", ud.Usings[0].XmlPrefix); + Assert.AreEqual("http://icsharpcode.net/sharpdevelop/avalonedit", ud.Usings[0].Name); + } + + [Test] + public void VBNetXmlNamespaceWithPrefixUsingTest() + { + string program = "Imports "; + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + + Assert.AreEqual("", parser.Errors.ErrorOutput); + CompilationUnit unit = parser.CompilationUnit; + + Assert.AreEqual(1, unit.Children.Count); + Assert.IsTrue(unit.Children[0] is UsingDeclaration); + UsingDeclaration ud = (UsingDeclaration)unit.Children[0]; + Assert.AreEqual(1, ud.Usings.Count); + Assert.IsFalse(ud.Usings[0].IsAlias); + Assert.IsTrue(ud.Usings[0].IsXml); + + Assert.AreEqual("xmlns:avalonedit", ud.Usings[0].XmlPrefix); + Assert.AreEqual("http://icsharpcode.net/sharpdevelop/avalonedit", ud.Usings[0].Name); + } + + [Test] + public void VBNetXmlNamespaceSingleQuotedUsingTest() + { + string program = "Imports "; + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + + Assert.AreEqual("", parser.Errors.ErrorOutput); + CompilationUnit unit = parser.CompilationUnit; + + Assert.AreEqual(1, unit.Children.Count); + Assert.IsTrue(unit.Children[0] is UsingDeclaration); + UsingDeclaration ud = (UsingDeclaration)unit.Children[0]; + Assert.AreEqual(1, ud.Usings.Count); + Assert.IsFalse(ud.Usings[0].IsAlias); + Assert.IsTrue(ud.Usings[0].IsXml); + + Assert.AreEqual("xmlns", ud.Usings[0].XmlPrefix); + Assert.AreEqual("http://icsharpcode.net/sharpdevelop/avalonedit", ud.Usings[0].Name); + } + + [Test] + public void VBNetXmlNamespaceSingleQuotedWithPrefixUsingTest() + { + string program = "Imports "; + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + + Assert.AreEqual("", parser.Errors.ErrorOutput); + CompilationUnit unit = parser.CompilationUnit; + + Assert.AreEqual(1, unit.Children.Count); + Assert.IsTrue(unit.Children[0] is UsingDeclaration); + UsingDeclaration ud = (UsingDeclaration)unit.Children[0]; + Assert.AreEqual(1, ud.Usings.Count); + Assert.IsFalse(ud.Usings[0].IsAlias); + Assert.IsTrue(ud.Usings[0].IsXml); + + Assert.AreEqual("xmlns:avalonedit", ud.Usings[0].XmlPrefix); + Assert.AreEqual("http://icsharpcode.net/sharpdevelop/avalonedit", ud.Usings[0].Name); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/LocationAssignmentCheckVisitor.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/LocationAssignmentCheckVisitor.cs new file mode 100644 index 000000000..4b2bbd464 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/LocationAssignmentCheckVisitor.cs @@ -0,0 +1,26 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Visitors; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + public class LocationAssignmentCheckVisitor : NodeTrackingDomVisitor + { + protected override void BeginVisit(INode node) + { + if (node is CompilationUnit) + return; + if (node is INullable && ((INullable)node).IsNull) + return; + if (node is TypeReference) + return; + + Assert.IsFalse(node.StartLocation.IsEmpty, "StartLocation of {0}", node); + Assert.IsFalse(node.EndLocation.IsEmpty, "EndLocation of {0}", node); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/ParseUtil.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/ParseUtil.cs new file mode 100644 index 000000000..917b5bde3 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/ParseUtil.cs @@ -0,0 +1,92 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + public class ParseUtil + { + public static T ParseGlobal(string program) where T : INode + { + return ParseGlobal(program, false); + } + + public static T ParseGlobal(string program, bool expectErrors) where T : INode + { + VBParser parser = ParserFactory.CreateParser(new StringReader(program)); + parser.Parse(); + + if (expectErrors) + Assert.IsFalse(parser.Errors.ErrorOutput.Length == 0, "Expected errors, but operation completed successfully"); + else + Assert.AreEqual("", parser.Errors.ErrorOutput); + + Assert.IsNotNull(parser.CompilationUnit); + Assert.IsNotNull(parser.CompilationUnit.Children); + Assert.IsNotNull(parser.CompilationUnit.Children[0]); + Assert.AreEqual(1, parser.CompilationUnit.Children.Count); + + Type type = typeof(T); + Assert.IsTrue(type.IsAssignableFrom(parser.CompilationUnit.Children[0].GetType()), String.Format("Parsed expression was {0} instead of {1} ({2})", parser.CompilationUnit.Children[0].GetType(), type, parser.CompilationUnit.Children[0])); + + parser.CompilationUnit.AcceptVisitor(new CheckParentVisitor(), null); + // TODO fix Locations +// parser.CompilationUnit.AcceptChildren(new LocationAssignmentCheckVisitor(), null); + + return (T)parser.CompilationUnit.Children[0]; + } + + public static T ParseTypeMember(string typeMember, bool expectErrors) where T : INode + { + TypeDeclaration td = ParseGlobal("Class TestClass\n " + typeMember + "\n End Class\n", expectErrors); + Assert.AreEqual(1, td.Children.Count); + Type type = typeof(T); + Assert.IsTrue(type.IsAssignableFrom(td.Children[0].GetType()), String.Format("Parsed expression was {0} instead of {1} ({2})", td.GetType(), type, td)); + return (T)td.Children[0]; + } + + public static T ParseTypeMember(string typeMember) where T : INode + { + return ParseTypeMember(typeMember, false); + } + + public static T ParseStatement(string statement, bool expectErrors) where T : INode + { + MethodDeclaration md = ParseTypeMember("Sub A()\n " + statement + "\nEnd Sub\n", expectErrors); + Assert.AreEqual(1, md.Body.Children.Count); + Type type = typeof(T); + Assert.IsTrue(type.IsAssignableFrom(md.Body.Children[0].GetType()), String.Format("Parsed expression was {0} instead of {1} ({2})", md.GetType(), type, md)); + return (T)md.Body.Children[0]; + } + + public static T ParseStatement(string statement) where T : INode + { + return ParseStatement(statement, false); + } + + public static T ParseExpression(string expr) where T : INode + { + return ParseExpression(expr, false); + } + + public static T ParseExpression(string expr, bool expectErrors) where T : INode + { + VBParser parser = ParserFactory.CreateParser(new StringReader(expr)); + INode parsedExpression = parser.ParseExpression(); + if (expectErrors) + Assert.IsFalse(parser.Errors.ErrorOutput.Length == 0, "Expected errors, but operation completed successfully"); + else + Assert.AreEqual("", parser.Errors.ErrorOutput); + // TODO fix Locations +// parsedExpression.AcceptVisitor(new LocationAssignmentCheckVisitor(), null); + Type type = typeof(T); + Assert.IsTrue(type.IsAssignableFrom(parsedExpression.GetType()), String.Format("Parsed expression was {0} instead of {1} ({2})", parsedExpression.GetType(), type, parsedExpression)); + return (T)parsedExpression; + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/SnippetParserTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/SnippetParserTests.cs new file mode 100644 index 000000000..adf945a7b --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/SnippetParserTests.cs @@ -0,0 +1,22 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using ICSharpCode.NRefactory.VB.Dom; +using System; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests +{ + [TestFixture] + public class SnippetParserTests + { + [Test] + public void InvalidExpressionSyntax() + { + // SD2-1584: ensure we don't crash on this invalid VB code + SnippetParser parser = new SnippetParser(); + INode node = parser.Parse("i == 5"); + Assert.IsTrue(parser.Errors.Count > 0); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/AddHandlerStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/AddHandlerStatementTests.cs new file mode 100644 index 000000000..efa0dc751 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/AddHandlerStatementTests.cs @@ -0,0 +1,22 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class AddHandlerStatementTests + { + [Test] + public void AddHandlerTest() + { + AddHandlerStatement addHandlerStatement = ParseUtil.ParseStatement("AddHandler Obj.Ev_Event, AddressOf EventHandler"); + // TODO : extend tests + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/BlockStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/BlockStatementTests.cs new file mode 100644 index 000000000..0dcba6367 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/BlockStatementTests.cs @@ -0,0 +1,17 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class BlockStatementTests + { + // TODO create BlockStatementTests + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ContinueStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ContinueStatementTests.cs new file mode 100644 index 000000000..0b50f9ed4 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ContinueStatementTests.cs @@ -0,0 +1,17 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ContinueStatementTests + { + // TODO : add ContinueStatementTests + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/DoLoopStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/DoLoopStatementTests.cs new file mode 100644 index 000000000..5b8c2c827 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/DoLoopStatementTests.cs @@ -0,0 +1,17 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class DoLoopStatementTests + { + // TODO write some DoLoopStatement tests + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/EndStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/EndStatementTests.cs new file mode 100644 index 000000000..bec0b212f --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/EndStatementTests.cs @@ -0,0 +1,29 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class EndStatementTests + { + #region VB.NET + [Test] + public void VBNetEndStatementTest() + { + EndStatement endStatement = ParseUtil.ParseStatement("End"); + } + + [Test] + public void VBNetEndStatementInIfThenTest2() + { + IfElseStatement endStatement = ParseUtil.ParseStatement("IF a THEN End"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/EraseStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/EraseStatementTests.cs new file mode 100644 index 000000000..4bfa39ed2 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/EraseStatementTests.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class EraseStatementTests + { + #region VB.NET + [Test] + public void VBNetEraseStatementTest() + { + EraseStatement eraseStatement = ParseUtil.ParseStatement("Erase a, b, c"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ErrorStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ErrorStatementTests.cs new file mode 100644 index 000000000..0f2cfb9eb --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ErrorStatementTests.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ErrorStatementTests + { + #region VB.NET + [Test] + public void VBNetErrorStatementTest() + { + ErrorStatement errorStatement = ParseUtil.ParseStatement("Error a"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ExpressionStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ExpressionStatementTests.cs new file mode 100644 index 000000000..57c08f3df --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ExpressionStatementTests.cs @@ -0,0 +1,17 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ExpressionStatementTests + { + // TODO : Create ExpressionStatementTests + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ForNextStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ForNextStatementTests.cs new file mode 100644 index 000000000..6ce3d9410 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ForNextStatementTests.cs @@ -0,0 +1,29 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ForNextStatementTests + { + #region VB.NET + [Test] + public void VBNetForNextStatementTest() + { + ForNextStatement forNextStatement = ParseUtil.ParseStatement("For i=0 To 10 Step 2 : Next i"); + } + + [Test] + public void VBNetForNextStatementWithComplexExpressionTest() + { + ForNextStatement forNextStatement = ParseUtil.ParseStatement("For SomeMethod().Property = 0 To 10 : Next SomeMethod().Property"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ForeachStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ForeachStatementTests.cs new file mode 100644 index 000000000..581514eb1 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ForeachStatementTests.cs @@ -0,0 +1,25 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ForeachStatementTests + { + #region VB.NET + [Test] + public void VBNetForeachStatementTest() + { + ForeachStatement foreachStmt = ParseUtil.ParseStatement("For Each i As Integer In myColl : Next"); + // TODO : Extend test. + } + #endregion + + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/GotoStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/GotoStatementTests.cs new file mode 100644 index 000000000..72b51bba1 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/GotoStatementTests.cs @@ -0,0 +1,24 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class GotoStatementTests + { + #region VB.NET + [Test] + public void VBNetGotoStatementTest() + { + GotoStatement gotoStmt = ParseUtil.ParseStatement("GoTo myLabel"); + Assert.AreEqual("myLabel", gotoStmt.Label); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/IfElseStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/IfElseStatementTests.cs new file mode 100644 index 000000000..93e73fb55 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/IfElseStatementTests.cs @@ -0,0 +1,142 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class IfElseStatementTests + { + #region VB.NET + [Test] + public void VBNetSimpleIfStatementTest() + { + IfElseStatement ifElseStatement = ParseUtil.ParseStatement("If True THEN END"); + Assert.IsFalse(ifElseStatement.Condition.IsNull); + Assert.IsTrue(ifElseStatement.TrueStatement.Count == 1, "true count != 1:" + ifElseStatement.TrueStatement.Count); + Assert.IsTrue(ifElseStatement.FalseStatement.Count == 0, "false count != 0:" + ifElseStatement.FalseStatement.Count); + + Assert.IsTrue(ifElseStatement.TrueStatement[0] is EndStatement, "Statement was: " + ifElseStatement.TrueStatement[0]); + } + [Test] + public void VBNetSimpleIfStatementTest2() + { + IfElseStatement ifElseStatement = ParseUtil.ParseStatement("If True THEN\n END\n END IF"); + Assert.IsFalse(ifElseStatement.Condition.IsNull); + Assert.IsTrue(ifElseStatement.TrueStatement.Count == 1, "true count != 1:" + ifElseStatement.TrueStatement.Count); + Assert.IsTrue(ifElseStatement.FalseStatement.Count == 0, "false count != 0:" + ifElseStatement.FalseStatement.Count); + + Assert.IsTrue(ifElseStatement.TrueStatement[0] is BlockStatement, "Statement was: " + ifElseStatement.TrueStatement[0]); + } + + // test for SD2-1201 + [Test] + public void VBNetIfStatementLocationTest() + { + IfElseStatement ifElseStatement = ParseUtil.ParseStatement("If True THEN\n" + + "DoIt()\n" + + "ElseIf False Then\n" + + "DoIt()\n" + + "End If"); + Assert.AreEqual(3, (ifElseStatement.StartLocation).Line); + Assert.AreEqual(7, (ifElseStatement.EndLocation).Line); + Assert.AreEqual(5, (ifElseStatement.ElseIfSections[0].StartLocation).Line); + Assert.AreEqual(6, (ifElseStatement.ElseIfSections[0].EndLocation).Line); + Assert.IsNotNull(ifElseStatement.ElseIfSections[0].Parent); + + } + + [Test] + public void VBNetElseIfStatementTest() + { + IfElseStatement ifElseStatement = ParseUtil.ParseStatement("If True THEN\n" + + "END\n" + + "ElseIf False Then\n" + + "Stop\n" + + "End If"); + Assert.IsFalse(ifElseStatement.Condition.IsNull); + Assert.IsTrue(ifElseStatement.TrueStatement.Count == 1, "true count != 1:" + ifElseStatement.TrueStatement.Count); + Assert.IsTrue(ifElseStatement.FalseStatement.Count == 0, "false count != 0:" + ifElseStatement.FalseStatement.Count); + Assert.IsFalse((bool)(ifElseStatement.ElseIfSections[0].Condition as PrimitiveExpression).Value); + + Assert.IsTrue(ifElseStatement.TrueStatement[0] is BlockStatement, "Statement was: " + ifElseStatement.TrueStatement[0]); + Assert.IsTrue(ifElseStatement.ElseIfSections[0].EmbeddedStatement.Children[0] is StopStatement, "Statement was: " + ifElseStatement.ElseIfSections[0].EmbeddedStatement.Children[0]); + } + [Test] + public void VBNetElse_IfStatementTest() + { + IfElseStatement ifElseStatement = ParseUtil.ParseStatement("If True THEN\n" + + "END\n" + + "Else If False Then\n" + + "Stop\n" + + "End If"); + Assert.IsFalse(ifElseStatement.Condition.IsNull); + Assert.IsTrue(ifElseStatement.TrueStatement.Count == 1, "true count != 1:" + ifElseStatement.TrueStatement.Count); + Assert.IsTrue(ifElseStatement.FalseStatement.Count == 0, "false count != 0:" + ifElseStatement.FalseStatement.Count); + Assert.IsFalse((bool)(ifElseStatement.ElseIfSections[0].Condition as PrimitiveExpression).Value); + + Assert.IsTrue(ifElseStatement.TrueStatement[0] is BlockStatement, "Statement was: " + ifElseStatement.TrueStatement[0]); + Assert.IsTrue(ifElseStatement.ElseIfSections[0].EmbeddedStatement.Children[0] is StopStatement, "Statement was: " + ifElseStatement.ElseIfSections[0].EmbeddedStatement.Children[0]); + } + [Test] + public void VBNetMultiStatementIfStatementTest() + { + IfElseStatement ifElseStatement = ParseUtil.ParseStatement("If True THEN Stop : b"); + Assert.IsFalse(ifElseStatement.Condition.IsNull); + Assert.AreEqual(2, ifElseStatement.TrueStatement.Count, "true count"); + Assert.AreEqual(0, ifElseStatement.FalseStatement.Count, "false count"); + + Assert.IsTrue(ifElseStatement.TrueStatement[0] is StopStatement); + Assert.IsTrue(ifElseStatement.TrueStatement[1] is ExpressionStatement); + } + [Test] + public void VBNetMultiStatementIfStatementWithEndStatementTest() + { + IfElseStatement ifElseStatement = ParseUtil.ParseStatement("If True THEN Stop : End : b"); + Assert.IsFalse(ifElseStatement.Condition.IsNull); + Assert.AreEqual(3, ifElseStatement.TrueStatement.Count, "true count"); + Assert.AreEqual(0, ifElseStatement.FalseStatement.Count, "false count"); + + Assert.IsTrue(ifElseStatement.TrueStatement[0] is StopStatement); + Assert.IsTrue(ifElseStatement.TrueStatement[1] is EndStatement); + Assert.IsTrue(ifElseStatement.TrueStatement[2] is ExpressionStatement); + } + + [Test] + public void VBNetIfWithEmptyElseTest() + { + IfElseStatement ifElseStatement = ParseUtil.ParseStatement("If True THEN a Else"); + Assert.IsFalse(ifElseStatement.Condition.IsNull); + Assert.AreEqual(1, ifElseStatement.TrueStatement.Count, "true count"); + Assert.AreEqual(0, ifElseStatement.FalseStatement.Count, "false count"); + } + + [Test] + public void VBNetIfWithMultipleColons() + { + IfElseStatement ifElseStatement = ParseUtil.ParseStatement("If True THEN a : : b"); + Assert.IsFalse(ifElseStatement.Condition.IsNull); + Assert.AreEqual(2, ifElseStatement.TrueStatement.Count, "true count"); + Assert.AreEqual(0, ifElseStatement.FalseStatement.Count, "false count"); + } + + [Test] + public void VBNetIfWithSingleLineElse() + { + // This isn't legal according to the VB spec, but the MS VB compiler seems to allow it. + IfElseStatement ifElseStatement = ParseUtil.ParseStatement("If True THEN\n" + + " x()\n" + + "Else y()\n" + + "End If"); + Assert.IsFalse(ifElseStatement.Condition.IsNull); + Assert.AreEqual(1, ifElseStatement.TrueStatement.Count, "true count"); + Assert.AreEqual(1, ifElseStatement.FalseStatement.Count, "false count"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LabelStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LabelStatementTests.cs new file mode 100644 index 000000000..1b3a270b1 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LabelStatementTests.cs @@ -0,0 +1,26 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class LabelStatementTests + { + #region VB.NET + [Test] + public void VBNetLabelStatementTest() + { + MethodDeclaration method = ParseUtil.ParseTypeMember("Sub Test \n myLabel: Console.WriteLine() \n End Sub"); + Assert.AreEqual(2, method.Body.Children.Count); + LabelStatement labelStmt = (LabelStatement)method.Body.Children[0]; + Assert.AreEqual("myLabel", labelStmt.Label); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LocalVariableDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LocalVariableDeclarationTests.cs new file mode 100644 index 000000000..294d2a1f1 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LocalVariableDeclarationTests.cs @@ -0,0 +1,204 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class LocalVariableDeclarationTests + { + #region VB.NET + [Test] + public void VBNetLocalVariableDeclarationTest() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a As Integer = 5"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("a", lvd.Variables[0].Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.Int32", type.Type); + Assert.AreEqual(5, ((PrimitiveExpression)lvd.Variables[0].Initializer).Value); + } + + [Test] + public void VBNetLocalVariableNamedOverrideDeclarationTest() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim override As Integer = 5"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("override", lvd.Variables[0].Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.Int32", type.Type); + Assert.AreEqual(5, ((PrimitiveExpression)lvd.Variables[0].Initializer).Value); + } + + [Test] + public void VBNetLocalArrayDeclarationWithInitializationTest() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a(10) As Integer"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("a", lvd.Variables[0].Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.Int32", type.Type); + Assert.AreEqual(new int[] { 0 } , type.RankSpecifier); + ArrayCreateExpression ace = (ArrayCreateExpression)lvd.Variables[0].Initializer; + Assert.AreEqual(new int[] { 0 } , ace.CreateType.RankSpecifier); + Assert.AreEqual(1, ace.Arguments.Count); + Assert.AreEqual(10, ((PrimitiveExpression)ace.Arguments[0]).Value); + } + + [Test] + public void VBNetLocalArrayDeclarationWithInitializationAndLowerBoundTest() + { + // VB.NET allows only "0" as lower bound + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a(0 To 10) As Integer"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("a", lvd.Variables[0].Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.Int32", type.Type); + Assert.AreEqual(new int[] { 0 } , type.RankSpecifier); + ArrayCreateExpression ace = (ArrayCreateExpression)lvd.Variables[0].Initializer; + Assert.AreEqual(new int[] { 0 } , ace.CreateType.RankSpecifier); + Assert.AreEqual(1, ace.Arguments.Count); + Assert.AreEqual(10, ((PrimitiveExpression)ace.Arguments[0]).Value); + } + + [Test] + public void VBNetLocalArrayDeclarationTest() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a() As Integer"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("a", lvd.Variables[0].Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.Int32", type.Type); + Assert.AreEqual(new int[] { 0 } , type.RankSpecifier); + } + + [Test] + public void VBNetLocalJaggedArrayDeclarationTest() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a(10)() As Integer"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("a", lvd.Variables[0].Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.Int32", type.Type); + Assert.AreEqual(new int[] { 0, 0 } , type.RankSpecifier); + ArrayCreateExpression ace = (ArrayCreateExpression)lvd.Variables[0].Initializer; + Assert.AreEqual(new int[] {0, 0}, ace.CreateType.RankSpecifier); + Assert.AreEqual(1, ace.Arguments.Count); + Assert.AreEqual(10, ((PrimitiveExpression)ace.Arguments[0]).Value); + } + + [Test] + public void VBNetComplexGenericLocalVariableDeclarationTest() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim where As Generic(Of Printable, G(Of Printable()))"); + Assert.AreEqual(1, lvd.Variables.Count); + Assert.AreEqual("where", lvd.Variables[0].Name); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("Generic", type.Type); + Assert.AreEqual(2, type.GenericTypes.Count); + Assert.AreEqual("Printable", type.GenericTypes[0].Type); + Assert.AreEqual(0, type.GenericTypes[0].GenericTypes.Count); + Assert.AreEqual("G", type.GenericTypes[1].Type); + Assert.AreEqual(1, type.GenericTypes[1].GenericTypes.Count); + Assert.AreEqual("Printable", type.GenericTypes[1].GenericTypes[0].Type); + } + + [Test] + public void VBNetGenericWithArrayLocalVariableDeclarationTest1() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a As G(Of Integer)()"); + Assert.AreEqual(1, lvd.Variables.Count); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("G", type.Type); + Assert.AreEqual(1, type.GenericTypes.Count); + Assert.AreEqual("System.Int32", type.GenericTypes[0].Type); + Assert.AreEqual(0, type.GenericTypes[0].GenericTypes.Count); + Assert.IsFalse(type.GenericTypes[0].IsArrayType); + Assert.AreEqual(new int[] { 0 }, type.RankSpecifier); + } + + [Test] + public void VBNetGenericWithArrayLocalVariableDeclarationTest2() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a As G(Of Integer())"); + Assert.AreEqual(1, lvd.Variables.Count); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("G", type.Type); + Assert.AreEqual(1, type.GenericTypes.Count); + Assert.AreEqual("System.Int32", type.GenericTypes[0].Type); + Assert.AreEqual(0, type.GenericTypes[0].GenericTypes.Count); + Assert.IsFalse(type.IsArrayType); + Assert.AreEqual(1, type.GenericTypes[0].RankSpecifier.Length); + Assert.AreEqual(0, type.GenericTypes[0].RankSpecifier[0]); + } + + [Test] + public void VBNetGenericLocalVariableDeclarationTest2() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a As G(Of G(Of Integer))"); + Assert.AreEqual(1, lvd.Variables.Count); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("G", type.Type); + Assert.AreEqual(1, type.GenericTypes.Count); + Assert.AreEqual("G", type.GenericTypes[0].Type); + Assert.AreEqual(1, type.GenericTypes[0].GenericTypes.Count); + Assert.AreEqual("System.Int32", type.GenericTypes[0].GenericTypes[0].Type); + } + + [Test] + public void VBNetGenericLocalVariableDeclarationTest() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a As G(Of Integer)"); + Assert.AreEqual(1, lvd.Variables.Count); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("G", type.Type); + Assert.AreEqual(1, type.GenericTypes.Count); + Assert.AreEqual("System.Int32", type.GenericTypes[0].Type); + } + + [Test] + public void VBNetGenericLocalVariableInitializationTest() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a As New G(Of Integer)"); + Assert.AreEqual(1, lvd.Variables.Count); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("G", type.Type); + Assert.AreEqual(1, type.GenericTypes.Count); + Assert.AreEqual("System.Int32", type.GenericTypes[0].Type); + // TODO: Check initializer + } + + [Test] + public void VBNetNestedGenericLocalVariableDeclarationTest() + { + LocalVariableDeclaration lvd = ParseUtil.ParseStatement("Dim a as MyType(of string).InnerClass(of integer).InnerInnerClass"); + Assert.AreEqual(1, lvd.Variables.Count); + InnerClassTypeReference ic = (InnerClassTypeReference)lvd.GetTypeForVariable(0); + Assert.AreEqual("InnerInnerClass", ic.Type); + Assert.AreEqual(0, ic.GenericTypes.Count); + ic = (InnerClassTypeReference)ic.BaseType; + Assert.AreEqual("InnerClass", ic.Type); + Assert.AreEqual(1, ic.GenericTypes.Count); + Assert.AreEqual("System.Int32", ic.GenericTypes[0].Type); + Assert.AreEqual("MyType", ic.BaseType.Type); + Assert.AreEqual(1, ic.BaseType.GenericTypes.Count); + Assert.AreEqual("System.String", ic.BaseType.GenericTypes[0].Type); + } + + [Test] + public void VBNetDimInSingleLineIf() + { + IfElseStatement ifes = ParseUtil.ParseStatement("If a Then Dim b As String"); + LocalVariableDeclaration lvd = (LocalVariableDeclaration)ifes.TrueStatement[0]; + Assert.AreEqual(1, lvd.Variables.Count); + TypeReference type = lvd.GetTypeForVariable(0); + Assert.AreEqual("System.String", type.Type); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LockStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LockStatementTests.cs new file mode 100644 index 000000000..1d32d6062 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/LockStatementTests.cs @@ -0,0 +1,17 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class LockStatementTests + { + // TODO : write some tests on SyncLock + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/OnErrorStatementTest.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/OnErrorStatementTest.cs new file mode 100644 index 000000000..2ee72a573 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/OnErrorStatementTest.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class OnErrorStatementTest + { + #region VB.NET + [Test] + public void VBNetOnErrorStatementTest() + { + OnErrorStatement onErrorStatement = ParseUtil.ParseStatement("On Error Goto err"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/RaiseEventStatementTest.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/RaiseEventStatementTest.cs new file mode 100644 index 000000000..3f6f43c4e --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/RaiseEventStatementTest.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class RaiseEventStatementTest + { + #region VB.NET + [Test] + public void VBNetRaiseEventStatementTest() + { + RaiseEventStatement raiseEventStatement = ParseUtil.ParseStatement("RaiseEvent MyEvent(a, 5, (6))"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ReDimStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ReDimStatementTests.cs new file mode 100644 index 000000000..7bcb79a2b --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ReDimStatementTests.cs @@ -0,0 +1,77 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ReDimStatementTests + { + [Test] + public void VBNetReDimStatementTest() + { + ReDimStatement reDimStatement = ParseUtil.ParseStatement("ReDim Preserve MyArray(15)"); + Assert.AreEqual(1, reDimStatement.ReDimClauses.Count); + Assert.AreSame(reDimStatement, reDimStatement.ReDimClauses[0].Parent); + } + + [Test] + public void VBNetReDimStatementTest2() + { + ReDimStatement reDimStatement = ParseUtil.ParseStatement("ReDim calCheckData(channelNum, lambdaNum).ShiftFromLastFullCalPixels(CalCheckPeak.HighWavelength)"); + } + + [Test] + public void VBNetBigReDimStatementTest() + { + string program = @" +Class X + Sub x + ReDim sU(m - 1, n - 1) + ReDim sW(n - 1) + ReDim sV(n - 1, n - 1) + ReDim rv1(n - 1) + ReDim sMt(iNrCols - 1, 0) + ReDim Preserve sMt(iNrCols - 1, iRowNr) + ReDim sM(iRowNr - 1, iNrCols - 1) + If (IsNothing(ColLengths)) Then ReDim ColLengths(0) + If (ColLengths.Length = (SubItem + 1)) Then ReDim Preserve ColLengths(SubItem + 1) + ReDim sTransform(2, iTransformType - 1) + ReDim Preserve _Items(_Count) + ReDim Preserve _Items(nCapacity) + ReDim Preserve _Items(0 To _Count) + ReDim Preserve _Items(0 To nCapacity) + ReDim sU(m - 1, n - 1) + ReDim sW(n - 1) + ReDim sV(n - 1, n - 1) + ReDim rv1(n - 1) + ReDim sMt(iNrCols - 1, 0) + ReDim Preserve sMt(iNrCols - 1, iRowNr) + ReDim sM(iRowNr - 1, iNrCols - 1) + If (IsNothing(ColLengths)) Then ReDim ColLengths(0) + If (ColLengths.Length = (SubItem + 1)) Then ReDim Preserve ColLengths(SubItem + 1) + ReDim sTransform(2, iTransformType - 1) + ReDim Preserve Samples(Samples.GetUpperBound(0) + 1) + ReDim Samples(0) + ReDim BaseCssContent(BaseCssContentRows - 1) + ReDim mabtRxBuf(Bytes2Read - 1) + ReDim Preserve primarykey(primarykey.Length) + ReDim Preserve IntArray(10, 10, 15) + ReDim X(10, 10) + ReDim Preserve IntArray(0 To 10, 10, 0 To 20) + ReDim Preserve IntArray(10, 10, 15) + ReDim X(0 To 10, 0 To 10) + ReDim GetMe().IntArray(0 To 10, 10, 0 To 20) + ReDim GetMe(ExplicitParameter := 3).IntArray(0 To 10, 10, 0 To 20) + ReDim SomeType(Of Integer).IntArray(0 To 10, 10, 0 To 20) + End Sub +End Class"; + TypeDeclaration typeDeclaration = ParseUtil.ParseGlobal(program); + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/RemoveHandlerStatement.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/RemoveHandlerStatement.cs new file mode 100644 index 000000000..a0804c773 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/RemoveHandlerStatement.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class RemoveHandlerStatementTests + { + #region VB.NET + [Test] + public void VBNetRemoveHandlerTest() + { + RemoveHandlerStatement removeHandlerStatement = ParseUtil.ParseStatement("RemoveHandler MyHandler, AddressOf MyMethod"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ResumeStatement.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ResumeStatement.cs new file mode 100644 index 000000000..34729c06b --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ResumeStatement.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ResumeStatementTests + { + [Test] + public void ResumeStatementTest() + { + ResumeStatement resumeStatement = ParseUtil.ParseStatement("Resume"); + } + + // TODO : write some more + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ReturnStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ReturnStatementTests.cs new file mode 100644 index 000000000..2122a0ada --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ReturnStatementTests.cs @@ -0,0 +1,32 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ReturnStatementTests + { + #region VB.NET + [Test] + public void VBNetEmptyReturnStatementTest() + { + ReturnStatement returnStatement = ParseUtil.ParseStatement("Return"); + Assert.IsTrue(returnStatement.Expression.IsNull); + } + + [Test] + public void VBNetReturnStatementTest() + { + ReturnStatement returnStatement = ParseUtil.ParseStatement("Return 5"); + Assert.IsFalse(returnStatement.Expression.IsNull); + Assert.IsTrue(returnStatement.Expression is PrimitiveExpression); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/StopStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/StopStatementTests.cs new file mode 100644 index 000000000..00dd5cc26 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/StopStatementTests.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class StopStatementTests + { + #region VB.NET + [Test] + public void VBNetStopStatementTest() + { + StopStatement stopStatement = ParseUtil.ParseStatement("Stop"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/SwitchStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/SwitchStatementTests.cs new file mode 100644 index 000000000..6e2bdffae --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/SwitchStatementTests.cs @@ -0,0 +1,34 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class SwitchStatementTests + { + #region VB.NET + [Test] + public void VBSwitchStatementTest() + { + SwitchStatement switchStmt = ParseUtil.ParseStatement("Select Case a\n Case 4, 5\n Case 6\n Case Else\n End Select"); + Assert.AreEqual("a", ((IdentifierExpression)switchStmt.SwitchExpression).Identifier); + // TODO: Extend test + } + + [Test] + public void InvalidVBSwitchStatementTest() + { + SwitchStatement switchStmt = ParseUtil.ParseStatement("Select Case a\n Case \n End Select", true); + Assert.AreEqual("a", ((IdentifierExpression)switchStmt.SwitchExpression).Identifier); + SwitchSection sec = switchStmt.SwitchSections[0]; + Assert.AreEqual(0, sec.SwitchLabels.Count); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ThrowStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ThrowStatementTests.cs new file mode 100644 index 000000000..9386387c5 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/ThrowStatementTests.cs @@ -0,0 +1,17 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ThrowStatementTests + { + // TODO : ThrowStatementTests + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/TryCatchStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/TryCatchStatementTests.cs new file mode 100644 index 000000000..a2c3bf268 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/TryCatchStatementTests.cs @@ -0,0 +1,17 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class TryCatchStatementTests + { + // TODO : TryCatchStatementTests + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/UsingStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/UsingStatementTests.cs new file mode 100644 index 000000000..8ee0649bb --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/UsingStatementTests.cs @@ -0,0 +1,47 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class UsingStatementTests + { + [Test] + public void UsingStatement() + { + string usingText = @" +Using nf As New System.Drawing.Font(""Arial"", 12.0F, FontStyle.Bold) + c.Font = nf + c.Text = ""This is 12-point Arial bold"" +End Using"; + UsingStatement usingStmt = ParseUtil.ParseStatement(usingText); + // TODO : Extend test. + } + [Test] + public void UsingStatement2() + { + string usingText = @" +Using nf As Font = New Font() + Bla(nf) +End Using"; + UsingStatement usingStmt = ParseUtil.ParseStatement(usingText); + // TODO : Extend test. + } + [Test] + public void UsingStatement3() + { + string usingText = @" +Using nf As New Font(), nf2 As New List(Of Font)(), nf3 = Nothing + Bla(nf) +End Using"; + UsingStatement usingStmt = ParseUtil.ParseStatement(usingText); + // TODO : Extend test. + } + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/WithStatementTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/WithStatementTests.cs new file mode 100644 index 000000000..4df188f19 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/Statements/WithStatementTests.cs @@ -0,0 +1,23 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class WithStatementTests + { + #region VB.NET + [Test] + public void VBNetWithStatementTest() + { + WithStatement withStatement = ParseUtil.ParseStatement("With MyObj : End With"); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/ConstructorDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/ConstructorDeclarationTests.cs new file mode 100644 index 000000000..ca5e54e80 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/ConstructorDeclarationTests.cs @@ -0,0 +1,34 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class ConstructorDeclarationTests + { + #region VB.NET + [Test] + public void VBNetConstructorDeclarationTest1() + { + string program = @"Sub New() + End Sub"; + ConstructorDeclaration cd = ParseUtil.ParseTypeMember(program); + Assert.IsTrue(cd.ConstructorInitializer.IsNull); + } + + [Test] + public void VBNetConstructorDeclarationTest2() + { + ConstructorDeclaration cd = ParseUtil.ParseTypeMember("Sub New(x As Integer, Optional y As String) \nEnd Sub"); + Assert.AreEqual(2, cd.Parameters.Count); + Assert.AreEqual("System.Int32", cd.Parameters[0].TypeReference.Type); + Assert.AreEqual("System.String", cd.Parameters[1].TypeReference.Type); + Assert.AreEqual(ParameterModifiers.Optional, cd.Parameters[1].ParamModifier & ParameterModifiers.Optional); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/CustomEventTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/CustomEventTests.cs new file mode 100644 index 000000000..c5cdebdd7 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/CustomEventTests.cs @@ -0,0 +1,44 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using NUnit.Framework; +using ICSharpCode.NRefactory.VB.Parser; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class CustomEventTests + { + #region VB.NET + [Test] + public void VBNetCustomEventsStatementTest() + { + string code = @" Public Custom Event TestEvent As EventHandler + AddHandler(ByVal value As EventHandler) + Handlers = CType([Delegate].Combine(Handlers, value), _ + EventHandler) + End AddHandler + + RemoveHandler(ByVal value as EventHandler) + Handlers = CType([Delegate].Remove(Handlers, value), _ + EventHandler) + End RemoveHandler + + RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) + Dim TempHandlers As EventHandler = Handlers + + If TempHandlers IsNot Nothing Then + TempHandlers(sender, e) + End If + End RaiseEvent + End Event"; + EventDeclaration customEventDecl = ParseUtil.ParseTypeMember(code); + Assert.IsNotNull(customEventDecl); + Assert.AreEqual("TestEvent", customEventDecl.Name); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/DeclareDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/DeclareDeclarationTests.cs new file mode 100644 index 000000000..47a56ded9 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/DeclareDeclarationTests.cs @@ -0,0 +1,28 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class DeclareDeclarationTests + { + #region VB.NET + [Test] + public void VBNetDeclareDeclarationTest() + { + string program = "Declare Ansi Function GetUserName Lib \"advapi32.dll\" Alias \"GetUserNameA\" (ByVal lpBuffer As String, ByRef nSize As Integer) As Integer\n"; + DeclareDeclaration dd = ParseUtil.ParseTypeMember(program); + Assert.AreEqual("System.Int32", dd.TypeReference.Type); + Assert.AreEqual("GetUserName", dd.Name); + Assert.AreEqual("advapi32.dll", dd.Library); + Assert.AreEqual("GetUserNameA", dd.Alias); + Assert.AreEqual(CharsetModifier.Ansi, dd.Charset); + } + #endregion + + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/EventDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/EventDeclarationTests.cs new file mode 100644 index 000000000..498182888 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/EventDeclarationTests.cs @@ -0,0 +1,25 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class EventDeclarationTests + { + #region VB.NET + [Test] + public void VBNetSimpleEventDeclarationTest() + { + EventDeclaration ed = ParseUtil.ParseTypeMember("event MyEvent(x as Integer)"); + Assert.AreEqual(1, ed.Parameters.Count); + Assert.AreEqual("MyEvent", ed.Name); + Assert.IsFalse(ed.HasAddRegion); + Assert.IsFalse(ed.HasRemoveRegion); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/FieldDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/FieldDeclarationTests.cs new file mode 100644 index 000000000..12f3e4998 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/FieldDeclarationTests.cs @@ -0,0 +1,74 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class FieldDeclarationTests + { + #region VB.NET + [Test] + public void VBNetSimpleFieldDeclarationTest() + { + FieldDeclaration fd = ParseUtil.ParseTypeMember("myField As Integer(,,,)"); + Assert.AreEqual(1, fd.Fields.Count); + + Assert.AreEqual("System.Int32", ((VariableDeclaration)fd.Fields[0]).TypeReference.Type); + Assert.AreEqual("System.Int32", ((VariableDeclaration)fd.Fields[0]).TypeReference.Type); + Assert.AreEqual("myField", ((VariableDeclaration)fd.Fields[0]).Name); + Assert.AreEqual(new int[] { 3 } , ((VariableDeclaration)fd.Fields[0]).TypeReference.RankSpecifier); + } + + [Test] + public void VBNetMultiFieldDeclarationTest() + { + FieldDeclaration fd = ParseUtil.ParseTypeMember("a, b As String"); + Assert.AreEqual(2, fd.Fields.Count); + + Assert.AreEqual("System.String", ((VariableDeclaration)fd.Fields[0]).TypeReference.Type); + Assert.IsFalse(((VariableDeclaration)fd.Fields[0]).TypeReference.IsArrayType); + Assert.AreEqual("System.String", ((VariableDeclaration)fd.Fields[1]).TypeReference.Type); + Assert.IsFalse(((VariableDeclaration)fd.Fields[1]).TypeReference.IsArrayType); + } + + [Test] + public void VBNetMultiFieldsOnSingleLineTest() + { + string program = "Class TestClass : Dim a : Dim b : End Class"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + + Assert.AreEqual(2, td.Children.Count); + Assert.IsTrue(td.Children[0] is FieldDeclaration); + Assert.IsTrue(td.Children[1] is FieldDeclaration); + } + + [Test] + public void VBNetMultiFieldDeclarationTest2() + { + FieldDeclaration fd = ParseUtil.ParseTypeMember("Dim a, b() As String"); + Assert.AreEqual(2, fd.Fields.Count); + + Assert.AreEqual("System.String", ((VariableDeclaration)fd.Fields[0]).TypeReference.Type); + Assert.AreEqual("System.String", ((VariableDeclaration)fd.Fields[1]).TypeReference.Type); + Assert.IsFalse(((VariableDeclaration)fd.Fields[0]).TypeReference.IsArrayType); + Assert.IsTrue(((VariableDeclaration)fd.Fields[1]).TypeReference.IsArrayType); + } + + [Test] + public void VBNetMultiFieldDeclarationTest3() + { + FieldDeclaration fd = ParseUtil.ParseTypeMember("Dim a(), b As String"); + Assert.AreEqual(2, fd.Fields.Count); + + Assert.AreEqual("System.String", ((VariableDeclaration)fd.Fields[0]).TypeReference.Type); + Assert.AreEqual("System.String", ((VariableDeclaration)fd.Fields[1]).TypeReference.Type); + Assert.IsTrue(((VariableDeclaration)fd.Fields[0]).TypeReference.IsArrayType); + Assert.IsFalse(((VariableDeclaration)fd.Fields[1]).TypeReference.IsArrayType); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/MethodDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/MethodDeclarationTests.cs new file mode 100644 index 000000000..1fc606bb2 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/MethodDeclarationTests.cs @@ -0,0 +1,199 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class MethodDeclarationTests + { + #region VB.NET + + [Test] + public void VBNetDefiningPartialMethodDeclarationTest() + { + MethodDeclaration md = ParseUtil.ParseTypeMember(@"Partial Sub MyMethod() + End Sub"); + Assert.AreEqual(0, md.Parameters.Count); + Assert.AreEqual("MyMethod", md.Name); + Assert.IsFalse(md.IsExtensionMethod); + Assert.AreEqual(Modifiers.Partial, md.Modifier); + } + + [Test] + public void VBNetMethodWithModifiersRegionTest() + { + const string program = @"public shared sub MyMethod() + OtherMethod() + end sub"; + + MethodDeclaration md = ParseUtil.ParseTypeMember(program); + Assert.AreEqual(Modifiers.Public | Modifiers.Static, md.Modifier); + Assert.AreEqual(2, md.StartLocation.Line, "StartLocation.Y"); + Assert.AreEqual(2, md.EndLocation.Line, "EndLocation.Y"); + Assert.AreEqual(2, md.StartLocation.Column, "StartLocation.X"); + } + + [Test] + public void VBNetFunctionMethodDeclarationTest() + { + const string program = @"public function MyFunction() as Integer + return 1 + end function"; + + MethodDeclaration md = ParseUtil.ParseTypeMember(program); + Assert.AreEqual(Modifiers.Public, md.Modifier); + Assert.AreEqual(2, md.StartLocation.Line, "StartLocation.Y"); + Assert.AreEqual(2, md.StartLocation.Column, "StartLocation.X"); + Assert.AreEqual(2, md.EndLocation.Line, "EndLocation.Y"); + } + + [Test] + public void VBNetSubroutineMethodDeclarationTest() + { + const string program = @"public Sub MyMethod() + OtherMethod() + end Sub"; + + MethodDeclaration md = ParseUtil.ParseTypeMember(program); + Assert.AreEqual(Modifiers.Public, md.Modifier); + Assert.AreEqual(2, md.StartLocation.Line, "StartLocation.Y"); + Assert.AreEqual(2, md.StartLocation.Column, "StartLocation.X"); + Assert.AreEqual(2, md.EndLocation.Line, "EndLocation.Y"); + } + + [Test] + public void VBNetGenericFunctionMethodDeclarationTest() + { + MethodDeclaration md = ParseUtil.ParseTypeMember("function MyMethod(Of T)(a As T) As Double\nEnd Function"); + Assert.AreEqual("System.Double", md.TypeReference.Type); + Assert.AreEqual(1, md.Parameters.Count); + Assert.AreEqual("T", ((ParameterDeclarationExpression)md.Parameters[0]).TypeReference.Type); + Assert.AreEqual("a", ((ParameterDeclarationExpression)md.Parameters[0]).ParameterName); + + Assert.AreEqual(1, md.Templates.Count); + Assert.AreEqual("T", md.Templates[0].Name); + } + + [Test] + public void VBNetGenericMethodDeclarationTest() + { + MethodDeclaration md = ParseUtil.ParseTypeMember("Function MyMethod(Of T)(a As T) As T\nEnd Function "); + Assert.AreEqual("T", md.TypeReference.Type); + Assert.AreEqual(1, md.Parameters.Count); + Assert.AreEqual("T", ((ParameterDeclarationExpression)md.Parameters[0]).TypeReference.Type); + Assert.AreEqual("a", ((ParameterDeclarationExpression)md.Parameters[0]).ParameterName); + + Assert.AreEqual(1, md.Templates.Count); + Assert.AreEqual("T", md.Templates[0].Name); + } + + [Test] + public void VBNetGenericMethodDeclarationWithConstraintTest() + { + string program = "Function MyMethod(Of T As { ISomeInterface })(a As T) As T\n End Function"; + MethodDeclaration md = ParseUtil.ParseTypeMember(program); + Assert.AreEqual("T", md.TypeReference.Type); + Assert.AreEqual(1, md.Parameters.Count); + Assert.AreEqual("T", ((ParameterDeclarationExpression)md.Parameters[0]).TypeReference.Type); + Assert.AreEqual("a", ((ParameterDeclarationExpression)md.Parameters[0]).ParameterName); + + Assert.AreEqual(1, md.Templates.Count); + Assert.AreEqual("T", md.Templates[0].Name); + Assert.AreEqual(1, md.Templates[0].Bases.Count); + Assert.AreEqual("ISomeInterface", md.Templates[0].Bases[0].Type); + } + + [Test] + public void VBNetExtensionMethodDeclaration() + { + MethodDeclaration md = ParseUtil.ParseTypeMember( + @" _ + Sub Print(s As String) + Console.WriteLine(s) + End Sub"); + + Assert.AreEqual("Print", md.Name); + + // IsExtensionMethod is only valid for c#. + // Assert.IsTrue(md.IsExtensionMethod); + + Assert.AreEqual("s", md.Parameters[0].ParameterName); + Assert.AreEqual("System.String", md.Parameters[0].TypeReference.Type); + } + + [Test] + public void VBNetGenericMethodInInterface() + { + const string program = @"Interface MyInterface + Function MyMethod(Of T As {ISomeInterface})(a As T) As T + End Interface"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + MethodDeclaration md = (MethodDeclaration)td.Children[0]; + Assert.AreEqual("T", md.TypeReference.Type); + Assert.AreEqual(1, md.Parameters.Count); + Assert.AreEqual("T", ((ParameterDeclarationExpression)md.Parameters[0]).TypeReference.Type); + Assert.AreEqual("a", ((ParameterDeclarationExpression)md.Parameters[0]).ParameterName); + + Assert.AreEqual(1, md.Templates.Count); + Assert.AreEqual("T", md.Templates[0].Name); + Assert.AreEqual(1, md.Templates[0].Bases.Count); + Assert.AreEqual("ISomeInterface", md.Templates[0].Bases[0].Type); + } + + [Test] + public void VBNetGenericVoidMethodInInterface() + { + const string program = @"interface MyInterface + Sub MyMethod(Of T As {ISomeInterface})(a as T) +End Interface +"; + TypeDeclaration td = ParseUtil.ParseGlobal(program); + MethodDeclaration md = (MethodDeclaration)td.Children[0]; + Assert.AreEqual("System.Void", md.TypeReference.Type); + Assert.AreEqual(1, md.Parameters.Count); + Assert.AreEqual("T", ((ParameterDeclarationExpression)md.Parameters[0]).TypeReference.Type); + Assert.AreEqual("a", ((ParameterDeclarationExpression)md.Parameters[0]).ParameterName); + + Assert.AreEqual(1, md.Templates.Count); + Assert.AreEqual("T", md.Templates[0].Name); + Assert.AreEqual(1, md.Templates[0].Bases.Count); + Assert.AreEqual("ISomeInterface", md.Templates[0].Bases[0].Type); + } + + [Test] + public void VBNetMethodWithHandlesClause() + { + MethodDeclaration md = ParseUtil.ParseTypeMember( + @"Public Sub MyMethod(sender As Object, e As EventArgs) Handles x.y + End Sub"); + Assert.AreEqual(new string[] { "x.y" }, md.HandlesClause.ToArray()); + + md = ParseUtil.ParseTypeMember( + @"Public Sub MyMethod() Handles Me.FormClosing + End Sub"); + Assert.AreEqual(new string[] { "Me.FormClosing" }, md.HandlesClause.ToArray()); + + md = ParseUtil.ParseTypeMember( + @"Public Sub MyMethod() Handles MyBase.Event, Button1.Click + End Sub"); + Assert.AreEqual(new string[] { "MyBase.Event", "Button1.Click" }, md.HandlesClause.ToArray()); + } + + [Test] + public void VBNetMethodWithTypeCharactersTest() + { + const string program = @"Public Function Func!(ByVal Param&) + Func! = CSingle(Param&) + End Function"; + + MethodDeclaration md = ParseUtil.ParseTypeMember(program); + Assert.AreEqual(Modifiers.Public, md.Modifier); + } + + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/OperatorDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/OperatorDeclarationTests.cs new file mode 100644 index 000000000..b50063a99 --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/OperatorDeclarationTests.cs @@ -0,0 +1,30 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class OperatorDeclarationTests + { + #region VB.NET + + [Test] + public void VBNetImplictOperatorDeclarationTest() + { + string programm = @"Public Shared Operator + (ByVal v As Complex) As Complex + Return v + End Operator"; + + OperatorDeclaration od = ParseUtil.ParseTypeMember(programm); + Assert.IsFalse(od.IsConversionOperator); + Assert.AreEqual(1, od.Parameters.Count); + Assert.AreEqual(ConversionType.None, od.ConversionType); + Assert.AreEqual("Complex", od.TypeReference.Type); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/PropertyDeclarationTests.cs b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/PropertyDeclarationTests.cs new file mode 100644 index 000000000..bd4b1bf1b --- /dev/null +++ b/ICSharpCode.NRefactory.VB.Tests/Parser/TypeLevel/PropertyDeclarationTests.cs @@ -0,0 +1,107 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.IO; +using ICSharpCode.NRefactory.VB.Dom; +using NUnit.Framework; + +namespace ICSharpCode.NRefactory.VB.Tests.Dom +{ + [TestFixture] + public class PropertyDeclarationTests + { + #region VB.NET + [Test] + public void VBNetSimpleGetSetPropertyDeclarationTest() + { + PropertyDeclaration pd = ParseUtil.ParseTypeMember("Property MyProperty As Integer \n Get \n End Get \n Set \n End Set\nEnd Property"); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsTrue(pd.HasGetRegion); + Assert.IsTrue(pd.HasSetRegion); + } + + [Test] + public void VBNetSimpleGetPropertyDeclarationTest() + { + PropertyDeclaration pd = ParseUtil.ParseTypeMember("ReadOnly Property MyProperty \nGet\nEnd Get\nEnd Property"); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsTrue(pd.HasGetRegion); + Assert.IsFalse(pd.HasSetRegion); + Assert.IsTrue((pd.Modifier & Modifiers.ReadOnly) == Modifiers.ReadOnly); + } + + [Test] + public void VBNetSimpleSetPropertyDeclarationTest() + { + PropertyDeclaration pd = ParseUtil.ParseTypeMember("WriteOnly Property MyProperty \n Set\nEnd Set\nEnd Property "); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsFalse(pd.HasGetRegion); + Assert.IsTrue(pd.HasSetRegion); + Assert.IsTrue((pd.Modifier & Modifiers.WriteOnly) == Modifiers.WriteOnly); + } + + [Test] + public void VBNetAutoPropertyTest() + { + PropertyDeclaration pd = ParseUtil.ParseTypeMember("Property MyProperty"); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsTrue(pd.HasGetRegion); + Assert.IsTrue(pd.HasSetRegion); + Assert.AreEqual(pd.Initializer, Expression.Null); + } + + [Test] + public void VBNetReadOnlyAutoPropertyTest() + { + PropertyDeclaration pd = ParseUtil.ParseTypeMember("ReadOnly Property MyProperty"); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsTrue(pd.HasGetRegion); + Assert.IsFalse(pd.HasSetRegion); + Assert.AreEqual(pd.Initializer, Expression.Null); + } + + [Test] + public void VBNetWriteOnlyAutoPropertyTest() + { + PropertyDeclaration pd = ParseUtil.ParseTypeMember("WriteOnly Property MyProperty"); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsFalse(pd.HasGetRegion); + Assert.IsTrue(pd.HasSetRegion); + Assert.AreEqual(pd.Initializer, Expression.Null); + } + + [Test] + public void VBNetSimpleInitializerAutoPropertyTest() + { + PropertyDeclaration pd = ParseUtil.ParseTypeMember("Property MyProperty = 5"); + Assert.AreEqual("MyProperty", pd.Name); + Assert.IsTrue(pd.HasGetRegion); + Assert.IsTrue(pd.HasSetRegion); + Assert.AreEqual(pd.Initializer.ToString(), new PrimitiveExpression(5).ToString()); + } + + [Test] + public void VBNetSimpleInitializerAutoPropertyWithTypeTest() + { + PropertyDeclaration pd = ParseUtil.ParseTypeMember("Property MyProperty As Integer = 5"); + Assert.AreEqual("MyProperty", pd.Name); + Assert.AreEqual("System.Int32", pd.TypeReference.Type); + Assert.IsTrue(pd.HasGetRegion); + Assert.IsTrue(pd.HasSetRegion); + Assert.AreEqual(pd.Initializer.ToString(), new PrimitiveExpression(5).ToString()); + } + + [Test] + public void VBNetSimpleObjectInitializerAutoPropertyTest() + { + PropertyDeclaration pd = ParseUtil.ParseTypeMember("Property MyProperty As New List"); + Assert.AreEqual("MyProperty", pd.Name); + Assert.AreEqual("List", pd.TypeReference.Type); + Assert.IsTrue(pd.HasGetRegion); + Assert.IsTrue(pd.HasSetRegion); + Assert.AreEqual(pd.Initializer.ToString(), new ObjectCreateExpression(new TypeReference("List"), null).ToString()); + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB/.gitignore b/ICSharpCode.NRefactory.VB/.gitignore new file mode 100644 index 000000000..9ce745d95 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/.gitignore @@ -0,0 +1,3 @@ + +bin/ +obj/ \ No newline at end of file diff --git a/ICSharpCode.NRefactory.VB/Dom/AbstractNode.cs b/ICSharpCode.NRefactory.VB/Dom/AbstractNode.cs new file mode 100644 index 000000000..113d12229 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/AbstractNode.cs @@ -0,0 +1,73 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; + +namespace ICSharpCode.NRefactory.VB.Dom +{ + public abstract class AbstractNode : INode + { + List children = new List(); + + public INode Parent { get; set; } + public Location StartLocation { get; set; } + public Location EndLocation { get; set; } + public object UserData { get; set; } + + public List Children { + get { + return children; + } + set { + Debug.Assert(value != null); + children = value; + } + } + + public virtual void AddChild(INode childNode) + { + Debug.Assert(childNode != null); + childNode.Parent = this; + children.Add(childNode); + } + + public abstract object AcceptVisitor(IDomVisitor visitor, object data); + + public virtual object AcceptChildren(IDomVisitor visitor, object data) + { + foreach (INode child in children) { + Debug.Assert(child != null); + child.AcceptVisitor(visitor, data); + } + return data; + } + + public static string GetCollectionString(ICollection collection) + { + StringBuilder output = new StringBuilder(); + output.Append('{'); + + if (collection != null) { + IEnumerator en = collection.GetEnumerator(); + bool isFirst = true; + while (en.MoveNext()) { + if (!isFirst) { + output.Append(", "); + } else { + isFirst = false; + } + output.Append(en.Current == null ? "" : en.Current.ToString()); + } + } else { + return "null"; + } + + output.Append('}'); + return output.ToString(); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Dom/Enums.cs b/ICSharpCode.NRefactory.VB/Dom/Enums.cs new file mode 100644 index 000000000..bf2149747 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/Enums.cs @@ -0,0 +1,412 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB.Dom +{ + [Flags] + public enum Modifiers + { + None = 0x0000, + + // Access + Private = 0x0001, + /// C# 'internal', VB 'Friend' + Internal = 0x0002, + Protected = 0x0004, + Public = 0x0008, + + // Scope + Abstract = 0x0010, // == MustOverride/MustInherit + Virtual = 0x0020, + Sealed = 0x0040, + /// C# 'static', VB 'Shared' + Static = 0x0080, + Override = 0x0100, + /// For fields: readonly (c# and vb), for properties: get-only (vb) + ReadOnly = 0x0200, + Const = 0x0400, + /// C# 'new', VB 'Shadows' + New = 0x0800, + Partial = 0x1000, + + // Special + Extern = 0x2000, + Volatile = 0x4000, + Unsafe = 0x8000, + Overloads = 0x10000, // VB specific + WithEvents = 0x20000, // VB specific + Default = 0x40000, // VB specific + Fixed = 0x80000, // C# specific (fixed size arrays in unsafe structs) + + Dim = 0x100000, // VB.NET SPECIFIC, for fields/local variables only + + /// Generated code, not part of parsed code + Synthetic = 0x200000, + /// Only for VB properties. + WriteOnly = 0x400000, // VB specific + + Visibility = Private | Public | Protected | Internal, + Classes = New | Visibility | Abstract | Sealed | Partial | Static, + VBModules = Visibility, + VBStructures = Visibility | New, + VBEnums = Visibility | New, + VBInterfacs = Visibility | New, + VBDelegates = Visibility | New, + VBMethods = Visibility | New | Static | Virtual | Sealed | Abstract | Override | Overloads, + VBExternalMethods = Visibility | New | Overloads, + VBEvents = Visibility | New | Overloads, + VBProperties = VBMethods | Default | ReadOnly | WriteOnly, + VBCustomEvents = Visibility | New | Overloads, + VBOperators = Public | Static | Overloads | New, + + + // this is not documented in the spec + VBInterfaceEvents = New, + VBInterfaceMethods = New | Overloads, + VBInterfaceProperties = New | Overloads | ReadOnly | WriteOnly | Default, + VBInterfaceEnums = New, + + Fields = New | Visibility | Static | ReadOnly | Volatile | Fixed, + PropertysEventsMethods = New | Visibility | Static | Virtual | Sealed | Override | Abstract | Extern, + Indexers = New | Visibility | Virtual | Sealed | Override | Abstract | Extern, + Operators = Public | Static | Extern, + Constants = New | Visibility, + StructsInterfacesEnumsDelegates = New | Visibility | Partial, + StaticConstructors = Extern | Static | Unsafe, + Destructors = Extern | Unsafe, + Constructors = Visibility | Extern, + } + + public enum ClassType + { + Class, + Module, + Interface, + Struct, + Enum + } + + public enum ParentType + { + ClassOrStruct, + InterfaceOrEnum, + Namespace, + Unknown + } + + public enum FieldDirection + { + None, + In, + Out, + Ref + } + + [Flags] + public enum ParameterModifiers + { + // Values must be the same as in SharpDevelop's ParameterModifiers + None = 0, + In = 1, + Out = 2, + Ref = 4, + Params = 8, + Optional = 16 + } + + public enum VarianceModifier + { + Invariant, + Covariant, + Contravariant + }; + + public enum AssignmentOperatorType + { + None, + Assign, + + Add, + Subtract, + Multiply, + Divide, + Modulus, + + Power, // (VB only) + DivideInteger, // (VB only) + ConcatString, // (VB only) + + ShiftLeft, + ShiftRight, + + BitwiseAnd, + BitwiseOr, + ExclusiveOr, + } + + public enum BinaryOperatorType + { + None, + + /// '&' in C#, 'And' in VB. + BitwiseAnd, + /// '|' in C#, 'Or' in VB. + BitwiseOr, + /// '&&' in C#, 'AndAlso' in VB. + LogicalAnd, + /// '||' in C#, 'OrElse' in VB. + LogicalOr, + /// '^' in C#, 'Xor' in VB. + ExclusiveOr, + + /// > + GreaterThan, + /// >= + GreaterThanOrEqual, + /// '==' in C#, '=' in VB. + Equality, + /// '!=' in C#, '<>' in VB. + InEquality, + /// < + LessThan, + /// <= + LessThanOrEqual, + + /// + + Add, + /// - + Subtract, + /// * + Multiply, + /// / + Divide, + /// '%' in C#, 'Mod' in VB. + Modulus, + /// VB-only: \ + DivideInteger, + /// VB-only: ^ + Power, + /// VB-only: & + Concat, + + /// C#: << + ShiftLeft, + /// C#: >> + ShiftRight, + /// VB-only: Is + ReferenceEquality, + /// VB-only: IsNot + ReferenceInequality, + + /// VB-only: Like + Like, + /// + /// C#: ?? + /// VB: IF(x, y) + /// + NullCoalescing, + + /// VB-only: ! + DictionaryAccess + } + + public enum CastType + { + /// + /// direct cast (C#, VB "DirectCast") + /// + Cast, + /// + /// try cast (C# "as", VB "TryCast") + /// + TryCast, + /// + /// converting cast (VB "CType") + /// + Conversion, + /// + /// primitive converting cast (VB "CString" etc.) + /// + PrimitiveConversion + } + + public enum UnaryOperatorType + { + None, + Not, + BitNot, + + Minus, + Plus, + + Increment, + Decrement, + + PostIncrement, + PostDecrement, + + /// Dereferencing pointer + Dereference, + /// Get address of + AddressOf + } + + public enum ContinueType + { + None, + Do, + For, + While + } + + public enum ConditionType + { + None, + Until, + While, + DoWhile + } + + public enum ConditionPosition + { + None, + Start, + End + } + + public enum ExitType + { + None, + Sub, + Function, + Property, + Do, + For, + While, + Select, + Try + } + + public enum ConstructorInitializerType + { + None, + Base, + This + } + + public enum ConversionType + { + None, + Implicit, + Explicit + } + + public enum OverloadableOperatorType + { + None, + + Add, + Subtract, + Multiply, + Divide, + Modulus, + Concat, + + UnaryPlus, + UnaryMinus, + + Not, + BitNot, + + BitwiseAnd, + BitwiseOr, + ExclusiveOr, + + ShiftLeft, + ShiftRight, + + GreaterThan, + GreaterThanOrEqual, + Equality, + InEquality, + LessThan, + LessThanOrEqual, + + Increment, + Decrement, + + IsTrue, + IsFalse, + + // VB specific + Like, + Power, + CType, + DivideInteger + } + + /// + /// Charset types, used in external methods + /// declarations (VB only). + /// + public enum CharsetModifier + { + None, + Auto, + Unicode, + Ansi + } + + /// + /// Compare type, used in the Option Compare + /// pragma (VB only). + /// + public enum OptionType + { + None, + Explicit, + Strict, + CompareBinary, + CompareText, + Infer + } + + /// + /// Specifies the ordering direction of a QueryExpressionOrdering node. + /// + public enum QueryExpressionOrderingDirection + { + None, + Ascending, + Descending + } + + /// + /// Specifies the partition type for a VB.NET + /// query expression. + /// + public enum QueryExpressionPartitionType + { + Take, + TakeWhile, + Skip, + SkipWhile + } + + public enum XmlAxisType + { + Element, // . + Attribute, // .@ + Descendents // ... + } + + public enum XmlContentType + { + Comment, + Text, + CData, + ProcessingInstruction + } +} diff --git a/ICSharpCode.NRefactory.VB/Dom/General/BlockStatement.cs b/ICSharpCode.NRefactory.VB/Dom/General/BlockStatement.cs new file mode 100644 index 000000000..2be9118cc --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/General/BlockStatement.cs @@ -0,0 +1,58 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB.Dom +{ + public class BlockStatement : Statement + { + // Children in VB: LabelStatement, EndStatement, Statement + + public static new BlockStatement Null { + get { + return NullBlockStatement.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) + { + return visitor.VisitBlockStatement(this, data); + } + + public override string ToString() + { + return String.Format("[BlockStatement: Children={0}]", + GetCollectionString(base.Children)); + } + } + + internal sealed class NullBlockStatement : BlockStatement + { + public static readonly NullBlockStatement Instance = new NullBlockStatement(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) + { + return data; + } + public override object AcceptChildren(IDomVisitor visitor, object data) + { + return data; + } + public override void AddChild(INode childNode) + { + throw new InvalidOperationException(); + } + + public override string ToString() + { + return String.Format("[NullBlockStatement]"); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Dom/General/CompilationUnit.cs b/ICSharpCode.NRefactory.VB/Dom/General/CompilationUnit.cs new file mode 100644 index 000000000..b40f061a2 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/General/CompilationUnit.cs @@ -0,0 +1,24 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections; + +namespace ICSharpCode.NRefactory.VB.Dom +{ + public class CompilationUnit : AbstractNode + { + // Children in C#: UsingAliasDeclaration, UsingDeclaration, AttributeSection, NamespaceDeclaration + // Children in VB: OptionStatements, ImportsStatement, AttributeSection, NamespaceDeclaration + + public override object AcceptVisitor(IDomVisitor visitor, object data) + { + return visitor.VisitCompilationUnit(this, data); + } + + public override string ToString() + { + return String.Format("[CompilationUnit]"); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Dom/General/Expression.cs b/ICSharpCode.NRefactory.VB/Dom/General/Expression.cs new file mode 100644 index 000000000..09f39f5b5 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/General/Expression.cs @@ -0,0 +1,103 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB.Dom +{ + public abstract class Expression : AbstractNode, INullable + { + public static Expression Null { + get { + return NullExpression.Instance; + } + } + + public virtual bool IsNull { + get { + return false; + } + } + + public static Expression CheckNull(Expression expression) + { + return expression == null ? NullExpression.Instance : expression; + } + + /// + /// Returns the existing expression plus the specified integer value. + /// The old object is not modified, but might be a subobject on the new expression + /// (and thus its parent property is modified). + /// + public static Expression AddInteger(Expression expr, int value) + { + PrimitiveExpression pe = expr as PrimitiveExpression; + if (pe != null && pe.Value is int) { + int newVal = (int)pe.Value + value; + return new PrimitiveExpression(newVal, newVal.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); + } + BinaryOperatorExpression boe = expr as BinaryOperatorExpression; + if (boe != null && boe.Op == BinaryOperatorType.Add) { + // clone boe: + boe = new BinaryOperatorExpression(boe.Left, boe.Op, boe.Right); + + boe.Right = AddInteger(boe.Right, value); + if (boe.Right is PrimitiveExpression && ((PrimitiveExpression)boe.Right).Value is int) { + int newVal = (int)((PrimitiveExpression)boe.Right).Value; + if (newVal == 0) { + return boe.Left; + } else if (newVal < 0) { + ((PrimitiveExpression)boe.Right).Value = -newVal; + boe.Op = BinaryOperatorType.Subtract; + } + } + return boe; + } + if (boe != null && boe.Op == BinaryOperatorType.Subtract) { + pe = boe.Right as PrimitiveExpression; + if (pe != null && pe.Value is int) { + int newVal = (int)pe.Value - value; + if (newVal == 0) + return boe.Left; + + // clone boe: + boe = new BinaryOperatorExpression(boe.Left, boe.Op, boe.Right); + + if (newVal < 0) { + newVal = -newVal; + boe.Op = BinaryOperatorType.Add; + } + boe.Right = new PrimitiveExpression(newVal, newVal.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); + return boe; + } + } + BinaryOperatorType opType = BinaryOperatorType.Add; + if (value < 0) { + value = -value; + opType = BinaryOperatorType.Subtract; + } + return new BinaryOperatorExpression(expr, opType, new PrimitiveExpression(value, value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo))); + } + } + + internal sealed class NullExpression : Expression + { + internal static readonly NullExpression Instance = new NullExpression(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) + { + return null; + } + + public override string ToString() + { + return String.Format("[NullExpression]"); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Dom/General/LocalVariableDeclaration.cs b/ICSharpCode.NRefactory.VB/Dom/General/LocalVariableDeclaration.cs new file mode 100644 index 000000000..845d37743 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/General/LocalVariableDeclaration.cs @@ -0,0 +1,99 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; + +namespace ICSharpCode.NRefactory.VB.Dom +{ + public class LocalVariableDeclaration : Statement + { + TypeReference typeReference; + Modifiers modifier = Modifiers.None; + List variables = new List(); + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = TypeReference.CheckNull(value); + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public Modifiers Modifier { + get { + return modifier; + } + set { + modifier = value; + } + } + + public List Variables { + get { + return variables; + } + } + + public TypeReference GetTypeForVariable(int variableIndex) + { + if (!typeReference.IsNull) { + return typeReference; + } + + for (int i = variableIndex; i < Variables.Count;++i) { + if (!((VariableDeclaration)Variables[i]).TypeReference.IsNull) { + return ((VariableDeclaration)Variables[i]).TypeReference; + } + } + return null; + } + + public LocalVariableDeclaration(VariableDeclaration declaration) : this(TypeReference.Null) + { + Variables.Add(declaration); + } + + public LocalVariableDeclaration(TypeReference typeReference) + { + this.TypeReference = typeReference; + } + + public LocalVariableDeclaration(TypeReference typeReference, Modifiers modifier) + { + this.TypeReference = typeReference; + this.modifier = modifier; + } + + public LocalVariableDeclaration(Modifiers modifier) + { + this.typeReference = TypeReference.Null; + this.modifier = modifier; + } + + public VariableDeclaration GetVariableDeclaration(string variableName) + { + foreach (VariableDeclaration variableDeclaration in variables) { + if (variableDeclaration.Name == variableName) { + return variableDeclaration; + } + } + return null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) + { + return visitor.VisitLocalVariableDeclaration(this, data); + } + + public override string ToString() + { + return String.Format("[LocalVariableDeclaration: Type={0}, Modifier ={1} Variables={2}]", + typeReference, + modifier, + GetCollectionString(variables)); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Dom/General/PrimitiveExpression.cs b/ICSharpCode.NRefactory.VB/Dom/General/PrimitiveExpression.cs new file mode 100644 index 000000000..6e053d388 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/General/PrimitiveExpression.cs @@ -0,0 +1,53 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using ICSharpCode.NRefactory.VB.PrettyPrinter; +using System; + +namespace ICSharpCode.NRefactory.VB.Dom +{ + public class PrimitiveExpression : Expression + { + string stringValue; + + public Parser.LiteralFormat LiteralFormat { get; set; } + public object Value { get; set; } + + public string StringValue { + get { + if (stringValue == null) + return VBNetOutputVisitor.ToVBNetString(this); + else + return stringValue; + } + set { + stringValue = value == null ? String.Empty : value; + } + } + + public PrimitiveExpression(object val) + { + this.Value = val; + } + + public PrimitiveExpression(object val, string stringValue) + { + this.Value = val; + this.StringValue = stringValue; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) + { + return visitor.VisitPrimitiveExpression(this, data); + } + + public override string ToString() + { + return String.Format("[PrimitiveExpression: Value={1}, ValueType={2}, StringValue={0}]", + this.StringValue, + this.Value, + this.Value == null ? "null" : this.Value.GetType().FullName + ); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Dom/General/Statement.cs b/ICSharpCode.NRefactory.VB/Dom/General/Statement.cs new file mode 100644 index 000000000..1114a23ed --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/General/Statement.cs @@ -0,0 +1,62 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB.Dom +{ + public abstract class Statement : AbstractNode, INullable + { + public static Statement Null { + get { + return NullStatement.Instance; + } + } + + public virtual bool IsNull { + get { + return false; + } + } + + public static Statement CheckNull(Statement statement) + { + return statement ?? NullStatement.Instance; + } + } + + public abstract class StatementWithEmbeddedStatement : Statement + { + Statement embeddedStatement; + + public Statement EmbeddedStatement { + get { + return embeddedStatement; + } + set { + embeddedStatement = Statement.CheckNull(value); + if (value != null) + value.Parent = this; + } + } + } + + internal sealed class NullStatement : Statement + { + public static readonly NullStatement Instance = new NullStatement(); + + public override bool IsNull { + get { return true; } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) + { + return data; + } + + public override string ToString() + { + return String.Format("[NullStatement]"); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Dom/Generated.cs b/ICSharpCode.NRefactory.VB/Dom/Generated.cs new file mode 100644 index 000000000..a2daebfc8 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/Generated.cs @@ -0,0 +1,5153 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ICSharpCode.NRefactory.VB.Dom { + using System; + using System.Collections.Generic; + + + public class AddHandlerStatement : Statement { + + Expression eventExpression; + + Expression handlerExpression; + + public Expression EventExpression { + get { + return eventExpression; + } + set { + eventExpression = value ?? Expression.Null; + if (!eventExpression.IsNull) eventExpression.Parent = this; + } + } + + public Expression HandlerExpression { + get { + return handlerExpression; + } + set { + handlerExpression = value ?? Expression.Null; + if (!handlerExpression.IsNull) handlerExpression.Parent = this; + } + } + + public AddHandlerStatement(Expression eventExpression, Expression handlerExpression) { + EventExpression = eventExpression; + HandlerExpression = handlerExpression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitAddHandlerStatement(this, data); + } + + public override string ToString() { + return string.Format("[AddHandlerStatement EventExpression={0} HandlerExpression={1}]", EventExpression, HandlerExpression); + } + } + + public class AddressOfExpression : Expression { + + Expression expression; + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public AddressOfExpression(Expression expression) { + Expression = expression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitAddressOfExpression(this, data); + } + + public override string ToString() { + return string.Format("[AddressOfExpression Expression={0}]", Expression); + } + } + + public class ArrayCreateExpression : Expression { + + TypeReference createType; + + List arguments; + + CollectionInitializerExpression arrayInitializer; + + public TypeReference CreateType { + get { + return createType; + } + set { + createType = value ?? TypeReference.Null; + if (!createType.IsNull) createType.Parent = this; + } + } + + public List Arguments { + get { + return arguments; + } + set { + arguments = value ?? new List(); + } + } + + public CollectionInitializerExpression ArrayInitializer { + get { + return arrayInitializer; + } + set { + arrayInitializer = value ?? CollectionInitializerExpression.Null; + if (!arrayInitializer.IsNull) arrayInitializer.Parent = this; + } + } + + public ArrayCreateExpression(TypeReference createType) { + CreateType = createType; + arguments = new List(); + arrayInitializer = CollectionInitializerExpression.Null; + } + + public ArrayCreateExpression(TypeReference createType, List arguments) { + CreateType = createType; + Arguments = arguments; + arrayInitializer = CollectionInitializerExpression.Null; + } + + public ArrayCreateExpression(TypeReference createType, CollectionInitializerExpression arrayInitializer) { + CreateType = createType; + ArrayInitializer = arrayInitializer; + arguments = new List(); + } + + public bool IsImplicitlyTyped { + get { + return createType.IsNull || string.IsNullOrEmpty(createType.Type); + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitArrayCreateExpression(this, data); + } + + public override string ToString() { + return string.Format("[ArrayCreateExpression CreateType={0} Arguments={1} ArrayInitializer={2}]", CreateType, GetCollectionString(Arguments), ArrayInitializer); + } + } + + public class AssignmentExpression : Expression { + + Expression left; + + AssignmentOperatorType op; + + Expression right; + + public Expression Left { + get { + return left; + } + set { + left = value ?? Expression.Null; + if (!left.IsNull) left.Parent = this; + } + } + + public AssignmentOperatorType Op { + get { + return op; + } + set { + op = value; + } + } + + public Expression Right { + get { + return right; + } + set { + right = value ?? Expression.Null; + if (!right.IsNull) right.Parent = this; + } + } + + public AssignmentExpression(Expression left, AssignmentOperatorType op, Expression right) { + Left = left; + Op = op; + Right = right; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitAssignmentExpression(this, data); + } + + public override string ToString() { + return string.Format("[AssignmentExpression Left={0} Op={1} Right={2}]", Left, Op, Right); + } + } + + public class Attribute : AbstractNode { + + string name; + + List positionalArguments; + + List namedArguments; + + public string Name { + get { + return name; + } + set { + name = value ?? ""; + } + } + + public List PositionalArguments { + get { + return positionalArguments; + } + set { + positionalArguments = value ?? new List(); + } + } + + public List NamedArguments { + get { + return namedArguments; + } + set { + namedArguments = value ?? new List(); + } + } + + public Attribute() { + name = ""; + positionalArguments = new List(); + namedArguments = new List(); + } + + public Attribute(string name, List positionalArguments, List namedArguments) { + Name = name; + PositionalArguments = positionalArguments; + NamedArguments = namedArguments; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitAttribute(this, data); + } + + public override string ToString() { + return string.Format("[Attribute Name={0} PositionalArguments={1} NamedArguments={2}]", Name, GetCollectionString(PositionalArguments), GetCollectionString(NamedArguments)); + } + } + + public abstract class AttributedNode : AbstractNode { + + List attributes; + + Modifiers modifier; + + public List Attributes { + get { + return attributes; + } + set { + attributes = value ?? new List(); + } + } + + public Modifiers Modifier { + get { + return modifier; + } + set { + modifier = value; + } + } + + protected AttributedNode() { + attributes = new List(); + } + + protected AttributedNode(List attributes) { + Attributes = attributes; + } + + protected AttributedNode(Modifiers modifier, List attributes) { + Modifier = modifier; + Attributes = attributes; + } + } + + public class AttributeSection : AbstractNode { + + string attributeTarget; + + List attributes; + + public string AttributeTarget { + get { + return attributeTarget; + } + set { + attributeTarget = value ?? ""; + } + } + + public List Attributes { + get { + return attributes; + } + set { + attributes = value ?? new List(); + } + } + + public AttributeSection() { + attributeTarget = ""; + attributes = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitAttributeSection(this, data); + } + + public override string ToString() { + return string.Format("[AttributeSection AttributeTarget={0} Attributes={1}]", AttributeTarget, GetCollectionString(Attributes)); + } + } + + public class BaseReferenceExpression : Expression { + + public BaseReferenceExpression() { + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitBaseReferenceExpression(this, data); + } + + public override string ToString() { + return "[BaseReferenceExpression]"; + } + } + + public class BinaryOperatorExpression : Expression { + + Expression left; + + BinaryOperatorType op; + + Expression right; + + public Expression Left { + get { + return left; + } + set { + left = value ?? Expression.Null; + if (!left.IsNull) left.Parent = this; + } + } + + public BinaryOperatorType Op { + get { + return op; + } + set { + op = value; + } + } + + public Expression Right { + get { + return right; + } + set { + right = value ?? Expression.Null; + if (!right.IsNull) right.Parent = this; + } + } + + public BinaryOperatorExpression() { + left = Expression.Null; + right = Expression.Null; + } + + public BinaryOperatorExpression(Expression left, BinaryOperatorType op, Expression right) { + Left = left; + Op = op; + Right = right; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitBinaryOperatorExpression(this, data); + } + + public override string ToString() { + return string.Format("[BinaryOperatorExpression Left={0} Op={1} Right={2}]", Left, Op, Right); + } + } + + public class CaseLabel : AbstractNode { + + Expression label; + + BinaryOperatorType binaryOperatorType; + + Expression toExpression; + + public Expression Label { + get { + return label; + } + set { + label = value ?? Expression.Null; + if (!label.IsNull) label.Parent = this; + } + } + + public BinaryOperatorType BinaryOperatorType { + get { + return binaryOperatorType; + } + set { + binaryOperatorType = value; + } + } + + public Expression ToExpression { + get { + return toExpression; + } + set { + toExpression = value ?? Expression.Null; + if (!toExpression.IsNull) toExpression.Parent = this; + } + } + + public CaseLabel() { + label = Expression.Null; + toExpression = Expression.Null; + } + + public CaseLabel(Expression label) { + Label = label; + toExpression = Expression.Null; + } + + public CaseLabel(Expression label, Expression toExpression) { + Label = label; + ToExpression = toExpression; + } + + public CaseLabel(BinaryOperatorType binaryOperatorType, Expression label) { + BinaryOperatorType = binaryOperatorType; + Label = label; + toExpression = Expression.Null; + } + + public bool IsDefault { + get { + return label.IsNull; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitCaseLabel(this, data); + } + + public override string ToString() { + return string.Format("[CaseLabel Label={0} BinaryOperatorType={1} ToExpression={2}]", Label, BinaryOperatorType, ToExpression); + } + } + + public class CastExpression : Expression { + + TypeReference castTo; + + Expression expression; + + CastType castType; + + public TypeReference CastTo { + get { + return castTo; + } + set { + castTo = value ?? TypeReference.Null; + if (!castTo.IsNull) castTo.Parent = this; + } + } + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public CastType CastType { + get { + return castType; + } + set { + castType = value; + } + } + + public CastExpression(TypeReference castTo) { + CastTo = castTo; + expression = Expression.Null; + } + + public CastExpression(TypeReference castTo, Expression expression, CastType castType) { + CastTo = castTo; + Expression = expression; + CastType = castType; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitCastExpression(this, data); + } + + public override string ToString() { + return string.Format("[CastExpression CastTo={0} Expression={1} CastType={2}]", CastTo, Expression, CastType); + } + } + + public class CatchClause : AbstractNode { + + TypeReference typeReference; + + string variableName; + + Statement statementBlock; + + Expression condition; + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public string VariableName { + get { + return variableName; + } + set { + variableName = value ?? ""; + } + } + + public Statement StatementBlock { + get { + return statementBlock; + } + set { + statementBlock = value ?? Statement.Null; + if (!statementBlock.IsNull) statementBlock.Parent = this; + } + } + + public Expression Condition { + get { + return condition; + } + set { + condition = value ?? Expression.Null; + if (!condition.IsNull) condition.Parent = this; + } + } + + public CatchClause(TypeReference typeReference, string variableName, Statement statementBlock) { + TypeReference = typeReference; + VariableName = variableName; + StatementBlock = statementBlock; + condition = Expression.Null; + } + + public CatchClause(TypeReference typeReference, string variableName, Statement statementBlock, Expression condition) { + TypeReference = typeReference; + VariableName = variableName; + StatementBlock = statementBlock; + Condition = condition; + } + + public CatchClause(Statement statementBlock) { + StatementBlock = statementBlock; + typeReference = TypeReference.Null; + variableName = ""; + condition = Expression.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitCatchClause(this, data); + } + + public override string ToString() { + return string.Format("[CatchClause TypeReference={0} VariableName={1} StatementBlock={2} Condition={3}]" + + "", TypeReference, VariableName, StatementBlock, Condition); + } + } + + public class ClassReferenceExpression : Expression { + + public ClassReferenceExpression() { + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitClassReferenceExpression(this, data); + } + + public override string ToString() { + return "[ClassReferenceExpression]"; + } + } + + public class CollectionInitializerExpression : Expression { + + List createExpressions; + + public List CreateExpressions { + get { + return createExpressions; + } + set { + createExpressions = value ?? new List(); + } + } + + public CollectionInitializerExpression() { + createExpressions = new List(); + } + + public CollectionInitializerExpression(List createExpressions) { + CreateExpressions = createExpressions; + } + + public new static CollectionInitializerExpression Null { + get { + return NullCollectionInitializerExpression.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitCollectionInitializerExpression(this, data); + } + + public override string ToString() { + return string.Format("[CollectionInitializerExpression CreateExpressions={0}]", GetCollectionString(CreateExpressions)); + } + } + + internal sealed class NullCollectionInitializerExpression : CollectionInitializerExpression { + + internal static NullCollectionInitializerExpression Instance = new NullCollectionInitializerExpression(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullCollectionInitializerExpression]"; + } + } + + public class CollectionRangeVariable : AbstractNode, INullable { + + string identifier; + + Expression expression; + + TypeReference type; + + public string Identifier { + get { + return identifier; + } + set { + identifier = value ?? ""; + } + } + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public TypeReference Type { + get { + return type; + } + set { + type = value ?? TypeReference.Null; + if (!type.IsNull) type.Parent = this; + } + } + + public CollectionRangeVariable() { + identifier = ""; + expression = Expression.Null; + type = TypeReference.Null; + } + + public virtual bool IsNull { + get { + return false; + } + } + + public static CollectionRangeVariable Null { + get { + return NullCollectionRangeVariable.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitCollectionRangeVariable(this, data); + } + + public override string ToString() { + return string.Format("[CollectionRangeVariable Identifier={0} Expression={1} Type={2}]", Identifier, Expression, Type); + } + } + + internal sealed class NullCollectionRangeVariable : CollectionRangeVariable { + + internal static NullCollectionRangeVariable Instance = new NullCollectionRangeVariable(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullCollectionRangeVariable]"; + } + } + + public class ConditionalExpression : Expression { + + Expression condition; + + Expression trueExpression; + + Expression falseExpression; + + public Expression Condition { + get { + return condition; + } + set { + condition = value ?? Expression.Null; + if (!condition.IsNull) condition.Parent = this; + } + } + + public Expression TrueExpression { + get { + return trueExpression; + } + set { + trueExpression = value ?? Expression.Null; + if (!trueExpression.IsNull) trueExpression.Parent = this; + } + } + + public Expression FalseExpression { + get { + return falseExpression; + } + set { + falseExpression = value ?? Expression.Null; + if (!falseExpression.IsNull) falseExpression.Parent = this; + } + } + + public ConditionalExpression() { + condition = Expression.Null; + trueExpression = Expression.Null; + falseExpression = Expression.Null; + } + + public ConditionalExpression(Expression condition, Expression trueExpression, Expression falseExpression) { + Condition = condition; + TrueExpression = trueExpression; + FalseExpression = falseExpression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitConditionalExpression(this, data); + } + + public override string ToString() { + return string.Format("[ConditionalExpression Condition={0} TrueExpression={1} FalseExpression={2}]", Condition, TrueExpression, FalseExpression); + } + } + + public class ConstructorDeclaration : ParametrizedNode { + + ConstructorInitializer constructorInitializer; + + BlockStatement body; + + public ConstructorInitializer ConstructorInitializer { + get { + return constructorInitializer; + } + set { + constructorInitializer = value ?? ConstructorInitializer.Null; + if (!constructorInitializer.IsNull) constructorInitializer.Parent = this; + } + } + + public BlockStatement Body { + get { + return body; + } + set { + body = value ?? BlockStatement.Null; + if (!body.IsNull) body.Parent = this; + } + } + + public ConstructorDeclaration(string name, Modifiers modifier, List parameters, List attributes) { + Name = name; + Modifier = modifier; + Parameters = parameters; + Attributes = attributes; + constructorInitializer = ConstructorInitializer.Null; + body = BlockStatement.Null; + } + + public ConstructorDeclaration(string name, Modifiers modifier, List parameters, ConstructorInitializer constructorInitializer, List attributes) { + Name = name; + Modifier = modifier; + Parameters = parameters; + ConstructorInitializer = constructorInitializer; + Attributes = attributes; + body = BlockStatement.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitConstructorDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[ConstructorDeclaration ConstructorInitializer={0} Body={1} Name={2} Parameters={" + + "3} Attributes={4} Modifier={5}]", ConstructorInitializer, Body, Name, GetCollectionString(Parameters), GetCollectionString(Attributes), Modifier); + } + } + + public class ConstructorInitializer : AbstractNode, INullable { + + ConstructorInitializerType constructorInitializerType; + + List arguments; + + public ConstructorInitializerType ConstructorInitializerType { + get { + return constructorInitializerType; + } + set { + constructorInitializerType = value; + } + } + + public List Arguments { + get { + return arguments; + } + set { + arguments = value ?? new List(); + } + } + + public ConstructorInitializer() { + arguments = new List(); + } + + public virtual bool IsNull { + get { + return false; + } + } + + public static ConstructorInitializer Null { + get { + return NullConstructorInitializer.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitConstructorInitializer(this, data); + } + + public override string ToString() { + return string.Format("[ConstructorInitializer ConstructorInitializerType={0} Arguments={1}]", ConstructorInitializerType, GetCollectionString(Arguments)); + } + } + + internal sealed class NullConstructorInitializer : ConstructorInitializer { + + internal static NullConstructorInitializer Instance = new NullConstructorInitializer(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullConstructorInitializer]"; + } + } + + public class ContinueStatement : Statement { + + ContinueType continueType; + + public ContinueType ContinueType { + get { + return continueType; + } + set { + continueType = value; + } + } + + public ContinueStatement() { + } + + public ContinueStatement(ContinueType continueType) { + ContinueType = continueType; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitContinueStatement(this, data); + } + + public override string ToString() { + return string.Format("[ContinueStatement ContinueType={0}]", ContinueType); + } + } + + public class DeclareDeclaration : ParametrizedNode { + + string alias; + + string library; + + CharsetModifier charset; + + TypeReference typeReference; + + public string Alias { + get { + return alias; + } + set { + alias = value ?? ""; + } + } + + public string Library { + get { + return library; + } + set { + library = value ?? ""; + } + } + + public CharsetModifier Charset { + get { + return charset; + } + set { + charset = value; + } + } + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public DeclareDeclaration(string name, Modifiers modifier, TypeReference typeReference, List parameters, List attributes, string library, string alias, CharsetModifier charset) { + Name = name; + Modifier = modifier; + TypeReference = typeReference; + Parameters = parameters; + Attributes = attributes; + Library = library; + Alias = alias; + Charset = charset; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitDeclareDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[DeclareDeclaration Alias={0} Library={1} Charset={2} TypeReference={3} Name={4} " + + "Parameters={5} Attributes={6} Modifier={7}]", Alias, Library, Charset, TypeReference, Name, GetCollectionString(Parameters), GetCollectionString(Attributes), Modifier); + } + } + + public class DefaultValueExpression : Expression { + + TypeReference typeReference; + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public DefaultValueExpression(TypeReference typeReference) { + TypeReference = typeReference; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitDefaultValueExpression(this, data); + } + + public override string ToString() { + return string.Format("[DefaultValueExpression TypeReference={0}]", TypeReference); + } + } + + public class DelegateDeclaration : AttributedNode { + + string name; + + TypeReference returnType; + + List parameters; + + List templates; + + public string Name { + get { + return name; + } + set { + name = string.IsNullOrEmpty(value) ? "?" : value; + } + } + + public TypeReference ReturnType { + get { + return returnType; + } + set { + returnType = value ?? TypeReference.Null; + if (!returnType.IsNull) returnType.Parent = this; + } + } + + public List Parameters { + get { + return parameters; + } + set { + parameters = value ?? new List(); + } + } + + public List Templates { + get { + return templates; + } + set { + templates = value ?? new List(); + } + } + + public DelegateDeclaration(Modifiers modifier, List attributes) { + Modifier = modifier; + Attributes = attributes; + name = "?"; + returnType = TypeReference.Null; + parameters = new List(); + templates = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitDelegateDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[DelegateDeclaration Name={0} ReturnType={1} Parameters={2} Templates={3} Attribu" + + "tes={4} Modifier={5}]", Name, ReturnType, GetCollectionString(Parameters), GetCollectionString(Templates), GetCollectionString(Attributes), Modifier); + } + } + + public class DirectionExpression : Expression { + + FieldDirection fieldDirection; + + Expression expression; + + public FieldDirection FieldDirection { + get { + return fieldDirection; + } + set { + fieldDirection = value; + } + } + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public DirectionExpression(FieldDirection fieldDirection, Expression expression) { + FieldDirection = fieldDirection; + Expression = expression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitDirectionExpression(this, data); + } + + public override string ToString() { + return string.Format("[DirectionExpression FieldDirection={0} Expression={1}]", FieldDirection, Expression); + } + } + + public class DoLoopStatement : StatementWithEmbeddedStatement { + + Expression condition; + + ConditionType conditionType; + + ConditionPosition conditionPosition; + + public Expression Condition { + get { + return condition; + } + set { + condition = value ?? Expression.Null; + if (!condition.IsNull) condition.Parent = this; + } + } + + public ConditionType ConditionType { + get { + return conditionType; + } + set { + conditionType = value; + } + } + + public ConditionPosition ConditionPosition { + get { + return conditionPosition; + } + set { + conditionPosition = value; + } + } + + public DoLoopStatement(Expression condition, Statement embeddedStatement, ConditionType conditionType, ConditionPosition conditionPosition) { + Condition = condition; + EmbeddedStatement = embeddedStatement; + ConditionType = conditionType; + ConditionPosition = conditionPosition; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitDoLoopStatement(this, data); + } + + public override string ToString() { + return string.Format("[DoLoopStatement Condition={0} ConditionType={1} ConditionPosition={2} EmbeddedSt" + + "atement={3}]", Condition, ConditionType, ConditionPosition, EmbeddedStatement); + } + } + + public class ElseIfSection : StatementWithEmbeddedStatement { + + Expression condition; + + public Expression Condition { + get { + return condition; + } + set { + condition = value ?? Expression.Null; + if (!condition.IsNull) condition.Parent = this; + } + } + + public ElseIfSection(Expression condition, Statement embeddedStatement) { + Condition = condition; + EmbeddedStatement = embeddedStatement; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitElseIfSection(this, data); + } + + public override string ToString() { + return string.Format("[ElseIfSection Condition={0} EmbeddedStatement={1}]", Condition, EmbeddedStatement); + } + } + + public class EndStatement : Statement { + + public EndStatement() { + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitEndStatement(this, data); + } + + public override string ToString() { + return "[EndStatement]"; + } + } + + public class EraseStatement : Statement { + + List expressions; + + public List Expressions { + get { + return expressions; + } + set { + expressions = value ?? new List(); + } + } + + public EraseStatement() { + expressions = new List(); + } + + public EraseStatement(List expressions) { + Expressions = expressions; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitEraseStatement(this, data); + } + + public override string ToString() { + return string.Format("[EraseStatement Expressions={0}]", GetCollectionString(Expressions)); + } + } + + public class ErrorStatement : Statement { + + Expression expression; + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public ErrorStatement(Expression expression) { + Expression = expression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitErrorStatement(this, data); + } + + public override string ToString() { + return string.Format("[ErrorStatement Expression={0}]", Expression); + } + } + + public class EventAddRegion : EventAddRemoveRegion { + + public EventAddRegion(List attributes) : + base(attributes) { + } + + public static EventAddRegion Null { + get { + return NullEventAddRegion.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitEventAddRegion(this, data); + } + + public override string ToString() { + return string.Format("[EventAddRegion Block={0} Parameters={1} Attributes={2} Modifier={3}]", Block, GetCollectionString(Parameters), GetCollectionString(Attributes), Modifier); + } + } + + internal sealed class NullEventAddRegion : EventAddRegion { + + private NullEventAddRegion() : + base(null) { + } + + internal static NullEventAddRegion Instance = new NullEventAddRegion(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullEventAddRegion]"; + } + } + + public abstract class EventAddRemoveRegion : AttributedNode, INullable { + + BlockStatement block; + + List parameters; + + public BlockStatement Block { + get { + return block; + } + set { + block = value ?? BlockStatement.Null; + if (!block.IsNull) block.Parent = this; + } + } + + public List Parameters { + get { + return parameters; + } + set { + parameters = value ?? new List(); + } + } + + protected EventAddRemoveRegion(List attributes) { + Attributes = attributes; + block = BlockStatement.Null; + parameters = new List(); + } + + public virtual bool IsNull { + get { + return false; + } + } + } + + public class EventDeclaration : MemberNode { + + EventAddRegion addRegion; + + EventRemoveRegion removeRegion; + + EventRaiseRegion raiseRegion; + + Location bodyStart; + + Location bodyEnd; + + Expression initializer; + + public EventAddRegion AddRegion { + get { + return addRegion; + } + set { + addRegion = value ?? EventAddRegion.Null; + if (!addRegion.IsNull) addRegion.Parent = this; + } + } + + public EventRemoveRegion RemoveRegion { + get { + return removeRegion; + } + set { + removeRegion = value ?? EventRemoveRegion.Null; + if (!removeRegion.IsNull) removeRegion.Parent = this; + } + } + + public EventRaiseRegion RaiseRegion { + get { + return raiseRegion; + } + set { + raiseRegion = value ?? EventRaiseRegion.Null; + if (!raiseRegion.IsNull) raiseRegion.Parent = this; + } + } + + public Location BodyStart { + get { + return bodyStart; + } + set { + bodyStart = value; + } + } + + public Location BodyEnd { + get { + return bodyEnd; + } + set { + bodyEnd = value; + } + } + + public Expression Initializer { + get { + return initializer; + } + set { + initializer = value ?? Expression.Null; + if (!initializer.IsNull) initializer.Parent = this; + } + } + + public EventDeclaration() { + addRegion = EventAddRegion.Null; + removeRegion = EventRemoveRegion.Null; + raiseRegion = EventRaiseRegion.Null; + bodyStart = Location.Empty; + bodyEnd = Location.Empty; + initializer = Expression.Null; + } + + public bool HasAddRegion { + get { + return !addRegion.IsNull; + } + } + + public bool HasRemoveRegion { + get { + return !removeRegion.IsNull; + } + } + + public bool HasRaiseRegion { + get { + return !raiseRegion.IsNull; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitEventDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[EventDeclaration AddRegion={0} RemoveRegion={1} RaiseRegion={2} BodyStart={3} Bo" + + "dyEnd={4} Initializer={5} InterfaceImplementations={6} TypeReference={7} Name={8" + + "} Parameters={9} Attributes={10} Modifier={11}]", AddRegion, RemoveRegion, RaiseRegion, BodyStart, BodyEnd, Initializer, GetCollectionString(InterfaceImplementations), TypeReference, Name, GetCollectionString(Parameters), GetCollectionString(Attributes), Modifier); + } + } + + public class EventRaiseRegion : EventAddRemoveRegion { + + public EventRaiseRegion(List attributes) : + base(attributes) { + } + + public static EventRaiseRegion Null { + get { + return NullEventRaiseRegion.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitEventRaiseRegion(this, data); + } + + public override string ToString() { + return string.Format("[EventRaiseRegion Block={0} Parameters={1} Attributes={2} Modifier={3}]", Block, GetCollectionString(Parameters), GetCollectionString(Attributes), Modifier); + } + } + + internal sealed class NullEventRaiseRegion : EventRaiseRegion { + + private NullEventRaiseRegion() : + base(null) { + } + + internal static NullEventRaiseRegion Instance = new NullEventRaiseRegion(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullEventRaiseRegion]"; + } + } + + public class EventRemoveRegion : EventAddRemoveRegion { + + public EventRemoveRegion(List attributes) : + base(attributes) { + } + + public static EventRemoveRegion Null { + get { + return NullEventRemoveRegion.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitEventRemoveRegion(this, data); + } + + public override string ToString() { + return string.Format("[EventRemoveRegion Block={0} Parameters={1} Attributes={2} Modifier={3}]", Block, GetCollectionString(Parameters), GetCollectionString(Attributes), Modifier); + } + } + + internal sealed class NullEventRemoveRegion : EventRemoveRegion { + + private NullEventRemoveRegion() : + base(null) { + } + + internal static NullEventRemoveRegion Instance = new NullEventRemoveRegion(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullEventRemoveRegion]"; + } + } + + public class ExitStatement : Statement { + + ExitType exitType; + + public ExitType ExitType { + get { + return exitType; + } + set { + exitType = value; + } + } + + public ExitStatement(ExitType exitType) { + ExitType = exitType; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitExitStatement(this, data); + } + + public override string ToString() { + return string.Format("[ExitStatement ExitType={0}]", ExitType); + } + } + + public class ExpressionRangeVariable : AbstractNode, INullable { + + string identifier; + + Expression expression; + + TypeReference type; + + public string Identifier { + get { + return identifier; + } + set { + identifier = value ?? ""; + } + } + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public TypeReference Type { + get { + return type; + } + set { + type = value ?? TypeReference.Null; + if (!type.IsNull) type.Parent = this; + } + } + + public ExpressionRangeVariable() { + identifier = ""; + expression = Expression.Null; + type = TypeReference.Null; + } + + public virtual bool IsNull { + get { + return false; + } + } + + public static ExpressionRangeVariable Null { + get { + return NullExpressionRangeVariable.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitExpressionRangeVariable(this, data); + } + + public override string ToString() { + return string.Format("[ExpressionRangeVariable Identifier={0} Expression={1} Type={2}]", Identifier, Expression, Type); + } + } + + internal sealed class NullExpressionRangeVariable : ExpressionRangeVariable { + + internal static NullExpressionRangeVariable Instance = new NullExpressionRangeVariable(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullExpressionRangeVariable]"; + } + } + + public class ExpressionStatement : Statement { + + Expression expression; + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public ExpressionStatement(Expression expression) { + Expression = expression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitExpressionStatement(this, data); + } + + public override string ToString() { + return string.Format("[ExpressionStatement Expression={0}]", Expression); + } + } + + public class ExternAliasDirective : AbstractNode { + + string name; + + public string Name { + get { + return name; + } + set { + name = value ?? ""; + } + } + + public ExternAliasDirective() { + name = ""; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitExternAliasDirective(this, data); + } + + public override string ToString() { + return string.Format("[ExternAliasDirective Name={0}]", Name); + } + } + + public class FieldDeclaration : AttributedNode { + + TypeReference typeReference; + + List fields; + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public List Fields { + get { + return fields; + } + set { + fields = value ?? new List(); + } + } + + public FieldDeclaration(List attributes) { + Attributes = attributes; + typeReference = TypeReference.Null; + fields = new List(); + } + + public FieldDeclaration(List attributes, TypeReference typeReference, Modifiers modifier) { + Attributes = attributes; + TypeReference = typeReference; + Modifier = modifier; + fields = new List(); + } + + + public TypeReference GetTypeForField(int fieldIndex) + { + if (!typeReference.IsNull) { + return typeReference; + } + return ((VariableDeclaration)Fields[fieldIndex]).TypeReference; + } + + + public VariableDeclaration GetVariableDeclaration(string variableName) + { + foreach (VariableDeclaration variableDeclaration in Fields) { + if (variableDeclaration.Name == variableName) { + return variableDeclaration; + } + } + return null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitFieldDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[FieldDeclaration TypeReference={0} Fields={1} Attributes={2} Modifier={3}]", TypeReference, GetCollectionString(Fields), GetCollectionString(Attributes), Modifier); + } + } + + public class ForeachStatement : StatementWithEmbeddedStatement { + + TypeReference typeReference; + + string variableName; + + Expression expression; + + Expression nextExpression; + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public string VariableName { + get { + return variableName; + } + set { + variableName = value ?? ""; + } + } + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public Expression NextExpression { + get { + return nextExpression; + } + set { + nextExpression = value ?? Expression.Null; + if (!nextExpression.IsNull) nextExpression.Parent = this; + } + } + + public ForeachStatement(TypeReference typeReference, string variableName, Expression expression, Statement embeddedStatement) { + TypeReference = typeReference; + VariableName = variableName; + Expression = expression; + EmbeddedStatement = embeddedStatement; + nextExpression = Expression.Null; + } + + public ForeachStatement(TypeReference typeReference, string variableName, Expression expression, Statement embeddedStatement, Expression nextExpression) { + TypeReference = typeReference; + VariableName = variableName; + Expression = expression; + EmbeddedStatement = embeddedStatement; + NextExpression = nextExpression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitForeachStatement(this, data); + } + + public override string ToString() { + return string.Format("[ForeachStatement TypeReference={0} VariableName={1} Expression={2} NextExpressio" + + "n={3} EmbeddedStatement={4}]", TypeReference, VariableName, Expression, NextExpression, EmbeddedStatement); + } + } + + public class ForNextStatement : StatementWithEmbeddedStatement { + + Expression start; + + Expression end; + + Expression step; + + List nextExpressions; + + TypeReference typeReference; + + string variableName; + + Expression loopVariableExpression; + + public Expression Start { + get { + return start; + } + set { + start = value ?? Expression.Null; + if (!start.IsNull) start.Parent = this; + } + } + + public Expression End { + get { + return end; + } + set { + end = value ?? Expression.Null; + if (!end.IsNull) end.Parent = this; + } + } + + public Expression Step { + get { + return step; + } + set { + step = value ?? Expression.Null; + if (!step.IsNull) step.Parent = this; + } + } + + public List NextExpressions { + get { + return nextExpressions; + } + set { + nextExpressions = value ?? new List(); + } + } + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public string VariableName { + get { + return variableName; + } + set { + variableName = value ?? ""; + } + } + + public Expression LoopVariableExpression { + get { + return loopVariableExpression; + } + set { + loopVariableExpression = value ?? Expression.Null; + if (!loopVariableExpression.IsNull) loopVariableExpression.Parent = this; + } + } + + public ForNextStatement() { + start = Expression.Null; + end = Expression.Null; + step = Expression.Null; + nextExpressions = new List(); + typeReference = TypeReference.Null; + variableName = ""; + loopVariableExpression = Expression.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitForNextStatement(this, data); + } + + public override string ToString() { + return string.Format("[ForNextStatement Start={0} End={1} Step={2} NextExpressions={3} TypeReference={4" + + "} VariableName={5} LoopVariableExpression={6} EmbeddedStatement={7}]", Start, End, Step, GetCollectionString(NextExpressions), TypeReference, VariableName, LoopVariableExpression, EmbeddedStatement); + } + } + + public class GotoStatement : Statement { + + string label; + + public string Label { + get { + return label; + } + set { + label = value ?? ""; + } + } + + public GotoStatement(string label) { + Label = label; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitGotoStatement(this, data); + } + + public override string ToString() { + return string.Format("[GotoStatement Label={0}]", Label); + } + } + + public class IdentifierExpression : Expression { + + string identifier; + + List typeArguments; + + public string Identifier { + get { + return identifier; + } + set { + identifier = value ?? ""; + } + } + + public List TypeArguments { + get { + return typeArguments; + } + set { + typeArguments = value ?? new List(); + } + } + + public IdentifierExpression(string identifier) { + Identifier = identifier; + typeArguments = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitIdentifierExpression(this, data); + } + + public override string ToString() { + return string.Format("[IdentifierExpression Identifier={0} TypeArguments={1}]", Identifier, GetCollectionString(TypeArguments)); + } + } + + public class IfElseStatement : Statement { + + Expression condition; + + List trueStatement; + + List falseStatement; + + List elseIfSections; + + public Expression Condition { + get { + return condition; + } + set { + condition = value ?? Expression.Null; + if (!condition.IsNull) condition.Parent = this; + } + } + + public List TrueStatement { + get { + return trueStatement; + } + set { + trueStatement = value ?? new List(); + } + } + + public List FalseStatement { + get { + return falseStatement; + } + set { + falseStatement = value ?? new List(); + } + } + + public List ElseIfSections { + get { + return elseIfSections; + } + set { + elseIfSections = value ?? new List(); + } + } + + public IfElseStatement(Expression condition) { + Condition = condition; + trueStatement = new List(); + falseStatement = new List(); + elseIfSections = new List(); + } + + + public IfElseStatement(Expression condition, Statement trueStatement) + : this(condition) { + this.trueStatement.Add(Statement.CheckNull(trueStatement)); + if (trueStatement != null) trueStatement.Parent = this; + } + + public bool HasElseStatements { + get { + return falseStatement.Count > 0; + } + } + + public bool HasElseIfSections { + get { + return elseIfSections.Count > 0; + } + } + + + public IfElseStatement(Expression condition, Statement trueStatement, Statement falseStatement) + : this(condition) { + this.trueStatement.Add(Statement.CheckNull(trueStatement)); + this.falseStatement.Add(Statement.CheckNull(falseStatement)); + if (trueStatement != null) trueStatement.Parent = this; + if (falseStatement != null) falseStatement.Parent = this; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitIfElseStatement(this, data); + } + + public override string ToString() { + return string.Format("[IfElseStatement Condition={0} TrueStatement={1} FalseStatement={2} ElseIfSection" + + "s={3}]", Condition, GetCollectionString(TrueStatement), GetCollectionString(FalseStatement), GetCollectionString(ElseIfSections)); + } + } + + public class InterfaceImplementation : AbstractNode { + + TypeReference interfaceType; + + string memberName; + + public TypeReference InterfaceType { + get { + return interfaceType; + } + set { + interfaceType = value ?? TypeReference.Null; + if (!interfaceType.IsNull) interfaceType.Parent = this; + } + } + + public string MemberName { + get { + return memberName; + } + set { + memberName = string.IsNullOrEmpty(value) ? "?" : value; + } + } + + public InterfaceImplementation(TypeReference interfaceType, string memberName) { + InterfaceType = interfaceType; + MemberName = memberName; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitInterfaceImplementation(this, data); + } + + public override string ToString() { + return string.Format("[InterfaceImplementation InterfaceType={0} MemberName={1}]", InterfaceType, MemberName); + } + } + + public class InvocationExpression : Expression { + + Expression targetObject; + + List arguments; + + public Expression TargetObject { + get { + return targetObject; + } + set { + targetObject = value ?? Expression.Null; + if (!targetObject.IsNull) targetObject.Parent = this; + } + } + + public List Arguments { + get { + return arguments; + } + set { + arguments = value ?? new List(); + } + } + + public InvocationExpression(Expression targetObject) { + TargetObject = targetObject; + arguments = new List(); + } + + public InvocationExpression(Expression targetObject, List arguments) { + TargetObject = targetObject; + Arguments = arguments; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitInvocationExpression(this, data); + } + + public override string ToString() { + return string.Format("[InvocationExpression TargetObject={0} Arguments={1}]", TargetObject, GetCollectionString(Arguments)); + } + } + + public class LabelStatement : Statement { + + string label; + + public string Label { + get { + return label; + } + set { + label = value ?? ""; + } + } + + public LabelStatement(string label) { + Label = label; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitLabelStatement(this, data); + } + + public override string ToString() { + return string.Format("[LabelStatement Label={0}]", Label); + } + } + + public class LambdaExpression : Expression { + + List parameters; + + Statement statementBody; + + Expression expressionBody; + + TypeReference returnType; + + public List Parameters { + get { + return parameters; + } + set { + parameters = value ?? new List(); + } + } + + public Statement StatementBody { + get { + return statementBody; + } + set { + statementBody = value ?? Statement.Null; + if (!statementBody.IsNull) statementBody.Parent = this; + } + } + + public Expression ExpressionBody { + get { + return expressionBody; + } + set { + expressionBody = value ?? Expression.Null; + if (!expressionBody.IsNull) expressionBody.Parent = this; + } + } + + public TypeReference ReturnType { + get { + return returnType; + } + set { + returnType = value ?? TypeReference.Null; + if (!returnType.IsNull) returnType.Parent = this; + } + } + + public LambdaExpression() { + parameters = new List(); + statementBody = Statement.Null; + expressionBody = Expression.Null; + returnType = TypeReference.Null; + } + +public Location ExtendedEndLocation { get; set; } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitLambdaExpression(this, data); + } + + public override string ToString() { + return string.Format("[LambdaExpression Parameters={0} StatementBody={1} ExpressionBody={2} ReturnType=" + + "{3}]", GetCollectionString(Parameters), StatementBody, ExpressionBody, ReturnType); + } + } + + public class LockStatement : StatementWithEmbeddedStatement { + + Expression lockExpression; + + public Expression LockExpression { + get { + return lockExpression; + } + set { + lockExpression = value ?? Expression.Null; + if (!lockExpression.IsNull) lockExpression.Parent = this; + } + } + + public LockStatement(Expression lockExpression, Statement embeddedStatement) { + LockExpression = lockExpression; + EmbeddedStatement = embeddedStatement; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitLockStatement(this, data); + } + + public override string ToString() { + return string.Format("[LockStatement LockExpression={0} EmbeddedStatement={1}]", LockExpression, EmbeddedStatement); + } + } + + public class MemberInitializerExpression : Expression { + + string name; + + bool isKey; + + Expression expression; + + public string Name { + get { + return name; + } + set { + name = value ?? ""; + } + } + + public bool IsKey { + get { + return isKey; + } + set { + isKey = value; + } + } + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public MemberInitializerExpression() { + name = ""; + expression = Expression.Null; + } + + public MemberInitializerExpression(string name, Expression expression) { + Name = name; + Expression = expression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitMemberInitializerExpression(this, data); + } + + public override string ToString() { + return string.Format("[MemberInitializerExpression Name={0} IsKey={1} Expression={2}]", Name, IsKey, Expression); + } + } + + public abstract class MemberNode : ParametrizedNode { + + List interfaceImplementations; + + TypeReference typeReference; + + public List InterfaceImplementations { + get { + return interfaceImplementations; + } + set { + interfaceImplementations = value ?? new List(); + } + } + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + protected MemberNode() { + interfaceImplementations = new List(); + typeReference = TypeReference.Null; + } + + protected MemberNode(Modifiers modifier, List attributes, string name, List parameters) { + Modifier = modifier; + Attributes = attributes; + Name = name; + Parameters = parameters; + interfaceImplementations = new List(); + typeReference = TypeReference.Null; + } + } + + public class MemberReferenceExpression : Expression { + + Expression targetObject; + + string memberName; + + List typeArguments; + + public Expression TargetObject { + get { + return targetObject; + } + set { + targetObject = value ?? Expression.Null; + if (!targetObject.IsNull) targetObject.Parent = this; + } + } + + public string MemberName { + get { + return memberName; + } + set { + memberName = value ?? ""; + } + } + + public List TypeArguments { + get { + return typeArguments; + } + set { + typeArguments = value ?? new List(); + } + } + + public MemberReferenceExpression(Expression targetObject, string memberName) { + TargetObject = targetObject; + MemberName = memberName; + typeArguments = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitMemberReferenceExpression(this, data); + } + + public override string ToString() { + return string.Format("[MemberReferenceExpression TargetObject={0} MemberName={1} TypeArguments={2}]", TargetObject, MemberName, GetCollectionString(TypeArguments)); + } + } + + public class MethodDeclaration : MemberNode { + + BlockStatement body; + + List handlesClause; + + List templates; + + bool isExtensionMethod; + + public BlockStatement Body { + get { + return body; + } + set { + body = value ?? BlockStatement.Null; + if (!body.IsNull) body.Parent = this; + } + } + + public List HandlesClause { + get { + return handlesClause; + } + set { + handlesClause = value ?? new List(); + } + } + + public List Templates { + get { + return templates; + } + set { + templates = value ?? new List(); + } + } + + public bool IsExtensionMethod { + get { + return isExtensionMethod; + } + set { + isExtensionMethod = value; + } + } + + public MethodDeclaration() { + body = BlockStatement.Null; + handlesClause = new List(); + templates = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitMethodDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[MethodDeclaration Body={0} HandlesClause={1} Templates={2} IsExtensionMethod={3}" + + " InterfaceImplementations={4} TypeReference={5} Name={6} Parameters={7} Attribut" + + "es={8} Modifier={9}]", Body, GetCollectionString(HandlesClause), GetCollectionString(Templates), IsExtensionMethod, GetCollectionString(InterfaceImplementations), TypeReference, Name, GetCollectionString(Parameters), GetCollectionString(Attributes), Modifier); + } + } + + public class NamedArgumentExpression : Expression { + + string name; + + Expression expression; + + public string Name { + get { + return name; + } + set { + name = value ?? ""; + } + } + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public NamedArgumentExpression() { + name = ""; + expression = Expression.Null; + } + + public NamedArgumentExpression(string name, Expression expression) { + Name = name; + Expression = expression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitNamedArgumentExpression(this, data); + } + + public override string ToString() { + return string.Format("[NamedArgumentExpression Name={0} Expression={1}]", Name, Expression); + } + } + + public class NamespaceDeclaration : AbstractNode { + + string name; + + public string Name { + get { + return name; + } + set { + name = value ?? ""; + } + } + + public NamespaceDeclaration(string name) { + Name = name; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitNamespaceDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[NamespaceDeclaration Name={0}]", Name); + } + } + + public class ObjectCreateExpression : Expression { + + TypeReference createType; + + List parameters; + + CollectionInitializerExpression objectInitializer; + + public TypeReference CreateType { + get { + return createType; + } + set { + createType = value ?? TypeReference.Null; + if (!createType.IsNull) createType.Parent = this; + } + } + + public List Parameters { + get { + return parameters; + } + set { + parameters = value ?? new List(); + } + } + + public CollectionInitializerExpression ObjectInitializer { + get { + return objectInitializer; + } + set { + objectInitializer = value ?? CollectionInitializerExpression.Null; + if (!objectInitializer.IsNull) objectInitializer.Parent = this; + } + } + + public ObjectCreateExpression(TypeReference createType, List parameters) { + CreateType = createType; + Parameters = parameters; + objectInitializer = CollectionInitializerExpression.Null; + } + + public bool IsAnonymousType { + get { + return createType.IsNull || string.IsNullOrEmpty(createType.Type); + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitObjectCreateExpression(this, data); + } + + public override string ToString() { + return string.Format("[ObjectCreateExpression CreateType={0} Parameters={1} ObjectInitializer={2}]", CreateType, GetCollectionString(Parameters), ObjectInitializer); + } + } + + public class OnErrorStatement : StatementWithEmbeddedStatement { + + public OnErrorStatement(Statement embeddedStatement) { + EmbeddedStatement = embeddedStatement; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitOnErrorStatement(this, data); + } + + public override string ToString() { + return string.Format("[OnErrorStatement EmbeddedStatement={0}]", EmbeddedStatement); + } + } + + public class OperatorDeclaration : MethodDeclaration { + + ConversionType conversionType; + + OverloadableOperatorType overloadableOperator; + + public ConversionType ConversionType { + get { + return conversionType; + } + set { + conversionType = value; + } + } + + public OverloadableOperatorType OverloadableOperator { + get { + return overloadableOperator; + } + set { + overloadableOperator = value; + } + } + + public OperatorDeclaration() { + } + + public bool IsConversionOperator { + get { + return conversionType != ConversionType.None; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitOperatorDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[OperatorDeclaration ConversionType={0} OverloadableOperator={1} Body={2} Handles" + + "Clause={3} Templates={4} IsExtensionMethod={5} InterfaceImplementations={6} Type" + + "Reference={7} Name={8} Parameters={9} Attributes={10} Modifier={11}]", ConversionType, OverloadableOperator, Body, GetCollectionString(HandlesClause), GetCollectionString(Templates), IsExtensionMethod, GetCollectionString(InterfaceImplementations), TypeReference, Name, GetCollectionString(Parameters), GetCollectionString(Attributes), Modifier); + } + } + + public class OptionDeclaration : AbstractNode { + + OptionType optionType; + + bool optionValue; + + public OptionType OptionType { + get { + return optionType; + } + set { + optionType = value; + } + } + + public bool OptionValue { + get { + return optionValue; + } + set { + optionValue = value; + } + } + + public OptionDeclaration(OptionType optionType, bool optionValue) { + OptionType = optionType; + OptionValue = optionValue; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitOptionDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[OptionDeclaration OptionType={0} OptionValue={1}]", OptionType, OptionValue); + } + } + + public class ParameterDeclarationExpression : Expression { + + List attributes; + + string parameterName; + + TypeReference typeReference; + + ParameterModifiers paramModifier; + + Expression defaultValue; + + public List Attributes { + get { + return attributes; + } + set { + attributes = value ?? new List(); + } + } + + public string ParameterName { + get { + return parameterName; + } + set { + parameterName = string.IsNullOrEmpty(value) ? "?" : value; + } + } + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public ParameterModifiers ParamModifier { + get { + return paramModifier; + } + set { + paramModifier = value; + } + } + + public Expression DefaultValue { + get { + return defaultValue; + } + set { + defaultValue = value ?? Expression.Null; + if (!defaultValue.IsNull) defaultValue.Parent = this; + } + } + + public ParameterDeclarationExpression(TypeReference typeReference, string parameterName) { + TypeReference = typeReference; + ParameterName = parameterName; + attributes = new List(); + defaultValue = Expression.Null; + } + + public ParameterDeclarationExpression(TypeReference typeReference, string parameterName, ParameterModifiers paramModifier) { + TypeReference = typeReference; + ParameterName = parameterName; + ParamModifier = paramModifier; + attributes = new List(); + defaultValue = Expression.Null; + } + + public ParameterDeclarationExpression(TypeReference typeReference, string parameterName, ParameterModifiers paramModifier, Expression defaultValue) { + TypeReference = typeReference; + ParameterName = parameterName; + ParamModifier = paramModifier; + DefaultValue = defaultValue; + attributes = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitParameterDeclarationExpression(this, data); + } + + public override string ToString() { + return string.Format("[ParameterDeclarationExpression Attributes={0} ParameterName={1} TypeReference={2" + + "} ParamModifier={3} DefaultValue={4}]", GetCollectionString(Attributes), ParameterName, TypeReference, ParamModifier, DefaultValue); + } + } + + public abstract class ParametrizedNode : AttributedNode { + + string name; + + List parameters; + + public string Name { + get { + return name; + } + set { + name = value ?? ""; + } + } + + public List Parameters { + get { + return parameters; + } + set { + parameters = value ?? new List(); + } + } + + protected ParametrizedNode() { + name = ""; + parameters = new List(); + } + + protected ParametrizedNode(Modifiers modifier, List attributes, string name, List parameters) { + Modifier = modifier; + Attributes = attributes; + Name = name; + Parameters = parameters; + } + } + + public class ParenthesizedExpression : Expression { + + Expression expression; + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public ParenthesizedExpression(Expression expression) { + Expression = expression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitParenthesizedExpression(this, data); + } + + public override string ToString() { + return string.Format("[ParenthesizedExpression Expression={0}]", Expression); + } + } + + public class PropertyDeclaration : MemberNode { + + Location bodyStart; + + Location bodyEnd; + + PropertyGetRegion getRegion; + + PropertySetRegion setRegion; + + Expression initializer; + + public Location BodyStart { + get { + return bodyStart; + } + set { + bodyStart = value; + } + } + + public Location BodyEnd { + get { + return bodyEnd; + } + set { + bodyEnd = value; + } + } + + public PropertyGetRegion GetRegion { + get { + return getRegion; + } + set { + getRegion = value ?? PropertyGetRegion.Null; + if (!getRegion.IsNull) getRegion.Parent = this; + } + } + + public PropertySetRegion SetRegion { + get { + return setRegion; + } + set { + setRegion = value ?? PropertySetRegion.Null; + if (!setRegion.IsNull) setRegion.Parent = this; + } + } + + public Expression Initializer { + get { + return initializer; + } + set { + initializer = value ?? Expression.Null; + if (!initializer.IsNull) initializer.Parent = this; + } + } + + public PropertyDeclaration(Modifiers modifier, List attributes, string name, List parameters) { + Modifier = modifier; + Attributes = attributes; + Name = name; + Parameters = parameters; + bodyStart = Location.Empty; + bodyEnd = Location.Empty; + getRegion = PropertyGetRegion.Null; + setRegion = PropertySetRegion.Null; + initializer = Expression.Null; + } + + public bool IsReadOnly { + get { + return HasGetRegion && !HasSetRegion; + } + } + + public bool HasGetRegion { + get { + return !getRegion.IsNull; + } + } + + public bool IsWriteOnly { + get { + return !HasGetRegion && HasSetRegion; + } + } + + public bool IsIndexer { + get { + return (Modifier & Modifiers.Default) != 0; + } + } + + + internal PropertyDeclaration(string name, TypeReference typeReference, Modifiers modifier, List attributes) : this(modifier, attributes, name, null) + { + this.TypeReference = typeReference; + if ((modifier & Modifiers.ReadOnly) != Modifiers.ReadOnly) { + this.SetRegion = new PropertySetRegion(null, null); + } + if ((modifier & Modifiers.WriteOnly) != Modifiers.WriteOnly) { + this.GetRegion = new PropertyGetRegion(null, null); + } + } + + public bool HasSetRegion { + get { + return !setRegion.IsNull; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitPropertyDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[PropertyDeclaration BodyStart={0} BodyEnd={1} GetRegion={2} SetRegion={3} Initia" + + "lizer={4} InterfaceImplementations={5} TypeReference={6} Name={7} Parameters={8}" + + " Attributes={9} Modifier={10}]", BodyStart, BodyEnd, GetRegion, SetRegion, Initializer, GetCollectionString(InterfaceImplementations), TypeReference, Name, GetCollectionString(Parameters), GetCollectionString(Attributes), Modifier); + } + } + + public class PropertyGetRegion : PropertyGetSetRegion { + + public PropertyGetRegion(BlockStatement block, List attributes) : + base(block, attributes) { + } + + public static PropertyGetRegion Null { + get { + return NullPropertyGetRegion.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitPropertyGetRegion(this, data); + } + + public override string ToString() { + return string.Format("[PropertyGetRegion Block={0} Attributes={1} Modifier={2}]", Block, GetCollectionString(Attributes), Modifier); + } + } + + internal sealed class NullPropertyGetRegion : PropertyGetRegion { + + private NullPropertyGetRegion() : + base(null, null) { + } + + internal static NullPropertyGetRegion Instance = new NullPropertyGetRegion(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullPropertyGetRegion]"; + } + } + + public abstract class PropertyGetSetRegion : AttributedNode, INullable { + + BlockStatement block; + + public BlockStatement Block { + get { + return block; + } + set { + block = value ?? BlockStatement.Null; + if (!block.IsNull) block.Parent = this; + } + } + + protected PropertyGetSetRegion(BlockStatement block, List attributes) { + Block = block; + Attributes = attributes; + } + + public virtual bool IsNull { + get { + return false; + } + } + } + + public class PropertySetRegion : PropertyGetSetRegion { + + List parameters; + + public List Parameters { + get { + return parameters; + } + set { + parameters = value ?? new List(); + } + } + + public PropertySetRegion(BlockStatement block, List attributes) : + base(block, attributes) { + parameters = new List(); + } + + public static PropertySetRegion Null { + get { + return NullPropertySetRegion.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitPropertySetRegion(this, data); + } + + public override string ToString() { + return string.Format("[PropertySetRegion Parameters={0} Block={1} Attributes={2} Modifier={3}]", GetCollectionString(Parameters), Block, GetCollectionString(Attributes), Modifier); + } + } + + internal sealed class NullPropertySetRegion : PropertySetRegion { + + private NullPropertySetRegion() : + base(null, null) { + } + + internal static NullPropertySetRegion Instance = new NullPropertySetRegion(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullPropertySetRegion]"; + } + } + + public class QueryExpression : Expression { + + List clauses; + + public List Clauses { + get { + return clauses; + } + set { + clauses = value ?? new List(); + } + } + + public QueryExpression() { + clauses = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpression(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpression Clauses={0}]", GetCollectionString(Clauses)); + } + } + + public class QueryExpressionAggregateClause : QueryExpressionClause { + + CollectionRangeVariable source; + + List middleClauses; + + List intoVariables; + + public CollectionRangeVariable Source { + get { + return source; + } + set { + source = value ?? CollectionRangeVariable.Null; + if (!source.IsNull) source.Parent = this; + } + } + + public List MiddleClauses { + get { + return middleClauses; + } + set { + middleClauses = value ?? new List(); + } + } + + public List IntoVariables { + get { + return intoVariables; + } + set { + intoVariables = value ?? new List(); + } + } + + public QueryExpressionAggregateClause() { + source = CollectionRangeVariable.Null; + middleClauses = new List(); + intoVariables = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionAggregateClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionAggregateClause Source={0} MiddleClauses={1} IntoVariables={2}]", Source, GetCollectionString(MiddleClauses), GetCollectionString(IntoVariables)); + } + } + + public abstract class QueryExpressionClause : AbstractNode, INullable { + + protected QueryExpressionClause() { + } + + public virtual bool IsNull { + get { + return false; + } + } + + public static QueryExpressionClause Null { + get { + return NullQueryExpressionClause.Instance; + } + } + } + + internal sealed class NullQueryExpressionClause : QueryExpressionClause { + + internal static NullQueryExpressionClause Instance = new NullQueryExpressionClause(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullQueryExpressionClause]"; + } + } + + public class QueryExpressionDistinctClause : QueryExpressionClause { + + public QueryExpressionDistinctClause() { + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionDistinctClause(this, data); + } + + public override string ToString() { + return "[QueryExpressionDistinctClause]"; + } + } + + public class QueryExpressionFromClause : QueryExpressionClause { + + List sources; + + public List Sources { + get { + return sources; + } + set { + sources = value ?? new List(); + } + } + + public QueryExpressionFromClause() { + sources = new List(); + } + + public new static QueryExpressionFromClause Null { + get { + return NullQueryExpressionFromClause.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionFromClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionFromClause Sources={0}]", GetCollectionString(Sources)); + } + } + + internal sealed class NullQueryExpressionFromClause : QueryExpressionFromClause { + + internal static NullQueryExpressionFromClause Instance = new NullQueryExpressionFromClause(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullQueryExpressionFromClause]"; + } + } + + public class QueryExpressionGroupClause : QueryExpressionClause { + + Expression projection; + + Expression groupBy; + + public Expression Projection { + get { + return projection; + } + set { + projection = value ?? Expression.Null; + if (!projection.IsNull) projection.Parent = this; + } + } + + public Expression GroupBy { + get { + return groupBy; + } + set { + groupBy = value ?? Expression.Null; + if (!groupBy.IsNull) groupBy.Parent = this; + } + } + + public QueryExpressionGroupClause() { + projection = Expression.Null; + groupBy = Expression.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionGroupClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionGroupClause Projection={0} GroupBy={1}]", Projection, GroupBy); + } + } + + public class QueryExpressionGroupJoinVBClause : QueryExpressionClause { + + QueryExpressionJoinVBClause joinClause; + + List intoVariables; + + public QueryExpressionJoinVBClause JoinClause { + get { + return joinClause; + } + set { + joinClause = value ?? QueryExpressionJoinVBClause.Null; + if (!joinClause.IsNull) joinClause.Parent = this; + } + } + + public List IntoVariables { + get { + return intoVariables; + } + set { + intoVariables = value ?? new List(); + } + } + + public QueryExpressionGroupJoinVBClause() { + joinClause = QueryExpressionJoinVBClause.Null; + intoVariables = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionGroupJoinVBClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionGroupJoinVBClause JoinClause={0} IntoVariables={1}]", JoinClause, GetCollectionString(IntoVariables)); + } + } + + public class QueryExpressionGroupVBClause : QueryExpressionClause { + + List groupVariables; + + List byVariables; + + List intoVariables; + + public List GroupVariables { + get { + return groupVariables; + } + set { + groupVariables = value ?? new List(); + } + } + + public List ByVariables { + get { + return byVariables; + } + set { + byVariables = value ?? new List(); + } + } + + public List IntoVariables { + get { + return intoVariables; + } + set { + intoVariables = value ?? new List(); + } + } + + public QueryExpressionGroupVBClause() { + groupVariables = new List(); + byVariables = new List(); + intoVariables = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionGroupVBClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionGroupVBClause GroupVariables={0} ByVariables={1} IntoVariables={2" + + "}]", GetCollectionString(GroupVariables), GetCollectionString(ByVariables), GetCollectionString(IntoVariables)); + } + } + + public class QueryExpressionJoinClause : QueryExpressionClause { + + Expression onExpression; + + Expression equalsExpression; + + CollectionRangeVariable source; + + string intoIdentifier; + + public Expression OnExpression { + get { + return onExpression; + } + set { + onExpression = value ?? Expression.Null; + if (!onExpression.IsNull) onExpression.Parent = this; + } + } + + public Expression EqualsExpression { + get { + return equalsExpression; + } + set { + equalsExpression = value ?? Expression.Null; + if (!equalsExpression.IsNull) equalsExpression.Parent = this; + } + } + + public CollectionRangeVariable Source { + get { + return source; + } + set { + source = value ?? CollectionRangeVariable.Null; + if (!source.IsNull) source.Parent = this; + } + } + + public string IntoIdentifier { + get { + return intoIdentifier; + } + set { + intoIdentifier = value ?? ""; + } + } + + public QueryExpressionJoinClause() { + onExpression = Expression.Null; + equalsExpression = Expression.Null; + source = CollectionRangeVariable.Null; + intoIdentifier = ""; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionJoinClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionJoinClause OnExpression={0} EqualsExpression={1} Source={2} IntoI" + + "dentifier={3}]", OnExpression, EqualsExpression, Source, IntoIdentifier); + } + } + + public class QueryExpressionJoinConditionVB : AbstractNode { + + Expression leftSide; + + Expression rightSide; + + public Expression LeftSide { + get { + return leftSide; + } + set { + leftSide = value ?? Expression.Null; + if (!leftSide.IsNull) leftSide.Parent = this; + } + } + + public Expression RightSide { + get { + return rightSide; + } + set { + rightSide = value ?? Expression.Null; + if (!rightSide.IsNull) rightSide.Parent = this; + } + } + + public QueryExpressionJoinConditionVB() { + leftSide = Expression.Null; + rightSide = Expression.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionJoinConditionVB(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionJoinConditionVB LeftSide={0} RightSide={1}]", LeftSide, RightSide); + } + } + + public class QueryExpressionJoinVBClause : QueryExpressionClause { + + CollectionRangeVariable joinVariable; + + QueryExpressionJoinVBClause subJoin; + + List conditions; + + public CollectionRangeVariable JoinVariable { + get { + return joinVariable; + } + set { + joinVariable = value ?? CollectionRangeVariable.Null; + if (!joinVariable.IsNull) joinVariable.Parent = this; + } + } + + public QueryExpressionJoinVBClause SubJoin { + get { + return subJoin; + } + set { + subJoin = value ?? QueryExpressionJoinVBClause.Null; + if (!subJoin.IsNull) subJoin.Parent = this; + } + } + + public List Conditions { + get { + return conditions; + } + set { + conditions = value ?? new List(); + } + } + + public QueryExpressionJoinVBClause() { + joinVariable = CollectionRangeVariable.Null; + subJoin = QueryExpressionJoinVBClause.Null; + conditions = new List(); + } + + public new static QueryExpressionJoinVBClause Null { + get { + return NullQueryExpressionJoinVBClause.Instance; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionJoinVBClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionJoinVBClause JoinVariable={0} SubJoin={1} Conditions={2}]", JoinVariable, SubJoin, GetCollectionString(Conditions)); + } + } + + internal sealed class NullQueryExpressionJoinVBClause : QueryExpressionJoinVBClause { + + internal static NullQueryExpressionJoinVBClause Instance = new NullQueryExpressionJoinVBClause(); + + public override bool IsNull { + get { + return true; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return null; + } + + public override string ToString() { + return "[NullQueryExpressionJoinVBClause]"; + } + } + + public class QueryExpressionLetClause : QueryExpressionClause { + + string identifier; + + Expression expression; + + public string Identifier { + get { + return identifier; + } + set { + identifier = string.IsNullOrEmpty(value) ? "?" : value; + } + } + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public QueryExpressionLetClause() { + identifier = "?"; + expression = Expression.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionLetClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionLetClause Identifier={0} Expression={1}]", Identifier, Expression); + } + } + + public class QueryExpressionLetVBClause : QueryExpressionClause { + + List variables; + + public List Variables { + get { + return variables; + } + set { + variables = value ?? new List(); + } + } + + public QueryExpressionLetVBClause() { + variables = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionLetVBClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionLetVBClause Variables={0}]", GetCollectionString(Variables)); + } + } + + public class QueryExpressionOrderClause : QueryExpressionClause { + + List orderings; + + public List Orderings { + get { + return orderings; + } + set { + orderings = value ?? new List(); + } + } + + public QueryExpressionOrderClause() { + orderings = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionOrderClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionOrderClause Orderings={0}]", GetCollectionString(Orderings)); + } + } + + public class QueryExpressionOrdering : AbstractNode { + + Expression criteria; + + QueryExpressionOrderingDirection direction; + + public Expression Criteria { + get { + return criteria; + } + set { + criteria = value ?? Expression.Null; + if (!criteria.IsNull) criteria.Parent = this; + } + } + + public QueryExpressionOrderingDirection Direction { + get { + return direction; + } + set { + direction = value; + } + } + + public QueryExpressionOrdering() { + criteria = Expression.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionOrdering(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionOrdering Criteria={0} Direction={1}]", Criteria, Direction); + } + } + + public class QueryExpressionPartitionVBClause : QueryExpressionClause { + + Expression expression; + + QueryExpressionPartitionType partitionType; + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public QueryExpressionPartitionType PartitionType { + get { + return partitionType; + } + set { + partitionType = value; + } + } + + public QueryExpressionPartitionVBClause() { + expression = Expression.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionPartitionVBClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionPartitionVBClause Expression={0} PartitionType={1}]", Expression, PartitionType); + } + } + + public class QueryExpressionSelectClause : QueryExpressionClause { + + Expression projection; + + public Expression Projection { + get { + return projection; + } + set { + projection = value ?? Expression.Null; + if (!projection.IsNull) projection.Parent = this; + } + } + + public QueryExpressionSelectClause() { + projection = Expression.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionSelectClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionSelectClause Projection={0}]", Projection); + } + } + + public class QueryExpressionSelectVBClause : QueryExpressionClause { + + List variables; + + public List Variables { + get { + return variables; + } + set { + variables = value ?? new List(); + } + } + + public QueryExpressionSelectVBClause() { + variables = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionSelectVBClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionSelectVBClause Variables={0}]", GetCollectionString(Variables)); + } + } + + public class QueryExpressionWhereClause : QueryExpressionClause { + + Expression condition; + + public Expression Condition { + get { + return condition; + } + set { + condition = value ?? Expression.Null; + if (!condition.IsNull) condition.Parent = this; + } + } + + public QueryExpressionWhereClause() { + condition = Expression.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitQueryExpressionWhereClause(this, data); + } + + public override string ToString() { + return string.Format("[QueryExpressionWhereClause Condition={0}]", Condition); + } + } + + public class RaiseEventStatement : Statement { + + string eventName; + + List arguments; + + public string EventName { + get { + return eventName; + } + set { + eventName = value ?? ""; + } + } + + public List Arguments { + get { + return arguments; + } + set { + arguments = value ?? new List(); + } + } + + public RaiseEventStatement(string eventName, List arguments) { + EventName = eventName; + Arguments = arguments; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitRaiseEventStatement(this, data); + } + + public override string ToString() { + return string.Format("[RaiseEventStatement EventName={0} Arguments={1}]", EventName, GetCollectionString(Arguments)); + } + } + + public class ReDimStatement : Statement { + + List reDimClauses; + + bool isPreserve; + + public List ReDimClauses { + get { + return reDimClauses; + } + set { + reDimClauses = value ?? new List(); + } + } + + public bool IsPreserve { + get { + return isPreserve; + } + set { + isPreserve = value; + } + } + + public ReDimStatement(bool isPreserve) { + IsPreserve = isPreserve; + reDimClauses = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitReDimStatement(this, data); + } + + public override string ToString() { + return string.Format("[ReDimStatement ReDimClauses={0} IsPreserve={1}]", GetCollectionString(ReDimClauses), IsPreserve); + } + } + + public class RemoveHandlerStatement : Statement { + + Expression eventExpression; + + Expression handlerExpression; + + public Expression EventExpression { + get { + return eventExpression; + } + set { + eventExpression = value ?? Expression.Null; + if (!eventExpression.IsNull) eventExpression.Parent = this; + } + } + + public Expression HandlerExpression { + get { + return handlerExpression; + } + set { + handlerExpression = value ?? Expression.Null; + if (!handlerExpression.IsNull) handlerExpression.Parent = this; + } + } + + public RemoveHandlerStatement(Expression eventExpression, Expression handlerExpression) { + EventExpression = eventExpression; + HandlerExpression = handlerExpression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitRemoveHandlerStatement(this, data); + } + + public override string ToString() { + return string.Format("[RemoveHandlerStatement EventExpression={0} HandlerExpression={1}]", EventExpression, HandlerExpression); + } + } + + public class ResumeStatement : Statement { + + string labelName; + + bool isResumeNext; + + public string LabelName { + get { + return labelName; + } + set { + labelName = value ?? ""; + } + } + + public bool IsResumeNext { + get { + return isResumeNext; + } + set { + isResumeNext = value; + } + } + + public ResumeStatement(bool isResumeNext) { + IsResumeNext = isResumeNext; + labelName = ""; + } + + public ResumeStatement(string labelName) { + LabelName = labelName; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitResumeStatement(this, data); + } + + public override string ToString() { + return string.Format("[ResumeStatement LabelName={0} IsResumeNext={1}]", LabelName, IsResumeNext); + } + } + + public class ReturnStatement : Statement { + + Expression expression; + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public ReturnStatement(Expression expression) { + Expression = expression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitReturnStatement(this, data); + } + + public override string ToString() { + return string.Format("[ReturnStatement Expression={0}]", Expression); + } + } + + public class StopStatement : Statement { + + public StopStatement() { + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitStopStatement(this, data); + } + + public override string ToString() { + return "[StopStatement]"; + } + } + + public class SwitchSection : BlockStatement { + + List switchLabels; + + public List SwitchLabels { + get { + return switchLabels; + } + set { + switchLabels = value ?? new List(); + } + } + + public SwitchSection() { + switchLabels = new List(); + } + + public SwitchSection(List switchLabels) { + SwitchLabels = switchLabels; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitSwitchSection(this, data); + } + + public override string ToString() { + return string.Format("[SwitchSection SwitchLabels={0}]", GetCollectionString(SwitchLabels)); + } + } + + public class SwitchStatement : Statement { + + Expression switchExpression; + + List switchSections; + + public Expression SwitchExpression { + get { + return switchExpression; + } + set { + switchExpression = value ?? Expression.Null; + if (!switchExpression.IsNull) switchExpression.Parent = this; + } + } + + public List SwitchSections { + get { + return switchSections; + } + set { + switchSections = value ?? new List(); + } + } + + public SwitchStatement(Expression switchExpression, List switchSections) { + SwitchExpression = switchExpression; + SwitchSections = switchSections; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitSwitchStatement(this, data); + } + + public override string ToString() { + return string.Format("[SwitchStatement SwitchExpression={0} SwitchSections={1}]", SwitchExpression, GetCollectionString(SwitchSections)); + } + } + + public class TemplateDefinition : AttributedNode { + + string name; + + VarianceModifier varianceModifier; + + List bases; + + public string Name { + get { + return name; + } + set { + name = string.IsNullOrEmpty(value) ? "?" : value; + } + } + + public VarianceModifier VarianceModifier { + get { + return varianceModifier; + } + set { + varianceModifier = value; + } + } + + public List Bases { + get { + return bases; + } + set { + bases = value ?? new List(); + } + } + + public TemplateDefinition() { + name = "?"; + bases = new List(); + } + + public TemplateDefinition(string name, List attributes) { + Name = name; + Attributes = attributes; + bases = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitTemplateDefinition(this, data); + } + + public override string ToString() { + return string.Format("[TemplateDefinition Name={0} VarianceModifier={1} Bases={2} Attributes={3} Modifi" + + "er={4}]", Name, VarianceModifier, GetCollectionString(Bases), GetCollectionString(Attributes), Modifier); + } + } + + public class ThisReferenceExpression : Expression { + + public ThisReferenceExpression() { + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitThisReferenceExpression(this, data); + } + + public override string ToString() { + return "[ThisReferenceExpression]"; + } + } + + public class ThrowStatement : Statement { + + Expression expression; + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public ThrowStatement(Expression expression) { + Expression = expression; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitThrowStatement(this, data); + } + + public override string ToString() { + return string.Format("[ThrowStatement Expression={0}]", Expression); + } + } + + public class TryCatchStatement : Statement { + + Statement statementBlock; + + List catchClauses; + + Statement finallyBlock; + + public Statement StatementBlock { + get { + return statementBlock; + } + set { + statementBlock = value ?? Statement.Null; + if (!statementBlock.IsNull) statementBlock.Parent = this; + } + } + + public List CatchClauses { + get { + return catchClauses; + } + set { + catchClauses = value ?? new List(); + } + } + + public Statement FinallyBlock { + get { + return finallyBlock; + } + set { + finallyBlock = value ?? Statement.Null; + if (!finallyBlock.IsNull) finallyBlock.Parent = this; + } + } + + public TryCatchStatement(Statement statementBlock, List catchClauses, Statement finallyBlock) { + StatementBlock = statementBlock; + CatchClauses = catchClauses; + FinallyBlock = finallyBlock; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitTryCatchStatement(this, data); + } + + public override string ToString() { + return string.Format("[TryCatchStatement StatementBlock={0} CatchClauses={1} FinallyBlock={2}]", StatementBlock, GetCollectionString(CatchClauses), FinallyBlock); + } + } + + public class TypeDeclaration : AttributedNode { + + string name; + + ClassType type; + + List baseTypes; + + List templates; + + Location bodyStartLocation; + + public string Name { + get { + return name; + } + set { + name = value ?? ""; + } + } + + public ClassType Type { + get { + return type; + } + set { + type = value; + } + } + + public List BaseTypes { + get { + return baseTypes; + } + set { + baseTypes = value ?? new List(); + } + } + + public List Templates { + get { + return templates; + } + set { + templates = value ?? new List(); + } + } + + public Location BodyStartLocation { + get { + return bodyStartLocation; + } + set { + bodyStartLocation = value; + } + } + + public TypeDeclaration(Modifiers modifier, List attributes) { + Modifier = modifier; + Attributes = attributes; + name = ""; + baseTypes = new List(); + templates = new List(); + bodyStartLocation = Location.Empty; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitTypeDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[TypeDeclaration Name={0} Type={1} BaseTypes={2} Templates={3} BodyStartLocation=" + + "{4} Attributes={5} Modifier={6}]", Name, Type, GetCollectionString(BaseTypes), GetCollectionString(Templates), BodyStartLocation, GetCollectionString(Attributes), Modifier); + } + } + + public class TypeOfExpression : Expression { + + TypeReference typeReference; + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public TypeOfExpression(TypeReference typeReference) { + TypeReference = typeReference; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitTypeOfExpression(this, data); + } + + public override string ToString() { + return string.Format("[TypeOfExpression TypeReference={0}]", TypeReference); + } + } + + public class TypeOfIsExpression : Expression { + + Expression expression; + + TypeReference typeReference; + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public TypeOfIsExpression(Expression expression, TypeReference typeReference) { + Expression = expression; + TypeReference = typeReference; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitTypeOfIsExpression(this, data); + } + + public override string ToString() { + return string.Format("[TypeOfIsExpression Expression={0} TypeReference={1}]", Expression, TypeReference); + } + } + + public class TypeReferenceExpression : Expression { + + TypeReference typeReference; + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public TypeReferenceExpression(TypeReference typeReference) { + TypeReference = typeReference; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitTypeReferenceExpression(this, data); + } + + public override string ToString() { + return string.Format("[TypeReferenceExpression TypeReference={0}]", TypeReference); + } + } + + public class UnaryOperatorExpression : Expression { + + UnaryOperatorType op; + + Expression expression; + + public UnaryOperatorType Op { + get { + return op; + } + set { + op = value; + } + } + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public UnaryOperatorExpression(UnaryOperatorType op) { + Op = op; + expression = Expression.Null; + } + + public UnaryOperatorExpression(Expression expression, UnaryOperatorType op) { + Expression = expression; + Op = op; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitUnaryOperatorExpression(this, data); + } + + public override string ToString() { + return string.Format("[UnaryOperatorExpression Op={0} Expression={1}]", Op, Expression); + } + } + + public class Using : AbstractNode { + + string name; + + TypeReference alias; + + string xmlPrefix; + + public string Name { + get { + return name; + } + set { + name = string.IsNullOrEmpty(value) ? "?" : value; + } + } + + public TypeReference Alias { + get { + return alias; + } + set { + alias = value ?? TypeReference.Null; + if (!alias.IsNull) alias.Parent = this; + } + } + + public string XmlPrefix { + get { + return xmlPrefix; + } + set { + xmlPrefix = value ?? ""; + } + } + + public Using(string name) { + Name = name; + alias = TypeReference.Null; + xmlPrefix = ""; + } + + public Using(string name, TypeReference alias) { + Name = name; + Alias = alias; + xmlPrefix = ""; + } + + public Using(string name, string xmlPrefix) { + Name = name; + XmlPrefix = xmlPrefix; + alias = TypeReference.Null; + } + + public bool IsXml { + get { + return xmlPrefix != null; + } + } + + public bool IsAlias { + get { + return !alias.IsNull; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitUsing(this, data); + } + + public override string ToString() { + return string.Format("[Using Name={0} Alias={1} XmlPrefix={2}]", Name, Alias, XmlPrefix); + } + } + + public class UsingDeclaration : AbstractNode { + + List usings; + + public List Usings { + get { + return usings; + } + set { + usings = value ?? new List(); + } + } + + public UsingDeclaration(List usings) { + Usings = usings; + } + +public UsingDeclaration(string xmlNamespace, string prefix) { usings = new List(1); usings.Add(new Using(xmlNamespace, prefix)); } + +public UsingDeclaration(string @namespace) : this(@namespace, TypeReference.Null) {} + +public UsingDeclaration(string @namespace, TypeReference alias) { usings = new List(1); usings.Add(new Using(@namespace, alias)); } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitUsingDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[UsingDeclaration Usings={0}]", GetCollectionString(Usings)); + } + } + + public class UsingStatement : StatementWithEmbeddedStatement { + + Statement resourceAcquisition; + + public Statement ResourceAcquisition { + get { + return resourceAcquisition; + } + set { + resourceAcquisition = value ?? Statement.Null; + if (!resourceAcquisition.IsNull) resourceAcquisition.Parent = this; + } + } + + public UsingStatement(Statement resourceAcquisition, Statement embeddedStatement) { + ResourceAcquisition = resourceAcquisition; + EmbeddedStatement = embeddedStatement; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitUsingStatement(this, data); + } + + public override string ToString() { + return string.Format("[UsingStatement ResourceAcquisition={0} EmbeddedStatement={1}]", ResourceAcquisition, EmbeddedStatement); + } + } + + public class VariableDeclaration : AbstractNode { + + string name; + + Expression initializer; + + TypeReference typeReference; + + Expression fixedArrayInitialization; + + public string Name { + get { + return name; + } + set { + name = value ?? ""; + } + } + + public Expression Initializer { + get { + return initializer; + } + set { + initializer = value ?? Expression.Null; + if (!initializer.IsNull) initializer.Parent = this; + } + } + + public TypeReference TypeReference { + get { + return typeReference; + } + set { + typeReference = value ?? TypeReference.Null; + if (!typeReference.IsNull) typeReference.Parent = this; + } + } + + public Expression FixedArrayInitialization { + get { + return fixedArrayInitialization; + } + set { + fixedArrayInitialization = value ?? Expression.Null; + if (!fixedArrayInitialization.IsNull) fixedArrayInitialization.Parent = this; + } + } + + public VariableDeclaration(string name) { + Name = name; + initializer = Expression.Null; + typeReference = TypeReference.Null; + fixedArrayInitialization = Expression.Null; + } + + public VariableDeclaration(string name, Expression initializer) { + Name = name; + Initializer = initializer; + typeReference = TypeReference.Null; + fixedArrayInitialization = Expression.Null; + } + + public VariableDeclaration(string name, Expression initializer, TypeReference typeReference) { + Name = name; + Initializer = initializer; + TypeReference = typeReference; + fixedArrayInitialization = Expression.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitVariableDeclaration(this, data); + } + + public override string ToString() { + return string.Format("[VariableDeclaration Name={0} Initializer={1} TypeReference={2} FixedArrayInitial" + + "ization={3}]", Name, Initializer, TypeReference, FixedArrayInitialization); + } + } + + public class WithStatement : Statement { + + Expression expression; + + BlockStatement body; + + public Expression Expression { + get { + return expression; + } + set { + expression = value ?? Expression.Null; + if (!expression.IsNull) expression.Parent = this; + } + } + + public BlockStatement Body { + get { + return body; + } + set { + body = value ?? BlockStatement.Null; + if (!body.IsNull) body.Parent = this; + } + } + + public WithStatement(Expression expression) { + Expression = expression; + body = BlockStatement.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitWithStatement(this, data); + } + + public override string ToString() { + return string.Format("[WithStatement Expression={0} Body={1}]", Expression, Body); + } + } + + public class XmlAttributeExpression : XmlExpression { + + string name; + + string literalValue; + + bool useDoubleQuotes; + + Expression expressionValue; + + public string Name { + get { + return name; + } + set { + name = value ?? ""; + } + } + + public string LiteralValue { + get { + return literalValue; + } + set { + literalValue = value ?? ""; + } + } + + public bool UseDoubleQuotes { + get { + return useDoubleQuotes; + } + set { + useDoubleQuotes = value; + } + } + + public Expression ExpressionValue { + get { + return expressionValue; + } + set { + expressionValue = value ?? Expression.Null; + if (!expressionValue.IsNull) expressionValue.Parent = this; + } + } + + public XmlAttributeExpression() { + name = ""; + literalValue = ""; + expressionValue = Expression.Null; + } + + public bool IsLiteralValue { + get { + return expressionValue.IsNull; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitXmlAttributeExpression(this, data); + } + + public override string ToString() { + return string.Format("[XmlAttributeExpression Name={0} LiteralValue={1} UseDoubleQuotes={2} ExpressionV" + + "alue={3}]", Name, LiteralValue, UseDoubleQuotes, ExpressionValue); + } + } + + public class XmlContentExpression : XmlExpression { + + string content; + + XmlContentType type; + + public string Content { + get { + return content; + } + set { + content = value ?? ""; + } + } + + public XmlContentType Type { + get { + return type; + } + set { + type = value; + } + } + + public XmlContentExpression(string content, XmlContentType type) { + Content = content; + Type = type; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitXmlContentExpression(this, data); + } + + public override string ToString() { + return string.Format("[XmlContentExpression Content={0} Type={1}]", Content, Type); + } + } + + public class XmlDocumentExpression : XmlExpression { + + List expressions; + + public List Expressions { + get { + return expressions; + } + set { + expressions = value ?? new List(); + } + } + + public XmlDocumentExpression() { + expressions = new List(); + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitXmlDocumentExpression(this, data); + } + + public override string ToString() { + return string.Format("[XmlDocumentExpression Expressions={0}]", GetCollectionString(Expressions)); + } + } + + public class XmlElementExpression : XmlExpression { + + Expression content; + + Expression nameExpression; + + string xmlName; + + List attributes; + + public Expression Content { + get { + return content; + } + set { + content = value ?? Expression.Null; + if (!content.IsNull) content.Parent = this; + } + } + + public Expression NameExpression { + get { + return nameExpression; + } + set { + nameExpression = value ?? Expression.Null; + if (!nameExpression.IsNull) nameExpression.Parent = this; + } + } + + public string XmlName { + get { + return xmlName; + } + set { + xmlName = value ?? ""; + } + } + + public List Attributes { + get { + return attributes; + } + set { + attributes = value ?? new List(); + } + } + + public XmlElementExpression() { + content = Expression.Null; + nameExpression = Expression.Null; + xmlName = ""; + attributes = new List(); + } + + public bool IsExpression { + get { + return !content.IsNull; + } + } + + public bool NameIsExpression { + get { + return !nameExpression.IsNull; + } + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitXmlElementExpression(this, data); + } + + public override string ToString() { + return string.Format("[XmlElementExpression Content={0} NameExpression={1} XmlName={2} Attributes={3}]", Content, NameExpression, XmlName, GetCollectionString(Attributes)); + } + } + + public class XmlEmbeddedExpression : XmlExpression { + + Expression inlineVBExpression; + + public Expression InlineVBExpression { + get { + return inlineVBExpression; + } + set { + inlineVBExpression = value ?? Expression.Null; + if (!inlineVBExpression.IsNull) inlineVBExpression.Parent = this; + } + } + + public XmlEmbeddedExpression() { + inlineVBExpression = Expression.Null; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitXmlEmbeddedExpression(this, data); + } + + public override string ToString() { + return string.Format("[XmlEmbeddedExpression InlineVBExpression={0}]", InlineVBExpression); + } + } + + public abstract class XmlExpression : Expression { + + protected XmlExpression() { + } + } + + public class XmlMemberAccessExpression : Expression { + + Expression targetObject; + + XmlAxisType axisType; + + bool isXmlIdentifier; + + string identifier; + + public Expression TargetObject { + get { + return targetObject; + } + set { + targetObject = value ?? Expression.Null; + if (!targetObject.IsNull) targetObject.Parent = this; + } + } + + public XmlAxisType AxisType { + get { + return axisType; + } + set { + axisType = value; + } + } + + public bool IsXmlIdentifier { + get { + return isXmlIdentifier; + } + set { + isXmlIdentifier = value; + } + } + + public string Identifier { + get { + return identifier; + } + set { + identifier = value ?? ""; + } + } + + public XmlMemberAccessExpression(Expression targetObject, XmlAxisType axisType, string identifier, bool isXmlIdentifier) { + TargetObject = targetObject; + AxisType = axisType; + Identifier = identifier; + IsXmlIdentifier = isXmlIdentifier; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) { + return visitor.VisitXmlMemberAccessExpression(this, data); + } + + public override string ToString() { + return string.Format("[XmlMemberAccessExpression TargetObject={0} AxisType={1} IsXmlIdentifier={2} Iden" + + "tifier={3}]", TargetObject, AxisType, IsXmlIdentifier, Identifier); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Dom/INode.cs b/ICSharpCode.NRefactory.VB/Dom/INode.cs new file mode 100644 index 000000000..2bfa18115 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/INode.cs @@ -0,0 +1,51 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; + +namespace ICSharpCode.NRefactory.VB.Dom +{ + public interface INode + { + INode Parent { + get; + set; + } + + List Children { + get; + } + + Location StartLocation { + get; + set; + } + + Location EndLocation { + get; + set; + } + + object UserData { + get; + set; + } + + /// + /// Visits all children + /// + /// The visitor to accept + /// Additional data for the visitor + /// The paremeter + object AcceptChildren(IDomVisitor visitor, object data); + + /// + /// Accept the visitor + /// + /// The visitor to accept + /// Additional data for the visitor + /// The value the visitor returns after the visit + object AcceptVisitor(IDomVisitor visitor, object data); + } +} diff --git a/ICSharpCode.NRefactory.VB/Dom/INullable.cs b/ICSharpCode.NRefactory.VB/Dom/INullable.cs new file mode 100644 index 000000000..c12c54b69 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/INullable.cs @@ -0,0 +1,12 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +namespace ICSharpCode.NRefactory.VB.Dom +{ + public interface INullable + { + bool IsNull { + get; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Dom/TypeReference.cs b/ICSharpCode.NRefactory.VB/Dom/TypeReference.cs new file mode 100644 index 000000000..a3c82d0ee --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Dom/TypeReference.cs @@ -0,0 +1,427 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Runtime.InteropServices; +using System.Text; + +namespace ICSharpCode.NRefactory.VB.Dom +{ + public class TypeReference : AbstractNode, INullable, ICloneable + { + public static readonly TypeReference StructConstraint = new TypeReference("constraint: struct"); + public static readonly TypeReference ClassConstraint = new TypeReference("constraint: class"); + public static readonly TypeReference NewConstraint = new TypeReference("constraint: new"); + + string type = ""; + int pointerNestingLevel; + int[] rankSpecifier; + List genericTypes = new List(); + + #region Static primitive type list + static Dictionary types = new Dictionary(); + static Dictionary vbtypes = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + static Dictionary typesReverse = new Dictionary(); + static Dictionary vbtypesReverse = new Dictionary(); + + static TypeReference() + { + // C# types + types.Add("bool", "System.Boolean"); + types.Add("byte", "System.Byte"); + types.Add("char", "System.Char"); + types.Add("decimal", "System.Decimal"); + types.Add("double", "System.Double"); + types.Add("float", "System.Single"); + types.Add("int", "System.Int32"); + types.Add("long", "System.Int64"); + types.Add("object", "System.Object"); + types.Add("sbyte", "System.SByte"); + types.Add("short", "System.Int16"); + types.Add("string", "System.String"); + types.Add("uint", "System.UInt32"); + types.Add("ulong", "System.UInt64"); + types.Add("ushort", "System.UInt16"); + types.Add("void", "System.Void"); + + // VB.NET types + vbtypes.Add("Boolean", "System.Boolean"); + vbtypes.Add("Byte", "System.Byte"); + vbtypes.Add("SByte", "System.SByte"); + vbtypes.Add("Date", "System.DateTime"); + vbtypes.Add("Char", "System.Char"); + vbtypes.Add("Decimal", "System.Decimal"); + vbtypes.Add("Double", "System.Double"); + vbtypes.Add("Single", "System.Single"); + vbtypes.Add("Integer", "System.Int32"); + vbtypes.Add("Long", "System.Int64"); + vbtypes.Add("UInteger","System.UInt32"); + vbtypes.Add("ULong", "System.UInt64"); + vbtypes.Add("Object", "System.Object"); + vbtypes.Add("Short", "System.Int16"); + vbtypes.Add("UShort", "System.UInt16"); + vbtypes.Add("String", "System.String"); + + foreach (KeyValuePair pair in types) { + typesReverse.Add(pair.Value, pair.Key); + } + foreach (KeyValuePair pair in vbtypes) { + vbtypesReverse.Add(pair.Value, pair.Key); + } + } + + /// + /// Gets a shortname=>full name dictionary of C# types. + /// + public static IDictionary PrimitiveTypesCSharp { + get { return types; } + } + + /// + /// Gets a shortname=>full name dictionary of VB types. + /// + public static IDictionary PrimitiveTypesVB { + get { return vbtypes; } + } + + /// + /// Gets a full name=>shortname dictionary of C# types. + /// + public static IDictionary PrimitiveTypesCSharpReverse { + get { return typesReverse; } + } + + /// + /// Gets a full name=>shortname dictionary of VB types. + /// + public static IDictionary PrimitiveTypesVBReverse { + get { return vbtypesReverse; } + } + + + static string GetSystemType(string type) + { + if (types == null) return type; + + string systemType; + if (types.TryGetValue(type, out systemType)) { + return systemType; + } + if (vbtypes.TryGetValue(type, out systemType)) { + return systemType; + } + return type; + } + #endregion + + object ICloneable.Clone() + { + return this.Clone(); + } + + public virtual TypeReference Clone() + { + TypeReference c = new TypeReference(type); + CopyFields(this, c); + return c; + } + + /// + /// Copies the pointerNestingLevel, RankSpecifier, GenericTypes and IsGlobal flag + /// from to . + /// + /// + /// If already contains generics, the new generics are appended to the list. + /// + protected static void CopyFields(TypeReference from, TypeReference to) + { + to.pointerNestingLevel = from.pointerNestingLevel; + if (from.rankSpecifier != null) { + to.rankSpecifier = (int[])from.rankSpecifier.Clone(); + } + foreach (TypeReference r in from.genericTypes) { + to.genericTypes.Add(r.Clone()); + } + to.IsGlobal = from.IsGlobal; + to.IsKeyword = from.IsKeyword; + } + + public string Type { + get { + return type; + } + set { + Debug.Assert(value != null); + type = value ?? "?"; + } + } + + /// + /// Removes the last identifier from the type. + /// e.g. "System.String.Length" becomes "System.String" or + /// "System.Collections.IEnumerable(of string).Current" becomes "System.Collections.IEnumerable(of string)" + /// This is used for explicit interface implementation in VB. + /// + public static string StripLastIdentifierFromType(ref TypeReference tr) + { + if (tr is InnerClassTypeReference && ((InnerClassTypeReference)tr).Type.IndexOf('.') < 0) { + string ident = ((InnerClassTypeReference)tr).Type; + tr = ((InnerClassTypeReference)tr).BaseType; + return ident; + } else { + int pos = tr.Type.LastIndexOf('.'); + if (pos < 0) + return tr.Type; + string ident = tr.Type.Substring(pos + 1); + tr.Type = tr.Type.Substring(0, pos); + return ident; + } + } + + public int PointerNestingLevel { + get { + return pointerNestingLevel; + } + set { + Debug.Assert(this.IsNull == false); + pointerNestingLevel = value; + } + } + + /// + /// The rank of the array type. + /// For "object[]", this is { 0 }; for "object[,]", it is {1}. + /// For "object[,][,,][]", it is {1, 2, 0}. + /// For non-array types, this property is null or {}. + /// + public int[] RankSpecifier { + get { + return rankSpecifier; + } + set { + Debug.Assert(this.IsNull == false); + rankSpecifier = value; + } + } + + public List GenericTypes { + get { + return genericTypes; + } + } + + public bool IsArrayType { + get { + return rankSpecifier != null && rankSpecifier.Length > 0; + } + } + + public static TypeReference CheckNull(TypeReference typeReference) + { + return typeReference ?? NullTypeReference.Instance; + } + + public static TypeReference Null { + get { + return NullTypeReference.Instance; + } + } + + public virtual bool IsNull { + get { + return false; + } + } + + /// + /// Gets/Sets if the type reference had a "global::" prefix. + /// + public bool IsGlobal { + get; set; + } + + /// + /// Gets/Sets if the type reference was using a language keyword. + /// + public bool IsKeyword { + get; set; + } + + public TypeReference(string type) + { + this.Type = type; + } + + public TypeReference(string type, bool isKeyword) + { + this.Type = type; + this.IsKeyword = isKeyword; + } + + public TypeReference(string type, List genericTypes) : this(type) + { + if (genericTypes != null) { + this.genericTypes = genericTypes; + } + } + + public TypeReference(string type, int[] rankSpecifier) : this(type, 0, rankSpecifier) + { + } + + public TypeReference(string type, int pointerNestingLevel, int[] rankSpecifier) : this(type, pointerNestingLevel, rankSpecifier, null) + { + } + + public TypeReference(string type, int pointerNestingLevel, int[] rankSpecifier, List genericTypes) + { + Debug.Assert(type != null); + this.type = type; + this.pointerNestingLevel = pointerNestingLevel; + this.rankSpecifier = rankSpecifier; + if (genericTypes != null) { + this.genericTypes = genericTypes; + } + } + + protected TypeReference() + {} + + public override object AcceptVisitor(IDomVisitor visitor, object data) + { + return visitor.VisitTypeReference(this, data); + } + + public override string ToString() + { + StringBuilder b = new StringBuilder(type); + if (genericTypes != null && genericTypes.Count > 0) { + b.Append('<'); + for (int i = 0; i < genericTypes.Count; i++) { + if (i > 0) b.Append(','); + b.Append(genericTypes[i].ToString()); + } + b.Append('>'); + } + if (pointerNestingLevel > 0) { + b.Append('*', pointerNestingLevel); + } + if (IsArrayType) { + foreach (int rank in rankSpecifier) { + b.Append('['); + if (rank < 0) + b.Append('`', -rank); + else + b.Append(',', rank); + b.Append(']'); + } + } + return b.ToString(); + } + + public static bool AreEqualReferences(TypeReference a, TypeReference b) + { + if (a == b) return true; + if (a == null || b == null) return false; + if (a is InnerClassTypeReference) a = ((InnerClassTypeReference)a).CombineToNormalTypeReference(); + if (b is InnerClassTypeReference) b = ((InnerClassTypeReference)b).CombineToNormalTypeReference(); + if (a.type != b.type) return false; + if (a.IsKeyword != b.IsKeyword) return false; + if (a.IsGlobal != b.IsGlobal) return false; + if (a.pointerNestingLevel != b.pointerNestingLevel) return false; + if (a.IsArrayType != b.IsArrayType) return false; + if (a.IsArrayType) { + if (a.rankSpecifier.Length != b.rankSpecifier.Length) return false; + for (int i = 0; i < a.rankSpecifier.Length; i++) { + if (a.rankSpecifier[i] != b.rankSpecifier[i]) return false; + } + } + if (a.genericTypes.Count != b.genericTypes.Count) return false; + for (int i = 0; i < a.genericTypes.Count; i++) { + if (!AreEqualReferences(a.genericTypes[i], b.genericTypes[i])) + return false; + } + return true; + } + } + + internal sealed class NullTypeReference : TypeReference + { + public static readonly NullTypeReference Instance = new NullTypeReference(); + public override bool IsNull { + get { + return true; + } + } + public override TypeReference Clone() + { + return this; + } + public override object AcceptVisitor(IDomVisitor visitor, object data) + { + return null; + } + + public override string ToString() + { + return String.Format("[NullTypeReference]"); + } + } + + /// + /// We need this special type reference for cases like + /// OuterClass(Of T1).InnerClass(Of T2) (in expression or type context) + /// or Dictionary(Of String, NamespaceStruct).KeyCollection (in type context, otherwise it's a + /// MemberReferenceExpression) + /// + public class InnerClassTypeReference: TypeReference + { + TypeReference baseType; + + public TypeReference BaseType { + get { return baseType; } + set { baseType = value; } + } + + public override TypeReference Clone() + { + InnerClassTypeReference c = new InnerClassTypeReference(baseType.Clone(), Type, new List()); + CopyFields(this, c); + return c; + } + + public InnerClassTypeReference(TypeReference outerClass, string innerType, List innerGenericTypes) + : base(innerType, innerGenericTypes) + { + this.baseType = outerClass; + } + + public override object AcceptVisitor(IDomVisitor visitor, object data) + { + return visitor.VisitInnerClassTypeReference(this, data); + } + + /// + /// Creates a type reference where all type parameters are specified for the innermost class. + /// Namespace.OuterClass(of string).InnerClass(of integer).InnerInnerClass + /// becomes Namespace.OuterClass.InnerClass.InnerInnerClass(of string, integer) + /// + public TypeReference CombineToNormalTypeReference() + { + TypeReference tr = (baseType is InnerClassTypeReference) + ? ((InnerClassTypeReference)baseType).CombineToNormalTypeReference() + : baseType.Clone(); + CopyFields(this, tr); + tr.Type += "." + Type; + return tr; + } + + public override string ToString() + { + return baseType.ToString() + "+" + base.ToString(); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/DomBuilder/ExpressionBuilder.cs b/ICSharpCode.NRefactory.VB/DomBuilder/ExpressionBuilder.cs new file mode 100644 index 000000000..5b832efb2 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/DomBuilder/ExpressionBuilder.cs @@ -0,0 +1,92 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.DomBuilder +{ + /// + /// Extension methods for NRefactory.Dom.Expression. + /// + public static class ExpressionBuilder + { + public static IdentifierExpression Identifier(string identifier) + { + return new IdentifierExpression(identifier); + } + + public static MemberReferenceExpression Member(this Expression targetObject, string memberName) + { + if (targetObject == null) + throw new ArgumentNullException("targetObject"); + return new MemberReferenceExpression(targetObject, memberName); + } + + public static InvocationExpression Call(this Expression callTarget, string methodName, params Expression[] arguments) + { + if (callTarget == null) + throw new ArgumentNullException("callTarget"); + return Call(Member(callTarget, methodName), arguments); + } + + public static InvocationExpression Call(this Expression callTarget, params Expression[] arguments) + { + if (callTarget == null) + throw new ArgumentNullException("callTarget"); + if (arguments == null) + throw new ArgumentNullException("arguments"); + return new InvocationExpression(callTarget, new List(arguments)); + } + + public static ObjectCreateExpression New(this TypeReference createType, params Expression[] arguments) + { + if (createType == null) + throw new ArgumentNullException("createType"); + if (arguments == null) + throw new ArgumentNullException("arguments"); + return new ObjectCreateExpression(createType, new List(arguments)); + } + + public static Expression CreateDefaultValueForType(TypeReference type) + { + if (type != null && !type.IsArrayType) { + switch (type.Type) { + case "System.SByte": + case "System.Byte": + case "System.Int16": + case "System.UInt16": + case "System.Int32": + case "System.UInt32": + case "System.Int64": + case "System.UInt64": + case "System.Single": + case "System.Double": + return new PrimitiveExpression(0, "0"); + case "System.Char": + return new PrimitiveExpression('\0', "'\\0'"); + case "System.Object": + case "System.String": + return new PrimitiveExpression(null, "null"); + case "System.Boolean": + return new PrimitiveExpression(false, "false"); + default: + return new DefaultValueExpression(type); + } + } else { + return new PrimitiveExpression(null, "null"); + } + } + + /// + /// Just calls the BinaryOperatorExpression constructor, + /// but being an extension method; this allows for a nicer + /// infix syntax in some cases. + /// + public static BinaryOperatorExpression Operator(this Expression left, BinaryOperatorType op, Expression right) + { + return new BinaryOperatorExpression(left, op, right); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/DomBuilder/StatementBuilder.cs b/ICSharpCode.NRefactory.VB/DomBuilder/StatementBuilder.cs new file mode 100644 index 000000000..cf5225356 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/DomBuilder/StatementBuilder.cs @@ -0,0 +1,55 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.DomBuilder +{ + /// + /// Extension methods for NRefactory.Dom.Expression. + /// + public static class StatementBuilder + { + public static void AddStatement(this BlockStatement block, Statement statement) + { + if (block == null) + throw new ArgumentNullException("block"); + if (statement == null) + throw new ArgumentNullException("statement"); + block.AddChild(statement); + statement.Parent = block; + } + + public static void AddStatement(this BlockStatement block, Expression expressionStatement) + { + if (expressionStatement == null) + throw new ArgumentNullException("expressionStatement"); + AddStatement(block, new ExpressionStatement(expressionStatement)); + } + + public static void Throw(this BlockStatement block, Expression expression) + { + if (expression == null) + throw new ArgumentNullException("expression"); + AddStatement(block, new ThrowStatement(expression)); + } + + public static void Return(this BlockStatement block, Expression expression) + { + if (expression == null) + throw new ArgumentNullException("expression"); + AddStatement(block, new ReturnStatement(expression)); + } + + public static void Assign(this BlockStatement block, Expression left, Expression right) + { + if (left == null) + throw new ArgumentNullException("left"); + if (right == null) + throw new ArgumentNullException("right"); + AddStatement(block, new AssignmentExpression(left, AssignmentOperatorType.Assign, right)); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/EnvironmentInformationProvider.cs b/ICSharpCode.NRefactory.VB/EnvironmentInformationProvider.cs new file mode 100644 index 000000000..df393e9dc --- /dev/null +++ b/ICSharpCode.NRefactory.VB/EnvironmentInformationProvider.cs @@ -0,0 +1,22 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB +{ + public interface IEnvironmentInformationProvider + { + bool HasField(string reflectionTypeName, int typeParameterCount, string fieldName); + } + + sealed class DummyEnvironmentInformationProvider : IEnvironmentInformationProvider + { + internal static readonly IEnvironmentInformationProvider Instance = new DummyEnvironmentInformationProvider(); + + public bool HasField(string reflectionTypeName, int typeParameterCount, string fieldName) + { + return false; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/ICSharpCode.NRefactory.VB.csproj b/ICSharpCode.NRefactory.VB/ICSharpCode.NRefactory.VB.csproj new file mode 100644 index 000000000..52d851010 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/ICSharpCode.NRefactory.VB.csproj @@ -0,0 +1,148 @@ + + + + {7B82B671-419F-45F4-B778-D9286F996EFA} + Debug + x86 + Library + ICSharpCode.NRefactory.VB + ICSharpCode.NRefactory.VB + v4.0 + Properties + + + x86 + + + bin\Debug\ + True + Full + False + True + DEBUG;TRACE + + + bin\Release\ + False + None + True + False + TRACE + + + + + 3.5 + + + + 3.5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ExpressionFinder.atg + + + + + + + + + + + + + + + + + + + + + vb.atg + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + CocoParserGenerator + ICSharpCode.NRefactory.VB.Parser + + + + ExpressionFinder.atg + + + vb.atg + + + ICSharpCode.NRefactory.VB.Parser + CocoParserGenerator + + + + + {3B2A5653-EC97-4001-BB9B-D90F1AF2C371} + ICSharpCode.NRefactory + + + + \ No newline at end of file diff --git a/ICSharpCode.NRefactory.VB/IDomVisitor.cs b/ICSharpCode.NRefactory.VB/IDomVisitor.cs new file mode 100644 index 000000000..f934f2d63 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/IDomVisitor.cs @@ -0,0 +1,242 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ICSharpCode.NRefactory.VB { + using System; + using ICSharpCode.NRefactory.VB.Dom; + + + public interface IDomVisitor { + + object VisitAddHandlerStatement(AddHandlerStatement addHandlerStatement, object data); + + object VisitAddressOfExpression(AddressOfExpression addressOfExpression, object data); + + object VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data); + + object VisitAssignmentExpression(AssignmentExpression assignmentExpression, object data); + + object VisitAttribute(ICSharpCode.NRefactory.VB.Dom.Attribute attribute, object data); + + object VisitAttributeSection(AttributeSection attributeSection, object data); + + object VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression, object data); + + object VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, object data); + + object VisitBlockStatement(BlockStatement blockStatement, object data); + + object VisitCaseLabel(CaseLabel caseLabel, object data); + + object VisitCastExpression(CastExpression castExpression, object data); + + object VisitCatchClause(CatchClause catchClause, object data); + + object VisitClassReferenceExpression(ClassReferenceExpression classReferenceExpression, object data); + + object VisitCollectionInitializerExpression(CollectionInitializerExpression collectionInitializerExpression, object data); + + object VisitCollectionRangeVariable(CollectionRangeVariable collectionRangeVariable, object data); + + object VisitCompilationUnit(CompilationUnit compilationUnit, object data); + + object VisitConditionalExpression(ConditionalExpression conditionalExpression, object data); + + object VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data); + + object VisitConstructorInitializer(ConstructorInitializer constructorInitializer, object data); + + object VisitContinueStatement(ContinueStatement continueStatement, object data); + + object VisitDeclareDeclaration(DeclareDeclaration declareDeclaration, object data); + + object VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression, object data); + + object VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data); + + object VisitDirectionExpression(DirectionExpression directionExpression, object data); + + object VisitDoLoopStatement(DoLoopStatement doLoopStatement, object data); + + object VisitElseIfSection(ElseIfSection elseIfSection, object data); + + object VisitEndStatement(EndStatement endStatement, object data); + + object VisitEraseStatement(EraseStatement eraseStatement, object data); + + object VisitErrorStatement(ErrorStatement errorStatement, object data); + + object VisitEventAddRegion(EventAddRegion eventAddRegion, object data); + + object VisitEventDeclaration(EventDeclaration eventDeclaration, object data); + + object VisitEventRaiseRegion(EventRaiseRegion eventRaiseRegion, object data); + + object VisitEventRemoveRegion(EventRemoveRegion eventRemoveRegion, object data); + + object VisitExitStatement(ExitStatement exitStatement, object data); + + object VisitExpressionRangeVariable(ExpressionRangeVariable expressionRangeVariable, object data); + + object VisitExpressionStatement(ExpressionStatement expressionStatement, object data); + + object VisitExternAliasDirective(ExternAliasDirective externAliasDirective, object data); + + object VisitFieldDeclaration(FieldDeclaration fieldDeclaration, object data); + + object VisitForeachStatement(ForeachStatement foreachStatement, object data); + + object VisitForNextStatement(ForNextStatement forNextStatement, object data); + + object VisitGotoStatement(GotoStatement gotoStatement, object data); + + object VisitIdentifierExpression(IdentifierExpression identifierExpression, object data); + + object VisitIfElseStatement(IfElseStatement ifElseStatement, object data); + + object VisitInnerClassTypeReference(InnerClassTypeReference innerClassTypeReference, object data); + + object VisitInterfaceImplementation(InterfaceImplementation interfaceImplementation, object data); + + object VisitInvocationExpression(InvocationExpression invocationExpression, object data); + + object VisitLabelStatement(LabelStatement labelStatement, object data); + + object VisitLambdaExpression(LambdaExpression lambdaExpression, object data); + + object VisitLocalVariableDeclaration(LocalVariableDeclaration localVariableDeclaration, object data); + + object VisitLockStatement(LockStatement lockStatement, object data); + + object VisitMemberInitializerExpression(MemberInitializerExpression memberInitializerExpression, object data); + + object VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression, object data); + + object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data); + + object VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, object data); + + object VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, object data); + + object VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, object data); + + object VisitOnErrorStatement(OnErrorStatement onErrorStatement, object data); + + object VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration, object data); + + object VisitOptionDeclaration(OptionDeclaration optionDeclaration, object data); + + object VisitParameterDeclarationExpression(ParameterDeclarationExpression parameterDeclarationExpression, object data); + + object VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, object data); + + object VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, object data); + + object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data); + + object VisitPropertyGetRegion(PropertyGetRegion propertyGetRegion, object data); + + object VisitPropertySetRegion(PropertySetRegion propertySetRegion, object data); + + object VisitQueryExpression(QueryExpression queryExpression, object data); + + object VisitQueryExpressionAggregateClause(QueryExpressionAggregateClause queryExpressionAggregateClause, object data); + + object VisitQueryExpressionDistinctClause(QueryExpressionDistinctClause queryExpressionDistinctClause, object data); + + object VisitQueryExpressionFromClause(QueryExpressionFromClause queryExpressionFromClause, object data); + + object VisitQueryExpressionGroupClause(QueryExpressionGroupClause queryExpressionGroupClause, object data); + + object VisitQueryExpressionGroupJoinVBClause(QueryExpressionGroupJoinVBClause queryExpressionGroupJoinVBClause, object data); + + object VisitQueryExpressionGroupVBClause(QueryExpressionGroupVBClause queryExpressionGroupVBClause, object data); + + object VisitQueryExpressionJoinClause(QueryExpressionJoinClause queryExpressionJoinClause, object data); + + object VisitQueryExpressionJoinConditionVB(QueryExpressionJoinConditionVB queryExpressionJoinConditionVB, object data); + + object VisitQueryExpressionJoinVBClause(QueryExpressionJoinVBClause queryExpressionJoinVBClause, object data); + + object VisitQueryExpressionLetClause(QueryExpressionLetClause queryExpressionLetClause, object data); + + object VisitQueryExpressionLetVBClause(QueryExpressionLetVBClause queryExpressionLetVBClause, object data); + + object VisitQueryExpressionOrderClause(QueryExpressionOrderClause queryExpressionOrderClause, object data); + + object VisitQueryExpressionOrdering(QueryExpressionOrdering queryExpressionOrdering, object data); + + object VisitQueryExpressionPartitionVBClause(QueryExpressionPartitionVBClause queryExpressionPartitionVBClause, object data); + + object VisitQueryExpressionSelectClause(QueryExpressionSelectClause queryExpressionSelectClause, object data); + + object VisitQueryExpressionSelectVBClause(QueryExpressionSelectVBClause queryExpressionSelectVBClause, object data); + + object VisitQueryExpressionWhereClause(QueryExpressionWhereClause queryExpressionWhereClause, object data); + + object VisitRaiseEventStatement(RaiseEventStatement raiseEventStatement, object data); + + object VisitReDimStatement(ReDimStatement reDimStatement, object data); + + object VisitRemoveHandlerStatement(RemoveHandlerStatement removeHandlerStatement, object data); + + object VisitResumeStatement(ResumeStatement resumeStatement, object data); + + object VisitReturnStatement(ReturnStatement returnStatement, object data); + + object VisitStopStatement(StopStatement stopStatement, object data); + + object VisitSwitchSection(SwitchSection switchSection, object data); + + object VisitSwitchStatement(SwitchStatement switchStatement, object data); + + object VisitTemplateDefinition(TemplateDefinition templateDefinition, object data); + + object VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression, object data); + + object VisitThrowStatement(ThrowStatement throwStatement, object data); + + object VisitTryCatchStatement(TryCatchStatement tryCatchStatement, object data); + + object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data); + + object VisitTypeOfExpression(TypeOfExpression typeOfExpression, object data); + + object VisitTypeOfIsExpression(TypeOfIsExpression typeOfIsExpression, object data); + + object VisitTypeReference(TypeReference typeReference, object data); + + object VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, object data); + + object VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, object data); + + object VisitUsing(Using @using, object data); + + object VisitUsingDeclaration(UsingDeclaration usingDeclaration, object data); + + object VisitUsingStatement(UsingStatement usingStatement, object data); + + object VisitVariableDeclaration(VariableDeclaration variableDeclaration, object data); + + object VisitWithStatement(WithStatement withStatement, object data); + + object VisitXmlAttributeExpression(XmlAttributeExpression xmlAttributeExpression, object data); + + object VisitXmlContentExpression(XmlContentExpression xmlContentExpression, object data); + + object VisitXmlDocumentExpression(XmlDocumentExpression xmlDocumentExpression, object data); + + object VisitXmlElementExpression(XmlElementExpression xmlElementExpression, object data); + + object VisitXmlEmbeddedExpression(XmlEmbeddedExpression xmlEmbeddedExpression, object data); + + object VisitXmlMemberAccessExpression(XmlMemberAccessExpression xmlMemberAccessExpression, object data); + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Block.cs b/ICSharpCode.NRefactory.VB/Lexer/Block.cs new file mode 100644 index 000000000..f7c104fce --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Block.cs @@ -0,0 +1,57 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public enum Context + { + Global, + TypeDeclaration, + ObjectCreation, + ObjectInitializer, + CollectionInitializer, + Type, + Member, + Parameter, + Identifier, + Body, + Xml, + Attribute, + Importable, + Query, + Expression, + Debug, + Default + } + + public class Block : ICloneable + { + public static readonly Block Default = new Block() { + context = Context.Global, + lastExpressionStart = Location.Empty + }; + + public Context context; + public Location lastExpressionStart; + public bool isClosed; + + public override string ToString() + { + return string.Format("[Block Context={0}, LastExpressionStart={1}, IsClosed={2}]", context, lastExpressionStart, isClosed); + } + + public object Clone() + { + return new Block() { + context = this.context, + lastExpressionStart = this.lastExpressionStart, + isClosed = this.isClosed + }; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinder.atg b/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinder.atg new file mode 100644 index 000000000..21548a063 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinder.atg @@ -0,0 +1,1361 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +PUSHCOMPILER WITH EXPECTEDSETS ExpressionFinder + +/* START AUTOGENERATED TOKENS SECTION */ +TOKENS + /* ----- terminal classes ----- */ + /* EOF is 0 */ + EOL + ident + LiteralString + LiteralCharacter + LiteralInteger + LiteralDouble + LiteralSingle + LiteralDecimal + LiteralDate + XmlOpenTag + XmlCloseTag + XmlStartInlineVB + XmlEndInlineVB + XmlCloseTagEmptyElement + XmlOpenEndTag + XmlContent + XmlComment + XmlCData + XmlProcessingInstruction + + /* ----- special character ----- */ + "=" + ":" + "," + "&" + "/" + "\\" + "." + "..." + ".@" + "!" + "-" + "+" + "^" + "?" + "*" + "{" + "}" + "(" + ")" + ">" + "<" + "<>" + ">=" + "<=" + "<<" + ">>" + "+=" + "^=" + "-=" + "*=" + "/=" + "\\=" + "<<=" + ">>=" + "&=" + ":=" + + /* ----- keywords ----- */ + "AddHandler" + "AddressOf" + "Aggregate" + "Alias" + "And" + "AndAlso" + "Ansi" + "As" + "Ascending" + "Assembly" + "Auto" + "Binary" + "Boolean" + "ByRef" + "By" + "Byte" + "ByVal" + "Call" + "Case" + "Catch" + "CBool" + "CByte" + "CChar" + "CDate" + "CDbl" + "CDec" + "Char" + "CInt" + "Class" + "CLng" + "CObj" + "Compare" + "Const" + "Continue" + "CSByte" + "CShort" + "CSng" + "CStr" + "CType" + "CUInt" + "CULng" + "CUShort" + "Custom" + "Date" + "Decimal" + "Declare" + "Default" + "Delegate" + "Descending" + "Dim" + "DirectCast" + "Distinct" + "Do" + "Double" + "Each" + "Else" + "ElseIf" + "End" + "EndIf" + "Enum" + "Equals" + "Erase" + "Error" + "Event" + "Exit" + "Explicit" + "False" + "Finally" + "For" + "Friend" + "From" + "Function" + "Get" + "GetType" + "Global" + "GoSub" + "GoTo" + "Group" + "Handles" + "If" + "Implements" + "Imports" + "In" + "Infer" + "Inherits" + "Integer" + "Interface" + "Into" + "Is" + "IsNot" + "Join" + "Key" + "Let" + "Lib" + "Like" + "Long" + "Loop" + "Me" + "Mod" + "Module" + "MustInherit" + "MustOverride" + "MyBase" + "MyClass" + "Namespace" + "Narrowing" + "New" + "Next" + "Not" + "Nothing" + "NotInheritable" + "NotOverridable" + "Object" + "Of" + "Off" + "On" + "Operator" + "Option" + "Optional" + "Or" + "Order" + "OrElse" + "Out" + "Overloads" + "Overridable" + "Overrides" + "ParamArray" + "Partial" + "Preserve" + "Private" + "Property" + "Protected" + "Public" + "RaiseEvent" + "ReadOnly" + "ReDim" + "Rem" + "RemoveHandler" + "Resume" + "Return" + "SByte" + "Select" + "Set" + "Shadows" + "Shared" + "Short" + "Single" + "Skip" + "Static" + "Step" + "Stop" + "Strict" + "String" + "Structure" + "Sub" + "SyncLock" + "Take" + "Text" + "Then" + "Throw" + "To" + "True" + "Try" + "TryCast" + "TypeOf" + "UInteger" + "ULong" + "Unicode" + "Until" + "UShort" + "Using" + "Variant" + "Wend" + "When" + "Where" + "While" + "Widening" + "With" + "WithEvents" + "WriteOnly" + "Xor" + "GetXmlNamespace" +/* END AUTOGENERATED TOKENS SECTION */ + +PRODUCTIONS +/*------------------------------------------------------------------------*/ +ExpressionFinder = + (. PushContext(Context.Global, la, t); .) + { OptionStatement } + { ImportsStatement } + { EXPECTEDCONFLICT("<") AttributeBlock } /* Expected LL(1) conflict: we can't tell global attributes */ + /* from those on types. */ + /* This isn't a problem, we can just treat all as global attributes */ + { NamespaceMemberDeclaration } + (. PopContext(); .) +. + +StatementTerminator + (. if (la != null) CurrentBlock.lastExpressionStart = la.Location; .) += + EOL | ":" +. + +OptionStatement = + "Option" ( ( "Explicit" | "Strict" | "Infer" ) [ "Off" | "On" ] | "Compare" ( "Text" | "Binary" ) ) StatementTerminator +. + +ImportsStatement = + "Imports" (. PushContext(Context.Importable, la, t); .) + (. nextTokenIsStartOfImportsOrAccessExpression = true; .) + ( + ( "Global" | Identifier | PrimitiveTypeName ) { TypeSuffix } [ ( "." | "=" ) TypeName ] + | XmlOpenTag Identifier "=" LiteralString XmlCloseTag + ) + (. PopContext(); .) + StatementTerminator + +. + +AttributeBlock = + "<" (. wasNormalAttribute = true; PushContext(Context.Attribute, la, t); .) [ ( "Assembly" | "Module" ) ":" (. wasNormalAttribute = false; .) ] { ANY } ">" (. PopContext(); .) [ EOL ] +. + +NamespaceMemberDeclaration = + NamespaceDeclaration + | TypeDeclaration +. + +NamespaceDeclaration = + "Namespace" (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) { ANY } (. PopContext(); .) StatementTerminator + { NamespaceMemberDeclaration } + "End" "Namespace" StatementTerminator +. + +TypeDeclaration = + { AttributeBlock } + { TypeModifier } + ( ClassOrModuleOrStructureTypeDeclaration | + DelegateTypeDeclaration | + EnumTypeDeclaration | + InterfaceDeclaration ) +. + +ClassOrModuleOrStructureTypeDeclaration = + (. PushContext(Context.TypeDeclaration, la, t); .) + ( "Module" | "Class" | "Structure" ) (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + [ "(" "Of" GenericTypeParameterDeclaration ")" ] StatementTerminator + [ (. isMissingModifier = false; .) "Inherits" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) StatementTerminator ] + [ (. isMissingModifier = false; .) "Implements" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) { "," (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) } StatementTerminator ] + { + { AttributeBlock } (.OnEachPossiblePath: isMissingModifier = true; .) + { TypeOrMemberModifier (. isMissingModifier = false; .) } (. isMissingModifier = false; .) + ( ClassOrModuleOrStructureTypeDeclaration | DelegateTypeDeclaration | EnumTypeDeclaration + | InterfaceDeclaration | MemberDeclaration ) + } + (. isMissingModifier = false; .) + "End" ( "Module" | "Class" | "Structure" ) StatementTerminator + (. PopContext(); .) +. + +EnumTypeDeclaration = + (. PushContext(Context.TypeDeclaration, la, t); .) + "Enum" (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + [ "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ] StatementTerminator + { + { AttributeBlock } + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + [ "=" Expression ] + StatementTerminator + } + "End" "Enum" StatementTerminator + (. PopContext(); .) +. + +InterfaceDeclaration = + (. PushContext(Context.TypeDeclaration, la, t); .) + "Interface" (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + [ "(" "Of" GenericTypeParameterDeclaration ")" ] StatementTerminator + [ "Inherits" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) { "," (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) } StatementTerminator ] + { + { AttributeBlock } (.OnEachPossiblePath: isMissingModifier = true; .) + { TypeOrMemberModifier (. isMissingModifier = false; .) } (. isMissingModifier = false; .) + ( ClassOrModuleOrStructureTypeDeclaration | DelegateTypeDeclaration | EnumTypeDeclaration + | InterfaceDeclaration | InterfaceMemberDeclaration ) + } + (. isMissingModifier = false; .) + "End" "Interface" StatementTerminator + (. PopContext(); .) +. + +InterfaceMemberDeclaration = + InterfaceEvent | InterfaceProperty | InterfaceSubOrFunction +. + +TypeOrMemberModifier = + MemberModifier /* contains all modifiers for types */ +. + +InterfaceEvent = + "Event" (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + [ "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) | "(" [ ParameterList ] ")" ] + StatementTerminator +. + +InterfaceProperty = + "Property" (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + [ "(" [ ParameterList ] ")" ] [ "As" (. PushContext(Context.Type, la, t); .) { AttributeBlock } TypeName (. PopContext(); .) ] + StatementTerminator +. + +InterfaceSubOrFunction = + ("Sub" | "Function") + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) ANY (. PopContext(); .) + { "(" [ ( "Of" GenericTypeParameterDeclaration | ParameterList ) ] ")" } + [ "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ] + StatementTerminator +. + +GenericConstraint = + TypeName | "New" | "Class" | "Structure" +. + +GenericConstraintList = + GenericConstraint | "{" GenericConstraint { "," GenericConstraint } "}" +. + +GenericTypeParameterDeclaration = + [ "Out" | "In" ] (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) IdentifierExceptOut (. PopContext(); .) [ "As" (. PushContext(Context.Type, la, t); .) GenericConstraintList (. PopContext(); .) ] + { "," [ "Out" | "In" ] (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) IdentifierExceptOut (. PopContext(); .) [ "As" (. PushContext(Context.Type, la, t); .) GenericConstraintList (. PopContext(); .) ] } +. + +DelegateTypeDeclaration = + "Delegate" ("Sub" | "Function") + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) ANY (. PopContext(); .) + { "(" [ "Of" GenericTypeParameterDeclaration | ParameterList ] ")" } + [ "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ] + StatementTerminator +. + +MemberDeclaration = + (. PushContext(Context.Member, la, t); .) + ( + MemberVariableOrConstantDeclaration | + SubOrFunctionDeclaration | + ExternalMemberDeclaration | + EventMemberDeclaration | + CustomEventMemberDeclaration | + PropertyDeclaration | + OperatorDeclaration + ) + (. PopContext(); .) +. + +SubOrFunctionDeclaration = + ("Sub" | "Function") + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) ANY (. PopContext(); .) + { "(" [ ( "Of" GenericTypeParameterDeclaration | ParameterList ) ] ")" } + [ "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ] + [ ( "Implements" | "Handles" ) [ ( "Me" | "MyClass" | "MyBase" ) "." ] TypeName ] + StatementTerminatorAndBlock + "End" ("Sub" | "Function") StatementTerminator +. + +ExternalMemberDeclaration = + "Declare" [ "Ansi" | "Unicode" | "Auto" ] ( "Sub" | "Function" ) + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + "Lib" LiteralString + [ "Alias" LiteralString ] + [ "(" [ ParameterList ] ")" ] + [ "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ] + StatementTerminator +. + +EventMemberDeclaration = + "Event" + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + ( "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) | [ "(" [ ParameterList ] ")" ] ) + [ "Implements" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) /*"." IdentifierOrKeyword*/ + { "," (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) /*"." IdentifierOrKeyword*/ } ] + /* the TypeName production already allows the "." IdentifierOrKeyword syntax, so to avoid an ambiguous grammer we just leave that out */ + StatementTerminator +. + +CustomEventMemberDeclaration = + "Custom" EventMemberDeclaration + { + { AttributeBlock } ( "AddHandler" | "RemoveHandler" | "RaiseEvent" ) "(" ParameterList ")" + StatementTerminatorAndBlock + "End" ( "AddHandler" | "RemoveHandler" | "RaiseEvent" ) StatementTerminator + } + "End" "Event" StatementTerminator +. + +PropertyDeclaration = + "Property" + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + [ "(" [ ParameterList ] ")" ] + [ "As" { AttributeBlock } ( NewExpression | (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ) ] + [ "Implements" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) /*"." IdentifierOrKeyword*/ + { "," (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) /*"." IdentifierOrKeyword*/ } ] + [ "=" Expression ] StatementTerminator + (. PopContext(); .) { EXPECTEDCONFLICT("<") AttributeBlock } + { EXPECTEDCONFLICT("Public", "Protected", "Private", "Friend") AccessModifier + // HACK : OnEachPossiblePath cannot detect that this might be the end of an auto property + // so we need to simulate it + (.OnEachPossiblePath: SetIdentifierExpected(la); .) } + [ (. PushContext(Context.Member, la, t); .) + ( "Get" | "Set" ) [ "(" [ ParameterList ] ")" ] + StatementTerminatorAndBlock + "End" ( "Get" | "Set" ) StatementTerminator + [ { AttributeBlock } { AccessModifier } ( "Get" | "Set" ) [ "(" [ ParameterList ] ")" ] + StatementTerminatorAndBlock + "End" ( "Get" | "Set" ) StatementTerminator ] + + "End" "Property" StatementTerminator ] +. + +OperatorDeclaration = + "Operator" (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) ANY (. PopContext(); .) + "(" ParameterList ")" + [ "As" (. PushContext(Context.Type, la, t); .) { AttributeBlock } TypeName (. PopContext(); .) ] + StatementTerminatorAndBlock + "End" "Operator" StatementTerminator +. + +MemberVariableOrConstantDeclaration = + MemberVariableOrConstantDeclarator { "," MemberVariableOrConstantDeclarator } StatementTerminator +. + +MemberVariableOrConstantDeclarator = + [ "Const" ] + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) IdentifierForFieldDeclaration (. PopContext(); .) + [ "?" ] { "(" [ Expression ] { "," [ Expression ] } ")" } + [ "As" (. PushContext(Context.Type, la, t); .) ( NewExpression | TypeName ) (. PopContext(); .) ] + [ "=" Expression ] +. + +ParameterList = + Parameter { "," Parameter } +. + +Parameter = + (. PushContext(Context.Parameter, la, t); .) + { AttributeBlock } { ParameterModifier } + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + [ "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ] + [ "=" Expression ] + (. PopContext(); .) +. + +StatementTerminatorAndBlock = + (. PushContext(Context.Body, la, t); .) + StatementTerminator + { EXPECTEDCONFLICT("End") + ( + [ Statement] StatementTerminator + | "End" + ( StatementTerminator /* End+StatementTerminator is end statement */ + | /* End+anything else is the end of this block. */ + (. + currentState = endOfStatementTerminatorAndBlock; /* leave this block */ + InformToken(t); /* process End again*/ + /* for processing current token (la): go to the position after processing End */ + goto switchlbl; + .) + ANY /* never reached due to goto above: */ + /* this ANY is just so that Coco knows this branch isn't empty */ + ) + ) + } + (.NamedState:endOfStatementTerminatorAndBlock.) + (. PopContext(); .) +. + +Expression + (.NamedState:startOfExpression.) += + (. PushContext(Context.Expression, la, t); .) + SimpleExpressionWithSuffix { BinaryOperator SimpleExpressionWithSuffix } + (. PopContext(); .) +. + +BinaryOperator = + "+" | "-" | "*" | "\\" | "/" | "^" | "Mod" + | "=" | "<>" | "<" | ">" (. wasNormalAttribute = false; .) | "<=" | ">=" + | "Like" | "&" | "And" | "AndAlso" | "Or" | "OrElse" + | "Xor" | "<<" | ">>" | "Is" | "IsNot" + | "^=" | "*=" | "/=" | "\\=" | "+=" | "-=" | "&=" | "<<=" | ">>=" | "To" | ":=" +. + +UnaryOperator = + "+" | "-" | "Not" | "AddressOf" +. + +SimpleExpressionWithSuffix = + (. PushContext(Context.Expression, la, t); .) + { UnaryOperator } + ( + SimpleExpression { ExpressionSuffix } + | "TypeOf" SimpleExpressionWithSuffix "Is" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) + | NewExpression + | CollectionInitializer + ) + (. PopContext(); .) +. + +SimpleExpression = + (. PushContext(Context.Expression, la, t); .) + ( Literal + | ( "(" (. activeArgument = 0; .) Expression // HACK in ExpressionRangeVariable Identifier is consumed before start + // of Expression so this can be an argument list too + { "," (. activeArgument++; .) Expression } ")" ) + | IdentifierForExpressionStart + | PrimitiveTypeName + | ( "." | "!" | ".@" | "..." ) (. nextTokenIsStartOfImportsOrAccessExpression = true; wasQualifierTokenAtStart = true; .) [ XmlOpenTag ] IdentifierOrKeyword [ XmlCloseTag ] + | "GetType" "(" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ")" + | "GetXmlNamespace" "(" (. readXmlIdentifier = true; .) Identifier ")" + | XmlLiteral + | LambdaExpression + | GREEDY QueryExpression + | CastExpression + | ConditionalExpression + ) + (. PopContext(); .) +. + +NewExpression = + "New" (. PushContext(Context.ObjectCreation, la, t); .) + ( + TypeName + [ + EXPECTEDCONFLICT("From") + ( + (. PushContext(Context.CollectionInitializer, la, t); .) + "From" + ( + CollectionInitializer /* From + CollectionInitializer is a NewExpression */ + | + (. + currentState = endOfStatementTerminatorAndBlock; /* leave this block */ + InformToken(t); /* process From again*/ + /* for processing current token (la): go to the position after processing End */ + goto switchlbl; + .) + ANY /* never reached due to goto above: */ + /* this ANY is just so that Coco knows this branch isn't empty */ + ) + (. PopContext(); .) + | + /* handle array initializer after New */ + (. PushContext(Context.CollectionInitializer, la, t); .) + CollectionInitializer + (. PopContext(); .) + | + (. PushContext(Context.ObjectInitializer, la, t); .) + "With" ObjectInitializer + (. PopContext(); .) + ) + ] + | + (. PushContext(Context.ObjectInitializer, la, t); .) + "With" ObjectInitializer + (. PopContext(); .) + ) + (. PopContext(); .) +. + +ObjectInitializer = + "{" [ [ "Key" ] "." IdentifierOrKeyword "=" Expression { "," [ "Key" ] "." IdentifierOrKeyword "=" Expression } ] "}" +. + +CollectionInitializer = + "{" [ Expression { "," Expression } ] "}" +. + +ExpressionSuffix = + "(" (. PushContext(Context.Expression, la, t); .) + ( "Of" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) + { "," (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) } + | [ ArgumentList ] ) (. PopContext(); .) ")" +| ( "." | "!" | ".@" | "..." ) (. nextTokenIsStartOfImportsOrAccessExpression = true; .) [ XmlOpenTag ] IdentifierOrKeyword [ XmlCloseTag ] +. + +CastExpression = + SimpleCastExpression | ("DirectCast" | "TryCast" | "CType") "(" Expression "," (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ")" +. + +SimpleCastExpression = + ( + "CBool" | + "CByte" | + "CChar" | + "CDate" | + "CDec" | + "CDbl" | + "CInt" | + "CLng" | + "CObj" | + "CSByte" | + "CShort" | + "CSng" | + "CStr" | + "CUInt" | + "CULng" | + "CUShort" + ) + "(" Expression ")" +. + +ConditionalExpression = + "If" "(" Expression "," Expression [ "," Expression ] ")" +. + +LambdaExpression = + SubLambdaExpression | + FunctionLambdaExpression +. + +SubLambdaExpression = + "Sub" "(" [ ParameterList ] ")" + ( GREEDY Statement | StatementTerminatorAndBlock "End" "Sub" ) +. + +FunctionLambdaExpression = + "Function" "(" [ ParameterList ] ")" + ( GREEDY Expression | [ "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ] StatementTerminatorAndBlock "End" "Function" ) +. + +QueryExpression + (. PushContext(Context.Query, la, t); .) += + ( FromQueryOperator | AggregateQueryOperator ) + { QueryOperator } + (. PopContext(); .) +. + +QueryOperator = + FromQueryOperator + | AggregateQueryOperator + | SelectQueryOperator + | DistinctQueryOperator + | WhereQueryOperator + | OrderByQueryOperator + | PartitionQueryOperator + | LetQueryOperator + | GroupByOrGroupJoinQueryOperator + | JoinQueryOperator +. + +FromQueryOperator = + "From" CollectionRangeVariable { "," CollectionRangeVariable } +. + +AggregateQueryOperator = + "Aggregate" CollectionRangeVariable { QueryOperator } "Into" ExpressionRangeVariable { "," ExpressionRangeVariable } +. + +SelectQueryOperator = + "Select" ExpressionRangeVariable { "," ExpressionRangeVariable } +. + +DistinctQueryOperator = + "Distinct" +. + +WhereQueryOperator = + "Where" Expression +. + +OrderByQueryOperator = + "Order" "By" Expression ( "Ascending" | "Descending" ) { "," Expression ( "Ascending" | "Descending" ) } +. + +PartitionQueryOperator = + ( "Take" | "Skip" ) [ "While" ] Expression +. + +LetQueryOperator = + "Let" ExpressionRangeVariable { "," ExpressionRangeVariable } +. + +GroupByOrGroupJoinQueryOperator = + "Group" + ( + EXPECTEDCONFLICT("Join") + JoinQueryOperator { ( "Group" JoinQueryOperator GroupJoinSuffix | JoinQueryOperator ) } + GroupJoinSuffix + | + ( EXPECTEDCONFLICT("By") () | ExpressionRangeVariable { "," ExpressionRangeVariable } ) + "By" ExpressionRangeVariable { "," ExpressionRangeVariable } + "Into" ExpressionRangeVariable { "," ExpressionRangeVariable } + ) +. + +JoinQueryOperator = + "Join" CollectionRangeVariable + "On" Expression "Equals" Expression { "," Expression "Equals" Expression } +. + +GroupJoinSuffix = + "Into" ExpressionRangeVariable { "," ExpressionRangeVariable } +. + +ExpressionRangeVariable = + [ + EXPECTEDCONFLICT("Where", "Until", "Unicode", "Text", "Take", "Skip", "Preserve", + "Order", "Off", "Out", "Key", "Join", "Into", "Infer", "Group", "From", + "Explicit", "Equals", "Distinct", "Descending", "Compare", "By", + "Binary", "Auto", "Assembly", "Ascending", "Ansi", "Aggregate", ident) + ( + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier + // HACK: needs to be optional because Expression can start with Identifier too + [ (. PopContext(); isAlreadyInExpr = true; .) + ( "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) "=" + | "=" + | (. + currentState = endOfStatementTerminatorAndBlock; /* leave this block */ + InformToken(t); /* process Identifier again*/ + /* for processing current token (la): go to the position after processing End */ + goto switchlbl; + .) + ANY /* never reached due to goto above: */ + /* this ANY is just so that Coco knows this branch isn't empty */ + ) + ] + ) + ] + Expression + (. if (!isAlreadyInExpr) PopContext(); isAlreadyInExpr = false; .) +. + +CollectionRangeVariable = + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + [ "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ] + "In" Expression +. + +/* semantic action will be inserted on all paths that possibly lead to XmlLiteral */ +XmlLiteral + (.OnEachPossiblePath: nextTokenIsPotentialStartOfExpression = true; .) += + (. PushContext(Context.Xml, la, t); .) + ( + ( XmlComment | XmlProcessingInstruction | XmlCData ) [ XmlContent ] { ( XmlComment | XmlProcessingInstruction ) [ XmlContent ] } [ XmlElement { XmlComment [ XmlContent ] } ] + | + XmlElement { XmlComment [ XmlContent ] } + ) + (. PopContext(); .) +. + +XmlElement = + (. PushContext(Context.Xml, la, t); .) + XmlOpenTag { ANY | XmlEmbeddedExpression } ( XmlCloseTagEmptyElement | XmlCloseTag { ANY | XmlEmbeddedExpression | XmlElement } XmlOpenEndTag { ANY | XmlEmbeddedExpression } XmlCloseTag ) + (. PopContext(); .) +. + +XmlEmbeddedExpression = + XmlStartInlineVB Expression XmlEndInlineVB +. + +PrimitiveTypeName = + "Byte" | + "SByte" | + "UShort" | + "Short" | + "UInteger" | + "Integer" | + "ULong" | + "Long" | + "Single" | + "Double" | + "Decimal" | + "Boolean" | + "Date" | + "Char" | + "String" | + "Object" +. + +TypeName = ( "Global" | Identifier | PrimitiveTypeName | "?" /* used for ? = completion */ ) { TypeSuffix } { "." IdentifierOrKeyword { TypeSuffix } } . + +TypeSuffix = "(" ( "Of" [ TypeName ] { "," [ TypeName ] } | [ ArgumentList ] ) ")" . + +IdentifierOrKeyword = ident +| "AddHandler" +| "AddressOf" +| "Aggregate" +| "Alias" +| "And" +| "AndAlso" +| "Ansi" +| "As" +| "Ascending" +| "Assembly" +| "Auto" +| "Binary" +| "Boolean" +| "ByRef" +| "By" +| "Byte" +| "ByVal" +| "Call" +| "Case" +| "Catch" +| "CBool" +| "CByte" +| "CChar" +| "CDate" +| "CDbl" +| "CDec" +| "Char" +| "CInt" +| "Class" +| "CLng" +| "CObj" +| "Compare" +| "Const" +| "Continue" +| "CSByte" +| "CShort" +| "CSng" +| "CStr" +| "CType" +| "CUInt" +| "CULng" +| "CUShort" +| "Custom" +| "Date" +| "Decimal" +| "Declare" +| "Default" +| "Delegate" +| "Descending" +| "Dim" +| "DirectCast" +| "Distinct" +| "Do" +| "Double" +| "Each" +| "Else" +| "ElseIf" +| "End" +| "EndIf" +| "Enum" +| "Equals" +| "Erase" +| "Error" +| "Event" +| "Exit" +| "Explicit" +| "False" +| "Finally" +| "For" +| "Friend" +| "From" +| "Function" +| "Get" +| "GetType" +| "Global" +| "GoSub" +| "GoTo" +| "Group" +| "Handles" +| "If" +| "Implements" +| "Imports" +| "In" +| "Infer" +| "Inherits" +| "Integer" +| "Interface" +| "Into" +| "Is" +| "IsNot" +| "Join" +| "Key" +| "Let" +| "Lib" +| "Like" +| "Long" +| "Loop" +| "Me" +| "Mod" +| "Module" +| "MustInherit" +| "MustOverride" +| "MyBase" +| "MyClass" +| "Namespace" +| "Narrowing" +| "New" +| "Next" +| "Not" +| "Nothing" +| "NotInheritable" +| "NotOverridable" +| "Object" +| "Of" +| "Off" +| "On" +| "Operator" +| "Option" +| "Optional" +| "Or" +| "Order" +| "OrElse" +| "Out" +| "Overloads" +| "Overridable" +| "Overrides" +| "ParamArray" +| "Partial" +| "Preserve" +| "Private" +| "Property" +| "Protected" +| "Public" +| "RaiseEvent" +| "ReadOnly" +| "ReDim" +| "Rem" +| "RemoveHandler" +| "Resume" +| "Return" +| "SByte" +| "Select" +| "Set" +| "Shadows" +| "Shared" +| "Short" +| "Single" +| "Skip" +| "Static" +| "Step" +| "Stop" +| "Strict" +| "String" +| "Structure" +| "Sub" +| "SyncLock" +| "Take" +| "Text" +| "Then" +| "Throw" +| "To" +| "True" +| "Try" +| "TryCast" +| "TypeOf" +| "UInteger" +| "ULong" +| "Unicode" +| "Until" +| "UShort" +| "Using" +| "Variant" +| "Wend" +| "When" +| "Where" +| "While" +| "Widening" +| "With" +| "WithEvents" +| "WriteOnly" +| "Xor" +| "GetXmlNamespace" +. + +Literal = + LiteralString | + LiteralCharacter | + LiteralInteger | + LiteralDouble | + LiteralSingle | + LiteralDecimal | + LiteralDate | + "True" | + "False" | + "Nothing" | + /* from InstanceExpression */ + "Me" | + "MyBase" | + "MyClass" +. + +Statement = + VariableDeclarationStatement + | WithOrLockStatement + | AddOrRemoveHandlerStatement + | RaiseEventStatement + | EXPECTEDCONFLICT("If") IfStatement /* prefer if-statement to if-expression */ + | SelectStatement + | WhileStatement + | DoLoopStatement + | ForStatement + | ErrorHandlingStatement + | ThrowStatement + | TryStatement + | BranchStatement + | ReDimStatement + | EraseStatement + | UsingStatement + | InvocationStatement +. + +VariableDeclarationStatement = + ( "Dim" | "Static" | "Const" ) + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) + Identifier (. PopContext(); .) [ "?" ] { "(" [ Expression ] { "," [ Expression ] } ")" } + { "," + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) + Identifier (. PopContext(); .) [ "?" ] { "(" [ Expression ] { "," [ Expression ] } ")" } + } + [ "As" (. PushContext(Context.Type, la, t); .) ( NewExpression | TypeName ) (. PopContext(); .) ] + [ "=" Expression ] +. + +WithOrLockStatement = + ( "With" | "SyncLock" ) Expression StatementTerminatorAndBlock "End" ( "With" | "SyncLock" ) +. + +AddOrRemoveHandlerStatement = + ( "AddHandler" | "RemoveHandler" ) Expression "," Expression +. + +RaiseEventStatement = + "RaiseEvent" IdentifierOrKeyword [ "(" [ ArgumentList ] ")" ] +. + +IfStatement = + "If" Expression + ( "Then" + ( Statement { EXPECTEDCONFLICT(":") ":" [Statement] } [ EXPECTEDCONFLICT("Else") "Else" [Statement] { EXPECTEDCONFLICT(":") ":" [Statement] } ] + | MultilineIfRemainder + ) + | MultilineIfRemainder + ) +. + +MultilineIfRemainder = + StatementTerminatorAndBlock + { + ("Else" [ "If" Expression [ "Then" ] ] + | "ElseIf" Expression [ "Then" ] + ) + StatementTerminatorAndBlock + } + "End" "If" +. + +SelectStatement = + "Select" [ "Case" ] Expression StatementTerminator + { + "Case" ( + "Else" | + ( [ "Is" ] ComparisonOperator SimpleExpressionWithSuffix | Expression ) + { "," ( [ "Is" ] ComparisonOperator SimpleExpressionWithSuffix | Expression ) } + ) + StatementTerminatorAndBlock + } + "End" "Select" +. + +ComparisonOperator = + "=" | "<>" | "<" | ">" (. wasNormalAttribute = false; .) | ">=" | "<=" +. + +WhileStatement = + "While" Expression StatementTerminatorAndBlock "End" "While" +. + +DoLoopStatement = + "Do" ( DoTopLoopStatement | DoBottomLoopStatement ) +. + +DoTopLoopStatement = + ( "While" | "Until" ) Expression + StatementTerminatorAndBlock + "Loop" +. + +DoBottomLoopStatement = + StatementTerminatorAndBlock + "Loop" [ ( "While" | "Until" ) Expression ] +. + +ForStatement = + "For" ( ForLoopStatement | ForEachLoopStatement ) +. + +ForLoopStatement = + ForLoopVariable "=" Expression /* "To" is binary operator */ [ "Step" Expression ] + StatementTerminatorAndBlock + "Next" [ Expression { "," Expression } ] +. + +ForEachLoopStatement = + "Each" ForLoopVariable "In" Expression + StatementTerminatorAndBlock + "Next" [ Expression { "," Expression } ] +. + +ForLoopVariable = + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) SimpleExpression (. PopContext(); .) + [ "?" ] { ExpressionSuffix } + [ "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ] +. + +ErrorHandlingStatement = + [ "On" ] "Error" ( Expression | "GoTo" ( LiteralInteger | Identifier ) | "Resume" "Next" ) + | "Resume" ( "Next" | LiteralInteger | Identifier ) +. + +ThrowStatement = + "Throw" [ Expression ] +. + +TryStatement = + "Try" + StatementTerminatorAndBlock + { + "Catch" + [ (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier (. PopContext(); .) + [ "As" (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) ] + ] + [ "When" Expression ] + StatementTerminatorAndBlock + } + [ + "Finally" + StatementTerminatorAndBlock + ] + "End" "Try" +. + +BranchStatement = + "GoTo" ( Identifier | LiteralInteger ) + | "Exit" ( "Do" | "For" | "While" | "Select" | "Sub" | "Function" | "Property" | "Try" ) + | "Continue" ( "Do" | "For" | "While" ) + | "Stop" + /*| "End" HACK End-Statements has special handling in Block */ + | "Return" (. PushContext(Context.Expression, la, t); .) [ Expression ] (. PopContext(); .) +. + +ReDimStatement = + "ReDim" + [ EXPECTEDCONFLICT("Preserve") "Preserve" ] /* Preserve is context-dependend keyword */ + Expression +. + +EraseStatement = + "Erase" Expression { "," Expression } +. + +UsingVariable = + [ + EXPECTEDCONFLICT("Where", "Until", "Unicode", "Text", "Take", "Skip", "Preserve", + "Order", "Off", "Out", "Key", "Join", "Into", "Infer", "Group", "From", + "Explicit", "Equals", "Distinct", "Descending", "Compare", "By", + "Binary", "Auto", "Assembly", "Ascending", "Ansi", "Aggregate", ident) + ( + (. PushContext(Context.Identifier, la, t); .) (.OnEachPossiblePath: SetIdentifierExpected(la); .) Identifier + // HACK: needs to be optional because Expression can start with Identifier too + [ (. PopContext(); isAlreadyInExpr = true; .) + ( "As" [ EXPECTEDCONFLICT("Where", "UShort", "Until", "Unicode", "ULong", "UInteger", "Text", "Take", + "String", "Skip", "Single", "Short", "SByte", "Preserve", "Out", "Order", + "Off", "Object", "Long", "Key", "Join", "Into", "Integer", "Infer", "Group", + "From", "Explicit", "Equals", "Double", "Distinct", "Descending", "Decimal", + "Date", "Compare", "Char", "Byte", "By", "Boolean", "Binary", "Binary", "Auto", + "Assembly", "Ascending", "Ansi", "Aggregate", ident) + (. PushContext(Context.Type, la, t); .) TypeName (. PopContext(); .) "=" ] + | "=" + | (. + currentState = endOfStatementTerminatorAndBlock; /* leave this block */ + InformToken(t); /* process Identifier again*/ + /* for processing current token (la): go to the position after processing End */ + goto switchlbl; + .) + ANY /* never reached due to goto above: */ + /* this ANY is just so that Coco knows this branch isn't empty */ + ) + ] + ) + ] + Expression + (. if (!isAlreadyInExpr) PopContext(); isAlreadyInExpr = false; .) +. + +UsingStatement = + "Using" UsingVariable { "," UsingVariable } + StatementTerminatorAndBlock + "End" "Using" +. + +InvocationStatement = + [ "Call" ] Expression +. + +ArgumentList = + (. activeArgument = 0; .) Expression { "," (. activeArgument++; .) [ Expression ] } +| (. activeArgument = 0; .) "," (. activeArgument++; .) [ Expression ] { "," (. activeArgument++; .) [ Expression ] } +. + +/* This production handles pseudo keywords that are needed in the grammar */ +Identifier = + IdentifierForFieldDeclaration + | "Custom" +. + +IdentifierForFieldDeclaration = + IdentifierForExpressionStart + | "Aggregate" + | "From" +. + +IdentifierForExpressionStart = + IdentifierExceptOut + | "Out" +. + +IdentifierExceptOut = + ident + | "Ansi" + | "Ascending" + | "Assembly" + | "Auto" + | "Binary" + | "By" + | "Compare" + | "Descending" + | "Distinct" + | "Equals" + | "Explicit" + | "Group" + | "Infer" + | "Into" + | "Join" + | "Key" + | "Off" + | "Order" + | "Preserve" + | "Skip" + | "Take" + | "Text" + | "Unicode" + | "Until" + | "Where" +. + +AccessModifier = + "Public" | + "Friend" | + "Protected" | + "Private" +. + +TypeModifier = + AccessModifier | + "MustInherit" | + "NotInheritable" | + "Shadows" | + "Partial" +. + +MemberModifier = + AccessModifier | + "Shadows" | + "Shared" | + "Overridable" | + "NotOverridable" | + "NotInheritable" | + "Overrides" | + "Overloads" | + "Partial" | + "WithEvents" | + "MustOverride" | + "Widening" | + "Narrowing" | + "ReadOnly" | + "WriteOnly" | + "Default" | + "Dim" +. + +ParameterModifier = + "ByVal" | + "ByRef" | + "Optional" | + "ParamArray" +. + +END ExpressionFinder . diff --git a/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinder.cs b/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinder.cs new file mode 100644 index 000000000..9e5feef6e --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinder.cs @@ -0,0 +1,154 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public partial class ExpressionFinder + { + Stack stack = new Stack(); + StringBuilder output = new StringBuilder(); + + void PopContext() + { + if (stack.Any()) { + string indent = new string('\t', stack.Count - 1); + var item = stack.Pop(); + item.isClosed = true; + Print(indent + "exit " + item.context); + } else { + Print("empty stack"); + } + } + + void PushContext(Context context, Token la, Token t) + { + string indent = new string('\t', stack.Count); + Location l = la == null ? (t == null ? Location.Empty : t.EndLocation) : la.Location; + + stack.Push(new Block() { context = context, lastExpressionStart = l }); + Print(indent + "enter " + context); + } + + public ExpressionFinder(ExpressionFinderState state) + { + wasQualifierTokenAtStart = state.WasQualifierTokenAtStart; + nextTokenIsPotentialStartOfExpression = state.NextTokenIsPotentialStartOfExpression; + nextTokenIsStartOfImportsOrAccessExpression = state.NextTokenIsStartOfImportsOrAccessExpression; + readXmlIdentifier = state.ReadXmlIdentifier; + identifierExpected = state.IdentifierExpected; + stateStack = new Stack(state.StateStack.Reverse()); + stack = new Stack(state.BlockStack.Select(x => (Block)x.Clone()).Reverse()); + currentState = state.CurrentState; + output = new StringBuilder(); + } + + void Print(string text) + { + //Console.WriteLine(text); + output.AppendLine(text); + } + + public void SetContext(SnippetType type) + { + switch (type) { + case SnippetType.Expression: + currentState = startOfExpression; + break; + } + + Advance(); + } + + public string Output { + get { return output.ToString(); } + } + + public string Stacktrace { + get { + string text = ""; + + foreach (Block b in stack) { + text += b.ToString() + "\n"; + } + + return text; + } + } + + public Block CurrentBlock { + get { return stack.Any() ? stack.Peek() : Block.Default; } + } + + public bool IsIdentifierExpected { + get { return identifierExpected; } + } + + void SetIdentifierExpected(Token la) + { + identifierExpected = true; + if (la != null) + CurrentBlock.lastExpressionStart = la.Location; + else if (t != null) + CurrentBlock.lastExpressionStart = t.EndLocation; + } + + public bool InContext(Context expected) + { + return stack + .SkipWhile(f => f.context == Context.Expression) + .IsElement(fx => fx.context == expected); + } + + public bool NextTokenIsPotentialStartOfExpression { + get { return nextTokenIsPotentialStartOfExpression; } + } + + public bool ReadXmlIdentifier { + get { return readXmlIdentifier; } + set { readXmlIdentifier = value; } + } + + public bool NextTokenIsStartOfImportsOrAccessExpression { + get { return nextTokenIsStartOfImportsOrAccessExpression; } + } + + public bool WasQualifierTokenAtStart { + get { return wasQualifierTokenAtStart; } + } + + public bool IsMissingModifier { + get { return isMissingModifier; } + } + + public bool WasNormalAttribute { + get { return wasNormalAttribute; } + } + + public int ActiveArgument { + get { return activeArgument; } + } + + public List Errors { + get { return errors; } + } + + public ExpressionFinderState Export() + { + return new ExpressionFinderState() { + WasQualifierTokenAtStart = wasQualifierTokenAtStart, + NextTokenIsPotentialStartOfExpression = nextTokenIsPotentialStartOfExpression, + NextTokenIsStartOfImportsOrAccessExpression = nextTokenIsStartOfImportsOrAccessExpression, + ReadXmlIdentifier = readXmlIdentifier, + IdentifierExpected = identifierExpected, + StateStack = new Stack(stateStack.Reverse()), + BlockStack = new Stack(stack.Select(x => (Block)x.Clone()).Reverse()), + CurrentState = currentState + }; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinderState.cs b/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinderState.cs new file mode 100644 index 000000000..485ed3d23 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/ExpressionFinderState.cs @@ -0,0 +1,22 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public class ExpressionFinderState + { + public bool WasQualifierTokenAtStart { get; set; } + public bool NextTokenIsPotentialStartOfExpression { get; set; } + public bool ReadXmlIdentifier { get; set; } + public bool IdentifierExpected { get; set; } + public bool NextTokenIsStartOfImportsOrAccessExpression { get; set; } + public Stack StateStack { get; set; } + public Stack BlockStack { get; set; } + public int CurrentState { get; set; } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Extensions.cs b/ICSharpCode.NRefactory.VB/Lexer/Extensions.cs new file mode 100644 index 000000000..7b5d4163a --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Extensions.cs @@ -0,0 +1,22 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public static class Extensions + { + public static bool IsElement(this IEnumerable items, Func check) + { + T item = items.FirstOrDefault(); + + if (item != null) + return check(item); + return false; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/KeywordList.txt b/ICSharpCode.NRefactory.VB/Lexer/KeywordList.txt new file mode 100644 index 000000000..a2a29b670 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/KeywordList.txt @@ -0,0 +1,284 @@ +# this list is used for autogeneration of: +# - Keywords.cs +# - Tokens.cs +# - ATGTokensSection.txt - the TOKENS section of the ATG file + +# use BuildKeywords to generate the different lists. + +$Namespace=ICSharpCode.NRefactory.VB.Parser +$UpperCaseKeywords=True + +# TERMINAL_CLASSES +EOF +EOL +Identifier +LiteralString +LiteralCharacter +LiteralInteger +LiteralDouble +LiteralSingle +LiteralDecimal +LiteralDate + +# XML_TERMINALS +XmlOpenTag +XmlCloseTag +XmlStartInlineVB +XmlEndInlineVB +XmlCloseTagEmptyElement +XmlOpenEndTag +XmlContent +XmlComment +XmlCData +XmlProcessingInstruction + +# SPECIAL_CHARACTERS +Assign = "=" +Colon =":" +Comma = "," +ConcatString = "&" +Div ="/" +DivInteger = "\\" +Dot = "." +TripleDot = "..." +DotAt = ".@" +# Exclamation mark = Dictionary access operator (not always a token, sometimes it's a type character) +ExclamationMark = "!" +Minus = "-" +Plus = "+" +Power = "^" +QuestionMark = "?" +Times = "*" + +OpenCurlyBrace = "{" +CloseCurlyBrace = "}" + +OpenParenthesis = "(" +CloseParenthesis = ")" + +GreaterThan = ">" +LessThan = "<" + +NotEqual = "<>" +GreaterEqual = ">=" +LessEqual = "<=" + +ShiftLeft = "<<" +ShiftRight = ">>" + +PlusAssign = "+=" +PowerAssign = "^=" +MinusAssign = "-=" +TimesAssign = "*=" +DivAssign = "/=" +DivIntegerAssign = "\\=" +ShiftLeftAssign = "<<=" +ShiftRightAssign = ">>=" +ConcatStringAssign = "&=" +ColonAssign = ":=" + +# keywords according to the spec: +# Keywordlist +"AddHandler" +"AddressOf" +"Aggregate" +"Alias" +"And" +"AndAlso" +"Ansi" +"As" +"Ascending" +"Assembly" +"Auto" +"Binary" +"Boolean" +"ByRef" +"By" +"Byte" +"ByVal" +"Call" +"Case" +"Catch" +"CBool" +"CByte" +"CChar" +"CDate" +"CDbl" +"CDec" +"Char" +"CInt" +"Class" +"CLng" +"CObj" +"Compare" +"Const" +"Continue" +"CSByte" +"CShort" +"CSng" +"CStr" +"CType" +"CUInt" +"CULng" +"CUShort" +"Custom" +"Date" +"Decimal" +"Declare" +"Default" +"Delegate" +"Descending" +"Dim" +"DirectCast" +"Distinct" +"Do" +"Double" +"Each" +"Else" +"ElseIf" +"End" +"EndIf" +"Enum" +"Equals" +"Erase" +"Error" +"Event" +"Exit" +"Explicit" +"False" +"Finally" +"For" +"Friend" +"From" +"Function" +"Get" +"GetType" +"Global" +"GoSub" +"GoTo" +"Group" +"Handles" +"If" +"Implements" +"Imports" +"In" +"Infer" +"Inherits" +"Integer" +"Interface" +"Into" +"Is" +"IsNot" +# Note: IsTrue and IsFalse are 'NOT' keywords they're only valid in Operator declarations (like get/set/value are no C# 'keywords') +"Join" +"Key" +"Let" +"Lib" +"Like" +"Long" +"Loop" +"Me" +"Mod" +"Module" +"MustInherit" +"MustOverride" +"MyBase" +"MyClass" +"Namespace" +"Narrowing" +"New" +"Next" +"Not" +"Nothing" +"NotInheritable" +"NotOverridable" +"Object" +"Of" +"Off" +"On" +"Operator" +"Option" +"Optional" +"Or" +"Order" +"OrElse" +"Out" +"Overloads" +"Overridable" +"Overrides" +"ParamArray" +"Partial" +"Preserve" +"Private" +"Property" +"Protected" +"Public" +"RaiseEvent" +"ReadOnly" +"ReDim" +# has to be in the keyword list for the output formatter +"Rem" +"RemoveHandler" +"Resume" +"Return" +"SByte" +"Select" +"Set" +"Shadows" +"Shared" +"Short" +"Single" +"Skip" +"Static" +"Step" +"Stop" +"Strict" +"String" +"Structure" +"Sub" +"SyncLock" +"Take" +"Text" +"Then" +"Throw" +"To" +"True" +"Try" +"TryCast" +"TypeOf" +"UInteger" +"ULong" +"Unicode" +"Until" +"UShort" +"Using" +"Variant" +"Wend" +"When" +"Where" +"While" +"Widening" +"With" +"WithEvents" +"WriteOnly" +"Xor" + +#XML specific keywords +"GetXmlNamespace" + +#Sets +Null("Nothing") +BlockSucc("Case", "Catch", "Else", "ElseIf", "End", "Finally", "Loop", "Next") +GlobalLevel("Namespace", "Module", "Class", "Structure", "Imports", "Option") +TypeLevel("Sub", "Function", "Property") + +# List of keywords that are valid identifiers, must be the same as the "Identifier" production in VBNET.ATG +IdentifierTokens("Text", "Binary", "Compare", "Assembly", "Ansi", "Auto", "Preserve", "Unicode", "Until", "Off", "Out", "Key", "Explicit", "Infer", "From", "Join", "Equals", "Distinct", "Where", "Take", "Skip", "Order", "By", "Ascending", "Descending", "Group", "Into", "Aggregate") +ExpressionStart("Me", "MyBase", "MyClass", @BooleanExpressions, @OperatorsAtStart, "New", @Null, "AddressOf", "GetType", "TypeOf", "GetXmlNamespace", "Global", @TypeKW, @LambdaStart, @CastExpressions) +StatementStart(@Null, @ExpressionStart, "Dim", "Const", "Static", "For", "While", "Do", "Select") +SimpleTypeName(@TypeKW, @IdentifierTokens) +CastExpressions("DirectCast", "TryCast", "CType", "CBool", "CByte", "CChar", "CDate", "CDec", "CDbl", "CInt", "CLng", "CObj", "CSByte", "CShort", "CSng", "CStr", "CUInt", "CULng", "CUShort") +BooleanExpressions("True", "False") +LambdaStart("Sub", "Function") +OperatorsAtStart("Not", "From", "Aggregate") +TypeKW("Boolean", "Date", "Char", "String", "Decimal", "Byte", "Short", "Integer", "Long", "Single", "Double", "UInteger", "ULong", "UShort", "SByte") \ No newline at end of file diff --git a/ICSharpCode.NRefactory.VB/Lexer/Keywords.cs b/ICSharpCode.NRefactory.VB/Lexer/Keywords.cs new file mode 100644 index 000000000..507ab10b4 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Keywords.cs @@ -0,0 +1,215 @@ +// this file was autogenerated by a tool. +using System; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public static class Keywords + { + static readonly string[] keywordList = { + "ADDHANDLER", + "ADDRESSOF", + "AGGREGATE", + "ALIAS", + "AND", + "ANDALSO", + "ANSI", + "AS", + "ASCENDING", + "ASSEMBLY", + "AUTO", + "BINARY", + "BOOLEAN", + "BYREF", + "BY", + "BYTE", + "BYVAL", + "CALL", + "CASE", + "CATCH", + "CBOOL", + "CBYTE", + "CCHAR", + "CDATE", + "CDBL", + "CDEC", + "CHAR", + "CINT", + "CLASS", + "CLNG", + "COBJ", + "COMPARE", + "CONST", + "CONTINUE", + "CSBYTE", + "CSHORT", + "CSNG", + "CSTR", + "CTYPE", + "CUINT", + "CULNG", + "CUSHORT", + "CUSTOM", + "DATE", + "DECIMAL", + "DECLARE", + "DEFAULT", + "DELEGATE", + "DESCENDING", + "DIM", + "DIRECTCAST", + "DISTINCT", + "DO", + "DOUBLE", + "EACH", + "ELSE", + "ELSEIF", + "END", + "ENDIF", + "ENUM", + "EQUALS", + "ERASE", + "ERROR", + "EVENT", + "EXIT", + "EXPLICIT", + "FALSE", + "FINALLY", + "FOR", + "FRIEND", + "FROM", + "FUNCTION", + "GET", + "GETTYPE", + "GLOBAL", + "GOSUB", + "GOTO", + "GROUP", + "HANDLES", + "IF", + "IMPLEMENTS", + "IMPORTS", + "IN", + "INFER", + "INHERITS", + "INTEGER", + "INTERFACE", + "INTO", + "IS", + "ISNOT", + "JOIN", + "KEY", + "LET", + "LIB", + "LIKE", + "LONG", + "LOOP", + "ME", + "MOD", + "MODULE", + "MUSTINHERIT", + "MUSTOVERRIDE", + "MYBASE", + "MYCLASS", + "NAMESPACE", + "NARROWING", + "NEW", + "NEXT", + "NOT", + "NOTHING", + "NOTINHERITABLE", + "NOTOVERRIDABLE", + "OBJECT", + "OF", + "OFF", + "ON", + "OPERATOR", + "OPTION", + "OPTIONAL", + "OR", + "ORDER", + "ORELSE", + "OUT", + "OVERLOADS", + "OVERRIDABLE", + "OVERRIDES", + "PARAMARRAY", + "PARTIAL", + "PRESERVE", + "PRIVATE", + "PROPERTY", + "PROTECTED", + "PUBLIC", + "RAISEEVENT", + "READONLY", + "REDIM", + "REM", + "REMOVEHANDLER", + "RESUME", + "RETURN", + "SBYTE", + "SELECT", + "SET", + "SHADOWS", + "SHARED", + "SHORT", + "SINGLE", + "SKIP", + "STATIC", + "STEP", + "STOP", + "STRICT", + "STRING", + "STRUCTURE", + "SUB", + "SYNCLOCK", + "TAKE", + "TEXT", + "THEN", + "THROW", + "TO", + "TRUE", + "TRY", + "TRYCAST", + "TYPEOF", + "UINTEGER", + "ULONG", + "UNICODE", + "UNTIL", + "USHORT", + "USING", + "VARIANT", + "WEND", + "WHEN", + "WHERE", + "WHILE", + "WIDENING", + "WITH", + "WITHEVENTS", + "WRITEONLY", + "XOR", + "GETXMLNAMESPACE" + }; + + static LookupTable keywords = new LookupTable(false); + + static Keywords() + { + for (int i = 0; i < keywordList.Length; ++i) { + keywords[keywordList[i]] = i + Tokens.AddHandler; + } + } + + public static int GetToken(string keyword) + { + return keywords[keyword]; + } + + public static bool IsNonIdentifierKeyword(string word) + { + int token = GetToken(word); + if (token < 0) + return false; + return !Tokens.IdentifierTokens[token]; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/LATextReader.cs b/ICSharpCode.NRefactory.VB/Lexer/LATextReader.cs new file mode 100644 index 000000000..f11043307 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/LATextReader.cs @@ -0,0 +1,52 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.IO; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public class LATextReader : TextReader + { + List buffer; + TextReader reader; + + public LATextReader(TextReader reader) + { + this.buffer = new List(); + this.reader = reader; + } + + public override int Peek() + { + return Peek(0); + } + + public override int Read() + { + int c = Peek(); + buffer.RemoveAt(0); + return c; + } + + public int Peek(int step) + { + while (step >= buffer.Count) { + buffer.Add(reader.Read()); + } + + if (step < 0) + return -1; + + return buffer[step]; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + reader.Dispose(); + base.Dispose(disposing); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/LookupTable.cs b/ICSharpCode.NRefactory.VB/Lexer/LookupTable.cs new file mode 100644 index 000000000..2ec80b687 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/LookupTable.cs @@ -0,0 +1,116 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Globalization; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + /// + /// This class implements a keyword map. It implements a digital search trees (tries) to find + /// a word. + /// + internal class LookupTable + { + Node root = new Node(-1, null); + bool casesensitive; + int length; + + /// + /// The number of elements in the table + /// + public int Count { + get { + return length; + } + } + + /// + /// Inserts an int in the tree, under keyword + /// + public int this[string keyword] { + get { + Node next = root; + + if (!casesensitive) { + keyword = keyword.ToUpper(CultureInfo.InvariantCulture); + } + + for (int i = 0; i < keyword.Length; ++i) { + int index = ((int)keyword[i]) % 256; + next = next.leaf[index]; + + if (next == null) { + return -1; + } + + if (keyword == next.word) { + return next.val; + } + } + return -1; + } + set { + Node node = root; + Node next = root; + + if (!casesensitive) { + keyword = keyword.ToUpper(CultureInfo.InvariantCulture); + } + + ++length; + + // insert word into the tree + for (int i = 0; i < keyword.Length; ++i) { + int index = ((int)keyword[i]) % 256; // index of curchar + bool d = keyword[i] == '\\'; + + next = next.leaf[index]; // get node to this index + + if (next == null) { // no node created -> insert word here + node.leaf[index] = new Node(value, keyword); + break; + } + + if (next.word != null && next.word.Length != i) { // node there, take node content and insert them again + string tmpword = next.word; // this word will be inserted 1 level deeper (better, don't need too much + int tmpval = next.val; // string comparisons for finding.) + next.val = -1; + next.word = null; + this[tmpword] = tmpval; + } + + if (i == keyword.Length - 1) { // end of keyword reached, insert node there, if a node was here it was + next.word = keyword; // reinserted, if it has the same length (keyword EQUALS this word) it will be overwritten + next.val = value; + break; + } + + node = next; + } + } + } + + /// + /// Creates a new instance of + /// + public LookupTable(bool casesensitive) + { + this.casesensitive = casesensitive; + } + + class Node + { + public Node(int val, string word) + { + this.word = word; + this.val = val; + } + + public string word; + public int val; + + public Node[] leaf = new Node[256]; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Parser.cs b/ICSharpCode.NRefactory.VB/Lexer/Parser.cs new file mode 100644 index 000000000..f1cd830b9 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Parser.cs @@ -0,0 +1,8660 @@ +using System; +using System.Collections; +using System.Collections.Generic; + + + +namespace ICSharpCode.NRefactory.VB.Parser { + + + +partial class ExpressionFinder { + const int startOfExpression = 56; + const int endOfStatementTerminatorAndBlock = 267; + static BitArray GetExpectedSet(int state) + { + switch (state) { + case 0: + case 1: + return set[0]; + case 2: + return set[1]; + case 3: + case 4: + return set[2]; + case 5: + return set[3]; + case 6: + case 89: + case 268: + case 525: + { + BitArray a = new BitArray(239); + return a; + } + case 7: + return set[4]; + case 8: + return set[5]; + case 9: + case 10: + case 20: + { + BitArray a = new BitArray(239); + a.Set(142, true); + return a; + } + case 11: + case 194: + case 200: + case 206: + case 245: + case 249: + case 299: + case 400: + case 410: + case 469: + case 512: + case 522: + case 533: + case 563: + case 599: + case 656: + case 673: + case 749: + return set[6]; + case 12: + case 13: + case 564: + case 565: + case 610: + case 620: + { + BitArray a = new BitArray(239); + a.Set(1, true); + a.Set(21, true); + a.Set(37, true); + return a; + } + case 14: + case 21: + case 23: + case 24: + case 36: + case 260: + case 263: + case 264: + case 300: + case 304: + case 326: + case 341: + case 352: + case 355: + case 361: + case 366: + case 376: + case 377: + case 397: + case 421: + case 518: + case 530: + case 536: + case 540: + case 548: + case 556: + case 566: + case 575: + case 592: + case 597: + case 605: + case 611: + case 614: + case 621: + case 624: + case 651: + case 654: + case 681: + case 692: + case 728: + case 748: + { + BitArray a = new BitArray(239); + a.Set(1, true); + a.Set(21, true); + return a; + } + case 15: + case 16: + return set[7]; + case 17: + case 18: + return set[8]; + case 19: + case 261: + case 275: + case 302: + case 356: + case 398: + case 449: + case 573: + case 593: + case 612: + case 616: + case 622: + case 652: + case 693: + { + BitArray a = new BitArray(239); + a.Set(113, true); + return a; + } + case 22: + case 541: + case 576: + return set[9]; + case 25: + { + BitArray a = new BitArray(239); + a.Set(1, true); + return a; + } + case 26: + case 27: + return set[10]; + case 28: + case 732: + return set[11]; + case 29: + return set[12]; + case 30: + return set[13]; + case 31: + case 32: + case 153: + case 218: + case 219: + case 269: + case 280: + case 281: + case 436: + case 437: + case 457: + case 458: + case 459: + case 460: + case 551: + case 552: + case 585: + case 586: + case 687: + case 688: + case 741: + case 742: + return set[14]; + case 33: + case 34: + case 513: + case 514: + case 523: + case 524: + case 553: + case 554: + case 678: + return set[15]; + case 35: + case 37: + case 158: + case 169: + case 172: + case 188: + case 204: + case 222: + case 311: + case 336: + case 420: + case 433: + case 472: + case 529: + case 547: + case 555: + case 633: + case 636: + case 660: + case 663: + case 668: + case 680: + case 696: + case 698: + case 721: + case 724: + case 727: + case 733: + case 736: + case 754: + return set[16]; + case 38: + case 41: + return set[17]; + case 39: + return set[18]; + case 40: + case 98: + case 102: + case 164: + case 392: + case 476: + return set[19]; + case 42: + case 178: + case 185: + case 190: + case 254: + case 443: + case 468: + case 471: + case 587: + case 588: + case 648: + { + BitArray a = new BitArray(239); + a.Set(37, true); + return a; + } + case 43: + case 44: + case 166: + case 167: + return set[20]; + case 45: + case 168: + case 189: + case 257: + case 446: + case 470: + case 473: + case 490: + case 521: + case 528: + case 559: + case 590: + case 627: + case 630: + case 642: + case 650: + case 667: + case 684: + case 702: + case 731: + case 740: + { + BitArray a = new BitArray(239); + a.Set(38, true); + return a; + } + case 46: + case 47: + case 51: + case 52: + case 53: + case 55: + case 414: + case 415: + case 417: + case 418: + case 484: + case 485: + case 715: + case 716: + return set[21]; + case 48: + case 49: + return set[22]; + case 50: + case 180: + case 187: + case 395: + { + BitArray a = new BitArray(239); + a.Set(22, true); + return a; + } + case 54: + case 170: + case 171: + case 173: + case 182: + case 416: + case 419: + case 423: + case 431: + case 480: + case 483: + case 487: + case 497: + case 504: + case 511: + case 717: + { + BitArray a = new BitArray(239); + a.Set(22, true); + a.Set(38, true); + return a; + } + case 56: + case 57: + case 71: + case 76: + case 77: + case 78: + case 84: + case 100: + case 156: + case 179: + case 181: + case 183: + case 186: + case 196: + case 198: + case 216: + case 240: + case 278: + case 288: + case 290: + case 291: + case 308: + case 325: + case 330: + case 339: + case 345: + case 347: + case 351: + case 354: + case 360: + case 371: + case 373: + case 374: + case 380: + case 394: + case 396: + case 432: + case 462: + case 478: + case 479: + case 481: + case 482: + case 546: + case 632: + return set[23]; + case 58: + case 79: + case 159: + return set[24]; + case 59: + return set[25]; + case 60: + { + BitArray a = new BitArray(239); + a.Set(216, true); + return a; + } + case 61: + { + BitArray a = new BitArray(239); + a.Set(145, true); + return a; + } + case 62: + case 157: + { + BitArray a = new BitArray(239); + a.Set(144, true); + return a; + } + case 63: + { + BitArray a = new BitArray(239); + a.Set(236, true); + return a; + } + case 64: + { + BitArray a = new BitArray(239); + a.Set(177, true); + return a; + } + case 65: + { + BitArray a = new BitArray(239); + a.Set(175, true); + return a; + } + case 66: + { + BitArray a = new BitArray(239); + a.Set(61, true); + return a; + } + case 67: + { + BitArray a = new BitArray(239); + a.Set(60, true); + return a; + } + case 68: + { + BitArray a = new BitArray(239); + a.Set(150, true); + return a; + } + case 69: + { + BitArray a = new BitArray(239); + a.Set(42, true); + return a; + } + case 70: + { + BitArray a = new BitArray(239); + a.Set(43, true); + return a; + } + case 72: + case 435: + { + BitArray a = new BitArray(239); + a.Set(40, true); + return a; + } + case 73: + { + BitArray a = new BitArray(239); + a.Set(41, true); + return a; + } + case 74: + case 99: + case 223: + case 224: + case 286: + case 287: + case 338: + case 406: + case 750: + { + BitArray a = new BitArray(239); + a.Set(20, true); + return a; + } + case 75: + { + BitArray a = new BitArray(239); + a.Set(154, true); + return a; + } + case 80: + case 92: + case 94: + case 149: + { + BitArray a = new BitArray(239); + a.Set(35, true); + return a; + } + case 81: + case 82: + return set[26]; + case 83: + { + BitArray a = new BitArray(239); + a.Set(36, true); + return a; + } + case 85: + case 101: + case 507: + { + BitArray a = new BitArray(239); + a.Set(22, true); + a.Set(36, true); + return a; + } + case 86: + case 122: + { + BitArray a = new BitArray(239); + a.Set(162, true); + return a; + } + case 87: + case 88: + return set[27]; + case 90: + case 93: + case 150: + case 151: + case 154: + return set[28]; + case 91: + case 103: + case 148: + { + BitArray a = new BitArray(239); + a.Set(233, true); + return a; + } + case 95: + { + BitArray a = new BitArray(239); + a.Set(26, true); + a.Set(36, true); + a.Set(147, true); + return a; + } + case 96: + { + BitArray a = new BitArray(239); + a.Set(26, true); + a.Set(147, true); + return a; + } + case 97: + case 697: + { + BitArray a = new BitArray(239); + a.Set(26, true); + return a; + } + case 104: + case 357: + { + BitArray a = new BitArray(239); + a.Set(231, true); + return a; + } + case 105: + { + BitArray a = new BitArray(239); + a.Set(230, true); + return a; + } + case 106: + { + BitArray a = new BitArray(239); + a.Set(224, true); + return a; + } + case 107: + { + BitArray a = new BitArray(239); + a.Set(223, true); + return a; + } + case 108: + case 303: + { + BitArray a = new BitArray(239); + a.Set(218, true); + return a; + } + case 109: + { + BitArray a = new BitArray(239); + a.Set(213, true); + return a; + } + case 110: + { + BitArray a = new BitArray(239); + a.Set(212, true); + return a; + } + case 111: + { + BitArray a = new BitArray(239); + a.Set(211, true); + return a; + } + case 112: + case 450: + { + BitArray a = new BitArray(239); + a.Set(210, true); + return a; + } + case 113: + { + BitArray a = new BitArray(239); + a.Set(209, true); + return a; + } + case 114: + { + BitArray a = new BitArray(239); + a.Set(206, true); + return a; + } + case 115: + { + BitArray a = new BitArray(239); + a.Set(203, true); + return a; + } + case 116: + case 363: + { + BitArray a = new BitArray(239); + a.Set(197, true); + return a; + } + case 117: + case 598: + case 617: + { + BitArray a = new BitArray(239); + a.Set(186, true); + return a; + } + case 118: + { + BitArray a = new BitArray(239); + a.Set(184, true); + return a; + } + case 119: + { + BitArray a = new BitArray(239); + a.Set(176, true); + return a; + } + case 120: + { + BitArray a = new BitArray(239); + a.Set(170, true); + return a; + } + case 121: + case 320: + case 327: + case 342: + { + BitArray a = new BitArray(239); + a.Set(163, true); + return a; + } + case 123: + { + BitArray a = new BitArray(239); + a.Set(147, true); + return a; + } + case 124: + case 227: + case 232: + case 234: + { + BitArray a = new BitArray(239); + a.Set(146, true); + return a; + } + case 125: + case 229: + case 233: + { + BitArray a = new BitArray(239); + a.Set(143, true); + return a; + } + case 126: + { + BitArray a = new BitArray(239); + a.Set(139, true); + return a; + } + case 127: + { + BitArray a = new BitArray(239); + a.Set(133, true); + return a; + } + case 128: + case 262: + { + BitArray a = new BitArray(239); + a.Set(127, true); + return a; + } + case 129: + case 152: + case 252: + { + BitArray a = new BitArray(239); + a.Set(126, true); + return a; + } + case 130: + { + BitArray a = new BitArray(239); + a.Set(124, true); + return a; + } + case 131: + { + BitArray a = new BitArray(239); + a.Set(121, true); + return a; + } + case 132: + case 197: + { + BitArray a = new BitArray(239); + a.Set(116, true); + return a; + } + case 133: + { + BitArray a = new BitArray(239); + a.Set(108, true); + return a; + } + case 134: + { + BitArray a = new BitArray(239); + a.Set(107, true); + return a; + } + case 135: + { + BitArray a = new BitArray(239); + a.Set(104, true); + return a; + } + case 136: + case 643: + { + BitArray a = new BitArray(239); + a.Set(98, true); + return a; + } + case 137: + { + BitArray a = new BitArray(239); + a.Set(87, true); + return a; + } + case 138: + { + BitArray a = new BitArray(239); + a.Set(84, true); + return a; + } + case 139: + case 209: + case 239: + { + BitArray a = new BitArray(239); + a.Set(70, true); + return a; + } + case 140: + { + BitArray a = new BitArray(239); + a.Set(67, true); + return a; + } + case 141: + { + BitArray a = new BitArray(239); + a.Set(66, true); + return a; + } + case 142: + { + BitArray a = new BitArray(239); + a.Set(65, true); + return a; + } + case 143: + { + BitArray a = new BitArray(239); + a.Set(64, true); + return a; + } + case 144: + { + BitArray a = new BitArray(239); + a.Set(62, true); + return a; + } + case 145: + case 251: + { + BitArray a = new BitArray(239); + a.Set(58, true); + return a; + } + case 146: + { + BitArray a = new BitArray(239); + a.Set(2, true); + return a; + } + case 147: + return set[29]; + case 155: + return set[30]; + case 160: + return set[31]; + case 161: + return set[32]; + case 162: + case 163: + case 474: + case 475: + return set[33]; + case 165: + return set[34]; + case 174: + case 175: + case 323: + case 332: + return set[35]; + case 176: + case 452: + return set[36]; + case 177: + case 379: + { + BitArray a = new BitArray(239); + a.Set(135, true); + return a; + } + case 184: + return set[37]; + case 191: + { + BitArray a = new BitArray(239); + a.Set(58, true); + a.Set(126, true); + return a; + } + case 192: + case 193: + return set[38]; + case 195: + { + BitArray a = new BitArray(239); + a.Set(171, true); + return a; + } + case 199: + case 213: + case 231: + case 236: + case 242: + case 244: + case 248: + case 250: + return set[39]; + case 201: + case 202: + { + BitArray a = new BitArray(239); + a.Set(63, true); + a.Set(138, true); + return a; + } + case 203: + case 205: + case 324: + { + BitArray a = new BitArray(239); + a.Set(138, true); + return a; + } + case 207: + case 208: + case 210: + case 212: + case 214: + case 215: + case 225: + case 230: + case 235: + case 243: + case 247: + case 273: + case 277: + return set[40]; + case 211: + { + BitArray a = new BitArray(239); + a.Set(22, true); + a.Set(143, true); + return a; + } + case 217: + return set[41]; + case 220: + case 282: + return set[42]; + case 221: + case 283: + return set[43]; + case 226: + { + BitArray a = new BitArray(239); + a.Set(22, true); + a.Set(70, true); + return a; + } + case 228: + { + BitArray a = new BitArray(239); + a.Set(133, true); + a.Set(143, true); + a.Set(146, true); + return a; + } + case 237: + case 238: + return set[44]; + case 241: + { + BitArray a = new BitArray(239); + a.Set(64, true); + a.Set(104, true); + return a; + } + case 246: + return set[45]; + case 253: + case 550: + case 672: + case 686: + case 694: + { + BitArray a = new BitArray(239); + a.Set(127, true); + a.Set(210, true); + return a; + } + case 255: + case 256: + case 444: + case 445: + case 519: + case 520: + case 526: + case 527: + case 625: + case 626: + case 628: + case 629: + case 640: + case 641: + case 665: + case 666: + case 682: + case 683: + return set[46]; + case 258: + case 259: + return set[47]; + case 265: + case 266: + return set[48]; + case 267: + return set[49]; + case 270: + return set[50]; + case 271: + case 272: + case 385: + return set[51]; + case 274: + case 279: + case 369: + case 661: + case 662: + case 664: + case 705: + case 722: + case 723: + case 725: + case 734: + case 735: + case 737: + { + BitArray a = new BitArray(239); + a.Set(1, true); + a.Set(21, true); + a.Set(22, true); + return a; + } + case 276: + { + BitArray a = new BitArray(239); + a.Set(226, true); + return a; + } + case 284: + case 285: + return set[52]; + case 289: + case 331: + case 346: + return set[53]; + case 292: + case 293: + case 313: + case 314: + case 328: + case 329: + case 343: + case 344: + return set[54]; + case 294: + case 386: + case 389: + { + BitArray a = new BitArray(239); + a.Set(1, true); + a.Set(21, true); + a.Set(111, true); + return a; + } + case 295: + { + BitArray a = new BitArray(239); + a.Set(108, true); + a.Set(124, true); + a.Set(231, true); + return a; + } + case 296: + return set[55]; + case 297: + case 316: + return set[56]; + case 298: + { + BitArray a = new BitArray(239); + a.Set(5, true); + return a; + } + case 301: + { + BitArray a = new BitArray(239); + a.Set(75, true); + a.Set(113, true); + a.Set(123, true); + return a; + } + case 305: + case 306: + return set[57]; + case 307: + case 312: + { + BitArray a = new BitArray(239); + a.Set(1, true); + a.Set(21, true); + a.Set(229, true); + return a; + } + case 309: + case 310: + return set[58]; + case 315: + return set[59]; + case 317: + { + BitArray a = new BitArray(239); + a.Set(118, true); + return a; + } + case 318: + case 319: + return set[60]; + case 321: + case 322: + return set[61]; + case 333: + case 334: + return set[62]; + case 335: + return set[63]; + case 337: + { + BitArray a = new BitArray(239); + a.Set(20, true); + a.Set(138, true); + return a; + } + case 340: + { + BitArray a = new BitArray(239); + a.Set(1, true); + a.Set(21, true); + a.Set(205, true); + return a; + } + case 348: + return set[64]; + case 349: + case 353: + { + BitArray a = new BitArray(239); + a.Set(152, true); + return a; + } + case 350: + return set[65]; + case 358: + case 359: + return set[66]; + case 362: + { + BitArray a = new BitArray(239); + a.Set(74, true); + a.Set(113, true); + return a; + } + case 364: + case 365: + return set[67]; + case 367: + case 368: + return set[68]; + case 370: + case 372: + return set[69]; + case 375: + case 381: + { + BitArray a = new BitArray(239); + a.Set(1, true); + a.Set(21, true); + a.Set(214, true); + return a; + } + case 378: + { + BitArray a = new BitArray(239); + a.Set(111, true); + a.Set(112, true); + a.Set(113, true); + return a; + } + case 382: + { + BitArray a = new BitArray(239); + a.Set(1, true); + a.Set(21, true); + a.Set(135, true); + return a; + } + case 383: + case 384: + case 447: + case 448: + return set[70]; + case 387: + case 388: + case 390: + case 391: + return set[71]; + case 393: + return set[72]; + case 399: + { + BitArray a = new BitArray(239); + a.Set(211, true); + a.Set(233, true); + return a; + } + case 401: + case 402: + case 411: + case 412: + return set[73]; + case 403: + case 413: + return set[74]; + case 404: + return set[75]; + case 405: + case 409: + return set[76]; + case 407: + case 408: + case 712: + case 713: + return set[77]; + case 422: + case 424: + case 425: + case 589: + case 649: + return set[78]; + case 426: + case 427: + return set[79]; + case 428: + case 429: + return set[80]; + case 430: + case 434: + { + BitArray a = new BitArray(239); + a.Set(20, true); + a.Set(22, true); + a.Set(38, true); + return a; + } + case 438: + case 442: + return set[81]; + case 439: + case 440: + return set[82]; + case 441: + { + BitArray a = new BitArray(239); + a.Set(21, true); + return a; + } + case 451: + return set[83]; + case 453: + case 466: + return set[84]; + case 454: + case 467: + return set[85]; + case 455: + case 456: + { + BitArray a = new BitArray(239); + a.Set(10, true); + return a; + } + case 461: + { + BitArray a = new BitArray(239); + a.Set(12, true); + return a; + } + case 463: + { + BitArray a = new BitArray(239); + a.Set(13, true); + return a; + } + case 464: + return set[86]; + case 465: + return set[87]; + case 477: + return set[88]; + case 486: + return set[89]; + case 488: + case 489: + case 557: + case 558: + case 700: + case 701: + return set[90]; + case 491: + case 492: + case 493: + case 498: + case 499: + case 560: + case 703: + case 730: + case 739: + return set[91]; + case 494: + case 500: + case 509: + return set[92]; + case 495: + case 496: + case 501: + case 502: + { + BitArray a = new BitArray(239); + a.Set(22, true); + a.Set(38, true); + a.Set(63, true); + return a; + } + case 503: + case 505: + case 510: + return set[93]; + case 506: + case 508: + return set[94]; + case 515: + case 534: + case 535: + case 591: + case 679: + { + BitArray a = new BitArray(239); + a.Set(1, true); + a.Set(21, true); + a.Set(63, true); + return a; + } + case 516: + case 517: + case 595: + case 596: + return set[95]; + case 531: + case 532: + case 539: + { + BitArray a = new BitArray(239); + a.Set(115, true); + return a; + } + case 537: + case 538: + return set[96]; + case 542: + case 543: + return set[97]; + case 544: + case 545: + case 604: + { + BitArray a = new BitArray(239); + a.Set(1, true); + a.Set(20, true); + a.Set(21, true); + return a; + } + case 549: + { + BitArray a = new BitArray(239); + a.Set(103, true); + return a; + } + case 561: + case 562: + case 574: + { + BitArray a = new BitArray(239); + a.Set(84, true); + a.Set(155, true); + a.Set(209, true); + return a; + } + case 567: + case 568: + return set[98]; + case 569: + case 570: + return set[99]; + case 571: + case 572: + case 583: + return set[100]; + case 577: + case 578: + return set[101]; + case 579: + case 580: + case 719: + return set[102]; + case 581: + return set[103]; + case 582: + return set[104]; + case 584: + case 594: + { + BitArray a = new BitArray(239); + a.Set(172, true); + return a; + } + case 600: + case 601: + return set[105]; + case 602: + return set[106]; + case 603: + case 639: + return set[107]; + case 606: + case 607: + case 608: + case 631: + return set[108]; + case 609: + case 613: + case 623: + { + BitArray a = new BitArray(239); + a.Set(128, true); + a.Set(198, true); + return a; + } + case 615: + return set[109]; + case 618: + return set[110]; + case 619: + return set[111]; + case 634: + case 635: + case 637: + case 711: + case 714: + return set[112]; + case 638: + return set[113]; + case 644: + case 646: + case 655: + { + BitArray a = new BitArray(239); + a.Set(119, true); + return a; + } + case 645: + return set[114]; + case 647: + return set[115]; + case 653: + { + BitArray a = new BitArray(239); + a.Set(56, true); + a.Set(189, true); + a.Set(193, true); + return a; + } + case 657: + case 658: + return set[116]; + case 659: + case 669: + { + BitArray a = new BitArray(239); + a.Set(1, true); + a.Set(21, true); + a.Set(136, true); + return a; + } + case 670: + { + BitArray a = new BitArray(239); + a.Set(101, true); + return a; + } + case 671: + return set[117]; + case 674: + case 675: + { + BitArray a = new BitArray(239); + a.Set(149, true); + return a; + } + case 676: + case 685: + case 751: + { + BitArray a = new BitArray(239); + a.Set(3, true); + return a; + } + case 677: + return set[118]; + case 689: + case 690: + return set[119]; + case 691: + case 699: + return set[120]; + case 695: + return set[121]; + case 704: + case 706: + return set[122]; + case 707: + case 718: + return set[123]; + case 708: + case 709: + return set[124]; + case 710: + return set[125]; + case 720: + { + BitArray a = new BitArray(239); + a.Set(136, true); + return a; + } + case 726: + { + BitArray a = new BitArray(239); + a.Set(140, true); + return a; + } + case 729: + case 738: + { + BitArray a = new BitArray(239); + a.Set(169, true); + return a; + } + case 743: + return set[126]; + case 744: + { + BitArray a = new BitArray(239); + a.Set(160, true); + return a; + } + case 745: + { + BitArray a = new BitArray(239); + a.Set(137, true); + return a; + } + case 746: + case 747: + return set[127]; + case 752: + { + BitArray a = new BitArray(239); + a.Set(11, true); + return a; + } + case 753: + return set[128]; + case 755: + { + BitArray a = new BitArray(239); + a.Set(173, true); + return a; + } + case 756: + return set[129]; + case 757: + { + BitArray a = new BitArray(239); + a.Set(67, true); + a.Set(213, true); + return a; + } + case 758: + return set[130]; + default: throw new InvalidOperationException(); + } + } + + const bool T = true; + const bool x = false; + + int currentState = 0; + + readonly Stack stateStack = new Stack(); + bool wasQualifierTokenAtStart = false; + bool nextTokenIsPotentialStartOfExpression = false; + bool readXmlIdentifier = false; + bool identifierExpected = false; + bool nextTokenIsStartOfImportsOrAccessExpression = false; + bool isMissingModifier = false; + bool isAlreadyInExpr = false; + bool wasNormalAttribute = false; + int activeArgument = 0; + List errors = new List(); + + public ExpressionFinder() + { + stateStack.Push(-1); // required so that we don't crash when leaving the root production + } + + void Expect(int expectedKind, Token la) + { + if (la.kind != expectedKind) { + Error(la); + output.AppendLine("expected: " + expectedKind); + //Console.WriteLine("expected: " + expectedKind); + } + } + + void Error(Token la) + { + output.AppendLine("not expected: " + la); + //Console.WriteLine("not expected: " + la); + errors.Add(la); + } + + Token t; + + public void InformToken(Token la) + { + switchlbl: switch (currentState) { + case 0: { + PushContext(Context.Global, la, t); + goto case 1; + } + case 1: { + if (la == null) { currentState = 1; break; } + if (la.kind == 173) { + stateStack.Push(1); + goto case 755; + } else { + goto case 2; + } + } + case 2: { + if (la == null) { currentState = 2; break; } + if (la.kind == 137) { + stateStack.Push(2); + goto case 745; + } else { + goto case 3; + } + } + case 3: { + if (la == null) { currentState = 3; break; } + if (la.kind == 40) { + stateStack.Push(3); + goto case 435; + } else { + goto case 4; + } + } + case 4: { + if (la == null) { currentState = 4; break; } + if (set[3].Get(la.kind)) { + stateStack.Push(4); + goto case 5; + } else { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 5: { + if (la == null) { currentState = 5; break; } + if (la.kind == 160) { + currentState = 741; + break; + } else { + if (set[4].Get(la.kind)) { + goto case 7; + } else { + goto case 6; + } + } + } + case 6: { + Error(la); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 7: { + if (la == null) { currentState = 7; break; } + if (la.kind == 40) { + stateStack.Push(7); + goto case 435; + } else { + goto case 8; + } + } + case 8: { + if (la == null) { currentState = 8; break; } + if (set[131].Get(la.kind)) { + currentState = 8; + break; + } else { + if (la.kind == 84 || la.kind == 155 || la.kind == 209) { + goto case 561; + } else { + if (la.kind == 103) { + currentState = 550; + break; + } else { + if (la.kind == 115) { + goto case 531; + } else { + if (la.kind == 142) { + goto case 9; + } else { + goto case 6; + } + } + } + } + } + } + case 9: { + PushContext(Context.TypeDeclaration, la, t); + goto case 10; + } + case 10: { + if (la == null) { currentState = 10; break; } + Expect(142, la); // "Interface" + currentState = 11; + break; + } + case 11: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(12); + goto case 206; + } + case 12: { + PopContext(); + goto case 13; + } + case 13: { + if (la == null) { currentState = 13; break; } + if (la.kind == 37) { + currentState = 738; + break; + } else { + goto case 14; + } + } + case 14: { + stateStack.Push(15); + goto case 23; + } + case 15: { + isMissingModifier = true; + goto case 16; + } + case 16: { + if (la == null) { currentState = 16; break; } + if (la.kind == 140) { + currentState = 733; + break; + } else { + goto case 17; + } + } + case 17: { + isMissingModifier = true; + goto case 18; + } + case 18: { + if (la == null) { currentState = 18; break; } + if (set[10].Get(la.kind)) { + goto case 26; + } else { + isMissingModifier = false; + goto case 19; + } + } + case 19: { + if (la == null) { currentState = 19; break; } + Expect(113, la); // "End" + currentState = 20; + break; + } + case 20: { + if (la == null) { currentState = 20; break; } + Expect(142, la); // "Interface" + currentState = 21; + break; + } + case 21: { + stateStack.Push(22); + goto case 23; + } + case 22: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 23: { + if (la != null) CurrentBlock.lastExpressionStart = la.Location; + goto case 24; + } + case 24: { + if (la == null) { currentState = 24; break; } + if (la.kind == 1) { + goto case 25; + } else { + if (la.kind == 21) { + currentState = stateStack.Pop(); + break; + } else { + goto case 6; + } + } + } + case 25: { + if (la == null) { currentState = 25; break; } + currentState = stateStack.Pop(); + break; + } + case 26: { + isMissingModifier = true; + goto case 27; + } + case 27: { + if (la == null) { currentState = 27; break; } + if (la.kind == 40) { + stateStack.Push(26); + goto case 435; + } else { + isMissingModifier = true; + goto case 28; + } + } + case 28: { + if (la == null) { currentState = 28; break; } + if (set[132].Get(la.kind)) { + currentState = 732; + break; + } else { + isMissingModifier = false; + goto case 29; + } + } + case 29: { + if (la == null) { currentState = 29; break; } + if (la.kind == 84 || la.kind == 155 || la.kind == 209) { + stateStack.Push(17); + goto case 561; + } else { + if (la.kind == 103) { + stateStack.Push(17); + goto case 549; + } else { + if (la.kind == 115) { + stateStack.Push(17); + goto case 531; + } else { + if (la.kind == 142) { + stateStack.Push(17); + goto case 9; + } else { + if (set[13].Get(la.kind)) { + stateStack.Push(17); + goto case 30; + } else { + Error(la); + goto case 17; + } + } + } + } + } + } + case 30: { + if (la == null) { currentState = 30; break; } + if (la.kind == 119) { + currentState = 522; + break; + } else { + if (la.kind == 186) { + currentState = 512; + break; + } else { + if (la.kind == 127 || la.kind == 210) { + currentState = 31; + break; + } else { + goto case 6; + } + } + } + } + case 31: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + goto case 32; + } + case 32: { + if (la == null) { currentState = 32; break; } + currentState = 33; + break; + } + case 33: { + PopContext(); + goto case 34; + } + case 34: { + if (la == null) { currentState = 34; break; } + if (la.kind == 37) { + currentState = 488; + break; + } else { + if (la.kind == 63) { + currentState = 35; + break; + } else { + goto case 23; + } + } + } + case 35: { + PushContext(Context.Type, la, t); + stateStack.Push(36); + goto case 37; + } + case 36: { + PopContext(); + goto case 23; + } + case 37: { + if (la == null) { currentState = 37; break; } + if (la.kind == 130) { + currentState = 38; + break; + } else { + if (set[6].Get(la.kind)) { + currentState = 38; + break; + } else { + if (set[133].Get(la.kind)) { + currentState = 38; + break; + } else { + if (la.kind == 33) { + currentState = 38; + break; + } else { + Error(la); + goto case 38; + } + } + } + } + } + case 38: { + if (la == null) { currentState = 38; break; } + if (la.kind == 37) { + stateStack.Push(38); + goto case 42; + } else { + goto case 39; + } + } + case 39: { + if (la == null) { currentState = 39; break; } + if (la.kind == 26) { + currentState = 40; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 40: { + stateStack.Push(41); + goto case 102; + } + case 41: { + if (la == null) { currentState = 41; break; } + if (la.kind == 37) { + stateStack.Push(41); + goto case 42; + } else { + goto case 39; + } + } + case 42: { + if (la == null) { currentState = 42; break; } + Expect(37, la); // "(" + currentState = 43; + break; + } + case 43: { + nextTokenIsPotentialStartOfExpression = true; + goto case 44; + } + case 44: { + if (la == null) { currentState = 44; break; } + if (la.kind == 169) { + currentState = 486; + break; + } else { + if (set[21].Get(la.kind)) { + goto case 46; + } else { + Error(la); + goto case 45; + } + } + } + case 45: { + if (la == null) { currentState = 45; break; } + Expect(38, la); // ")" + currentState = stateStack.Pop(); + break; + } + case 46: { + nextTokenIsPotentialStartOfExpression = true; + goto case 47; + } + case 47: { + if (la == null) { currentState = 47; break; } + if (set[22].Get(la.kind)) { + stateStack.Push(45); + goto case 48; + } else { + goto case 45; + } + } + case 48: { + nextTokenIsPotentialStartOfExpression = true; + goto case 49; + } + case 49: { + if (la == null) { currentState = 49; break; } + if (set[23].Get(la.kind)) { + activeArgument = 0; + goto case 482; + } else { + if (la.kind == 22) { + activeArgument = 0; + goto case 50; + } else { + goto case 6; + } + } + } + case 50: { + if (la == null) { currentState = 50; break; } + Expect(22, la); // "," + currentState = 51; + break; + } + case 51: { + activeArgument++; + goto case 52; + } + case 52: { + nextTokenIsPotentialStartOfExpression = true; + goto case 53; + } + case 53: { + if (la == null) { currentState = 53; break; } + if (set[23].Get(la.kind)) { + stateStack.Push(54); + goto case 56; + } else { + goto case 54; + } + } + case 54: { + if (la == null) { currentState = 54; break; } + if (la.kind == 22) { + currentState = 55; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 55: { + activeArgument++; + goto case 52; + } + case 56: { + PushContext(Context.Expression, la, t); + goto case 57; + } + case 57: { + stateStack.Push(58); + goto case 76; + } + case 58: { + if (la == null) { currentState = 58; break; } + if (set[25].Get(la.kind)) { + stateStack.Push(57); + goto case 59; + } else { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 59: { + if (la == null) { currentState = 59; break; } + if (la.kind == 31) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 30) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 34) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 25) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 24) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 32) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 154) { + goto case 75; + } else { + if (la.kind == 20) { + goto case 74; + } else { + if (la.kind == 41) { + goto case 73; + } else { + if (la.kind == 40) { + goto case 72; + } else { + if (la.kind == 39) { + currentState = 71; + break; + } else { + if (la.kind == 43) { + goto case 70; + } else { + if (la.kind == 42) { + goto case 69; + } else { + if (la.kind == 150) { + goto case 68; + } else { + if (la.kind == 23) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 60) { + goto case 67; + } else { + if (la.kind == 61) { + goto case 66; + } else { + if (la.kind == 175) { + goto case 65; + } else { + if (la.kind == 177) { + goto case 64; + } else { + if (la.kind == 236) { + goto case 63; + } else { + if (la.kind == 44) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 45) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 144) { + goto case 62; + } else { + if (la.kind == 145) { + goto case 61; + } else { + if (la.kind == 47) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 49) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 50) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 51) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 46) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 48) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 54) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 52) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 53) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 216) { + goto case 60; + } else { + if (la.kind == 55) { + currentState = stateStack.Pop(); + break; + } else { + goto case 6; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + case 60: { + if (la == null) { currentState = 60; break; } + currentState = stateStack.Pop(); + break; + } + case 61: { + if (la == null) { currentState = 61; break; } + currentState = stateStack.Pop(); + break; + } + case 62: { + if (la == null) { currentState = 62; break; } + currentState = stateStack.Pop(); + break; + } + case 63: { + if (la == null) { currentState = 63; break; } + currentState = stateStack.Pop(); + break; + } + case 64: { + if (la == null) { currentState = 64; break; } + currentState = stateStack.Pop(); + break; + } + case 65: { + if (la == null) { currentState = 65; break; } + currentState = stateStack.Pop(); + break; + } + case 66: { + if (la == null) { currentState = 66; break; } + currentState = stateStack.Pop(); + break; + } + case 67: { + if (la == null) { currentState = 67; break; } + currentState = stateStack.Pop(); + break; + } + case 68: { + if (la == null) { currentState = 68; break; } + currentState = stateStack.Pop(); + break; + } + case 69: { + if (la == null) { currentState = 69; break; } + currentState = stateStack.Pop(); + break; + } + case 70: { + if (la == null) { currentState = 70; break; } + currentState = stateStack.Pop(); + break; + } + case 71: { + wasNormalAttribute = false; + currentState = stateStack.Pop(); + goto switchlbl; + } + case 72: { + if (la == null) { currentState = 72; break; } + currentState = stateStack.Pop(); + break; + } + case 73: { + if (la == null) { currentState = 73; break; } + currentState = stateStack.Pop(); + break; + } + case 74: { + if (la == null) { currentState = 74; break; } + currentState = stateStack.Pop(); + break; + } + case 75: { + if (la == null) { currentState = 75; break; } + currentState = stateStack.Pop(); + break; + } + case 76: { + PushContext(Context.Expression, la, t); + goto case 77; + } + case 77: { + nextTokenIsPotentialStartOfExpression = true; + goto case 78; + } + case 78: { + if (la == null) { currentState = 78; break; } + if (set[134].Get(la.kind)) { + currentState = 77; + break; + } else { + if (set[35].Get(la.kind)) { + stateStack.Push(160); + goto case 174; + } else { + if (la.kind == 220) { + currentState = 156; + break; + } else { + if (la.kind == 162) { + stateStack.Push(79); + goto case 86; + } else { + if (la.kind == 35) { + stateStack.Push(79); + goto case 80; + } else { + Error(la); + goto case 79; + } + } + } + } + } + } + case 79: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 80: { + if (la == null) { currentState = 80; break; } + Expect(35, la); // "{" + currentState = 81; + break; + } + case 81: { + nextTokenIsPotentialStartOfExpression = true; + goto case 82; + } + case 82: { + if (la == null) { currentState = 82; break; } + if (set[23].Get(la.kind)) { + goto case 84; + } else { + goto case 83; + } + } + case 83: { + if (la == null) { currentState = 83; break; } + Expect(36, la); // "}" + currentState = stateStack.Pop(); + break; + } + case 84: { + stateStack.Push(85); + goto case 56; + } + case 85: { + if (la == null) { currentState = 85; break; } + if (la.kind == 22) { + currentState = 84; + break; + } else { + goto case 83; + } + } + case 86: { + if (la == null) { currentState = 86; break; } + Expect(162, la); // "New" + currentState = 87; + break; + } + case 87: { + PushContext(Context.ObjectCreation, la, t); + goto case 88; + } + case 88: { + if (la == null) { currentState = 88; break; } + if (set[16].Get(la.kind)) { + stateStack.Push(147); + goto case 37; + } else { + if (la.kind == 233) { + PushContext(Context.ObjectInitializer, la, t); + goto case 91; + } else { + goto case 89; + } + } + } + case 89: { + Error(la); + goto case 90; + } + case 90: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 91: { + if (la == null) { currentState = 91; break; } + Expect(233, la); // "With" + currentState = 92; + break; + } + case 92: { + stateStack.Push(93); + goto case 94; + } + case 93: { + PopContext(); + goto case 90; + } + case 94: { + if (la == null) { currentState = 94; break; } + Expect(35, la); // "{" + currentState = 95; + break; + } + case 95: { + if (la == null) { currentState = 95; break; } + if (la.kind == 26 || la.kind == 147) { + goto case 96; + } else { + goto case 83; + } + } + case 96: { + if (la == null) { currentState = 96; break; } + if (la.kind == 147) { + currentState = 97; + break; + } else { + goto case 97; + } + } + case 97: { + if (la == null) { currentState = 97; break; } + Expect(26, la); // "." + currentState = 98; + break; + } + case 98: { + stateStack.Push(99); + goto case 102; + } + case 99: { + if (la == null) { currentState = 99; break; } + Expect(20, la); // "=" + currentState = 100; + break; + } + case 100: { + stateStack.Push(101); + goto case 56; + } + case 101: { + if (la == null) { currentState = 101; break; } + if (la.kind == 22) { + currentState = 96; + break; + } else { + goto case 83; + } + } + case 102: { + if (la == null) { currentState = 102; break; } + if (la.kind == 2) { + goto case 146; + } else { + if (la.kind == 56) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 57) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 58) { + goto case 145; + } else { + if (la.kind == 59) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 60) { + goto case 67; + } else { + if (la.kind == 61) { + goto case 66; + } else { + if (la.kind == 62) { + goto case 144; + } else { + if (la.kind == 63) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 64) { + goto case 143; + } else { + if (la.kind == 65) { + goto case 142; + } else { + if (la.kind == 66) { + goto case 141; + } else { + if (la.kind == 67) { + goto case 140; + } else { + if (la.kind == 68) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 69) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 70) { + goto case 139; + } else { + if (la.kind == 71) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 72) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 73) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 74) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 75) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 76) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 77) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 78) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 79) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 80) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 81) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 82) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 83) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 84) { + goto case 138; + } else { + if (la.kind == 85) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 86) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 87) { + goto case 137; + } else { + if (la.kind == 88) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 89) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 90) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 91) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 92) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 93) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 94) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 95) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 96) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 97) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 98) { + goto case 136; + } else { + if (la.kind == 99) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 100) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 101) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 102) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 103) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 104) { + goto case 135; + } else { + if (la.kind == 105) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 106) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 107) { + goto case 134; + } else { + if (la.kind == 108) { + goto case 133; + } else { + if (la.kind == 109) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 110) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 111) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 112) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 113) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 114) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 115) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 116) { + goto case 132; + } else { + if (la.kind == 117) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 118) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 119) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 120) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 121) { + goto case 131; + } else { + if (la.kind == 122) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 123) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 124) { + goto case 130; + } else { + if (la.kind == 125) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 126) { + goto case 129; + } else { + if (la.kind == 127) { + goto case 128; + } else { + if (la.kind == 128) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 129) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 130) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 131) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 132) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 133) { + goto case 127; + } else { + if (la.kind == 134) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 135) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 136) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 137) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 138) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 139) { + goto case 126; + } else { + if (la.kind == 140) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 141) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 142) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 143) { + goto case 125; + } else { + if (la.kind == 144) { + goto case 62; + } else { + if (la.kind == 145) { + goto case 61; + } else { + if (la.kind == 146) { + goto case 124; + } else { + if (la.kind == 147) { + goto case 123; + } else { + if (la.kind == 148) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 149) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 150) { + goto case 68; + } else { + if (la.kind == 151) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 152) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 153) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 154) { + goto case 75; + } else { + if (la.kind == 155) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 156) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 157) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 158) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 159) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 160) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 161) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 162) { + goto case 122; + } else { + if (la.kind == 163) { + goto case 121; + } else { + if (la.kind == 164) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 165) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 166) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 167) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 168) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 169) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 170) { + goto case 120; + } else { + if (la.kind == 171) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 172) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 173) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 174) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 175) { + goto case 65; + } else { + if (la.kind == 176) { + goto case 119; + } else { + if (la.kind == 177) { + goto case 64; + } else { + if (la.kind == 178) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 179) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 180) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 181) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 182) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 183) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 184) { + goto case 118; + } else { + if (la.kind == 185) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 186) { + goto case 117; + } else { + if (la.kind == 187) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 188) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 189) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 190) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 191) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 192) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 193) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 194) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 195) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 196) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 197) { + goto case 116; + } else { + if (la.kind == 198) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 199) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 200) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 201) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 202) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 203) { + goto case 115; + } else { + if (la.kind == 204) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 205) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 206) { + goto case 114; + } else { + if (la.kind == 207) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 208) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 209) { + goto case 113; + } else { + if (la.kind == 210) { + goto case 112; + } else { + if (la.kind == 211) { + goto case 111; + } else { + if (la.kind == 212) { + goto case 110; + } else { + if (la.kind == 213) { + goto case 109; + } else { + if (la.kind == 214) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 215) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 216) { + goto case 60; + } else { + if (la.kind == 217) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 218) { + goto case 108; + } else { + if (la.kind == 219) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 220) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 221) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 222) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 223) { + goto case 107; + } else { + if (la.kind == 224) { + goto case 106; + } else { + if (la.kind == 225) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 226) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 227) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 228) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 229) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 230) { + goto case 105; + } else { + if (la.kind == 231) { + goto case 104; + } else { + if (la.kind == 232) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 233) { + goto case 103; + } else { + if (la.kind == 234) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 235) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 236) { + goto case 63; + } else { + if (la.kind == 237) { + currentState = stateStack.Pop(); + break; + } else { + goto case 6; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + case 103: { + if (la == null) { currentState = 103; break; } + currentState = stateStack.Pop(); + break; + } + case 104: { + if (la == null) { currentState = 104; break; } + currentState = stateStack.Pop(); + break; + } + case 105: { + if (la == null) { currentState = 105; break; } + currentState = stateStack.Pop(); + break; + } + case 106: { + if (la == null) { currentState = 106; break; } + currentState = stateStack.Pop(); + break; + } + case 107: { + if (la == null) { currentState = 107; break; } + currentState = stateStack.Pop(); + break; + } + case 108: { + if (la == null) { currentState = 108; break; } + currentState = stateStack.Pop(); + break; + } + case 109: { + if (la == null) { currentState = 109; break; } + currentState = stateStack.Pop(); + break; + } + case 110: { + if (la == null) { currentState = 110; break; } + currentState = stateStack.Pop(); + break; + } + case 111: { + if (la == null) { currentState = 111; break; } + currentState = stateStack.Pop(); + break; + } + case 112: { + if (la == null) { currentState = 112; break; } + currentState = stateStack.Pop(); + break; + } + case 113: { + if (la == null) { currentState = 113; break; } + currentState = stateStack.Pop(); + break; + } + case 114: { + if (la == null) { currentState = 114; break; } + currentState = stateStack.Pop(); + break; + } + case 115: { + if (la == null) { currentState = 115; break; } + currentState = stateStack.Pop(); + break; + } + case 116: { + if (la == null) { currentState = 116; break; } + currentState = stateStack.Pop(); + break; + } + case 117: { + if (la == null) { currentState = 117; break; } + currentState = stateStack.Pop(); + break; + } + case 118: { + if (la == null) { currentState = 118; break; } + currentState = stateStack.Pop(); + break; + } + case 119: { + if (la == null) { currentState = 119; break; } + currentState = stateStack.Pop(); + break; + } + case 120: { + if (la == null) { currentState = 120; break; } + currentState = stateStack.Pop(); + break; + } + case 121: { + if (la == null) { currentState = 121; break; } + currentState = stateStack.Pop(); + break; + } + case 122: { + if (la == null) { currentState = 122; break; } + currentState = stateStack.Pop(); + break; + } + case 123: { + if (la == null) { currentState = 123; break; } + currentState = stateStack.Pop(); + break; + } + case 124: { + if (la == null) { currentState = 124; break; } + currentState = stateStack.Pop(); + break; + } + case 125: { + if (la == null) { currentState = 125; break; } + currentState = stateStack.Pop(); + break; + } + case 126: { + if (la == null) { currentState = 126; break; } + currentState = stateStack.Pop(); + break; + } + case 127: { + if (la == null) { currentState = 127; break; } + currentState = stateStack.Pop(); + break; + } + case 128: { + if (la == null) { currentState = 128; break; } + currentState = stateStack.Pop(); + break; + } + case 129: { + if (la == null) { currentState = 129; break; } + currentState = stateStack.Pop(); + break; + } + case 130: { + if (la == null) { currentState = 130; break; } + currentState = stateStack.Pop(); + break; + } + case 131: { + if (la == null) { currentState = 131; break; } + currentState = stateStack.Pop(); + break; + } + case 132: { + if (la == null) { currentState = 132; break; } + currentState = stateStack.Pop(); + break; + } + case 133: { + if (la == null) { currentState = 133; break; } + currentState = stateStack.Pop(); + break; + } + case 134: { + if (la == null) { currentState = 134; break; } + currentState = stateStack.Pop(); + break; + } + case 135: { + if (la == null) { currentState = 135; break; } + currentState = stateStack.Pop(); + break; + } + case 136: { + if (la == null) { currentState = 136; break; } + currentState = stateStack.Pop(); + break; + } + case 137: { + if (la == null) { currentState = 137; break; } + currentState = stateStack.Pop(); + break; + } + case 138: { + if (la == null) { currentState = 138; break; } + currentState = stateStack.Pop(); + break; + } + case 139: { + if (la == null) { currentState = 139; break; } + currentState = stateStack.Pop(); + break; + } + case 140: { + if (la == null) { currentState = 140; break; } + currentState = stateStack.Pop(); + break; + } + case 141: { + if (la == null) { currentState = 141; break; } + currentState = stateStack.Pop(); + break; + } + case 142: { + if (la == null) { currentState = 142; break; } + currentState = stateStack.Pop(); + break; + } + case 143: { + if (la == null) { currentState = 143; break; } + currentState = stateStack.Pop(); + break; + } + case 144: { + if (la == null) { currentState = 144; break; } + currentState = stateStack.Pop(); + break; + } + case 145: { + if (la == null) { currentState = 145; break; } + currentState = stateStack.Pop(); + break; + } + case 146: { + if (la == null) { currentState = 146; break; } + currentState = stateStack.Pop(); + break; + } + case 147: { + if (la == null) { currentState = 147; break; } + if (la.kind == 35 || la.kind == 126 || la.kind == 233) { + if (la.kind == 126) { + PushContext(Context.CollectionInitializer, la, t); + goto case 152; + } else { + if (la.kind == 35) { + PushContext(Context.CollectionInitializer, la, t); + stateStack.Push(151); + goto case 80; + } else { + if (la.kind == 233) { + PushContext(Context.ObjectInitializer, la, t); + goto case 148; + } else { + goto case 89; + } + } + } + } else { + goto case 90; + } + } + case 148: { + if (la == null) { currentState = 148; break; } + Expect(233, la); // "With" + currentState = 149; + break; + } + case 149: { + stateStack.Push(150); + goto case 94; + } + case 150: { + PopContext(); + goto case 90; + } + case 151: { + PopContext(); + goto case 90; + } + case 152: { + if (la == null) { currentState = 152; break; } + Expect(126, la); // "From" + currentState = 153; + break; + } + case 153: { + if (la == null) { currentState = 153; break; } + if (la.kind == 35) { + stateStack.Push(154); + goto case 80; + } else { + if (set[30].Get(la.kind)) { + currentState = endOfStatementTerminatorAndBlock; /* leave this block */ + InformToken(t); /* process From again*/ + /* for processing current token (la): go to the position after processing End */ + goto switchlbl; + + } else { + Error(la); + goto case 154; + } + } + } + case 154: { + PopContext(); + goto case 90; + } + case 155: { + if (la == null) { currentState = 155; break; } + currentState = 154; + break; + } + case 156: { + stateStack.Push(157); + goto case 76; + } + case 157: { + if (la == null) { currentState = 157; break; } + Expect(144, la); // "Is" + currentState = 158; + break; + } + case 158: { + PushContext(Context.Type, la, t); + stateStack.Push(159); + goto case 37; + } + case 159: { + PopContext(); + goto case 79; + } + case 160: { + if (la == null) { currentState = 160; break; } + if (set[32].Get(la.kind)) { + stateStack.Push(160); + goto case 161; + } else { + goto case 79; + } + } + case 161: { + if (la == null) { currentState = 161; break; } + if (la.kind == 37) { + currentState = 166; + break; + } else { + if (set[135].Get(la.kind)) { + currentState = 162; + break; + } else { + goto case 6; + } + } + } + case 162: { + nextTokenIsStartOfImportsOrAccessExpression = true; + goto case 163; + } + case 163: { + if (la == null) { currentState = 163; break; } + if (la.kind == 10) { + currentState = 164; + break; + } else { + goto case 164; + } + } + case 164: { + stateStack.Push(165); + goto case 102; + } + case 165: { + if (la == null) { currentState = 165; break; } + if (la.kind == 11) { + currentState = stateStack.Pop(); + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 166: { + PushContext(Context.Expression, la, t); + nextTokenIsPotentialStartOfExpression = true; + goto case 167; + } + case 167: { + if (la == null) { currentState = 167; break; } + if (la.kind == 169) { + currentState = 169; + break; + } else { + if (set[21].Get(la.kind)) { + if (set[22].Get(la.kind)) { + stateStack.Push(168); + goto case 48; + } else { + goto case 168; + } + } else { + Error(la); + goto case 168; + } + } + } + case 168: { + PopContext(); + goto case 45; + } + case 169: { + PushContext(Context.Type, la, t); + stateStack.Push(170); + goto case 37; + } + case 170: { + PopContext(); + goto case 171; + } + case 171: { + if (la == null) { currentState = 171; break; } + if (la.kind == 22) { + currentState = 172; + break; + } else { + goto case 168; + } + } + case 172: { + PushContext(Context.Type, la, t); + stateStack.Push(173); + goto case 37; + } + case 173: { + PopContext(); + goto case 171; + } + case 174: { + PushContext(Context.Expression, la, t); + nextTokenIsPotentialStartOfExpression = true; + goto case 175; + } + case 175: { + if (la == null) { currentState = 175; break; } + if (set[136].Get(la.kind)) { + currentState = 176; + break; + } else { + if (la.kind == 37) { + currentState = 478; + break; + } else { + if (set[137].Get(la.kind)) { + currentState = 176; + break; + } else { + if (set[133].Get(la.kind)) { + currentState = 176; + break; + } else { + if (set[135].Get(la.kind)) { + currentState = 474; + break; + } else { + if (la.kind == 129) { + currentState = 471; + break; + } else { + if (la.kind == 237) { + currentState = 468; + break; + } else { + if (set[83].Get(la.kind)) { + stateStack.Push(176); + nextTokenIsPotentialStartOfExpression = true; + PushContext(Context.Xml, la, t); + goto case 451; + } else { + if (la.kind == 127 || la.kind == 210) { + stateStack.Push(176); + goto case 253; + } else { + if (la.kind == 58 || la.kind == 126) { + stateStack.Push(176); + PushContext(Context.Query, la, t); + goto case 191; + } else { + if (set[37].Get(la.kind)) { + stateStack.Push(176); + goto case 184; + } else { + if (la.kind == 135) { + stateStack.Push(176); + goto case 177; + } else { + Error(la); + goto case 176; + } + } + } + } + } + } + } + } + } + } + } + } + } + case 176: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 177: { + if (la == null) { currentState = 177; break; } + Expect(135, la); // "If" + currentState = 178; + break; + } + case 178: { + if (la == null) { currentState = 178; break; } + Expect(37, la); // "(" + currentState = 179; + break; + } + case 179: { + stateStack.Push(180); + goto case 56; + } + case 180: { + if (la == null) { currentState = 180; break; } + Expect(22, la); // "," + currentState = 181; + break; + } + case 181: { + stateStack.Push(182); + goto case 56; + } + case 182: { + if (la == null) { currentState = 182; break; } + if (la.kind == 22) { + currentState = 183; + break; + } else { + goto case 45; + } + } + case 183: { + stateStack.Push(45); + goto case 56; + } + case 184: { + if (la == null) { currentState = 184; break; } + if (set[138].Get(la.kind)) { + currentState = 190; + break; + } else { + if (la.kind == 94 || la.kind == 106 || la.kind == 219) { + currentState = 185; + break; + } else { + goto case 6; + } + } + } + case 185: { + if (la == null) { currentState = 185; break; } + Expect(37, la); // "(" + currentState = 186; + break; + } + case 186: { + stateStack.Push(187); + goto case 56; + } + case 187: { + if (la == null) { currentState = 187; break; } + Expect(22, la); // "," + currentState = 188; + break; + } + case 188: { + PushContext(Context.Type, la, t); + stateStack.Push(189); + goto case 37; + } + case 189: { + PopContext(); + goto case 45; + } + case 190: { + if (la == null) { currentState = 190; break; } + Expect(37, la); // "(" + currentState = 183; + break; + } + case 191: { + if (la == null) { currentState = 191; break; } + if (la.kind == 126) { + stateStack.Push(192); + goto case 252; + } else { + if (la.kind == 58) { + stateStack.Push(192); + goto case 251; + } else { + Error(la); + goto case 192; + } + } + } + case 192: { + if (la == null) { currentState = 192; break; } + if (set[38].Get(la.kind)) { + stateStack.Push(192); + goto case 193; + } else { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 193: { + if (la == null) { currentState = 193; break; } + if (la.kind == 126) { + currentState = 249; + break; + } else { + if (la.kind == 58) { + currentState = 245; + break; + } else { + if (la.kind == 197) { + currentState = 243; + break; + } else { + if (la.kind == 107) { + goto case 134; + } else { + if (la.kind == 230) { + currentState = 56; + break; + } else { + if (la.kind == 176) { + currentState = 239; + break; + } else { + if (la.kind == 203 || la.kind == 212) { + currentState = 237; + break; + } else { + if (la.kind == 148) { + currentState = 235; + break; + } else { + if (la.kind == 133) { + currentState = 207; + break; + } else { + if (la.kind == 146) { + currentState = 194; + break; + } else { + goto case 6; + } + } + } + } + } + } + } + } + } + } + } + case 194: { + stateStack.Push(195); + goto case 200; + } + case 195: { + if (la == null) { currentState = 195; break; } + Expect(171, la); // "On" + currentState = 196; + break; + } + case 196: { + stateStack.Push(197); + goto case 56; + } + case 197: { + if (la == null) { currentState = 197; break; } + Expect(116, la); // "Equals" + currentState = 198; + break; + } + case 198: { + stateStack.Push(199); + goto case 56; + } + case 199: { + if (la == null) { currentState = 199; break; } + if (la.kind == 22) { + currentState = 196; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 200: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(201); + goto case 206; + } + case 201: { + PopContext(); + goto case 202; + } + case 202: { + if (la == null) { currentState = 202; break; } + if (la.kind == 63) { + currentState = 204; + break; + } else { + goto case 203; + } + } + case 203: { + if (la == null) { currentState = 203; break; } + Expect(138, la); // "In" + currentState = 56; + break; + } + case 204: { + PushContext(Context.Type, la, t); + stateStack.Push(205); + goto case 37; + } + case 205: { + PopContext(); + goto case 203; + } + case 206: { + if (la == null) { currentState = 206; break; } + if (set[123].Get(la.kind)) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 98) { + goto case 136; + } else { + goto case 6; + } + } + } + case 207: { + SetIdentifierExpected(la); + nextTokenIsPotentialStartOfExpression = true; + goto case 208; + } + case 208: { + if (la == null) { currentState = 208; break; } + if (la.kind == 146) { + goto case 227; + } else { + if (set[40].Get(la.kind)) { + if (la.kind == 70) { + currentState = 210; + break; + } else { + if (set[40].Get(la.kind)) { + goto case 225; + } else { + Error(la); + goto case 209; + } + } + } else { + goto case 6; + } + } + } + case 209: { + if (la == null) { currentState = 209; break; } + Expect(70, la); // "By" + currentState = 210; + break; + } + case 210: { + stateStack.Push(211); + goto case 214; + } + case 211: { + if (la == null) { currentState = 211; break; } + if (la.kind == 22) { + currentState = 210; + break; + } else { + Expect(143, la); // "Into" + currentState = 212; + break; + } + } + case 212: { + stateStack.Push(213); + goto case 214; + } + case 213: { + if (la == null) { currentState = 213; break; } + if (la.kind == 22) { + currentState = 212; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 214: { + SetIdentifierExpected(la); + nextTokenIsPotentialStartOfExpression = true; + goto case 215; + } + case 215: { + if (la == null) { currentState = 215; break; } + if (set[6].Get(la.kind)) { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(218); + goto case 206; + } else { + goto case 216; + } + } + case 216: { + stateStack.Push(217); + goto case 56; + } + case 217: { + if (!isAlreadyInExpr) PopContext(); isAlreadyInExpr = false; + currentState = stateStack.Pop(); + goto switchlbl; + } + case 218: { + nextTokenIsPotentialStartOfExpression = true; + goto case 219; + } + case 219: { + if (la == null) { currentState = 219; break; } + if (set[42].Get(la.kind)) { + PopContext(); isAlreadyInExpr = true; + goto case 220; + } else { + goto case 216; + } + } + case 220: { + if (la == null) { currentState = 220; break; } + if (la.kind == 63) { + currentState = 222; + break; + } else { + if (la.kind == 20) { + currentState = 216; + break; + } else { + if (set[43].Get(la.kind)) { + currentState = endOfStatementTerminatorAndBlock; /* leave this block */ + InformToken(t); /* process Identifier again*/ + /* for processing current token (la): go to the position after processing End */ + goto switchlbl; + + } else { + Error(la); + goto case 216; + } + } + } + } + case 221: { + if (la == null) { currentState = 221; break; } + currentState = 216; + break; + } + case 222: { + PushContext(Context.Type, la, t); + stateStack.Push(223); + goto case 37; + } + case 223: { + PopContext(); + goto case 224; + } + case 224: { + if (la == null) { currentState = 224; break; } + Expect(20, la); // "=" + currentState = 216; + break; + } + case 225: { + stateStack.Push(226); + goto case 214; + } + case 226: { + if (la == null) { currentState = 226; break; } + if (la.kind == 22) { + currentState = 225; + break; + } else { + goto case 209; + } + } + case 227: { + stateStack.Push(228); + goto case 234; + } + case 228: { + if (la == null) { currentState = 228; break; } + if (la.kind == 133 || la.kind == 146) { + if (la.kind == 133) { + currentState = 232; + break; + } else { + if (la.kind == 146) { + goto case 227; + } else { + Error(la); + goto case 228; + } + } + } else { + goto case 229; + } + } + case 229: { + if (la == null) { currentState = 229; break; } + Expect(143, la); // "Into" + currentState = 230; + break; + } + case 230: { + stateStack.Push(231); + goto case 214; + } + case 231: { + if (la == null) { currentState = 231; break; } + if (la.kind == 22) { + currentState = 230; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 232: { + stateStack.Push(233); + goto case 234; + } + case 233: { + stateStack.Push(228); + goto case 229; + } + case 234: { + if (la == null) { currentState = 234; break; } + Expect(146, la); // "Join" + currentState = 194; + break; + } + case 235: { + stateStack.Push(236); + goto case 214; + } + case 236: { + if (la == null) { currentState = 236; break; } + if (la.kind == 22) { + currentState = 235; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 237: { + nextTokenIsPotentialStartOfExpression = true; + goto case 238; + } + case 238: { + if (la == null) { currentState = 238; break; } + if (la.kind == 231) { + currentState = 56; + break; + } else { + goto case 56; + } + } + case 239: { + if (la == null) { currentState = 239; break; } + Expect(70, la); // "By" + currentState = 240; + break; + } + case 240: { + stateStack.Push(241); + goto case 56; + } + case 241: { + if (la == null) { currentState = 241; break; } + if (la.kind == 64) { + currentState = 242; + break; + } else { + if (la.kind == 104) { + currentState = 242; + break; + } else { + Error(la); + goto case 242; + } + } + } + case 242: { + if (la == null) { currentState = 242; break; } + if (la.kind == 22) { + currentState = 240; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 243: { + stateStack.Push(244); + goto case 214; + } + case 244: { + if (la == null) { currentState = 244; break; } + if (la.kind == 22) { + currentState = 243; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 245: { + stateStack.Push(246); + goto case 200; + } + case 246: { + if (la == null) { currentState = 246; break; } + if (set[38].Get(la.kind)) { + stateStack.Push(246); + goto case 193; + } else { + Expect(143, la); // "Into" + currentState = 247; + break; + } + } + case 247: { + stateStack.Push(248); + goto case 214; + } + case 248: { + if (la == null) { currentState = 248; break; } + if (la.kind == 22) { + currentState = 247; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 249: { + stateStack.Push(250); + goto case 200; + } + case 250: { + if (la == null) { currentState = 250; break; } + if (la.kind == 22) { + currentState = 249; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 251: { + if (la == null) { currentState = 251; break; } + Expect(58, la); // "Aggregate" + currentState = 245; + break; + } + case 252: { + if (la == null) { currentState = 252; break; } + Expect(126, la); // "From" + currentState = 249; + break; + } + case 253: { + if (la == null) { currentState = 253; break; } + if (la.kind == 210) { + currentState = 443; + break; + } else { + if (la.kind == 127) { + currentState = 254; + break; + } else { + goto case 6; + } + } + } + case 254: { + if (la == null) { currentState = 254; break; } + Expect(37, la); // "(" + currentState = 255; + break; + } + case 255: { + SetIdentifierExpected(la); + goto case 256; + } + case 256: { + if (la == null) { currentState = 256; break; } + if (set[78].Get(la.kind)) { + stateStack.Push(257); + goto case 422; + } else { + goto case 257; + } + } + case 257: { + if (la == null) { currentState = 257; break; } + Expect(38, la); // ")" + currentState = 258; + break; + } + case 258: { + nextTokenIsPotentialStartOfExpression = true; + goto case 259; + } + case 259: { + if (la == null) { currentState = 259; break; } + if (set[23].Get(la.kind)) { + goto case 56; + } else { + if (la.kind == 1 || la.kind == 21 || la.kind == 63) { + if (la.kind == 63) { + currentState = 420; + break; + } else { + goto case 260; + } + } else { + goto case 6; + } + } + } + case 260: { + stateStack.Push(261); + goto case 263; + } + case 261: { + if (la == null) { currentState = 261; break; } + Expect(113, la); // "End" + currentState = 262; + break; + } + case 262: { + if (la == null) { currentState = 262; break; } + Expect(127, la); // "Function" + currentState = stateStack.Pop(); + break; + } + case 263: { + PushContext(Context.Body, la, t); + goto case 264; + } + case 264: { + stateStack.Push(265); + goto case 23; + } + case 265: { + nextTokenIsPotentialStartOfExpression = true; + goto case 266; + } + case 266: { + if (la == null) { currentState = 266; break; } + if (set[139].Get(la.kind)) { + if (set[70].Get(la.kind)) { + if (set[51].Get(la.kind)) { + stateStack.Push(264); + goto case 271; + } else { + goto case 264; + } + } else { + if (la.kind == 113) { + currentState = 269; + break; + } else { + goto case 268; + } + } + } else { + goto case 267; + } + } + case 267: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 268: { + Error(la); + goto case 265; + } + case 269: { + if (la == null) { currentState = 269; break; } + if (la.kind == 1 || la.kind == 21) { + goto case 264; + } else { + if (set[50].Get(la.kind)) { + currentState = endOfStatementTerminatorAndBlock; /* leave this block */ + InformToken(t); /* process End again*/ + /* for processing current token (la): go to the position after processing End */ + goto switchlbl; + + } else { + goto case 268; + } + } + } + case 270: { + if (la == null) { currentState = 270; break; } + currentState = 265; + break; + } + case 271: { + nextTokenIsPotentialStartOfExpression = true; + goto case 272; + } + case 272: { + if (la == null) { currentState = 272; break; } + if (la.kind == 88 || la.kind == 105 || la.kind == 204) { + currentState = 400; + break; + } else { + if (la.kind == 211 || la.kind == 233) { + currentState = 396; + break; + } else { + if (la.kind == 56 || la.kind == 193) { + currentState = 394; + break; + } else { + if (la.kind == 189) { + currentState = 392; + break; + } else { + if (la.kind == 135) { + currentState = 374; + break; + } else { + if (la.kind == 197) { + currentState = 358; + break; + } else { + if (la.kind == 231) { + currentState = 354; + break; + } else { + if (la.kind == 108) { + currentState = 348; + break; + } else { + if (la.kind == 124) { + currentState = 321; + break; + } else { + if (la.kind == 118 || la.kind == 171 || la.kind == 194) { + if (la.kind == 118 || la.kind == 171) { + if (la.kind == 171) { + currentState = 317; + break; + } else { + goto case 317; + } + } else { + if (la.kind == 194) { + currentState = 315; + break; + } else { + goto case 6; + } + } + } else { + if (la.kind == 215) { + currentState = 313; + break; + } else { + if (la.kind == 218) { + currentState = 300; + break; + } else { + if (set[140].Get(la.kind)) { + if (la.kind == 132) { + currentState = 297; + break; + } else { + if (la.kind == 120) { + currentState = 296; + break; + } else { + if (la.kind == 89) { + currentState = 295; + break; + } else { + if (la.kind == 206) { + goto case 114; + } else { + if (la.kind == 195) { + currentState = 292; + break; + } else { + goto case 6; + } + } + } + } + } + } else { + if (la.kind == 191) { + currentState = 290; + break; + } else { + if (la.kind == 117) { + currentState = 288; + break; + } else { + if (la.kind == 226) { + currentState = 273; + break; + } else { + if (set[141].Get(la.kind)) { + if (la.kind == 73) { + currentState = 56; + break; + } else { + goto case 56; + } + } else { + goto case 6; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + case 273: { + stateStack.Push(274); + SetIdentifierExpected(la); + nextTokenIsPotentialStartOfExpression = true; + goto case 277; + } + case 274: { + if (la == null) { currentState = 274; break; } + if (la.kind == 22) { + currentState = 273; + break; + } else { + stateStack.Push(275); + goto case 263; + } + } + case 275: { + if (la == null) { currentState = 275; break; } + Expect(113, la); // "End" + currentState = 276; + break; + } + case 276: { + if (la == null) { currentState = 276; break; } + Expect(226, la); // "Using" + currentState = stateStack.Pop(); + break; + } + case 277: { + if (la == null) { currentState = 277; break; } + if (set[6].Get(la.kind)) { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(280); + goto case 206; + } else { + goto case 278; + } + } + case 278: { + stateStack.Push(279); + goto case 56; + } + case 279: { + if (!isAlreadyInExpr) PopContext(); isAlreadyInExpr = false; + currentState = stateStack.Pop(); + goto switchlbl; + } + case 280: { + nextTokenIsPotentialStartOfExpression = true; + goto case 281; + } + case 281: { + if (la == null) { currentState = 281; break; } + if (set[42].Get(la.kind)) { + PopContext(); isAlreadyInExpr = true; + goto case 282; + } else { + goto case 278; + } + } + case 282: { + if (la == null) { currentState = 282; break; } + if (la.kind == 63) { + currentState = 284; + break; + } else { + if (la.kind == 20) { + currentState = 278; + break; + } else { + if (set[43].Get(la.kind)) { + currentState = endOfStatementTerminatorAndBlock; /* leave this block */ + InformToken(t); /* process Identifier again*/ + /* for processing current token (la): go to the position after processing End */ + goto switchlbl; + + } else { + Error(la); + goto case 278; + } + } + } + } + case 283: { + if (la == null) { currentState = 283; break; } + currentState = 278; + break; + } + case 284: { + nextTokenIsPotentialStartOfExpression = true; + goto case 285; + } + case 285: { + if (la == null) { currentState = 285; break; } + if (set[16].Get(la.kind)) { + PushContext(Context.Type, la, t); + stateStack.Push(286); + goto case 37; + } else { + goto case 278; + } + } + case 286: { + PopContext(); + goto case 287; + } + case 287: { + if (la == null) { currentState = 287; break; } + Expect(20, la); // "=" + currentState = 278; + break; + } + case 288: { + stateStack.Push(289); + goto case 56; + } + case 289: { + if (la == null) { currentState = 289; break; } + if (la.kind == 22) { + currentState = 288; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 290: { + nextTokenIsPotentialStartOfExpression = true; + goto case 291; + } + case 291: { + if (la == null) { currentState = 291; break; } + if (la.kind == 184) { + currentState = 56; + break; + } else { + goto case 56; + } + } + case 292: { + PushContext(Context.Expression, la, t); + nextTokenIsPotentialStartOfExpression = true; + goto case 293; + } + case 293: { + if (la == null) { currentState = 293; break; } + if (set[23].Get(la.kind)) { + stateStack.Push(294); + goto case 56; + } else { + goto case 294; + } + } + case 294: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 295: { + if (la == null) { currentState = 295; break; } + if (la.kind == 108) { + goto case 133; + } else { + if (la.kind == 124) { + goto case 130; + } else { + if (la.kind == 231) { + goto case 104; + } else { + goto case 6; + } + } + } + } + case 296: { + if (la == null) { currentState = 296; break; } + if (la.kind == 108) { + goto case 133; + } else { + if (la.kind == 124) { + goto case 130; + } else { + if (la.kind == 231) { + goto case 104; + } else { + if (la.kind == 197) { + goto case 116; + } else { + if (la.kind == 210) { + goto case 112; + } else { + if (la.kind == 127) { + goto case 128; + } else { + if (la.kind == 186) { + goto case 117; + } else { + if (la.kind == 218) { + goto case 108; + } else { + goto case 6; + } + } + } + } + } + } + } + } + } + case 297: { + if (la == null) { currentState = 297; break; } + if (set[6].Get(la.kind)) { + goto case 299; + } else { + if (la.kind == 5) { + goto case 298; + } else { + goto case 6; + } + } + } + case 298: { + if (la == null) { currentState = 298; break; } + currentState = stateStack.Pop(); + break; + } + case 299: { + if (la == null) { currentState = 299; break; } + currentState = stateStack.Pop(); + break; + } + case 300: { + stateStack.Push(301); + goto case 263; + } + case 301: { + if (la == null) { currentState = 301; break; } + if (la.kind == 75) { + currentState = 305; + break; + } else { + if (la.kind == 123) { + currentState = 304; + break; + } else { + goto case 302; + } + } + } + case 302: { + if (la == null) { currentState = 302; break; } + Expect(113, la); // "End" + currentState = 303; + break; + } + case 303: { + if (la == null) { currentState = 303; break; } + Expect(218, la); // "Try" + currentState = stateStack.Pop(); + break; + } + case 304: { + stateStack.Push(302); + goto case 263; + } + case 305: { + SetIdentifierExpected(la); + goto case 306; + } + case 306: { + if (la == null) { currentState = 306; break; } + if (set[6].Get(la.kind)) { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(309); + goto case 206; + } else { + goto case 307; + } + } + case 307: { + if (la == null) { currentState = 307; break; } + if (la.kind == 229) { + currentState = 308; + break; + } else { + goto case 300; + } + } + case 308: { + stateStack.Push(300); + goto case 56; + } + case 309: { + PopContext(); + goto case 310; + } + case 310: { + if (la == null) { currentState = 310; break; } + if (la.kind == 63) { + currentState = 311; + break; + } else { + goto case 307; + } + } + case 311: { + PushContext(Context.Type, la, t); + stateStack.Push(312); + goto case 37; + } + case 312: { + PopContext(); + goto case 307; + } + case 313: { + nextTokenIsPotentialStartOfExpression = true; + goto case 314; + } + case 314: { + if (la == null) { currentState = 314; break; } + if (set[23].Get(la.kind)) { + goto case 56; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 315: { + if (la == null) { currentState = 315; break; } + if (la.kind == 163) { + goto case 121; + } else { + goto case 316; + } + } + case 316: { + if (la == null) { currentState = 316; break; } + if (la.kind == 5) { + goto case 298; + } else { + if (set[6].Get(la.kind)) { + goto case 299; + } else { + goto case 6; + } + } + } + case 317: { + if (la == null) { currentState = 317; break; } + Expect(118, la); // "Error" + currentState = 318; + break; + } + case 318: { + nextTokenIsPotentialStartOfExpression = true; + goto case 319; + } + case 319: { + if (la == null) { currentState = 319; break; } + if (set[23].Get(la.kind)) { + goto case 56; + } else { + if (la.kind == 132) { + currentState = 316; + break; + } else { + if (la.kind == 194) { + currentState = 320; + break; + } else { + goto case 6; + } + } + } + } + case 320: { + if (la == null) { currentState = 320; break; } + Expect(163, la); // "Next" + currentState = stateStack.Pop(); + break; + } + case 321: { + nextTokenIsPotentialStartOfExpression = true; + SetIdentifierExpected(la); + goto case 322; + } + case 322: { + if (la == null) { currentState = 322; break; } + if (set[35].Get(la.kind)) { + stateStack.Push(338); + goto case 332; + } else { + if (la.kind == 110) { + currentState = 323; + break; + } else { + goto case 6; + } + } + } + case 323: { + stateStack.Push(324); + goto case 332; + } + case 324: { + if (la == null) { currentState = 324; break; } + Expect(138, la); // "In" + currentState = 325; + break; + } + case 325: { + stateStack.Push(326); + goto case 56; + } + case 326: { + stateStack.Push(327); + goto case 263; + } + case 327: { + if (la == null) { currentState = 327; break; } + Expect(163, la); // "Next" + currentState = 328; + break; + } + case 328: { + nextTokenIsPotentialStartOfExpression = true; + goto case 329; + } + case 329: { + if (la == null) { currentState = 329; break; } + if (set[23].Get(la.kind)) { + goto case 330; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 330: { + stateStack.Push(331); + goto case 56; + } + case 331: { + if (la == null) { currentState = 331; break; } + if (la.kind == 22) { + currentState = 330; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 332: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(333); + goto case 174; + } + case 333: { + PopContext(); + goto case 334; + } + case 334: { + if (la == null) { currentState = 334; break; } + if (la.kind == 33) { + currentState = 335; + break; + } else { + goto case 335; + } + } + case 335: { + if (la == null) { currentState = 335; break; } + if (set[32].Get(la.kind)) { + stateStack.Push(335); + goto case 161; + } else { + if (la.kind == 63) { + currentState = 336; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + } + case 336: { + PushContext(Context.Type, la, t); + stateStack.Push(337); + goto case 37; + } + case 337: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 338: { + if (la == null) { currentState = 338; break; } + Expect(20, la); // "=" + currentState = 339; + break; + } + case 339: { + stateStack.Push(340); + goto case 56; + } + case 340: { + if (la == null) { currentState = 340; break; } + if (la.kind == 205) { + currentState = 347; + break; + } else { + goto case 341; + } + } + case 341: { + stateStack.Push(342); + goto case 263; + } + case 342: { + if (la == null) { currentState = 342; break; } + Expect(163, la); // "Next" + currentState = 343; + break; + } + case 343: { + nextTokenIsPotentialStartOfExpression = true; + goto case 344; + } + case 344: { + if (la == null) { currentState = 344; break; } + if (set[23].Get(la.kind)) { + goto case 345; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 345: { + stateStack.Push(346); + goto case 56; + } + case 346: { + if (la == null) { currentState = 346; break; } + if (la.kind == 22) { + currentState = 345; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 347: { + stateStack.Push(341); + goto case 56; + } + case 348: { + if (la == null) { currentState = 348; break; } + if (la.kind == 224 || la.kind == 231) { + currentState = 351; + break; + } else { + if (la.kind == 1 || la.kind == 21) { + stateStack.Push(349); + goto case 263; + } else { + goto case 6; + } + } + } + case 349: { + if (la == null) { currentState = 349; break; } + Expect(152, la); // "Loop" + currentState = 350; + break; + } + case 350: { + if (la == null) { currentState = 350; break; } + if (la.kind == 224 || la.kind == 231) { + currentState = 56; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 351: { + stateStack.Push(352); + goto case 56; + } + case 352: { + stateStack.Push(353); + goto case 263; + } + case 353: { + if (la == null) { currentState = 353; break; } + Expect(152, la); // "Loop" + currentState = stateStack.Pop(); + break; + } + case 354: { + stateStack.Push(355); + goto case 56; + } + case 355: { + stateStack.Push(356); + goto case 263; + } + case 356: { + if (la == null) { currentState = 356; break; } + Expect(113, la); // "End" + currentState = 357; + break; + } + case 357: { + if (la == null) { currentState = 357; break; } + Expect(231, la); // "While" + currentState = stateStack.Pop(); + break; + } + case 358: { + nextTokenIsPotentialStartOfExpression = true; + goto case 359; + } + case 359: { + if (la == null) { currentState = 359; break; } + if (la.kind == 74) { + currentState = 360; + break; + } else { + goto case 360; + } + } + case 360: { + stateStack.Push(361); + goto case 56; + } + case 361: { + stateStack.Push(362); + goto case 23; + } + case 362: { + if (la == null) { currentState = 362; break; } + if (la.kind == 74) { + currentState = 364; + break; + } else { + Expect(113, la); // "End" + currentState = 363; + break; + } + } + case 363: { + if (la == null) { currentState = 363; break; } + Expect(197, la); // "Select" + currentState = stateStack.Pop(); + break; + } + case 364: { + nextTokenIsPotentialStartOfExpression = true; + goto case 365; + } + case 365: { + if (la == null) { currentState = 365; break; } + if (la.kind == 111) { + currentState = 366; + break; + } else { + if (set[68].Get(la.kind)) { + goto case 367; + } else { + Error(la); + goto case 366; + } + } + } + case 366: { + stateStack.Push(362); + goto case 263; + } + case 367: { + nextTokenIsPotentialStartOfExpression = true; + goto case 368; + } + case 368: { + if (la == null) { currentState = 368; break; } + if (set[142].Get(la.kind)) { + if (la.kind == 144) { + currentState = 370; + break; + } else { + goto case 370; + } + } else { + if (set[23].Get(la.kind)) { + stateStack.Push(369); + goto case 56; + } else { + Error(la); + goto case 369; + } + } + } + case 369: { + if (la == null) { currentState = 369; break; } + if (la.kind == 22) { + currentState = 367; + break; + } else { + goto case 366; + } + } + case 370: { + stateStack.Push(371); + goto case 372; + } + case 371: { + stateStack.Push(369); + goto case 76; + } + case 372: { + if (la == null) { currentState = 372; break; } + if (la.kind == 20) { + goto case 74; + } else { + if (la.kind == 41) { + goto case 73; + } else { + if (la.kind == 40) { + goto case 72; + } else { + if (la.kind == 39) { + currentState = 373; + break; + } else { + if (la.kind == 42) { + goto case 69; + } else { + if (la.kind == 43) { + goto case 70; + } else { + goto case 6; + } + } + } + } + } + } + } + case 373: { + wasNormalAttribute = false; + currentState = stateStack.Pop(); + goto switchlbl; + } + case 374: { + stateStack.Push(375); + goto case 56; + } + case 375: { + if (la == null) { currentState = 375; break; } + if (la.kind == 214) { + currentState = 383; + break; + } else { + goto case 376; + } + } + case 376: { + if (la == null) { currentState = 376; break; } + if (la.kind == 1 || la.kind == 21) { + goto case 377; + } else { + goto case 6; + } + } + case 377: { + stateStack.Push(378); + goto case 263; + } + case 378: { + if (la == null) { currentState = 378; break; } + if (la.kind == 111 || la.kind == 112) { + if (la.kind == 111) { + currentState = 382; + break; + } else { + if (la.kind == 112) { + currentState = 380; + break; + } else { + Error(la); + goto case 377; + } + } + } else { + Expect(113, la); // "End" + currentState = 379; + break; + } + } + case 379: { + if (la == null) { currentState = 379; break; } + Expect(135, la); // "If" + currentState = stateStack.Pop(); + break; + } + case 380: { + stateStack.Push(381); + goto case 56; + } + case 381: { + if (la == null) { currentState = 381; break; } + if (la.kind == 214) { + currentState = 377; + break; + } else { + goto case 377; + } + } + case 382: { + if (la == null) { currentState = 382; break; } + if (la.kind == 135) { + currentState = 380; + break; + } else { + goto case 377; + } + } + case 383: { + nextTokenIsPotentialStartOfExpression = true; + goto case 384; + } + case 384: { + if (la == null) { currentState = 384; break; } + if (set[51].Get(la.kind)) { + goto case 385; + } else { + goto case 376; + } + } + case 385: { + stateStack.Push(386); + goto case 271; + } + case 386: { + if (la == null) { currentState = 386; break; } + if (la.kind == 21) { + currentState = 390; + break; + } else { + if (la.kind == 111) { + currentState = 387; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + } + case 387: { + nextTokenIsPotentialStartOfExpression = true; + goto case 388; + } + case 388: { + if (la == null) { currentState = 388; break; } + if (set[51].Get(la.kind)) { + stateStack.Push(389); + goto case 271; + } else { + goto case 389; + } + } + case 389: { + if (la == null) { currentState = 389; break; } + if (la.kind == 21) { + currentState = 387; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 390: { + nextTokenIsPotentialStartOfExpression = true; + goto case 391; + } + case 391: { + if (la == null) { currentState = 391; break; } + if (set[51].Get(la.kind)) { + goto case 385; + } else { + goto case 386; + } + } + case 392: { + stateStack.Push(393); + goto case 102; + } + case 393: { + if (la == null) { currentState = 393; break; } + if (la.kind == 37) { + currentState = 46; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 394: { + stateStack.Push(395); + goto case 56; + } + case 395: { + if (la == null) { currentState = 395; break; } + Expect(22, la); // "," + currentState = 56; + break; + } + case 396: { + stateStack.Push(397); + goto case 56; + } + case 397: { + stateStack.Push(398); + goto case 263; + } + case 398: { + if (la == null) { currentState = 398; break; } + Expect(113, la); // "End" + currentState = 399; + break; + } + case 399: { + if (la == null) { currentState = 399; break; } + if (la.kind == 233) { + goto case 103; + } else { + if (la.kind == 211) { + goto case 111; + } else { + goto case 6; + } + } + } + case 400: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(401); + goto case 206; + } + case 401: { + PopContext(); + goto case 402; + } + case 402: { + if (la == null) { currentState = 402; break; } + if (la.kind == 33) { + currentState = 403; + break; + } else { + goto case 403; + } + } + case 403: { + if (la == null) { currentState = 403; break; } + if (la.kind == 37) { + currentState = 417; + break; + } else { + goto case 404; + } + } + case 404: { + if (la == null) { currentState = 404; break; } + if (la.kind == 22) { + currentState = 410; + break; + } else { + if (la.kind == 63) { + currentState = 407; + break; + } else { + goto case 405; + } + } + } + case 405: { + if (la == null) { currentState = 405; break; } + if (la.kind == 20) { + goto case 406; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 406: { + if (la == null) { currentState = 406; break; } + currentState = 56; + break; + } + case 407: { + PushContext(Context.Type, la, t); + goto case 408; + } + case 408: { + if (la == null) { currentState = 408; break; } + if (la.kind == 162) { + stateStack.Push(409); + goto case 86; + } else { + if (set[16].Get(la.kind)) { + stateStack.Push(409); + goto case 37; + } else { + Error(la); + goto case 409; + } + } + } + case 409: { + PopContext(); + goto case 405; + } + case 410: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(411); + goto case 206; + } + case 411: { + PopContext(); + goto case 412; + } + case 412: { + if (la == null) { currentState = 412; break; } + if (la.kind == 33) { + currentState = 413; + break; + } else { + goto case 413; + } + } + case 413: { + if (la == null) { currentState = 413; break; } + if (la.kind == 37) { + currentState = 414; + break; + } else { + goto case 404; + } + } + case 414: { + nextTokenIsPotentialStartOfExpression = true; + goto case 415; + } + case 415: { + if (la == null) { currentState = 415; break; } + if (set[23].Get(la.kind)) { + stateStack.Push(416); + goto case 56; + } else { + goto case 416; + } + } + case 416: { + if (la == null) { currentState = 416; break; } + if (la.kind == 22) { + currentState = 414; + break; + } else { + Expect(38, la); // ")" + currentState = 413; + break; + } + } + case 417: { + nextTokenIsPotentialStartOfExpression = true; + goto case 418; + } + case 418: { + if (la == null) { currentState = 418; break; } + if (set[23].Get(la.kind)) { + stateStack.Push(419); + goto case 56; + } else { + goto case 419; + } + } + case 419: { + if (la == null) { currentState = 419; break; } + if (la.kind == 22) { + currentState = 417; + break; + } else { + Expect(38, la); // ")" + currentState = 403; + break; + } + } + case 420: { + PushContext(Context.Type, la, t); + stateStack.Push(421); + goto case 37; + } + case 421: { + PopContext(); + goto case 260; + } + case 422: { + stateStack.Push(423); + PushContext(Context.Parameter, la, t); + goto case 424; + } + case 423: { + if (la == null) { currentState = 423; break; } + if (la.kind == 22) { + currentState = 422; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 424: { + SetIdentifierExpected(la); + goto case 425; + } + case 425: { + if (la == null) { currentState = 425; break; } + if (la.kind == 40) { + stateStack.Push(424); + goto case 435; + } else { + goto case 426; + } + } + case 426: { + SetIdentifierExpected(la); + goto case 427; + } + case 427: { + if (la == null) { currentState = 427; break; } + if (set[143].Get(la.kind)) { + currentState = 426; + break; + } else { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(428); + goto case 206; + } + } + case 428: { + PopContext(); + goto case 429; + } + case 429: { + if (la == null) { currentState = 429; break; } + if (la.kind == 63) { + currentState = 433; + break; + } else { + goto case 430; + } + } + case 430: { + if (la == null) { currentState = 430; break; } + if (la.kind == 20) { + currentState = 432; + break; + } else { + goto case 431; + } + } + case 431: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 432: { + stateStack.Push(431); + goto case 56; + } + case 433: { + PushContext(Context.Type, la, t); + stateStack.Push(434); + goto case 37; + } + case 434: { + PopContext(); + goto case 430; + } + case 435: { + if (la == null) { currentState = 435; break; } + Expect(40, la); // "<" + currentState = 436; + break; + } + case 436: { + wasNormalAttribute = true; PushContext(Context.Attribute, la, t); + goto case 437; + } + case 437: { + if (la == null) { currentState = 437; break; } + if (la.kind == 65 || la.kind == 155) { + currentState = 441; + break; + } else { + goto case 438; + } + } + case 438: { + if (la == null) { currentState = 438; break; } + if (set[144].Get(la.kind)) { + currentState = 438; + break; + } else { + Expect(39, la); // ">" + currentState = 439; + break; + } + } + case 439: { + PopContext(); + goto case 440; + } + case 440: { + if (la == null) { currentState = 440; break; } + if (la.kind == 1) { + goto case 25; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 441: { + if (la == null) { currentState = 441; break; } + Expect(21, la); // ":" + currentState = 442; + break; + } + case 442: { + wasNormalAttribute = false; + goto case 438; + } + case 443: { + if (la == null) { currentState = 443; break; } + Expect(37, la); // "(" + currentState = 444; + break; + } + case 444: { + SetIdentifierExpected(la); + goto case 445; + } + case 445: { + if (la == null) { currentState = 445; break; } + if (set[78].Get(la.kind)) { + stateStack.Push(446); + goto case 422; + } else { + goto case 446; + } + } + case 446: { + if (la == null) { currentState = 446; break; } + Expect(38, la); // ")" + currentState = 447; + break; + } + case 447: { + nextTokenIsPotentialStartOfExpression = true; + goto case 448; + } + case 448: { + if (la == null) { currentState = 448; break; } + if (set[51].Get(la.kind)) { + goto case 271; + } else { + if (la.kind == 1 || la.kind == 21) { + stateStack.Push(449); + goto case 263; + } else { + goto case 6; + } + } + } + case 449: { + if (la == null) { currentState = 449; break; } + Expect(113, la); // "End" + currentState = 450; + break; + } + case 450: { + if (la == null) { currentState = 450; break; } + Expect(210, la); // "Sub" + currentState = stateStack.Pop(); + break; + } + case 451: { + if (la == null) { currentState = 451; break; } + if (la.kind == 17 || la.kind == 18 || la.kind == 19) { + currentState = 464; + break; + } else { + if (la.kind == 10) { + stateStack.Push(453); + goto case 455; + } else { + Error(la); + goto case 452; + } + } + } + case 452: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 453: { + if (la == null) { currentState = 453; break; } + if (la.kind == 17) { + currentState = 454; + break; + } else { + goto case 452; + } + } + case 454: { + if (la == null) { currentState = 454; break; } + if (la.kind == 16) { + currentState = 453; + break; + } else { + goto case 453; + } + } + case 455: { + PushContext(Context.Xml, la, t); + goto case 456; + } + case 456: { + if (la == null) { currentState = 456; break; } + Expect(10, la); // XmlOpenTag + currentState = 457; + break; + } + case 457: { + if (la == null) { currentState = 457; break; } + if (set[145].Get(la.kind)) { + if (set[146].Get(la.kind)) { + currentState = 457; + break; + } else { + if (la.kind == 12) { + stateStack.Push(457); + goto case 461; + } else { + Error(la); + goto case 457; + } + } + } else { + if (la.kind == 14) { + currentState = 458; + break; + } else { + if (la.kind == 11) { + currentState = 459; + break; + } else { + Error(la); + goto case 458; + } + } + } + } + case 458: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 459: { + if (la == null) { currentState = 459; break; } + if (set[147].Get(la.kind)) { + if (set[148].Get(la.kind)) { + currentState = 459; + break; + } else { + if (la.kind == 12) { + stateStack.Push(459); + goto case 461; + } else { + if (la.kind == 10) { + stateStack.Push(459); + goto case 455; + } else { + Error(la); + goto case 459; + } + } + } + } else { + Expect(15, la); // XmlOpenEndTag + currentState = 460; + break; + } + } + case 460: { + if (la == null) { currentState = 460; break; } + if (set[149].Get(la.kind)) { + if (set[150].Get(la.kind)) { + currentState = 460; + break; + } else { + if (la.kind == 12) { + stateStack.Push(460); + goto case 461; + } else { + Error(la); + goto case 460; + } + } + } else { + Expect(11, la); // XmlCloseTag + currentState = 458; + break; + } + } + case 461: { + if (la == null) { currentState = 461; break; } + Expect(12, la); // XmlStartInlineVB + currentState = 462; + break; + } + case 462: { + stateStack.Push(463); + goto case 56; + } + case 463: { + if (la == null) { currentState = 463; break; } + Expect(13, la); // XmlEndInlineVB + currentState = stateStack.Pop(); + break; + } + case 464: { + if (la == null) { currentState = 464; break; } + if (la.kind == 16) { + currentState = 465; + break; + } else { + goto case 465; + } + } + case 465: { + if (la == null) { currentState = 465; break; } + if (la.kind == 17 || la.kind == 19) { + currentState = 464; + break; + } else { + if (la.kind == 10) { + stateStack.Push(466); + goto case 455; + } else { + goto case 452; + } + } + } + case 466: { + if (la == null) { currentState = 466; break; } + if (la.kind == 17) { + currentState = 467; + break; + } else { + goto case 452; + } + } + case 467: { + if (la == null) { currentState = 467; break; } + if (la.kind == 16) { + currentState = 466; + break; + } else { + goto case 466; + } + } + case 468: { + if (la == null) { currentState = 468; break; } + Expect(37, la); // "(" + currentState = 469; + break; + } + case 469: { + readXmlIdentifier = true; + stateStack.Push(470); + goto case 206; + } + case 470: { + if (la == null) { currentState = 470; break; } + Expect(38, la); // ")" + currentState = 176; + break; + } + case 471: { + if (la == null) { currentState = 471; break; } + Expect(37, la); // "(" + currentState = 472; + break; + } + case 472: { + PushContext(Context.Type, la, t); + stateStack.Push(473); + goto case 37; + } + case 473: { + PopContext(); + goto case 470; + } + case 474: { + nextTokenIsStartOfImportsOrAccessExpression = true; wasQualifierTokenAtStart = true; + goto case 475; + } + case 475: { + if (la == null) { currentState = 475; break; } + if (la.kind == 10) { + currentState = 476; + break; + } else { + goto case 476; + } + } + case 476: { + stateStack.Push(477); + goto case 102; + } + case 477: { + if (la == null) { currentState = 477; break; } + if (la.kind == 11) { + currentState = 176; + break; + } else { + goto case 176; + } + } + case 478: { + activeArgument = 0; + goto case 479; + } + case 479: { + stateStack.Push(480); + goto case 56; + } + case 480: { + if (la == null) { currentState = 480; break; } + if (la.kind == 22) { + currentState = 481; + break; + } else { + goto case 470; + } + } + case 481: { + activeArgument++; + goto case 479; + } + case 482: { + stateStack.Push(483); + goto case 56; + } + case 483: { + if (la == null) { currentState = 483; break; } + if (la.kind == 22) { + currentState = 484; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 484: { + activeArgument++; + nextTokenIsPotentialStartOfExpression = true; + goto case 485; + } + case 485: { + if (la == null) { currentState = 485; break; } + if (set[23].Get(la.kind)) { + goto case 482; + } else { + goto case 483; + } + } + case 486: { + if (la == null) { currentState = 486; break; } + if (set[16].Get(la.kind)) { + stateStack.Push(487); + goto case 37; + } else { + goto case 487; + } + } + case 487: { + if (la == null) { currentState = 487; break; } + if (la.kind == 22) { + currentState = 486; + break; + } else { + goto case 45; + } + } + case 488: { + SetIdentifierExpected(la); + goto case 489; + } + case 489: { + if (la == null) { currentState = 489; break; } + if (set[151].Get(la.kind)) { + if (la.kind == 169) { + currentState = 491; + break; + } else { + if (set[78].Get(la.kind)) { + stateStack.Push(490); + goto case 422; + } else { + Error(la); + goto case 490; + } + } + } else { + goto case 490; + } + } + case 490: { + if (la == null) { currentState = 490; break; } + Expect(38, la); // ")" + currentState = 34; + break; + } + case 491: { + stateStack.Push(490); + goto case 492; + } + case 492: { + SetIdentifierExpected(la); + goto case 493; + } + case 493: { + if (la == null) { currentState = 493; break; } + if (la.kind == 138 || la.kind == 178) { + currentState = 494; + break; + } else { + goto case 494; + } + } + case 494: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(495); + goto case 509; + } + case 495: { + PopContext(); + goto case 496; + } + case 496: { + if (la == null) { currentState = 496; break; } + if (la.kind == 63) { + currentState = 510; + break; + } else { + goto case 497; + } + } + case 497: { + if (la == null) { currentState = 497; break; } + if (la.kind == 22) { + currentState = 498; + break; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 498: { + SetIdentifierExpected(la); + goto case 499; + } + case 499: { + if (la == null) { currentState = 499; break; } + if (la.kind == 138 || la.kind == 178) { + currentState = 500; + break; + } else { + goto case 500; + } + } + case 500: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(501); + goto case 509; + } + case 501: { + PopContext(); + goto case 502; + } + case 502: { + if (la == null) { currentState = 502; break; } + if (la.kind == 63) { + currentState = 503; + break; + } else { + goto case 497; + } + } + case 503: { + PushContext(Context.Type, la, t); + stateStack.Push(504); + goto case 505; + } + case 504: { + PopContext(); + goto case 497; + } + case 505: { + if (la == null) { currentState = 505; break; } + if (set[94].Get(la.kind)) { + goto case 508; + } else { + if (la.kind == 35) { + currentState = 506; + break; + } else { + goto case 6; + } + } + } + case 506: { + stateStack.Push(507); + goto case 508; + } + case 507: { + if (la == null) { currentState = 507; break; } + if (la.kind == 22) { + currentState = 506; + break; + } else { + goto case 83; + } + } + case 508: { + if (la == null) { currentState = 508; break; } + if (set[16].Get(la.kind)) { + currentState = 38; + break; + } else { + if (la.kind == 162) { + goto case 122; + } else { + if (la.kind == 84) { + goto case 138; + } else { + if (la.kind == 209) { + goto case 113; + } else { + goto case 6; + } + } + } + } + } + case 509: { + if (la == null) { currentState = 509; break; } + if (la.kind == 2) { + goto case 146; + } else { + if (la.kind == 62) { + goto case 144; + } else { + if (la.kind == 64) { + goto case 143; + } else { + if (la.kind == 65) { + goto case 142; + } else { + if (la.kind == 66) { + goto case 141; + } else { + if (la.kind == 67) { + goto case 140; + } else { + if (la.kind == 70) { + goto case 139; + } else { + if (la.kind == 87) { + goto case 137; + } else { + if (la.kind == 104) { + goto case 135; + } else { + if (la.kind == 107) { + goto case 134; + } else { + if (la.kind == 116) { + goto case 132; + } else { + if (la.kind == 121) { + goto case 131; + } else { + if (la.kind == 133) { + goto case 127; + } else { + if (la.kind == 139) { + goto case 126; + } else { + if (la.kind == 143) { + goto case 125; + } else { + if (la.kind == 146) { + goto case 124; + } else { + if (la.kind == 147) { + goto case 123; + } else { + if (la.kind == 170) { + goto case 120; + } else { + if (la.kind == 176) { + goto case 119; + } else { + if (la.kind == 184) { + goto case 118; + } else { + if (la.kind == 203) { + goto case 115; + } else { + if (la.kind == 212) { + goto case 110; + } else { + if (la.kind == 213) { + goto case 109; + } else { + if (la.kind == 223) { + goto case 107; + } else { + if (la.kind == 224) { + goto case 106; + } else { + if (la.kind == 230) { + goto case 105; + } else { + goto case 6; + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + case 510: { + PushContext(Context.Type, la, t); + stateStack.Push(511); + goto case 505; + } + case 511: { + PopContext(); + goto case 497; + } + case 512: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(513); + goto case 206; + } + case 513: { + PopContext(); + goto case 514; + } + case 514: { + if (la == null) { currentState = 514; break; } + if (la.kind == 37) { + currentState = 519; + break; + } else { + goto case 515; + } + } + case 515: { + if (la == null) { currentState = 515; break; } + if (la.kind == 63) { + currentState = 516; + break; + } else { + goto case 23; + } + } + case 516: { + PushContext(Context.Type, la, t); + goto case 517; + } + case 517: { + if (la == null) { currentState = 517; break; } + if (la.kind == 40) { + stateStack.Push(517); + goto case 435; + } else { + stateStack.Push(518); + goto case 37; + } + } + case 518: { + PopContext(); + goto case 23; + } + case 519: { + SetIdentifierExpected(la); + goto case 520; + } + case 520: { + if (la == null) { currentState = 520; break; } + if (set[78].Get(la.kind)) { + stateStack.Push(521); + goto case 422; + } else { + goto case 521; + } + } + case 521: { + if (la == null) { currentState = 521; break; } + Expect(38, la); // ")" + currentState = 515; + break; + } + case 522: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(523); + goto case 206; + } + case 523: { + PopContext(); + goto case 524; + } + case 524: { + if (la == null) { currentState = 524; break; } + if (la.kind == 37 || la.kind == 63) { + if (la.kind == 63) { + currentState = 529; + break; + } else { + if (la.kind == 37) { + currentState = 526; + break; + } else { + goto case 525; + } + } + } else { + goto case 23; + } + } + case 525: { + Error(la); + goto case 23; + } + case 526: { + SetIdentifierExpected(la); + goto case 527; + } + case 527: { + if (la == null) { currentState = 527; break; } + if (set[78].Get(la.kind)) { + stateStack.Push(528); + goto case 422; + } else { + goto case 528; + } + } + case 528: { + if (la == null) { currentState = 528; break; } + Expect(38, la); // ")" + currentState = 23; + break; + } + case 529: { + PushContext(Context.Type, la, t); + stateStack.Push(530); + goto case 37; + } + case 530: { + PopContext(); + goto case 23; + } + case 531: { + PushContext(Context.TypeDeclaration, la, t); + goto case 532; + } + case 532: { + if (la == null) { currentState = 532; break; } + Expect(115, la); // "Enum" + currentState = 533; + break; + } + case 533: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(534); + goto case 206; + } + case 534: { + PopContext(); + goto case 535; + } + case 535: { + if (la == null) { currentState = 535; break; } + if (la.kind == 63) { + currentState = 547; + break; + } else { + goto case 536; + } + } + case 536: { + stateStack.Push(537); + goto case 23; + } + case 537: { + SetIdentifierExpected(la); + goto case 538; + } + case 538: { + if (la == null) { currentState = 538; break; } + if (set[97].Get(la.kind)) { + goto case 542; + } else { + Expect(113, la); // "End" + currentState = 539; + break; + } + } + case 539: { + if (la == null) { currentState = 539; break; } + Expect(115, la); // "Enum" + currentState = 540; + break; + } + case 540: { + stateStack.Push(541); + goto case 23; + } + case 541: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 542: { + SetIdentifierExpected(la); + goto case 543; + } + case 543: { + if (la == null) { currentState = 543; break; } + if (la.kind == 40) { + stateStack.Push(542); + goto case 435; + } else { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(544); + goto case 206; + } + } + case 544: { + PopContext(); + goto case 545; + } + case 545: { + if (la == null) { currentState = 545; break; } + if (la.kind == 20) { + currentState = 546; + break; + } else { + goto case 536; + } + } + case 546: { + stateStack.Push(536); + goto case 56; + } + case 547: { + PushContext(Context.Type, la, t); + stateStack.Push(548); + goto case 37; + } + case 548: { + PopContext(); + goto case 536; + } + case 549: { + if (la == null) { currentState = 549; break; } + Expect(103, la); // "Delegate" + currentState = 550; + break; + } + case 550: { + if (la == null) { currentState = 550; break; } + if (la.kind == 210) { + currentState = 551; + break; + } else { + if (la.kind == 127) { + currentState = 551; + break; + } else { + Error(la); + goto case 551; + } + } + } + case 551: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + goto case 552; + } + case 552: { + if (la == null) { currentState = 552; break; } + currentState = 553; + break; + } + case 553: { + PopContext(); + goto case 554; + } + case 554: { + if (la == null) { currentState = 554; break; } + if (la.kind == 37) { + currentState = 557; + break; + } else { + if (la.kind == 63) { + currentState = 555; + break; + } else { + goto case 23; + } + } + } + case 555: { + PushContext(Context.Type, la, t); + stateStack.Push(556); + goto case 37; + } + case 556: { + PopContext(); + goto case 23; + } + case 557: { + SetIdentifierExpected(la); + goto case 558; + } + case 558: { + if (la == null) { currentState = 558; break; } + if (set[151].Get(la.kind)) { + if (la.kind == 169) { + currentState = 560; + break; + } else { + if (set[78].Get(la.kind)) { + stateStack.Push(559); + goto case 422; + } else { + Error(la); + goto case 559; + } + } + } else { + goto case 559; + } + } + case 559: { + if (la == null) { currentState = 559; break; } + Expect(38, la); // ")" + currentState = 554; + break; + } + case 560: { + stateStack.Push(559); + goto case 492; + } + case 561: { + PushContext(Context.TypeDeclaration, la, t); + goto case 562; + } + case 562: { + if (la == null) { currentState = 562; break; } + if (la.kind == 155) { + currentState = 563; + break; + } else { + if (la.kind == 84) { + currentState = 563; + break; + } else { + if (la.kind == 209) { + currentState = 563; + break; + } else { + Error(la); + goto case 563; + } + } + } + } + case 563: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(564); + goto case 206; + } + case 564: { + PopContext(); + goto case 565; + } + case 565: { + if (la == null) { currentState = 565; break; } + if (la.kind == 37) { + currentState = 729; + break; + } else { + goto case 566; + } + } + case 566: { + stateStack.Push(567); + goto case 23; + } + case 567: { + SetIdentifierExpected(la); + isMissingModifier = true; + goto case 568; + } + case 568: { + if (la == null) { currentState = 568; break; } + if (la.kind == 140) { + isMissingModifier = false; + goto case 726; + } else { + goto case 569; + } + } + case 569: { + SetIdentifierExpected(la); + isMissingModifier = true; + goto case 570; + } + case 570: { + if (la == null) { currentState = 570; break; } + if (la.kind == 136) { + isMissingModifier = false; + goto case 720; + } else { + goto case 571; + } + } + case 571: { + SetIdentifierExpected(la); + isMissingModifier = true; + goto case 572; + } + case 572: { + if (la == null) { currentState = 572; break; } + if (set[101].Get(la.kind)) { + goto case 577; + } else { + isMissingModifier = false; + goto case 573; + } + } + case 573: { + if (la == null) { currentState = 573; break; } + Expect(113, la); // "End" + currentState = 574; + break; + } + case 574: { + if (la == null) { currentState = 574; break; } + if (la.kind == 155) { + currentState = 575; + break; + } else { + if (la.kind == 84) { + currentState = 575; + break; + } else { + if (la.kind == 209) { + currentState = 575; + break; + } else { + Error(la); + goto case 575; + } + } + } + } + case 575: { + stateStack.Push(576); + goto case 23; + } + case 576: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 577: { + SetIdentifierExpected(la); + isMissingModifier = true; + goto case 578; + } + case 578: { + if (la == null) { currentState = 578; break; } + if (la.kind == 40) { + stateStack.Push(577); + goto case 435; + } else { + isMissingModifier = true; + goto case 579; + } + } + case 579: { + SetIdentifierExpected(la); + goto case 580; + } + case 580: { + if (la == null) { currentState = 580; break; } + if (set[132].Get(la.kind)) { + currentState = 719; + break; + } else { + isMissingModifier = false; + SetIdentifierExpected(la); + goto case 581; + } + } + case 581: { + if (la == null) { currentState = 581; break; } + if (la.kind == 84 || la.kind == 155 || la.kind == 209) { + stateStack.Push(571); + goto case 561; + } else { + if (la.kind == 103) { + stateStack.Push(571); + goto case 549; + } else { + if (la.kind == 115) { + stateStack.Push(571); + goto case 531; + } else { + if (la.kind == 142) { + stateStack.Push(571); + goto case 9; + } else { + if (set[104].Get(la.kind)) { + stateStack.Push(571); + PushContext(Context.Member, la, t); + SetIdentifierExpected(la); + goto case 582; + } else { + Error(la); + goto case 571; + } + } + } + } + } + } + case 582: { + if (la == null) { currentState = 582; break; } + if (set[122].Get(la.kind)) { + stateStack.Push(583); + goto case 704; + } else { + if (la.kind == 127 || la.kind == 210) { + stateStack.Push(583); + goto case 686; + } else { + if (la.kind == 101) { + stateStack.Push(583); + goto case 670; + } else { + if (la.kind == 119) { + stateStack.Push(583); + goto case 655; + } else { + if (la.kind == 98) { + stateStack.Push(583); + goto case 643; + } else { + if (la.kind == 186) { + stateStack.Push(583); + goto case 598; + } else { + if (la.kind == 172) { + stateStack.Push(583); + goto case 584; + } else { + Error(la); + goto case 583; + } + } + } + } + } + } + } + } + case 583: { + PopContext(); + currentState = stateStack.Pop(); + goto switchlbl; + } + case 584: { + if (la == null) { currentState = 584; break; } + Expect(172, la); // "Operator" + currentState = 585; + break; + } + case 585: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + goto case 586; + } + case 586: { + if (la == null) { currentState = 586; break; } + currentState = 587; + break; + } + case 587: { + PopContext(); + goto case 588; + } + case 588: { + if (la == null) { currentState = 588; break; } + Expect(37, la); // "(" + currentState = 589; + break; + } + case 589: { + stateStack.Push(590); + goto case 422; + } + case 590: { + if (la == null) { currentState = 590; break; } + Expect(38, la); // ")" + currentState = 591; + break; + } + case 591: { + if (la == null) { currentState = 591; break; } + if (la.kind == 63) { + currentState = 595; + break; + } else { + goto case 592; + } + } + case 592: { + stateStack.Push(593); + goto case 263; + } + case 593: { + if (la == null) { currentState = 593; break; } + Expect(113, la); // "End" + currentState = 594; + break; + } + case 594: { + if (la == null) { currentState = 594; break; } + Expect(172, la); // "Operator" + currentState = 23; + break; + } + case 595: { + PushContext(Context.Type, la, t); + goto case 596; + } + case 596: { + if (la == null) { currentState = 596; break; } + if (la.kind == 40) { + stateStack.Push(596); + goto case 435; + } else { + stateStack.Push(597); + goto case 37; + } + } + case 597: { + PopContext(); + goto case 592; + } + case 598: { + if (la == null) { currentState = 598; break; } + Expect(186, la); // "Property" + currentState = 599; + break; + } + case 599: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(600); + goto case 206; + } + case 600: { + PopContext(); + goto case 601; + } + case 601: { + if (la == null) { currentState = 601; break; } + if (la.kind == 37) { + currentState = 640; + break; + } else { + goto case 602; + } + } + case 602: { + if (la == null) { currentState = 602; break; } + if (la.kind == 63) { + currentState = 638; + break; + } else { + goto case 603; + } + } + case 603: { + if (la == null) { currentState = 603; break; } + if (la.kind == 136) { + currentState = 633; + break; + } else { + goto case 604; + } + } + case 604: { + if (la == null) { currentState = 604; break; } + if (la.kind == 20) { + currentState = 632; + break; + } else { + goto case 605; + } + } + case 605: { + stateStack.Push(606); + goto case 23; + } + case 606: { + PopContext(); + goto case 607; + } + case 607: { + if (la == null) { currentState = 607; break; } + if (la.kind == 40) { + stateStack.Push(607); + goto case 435; + } else { + goto case 608; + } + } + case 608: { + if (la == null) { currentState = 608; break; } + if (set[152].Get(la.kind)) { + currentState = 631; + break; + } else { + if (la.kind == 128 || la.kind == 198) { + PushContext(Context.Member, la, t); + goto case 609; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + } + case 609: { + if (la == null) { currentState = 609; break; } + if (la.kind == 128) { + currentState = 610; + break; + } else { + if (la.kind == 198) { + currentState = 610; + break; + } else { + Error(la); + goto case 610; + } + } + } + case 610: { + if (la == null) { currentState = 610; break; } + if (la.kind == 37) { + currentState = 628; + break; + } else { + goto case 611; + } + } + case 611: { + stateStack.Push(612); + goto case 263; + } + case 612: { + if (la == null) { currentState = 612; break; } + Expect(113, la); // "End" + currentState = 613; + break; + } + case 613: { + if (la == null) { currentState = 613; break; } + if (la.kind == 128) { + currentState = 614; + break; + } else { + if (la.kind == 198) { + currentState = 614; + break; + } else { + Error(la); + goto case 614; + } + } + } + case 614: { + stateStack.Push(615); + goto case 23; + } + case 615: { + if (la == null) { currentState = 615; break; } + if (set[110].Get(la.kind)) { + goto case 618; + } else { + goto case 616; + } + } + case 616: { + if (la == null) { currentState = 616; break; } + Expect(113, la); // "End" + currentState = 617; + break; + } + case 617: { + if (la == null) { currentState = 617; break; } + Expect(186, la); // "Property" + currentState = 23; + break; + } + case 618: { + if (la == null) { currentState = 618; break; } + if (la.kind == 40) { + stateStack.Push(618); + goto case 435; + } else { + goto case 619; + } + } + case 619: { + if (la == null) { currentState = 619; break; } + if (set[152].Get(la.kind)) { + currentState = 619; + break; + } else { + if (la.kind == 128) { + currentState = 620; + break; + } else { + if (la.kind == 198) { + currentState = 620; + break; + } else { + Error(la); + goto case 620; + } + } + } + } + case 620: { + if (la == null) { currentState = 620; break; } + if (la.kind == 37) { + currentState = 625; + break; + } else { + goto case 621; + } + } + case 621: { + stateStack.Push(622); + goto case 263; + } + case 622: { + if (la == null) { currentState = 622; break; } + Expect(113, la); // "End" + currentState = 623; + break; + } + case 623: { + if (la == null) { currentState = 623; break; } + if (la.kind == 128) { + currentState = 624; + break; + } else { + if (la.kind == 198) { + currentState = 624; + break; + } else { + Error(la); + goto case 624; + } + } + } + case 624: { + stateStack.Push(616); + goto case 23; + } + case 625: { + SetIdentifierExpected(la); + goto case 626; + } + case 626: { + if (la == null) { currentState = 626; break; } + if (set[78].Get(la.kind)) { + stateStack.Push(627); + goto case 422; + } else { + goto case 627; + } + } + case 627: { + if (la == null) { currentState = 627; break; } + Expect(38, la); // ")" + currentState = 621; + break; + } + case 628: { + SetIdentifierExpected(la); + goto case 629; + } + case 629: { + if (la == null) { currentState = 629; break; } + if (set[78].Get(la.kind)) { + stateStack.Push(630); + goto case 422; + } else { + goto case 630; + } + } + case 630: { + if (la == null) { currentState = 630; break; } + Expect(38, la); // ")" + currentState = 611; + break; + } + case 631: { + SetIdentifierExpected(la); + goto case 608; + } + case 632: { + stateStack.Push(605); + goto case 56; + } + case 633: { + PushContext(Context.Type, la, t); + stateStack.Push(634); + goto case 37; + } + case 634: { + PopContext(); + goto case 635; + } + case 635: { + if (la == null) { currentState = 635; break; } + if (la.kind == 22) { + currentState = 636; + break; + } else { + goto case 604; + } + } + case 636: { + PushContext(Context.Type, la, t); + stateStack.Push(637); + goto case 37; + } + case 637: { + PopContext(); + goto case 635; + } + case 638: { + if (la == null) { currentState = 638; break; } + if (la.kind == 40) { + stateStack.Push(638); + goto case 435; + } else { + if (la.kind == 162) { + stateStack.Push(603); + goto case 86; + } else { + if (set[16].Get(la.kind)) { + PushContext(Context.Type, la, t); + stateStack.Push(639); + goto case 37; + } else { + Error(la); + goto case 603; + } + } + } + } + case 639: { + PopContext(); + goto case 603; + } + case 640: { + SetIdentifierExpected(la); + goto case 641; + } + case 641: { + if (la == null) { currentState = 641; break; } + if (set[78].Get(la.kind)) { + stateStack.Push(642); + goto case 422; + } else { + goto case 642; + } + } + case 642: { + if (la == null) { currentState = 642; break; } + Expect(38, la); // ")" + currentState = 602; + break; + } + case 643: { + if (la == null) { currentState = 643; break; } + Expect(98, la); // "Custom" + currentState = 644; + break; + } + case 644: { + stateStack.Push(645); + goto case 655; + } + case 645: { + if (la == null) { currentState = 645; break; } + if (set[115].Get(la.kind)) { + goto case 647; + } else { + Expect(113, la); // "End" + currentState = 646; + break; + } + } + case 646: { + if (la == null) { currentState = 646; break; } + Expect(119, la); // "Event" + currentState = 23; + break; + } + case 647: { + if (la == null) { currentState = 647; break; } + if (la.kind == 40) { + stateStack.Push(647); + goto case 435; + } else { + if (la.kind == 56) { + currentState = 648; + break; + } else { + if (la.kind == 193) { + currentState = 648; + break; + } else { + if (la.kind == 189) { + currentState = 648; + break; + } else { + Error(la); + goto case 648; + } + } + } + } + } + case 648: { + if (la == null) { currentState = 648; break; } + Expect(37, la); // "(" + currentState = 649; + break; + } + case 649: { + stateStack.Push(650); + goto case 422; + } + case 650: { + if (la == null) { currentState = 650; break; } + Expect(38, la); // ")" + currentState = 651; + break; + } + case 651: { + stateStack.Push(652); + goto case 263; + } + case 652: { + if (la == null) { currentState = 652; break; } + Expect(113, la); // "End" + currentState = 653; + break; + } + case 653: { + if (la == null) { currentState = 653; break; } + if (la.kind == 56) { + currentState = 654; + break; + } else { + if (la.kind == 193) { + currentState = 654; + break; + } else { + if (la.kind == 189) { + currentState = 654; + break; + } else { + Error(la); + goto case 654; + } + } + } + } + case 654: { + stateStack.Push(645); + goto case 23; + } + case 655: { + if (la == null) { currentState = 655; break; } + Expect(119, la); // "Event" + currentState = 656; + break; + } + case 656: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(657); + goto case 206; + } + case 657: { + PopContext(); + goto case 658; + } + case 658: { + if (la == null) { currentState = 658; break; } + if (la.kind == 63) { + currentState = 668; + break; + } else { + if (set[153].Get(la.kind)) { + if (la.kind == 37) { + currentState = 665; + break; + } else { + goto case 659; + } + } else { + Error(la); + goto case 659; + } + } + } + case 659: { + if (la == null) { currentState = 659; break; } + if (la.kind == 136) { + currentState = 660; + break; + } else { + goto case 23; + } + } + case 660: { + PushContext(Context.Type, la, t); + stateStack.Push(661); + goto case 37; + } + case 661: { + PopContext(); + goto case 662; + } + case 662: { + if (la == null) { currentState = 662; break; } + if (la.kind == 22) { + currentState = 663; + break; + } else { + goto case 23; + } + } + case 663: { + PushContext(Context.Type, la, t); + stateStack.Push(664); + goto case 37; + } + case 664: { + PopContext(); + goto case 662; + } + case 665: { + SetIdentifierExpected(la); + goto case 666; + } + case 666: { + if (la == null) { currentState = 666; break; } + if (set[78].Get(la.kind)) { + stateStack.Push(667); + goto case 422; + } else { + goto case 667; + } + } + case 667: { + if (la == null) { currentState = 667; break; } + Expect(38, la); // ")" + currentState = 659; + break; + } + case 668: { + PushContext(Context.Type, la, t); + stateStack.Push(669); + goto case 37; + } + case 669: { + PopContext(); + goto case 659; + } + case 670: { + if (la == null) { currentState = 670; break; } + Expect(101, la); // "Declare" + currentState = 671; + break; + } + case 671: { + if (la == null) { currentState = 671; break; } + if (la.kind == 62 || la.kind == 66 || la.kind == 223) { + currentState = 672; + break; + } else { + goto case 672; + } + } + case 672: { + if (la == null) { currentState = 672; break; } + if (la.kind == 210) { + currentState = 673; + break; + } else { + if (la.kind == 127) { + currentState = 673; + break; + } else { + Error(la); + goto case 673; + } + } + } + case 673: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(674); + goto case 206; + } + case 674: { + PopContext(); + goto case 675; + } + case 675: { + if (la == null) { currentState = 675; break; } + Expect(149, la); // "Lib" + currentState = 676; + break; + } + case 676: { + if (la == null) { currentState = 676; break; } + Expect(3, la); // LiteralString + currentState = 677; + break; + } + case 677: { + if (la == null) { currentState = 677; break; } + if (la.kind == 59) { + currentState = 685; + break; + } else { + goto case 678; + } + } + case 678: { + if (la == null) { currentState = 678; break; } + if (la.kind == 37) { + currentState = 682; + break; + } else { + goto case 679; + } + } + case 679: { + if (la == null) { currentState = 679; break; } + if (la.kind == 63) { + currentState = 680; + break; + } else { + goto case 23; + } + } + case 680: { + PushContext(Context.Type, la, t); + stateStack.Push(681); + goto case 37; + } + case 681: { + PopContext(); + goto case 23; + } + case 682: { + SetIdentifierExpected(la); + goto case 683; + } + case 683: { + if (la == null) { currentState = 683; break; } + if (set[78].Get(la.kind)) { + stateStack.Push(684); + goto case 422; + } else { + goto case 684; + } + } + case 684: { + if (la == null) { currentState = 684; break; } + Expect(38, la); // ")" + currentState = 679; + break; + } + case 685: { + if (la == null) { currentState = 685; break; } + Expect(3, la); // LiteralString + currentState = 678; + break; + } + case 686: { + if (la == null) { currentState = 686; break; } + if (la.kind == 210) { + currentState = 687; + break; + } else { + if (la.kind == 127) { + currentState = 687; + break; + } else { + Error(la); + goto case 687; + } + } + } + case 687: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + goto case 688; + } + case 688: { + if (la == null) { currentState = 688; break; } + currentState = 689; + break; + } + case 689: { + PopContext(); + goto case 690; + } + case 690: { + if (la == null) { currentState = 690; break; } + if (la.kind == 37) { + currentState = 700; + break; + } else { + if (la.kind == 63) { + currentState = 698; + break; + } else { + goto case 691; + } + } + } + case 691: { + if (la == null) { currentState = 691; break; } + if (la.kind == 134 || la.kind == 136) { + currentState = 695; + break; + } else { + goto case 692; + } + } + case 692: { + stateStack.Push(693); + goto case 263; + } + case 693: { + if (la == null) { currentState = 693; break; } + Expect(113, la); // "End" + currentState = 694; + break; + } + case 694: { + if (la == null) { currentState = 694; break; } + if (la.kind == 210) { + currentState = 23; + break; + } else { + if (la.kind == 127) { + currentState = 23; + break; + } else { + goto case 525; + } + } + } + case 695: { + if (la == null) { currentState = 695; break; } + if (la.kind == 153 || la.kind == 158 || la.kind == 159) { + currentState = 697; + break; + } else { + goto case 696; + } + } + case 696: { + stateStack.Push(692); + goto case 37; + } + case 697: { + if (la == null) { currentState = 697; break; } + Expect(26, la); // "." + currentState = 696; + break; + } + case 698: { + PushContext(Context.Type, la, t); + stateStack.Push(699); + goto case 37; + } + case 699: { + PopContext(); + goto case 691; + } + case 700: { + SetIdentifierExpected(la); + goto case 701; + } + case 701: { + if (la == null) { currentState = 701; break; } + if (set[151].Get(la.kind)) { + if (la.kind == 169) { + currentState = 703; + break; + } else { + if (set[78].Get(la.kind)) { + stateStack.Push(702); + goto case 422; + } else { + Error(la); + goto case 702; + } + } + } else { + goto case 702; + } + } + case 702: { + if (la == null) { currentState = 702; break; } + Expect(38, la); // ")" + currentState = 690; + break; + } + case 703: { + stateStack.Push(702); + goto case 492; + } + case 704: { + stateStack.Push(705); + SetIdentifierExpected(la); + goto case 706; + } + case 705: { + if (la == null) { currentState = 705; break; } + if (la.kind == 22) { + currentState = 704; + break; + } else { + goto case 23; + } + } + case 706: { + if (la == null) { currentState = 706; break; } + if (la.kind == 88) { + currentState = 707; + break; + } else { + goto case 707; + } + } + case 707: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + stateStack.Push(708); + goto case 718; + } + case 708: { + PopContext(); + goto case 709; + } + case 709: { + if (la == null) { currentState = 709; break; } + if (la.kind == 33) { + currentState = 710; + break; + } else { + goto case 710; + } + } + case 710: { + if (la == null) { currentState = 710; break; } + if (la.kind == 37) { + currentState = 715; + break; + } else { + if (la.kind == 63) { + currentState = 712; + break; + } else { + goto case 711; + } + } + } + case 711: { + if (la == null) { currentState = 711; break; } + if (la.kind == 20) { + goto case 406; + } else { + currentState = stateStack.Pop(); + goto switchlbl; + } + } + case 712: { + PushContext(Context.Type, la, t); + goto case 713; + } + case 713: { + if (la == null) { currentState = 713; break; } + if (la.kind == 162) { + stateStack.Push(714); + goto case 86; + } else { + if (set[16].Get(la.kind)) { + stateStack.Push(714); + goto case 37; + } else { + Error(la); + goto case 714; + } + } + } + case 714: { + PopContext(); + goto case 711; + } + case 715: { + nextTokenIsPotentialStartOfExpression = true; + goto case 716; + } + case 716: { + if (la == null) { currentState = 716; break; } + if (set[23].Get(la.kind)) { + stateStack.Push(717); + goto case 56; + } else { + goto case 717; + } + } + case 717: { + if (la == null) { currentState = 717; break; } + if (la.kind == 22) { + currentState = 715; + break; + } else { + Expect(38, la); // ")" + currentState = 710; + break; + } + } + case 718: { + if (la == null) { currentState = 718; break; } + if (set[137].Get(la.kind)) { + currentState = stateStack.Pop(); + break; + } else { + if (la.kind == 58) { + goto case 145; + } else { + if (la.kind == 126) { + goto case 129; + } else { + goto case 6; + } + } + } + } + case 719: { + isMissingModifier = false; + goto case 579; + } + case 720: { + if (la == null) { currentState = 720; break; } + Expect(136, la); // "Implements" + currentState = 721; + break; + } + case 721: { + PushContext(Context.Type, la, t); + stateStack.Push(722); + goto case 37; + } + case 722: { + PopContext(); + goto case 723; + } + case 723: { + if (la == null) { currentState = 723; break; } + if (la.kind == 22) { + currentState = 724; + break; + } else { + stateStack.Push(571); + goto case 23; + } + } + case 724: { + PushContext(Context.Type, la, t); + stateStack.Push(725); + goto case 37; + } + case 725: { + PopContext(); + goto case 723; + } + case 726: { + if (la == null) { currentState = 726; break; } + Expect(140, la); // "Inherits" + currentState = 727; + break; + } + case 727: { + PushContext(Context.Type, la, t); + stateStack.Push(728); + goto case 37; + } + case 728: { + PopContext(); + stateStack.Push(569); + goto case 23; + } + case 729: { + if (la == null) { currentState = 729; break; } + Expect(169, la); // "Of" + currentState = 730; + break; + } + case 730: { + stateStack.Push(731); + goto case 492; + } + case 731: { + if (la == null) { currentState = 731; break; } + Expect(38, la); // ")" + currentState = 566; + break; + } + case 732: { + isMissingModifier = false; + goto case 28; + } + case 733: { + PushContext(Context.Type, la, t); + stateStack.Push(734); + goto case 37; + } + case 734: { + PopContext(); + goto case 735; + } + case 735: { + if (la == null) { currentState = 735; break; } + if (la.kind == 22) { + currentState = 736; + break; + } else { + stateStack.Push(17); + goto case 23; + } + } + case 736: { + PushContext(Context.Type, la, t); + stateStack.Push(737); + goto case 37; + } + case 737: { + PopContext(); + goto case 735; + } + case 738: { + if (la == null) { currentState = 738; break; } + Expect(169, la); // "Of" + currentState = 739; + break; + } + case 739: { + stateStack.Push(740); + goto case 492; + } + case 740: { + if (la == null) { currentState = 740; break; } + Expect(38, la); // ")" + currentState = 14; + break; + } + case 741: { + PushContext(Context.Identifier, la, t); + SetIdentifierExpected(la); + goto case 742; + } + case 742: { + if (la == null) { currentState = 742; break; } + if (set[50].Get(la.kind)) { + currentState = 742; + break; + } else { + PopContext(); + stateStack.Push(743); + goto case 23; + } + } + case 743: { + if (la == null) { currentState = 743; break; } + if (set[3].Get(la.kind)) { + stateStack.Push(743); + goto case 5; + } else { + Expect(113, la); // "End" + currentState = 744; + break; + } + } + case 744: { + if (la == null) { currentState = 744; break; } + Expect(160, la); // "Namespace" + currentState = 23; + break; + } + case 745: { + if (la == null) { currentState = 745; break; } + Expect(137, la); // "Imports" + currentState = 746; + break; + } + case 746: { + PushContext(Context.Importable, la, t); + nextTokenIsStartOfImportsOrAccessExpression = true; + goto case 747; + } + case 747: { + if (la == null) { currentState = 747; break; } + if (set[154].Get(la.kind)) { + currentState = 753; + break; + } else { + if (la.kind == 10) { + currentState = 749; + break; + } else { + Error(la); + goto case 748; + } + } + } + case 748: { + PopContext(); + goto case 23; + } + case 749: { + stateStack.Push(750); + goto case 206; + } + case 750: { + if (la == null) { currentState = 750; break; } + Expect(20, la); // "=" + currentState = 751; + break; + } + case 751: { + if (la == null) { currentState = 751; break; } + Expect(3, la); // LiteralString + currentState = 752; + break; + } + case 752: { + if (la == null) { currentState = 752; break; } + Expect(11, la); // XmlCloseTag + currentState = 748; + break; + } + case 753: { + if (la == null) { currentState = 753; break; } + if (la.kind == 37) { + stateStack.Push(753); + goto case 42; + } else { + if (la.kind == 20 || la.kind == 26) { + currentState = 754; + break; + } else { + goto case 748; + } + } + } + case 754: { + stateStack.Push(748); + goto case 37; + } + case 755: { + if (la == null) { currentState = 755; break; } + Expect(173, la); // "Option" + currentState = 756; + break; + } + case 756: { + if (la == null) { currentState = 756; break; } + if (la.kind == 121 || la.kind == 139 || la.kind == 207) { + currentState = 758; + break; + } else { + if (la.kind == 87) { + currentState = 757; + break; + } else { + goto case 525; + } + } + } + case 757: { + if (la == null) { currentState = 757; break; } + if (la.kind == 213) { + currentState = 23; + break; + } else { + if (la.kind == 67) { + currentState = 23; + break; + } else { + goto case 525; + } + } + } + case 758: { + if (la == null) { currentState = 758; break; } + if (la.kind == 170 || la.kind == 171) { + currentState = 23; + break; + } else { + goto case 23; + } + } + } + + if (la != null) { + t = la; + nextTokenIsPotentialStartOfExpression = false; + readXmlIdentifier = false; + nextTokenIsStartOfImportsOrAccessExpression = false; + wasQualifierTokenAtStart = false; + identifierExpected = false; + } + } + + public void Advance() + { + //Console.WriteLine("Advance"); + InformToken(null); + } + + public BitArray GetExpectedSet() { return GetExpectedSet(currentState); } + + static readonly BitArray[] set = { + new BitArray(new int[] {1, 256, 1048576, 537395328, 402670080, 444604481, 131200, 0}), + new BitArray(new int[] {1, 256, 1048576, 537395328, 402670080, 444596289, 131200, 0}), + new BitArray(new int[] {1, 256, 1048576, 537395328, 402669568, 444596289, 131200, 0}), + new BitArray(new int[] {0, 256, 1048576, 537395328, 402669568, 444596289, 131200, 0}), + new BitArray(new int[] {0, 256, 1048576, 537395328, 402669568, 444596288, 131200, 0}), + new BitArray(new int[] {0, 0, 1048576, 537395328, 402669568, 444596288, 131200, 0}), + new BitArray(new int[] {4, 1140850688, 8388687, 1108347140, 821280, 17105920, -2144335872, 65}), + new BitArray(new int[] {0, 256, 1048576, -1601568064, 671109120, 1589117122, 393600, 3328}), + new BitArray(new int[] {0, 256, 1048576, -1601568064, 671105024, 1589117122, 393600, 3328}), + new BitArray(new int[] {5, 1140850944, 26214479, -493220892, 940361760, 1606227139, -2143942272, 3393}), + new BitArray(new int[] {0, 256, 1048576, -1601699136, 671105024, 1589117122, 393600, 3328}), + new BitArray(new int[] {0, 0, 1048576, -1601699136, 671105024, 1589117122, 393600, 3328}), + new BitArray(new int[] {0, 0, 1048576, -2138570624, 134234112, 67108864, 393216, 0}), + new BitArray(new int[] {0, 0, 0, -2139095040, 0, 67108864, 262144, 0}), + new BitArray(new int[] {-2, -1, -1, -1, -1, -1, -1, -1}), + new BitArray(new int[] {2097154, -2147483616, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {4, 1140850690, 8650975, 1108355356, 9218084, 17106176, -533656048, 67}), + new BitArray(new int[] {-940564478, 889192445, 65, 1074825472, 72844640, 231424, 22030368, 4704}), + new BitArray(new int[] {-940564478, 889192413, 65, 1074825472, 72844640, 231424, 22030368, 4704}), + new BitArray(new int[] {4, -16777216, -1, -1, -1, -1, -1, 16383}), + new BitArray(new int[] {-61995012, 1174405224, -51384097, -972018405, -1030969182, 17106740, -97186288, 8259}), + new BitArray(new int[] {-61995012, 1174405224, -51384097, -972018405, -1030969182, 17106228, -97186288, 8259}), + new BitArray(new int[] {-61995012, 1174405160, -51384097, -972018405, -1030969182, 17106228, -97186288, 8259}), + new BitArray(new int[] {-66189316, 1174405160, -51384097, -972018405, -1030969182, 17106228, -97186288, 8259}), + new BitArray(new int[] {-1007673342, 889192405, 65, 1074825472, 72843296, 231424, 22030368, 4160}), + new BitArray(new int[] {-1013972992, 822083461, 0, 0, 71499776, 163840, 16777216, 4096}), + new BitArray(new int[] {-66189316, 1174405176, -51384097, -972018405, -1030969182, 17106228, -97186288, 8259}), + new BitArray(new int[] {4, 1140850690, 8650975, 1108355356, 9218084, 17106176, -533656048, 579}), + new BitArray(new int[] {-1007673342, 889192405, 65, 1074825472, 72843552, 231424, 22030368, 4160}), + new BitArray(new int[] {-1007673342, 889192413, 65, 1074825472, 72843552, 231424, 22030368, 4672}), + new BitArray(new int[] {-2, -9, -1, -1, -1, -1, -1, -1}), + new BitArray(new int[] {-1040382, 889192437, 65, 1074825472, 72843296, 231424, 22030368, 4160}), + new BitArray(new int[] {1006632960, 32, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {1028, -16777216, -1, -1, -1, -1, -1, 16383}), + new BitArray(new int[] {-1038334, -1258291211, 65, 1074825472, 72844320, 231424, 22030368, 4160}), + new BitArray(new int[] {1007552508, 1140850720, -51384097, -972018405, -1030969182, 17106208, -365621744, 8259}), + new BitArray(new int[] {-1040382, -1258291209, 65, 1074825472, 72844320, 231424, 22030368, 4160}), + new BitArray(new int[] {0, 0, -60035072, 1027, 0, 0, 134217728, 0}), + new BitArray(new int[] {0, 67108864, 0, 1073743872, 1310752, 65536, 1050656, 64}), + new BitArray(new int[] {4194304, 67108864, 0, 1073743872, 1343520, 65536, 1050656, 64}), + new BitArray(new int[] {-66189316, 1174405160, -51384097, -972018401, -1030969182, 17106228, -97186288, 8259}), + new BitArray(new int[] {4194304, 67108864, 64, 1073743872, 1343520, 65536, 1050656, 64}), + new BitArray(new int[] {66189314, -1174405161, 51384096, 972018404, 1030969181, -17106229, 97186287, -8260}), + new BitArray(new int[] {65140738, 973078487, 51384096, 972018404, 1030969181, -17106229, 97186287, -8260}), + new BitArray(new int[] {-66189316, 1174405160, -51384097, -972018405, -1030969182, 17106228, -97186288, 8387}), + new BitArray(new int[] {0, 67108864, 0, 1073743872, 1343520, 65536, 1050656, 64}), + new BitArray(new int[] {4, 1140851008, 8388975, 1108347140, 821280, 21316608, -2144335872, 65}), + new BitArray(new int[] {-64092162, -973078488, -51384097, -972018405, -1030969182, 17106228, -97186288, 8259}), + new BitArray(new int[] {-64092162, 1191182376, -1048865, -546062565, -1014191950, -1593504452, -21144002, 8903}), + new BitArray(new int[] {0, 0, 3072, 134447104, 16777216, 8, 0, 0}), + new BitArray(new int[] {-2097156, -1, -1, -1, -1, -1, -1, -1}), + new BitArray(new int[] {-66189316, 1191182376, -1051937, -680509669, -1030969166, -1593504460, -21144002, 8903}), + new BitArray(new int[] {-66189316, 1174405162, -51384097, -972018401, -1030969178, 17106228, -97186288, 8259}), + new BitArray(new int[] {6291458, 0, 0, 32768, 0, 0, 0, 0}), + new BitArray(new int[] {-64092162, 1174405160, -51384097, -971985637, -1030969182, 17106228, -97186288, 8259}), + new BitArray(new int[] {0, 0, 0, -1879044096, 0, 67108864, 67371040, 128}), + new BitArray(new int[] {36, 1140850688, 8388687, 1108347140, 821280, 17105920, -2144335872, 65}), + new BitArray(new int[] {2097158, 1140850688, 8388687, 1108347140, 821280, 17105920, -2144335872, 97}), + new BitArray(new int[] {2097154, -2147483648, 0, 0, 0, 0, 0, 32}), + new BitArray(new int[] {36, 1140850688, 8388687, 1108347140, 821280, 17105928, -2144335872, 65}), + new BitArray(new int[] {-66189316, 1174405160, -51384097, -972018405, -1030969166, 17106228, -97186284, 8259}), + new BitArray(new int[] {1007552508, 1140850720, -51384097, -972002021, -1030969182, 17106208, -365621744, 8259}), + new BitArray(new int[] {1007681536, -2147483614, 0, 0, 1024, 0, 0, 0}), + new BitArray(new int[] {1007681536, -2147483616, 0, 0, 1024, 0, 0, 0}), + new BitArray(new int[] {2097154, 0, 0, 0, 0, 0, 0, 129}), + new BitArray(new int[] {2097154, 0, 0, 32768, 0, 0, 0, 129}), + new BitArray(new int[] {-66189316, 1174405160, -51383073, -972018405, -1030969182, 17106228, -97186288, 8259}), + new BitArray(new int[] {-65140740, 1174409128, -51384097, -971985637, -1030903646, 17106228, -97186288, 8259}), + new BitArray(new int[] {-65140740, 1174409128, -51384097, -972018405, -1030903646, 17106228, -97186288, 8259}), + new BitArray(new int[] {1048576, 3968, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {-64092162, 1191182376, -1051937, -680509669, -1030969166, -1593504460, -21144002, 8903}), + new BitArray(new int[] {-64092162, 1191182376, -1051937, -680476901, -1030969166, -1593504460, -21144002, 8903}), + new BitArray(new int[] {2097154, 32, 0, 32768, 0, 0, 0, 0}), + new BitArray(new int[] {7340034, -2147483614, 0, 32768, 0, 0, 0, 0}), + new BitArray(new int[] {7340034, -2147483616, 0, 32768, 0, 0, 0, 0}), + new BitArray(new int[] {7340034, -2147483648, 0, 32768, 0, 0, 0, 0}), + new BitArray(new int[] {3145730, 0, 0, 32768, 0, 0, 0, 0}), + new BitArray(new int[] {4, 1140850690, 8650975, 1108355356, 9218084, 17106180, -533656048, 67}), + new BitArray(new int[] {4, 1140850944, 8388975, 1108347140, 821280, 21316608, -2144335872, 65}), + new BitArray(new int[] {4, 1140850688, 8388975, 1108347140, 821280, 21316608, -2144335872, 65}), + new BitArray(new int[] {5242880, -2147483584, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {-2, -1, -3, -1, -134217729, -1, -1, -1}), + new BitArray(new int[] {7, 1157628162, 26477055, -493212676, 948758565, 2147308999, -533262382, 3395}), + new BitArray(new int[] {918528, 0, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {-909310, -1258291209, 65, 1074825472, 72844320, 231424, 22030368, 4160}), + new BitArray(new int[] {-843774, -1258291209, 65, 1074825472, 72844320, 231424, 22030368, 4160}), + new BitArray(new int[] {-318462, -1258291209, 65, 1074825472, 72844320, 231424, 22030368, 4160}), + new BitArray(new int[] {-383998, -1258291209, 65, 1074825472, 72844320, 231424, 22030368, 4160}), + new BitArray(new int[] {-1038334, -1258291209, 65, 1074825472, 72844320, 231424, 22030368, 4160}), + new BitArray(new int[] {4194308, 1140850754, 8650975, 1108355356, 9218084, 17106176, -533656048, 67}), + new BitArray(new int[] {4, 1140851008, 8388975, 1108347140, 821280, 21317120, -2144335872, 65}), + new BitArray(new int[] {4, 1073741824, 8388687, 34605312, 822304, 17105920, -2144335872, 65}), + new BitArray(new int[] {4, 1073741824, 8388687, 34605312, 821280, 16843776, -2144335872, 65}), + new BitArray(new int[] {4, 1140850698, 9699551, 1108355356, 9218084, 17106180, -533524976, 67}), + new BitArray(new int[] {4, 1140850690, 9699551, 1108355356, 9218084, 17106180, -533524976, 67}), + new BitArray(new int[] {4, 1140850946, 8650975, 1108355356, 9218084, 17106176, -533656048, 67}), + new BitArray(new int[] {4, 1140850944, 8388687, 1108478212, 821280, 17105920, -2144335872, 65}), + new BitArray(new int[] {4, 1140850944, 8388687, 1108347140, 821280, 17105920, -2144335872, 65}), + new BitArray(new int[] {4, 1140850944, 26214479, -493220892, 671930656, 1606227138, -2143942272, 3393}), + new BitArray(new int[] {4, 1140850944, 26214479, -493220892, 671926560, 1606227138, -2143942272, 3393}), + new BitArray(new int[] {4, 1140850944, 26214479, -493220892, 671926304, 1606227138, -2143942272, 3393}), + new BitArray(new int[] {4, 1140850944, 26214479, -493351964, 671926304, 1606227138, -2143942272, 3393}), + new BitArray(new int[] {4, 1140850688, 26214479, -493351964, 671926304, 1606227138, -2143942272, 3393}), + new BitArray(new int[] {4, 1140850688, 26214479, -1030223452, 135055392, 84218880, -2143942656, 65}), + new BitArray(new int[] {4, 1140850688, 25165903, -1030747868, 821280, 84218880, -2144073728, 65}), + new BitArray(new int[] {3145730, -2147483616, 0, 0, 256, 0, 0, 0}), + new BitArray(new int[] {3145730, -2147483648, 0, 0, 256, 0, 0, 0}), + new BitArray(new int[] {3145730, 0, 0, 0, 256, 0, 0, 0}), + new BitArray(new int[] {4, 1140850944, 26214479, -493220892, 671926305, 1606227138, -2143942208, 3393}), + new BitArray(new int[] {0, 256, 0, 537001984, 1, 436207616, 64, 0}), + new BitArray(new int[] {0, 256, 0, 536870912, 1, 436207616, 64, 0}), + new BitArray(new int[] {0, 0, 0, 536870912, 1, 436207616, 64, 0}), + new BitArray(new int[] {7340034, 0, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {4, 1140850946, 8650975, 1108355356, 9218084, 17106180, -533656048, 67}), + new BitArray(new int[] {0, 16777472, 0, 131072, 0, 536870912, 2, 0}), + new BitArray(new int[] {0, 16777472, 0, 0, 0, 536870912, 2, 0}), + new BitArray(new int[] {2097154, -2147483616, 0, 0, 256, 0, 0, 0}), + new BitArray(new int[] {0, 1073741824, 4, -2147483648, 0, 0, -2147221504, 0}), + new BitArray(new int[] {2097154, -2013265888, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {2097154, -2147483616, 0, 0, 320, 0, 0, 0}), + new BitArray(new int[] {2097154, 0, 0, 0, 320, 0, 0, 0}), + new BitArray(new int[] {4, 1140850690, 8650975, 1108355356, -1030969308, 17106176, -533656048, 67}), + new BitArray(new int[] {4, 1140850688, 25165903, 1108347136, 821280, 17105920, -2144335872, 65}), + new BitArray(new int[] {4, 1140850688, 8388687, 1108347136, 821280, 17105920, -2144335872, 65}), + new BitArray(new int[] {7340034, -2147483614, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {7340034, -2147483616, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {0, 256, 1048576, 537526400, 402669568, 444596289, 131200, 0}), + new BitArray(new int[] {1028, 1140850688, 8650975, 1108355356, 9218084, 17106176, -533656048, 67}), + new BitArray(new int[] {70254594, 32, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {0, 0, 8388608, 33554432, 2048, 0, 32768, 0}), + new BitArray(new int[] {2097154, 0, 0, 0, 0, 3072, 0, 0}), + new BitArray(new int[] {0, 0, 0, 536870912, 268435456, 444596288, 128, 0}), + new BitArray(new int[] {0, 0, 0, 536871488, 536870912, 1522008258, 384, 3328}), + new BitArray(new int[] {0, 0, 262288, 8216, 8396800, 256, 1610679824, 2}), + new BitArray(new int[] {-1073741824, 33554432, 0, 0, 0, 16, 0, 0}), + new BitArray(new int[] {1006632960, 0, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {1016, 0, 0, 67108864, -1040187392, 32, 33554432, 0}), + new BitArray(new int[] {4, 1073741824, 8388687, 34605312, 821280, 17105920, -2144335872, 65}), + new BitArray(new int[] {0, 0, -1133776896, 3, 0, 0, 0, 0}), + new BitArray(new int[] {-64092162, 1191182376, -1051937, -680378597, -1030969166, -1593504460, -21144002, 8903}), + new BitArray(new int[] {0, 0, 33554432, 16777216, 16, 0, 16392, 0}), + new BitArray(new int[] {-66189316, 1174405160, -51383585, -972018405, -1030969182, 17106228, -97186288, 8259}), + new BitArray(new int[] {1048576, 3968, 0, 0, 65536, 0, 0, 0}), + new BitArray(new int[] {0, 0, 288, 0, 0, 4210688, 0, 0}), + new BitArray(new int[] {-2, -129, -3, -1, -134217729, -1, -1, -1}), + new BitArray(new int[] {-18434, -1, -1, -1, -1, -1, -1, -1}), + new BitArray(new int[] {-22530, -1, -1, -1, -1, -1, -1, -1}), + new BitArray(new int[] {-32770, -1, -1, -1, -1, -1, -1, -1}), + new BitArray(new int[] {-37890, -1, -1, -1, -1, -1, -1, -1}), + new BitArray(new int[] {-2050, -1, -1, -1, -1, -1, -1, -1}), + new BitArray(new int[] {-6146, -1, -1, -1, -1, -1, -1, -1}), + new BitArray(new int[] {4, 1140850944, 8388975, 1108347140, 821280, 21317120, -2144335872, 65}), + new BitArray(new int[] {0, 0, 0, 536870912, 0, 436207616, 0, 0}), + new BitArray(new int[] {2097154, 32, 0, 0, 256, 0, 0, 0}), + new BitArray(new int[] {4, 1140850688, 8650975, 1108355356, 9218084, 17106176, -533656048, 67}) + + }; + +} // end Parser + + +} \ No newline at end of file diff --git a/ICSharpCode.NRefactory.VB/Lexer/PushParser.frame b/ICSharpCode.NRefactory.VB/Lexer/PushParser.frame new file mode 100644 index 000000000..2e7fcca08 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/PushParser.frame @@ -0,0 +1,99 @@ +/*---------------------------------------------------------------------- +Compiler Generator Coco/R, +Copyright (c) 1990, 2004 Hanspeter Moessenboeck, University of Linz +extended by M. Loeberbauer & A. Woess, Univ. of Linz +with improvements by Pat Terry, Rhodes University + +This program is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License as published by the +Free Software Foundation; either version 2, or (at your option) any +later version. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +As an exception, it is allowed to write an extension of Coco/R that is +used as a plugin in non-free software. + +If not otherwise stated, any source code generated by Coco/R (other than +Coco/R itself) does not fall under the GNU General Public License. +----------------------------------------------------------------------*/ +-->begin +-->namespace + +partial class ExpressionFinder { +-->constants + const bool T = true; + const bool x = false; + +-->declarations + readonly Stack stateStack = new Stack(); + bool wasQualifierTokenAtStart = false; + bool nextTokenIsPotentialStartOfExpression = false; + bool readXmlIdentifier = false; + bool identifierExpected = false; + bool nextTokenIsStartOfImportsOrAccessExpression = false; + bool isMissingModifier = false; + bool isAlreadyInExpr = false; + bool wasNormalAttribute = false; + int activeArgument = 0; + List errors = new List(); + + public ExpressionFinder() + { + stateStack.Push(-1); // required so that we don't crash when leaving the root production + } + + void Expect(int expectedKind, Token la) + { + if (la.kind != expectedKind) { + Error(la); + output.AppendLine("expected: " + expectedKind); + //Console.WriteLine("expected: " + expectedKind); + } + } + + void Error(Token la) + { + output.AppendLine("not expected: " + la); + //Console.WriteLine("not expected: " + la); + errors.Add(la); + } + + Token t; + + public void InformToken(Token la) + { + -->informToken + if (la != null) { + t = la; + nextTokenIsPotentialStartOfExpression = false; + readXmlIdentifier = false; + nextTokenIsStartOfImportsOrAccessExpression = false; + wasQualifierTokenAtStart = false; + identifierExpected = false; + } + } + + public void Advance() + { + //Console.WriteLine("Advance"); + InformToken(null); + } + + public BitArray GetExpectedSet() { return GetExpectedSet(currentState); } + + static readonly BitArray[] set = { +-->initialization + }; + +} // end Parser + + +$$$ \ No newline at end of file diff --git a/ICSharpCode.NRefactory.VB/Lexer/SavepointEventArgs.cs b/ICSharpCode.NRefactory.VB/Lexer/SavepointEventArgs.cs new file mode 100644 index 000000000..4c9cc88cc --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/SavepointEventArgs.cs @@ -0,0 +1,20 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public class SavepointEventArgs : EventArgs + { + public Location SavepointLocation { get; private set; } + public VBLexerMemento State { get; private set; } + + public SavepointEventArgs(Location savepointLocation, VBLexerMemento state) + { + this.SavepointLocation = savepointLocation; + this.State = state; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Special/BlankLine.cs b/ICSharpCode.NRefactory.VB/Lexer/Special/BlankLine.cs new file mode 100644 index 000000000..67a85ec0a --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Special/BlankLine.cs @@ -0,0 +1,19 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB +{ + public class BlankLine : AbstractSpecial + { + public BlankLine(Location point) : base(point) + { + } + + public override object AcceptVisitor(ISpecialVisitor visitor, object data) + { + return visitor.Visit(this, data); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Special/Comment.cs b/ICSharpCode.NRefactory.VB/Lexer/Special/Comment.cs new file mode 100644 index 000000000..2bce0531c --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Special/Comment.cs @@ -0,0 +1,59 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB +{ + public class Comment : AbstractSpecial + { + CommentType commentType; + string comment; + + public CommentType CommentType { + get { + return commentType; + } + set { + commentType = value; + } + } + + public string CommentText { + get { + return comment; + } + set { + comment = value; + } + } + + /// + /// Is true, when the comment is at line start or only whitespaces + /// between line and comment start. + /// + public bool CommentStartsLine { + get; + set; + } + + public Comment(CommentType commentType, string comment, bool commentStartsLine, Location startPosition, Location endPosition) + : base(startPosition, endPosition) + { + this.commentType = commentType; + this.comment = comment; + this.CommentStartsLine = commentStartsLine; + } + + public override string ToString() + { + return String.Format("[{0}: Type = {1}, Text = {2}, Start = {3}, End = {4}]", + GetType().Name, CommentType, CommentText, StartPosition, EndPosition); + } + + public override object AcceptVisitor(ISpecialVisitor visitor, object data) + { + return visitor.Visit(this, data); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Special/CommentType.cs b/ICSharpCode.NRefactory.VB/Lexer/Special/CommentType.cs new file mode 100644 index 000000000..c06844a34 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Special/CommentType.cs @@ -0,0 +1,14 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB +{ + public enum CommentType + { + Block, + SingleLine, + Documentation + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Special/ISpecial.cs b/ICSharpCode.NRefactory.VB/Lexer/Special/ISpecial.cs new file mode 100644 index 000000000..ee6f106cd --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Special/ISpecial.cs @@ -0,0 +1,52 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB +{ + /// + /// Interface for all specials. + /// + public interface ISpecial + { + Location StartPosition { get; } + Location EndPosition { get; } + + object AcceptVisitor(ISpecialVisitor visitor, object data); + } + + public interface ISpecialVisitor + { + object Visit(ISpecial special, object data); + object Visit(BlankLine special, object data); + object Visit(Comment special, object data); + object Visit(PreprocessingDirective special, object data); + } + + public abstract class AbstractSpecial : ISpecial + { + public abstract object AcceptVisitor(ISpecialVisitor visitor, object data); + + protected AbstractSpecial(Location position) + { + this.StartPosition = position; + this.EndPosition = position; + } + + protected AbstractSpecial(Location startPosition, Location endPosition) + { + this.StartPosition = startPosition; + this.EndPosition = endPosition; + } + + public Location StartPosition { get; set; } + public Location EndPosition { get; set; } + + public override string ToString() + { + return String.Format("[{0}: Start = {1}, End = {2}]", + GetType().Name, StartPosition, EndPosition); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Special/PreProcessingDirective.cs b/ICSharpCode.NRefactory.VB/Lexer/Special/PreProcessingDirective.cs new file mode 100644 index 000000000..c1dd4bb18 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Special/PreProcessingDirective.cs @@ -0,0 +1,156 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; + +namespace ICSharpCode.NRefactory.VB +{ + public class PreprocessingDirective : AbstractSpecial + { + #region Conversion C# <-> VB + public static void VBToCSharp(IList list) + { + for (int i = 0; i < list.Count; ++i) { + if (list[i] is PreprocessingDirective) + list[i] = VBToCSharp((PreprocessingDirective)list[i]); + } + } + + public static PreprocessingDirective VBToCSharp(PreprocessingDirective dir) + { + string cmd = dir.Cmd; + string arg = dir.Arg; + if (cmd.Equals("#End", StringComparison.InvariantCultureIgnoreCase)) { + if (arg.ToLowerInvariant().StartsWith("region")) { + cmd = "#endregion"; + arg = ""; + } else if ("if".Equals(arg, StringComparison.InvariantCultureIgnoreCase)) { + cmd = "#endif"; + arg = ""; + } + } else if (cmd.Equals("#Region", StringComparison.InvariantCultureIgnoreCase)) { + cmd = "#region"; + } else if (cmd.Equals("#If", StringComparison.InvariantCultureIgnoreCase)) { + cmd = "#if"; + if (arg.ToLowerInvariant().EndsWith(" then")) + arg = arg.Substring(0, arg.Length - 5); + } else if (cmd.Equals("#Else", StringComparison.InvariantCultureIgnoreCase)) { + if (dir.Expression != null) + cmd = "#elif"; + else + cmd = "#else"; + } else if (cmd.Equals("#ElseIf", StringComparison.InvariantCultureIgnoreCase)) { + cmd = "#elif"; + } + return new PreprocessingDirective(cmd, arg, dir.StartPosition, dir.EndPosition) { + Expression = dir.Expression + }; + } + + public static void CSharpToVB(List list) + { + for (int i = 0; i < list.Count; ++i) { + if (list[i] is PreprocessingDirective) + list[i] = CSharpToVB((PreprocessingDirective)list[i]); + } + } + + public static PreprocessingDirective CSharpToVB(PreprocessingDirective dir) + { + string cmd = dir.Cmd; + string arg = dir.Arg; + switch (cmd) { + case "#region": + cmd = "#Region"; + if (!arg.StartsWith("\"")) { + arg = "\"" + arg.Trim() + "\""; + } + break; + case "#endregion": + cmd = "#End"; + arg = "Region"; + break; + case "#endif": + cmd = "#End"; + arg = "If"; + break; + case "#if": + arg += " Then"; + break; + } + if (cmd.Length > 1) { + cmd = cmd.Substring(0, 2).ToUpperInvariant() + cmd.Substring(2); + } + return new PreprocessingDirective(cmd, arg, dir.StartPosition, dir.EndPosition) { + Expression = dir.Expression + }; + } + #endregion + + string cmd; + string arg; + VB.Dom.Expression expression = Dom.Expression.Null; + + /// + /// Gets the directive name, including '#'. + /// + public string Cmd { + get { + return cmd; + } + set { + cmd = value ?? string.Empty; + } + } + + /// + /// Gets the directive argument. + /// + public string Arg { + get { + return arg; + } + set { + arg = value ?? string.Empty; + } + } + + /// + /// Gets/sets the expression (for directives that take an expression, e.g. #if and #elif). + /// + public Dom.Expression Expression { + get { return expression; } + set { expression = value ?? Dom.Expression.Null; } + } + + /// + /// The end position of the pre processor directive line. + /// May be != EndPosition. + /// + public Location LastLineEnd { + get; + set; + } + + + public override string ToString() + { + return String.Format("[PreProcessingDirective: Cmd = {0}, Arg = {1}]", + Cmd, + Arg); + } + + public PreprocessingDirective(string cmd, string arg, Location start, Location end) + : base(start, end) + { + this.Cmd = cmd; + this.Arg = arg; + } + + public override object AcceptVisitor(ISpecialVisitor visitor, object data) + { + return visitor.Visit(this, data); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Special/SpecialTracker.cs b/ICSharpCode.NRefactory.VB/Lexer/Special/SpecialTracker.cs new file mode 100644 index 000000000..b59f8c095 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Special/SpecialTracker.cs @@ -0,0 +1,71 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Text; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public class SpecialTracker + { + List currentSpecials = new List(); + + CommentType currentCommentType; + StringBuilder sb = new StringBuilder(); + Location startPosition; + bool commentStartsLine; + + public List CurrentSpecials { + get { + return currentSpecials; + } + } + + /// + /// Gets the specials from the SpecialTracker and resets the lists. + /// + public List RetrieveSpecials() + { + List tmp = currentSpecials; + currentSpecials = new List(); + return tmp; + } + + public void AddEndOfLine(Location point) + { + currentSpecials.Add(new BlankLine(point)); + } + + public void AddPreprocessingDirective(PreprocessingDirective directive) + { + if (directive == null) + throw new ArgumentNullException("directive"); + currentSpecials.Add(directive); + } + + // used for comment tracking + public void StartComment(CommentType commentType, bool commentStartsLine, Location startPosition) + { + this.currentCommentType = commentType; + this.startPosition = startPosition; + this.sb.Length = 0; + this.commentStartsLine = commentStartsLine; + } + + public void AddChar(char c) + { + sb.Append(c); + } + + public void AddString(string s) + { + sb.Append(s); + } + + public void FinishComment(Location endPosition) + { + currentSpecials.Add(new Comment(currentCommentType, sb.ToString(), commentStartsLine, startPosition, endPosition)); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Special/TagComment.cs b/ICSharpCode.NRefactory.VB/Lexer/Special/TagComment.cs new file mode 100644 index 000000000..7023c1c66 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Special/TagComment.cs @@ -0,0 +1,29 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + /// + /// Description of TagComment. + /// + public class TagComment : Comment + { + string tag; + + public string Tag { + get { + return tag; + } + set { + tag = value; + } + } + + public TagComment(string tag, string comment, bool commentStartsLine, Location startPosition, Location endPosition) : base(CommentType.SingleLine, comment, commentStartsLine, startPosition, endPosition) + { + this.tag = tag; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Token.cs b/ICSharpCode.NRefactory.VB/Lexer/Token.cs new file mode 100644 index 000000000..a67002b32 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Token.cs @@ -0,0 +1,111 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public enum LiteralFormat : byte + { + None, + DecimalNumber, + HexadecimalNumber, + OctalNumber, + StringLiteral, + VerbatimStringLiteral, + CharLiteral, + DateTimeLiteral + } + + public class Token + { + internal readonly int kind; + + internal readonly int col; + internal readonly int line; + + internal readonly LiteralFormat literalFormat; + internal readonly object literalValue; + internal readonly string val; + internal Token next; + readonly Location endLocation; + + public int Kind { + get { return kind; } + } + + public LiteralFormat LiteralFormat { + get { return literalFormat; } + } + + public object LiteralValue { + get { return literalValue; } + } + + public string Value { + get { return val; } + } + + public Location EndLocation { + get { return endLocation; } + } + + public Location Location { + get { + return new Location(col, line); + } + } + + public Token() + : this(0, 1, 1) + { + } + + public Token(int kind, int col, int line) : this (kind, col, line, null) + { + } + + public Token(int kind, Location startLocation, Location endLocation) : this(kind, startLocation, endLocation, "", null, LiteralFormat.None) + { + } + + public Token(int kind, int col, int line, string val) + { + this.kind = kind; + this.col = col; + this.line = line; + this.val = val; + this.endLocation = new Location(col + (val == null ? 1 : val.Length), line); + } + + internal Token(int kind, int x, int y, string val, object literalValue, LiteralFormat literalFormat) + : this(kind, new Location(x, y), new Location(x + val.Length, y), val, literalValue, literalFormat) + { + } + + public Token(int kind, Location startLocation, Location endLocation, string val, object literalValue, LiteralFormat literalFormat) + { + this.kind = kind; + this.col = startLocation.Column; + this.line = startLocation.Line; + this.endLocation = endLocation; + this.val = val; + this.literalValue = literalValue; + this.literalFormat = literalFormat; + } + + public override string ToString() + { + string vbToken; + + try { + vbToken = Tokens.GetTokenString(kind); + } catch (NotSupportedException) { + vbToken = ""; + } + + return string.Format("[Token {0} Location={1} EndLocation={2} val={3}]", + vbToken, Location, EndLocation, val); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/Tokens.cs b/ICSharpCode.NRefactory.VB/Lexer/Tokens.cs new file mode 100644 index 000000000..484534a15 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/Tokens.cs @@ -0,0 +1,527 @@ +// this file was autogenerated by a tool. +using System; +using System.Collections; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public static class Tokens + { + // ----- terminal classes ----- + public const int EOF = 0; + public const int EOL = 1; + public const int Identifier = 2; + public const int LiteralString = 3; + public const int LiteralCharacter = 4; + public const int LiteralInteger = 5; + public const int LiteralDouble = 6; + public const int LiteralSingle = 7; + public const int LiteralDecimal = 8; + public const int LiteralDate = 9; + public const int XmlOpenTag = 10; + public const int XmlCloseTag = 11; + public const int XmlStartInlineVB = 12; + public const int XmlEndInlineVB = 13; + public const int XmlCloseTagEmptyElement = 14; + public const int XmlOpenEndTag = 15; + public const int XmlContent = 16; + public const int XmlComment = 17; + public const int XmlCData = 18; + public const int XmlProcessingInstruction = 19; + + // ----- special character ----- + public const int Assign = 20; + public const int Colon = 21; + public const int Comma = 22; + public const int ConcatString = 23; + public const int Div = 24; + public const int DivInteger = 25; + public const int Dot = 26; + public const int TripleDot = 27; + public const int DotAt = 28; + public const int ExclamationMark = 29; + public const int Minus = 30; + public const int Plus = 31; + public const int Power = 32; + public const int QuestionMark = 33; + public const int Times = 34; + public const int OpenCurlyBrace = 35; + public const int CloseCurlyBrace = 36; + public const int OpenParenthesis = 37; + public const int CloseParenthesis = 38; + public const int GreaterThan = 39; + public const int LessThan = 40; + public const int NotEqual = 41; + public const int GreaterEqual = 42; + public const int LessEqual = 43; + public const int ShiftLeft = 44; + public const int ShiftRight = 45; + public const int PlusAssign = 46; + public const int PowerAssign = 47; + public const int MinusAssign = 48; + public const int TimesAssign = 49; + public const int DivAssign = 50; + public const int DivIntegerAssign = 51; + public const int ShiftLeftAssign = 52; + public const int ShiftRightAssign = 53; + public const int ConcatStringAssign = 54; + public const int ColonAssign = 55; + + // ----- keywords ----- + public const int AddHandler = 56; + public const int AddressOf = 57; + public const int Aggregate = 58; + public const int Alias = 59; + public const int And = 60; + public const int AndAlso = 61; + public const int Ansi = 62; + public const int As = 63; + public const int Ascending = 64; + public const int Assembly = 65; + public const int Auto = 66; + public const int Binary = 67; + public const int Boolean = 68; + public const int ByRef = 69; + public const int By = 70; + public const int Byte = 71; + public const int ByVal = 72; + public const int Call = 73; + public const int Case = 74; + public const int Catch = 75; + public const int CBool = 76; + public const int CByte = 77; + public const int CChar = 78; + public const int CDate = 79; + public const int CDbl = 80; + public const int CDec = 81; + public const int Char = 82; + public const int CInt = 83; + public const int Class = 84; + public const int CLng = 85; + public const int CObj = 86; + public const int Compare = 87; + public const int Const = 88; + public const int Continue = 89; + public const int CSByte = 90; + public const int CShort = 91; + public const int CSng = 92; + public const int CStr = 93; + public const int CType = 94; + public const int CUInt = 95; + public const int CULng = 96; + public const int CUShort = 97; + public const int Custom = 98; + public const int Date = 99; + public const int Decimal = 100; + public const int Declare = 101; + public const int Default = 102; + public const int Delegate = 103; + public const int Descending = 104; + public const int Dim = 105; + public const int DirectCast = 106; + public const int Distinct = 107; + public const int Do = 108; + public const int Double = 109; + public const int Each = 110; + public const int Else = 111; + public const int ElseIf = 112; + public const int End = 113; + public const int EndIf = 114; + public const int Enum = 115; + new public const int Equals = 116; + public const int Erase = 117; + public const int Error = 118; + public const int Event = 119; + public const int Exit = 120; + public const int Explicit = 121; + public const int False = 122; + public const int Finally = 123; + public const int For = 124; + public const int Friend = 125; + public const int From = 126; + public const int Function = 127; + public const int Get = 128; + new public const int GetType = 129; + public const int Global = 130; + public const int GoSub = 131; + public const int GoTo = 132; + public const int Group = 133; + public const int Handles = 134; + public const int If = 135; + public const int Implements = 136; + public const int Imports = 137; + public const int In = 138; + public const int Infer = 139; + public const int Inherits = 140; + public const int Integer = 141; + public const int Interface = 142; + public const int Into = 143; + public const int Is = 144; + public const int IsNot = 145; + public const int Join = 146; + public const int Key = 147; + public const int Let = 148; + public const int Lib = 149; + public const int Like = 150; + public const int Long = 151; + public const int Loop = 152; + public const int Me = 153; + public const int Mod = 154; + public const int Module = 155; + public const int MustInherit = 156; + public const int MustOverride = 157; + public const int MyBase = 158; + public const int MyClass = 159; + public const int Namespace = 160; + public const int Narrowing = 161; + public const int New = 162; + public const int Next = 163; + public const int Not = 164; + public const int Nothing = 165; + public const int NotInheritable = 166; + public const int NotOverridable = 167; + public const int Object = 168; + public const int Of = 169; + public const int Off = 170; + public const int On = 171; + public const int Operator = 172; + public const int Option = 173; + public const int Optional = 174; + public const int Or = 175; + public const int Order = 176; + public const int OrElse = 177; + public const int Out = 178; + public const int Overloads = 179; + public const int Overridable = 180; + public const int Overrides = 181; + public const int ParamArray = 182; + public const int Partial = 183; + public const int Preserve = 184; + public const int Private = 185; + public const int Property = 186; + public const int Protected = 187; + public const int Public = 188; + public const int RaiseEvent = 189; + public const int ReadOnly = 190; + public const int ReDim = 191; + public const int Rem = 192; + public const int RemoveHandler = 193; + public const int Resume = 194; + public const int Return = 195; + public const int SByte = 196; + public const int Select = 197; + public const int Set = 198; + public const int Shadows = 199; + public const int Shared = 200; + public const int Short = 201; + public const int Single = 202; + public const int Skip = 203; + public const int Static = 204; + public const int Step = 205; + public const int Stop = 206; + public const int Strict = 207; + public const int String = 208; + public const int Structure = 209; + public const int Sub = 210; + public const int SyncLock = 211; + public const int Take = 212; + public const int Text = 213; + public const int Then = 214; + public const int Throw = 215; + public const int To = 216; + public const int True = 217; + public const int Try = 218; + public const int TryCast = 219; + public const int TypeOf = 220; + public const int UInteger = 221; + public const int ULong = 222; + public const int Unicode = 223; + public const int Until = 224; + public const int UShort = 225; + public const int Using = 226; + public const int Variant = 227; + public const int Wend = 228; + public const int When = 229; + public const int Where = 230; + public const int While = 231; + public const int Widening = 232; + public const int With = 233; + public const int WithEvents = 234; + public const int WriteOnly = 235; + public const int Xor = 236; + public const int GetXmlNamespace = 237; + + public const int MaxToken = 238; + static BitArray NewSet(params int[] values) + { + BitArray bitArray = new BitArray(MaxToken); + foreach (int val in values) { + bitArray[val] = true; + } + return bitArray; + } + public static BitArray Null = NewSet(Nothing); + public static BitArray BlockSucc = NewSet(Case, Catch, Else, ElseIf, End, Finally, Loop, Next); + public static BitArray GlobalLevel = NewSet(Namespace, Module, Class, Structure, Imports, Option); + public static BitArray TypeLevel = NewSet(Sub, Function, Property); + public static BitArray IdentifierTokens = NewSet(Text, Binary, Compare, Assembly, Ansi, Auto, Preserve, Unicode, Until, Off, Out, Key, Explicit, Infer, From, Join, Equals, Distinct, Where, Take, Skip, Order, By, Ascending, Descending, Group, Into, Aggregate); + public static BitArray ExpressionStart = NewSet(Me, MyBase, MyClass, True, False, Not, From, Aggregate, New, Nothing, AddressOf, GetType, TypeOf, GetXmlNamespace, Global, Boolean, Date, Char, String, Decimal, Byte, Short, Integer, Long, Single, Double, UInteger, ULong, UShort, SByte, Sub, Function, DirectCast, TryCast, CType, CBool, CByte, CChar, CDate, CDec, CDbl, CInt, CLng, CObj, CSByte, CShort, CSng, CStr, CUInt, CULng, CUShort); + public static BitArray StatementStart = NewSet(Nothing, Me, MyBase, MyClass, True, False, Not, From, Aggregate, New, Nothing, AddressOf, GetType, TypeOf, GetXmlNamespace, Global, Boolean, Date, Char, String, Decimal, Byte, Short, Integer, Long, Single, Double, UInteger, ULong, UShort, SByte, Sub, Function, DirectCast, TryCast, CType, CBool, CByte, CChar, CDate, CDec, CDbl, CInt, CLng, CObj, CSByte, CShort, CSng, CStr, CUInt, CULng, CUShort, Dim, Const, Static, For, While, Do, Select); + public static BitArray SimpleTypeName = NewSet(Boolean, Date, Char, String, Decimal, Byte, Short, Integer, Long, Single, Double, UInteger, ULong, UShort, SByte, Text, Binary, Compare, Assembly, Ansi, Auto, Preserve, Unicode, Until, Off, Out, Key, Explicit, Infer, From, Join, Equals, Distinct, Where, Take, Skip, Order, By, Ascending, Descending, Group, Into, Aggregate); + public static BitArray CastExpressions = NewSet(DirectCast, TryCast, CType, CBool, CByte, CChar, CDate, CDec, CDbl, CInt, CLng, CObj, CSByte, CShort, CSng, CStr, CUInt, CULng, CUShort); + public static BitArray BooleanExpressions = NewSet(True, False); + public static BitArray LambdaStart = NewSet(Sub, Function); + public static BitArray OperatorsAtStart = NewSet(Not, From, Aggregate); + public static BitArray TypeKW = NewSet(Boolean, Date, Char, String, Decimal, Byte, Short, Integer, Long, Single, Double, UInteger, ULong, UShort, SByte); + + static string[] tokenList = new string[] { + // ----- terminal classes ----- + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + // ----- special character ----- + "=", + ":", + ",", + "&", + "/", + "\\", + ".", + "...", + ".@", + "!", + "-", + "+", + "^", + "?", + "*", + "{", + "}", + "(", + ")", + ">", + "<", + "<>", + ">=", + "<=", + "<<", + ">>", + "+=", + "^=", + "-=", + "*=", + "/=", + "\\=", + "<<=", + ">>=", + "&=", + ":=", + // ----- keywords ----- + "AddHandler", + "AddressOf", + "Aggregate", + "Alias", + "And", + "AndAlso", + "Ansi", + "As", + "Ascending", + "Assembly", + "Auto", + "Binary", + "Boolean", + "ByRef", + "By", + "Byte", + "ByVal", + "Call", + "Case", + "Catch", + "CBool", + "CByte", + "CChar", + "CDate", + "CDbl", + "CDec", + "Char", + "CInt", + "Class", + "CLng", + "CObj", + "Compare", + "Const", + "Continue", + "CSByte", + "CShort", + "CSng", + "CStr", + "CType", + "CUInt", + "CULng", + "CUShort", + "Custom", + "Date", + "Decimal", + "Declare", + "Default", + "Delegate", + "Descending", + "Dim", + "DirectCast", + "Distinct", + "Do", + "Double", + "Each", + "Else", + "ElseIf", + "End", + "EndIf", + "Enum", + "Equals", + "Erase", + "Error", + "Event", + "Exit", + "Explicit", + "False", + "Finally", + "For", + "Friend", + "From", + "Function", + "Get", + "GetType", + "Global", + "GoSub", + "GoTo", + "Group", + "Handles", + "If", + "Implements", + "Imports", + "In", + "Infer", + "Inherits", + "Integer", + "Interface", + "Into", + "Is", + "IsNot", + "Join", + "Key", + "Let", + "Lib", + "Like", + "Long", + "Loop", + "Me", + "Mod", + "Module", + "MustInherit", + "MustOverride", + "MyBase", + "MyClass", + "Namespace", + "Narrowing", + "New", + "Next", + "Not", + "Nothing", + "NotInheritable", + "NotOverridable", + "Object", + "Of", + "Off", + "On", + "Operator", + "Option", + "Optional", + "Or", + "Order", + "OrElse", + "Out", + "Overloads", + "Overridable", + "Overrides", + "ParamArray", + "Partial", + "Preserve", + "Private", + "Property", + "Protected", + "Public", + "RaiseEvent", + "ReadOnly", + "ReDim", + "Rem", + "RemoveHandler", + "Resume", + "Return", + "SByte", + "Select", + "Set", + "Shadows", + "Shared", + "Short", + "Single", + "Skip", + "Static", + "Step", + "Stop", + "Strict", + "String", + "Structure", + "Sub", + "SyncLock", + "Take", + "Text", + "Then", + "Throw", + "To", + "True", + "Try", + "TryCast", + "TypeOf", + "UInteger", + "ULong", + "Unicode", + "Until", + "UShort", + "Using", + "Variant", + "Wend", + "When", + "Where", + "While", + "Widening", + "With", + "WithEvents", + "WriteOnly", + "Xor", + "GetXmlNamespace", + }; + public static string GetTokenString(int token) + { + if (token >= 0 && token < tokenList.Length) { + return tokenList[token]; + } + throw new System.NotSupportedException("Unknown token:" + token); + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/VBLexer.cs b/ICSharpCode.NRefactory.VB/Lexer/VBLexer.cs new file mode 100644 index 000000000..3944ba7cd --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/VBLexer.cs @@ -0,0 +1,1489 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Xml; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public class VBLexer : IDisposable + { + bool lineEnd = true; + bool isAtLineBegin = false; // TODO: handle line begin, if neccessarry + bool misreadExclamationMarkAsTypeCharacter; + bool encounteredLineContinuation; + + ExpressionFinder ef; + + bool inXmlMode; + + Stack xmlModeStack = new Stack(); + + public VBLexer(TextReader reader) + { + this.reader = new LATextReader(reader); + ef = new ExpressionFinder(); + } + + public VBLexer(TextReader reader, VBLexerMemento state) : this(reader) + { + SetInitialLocation(new Location(state.Column, state.Line)); + lastToken = new Token(state.PrevTokenKind, 0, 0); + ef = new ExpressionFinder(state.ExpressionFinder); + lineEnd = state.LineEnd; + isAtLineBegin = state.IsAtLineBegin; + encounteredLineContinuation = state.EncounteredLineContinuation; + misreadExclamationMarkAsTypeCharacter = state.MisreadExclamationMarkAsTypeCharacter; + xmlModeStack = new Stack(state.XmlModeInfoStack.Select(i => (XmlModeInfo)i.Clone()).Reverse()); + inXmlMode = state.InXmlMode; + } + + Token NextInternal() + { + if (misreadExclamationMarkAsTypeCharacter) { + misreadExclamationMarkAsTypeCharacter = false; + return new Token(Tokens.ExclamationMark, Col - 1, Line); + } + + unchecked { + while (true) { + Location startLocation = new Location(Col, Line); + int nextChar = ReaderRead(); + if (nextChar == -1) + return new Token(Tokens.EOF, Col, Line, string.Empty); + char ch = (char)nextChar; + #region XML mode + CheckXMLState(startLocation); + if (inXmlMode && xmlModeStack.Peek().level <= 0 && !xmlModeStack.Peek().isDocumentStart && !xmlModeStack.Peek().inXmlTag) { + XmlModeInfo info = xmlModeStack.Peek(); + int peek = nextChar; + while (true) { + int step = -1; + while (peek != -1 && XmlConvert.IsWhitespaceChar((char)peek)) { + step++; + peek = ReaderPeek(step); + } + + if (peek == '<' && (ReaderPeek(step + 1) == '!' || ReaderPeek(step + 1) == '?')) { + char lastCh = '\0'; + for (int i = 0; i < step + 2; i++) + lastCh = (char)ReaderRead(); + + if (lastCh == '!') + return ReadXmlCommentOrCData(Col - 2, Line); + else + return ReadXmlProcessingInstruction(Col - 2, Line); + } + + break; + } + inXmlMode = false; + xmlModeStack.Pop(); + } + if (inXmlMode) { + XmlModeInfo info = xmlModeStack.Peek(); + int x = Col - 1; + int y = Line; + switch (ch) { + case '<': + if (ReaderPeek() == '/') { + ReaderRead(); + info.inXmlCloseTag = true; + return new Token(Tokens.XmlOpenEndTag, new Location(x, y), new Location(Col, Line)); + } + if (ReaderPeek() == '%' && ReaderPeek(1) == '=') { + inXmlMode = false; + ReaderRead(); ReaderRead(); + return new Token(Tokens.XmlStartInlineVB, new Location(x, y), new Location(Col, Line)); + } + if (ReaderPeek() == '?') { + ReaderRead(); + Token t = ReadXmlProcessingInstruction(x, y); + return t; + } + if (ReaderPeek() == '!') { + ReaderRead(); + Token token = ReadXmlCommentOrCData(x, y); + return token; + } + info.level++; + info.isDocumentStart = false; + info.inXmlTag = true; + return new Token(Tokens.XmlOpenTag, x, y); + case '/': + if (ReaderPeek() == '>') { + ReaderRead(); + info.inXmlTag = false; + info.level--; + return new Token(Tokens.XmlCloseTagEmptyElement, new Location(x, y), new Location(Col, Line)); + } + break; + case '>': + if (info.inXmlCloseTag) + info.level--; + info.inXmlTag = info.inXmlCloseTag = false; + return new Token(Tokens.XmlCloseTag, x, y); + case '=': + return new Token(Tokens.Assign, x, y); + case '\'': + case '"': + string s = ReadXmlString(ch); + return new Token(Tokens.LiteralString, x, y, ch + s + ch, s, LiteralFormat.StringLiteral); + default: + if (info.inXmlCloseTag || info.inXmlTag) { + if (XmlConvert.IsWhitespaceChar(ch)) + continue; + return new Token(Tokens.Identifier, x, y, ReadXmlIdent(ch)); + } else { + string content = ReadXmlContent(ch); + return new Token(Tokens.XmlContent, startLocation, new Location(Col, Line), content, null, LiteralFormat.None); + } + } + #endregion + } else { + #region Standard Mode + if (Char.IsWhiteSpace(ch)) { + if (HandleLineEnd(ch)) { + if (lineEnd) { + // second line end before getting to a token + // -> here was a blank line + specialTracker.AddEndOfLine(startLocation); + } else { + lineEnd = true; + return new Token(Tokens.EOL, startLocation, new Location(Col, Line), null, null, LiteralFormat.None); + } + } + continue; + } + if (ch == '_') { + if (ReaderPeek() == -1) { + errors.Error(Line, Col, String.Format("No EOF expected after _")); + return new Token(Tokens.EOF, Col, Line, string.Empty); + } + if (!Char.IsWhiteSpace((char)ReaderPeek())) { + int x = Col - 1; + int y = Line; + string s = ReadIdent('_'); + lineEnd = false; + return new Token(Tokens.Identifier, x, y, s); + } + encounteredLineContinuation = true; + ch = (char)ReaderRead(); + + bool oldLineEnd = lineEnd; + lineEnd = false; + while (Char.IsWhiteSpace(ch)) { + if (HandleLineEnd(ch)) { + lineEnd = true; + break; + } + if (ReaderPeek() != -1) { + ch = (char)ReaderRead(); + } else { + errors.Error(Line, Col, String.Format("No EOF expected after _")); + return new Token(Tokens.EOF, Col, Line, string.Empty); + } + } + if (!lineEnd) { + errors.Error(Line, Col, String.Format("NewLine expected")); + } + lineEnd = oldLineEnd; + continue; + } + + if (ch == '#') { + while (Char.IsWhiteSpace((char)ReaderPeek())) { + ReaderRead(); + } + if (Char.IsDigit((char)ReaderPeek())) { + int x = Col - 1; + int y = Line; + string s = ReadDate(); + DateTime time = new DateTime(1, 1, 1, 0, 0, 0); + try { + time = DateTime.Parse(s, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault); + } catch (Exception e) { + errors.Error(Line, Col, String.Format("Invalid date time {0}", e)); + } + return new Token(Tokens.LiteralDate, x, y, s, time, LiteralFormat.DateTimeLiteral); + } else { + ReadPreprocessorDirective(); + continue; + } + } + + if (ch == '[') { // Identifier + lineEnd = false; + if (ReaderPeek() == -1) { + errors.Error(Line, Col, String.Format("Identifier expected")); + } + ch = (char)ReaderRead(); + if (ch == ']' || Char.IsWhiteSpace(ch)) { + errors.Error(Line, Col, String.Format("Identifier expected")); + } + int x = Col - 1; + int y = Line; + string s = ReadIdent(ch); + if (ReaderPeek() == -1) { + errors.Error(Line, Col, String.Format("']' expected")); + } + ch = (char)ReaderRead(); + if (!(ch == ']')) { + errors.Error(Line, Col, String.Format("']' expected")); + } + return new Token(Tokens.Identifier, x, y, s); + } + if (Char.IsLetter(ch)) { + int x = Col - 1; + int y = Line; + char typeCharacter; + string s = ReadIdent(ch, out typeCharacter); + if (typeCharacter == '\0') { + int keyWordToken = Keywords.GetToken(s); + if (keyWordToken >= 0) { + // handle 'REM' comments + if (keyWordToken == Tokens.Rem) { + ReadComment(); + if (!lineEnd) { + lineEnd = true; + return new Token(Tokens.EOL, Col, Line, "\n"); + } + continue; + } + + lineEnd = false; + return new Token(keyWordToken, x, y, s); + } + } + + lineEnd = false; + return new Token(Tokens.Identifier, x, y, s); + + } + if (Char.IsDigit(ch)) { + lineEnd = false; + return ReadDigit(ch, Col - 1); + } + if (ch == '&') { + lineEnd = false; + if (ReaderPeek() == -1) { + return ReadOperator('&'); + } + ch = (char)ReaderPeek(); + if (Char.ToUpper(ch, CultureInfo.InvariantCulture) == 'H' || Char.ToUpper(ch, CultureInfo.InvariantCulture) == 'O') { + return ReadDigit('&', Col - 1); + } + return ReadOperator('&'); + } + if (ch == '\'' || ch == '\u2018' || ch == '\u2019') { + int x = Col - 1; + int y = Line; + ReadComment(); + if (!lineEnd) { + lineEnd = true; + return new Token(Tokens.EOL, x, y, "\n"); + } + continue; + } + if (ch == '"') { + lineEnd = false; + int x = Col - 1; + int y = Line; + string s = ReadString(); + if (ReaderPeek() != -1 && (ReaderPeek() == 'C' || ReaderPeek() == 'c')) { + ReaderRead(); + if (s.Length != 1) { + errors.Error(Line, Col, String.Format("Chars can only have Length 1 ")); + } + if (s.Length == 0) { + s = "\0"; + } + return new Token(Tokens.LiteralCharacter, x, y, '"' + s + "\"C", s[0], LiteralFormat.CharLiteral); + } + return new Token(Tokens.LiteralString, x, y, '"' + s + '"', s, LiteralFormat.StringLiteral); + } + if (ch == '%' && ReaderPeek() == '>') { + int x = Col - 1; + int y = Line; + inXmlMode = true; + ReaderRead(); + return new Token(Tokens.XmlEndInlineVB, new Location(x, y), new Location(Col, Line)); + } + #endregion + if (ch == '<' && (ef.NextTokenIsPotentialStartOfExpression || ef.NextTokenIsStartOfImportsOrAccessExpression)) { + xmlModeStack.Push(new XmlModeInfo(ef.NextTokenIsStartOfImportsOrAccessExpression)); + XmlModeInfo info = xmlModeStack.Peek(); + int x = Col - 1; + int y = Line; + inXmlMode = true; + if (ReaderPeek() == '/') { + ReaderRead(); + info.inXmlCloseTag = true; + return new Token(Tokens.XmlOpenEndTag, new Location(x, y), new Location(Col, Line)); + } + // should we allow <%= at start of an expression? not valid with vbc ... + if (ReaderPeek() == '%' && ReaderPeek(1) == '=') { + inXmlMode = false; + ReaderRead(); ReaderRead(); + return new Token(Tokens.XmlStartInlineVB, new Location(x, y), new Location(Col, Line)); + } + if (ReaderPeek() == '!') { + ReaderRead(); + Token t = ReadXmlCommentOrCData(x, y); + return t; + } + if (ReaderPeek() == '?') { + ReaderRead(); + Token t = ReadXmlProcessingInstruction(x, y); + info.isDocumentStart = t.val.Trim().StartsWith("xml", StringComparison.OrdinalIgnoreCase); + return t; + } + info.inXmlTag = true; + info.level++; + return new Token(Tokens.XmlOpenTag, x, y); + } + Token token = ReadOperator(ch); + if (token != null) { + lineEnd = false; + return token; + } + } + + errors.Error(Line, Col, String.Format("Unknown char({0}) which can't be read", ch)); + } + } + } + + void CheckXMLState(Location startLocation) + { + if (inXmlMode && !xmlModeStack.Any()) + throw new InvalidOperationException("invalid XML stack state at " + startLocation); + } + + Token prevToken; + + Token Next() + { + Token t = NextInternal(); + if (t.kind == Tokens.EOL) { + Debug.Assert(t.next == null); // NextInternal() must return only 1 token + t.next = NextInternal(); + Debug.Assert(t.next.next == null); + if (SkipEOL(prevToken.kind, t.next.kind)) { + t = t.next; + } + } else + encounteredLineContinuation = false; + // inform EF only once we're sure it's really a token + // this means we inform it about EOL tokens "1 token too late", but that's not a problem because + // XML literals cannot start immediately after an EOL token + ef.InformToken(t); + if (t.next != null) { + // Next() isn't called again when it returns 2 tokens, so we need to process both tokens + ef.InformToken(t.next); + prevToken = t.next; + } else { + prevToken = t; + } + ef.Advance(); + Debug.Assert(t != null); + return t; + } + + /// see VB language specification 10; pg. 6 + bool SkipEOL(int prevTokenKind, int nextTokenKind) + { + // exception directly after _ + if (encounteredLineContinuation) { + return encounteredLineContinuation = false; + } + + // 1st rule + // after a comma (,), open parenthesis ((), open curly brace ({), or open embedded expression (<%=) + if (new[] { Tokens.Comma, Tokens.OpenParenthesis, Tokens.OpenCurlyBrace, Tokens.XmlStartInlineVB } + .Contains(prevTokenKind)) + return true; + + // 2nd rule + // after a member qualifier (. or .@ or ...), provided that something is being qualified (i.e. is not + // using an implicit With context) + if (new[] { Tokens.Dot, Tokens.DotAt, Tokens.TripleDot }.Contains(prevTokenKind) + && !ef.WasQualifierTokenAtStart) + return true; + + // 3rd rule + // before a close parenthesis ()), close curly brace (}), or close embedded expression (%>) + if (new[] { Tokens.CloseParenthesis, Tokens.CloseCurlyBrace, Tokens.XmlEndInlineVB } + .Contains(nextTokenKind)) + return true; + + // 4th rule + // after a less-than (<) in an attribute context + if (prevTokenKind == Tokens.LessThan && ef.InContext(Context.Attribute)) + return true; + + // 5th rule + // before a greater-than (>) in an attribute context + if (nextTokenKind == Tokens.GreaterThan && ef.InContext(Context.Attribute)) + return true; + + // 6th rule + // after a greater-than (>) in a non-file-level attribute context + if (ef.WasNormalAttribute && prevTokenKind == Tokens.GreaterThan) + return true; + + // 7th rule + // before and after query operators (Where, Order, Select, etc.) + var queryOperators = new int[] { Tokens.From, Tokens.Aggregate, Tokens.Select, Tokens.Distinct, + Tokens.Where, Tokens.Order, Tokens.By, Tokens.Ascending, Tokens.Descending, Tokens.Take, + Tokens.Skip, Tokens.Let, Tokens.Group, Tokens.Into, Tokens.On, Tokens.While, Tokens.Join }; + if (ef.InContext(Context.Query)) { + // Ascending, Descending, Distinct are special + // fixes http://community.sharpdevelop.net/forums/p/12068/32893.aspx#32893 + var specialQueryOperators = new int[] { Tokens.Ascending, Tokens.Descending, Tokens.Distinct }; + if (specialQueryOperators.Contains(prevTokenKind) && !queryOperators.Contains(nextTokenKind)) + return false; + + if ((queryOperators.Contains(prevTokenKind) || queryOperators.Contains(nextTokenKind))) + return true; + } + + // 8th rule + // after binary operators (+, -, /, *, etc.) in an expression context + if (new[] { Tokens.Plus, Tokens.Minus, Tokens.Div, Tokens.DivInteger, Tokens.Times, Tokens.Mod, Tokens.Power, + Tokens.Assign, Tokens.NotEqual, Tokens.LessThan, Tokens.LessEqual, Tokens.GreaterThan, Tokens.GreaterEqual, + Tokens.Like, Tokens.ConcatString, Tokens.AndAlso, Tokens.OrElse, Tokens.And, Tokens.Or, Tokens.Xor, + Tokens.ShiftLeft, Tokens.ShiftRight }.Contains(prevTokenKind) && ef.CurrentBlock.context == Context.Expression) + return true; + + // 9th rule + // after assignment operators (=, :=, +=, -=, etc.) in any context. + if (new[] { Tokens.Assign, Tokens.ColonAssign, Tokens.ConcatStringAssign, Tokens.DivAssign, + Tokens.DivIntegerAssign, Tokens.MinusAssign, Tokens.PlusAssign, Tokens.PowerAssign, + Tokens.ShiftLeftAssign, Tokens.ShiftRightAssign, Tokens.TimesAssign }.Contains(prevTokenKind)) + return true; + + return false; + } + + /// + /// Reads the next token. + /// + /// A object. + public Token NextToken() + { + if (curToken == null) { // first call of NextToken() + curToken = Next(); + //Console.WriteLine("Tok:" + Tokens.GetTokenString(curToken.kind) + " --- " + curToken.val); + return curToken; + } + + lastToken = curToken; + + if (curToken.next == null) { + curToken.next = Next(); + } + + curToken = curToken.next; + + if (curToken.kind == Tokens.EOF && !(lastToken.kind == Tokens.EOL)) { // be sure that before EOF there is an EOL token + curToken = new Token(Tokens.EOL, curToken.col, curToken.line, string.Empty); + curToken.next = new Token(Tokens.EOF, curToken.col, curToken.line, string.Empty); + } + //Console.WriteLine("Tok:" + Tokens.GetTokenString(curToken.kind) + " --- " + curToken.val); + return curToken; + } + + #region VB Readers + string ReadIdent(char ch) + { + char typeCharacter; + return ReadIdent(ch, out typeCharacter); + } + + string ReadIdent(char ch, out char typeCharacter) + { + typeCharacter = '\0'; + + if (ef.ReadXmlIdentifier) { + ef.ReadXmlIdentifier = false; + return ReadXmlIdent(ch); + } + + sb.Length = 0; + sb.Append(ch); + int peek; + while ((peek = ReaderPeek()) != -1 && (Char.IsLetterOrDigit(ch = (char)peek) || ch == '_')) { + ReaderRead(); + sb.Append(ch.ToString()); + } + if (peek == -1) { + return sb.ToString(); + } + + if ("%&@!#$".IndexOf((char)peek) != -1) { + typeCharacter = (char)peek; + ReaderRead(); + if (typeCharacter == '!') { + peek = ReaderPeek(); + if (peek != -1 && (peek == '_' || peek == '[' || char.IsLetter((char)peek))) { + misreadExclamationMarkAsTypeCharacter = true; + } + } + } + return sb.ToString(); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1818:DoNotConcatenateStringsInsideLoops")] + Token ReadDigit(char ch, int x) + { + sb.Length = 0; + sb.Append(ch); + + int y = Line; + string digit = ""; + if (ch != '&') { + digit += ch; + } + + bool isHex = false; + bool isOct = false; + bool isSingle = false; + bool isDouble = false; + bool isDecimal = false; + + if (ReaderPeek() == -1) { + if (ch == '&') { + errors.Error(Line, Col, String.Format("digit expected")); + } + return new Token(Tokens.LiteralInteger, x, y, sb.ToString() ,ch - '0', LiteralFormat.DecimalNumber); + } + if (ch == '.') { + if (Char.IsDigit((char)ReaderPeek())) { + isDouble = true; // double is default + if (isHex || isOct) { + errors.Error(Line, Col, String.Format("No hexadecimal or oktadecimal floating point values allowed")); + } + while (ReaderPeek() != -1 && Char.IsDigit((char)ReaderPeek())){ // read decimal digits beyond the dot + digit += (char)ReaderRead(); + } + } + } else if (ch == '&' && PeekUpperChar() == 'H') { + const string hex = "0123456789ABCDEF"; + sb.Append((char)ReaderRead()); // skip 'H' + while (ReaderPeek() != -1 && hex.IndexOf(PeekUpperChar()) != -1) { + ch = (char)ReaderRead(); + sb.Append(ch); + digit += Char.ToUpper(ch, CultureInfo.InvariantCulture); + } + isHex = true; + } else if (ReaderPeek() != -1 && ch == '&' && PeekUpperChar() == 'O') { + const string okt = "01234567"; + sb.Append((char)ReaderRead()); // skip 'O' + while (ReaderPeek() != -1 && okt.IndexOf(PeekUpperChar()) != -1) { + ch = (char)ReaderRead(); + sb.Append(ch); + digit += Char.ToUpper(ch, CultureInfo.InvariantCulture); + } + isOct = true; + } else { + while (ReaderPeek() != -1 && Char.IsDigit((char)ReaderPeek())) { + ch = (char)ReaderRead();; + digit += ch; + sb.Append(ch); + } + } + + if (digit.Length == 0) { + errors.Error(Line, Col, String.Format("digit expected")); + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), 0, LiteralFormat.DecimalNumber); + } + + if (ReaderPeek() != -1 && "%&SILU".IndexOf(PeekUpperChar()) != -1 || isHex || isOct) { + bool unsigned = false; + if (ReaderPeek() != -1) { + ch = (char)ReaderPeek(); + sb.Append(ch); + ch = Char.ToUpper(ch, CultureInfo.InvariantCulture); + unsigned = ch == 'U'; + if (unsigned) { + ReaderRead(); // read the U + ch = (char)ReaderPeek(); + sb.Append(ch); + ch = Char.ToUpper(ch, CultureInfo.InvariantCulture); + if (ch != 'I' && ch != 'L' && ch != 'S') { + errors.Error(Line, Col, "Invalid type character: U" + ch); + } + } + } + try { + if (isOct) { + ReaderRead(); + ulong number = 0L; + for (int i = 0; i < digit.Length; ++i) { + number = number * 8 + digit[i] - '0'; + } + if (ch == 'S') { + if (unsigned) + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (ushort)number, LiteralFormat.OctalNumber); + else + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (short)number, LiteralFormat.OctalNumber); + } else if (ch == '%' || ch == 'I') { + if (unsigned) + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (uint)number, LiteralFormat.OctalNumber); + else + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (int)number, LiteralFormat.OctalNumber); + } else if (ch == '&' || ch == 'L') { + if (unsigned) + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (ulong)number, LiteralFormat.OctalNumber); + else + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), (long)number, LiteralFormat.OctalNumber); + } else { + if (number > uint.MaxValue) { + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), unchecked((long)number), LiteralFormat.OctalNumber); + } else { + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), unchecked((int)number), LiteralFormat.OctalNumber); + } + } + } + LiteralFormat literalFormat = isHex ? LiteralFormat.HexadecimalNumber : LiteralFormat.DecimalNumber; + if (ch == 'S') { + ReaderRead(); + if (unsigned) + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), UInt16.Parse(digit, isHex ? NumberStyles.HexNumber : NumberStyles.Number), literalFormat); + else + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), Int16.Parse(digit, isHex ? NumberStyles.HexNumber : NumberStyles.Number), literalFormat); + } else if (ch == '%' || ch == 'I') { + ReaderRead(); + if (unsigned) + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), UInt32.Parse(digit, isHex ? NumberStyles.HexNumber : NumberStyles.Number), literalFormat); + else + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), Int32.Parse(digit, isHex ? NumberStyles.HexNumber : NumberStyles.Number), literalFormat); + } else if (ch == '&' || ch == 'L') { + ReaderRead(); + if (unsigned) + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), UInt64.Parse(digit, isHex ? NumberStyles.HexNumber : NumberStyles.Number), literalFormat); + else + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), Int64.Parse(digit, isHex ? NumberStyles.HexNumber : NumberStyles.Number), literalFormat); + } else if (isHex) { + ulong number = UInt64.Parse(digit, NumberStyles.HexNumber); + if (number > uint.MaxValue) { + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), unchecked((long)number), literalFormat); + } else { + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), unchecked((int)number), literalFormat); + } + } + } catch (OverflowException ex) { + errors.Error(Line, Col, ex.Message); + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), 0, LiteralFormat.None); + } catch (FormatException) { + errors.Error(Line, Col, String.Format("{0} is not a parseable number", digit)); + return new Token(Tokens.LiteralInteger, x, y, sb.ToString(), 0, LiteralFormat.None); + } + } + Token nextToken = null; // if we accidently read a 'dot' + if (!isDouble && ReaderPeek() == '.') { // read floating point number + ReaderRead(); + if (ReaderPeek() != -1 && Char.IsDigit((char)ReaderPeek())) { + isDouble = true; // double is default + if (isHex || isOct) { + errors.Error(Line, Col, String.Format("No hexadecimal or oktadecimal floating point values allowed")); + } + digit += '.'; + while (ReaderPeek() != -1 && Char.IsDigit((char)ReaderPeek())){ // read decimal digits beyond the dot + digit += (char)ReaderRead(); + } + } else { + nextToken = new Token(Tokens.Dot, Col - 1, Line); + } + } + + if (ReaderPeek() != -1 && PeekUpperChar() == 'E') { // read exponent + isDouble = true; + digit += (char)ReaderRead(); + if (ReaderPeek() != -1 && (ReaderPeek() == '-' || ReaderPeek() == '+')) { + digit += (char)ReaderRead(); + } + while (ReaderPeek() != -1 && Char.IsDigit((char)ReaderPeek())) { // read exponent value + digit += (char)ReaderRead(); + } + } + + if (ReaderPeek() != -1) { + switch (PeekUpperChar()) { + case 'R': + case '#': + ReaderRead(); + isDouble = true; + break; + case 'D': + case '@': + ReaderRead(); + isDecimal = true; + break; + case 'F': + case '!': + ReaderRead(); + isSingle = true; + break; + } + } + + try { + if (isSingle) { + return new Token(Tokens.LiteralSingle, x, y, sb.ToString(), Single.Parse(digit, CultureInfo.InvariantCulture), LiteralFormat.DecimalNumber); + } + if (isDecimal) { + return new Token(Tokens.LiteralDecimal, x, y, sb.ToString(), Decimal.Parse(digit, NumberStyles.Currency | NumberStyles.AllowExponent, CultureInfo.InvariantCulture), LiteralFormat.DecimalNumber); + } + if (isDouble) { + return new Token(Tokens.LiteralDouble, x, y, sb.ToString(), Double.Parse(digit, CultureInfo.InvariantCulture), LiteralFormat.DecimalNumber); + } + } catch (FormatException) { + errors.Error(Line, Col, String.Format("{0} is not a parseable number", digit)); + if (isSingle) + return new Token(Tokens.LiteralSingle, x, y, sb.ToString(), 0f, LiteralFormat.DecimalNumber); + if (isDecimal) + return new Token(Tokens.LiteralDecimal, x, y, sb.ToString(), 0m, LiteralFormat.DecimalNumber); + if (isDouble) + return new Token(Tokens.LiteralDouble, x, y, sb.ToString(), 0.0, LiteralFormat.DecimalNumber); + } + Token token; + try { + token = new Token(Tokens.LiteralInteger, x, y, sb.ToString(), Int32.Parse(digit, isHex ? NumberStyles.HexNumber : NumberStyles.Number), isHex ? LiteralFormat.HexadecimalNumber : LiteralFormat.DecimalNumber); + } catch (Exception) { + try { + token = new Token(Tokens.LiteralInteger, x, y, sb.ToString(), Int64.Parse(digit, isHex ? NumberStyles.HexNumber : NumberStyles.Number), isHex ? LiteralFormat.HexadecimalNumber : LiteralFormat.DecimalNumber); + } catch (FormatException) { + errors.Error(Line, Col, String.Format("{0} is not a parseable number", digit)); + // fallback, when nothing helps :) + token = new Token(Tokens.LiteralInteger, x, y, sb.ToString(), 0, LiteralFormat.DecimalNumber); + } catch (OverflowException) { + errors.Error(Line, Col, String.Format("{0} is too long for a integer literal", digit)); + // fallback, when nothing helps :) + token = new Token(Tokens.LiteralInteger, x, y, sb.ToString(), 0, LiteralFormat.DecimalNumber); + } + } + token.next = nextToken; + return token; + } + + void ReadPreprocessorDirective() + { + Location start = new Location(Col - 1, Line); + string directive = ReadIdent('#'); + // TODO : expression parser for PP directives + // needed for proper conversion to e. g. C# + string argument = ReadToEndOfLine(); + this.specialTracker.AddPreprocessingDirective(new PreprocessingDirective(directive, argument.Trim(), start, new Location(start.Column + directive.Length + argument.Length, start.Line))); + } + + string ReadDate() + { + char ch = '\0'; + sb.Length = 0; + int nextChar; + while ((nextChar = ReaderRead()) != -1) { + ch = (char)nextChar; + if (ch == '#') { + break; + } else if (ch == '\n') { + errors.Error(Line, Col, String.Format("No return allowed inside Date literal")); + } else { + sb.Append(ch); + } + } + if (ch != '#') { + errors.Error(Line, Col, String.Format("End of File reached before Date literal terminated")); + } + return sb.ToString(); + } + + string ReadString() + { + char ch = '\0'; + sb.Length = 0; + int nextChar; + while ((nextChar = ReaderRead()) != -1) { + ch = (char)nextChar; + if (ch == '"') { + if (ReaderPeek() != -1 && ReaderPeek() == '"') { + sb.Append('"'); + ReaderRead(); + } else { + break; + } + } else if (ch == '\n') { + errors.Error(Line, Col, String.Format("No return allowed inside String literal")); + } else { + sb.Append(ch); + } + } + if (ch != '"') { + errors.Error(Line, Col, String.Format("End of File reached before String terminated ")); + } + return sb.ToString(); + } + + void ReadComment() + { + Location startPos = new Location(Col, Line); + sb.Length = 0; + StringBuilder curWord = specialCommentHash != null ? new StringBuilder() : null; + int missingApostrophes = 2; // no. of ' missing until it is a documentation comment + int nextChar; + while ((nextChar = ReaderRead()) != -1) { + char ch = (char)nextChar; + + if (HandleLineEnd(ch)) { + break; + } + + sb.Append(ch); + + if (missingApostrophes > 0) { + if (ch == '\'' || ch == '\u2018' || ch == '\u2019') { + if (--missingApostrophes == 0) { + specialTracker.StartComment(CommentType.Documentation, isAtLineBegin, startPos); + sb.Length = 0; + } + } else { + specialTracker.StartComment(CommentType.SingleLine, isAtLineBegin, startPos); + missingApostrophes = 0; + } + } + + if (specialCommentHash != null) { + if (Char.IsLetter(ch)) { + curWord.Append(ch); + } else { + string tag = curWord.ToString(); + curWord.Length = 0; + if (specialCommentHash.ContainsKey(tag)) { + Location p = new Location(Col, Line); + string comment = ch + ReadToEndOfLine(); + this.TagComments.Add(new TagComment(tag, comment, isAtLineBegin, p, new Location(Col, Line))); + sb.Append(comment); + break; + } + } + } + } + if (missingApostrophes > 0) { + specialTracker.StartComment(CommentType.SingleLine, isAtLineBegin, startPos); + } + specialTracker.AddString(sb.ToString()); + specialTracker.FinishComment(new Location(Col, Line)); + } + + Token ReadOperator(char ch) + { + int x = Col - 1; + int y = Line; + switch(ch) { + case '+': + switch (ReaderPeek()) { + case '=': + ReaderRead(); + return new Token(Tokens.PlusAssign, x, y); + default: + break; + } + return new Token(Tokens.Plus, x, y); + case '-': + switch (ReaderPeek()) { + case '=': + ReaderRead(); + return new Token(Tokens.MinusAssign, x, y); + default: + break; + } + return new Token(Tokens.Minus, x, y); + case '*': + switch (ReaderPeek()) { + case '=': + ReaderRead(); + return new Token(Tokens.TimesAssign, x, y); + default: + break; + } + return new Token(Tokens.Times, x, y, "*"); + case '/': + switch (ReaderPeek()) { + case '=': + ReaderRead(); + return new Token(Tokens.DivAssign, x, y); + default: + break; + } + return new Token(Tokens.Div, x, y); + case '\\': + switch (ReaderPeek()) { + case '=': + ReaderRead(); + return new Token(Tokens.DivIntegerAssign, x, y); + default: + break; + } + return new Token(Tokens.DivInteger, x, y); + case '&': + switch (ReaderPeek()) { + case '=': + ReaderRead(); + return new Token(Tokens.ConcatStringAssign, x, y); + default: + break; + } + return new Token(Tokens.ConcatString, x, y); + case '^': + switch (ReaderPeek()) { + case '=': + ReaderRead(); + return new Token(Tokens.PowerAssign, x, y); + default: + break; + } + return new Token(Tokens.Power, x, y); + case ':': + if (ReaderPeek() == '=') { + ReaderRead(); + return new Token(Tokens.ColonAssign, x, y); + } + return new Token(Tokens.Colon, x, y); + case '=': + return new Token(Tokens.Assign, x, y); + case '<': + switch (ReaderPeek()) { + case '=': + ReaderRead(); + return new Token(Tokens.LessEqual, x, y); + case '>': + ReaderRead(); + return new Token(Tokens.NotEqual, x, y); + case '<': + ReaderRead(); + switch (ReaderPeek()) { + case '=': + ReaderRead(); + return new Token(Tokens.ShiftLeftAssign, x, y); + default: + break; + } + return new Token(Tokens.ShiftLeft, x, y); + } + return new Token(Tokens.LessThan, x, y); + case '>': + switch (ReaderPeek()) { + case '=': + ReaderRead(); + return new Token(Tokens.GreaterEqual, x, y); + case '>': + ReaderRead(); + if (ReaderPeek() != -1) { + switch (ReaderPeek()) { + case '=': + ReaderRead(); + return new Token(Tokens.ShiftRightAssign, x, y); + default: + break; + } + } + return new Token(Tokens.ShiftRight, x, y); + } + return new Token(Tokens.GreaterThan, x, y); + case ',': + return new Token(Tokens.Comma, x, y); + case '.': + // Prevent OverflowException when Peek returns -1 + int tmp = ReaderPeek(); int tmp2 = ReaderPeek(1); + if (tmp > 0) { + if (char.IsDigit((char)tmp)) + return ReadDigit('.', Col); + else if ((char)tmp == '@') { + ReaderRead(); + return new Token(Tokens.DotAt, x, y); + } else if ((char)tmp == '.' && tmp2 > 0 && (char)tmp2 == '.') { + ReaderRead(); ReaderRead(); + return new Token(Tokens.TripleDot, x, y); + } + } + return new Token(Tokens.Dot, x, y); + case '(': + return new Token(Tokens.OpenParenthesis, x, y); + case ')': + return new Token(Tokens.CloseParenthesis, x, y); + case '{': + return new Token(Tokens.OpenCurlyBrace, x, y); + case '}': + return new Token(Tokens.CloseCurlyBrace, x, y); + case '?': + return new Token(Tokens.QuestionMark, x, y); + case '!': + return new Token(Tokens.ExclamationMark, x, y); + } + return null; + } + #endregion + + #region XML Readers + Token ReadXmlProcessingInstruction(int x, int y) + { + sb.Length = 0; + int nextChar = -1; + + while (ReaderPeek() != '?' || ReaderPeek(1) != '>') { + nextChar = ReaderRead(); + if (nextChar == -1) + break; + sb.Append((char)nextChar); + } + + ReaderSkip("?>".Length); + + return new Token(Tokens.XmlProcessingInstruction, new Location(x, y), new Location(Col, Line), sb.ToString(), null, LiteralFormat.None); + } + + Token ReadXmlCommentOrCData(int x, int y) + { + sb.Length = 0; + int nextChar = -1; + + if (string.CompareOrdinal(ReaderPeekString("--".Length), "--") == 0) { + ReaderSkip("--".Length); + while ((nextChar = ReaderRead()) != -1) { + sb.Append((char)nextChar); + if (string.CompareOrdinal(ReaderPeekString("-->".Length), "-->") == 0) { + ReaderSkip("-->".Length); + return new Token(Tokens.XmlComment, new Location(x, y), new Location(Col, Line), sb.ToString(), null, LiteralFormat.None); + } + } + } + + if (string.CompareOrdinal(ReaderPeekString("[CDATA[".Length), "[CDATA[") == 0) { + ReaderSkip("[CDATA[".Length); + while ((nextChar = ReaderRead()) != -1) { + sb.Append((char)nextChar); + if (string.CompareOrdinal(ReaderPeekString("]]>".Length), "]]>") == 0) { + ReaderSkip("]]>".Length); + return new Token(Tokens.XmlCData, new Location(x, y), new Location(Col, Line), sb.ToString(), null, LiteralFormat.None); + } + } + } + + return new Token(Tokens.XmlComment, new Location(x, y), new Location(Col, Line), sb.ToString(), null, LiteralFormat.None); + } + + string ReadXmlContent(char ch) + { + sb.Length = 0; + while (true) { + sb.Append(ch); + int next = ReaderPeek(); + + if (next == -1 || next == '<') + break; + ch = (char)ReaderRead(); + } + + return sb.ToString(); + } + + string ReadXmlString(char terminator) + { + char ch = '\0'; + sb.Length = 0; + int nextChar; + while ((nextChar = ReaderRead()) != -1) { + ch = (char)nextChar; + if (ch == terminator) { + break; + } else if (ch == '\n') { + errors.Error(Line, Col, String.Format("No return allowed inside String literal")); + } else { + sb.Append(ch); + } + } + if (ch != terminator) { + errors.Error(Line, Col, String.Format("End of File reached before String terminated ")); + } + return sb.ToString(); + } + + string ReadXmlIdent(char ch) + { + sb.Length = 0; + sb.Append(ch); + + int peek; + + while ((peek = ReaderPeek()) != -1 && (peek == ':' || XmlConvert.IsNCNameChar((char)peek))) { + sb.Append((char)ReaderRead()); + } + + return sb.ToString(); + } + #endregion + + char PeekUpperChar() + { + return Char.ToUpper((char)ReaderPeek(), CultureInfo.InvariantCulture); + } + + /// + /// Skips to the end of the current code block. + /// For this, the lexer must have read the next token AFTER the token opening the + /// block (so that Lexer.Token is the block-opening token, not Lexer.LookAhead). + /// After the call, Lexer.LookAhead will be the block-closing token. + /// + public void SkipCurrentBlock(int targetToken) + { + int lastKind = -1; + int kind = lastToken.kind; + while (kind != Tokens.EOF && + !(lastKind == Tokens.End && kind == targetToken)) + { + lastKind = kind; + NextToken(); + kind = lastToken.kind; + } + } + + public void SetInitialContext(SnippetType type) + { + ef.SetContext(type); + } + + public VBLexerMemento Export() + { + return new VBLexerMemento() { + Column = Col, + Line = Line, + EncounteredLineContinuation = encounteredLineContinuation, + ExpressionFinder = ef.Export(), + InXmlMode = inXmlMode, + IsAtLineBegin = isAtLineBegin, + LineEnd = lineEnd, + PrevTokenKind = prevToken.kind, + MisreadExclamationMarkAsTypeCharacter = misreadExclamationMarkAsTypeCharacter, + XmlModeInfoStack = new Stack(xmlModeStack.Select(i => (XmlModeInfo)i.Clone()).Reverse()) + }; + } + + LATextReader reader; + int col = 1; + int line = 1; + + protected Errors errors = new Errors(); + + protected Token lastToken = null; + protected Token curToken = null; + protected Token peekToken = null; + + string[] specialCommentTags = null; + protected Hashtable specialCommentHash = null; + List tagComments = new List(); + protected StringBuilder sb = new StringBuilder(); + protected SpecialTracker specialTracker = new SpecialTracker(); + + // used for the original value of strings (with escape sequences). + protected StringBuilder originalValue = new StringBuilder(); + + public bool SkipAllComments { get; set; } + public bool EvaluateConditionalCompilation { get; set; } + public virtual IDictionary ConditionalCompilationSymbols { + get { throw new NotSupportedException(); } + } + + protected static IEnumerable GetSymbols (string symbols) + { + if (!string.IsNullOrEmpty(symbols)) { + foreach (string symbol in symbols.Split (';', ' ', '\t')) { + string s = symbol.Trim (); + if (s.Length == 0) + continue; + yield return s; + } + } + } + + public void SetConditionalCompilationSymbols (string symbols) + { + throw new NotSupportedException (); + } + + protected int Line { + get { + return line; + } + } + protected int Col { + get { + return col; + } + } + + protected bool recordRead = false; + protected StringBuilder recordedText = new StringBuilder (); + + protected int ReaderRead() + { + int val = reader.Read(); + if (recordRead && val >= 0) + recordedText.Append ((char)val); + if ((val == '\r' && reader.Peek() != '\n') || val == '\n') { + ++line; + col = 1; + LineBreak(); + } else if (val >= 0) { + col++; + } + return val; + } + + protected int ReaderPeek() + { + return reader.Peek(); + } + + protected int ReaderPeek(int step) + { + return reader.Peek(step); + } + + protected void ReaderSkip(int steps) + { + for (int i = 0; i < steps; i++) { + ReaderRead(); + } + } + + protected string ReaderPeekString(int length) + { + StringBuilder builder = new StringBuilder(); + + for (int i = 0; i < length; i++) { + int peek = ReaderPeek(i); + if (peek != -1) + builder.Append((char)peek); + } + + return builder.ToString(); + } + + public void SetInitialLocation(Location location) + { + if (lastToken != null || curToken != null || peekToken != null) + throw new InvalidOperationException(); + this.line = location.Line; + this.col = location.Column; + } + + public Errors Errors { + get { + return errors; + } + } + + /// + /// Returns the comments that had been read and containing tag key words. + /// + public List TagComments { + get { + return tagComments; + } + } + + public SpecialTracker SpecialTracker { + get { + return specialTracker; + } + } + + /// + /// Special comment tags are tags like TODO, HACK or UNDONE which are read by the lexer and stored in . + /// + public string[] SpecialCommentTags { + get { + return specialCommentTags; + } + set { + specialCommentTags = value; + specialCommentHash = null; + if (specialCommentTags != null && specialCommentTags.Length > 0) { + specialCommentHash = new Hashtable(); + foreach (string str in specialCommentTags) { + specialCommentHash.Add(str, null); + } + } + } + } + + /// + /// The current Token. + /// + public Token Token { + get { +// Console.WriteLine("Call to Token"); + return lastToken; + } + } + + /// + /// The next Token (The after call) . + /// + public Token LookAhead { + get { +// Console.WriteLine("Call to LookAhead"); + return curToken; + } + } + + #region System.IDisposable interface implementation + public virtual void Dispose() + { + reader.Close(); + reader = null; + errors = null; + lastToken = curToken = peekToken = null; + specialCommentHash = null; + tagComments = null; + sb = originalValue = null; + } + #endregion + + /// + /// Must be called before a peek operation. + /// + public void StartPeek() + { + peekToken = curToken; + } + + /// + /// Gives back the next token. A second call to Peek() gives the next token after the last call for Peek() and so on. + /// + /// An object. + public Token Peek() + { +// Console.WriteLine("Call to Peek"); + if (peekToken.next == null) { + peekToken.next = Next(); + } + peekToken = peekToken.next; + return peekToken; + } + + protected static bool IsIdentifierPart(int ch) + { + if (ch == 95) return true; // 95 = '_' + if (ch == -1) return false; + return char.IsLetterOrDigit((char)ch); // accept unicode letters + } + + protected static bool IsHex(char digit) + { + return Char.IsDigit(digit) || ('A' <= digit && digit <= 'F') || ('a' <= digit && digit <= 'f'); + } + + protected int GetHexNumber(char digit) + { + if (Char.IsDigit(digit)) { + return digit - '0'; + } + if ('A' <= digit && digit <= 'F') { + return digit - 'A' + 0xA; + } + if ('a' <= digit && digit <= 'f') { + return digit - 'a' + 0xA; + } + errors.Error(line, col, String.Format("Invalid hex number '" + digit + "'")); + return 0; + } + protected Location lastLineEnd = new Location (1, 1); + protected Location curLineEnd = new Location (1, 1); + protected void LineBreak () + { + lastLineEnd = curLineEnd; + curLineEnd = new Location (col - 1, line); + } + protected bool HandleLineEnd(char ch) + { + // Handle MS-DOS or MacOS line ends. + if (ch == '\r') { + if (reader.Peek() == '\n') { // MS-DOS line end '\r\n' + ReaderRead(); // LineBreak (); called by ReaderRead (); + return true; + } else { // assume MacOS line end which is '\r' + LineBreak (); + return true; + } + } + if (ch == '\n') { + LineBreak (); + return true; + } + return false; + } + + protected void SkipToEndOfLine() + { + int nextChar; + while ((nextChar = reader.Read()) != -1) { + if (nextChar == '\r') { + if (reader.Peek() == '\n') + reader.Read(); + nextChar = '\n'; + } + if (nextChar == '\n') { + ++line; + col = 1; + break; + } + } + } + + protected string ReadToEndOfLine() + { + sb.Length = 0; + int nextChar; + while ((nextChar = reader.Read()) != -1) { + char ch = (char)nextChar; + + if (nextChar == '\r') { + if (reader.Peek() == '\n') + reader.Read(); + nextChar = '\n'; + } + // Return read string, if EOL is reached + if (nextChar == '\n') { + ++line; + col = 1; + return sb.ToString(); + } + + sb.Append(ch); + } + + // Got EOF before EOL + string retStr = sb.ToString(); + col += retStr.Length; + return retStr; + } + + public event EventHandler SavepointReached; + + protected virtual void OnSavepointReached(SavepointEventArgs e) + { + if (SavepointReached != null) { + SavepointReached(this, e); + } + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/VBLexerMemento.cs b/ICSharpCode.NRefactory.VB/Lexer/VBLexerMemento.cs new file mode 100644 index 000000000..148475ccd --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/VBLexerMemento.cs @@ -0,0 +1,22 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public sealed class VBLexerMemento + { + public int Line { get; set; } + public int Column { get; set; } + public int PrevTokenKind { get; set; } + public bool LineEnd { get; set; } + public bool IsAtLineBegin { get; set; } + public bool MisreadExclamationMarkAsTypeCharacter { get; set; } + public bool EncounteredLineContinuation { get; set; } + public ExpressionFinderState ExpressionFinder { get; set; } + public Stack XmlModeInfoStack { get; set; } + public bool InXmlMode { get; set; } + } +} diff --git a/ICSharpCode.NRefactory.VB/Lexer/XmlModeInfo.cs b/ICSharpCode.NRefactory.VB/Lexer/XmlModeInfo.cs new file mode 100644 index 000000000..4f3ef71e9 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Lexer/XmlModeInfo.cs @@ -0,0 +1,29 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public class XmlModeInfo : ICloneable + { + public bool inXmlTag, inXmlCloseTag, isDocumentStart; + public int level; + + public XmlModeInfo(bool isSpecial) + { + level = isSpecial ? -1 : 0; + inXmlTag = inXmlCloseTag = isDocumentStart = false; + } + + public object Clone() + { + return new XmlModeInfo(false) { + inXmlCloseTag = this.inXmlCloseTag, + inXmlTag = this.inXmlTag, + isDocumentStart = this.isDocumentStart, + level = this.level + }; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Location.cs b/ICSharpCode.NRefactory.VB/Location.cs new file mode 100644 index 000000000..825207f05 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Location.cs @@ -0,0 +1,121 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; + +namespace ICSharpCode.NRefactory.VB +{ + /// + /// A line/column position. + /// NRefactory lines/columns are counting from one. + /// + public struct Location : IComparable, IEquatable + { + public static readonly Location Empty = new Location(-1, -1); + + public Location(int column, int line) + { + x = column; + y = line; + } + + int x, y; + + public int X { + get { return x; } + set { x = value; } + } + + public int Y { + get { return y; } + set { y = value; } + } + + public int Line { + get { return y; } + set { y = value; } + } + + public int Column { + get { return x; } + set { x = value; } + } + + public bool IsEmpty { + get { + return x <= 0 && y <= 0; + } + } + + public override string ToString() + { + return string.Format("(Line {1}, Col {0})", this.x, this.y); + } + + public override int GetHashCode() + { + return unchecked (87 * x.GetHashCode() ^ y.GetHashCode()); + } + + public override bool Equals(object obj) + { + if (!(obj is Location)) return false; + return (Location)obj == this; + } + + public bool Equals(Location other) + { + return this == other; + } + + public static bool operator ==(Location a, Location b) + { + return a.x == b.x && a.y == b.y; + } + + public static bool operator !=(Location a, Location b) + { + return a.x != b.x || a.y != b.y; + } + + public static bool operator <(Location a, Location b) + { + if (a.y < b.y) + return true; + else if (a.y == b.y) + return a.x < b.x; + else + return false; + } + + public static bool operator >(Location a, Location b) + { + if (a.y > b.y) + return true; + else if (a.y == b.y) + return a.x > b.x; + else + return false; + } + + public static bool operator <=(Location a, Location b) + { + return !(a > b); + } + + public static bool operator >=(Location a, Location b) + { + return !(a < b); + } + + public int CompareTo(Location other) + { + if (this == other) + return 0; + if (this < other) + return -1; + else + return 1; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/OperatorPrecedence.cs b/ICSharpCode.NRefactory.VB/OperatorPrecedence.cs new file mode 100644 index 000000000..eced7d595 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/OperatorPrecedence.cs @@ -0,0 +1,84 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB +{ + /// + /// Stores the operator precedences for the output visitor. + /// + static class OperatorPrecedence + { + static readonly Dictionary vbDict = MakePrecedenceTable( + new BinaryOperatorType[] { BinaryOperatorType.Power }, + new BinaryOperatorType[] { BinaryOperatorType.Multiply, BinaryOperatorType.Divide }, + new BinaryOperatorType[] { BinaryOperatorType.DivideInteger }, + new BinaryOperatorType[] { BinaryOperatorType.Modulus }, + new BinaryOperatorType[] { BinaryOperatorType.Add, BinaryOperatorType.Subtract }, + new BinaryOperatorType[] { BinaryOperatorType.Concat }, + new BinaryOperatorType[] { BinaryOperatorType.ShiftLeft, BinaryOperatorType.ShiftRight }, + new BinaryOperatorType[] { + BinaryOperatorType.Equality, BinaryOperatorType.InEquality, + BinaryOperatorType.LessThan, BinaryOperatorType.LessThanOrEqual, + BinaryOperatorType.GreaterThan, BinaryOperatorType.GreaterThanOrEqual, + BinaryOperatorType.ReferenceEquality, BinaryOperatorType.ReferenceInequality, + BinaryOperatorType.Like + }, + new BinaryOperatorType[] { BinaryOperatorType.LogicalAnd, BinaryOperatorType.BitwiseAnd }, + new BinaryOperatorType[] { BinaryOperatorType.LogicalOr, BinaryOperatorType.BitwiseOr }, + new BinaryOperatorType[] { BinaryOperatorType.ExclusiveOr } + ); + + static readonly Dictionary csharpDict = MakePrecedenceTable( + new BinaryOperatorType[] { BinaryOperatorType.Multiply, BinaryOperatorType.Divide, BinaryOperatorType.Modulus }, + new BinaryOperatorType[] { BinaryOperatorType.Add, BinaryOperatorType.Subtract }, + new BinaryOperatorType[] { BinaryOperatorType.ShiftLeft, BinaryOperatorType.ShiftRight }, + new BinaryOperatorType[] { + BinaryOperatorType.LessThan, BinaryOperatorType.LessThanOrEqual, + BinaryOperatorType.GreaterThan, BinaryOperatorType.GreaterThanOrEqual, + }, + new BinaryOperatorType[] { BinaryOperatorType.Equality, BinaryOperatorType.InEquality }, + new BinaryOperatorType[] { BinaryOperatorType.BitwiseAnd }, + new BinaryOperatorType[] { BinaryOperatorType.ExclusiveOr }, + new BinaryOperatorType[] { BinaryOperatorType.BitwiseOr }, + new BinaryOperatorType[] { BinaryOperatorType.LogicalAnd, BinaryOperatorType.LogicalOr }, + new BinaryOperatorType[] { BinaryOperatorType.NullCoalescing } + ); + + // create a dictionary operator->precedence (higher value = higher precedence) + static Dictionary MakePrecedenceTable(params BinaryOperatorType[][] input) + { + Dictionary dict = new Dictionary(); + for (int i = 0; i < input.Length; i++) { + foreach (BinaryOperatorType op in input[i]) { + dict.Add(op, input.Length - i); + } + } + return dict; + } + + public static int ComparePrecedenceVB(BinaryOperatorType op1, BinaryOperatorType op2) + { + int p1 = GetOperatorPrecedence(vbDict, op1); + int p2 = GetOperatorPrecedence(vbDict, op2); + return p1.CompareTo(p2); + } + + public static int ComparePrecedenceCSharp(BinaryOperatorType op1, BinaryOperatorType op2) + { + int p1 = GetOperatorPrecedence(csharpDict, op1); + int p2 = GetOperatorPrecedence(csharpDict, op2); + return p1.CompareTo(p2); + } + + static int GetOperatorPrecedence(Dictionary dict, BinaryOperatorType op) + { + int p; + dict.TryGetValue(op, out p); + return p; + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Parser/Errors.cs b/ICSharpCode.NRefactory.VB/Parser/Errors.cs new file mode 100644 index 000000000..6cd0b2e24 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Parser/Errors.cs @@ -0,0 +1,50 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Text; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public delegate void ErrorCodeProc(int line, int col, int n); + public delegate void ErrorMsgProc(int line, int col, string msg); + + public class Errors + { + int count = 0; // number of errors detected + public ErrorCodeProc SynErr; + public ErrorCodeProc SemErr; + public ErrorMsgProc Error; + StringBuilder errorText = new StringBuilder(); + + public string ErrorOutput { + get { + return errorText.ToString(); + } + } + + public Errors() + { + SynErr = new ErrorCodeProc(DefaultCodeError); // syntactic errors + SemErr = new ErrorCodeProc(DefaultCodeError); // semantic errors + Error = new ErrorMsgProc(DefaultMsgError); // user defined string based errors + } + + public int Count { + get { + return count; + } + } + + void DefaultCodeError(int line, int col, int n) + { + errorText.AppendLine(String.Format("-- line {0} col {1}: error {2}", line, col, n)); + count++; + } + + void DefaultMsgError(int line, int col, string s) { + errorText.AppendLine(String.Format("-- line {0} col {1}: {2}", line, col, s)); + count++; + } + } // Errors +} diff --git a/ICSharpCode.NRefactory.VB/Parser/ModifierList.cs b/ICSharpCode.NRefactory.VB/Parser/ModifierList.cs new file mode 100644 index 000000000..4b6ba47fb --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Parser/ModifierList.cs @@ -0,0 +1,69 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + internal class ModifierList + { + Modifiers cur; + Location location = new Location(-1, -1); + + public Modifiers Modifier { + get { + return cur; + } + } + + public Location GetDeclarationLocation(Location keywordLocation) + { + if(location.IsEmpty) { + return keywordLocation; + } + return location; + } + +// public Location Location { +// get { +// return location; +// } +// set { +// location = value; +// } +// } + + public bool isNone { get { return cur == Modifiers.None; } } + + public bool Contains(Modifiers m) + { + return ((cur & m) != 0); + } + + public void Add(Modifiers m, Location tokenLocation) + { + if(location.IsEmpty) { + location = tokenLocation; + } + + if ((cur & m) == 0) { + cur |= m; + } else { +// parser.Error("modifier " + m + " already defined"); + } + } + +// public void Add(Modifiers m) +// { +// Add(m.cur, m.Location); +// } + + public void Check(Modifiers allowed) + { + Modifiers wrong = cur & ~allowed; + if (wrong != Modifiers.None) { +// parser.Error("modifier(s) " + wrong + " not allowed here"); + } + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Parser/ParamModifierList.cs b/ICSharpCode.NRefactory.VB/Parser/ParamModifierList.cs new file mode 100644 index 000000000..6e6ed55c0 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Parser/ParamModifierList.cs @@ -0,0 +1,49 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using ICSharpCode.NRefactory.VB.Dom; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + internal class ParamModifierList + { + ParameterModifiers cur; + VBParser parser; + + public ParameterModifiers Modifier { + get { + return cur; + } + } + + public ParamModifierList(VBParser parser) + { + this.parser = parser; + cur = ParameterModifiers.None; + } + + public bool isNone { get { return cur == ParameterModifiers.None; } } + + public void Add(ParameterModifiers m) + { + if ((cur & m) == 0) { + cur |= m; + } else { + parser.Error("param modifier " + m + " already defined"); + } + } + + public void Add(ParamModifierList m) + { + Add(m.cur); + } + + public void Check() + { + if((cur & ParameterModifiers.In) != 0 && + (cur & ParameterModifiers.Ref) != 0) { + parser.Error("ByRef and ByVal are not allowed at the same time."); + } + } + } +} diff --git a/ICSharpCode.NRefactory.VB/Parser/Parser.cs b/ICSharpCode.NRefactory.VB/Parser/Parser.cs new file mode 100644 index 000000000..4a5f94598 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Parser/Parser.cs @@ -0,0 +1,5477 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; +using System.Text; +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Parser; +using ASTAttribute = ICSharpCode.NRefactory.VB.Dom.Attribute; + + + + +namespace ICSharpCode.NRefactory.VB.Parser { + + +// ---------------------------------------------------------------------------- +// Parser +// ---------------------------------------------------------------------------- +//! A Coco/R Parser +partial class VBParser +{ + public const int _EOF = 0; + public const int _EOL = 1; + public const int _ident = 2; + public const int _LiteralString = 3; + public const int _LiteralCharacter = 4; + public const int _LiteralInteger = 5; + public const int _LiteralDouble = 6; + public const int _LiteralSingle = 7; + public const int _LiteralDecimal = 8; + public const int _LiteralDate = 9; + public const int _XmlOpenTag = 10; + public const int _XmlCloseTag = 11; + public const int _XmlStartInlineVB = 12; + public const int _XmlEndInlineVB = 13; + public const int _XmlCloseTagEmptyElement = 14; + public const int _XmlOpenEndTag = 15; + public const int _XmlContent = 16; + public const int _XmlComment = 17; + public const int _XmlCData = 18; + public const int _XmlProcessingInstruction = 19; + public const int maxT = 238; // usings = new List(); + + Expect(137); + Location startPos = t.Location; + Using u; + + ImportClause(out u); + if (u != null) { usings.Add(u); } + while (la.kind == 22) { + Get(); + ImportClause(out u); + if (u != null) { usings.Add(u); } + } + EndOfStmt(); + UsingDeclaration usingDeclaration = new UsingDeclaration(usings); + usingDeclaration.StartLocation = startPos; + usingDeclaration.EndLocation = t.Location; + AddChild(usingDeclaration); + + } + + void GlobalAttributeSection() { + Expect(40); + Location startPos = t.Location; + if (la.kind == 65) { + Get(); + } else if (la.kind == 155) { + Get(); + } else SynErr(243); + string attributeTarget = t.val != null ? t.val.ToLower(System.Globalization.CultureInfo.InvariantCulture) : null; + List attributes = new List(); + ASTAttribute attribute; + + Expect(21); + Attribute(out attribute); + attributes.Add(attribute); + while (NotFinalComma()) { + if (la.kind == 22) { + Get(); + if (la.kind == 65) { + Get(); + } else if (la.kind == 155) { + Get(); + } else SynErr(244); + Expect(21); + } + Attribute(out attribute); + attributes.Add(attribute); + } + if (la.kind == 22) { + Get(); + } + Expect(39); + EndOfStmt(); + AttributeSection section = new AttributeSection { + AttributeTarget = attributeTarget, + Attributes = attributes, + StartLocation = startPos, + EndLocation = t.EndLocation + }; + AddChild(section); + + } + + void NamespaceMemberDecl() { + ModifierList m = new ModifierList(); + AttributeSection section; + List attributes = new List(); + string qualident; + + if (la.kind == 160) { + Get(); + Location startPos = t.Location; + + Qualident(out qualident); + INode node = new NamespaceDeclaration(qualident); + node.StartLocation = startPos; + AddChild(node); + BlockStart(node); + + EndOfStmt(); + NamespaceBody(); + node.EndLocation = t.Location; + BlockEnd(); + + } else if (StartOf(3)) { + while (la.kind == 40) { + AttributeSection(out section); + attributes.Add(section); + } + while (StartOf(4)) { + TypeModifier(m); + } + NonModuleDeclaration(m, attributes); + } else SynErr(245); + } + + void OptionValue(ref bool val) { + if (la.kind == 171) { + Get(); + val = true; + } else if (la.kind == 170) { + Get(); + val = false; + } else SynErr(246); + } + + void ImportClause(out Using u) { + string qualident = null; + TypeReference aliasedType = null; + u = null; + + if (StartOf(5)) { + Qualident(out qualident); + if (la.kind == 20) { + Get(); + TypeName(out aliasedType); + } + if (qualident != null && qualident.Length > 0) { + if (aliasedType != null) { + u = new Using(qualident, aliasedType); + } else { + u = new Using(qualident); + } + } + + } else if (la.kind == 10) { + string prefix = null; + Get(); + Identifier(); + prefix = t.val; + Expect(20); + Expect(3); + u = new Using(t.literalValue as string, prefix); + Expect(11); + } else SynErr(247); + } + + void Qualident(out string qualident) { + string name; + qualidentBuilder.Length = 0; + + Identifier(); + qualidentBuilder.Append(t.val); + while (DotAndIdentOrKw()) { + Expect(26); + IdentifierOrKeyword(out name); + qualidentBuilder.Append('.'); qualidentBuilder.Append(name); + } + qualident = qualidentBuilder.ToString(); + } + + void TypeName(out TypeReference typeref) { + ArrayList rank = null; Location startLocation = la.Location; + NonArrayTypeName(out typeref, false); + ArrayTypeModifiers(out rank); + if (typeref != null) { + if (rank != null) { + typeref.RankSpecifier = (int[])rank.ToArray(typeof(int)); + } + typeref.StartLocation = startLocation; + typeref.EndLocation = t.EndLocation; + } + + } + + void Identifier() { + if (StartOf(6)) { + IdentifierForFieldDeclaration(); + } else if (la.kind == 98) { + Get(); + } else SynErr(248); + } + + void NamespaceBody() { + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + while (StartOf(2)) { + NamespaceMemberDecl(); + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + } + Expect(113); + Expect(160); + EndOfStmt(); + } + + void AttributeSection(out AttributeSection section) { + string attributeTarget = ""; + List attributes = new List(); + ASTAttribute attribute; + Location startLocation = la.Location; + + Expect(40); + if (IsLocalAttrTarget()) { + if (la.kind == 119) { + Get(); + attributeTarget = "event"; + } else if (la.kind == 195) { + Get(); + attributeTarget = "return"; + } else if (StartOf(5)) { + Identifier(); + string val = t.val.ToLower(System.Globalization.CultureInfo.InvariantCulture); + if (val != "field" || val != "method" || + val != "module" || val != "param" || + val != "property" || val != "type") + Error("attribute target specifier (event, return, field," + + "method, module, param, property, or type) expected"); + attributeTarget = t.val; + + } else SynErr(249); + Expect(21); + } + Attribute(out attribute); + attributes.Add(attribute); + while (NotFinalComma()) { + Expect(22); + Attribute(out attribute); + attributes.Add(attribute); + } + if (la.kind == 22) { + Get(); + } + Expect(39); + section = new AttributeSection { + AttributeTarget = attributeTarget, + Attributes = attributes, + StartLocation = startLocation, + EndLocation = t.EndLocation + }; + + } + + void TypeModifier(ModifierList m) { + switch (la.kind) { + case 188: { + Get(); + m.Add(Modifiers.Public, t.Location); + break; + } + case 187: { + Get(); + m.Add(Modifiers.Protected, t.Location); + break; + } + case 125: { + Get(); + m.Add(Modifiers.Internal, t.Location); + break; + } + case 185: { + Get(); + m.Add(Modifiers.Private, t.Location); + break; + } + case 200: { + Get(); + m.Add(Modifiers.Static, t.Location); + break; + } + case 199: { + Get(); + m.Add(Modifiers.New, t.Location); + break; + } + case 156: { + Get(); + m.Add(Modifiers.Abstract, t.Location); + break; + } + case 166: { + Get(); + m.Add(Modifiers.Sealed, t.Location); + break; + } + case 183: { + Get(); + m.Add(Modifiers.Partial, t.Location); + break; + } + default: SynErr(250); break; + } + } + + void NonModuleDeclaration(ModifierList m, List attributes) { + TypeReference typeRef = null; + List baseInterfaces = null; + + switch (la.kind) { + case 84: { + m.Check(Modifiers.Classes); + Get(); + TypeDeclaration newType = new TypeDeclaration(m.Modifier, attributes); + newType.StartLocation = t.Location; + AddChild(newType); + BlockStart(newType); + + newType.Type = ClassType.Class; + + Identifier(); + newType.Name = t.val; + TypeParameterList(newType.Templates); + EndOfStmt(); + newType.BodyStartLocation = t.Location; + if (la.kind == 140) { + ClassBaseType(out typeRef); + SafeAdd(newType, newType.BaseTypes, typeRef); + } + while (la.kind == 136) { + TypeImplementsClause(out baseInterfaces); + newType.BaseTypes.AddRange(baseInterfaces); + } + ClassBody(newType); + Expect(113); + Expect(84); + newType.EndLocation = t.EndLocation; + EndOfStmt(); + BlockEnd(); + + break; + } + case 155: { + Get(); + m.Check(Modifiers.VBModules); + TypeDeclaration newType = new TypeDeclaration(m.Modifier, attributes); + AddChild(newType); + BlockStart(newType); + newType.StartLocation = m.GetDeclarationLocation(t.Location); + newType.Type = ClassType.Module; + + Identifier(); + newType.Name = t.val; + EndOfStmt(); + newType.BodyStartLocation = t.Location; + ModuleBody(newType); + BlockEnd(); + + break; + } + case 209: { + Get(); + m.Check(Modifiers.VBStructures); + TypeDeclaration newType = new TypeDeclaration(m.Modifier, attributes); + AddChild(newType); + BlockStart(newType); + newType.StartLocation = m.GetDeclarationLocation(t.Location); + newType.Type = ClassType.Struct; + + Identifier(); + newType.Name = t.val; + TypeParameterList(newType.Templates); + EndOfStmt(); + newType.BodyStartLocation = t.Location; + while (la.kind == 136) { + TypeImplementsClause(out baseInterfaces); + newType.BaseTypes.AddRange(baseInterfaces); + } + StructureBody(newType); + BlockEnd(); + + break; + } + case 115: { + Get(); + m.Check(Modifiers.VBEnums); + TypeDeclaration newType = new TypeDeclaration(m.Modifier, attributes); + newType.StartLocation = m.GetDeclarationLocation(t.Location); + AddChild(newType); + BlockStart(newType); + + newType.Type = ClassType.Enum; + + Identifier(); + newType.Name = t.val; + if (la.kind == 63) { + Get(); + NonArrayTypeName(out typeRef, false); + SafeAdd(newType, newType.BaseTypes, typeRef); + } + EndOfStmt(); + newType.BodyStartLocation = t.Location; + EnumBody(newType); + BlockEnd(); + + break; + } + case 142: { + Get(); + m.Check(Modifiers.VBInterfacs); + TypeDeclaration newType = new TypeDeclaration(m.Modifier, attributes); + newType.StartLocation = m.GetDeclarationLocation(t.Location); + AddChild(newType); + BlockStart(newType); + newType.Type = ClassType.Interface; + + Identifier(); + newType.Name = t.val; + TypeParameterList(newType.Templates); + EndOfStmt(); + newType.BodyStartLocation = t.Location; + while (la.kind == 140) { + InterfaceBase(out baseInterfaces); + newType.BaseTypes.AddRange(baseInterfaces); + } + InterfaceBody(newType); + BlockEnd(); + + break; + } + case 103: { + Get(); + m.Check(Modifiers.VBDelegates); + DelegateDeclaration delegateDeclr = new DelegateDeclaration(m.Modifier, attributes); + delegateDeclr.ReturnType = new TypeReference("System.Void", true); + delegateDeclr.StartLocation = m.GetDeclarationLocation(t.Location); + List p = new List(); + + if (la.kind == 210) { + Get(); + Identifier(); + delegateDeclr.Name = t.val; + TypeParameterList(delegateDeclr.Templates); + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + delegateDeclr.Parameters = p; + } + } else if (la.kind == 127) { + Get(); + Identifier(); + delegateDeclr.Name = t.val; + TypeParameterList(delegateDeclr.Templates); + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + delegateDeclr.Parameters = p; + } + if (la.kind == 63) { + Get(); + TypeReference type; + TypeName(out type); + delegateDeclr.ReturnType = type; + } + } else SynErr(251); + delegateDeclr.EndLocation = t.EndLocation; + EndOfStmt(); + AddChild(delegateDeclr); + + break; + } + default: SynErr(252); break; + } + } + + void TypeParameterList(List templates) { + TemplateDefinition template; + + if (la.kind == Tokens.OpenParenthesis && Peek(1).kind == Tokens.Of) { + Expect(37); + Expect(169); + TypeParameter(out template); + if (template != null) templates.Add(template); + + while (la.kind == 22) { + Get(); + TypeParameter(out template); + if (template != null) templates.Add(template); + + } + Expect(38); + } + } + + void TypeParameter(out TemplateDefinition template) { + VarianceModifier modifier = VarianceModifier.Invariant; Location startLocation = la.Location; + if (la.kind == 138 || (la.kind == Tokens.Out && IsIdentifierToken(Peek(1)))) { + if (la.kind == 138) { + Get(); + modifier = VarianceModifier.Contravariant; + } else { + Expect(178); + modifier = VarianceModifier.Covariant; + } + } + Identifier(); + template = new TemplateDefinition(t.val, null) { VarianceModifier = modifier }; + if (la.kind == 63) { + TypeParameterConstraints(template); + } + if (template != null) { + template.StartLocation = startLocation; + template.EndLocation = t.EndLocation; + } + + } + + void TypeParameterConstraints(TemplateDefinition template) { + TypeReference constraint; + + Expect(63); + if (la.kind == 35) { + Get(); + TypeParameterConstraint(out constraint); + if (constraint != null) { template.Bases.Add(constraint); } + while (la.kind == 22) { + Get(); + TypeParameterConstraint(out constraint); + if (constraint != null) { template.Bases.Add(constraint); } + } + Expect(36); + } else if (StartOf(8)) { + TypeParameterConstraint(out constraint); + if (constraint != null) { template.Bases.Add(constraint); } + } else SynErr(253); + } + + void TypeParameterConstraint(out TypeReference constraint) { + constraint = null; Location startLocation = la.Location; + if (la.kind == 84) { + Get(); + constraint = TypeReference.ClassConstraint; + } else if (la.kind == 209) { + Get(); + constraint = TypeReference.StructConstraint; + } else if (la.kind == 162) { + Get(); + constraint = TypeReference.NewConstraint; + } else if (StartOf(9)) { + TypeName(out constraint); + } else SynErr(254); + } + + void ClassBaseType(out TypeReference typeRef) { + typeRef = null; + + Expect(140); + TypeName(out typeRef); + EndOfStmt(); + } + + void TypeImplementsClause(out List baseInterfaces) { + baseInterfaces = new List(); + TypeReference type = null; + + Expect(136); + TypeName(out type); + if (type != null) baseInterfaces.Add(type); + + while (la.kind == 22) { + Get(); + TypeName(out type); + if (type != null) baseInterfaces.Add(type); + } + EndOfStmt(); + } + + void ClassBody(TypeDeclaration newType) { + AttributeSection section; + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + while (StartOf(10)) { + List attributes = new List(); + ModifierList m = new ModifierList(); + + while (la.kind == 40) { + AttributeSection(out section); + attributes.Add(section); + } + while (StartOf(11)) { + MemberModifier(m); + } + ClassMemberDecl(m, attributes); + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + } + } + + void ModuleBody(TypeDeclaration newType) { + AttributeSection section; + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + while (StartOf(10)) { + List attributes = new List(); + ModifierList m = new ModifierList(); + + while (la.kind == 40) { + AttributeSection(out section); + attributes.Add(section); + } + while (StartOf(11)) { + MemberModifier(m); + } + ClassMemberDecl(m, attributes); + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + } + Expect(113); + Expect(155); + newType.EndLocation = t.EndLocation; + EndOfStmt(); + } + + void StructureBody(TypeDeclaration newType) { + AttributeSection section; + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + while (StartOf(10)) { + List attributes = new List(); + ModifierList m = new ModifierList(); + + while (la.kind == 40) { + AttributeSection(out section); + attributes.Add(section); + } + while (StartOf(11)) { + MemberModifier(m); + } + StructureMemberDecl(m, attributes); + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + } + Expect(113); + Expect(209); + newType.EndLocation = t.EndLocation; + EndOfStmt(); + } + + void NonArrayTypeName(out TypeReference typeref, bool canBeUnbound) { + string name; + typeref = null; + bool isGlobal = false; + + if (StartOf(12)) { + if (la.kind == 130) { + Get(); + Expect(26); + isGlobal = true; + } + QualIdentAndTypeArguments(out typeref, canBeUnbound); + typeref.IsGlobal = isGlobal; + while (la.kind == 26) { + Get(); + TypeReference nestedTypeRef; + QualIdentAndTypeArguments(out nestedTypeRef, canBeUnbound); + typeref = new InnerClassTypeReference(typeref, nestedTypeRef.Type, nestedTypeRef.GenericTypes); + } + } else if (la.kind == 168) { + Get(); + typeref = new TypeReference("System.Object", true); + if (la.kind == 33) { + Get(); + List typeArguments = new List(1); + if (typeref != null) typeArguments.Add(typeref); + typeref = new TypeReference("System.Nullable", typeArguments) { IsKeyword = true }; + + } + } else if (StartOf(13)) { + PrimitiveTypeName(out name); + typeref = new TypeReference(name, true); + if (la.kind == 33) { + Get(); + List typeArguments = new List(1); + if (typeref != null) typeArguments.Add(typeref); + typeref = new TypeReference("System.Nullable", typeArguments) { IsKeyword = true }; + + } + } else SynErr(255); + } + + void EnumBody(TypeDeclaration newType) { + FieldDeclaration f; + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + while (StartOf(14)) { + EnumMemberDecl(out f); + AddChild(f); + + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + } + Expect(113); + Expect(115); + newType.EndLocation = t.EndLocation; + EndOfStmt(); + } + + void InterfaceBase(out List bases) { + TypeReference type; + bases = new List(); + + Expect(140); + TypeName(out type); + if (type != null) bases.Add(type); + while (la.kind == 22) { + Get(); + TypeName(out type); + if (type != null) bases.Add(type); + } + EndOfStmt(); + } + + void InterfaceBody(TypeDeclaration newType) { + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + while (StartOf(15)) { + InterfaceMemberDecl(); + while (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + } + Expect(113); + Expect(142); + newType.EndLocation = t.EndLocation; + EndOfStmt(); + } + + void FormalParameterList(List parameter) { + ParameterDeclarationExpression p; + FormalParameter(out p); + if (p != null) parameter.Add(p); + while (la.kind == 22) { + Get(); + FormalParameter(out p); + if (p != null) parameter.Add(p); + } + } + + void MemberModifier(ModifierList m) { + switch (la.kind) { + case 156: { + Get(); + m.Add(Modifiers.Abstract, t.Location); + break; + } + case 102: { + Get(); + m.Add(Modifiers.Default, t.Location); + break; + } + case 125: { + Get(); + m.Add(Modifiers.Internal, t.Location); + break; + } + case 199: { + Get(); + m.Add(Modifiers.New, t.Location); + break; + } + case 181: { + Get(); + m.Add(Modifiers.Override, t.Location); + break; + } + case 157: { + Get(); + m.Add(Modifiers.Abstract, t.Location); + break; + } + case 185: { + Get(); + m.Add(Modifiers.Private, t.Location); + break; + } + case 187: { + Get(); + m.Add(Modifiers.Protected, t.Location); + break; + } + case 188: { + Get(); + m.Add(Modifiers.Public, t.Location); + break; + } + case 166: { + Get(); + m.Add(Modifiers.Sealed, t.Location); + break; + } + case 167: { + Get(); + m.Add(Modifiers.Sealed, t.Location); + break; + } + case 200: { + Get(); + m.Add(Modifiers.Static, t.Location); + break; + } + case 180: { + Get(); + m.Add(Modifiers.Virtual, t.Location); + break; + } + case 179: { + Get(); + m.Add(Modifiers.Overloads, t.Location); + break; + } + case 190: { + Get(); + m.Add(Modifiers.ReadOnly, t.Location); + break; + } + case 235: { + Get(); + m.Add(Modifiers.WriteOnly, t.Location); + break; + } + case 234: { + Get(); + m.Add(Modifiers.WithEvents, t.Location); + break; + } + case 105: { + Get(); + m.Add(Modifiers.Dim, t.Location); + break; + } + case 183: { + Get(); + m.Add(Modifiers.Partial, t.Location); + break; + } + default: SynErr(256); break; + } + } + + void ClassMemberDecl(ModifierList m, List attributes) { + StructureMemberDecl(m, attributes); + } + + void StructureMemberDecl(ModifierList m, List attributes) { + TypeReference type = null; + List p = new List(); + Statement stmt = null; + List variableDeclarators = new List(); + List templates = new List(); + + switch (la.kind) { + case 84: case 103: case 115: case 142: case 155: case 209: { + NonModuleDeclaration(m, attributes); + break; + } + case 210: { + Get(); + Location startPos = t.Location; + + if (StartOf(5)) { + string name = String.Empty; + MethodDeclaration methodDeclaration; List handlesClause = null; + List implementsClause = null; + + Identifier(); + name = t.val; + m.Check(Modifiers.VBMethods); + + TypeParameterList(templates); + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + if (la.kind == 134 || la.kind == 136) { + if (la.kind == 136) { + ImplementsClause(out implementsClause); + } else { + HandlesClause(out handlesClause); + } + } + Location endLocation = t.EndLocation; + if (IsMustOverride(m)) { + EndOfStmt(); + methodDeclaration = new MethodDeclaration { + Name = name, Modifier = m.Modifier, Parameters = p, Attributes = attributes, + StartLocation = m.GetDeclarationLocation(startPos), EndLocation = endLocation, + TypeReference = new TypeReference("System.Void", true), + Templates = templates, + HandlesClause = handlesClause, + InterfaceImplementations = implementsClause + }; + AddChild(methodDeclaration); + + } else if (la.kind == 1) { + Get(); + methodDeclaration = new MethodDeclaration { + Name = name, Modifier = m.Modifier, Parameters = p, Attributes = attributes, + StartLocation = m.GetDeclarationLocation(startPos), EndLocation = endLocation, + TypeReference = new TypeReference("System.Void", true), + Templates = templates, + HandlesClause = handlesClause, + InterfaceImplementations = implementsClause + }; + AddChild(methodDeclaration); + + if (ParseMethodBodies) { + Block(out stmt); + Expect(113); + Expect(210); + } else { + // don't parse method body + lexer.SkipCurrentBlock(Tokens.Sub); stmt = new BlockStatement(); + } + + methodDeclaration.Body = (BlockStatement)stmt; + methodDeclaration.Body.EndLocation = t.EndLocation; + EndOfStmt(); + } else SynErr(257); + } else if (la.kind == 162) { + Get(); + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + m.Check(Modifiers.Constructors); + Location constructorEndLocation = t.EndLocation; + Expect(1); + if (ParseMethodBodies) { + Block(out stmt); + Expect(113); + Expect(210); + } else { + // don't parse method body + lexer.SkipCurrentBlock(Tokens.Sub); stmt = new BlockStatement(); + } + + Location endLocation = t.EndLocation; + EndOfStmt(); + ConstructorDeclaration cd = new ConstructorDeclaration("New", m.Modifier, p, attributes); + cd.StartLocation = m.GetDeclarationLocation(startPos); + cd.EndLocation = constructorEndLocation; + cd.Body = (BlockStatement)stmt; + cd.Body.EndLocation = endLocation; + AddChild(cd); + + } else SynErr(258); + break; + } + case 127: { + Get(); + m.Check(Modifiers.VBMethods); + string name = String.Empty; + Location startPos = t.Location; + MethodDeclaration methodDeclaration;List handlesClause = null; + List implementsClause = null; + AttributeSection returnTypeAttributeSection = null; + + Identifier(); + name = t.val; + TypeParameterList(templates); + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + if (la.kind == 63) { + Get(); + while (la.kind == 40) { + AttributeSection(out returnTypeAttributeSection); + if (returnTypeAttributeSection != null) { + returnTypeAttributeSection.AttributeTarget = "return"; + attributes.Add(returnTypeAttributeSection); + } + + } + TypeName(out type); + } + if(type == null) { + type = new TypeReference("System.Object", true); + } + + if (la.kind == 134 || la.kind == 136) { + if (la.kind == 136) { + ImplementsClause(out implementsClause); + } else { + HandlesClause(out handlesClause); + } + } + Location endLocation = t.EndLocation; + if (IsMustOverride(m)) { + EndOfStmt(); + methodDeclaration = new MethodDeclaration { + Name = name, Modifier = m.Modifier, TypeReference = type, + Parameters = p, Attributes = attributes, + StartLocation = m.GetDeclarationLocation(startPos), + EndLocation = endLocation, + HandlesClause = handlesClause, + Templates = templates, + InterfaceImplementations = implementsClause + }; + + AddChild(methodDeclaration); + + } else if (la.kind == 1) { + Get(); + methodDeclaration = new MethodDeclaration { + Name = name, Modifier = m.Modifier, TypeReference = type, + Parameters = p, Attributes = attributes, + StartLocation = m.GetDeclarationLocation(startPos), + EndLocation = endLocation, + Templates = templates, + HandlesClause = handlesClause, + InterfaceImplementations = implementsClause + }; + + AddChild(methodDeclaration); + + if (ParseMethodBodies) { + Block(out stmt); + Expect(113); + Expect(127); + } else { + // don't parse method body + lexer.SkipCurrentBlock(Tokens.Function); stmt = new BlockStatement(); + } + methodDeclaration.Body = (BlockStatement)stmt; + methodDeclaration.Body.StartLocation = methodDeclaration.EndLocation; + methodDeclaration.Body.EndLocation = t.EndLocation; + + EndOfStmt(); + } else SynErr(259); + break; + } + case 101: { + Get(); + m.Check(Modifiers.VBExternalMethods); + Location startPos = t.Location; + CharsetModifier charsetModifer = CharsetModifier.None; + string library = String.Empty; + string alias = null; + string name = String.Empty; + + if (StartOf(16)) { + Charset(out charsetModifer); + } + if (la.kind == 210) { + Get(); + Identifier(); + name = t.val; + Expect(149); + Expect(3); + library = t.literalValue as string; + if (la.kind == 59) { + Get(); + Expect(3); + alias = t.literalValue as string; + } + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + EndOfStmt(); + DeclareDeclaration declareDeclaration = new DeclareDeclaration(name, m.Modifier, null, p, attributes, library, alias, charsetModifer); + declareDeclaration.StartLocation = m.GetDeclarationLocation(startPos); + declareDeclaration.EndLocation = t.EndLocation; + AddChild(declareDeclaration); + + } else if (la.kind == 127) { + Get(); + Identifier(); + name = t.val; + Expect(149); + Expect(3); + library = t.literalValue as string; + if (la.kind == 59) { + Get(); + Expect(3); + alias = t.literalValue as string; + } + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + if (la.kind == 63) { + Get(); + TypeName(out type); + } + EndOfStmt(); + DeclareDeclaration declareDeclaration = new DeclareDeclaration(name, m.Modifier, type, p, attributes, library, alias, charsetModifer); + declareDeclaration.StartLocation = m.GetDeclarationLocation(startPos); + declareDeclaration.EndLocation = t.EndLocation; + AddChild(declareDeclaration); + + } else SynErr(260); + break; + } + case 119: { + Get(); + m.Check(Modifiers.VBEvents); + Location startPos = t.Location; + EventDeclaration eventDeclaration; + string name = String.Empty; + List implementsClause = null; + + Identifier(); + name= t.val; + if (la.kind == 63) { + Get(); + TypeName(out type); + } else if (StartOf(17)) { + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + } else SynErr(261); + if (la.kind == 136) { + ImplementsClause(out implementsClause); + } + eventDeclaration = new EventDeclaration { + Name = name, TypeReference = type, Modifier = m.Modifier, + Parameters = p, Attributes = attributes, InterfaceImplementations = implementsClause, + StartLocation = m.GetDeclarationLocation(startPos), + EndLocation = t.EndLocation + }; + AddChild(eventDeclaration); + + EndOfStmt(); + break; + } + case 2: case 58: case 62: case 64: case 65: case 66: case 67: case 70: case 87: case 104: case 107: case 116: case 121: case 126: case 133: case 139: case 143: case 146: case 147: case 170: case 176: case 178: case 184: case 203: case 212: case 213: case 223: case 224: case 230: { + m.Check(Modifiers.Fields); + FieldDeclaration fd = new FieldDeclaration(attributes, null, m.Modifier); + + IdentifierForFieldDeclaration(); + string name = t.val; + fd.StartLocation = m.GetDeclarationLocation(t.Location); + VariableDeclaratorPartAfterIdentifier(variableDeclarators, name); + while (la.kind == 22) { + Get(); + VariableDeclarator(variableDeclarators); + } + EndOfStmt(); + fd.EndLocation = t.EndLocation; + fd.Fields = variableDeclarators; + AddChild(fd); + + break; + } + case 88: { + m.Check(Modifiers.Fields); + Get(); + m.Add(Modifiers.Const, t.Location); + FieldDeclaration fd = new FieldDeclaration(attributes, type, m.Modifier); + fd.StartLocation = m.GetDeclarationLocation(t.Location); + List constantDeclarators = new List(); + + ConstantDeclarator(constantDeclarators); + while (la.kind == 22) { + Get(); + ConstantDeclarator(constantDeclarators); + } + fd.Fields = constantDeclarators; + fd.EndLocation = t.Location; + + EndOfStmt(); + fd.EndLocation = t.EndLocation; + AddChild(fd); + + break; + } + case 186: { + Get(); + m.Check(Modifiers.VBProperties); + Location startPos = t.Location; + List implementsClause = null; + AttributeSection returnTypeAttributeSection = null; + Expression initializer = null; + + Identifier(); + string propertyName = t.val; + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + if (la.kind == 63) { + Get(); + while (la.kind == 40) { + AttributeSection(out returnTypeAttributeSection); + if (returnTypeAttributeSection != null) { + returnTypeAttributeSection.AttributeTarget = "return"; + attributes.Add(returnTypeAttributeSection); + } + + } + if (IsNewExpression()) { + ObjectCreateExpression(out initializer); + if (initializer is ObjectCreateExpression) { + type = ((ObjectCreateExpression)initializer).CreateType.Clone(); + } else { + type = ((ArrayCreateExpression)initializer).CreateType.Clone(); + } + + } else if (StartOf(9)) { + TypeName(out type); + } else SynErr(262); + } + if (la.kind == 20) { + Get(); + Expr(out initializer); + } + if (la.kind == 136) { + ImplementsClause(out implementsClause); + } + EndOfStmt(); + if (IsMustOverride(m) || IsAutomaticProperty()) { + PropertyDeclaration pDecl = new PropertyDeclaration(propertyName, type, m.Modifier, attributes); + pDecl.StartLocation = m.GetDeclarationLocation(startPos); + pDecl.EndLocation = t.Location; + pDecl.TypeReference = type; + pDecl.InterfaceImplementations = implementsClause; + pDecl.Parameters = p; + if (initializer != null) + pDecl.Initializer = initializer; + AddChild(pDecl); + + } else if (StartOf(18)) { + PropertyDeclaration pDecl = new PropertyDeclaration(propertyName, type, m.Modifier, attributes); + pDecl.StartLocation = m.GetDeclarationLocation(startPos); + pDecl.EndLocation = t.Location; + pDecl.BodyStart = t.Location; + pDecl.TypeReference = type; + pDecl.InterfaceImplementations = implementsClause; + pDecl.Parameters = p; + PropertyGetRegion getRegion; + PropertySetRegion setRegion; + + AccessorDecls(out getRegion, out setRegion); + Expect(113); + Expect(186); + EndOfStmt(); + pDecl.GetRegion = getRegion; + pDecl.SetRegion = setRegion; + pDecl.BodyEnd = t.Location; // t = EndOfStmt; not "Property" + AddChild(pDecl); + + } else SynErr(263); + break; + } + case 98: { + Get(); + Location startPos = t.Location; + Expect(119); + m.Check(Modifiers.VBCustomEvents); + EventAddRemoveRegion eventAccessorDeclaration; + EventAddRegion addHandlerAccessorDeclaration = null; + EventRemoveRegion removeHandlerAccessorDeclaration = null; + EventRaiseRegion raiseEventAccessorDeclaration = null; + List implementsClause = null; + + Identifier(); + string customEventName = t.val; + Expect(63); + TypeName(out type); + if (la.kind == 136) { + ImplementsClause(out implementsClause); + } + EndOfStmt(); + while (StartOf(19)) { + EventAccessorDeclaration(out eventAccessorDeclaration); + if(eventAccessorDeclaration is EventAddRegion) + { + addHandlerAccessorDeclaration = (EventAddRegion)eventAccessorDeclaration; + } + else if(eventAccessorDeclaration is EventRemoveRegion) + { + removeHandlerAccessorDeclaration = (EventRemoveRegion)eventAccessorDeclaration; + } + else if(eventAccessorDeclaration is EventRaiseRegion) + { + raiseEventAccessorDeclaration = (EventRaiseRegion)eventAccessorDeclaration; + } + + } + Expect(113); + Expect(119); + EndOfStmt(); + if(addHandlerAccessorDeclaration == null) + { + Error("Need to provide AddHandler accessor."); + } + + if(removeHandlerAccessorDeclaration == null) + { + Error("Need to provide RemoveHandler accessor."); + } + + if(raiseEventAccessorDeclaration == null) + { + Error("Need to provide RaiseEvent accessor."); + } + + EventDeclaration decl = new EventDeclaration { + TypeReference = type, Name = customEventName, Modifier = m.Modifier, + Attributes = attributes, + StartLocation = m.GetDeclarationLocation(startPos), + EndLocation = t.EndLocation, + AddRegion = addHandlerAccessorDeclaration, + RemoveRegion = removeHandlerAccessorDeclaration, + RaiseRegion = raiseEventAccessorDeclaration + }; + AddChild(decl); + + break; + } + case 161: case 172: case 232: { + ConversionType opConversionType = ConversionType.None; + if (la.kind == 161 || la.kind == 232) { + if (la.kind == 232) { + Get(); + opConversionType = ConversionType.Implicit; + } else { + Get(); + opConversionType = ConversionType.Explicit; + } + } + Expect(172); + m.Check(Modifiers.VBOperators); + Location startPos = t.Location; + TypeReference returnType = NullTypeReference.Instance; + TypeReference operandType = NullTypeReference.Instance; + OverloadableOperatorType operatorType; + AttributeSection section; + ParameterDeclarationExpression param; + List parameters = new List(); + + OverloadableOperator(out operatorType); + Expect(37); + FormalParameter(out param); + if (param != null) parameters.Add(param); + if (la.kind == 22) { + Get(); + FormalParameter(out param); + if (param != null) parameters.Add(param); + } + Expect(38); + Location endPos = t.EndLocation; + if (la.kind == 63) { + Get(); + while (la.kind == 40) { + AttributeSection(out section); + if (section != null) { + section.AttributeTarget = "return"; + attributes.Add(section); + } + } + TypeName(out returnType); + endPos = t.EndLocation; + } + Expect(1); + Block(out stmt); + Expect(113); + Expect(172); + EndOfStmt(); + OperatorDeclaration operatorDeclaration = new OperatorDeclaration { + Modifier = m.Modifier, + Attributes = attributes, + Parameters = parameters, + TypeReference = returnType, + OverloadableOperator = operatorType, + ConversionType = opConversionType, + Body = (BlockStatement)stmt, + StartLocation = m.GetDeclarationLocation(startPos), + EndLocation = endPos + }; + operatorDeclaration.Body.StartLocation = startPos; + operatorDeclaration.Body.EndLocation = t.Location; + AddChild(operatorDeclaration); + + break; + } + default: SynErr(264); break; + } + } + + void EnumMemberDecl(out FieldDeclaration f) { + Expression expr = null;List attributes = new List(); + AttributeSection section = null; + VariableDeclaration varDecl = null; + + while (la.kind == 40) { + AttributeSection(out section); + attributes.Add(section); + } + Identifier(); + f = new FieldDeclaration(attributes); + varDecl = new VariableDeclaration(t.val); + f.Fields.Add(varDecl); + f.StartLocation = varDecl.StartLocation = t.Location; + + if (la.kind == 20) { + Get(); + Expr(out expr); + varDecl.Initializer = expr; + } + f.EndLocation = varDecl.EndLocation = t.EndLocation; + EndOfStmt(); + } + + void InterfaceMemberDecl() { + TypeReference type =null; + List p = new List(); + List templates = new List(); + AttributeSection section, returnTypeAttributeSection = null; + ModifierList mod = new ModifierList(); + List attributes = new List(); + string name; + + if (StartOf(20)) { + while (la.kind == 40) { + AttributeSection(out section); + attributes.Add(section); + } + while (StartOf(11)) { + MemberModifier(mod); + } + if (la.kind == 119) { + Get(); + mod.Check(Modifiers.VBInterfaceEvents); + Location startLocation = t.Location; + + Identifier(); + name = t.val; + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + if (la.kind == 63) { + Get(); + TypeName(out type); + } + EndOfStmt(); + EventDeclaration ed = new EventDeclaration { + Name = name, TypeReference = type, Modifier = mod.Modifier, + Parameters = p, Attributes = attributes, + StartLocation = startLocation, EndLocation = t.EndLocation + }; + AddChild(ed); + + } else if (la.kind == 210) { + Get(); + Location startLocation = t.Location; + mod.Check(Modifiers.VBInterfaceMethods); + + Identifier(); + name = t.val; + TypeParameterList(templates); + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + EndOfStmt(); + MethodDeclaration md = new MethodDeclaration { + Name = name, + Modifier = mod.Modifier, + Parameters = p, + Attributes = attributes, + TypeReference = new TypeReference("System.Void", true), + StartLocation = startLocation, + EndLocation = t.EndLocation, + Templates = templates + }; + AddChild(md); + + } else if (la.kind == 127) { + Get(); + mod.Check(Modifiers.VBInterfaceMethods); + Location startLocation = t.Location; + + Identifier(); + name = t.val; + TypeParameterList(templates); + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + if (la.kind == 63) { + Get(); + while (la.kind == 40) { + AttributeSection(out returnTypeAttributeSection); + } + TypeName(out type); + } + if(type == null) { + type = new TypeReference("System.Object", true); + } + MethodDeclaration md = new MethodDeclaration { + Name = name, Modifier = mod.Modifier, + TypeReference = type, Parameters = p, Attributes = attributes + }; + if (returnTypeAttributeSection != null) { + returnTypeAttributeSection.AttributeTarget = "return"; + md.Attributes.Add(returnTypeAttributeSection); + } + md.StartLocation = startLocation; + md.EndLocation = t.EndLocation; + md.Templates = templates; + AddChild(md); + + EndOfStmt(); + } else if (la.kind == 186) { + Get(); + Location startLocation = t.Location; + mod.Check(Modifiers.VBInterfaceProperties); + + Identifier(); + name = t.val; + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + if (la.kind == 63) { + Get(); + TypeName(out type); + } + if(type == null) { + type = new TypeReference("System.Object", true); + } + + EndOfStmt(); + PropertyDeclaration pd = new PropertyDeclaration(name, type, mod.Modifier, attributes); + pd.Parameters = p; + pd.EndLocation = t.EndLocation; + pd.StartLocation = startLocation; + AddChild(pd); + + } else SynErr(265); + } else if (StartOf(21)) { + NonModuleDeclaration(mod, attributes); + } else SynErr(266); + } + + void Expr(out Expression expr) { + expr = null; Location startLocation = la.Location; + if (IsQueryExpression()) { + QueryExpr(out expr); + } else if (la.kind == 127 || la.kind == 210) { + LambdaExpr(out expr); + } else if (StartOf(22)) { + DisjunctionExpr(out expr); + } else SynErr(267); + if (expr != null) { + expr.StartLocation = startLocation; + expr.EndLocation = t.EndLocation; + } + + } + + void ImplementsClause(out List baseInterfaces) { + baseInterfaces = new List(); + TypeReference type = null; + string memberName = null; + + Expect(136); + NonArrayTypeName(out type, false); + if (type != null) memberName = TypeReference.StripLastIdentifierFromType(ref type); + baseInterfaces.Add(new InterfaceImplementation(type, memberName)); + while (la.kind == 22) { + Get(); + NonArrayTypeName(out type, false); + if (type != null) memberName = TypeReference.StripLastIdentifierFromType(ref type); + baseInterfaces.Add(new InterfaceImplementation(type, memberName)); + } + } + + void HandlesClause(out List handlesClause) { + handlesClause = new List(); + string name; + + Expect(134); + EventMemberSpecifier(out name); + if (name != null) handlesClause.Add(name); + while (la.kind == 22) { + Get(); + EventMemberSpecifier(out name); + if (name != null) handlesClause.Add(name); + } + } + + void Block(out Statement stmt) { + BlockStatement blockStmt = new BlockStatement(); + /* in snippet parsing mode, t might be null */ + if (t != null) blockStmt.StartLocation = t.EndLocation; + BlockStart(blockStmt); + + while (IsEndStmtAhead() || StartOf(StatementEndOfStmt)) { + if (la.kind == 113) { + Get(); + Token first = t; + AddChild(new EndStatement() { + StartLocation = first.Location, + EndLocation = first.EndLocation } + ); + + EndOfStmt(); + } else if (StartOf(1)) { + Statement(); + EndOfStmt(); + } else SynErr(268); + } + stmt = blockStmt; + if (t != null) blockStmt.EndLocation = t.EndLocation; + BlockEnd(); + + } + + void Charset(out CharsetModifier charsetModifier) { + charsetModifier = CharsetModifier.None; + if (la.kind == 127 || la.kind == 210) { + } else if (la.kind == 62) { + Get(); + charsetModifier = CharsetModifier.Ansi; + } else if (la.kind == 66) { + Get(); + charsetModifier = CharsetModifier.Auto; + } else if (la.kind == 223) { + Get(); + charsetModifier = CharsetModifier.Unicode; + } else SynErr(269); + } + + void IdentifierForFieldDeclaration() { + switch (la.kind) { + case 2: { + Get(); + break; + } + case 58: { + Get(); + break; + } + case 62: { + Get(); + break; + } + case 64: { + Get(); + break; + } + case 65: { + Get(); + break; + } + case 66: { + Get(); + break; + } + case 67: { + Get(); + break; + } + case 70: { + Get(); + break; + } + case 87: { + Get(); + break; + } + case 104: { + Get(); + break; + } + case 107: { + Get(); + break; + } + case 116: { + Get(); + break; + } + case 121: { + Get(); + break; + } + case 126: { + Get(); + break; + } + case 133: { + Get(); + break; + } + case 139: { + Get(); + break; + } + case 143: { + Get(); + break; + } + case 146: { + Get(); + break; + } + case 147: { + Get(); + break; + } + case 170: { + Get(); + break; + } + case 176: { + Get(); + break; + } + case 178: { + Get(); + break; + } + case 184: { + Get(); + break; + } + case 203: { + Get(); + break; + } + case 212: { + Get(); + break; + } + case 213: { + Get(); + break; + } + case 223: { + Get(); + break; + } + case 224: { + Get(); + break; + } + case 230: { + Get(); + break; + } + default: SynErr(270); break; + } + } + + void VariableDeclaratorPartAfterIdentifier(List fieldDeclaration, string name) { + Expression expr = null; + TypeReference type = null; + ArrayList rank = null; + List dimension = null; + Location startLocation = t.Location; + + if (IsSize() && !IsDims()) { + ArrayInitializationModifier(out dimension); + } + if (IsDims()) { + ArrayNameModifier(out rank); + } + if (IsObjectCreation()) { + Expect(63); + ObjectCreateExpression(out expr); + if (expr is ObjectCreateExpression) { + type = ((ObjectCreateExpression)expr).CreateType.Clone(); + } else { + type = ((ArrayCreateExpression)expr).CreateType.Clone(); + } + + } else if (StartOf(23)) { + if (la.kind == 63) { + Get(); + TypeName(out type); + if (type != null) { + for (int i = fieldDeclaration.Count - 1; i >= 0; i--) { + VariableDeclaration vd = fieldDeclaration[i]; + if (vd.TypeReference.Type.Length > 0) break; + TypeReference newType = type.Clone(); + newType.RankSpecifier = vd.TypeReference.RankSpecifier; + vd.TypeReference = newType; + } + } + + } + if (type == null && (dimension != null || rank != null)) { + type = new TypeReference(""); + } + if (dimension != null) { + if(type.RankSpecifier != null) { + Error("array rank only allowed one time"); + } else { + if (rank == null) { + type.RankSpecifier = new int[] { dimension.Count - 1 }; + } else { + rank.Insert(0, dimension.Count - 1); + type.RankSpecifier = (int[])rank.ToArray(typeof(int)); + } + expr = new ArrayCreateExpression(type.Clone(), dimension); + } + } else if (rank != null) { + if(type.RankSpecifier != null) { + Error("array rank only allowed one time"); + } else { + type.RankSpecifier = (int[])rank.ToArray(typeof(int)); + } + } + + if (la.kind == 20) { + Get(); + Expr(out expr); + } + } else SynErr(271); + VariableDeclaration varDecl = new VariableDeclaration(name, expr, type); + varDecl.StartLocation = startLocation; + varDecl.EndLocation = t.Location; + fieldDeclaration.Add(varDecl); + + } + + void VariableDeclarator(List fieldDeclaration) { + Identifier(); + string name = t.val; + VariableDeclaratorPartAfterIdentifier(fieldDeclaration, name); + } + + void ConstantDeclarator(List constantDeclaration) { + Expression expr = null; + TypeReference type = null; + string name = String.Empty; + Location location; + + Identifier(); + name = t.val; location = t.Location; + if (la.kind == 63) { + Get(); + TypeName(out type); + } + Expect(20); + Expr(out expr); + VariableDeclaration f = new VariableDeclaration(name, expr); + f.TypeReference = type; + f.StartLocation = location; + constantDeclaration.Add(f); + + } + + void ObjectCreateExpression(out Expression oce) { + TypeReference type = null; + CollectionInitializerExpression initializer = null; + List arguments = null; + ArrayList dimensions = null; + oce = null; + Location startLocation = la.Location; + bool canBeNormal; bool canBeReDim; + + Expect(162); + if (StartOf(9)) { + NonArrayTypeName(out type, false); + if (la.kind == 37) { + Get(); + NormalOrReDimArgumentList(out arguments, out canBeNormal, out canBeReDim); + Expect(38); + if (la.kind == 35 || (la.kind == Tokens.OpenParenthesis)) { + if (la.kind == Tokens.OpenParenthesis) { + ArrayTypeModifiers(out dimensions); + CollectionInitializer(out initializer); + } else { + CollectionInitializer(out initializer); + } + } + if (canBeReDim && !canBeNormal && initializer == null) initializer = new CollectionInitializerExpression(); + } + } + if (initializer == null) { + oce = new ObjectCreateExpression(type, arguments); + } else { + if (dimensions == null) dimensions = new ArrayList(); + dimensions.Insert(0, (arguments == null) ? 0 : Math.Max(arguments.Count - 1, 0)); + type.RankSpecifier = (int[])dimensions.ToArray(typeof(int)); + ArrayCreateExpression ace = new ArrayCreateExpression(type, initializer); + ace.Arguments = arguments; + oce = ace; + } + + if (la.kind == 126 || la.kind == 233) { + if (la.kind == 233) { + MemberInitializerExpression memberInitializer = null; + Expression anonymousMember = null; + + Get(); + CollectionInitializerExpression memberInitializers = new CollectionInitializerExpression(); + memberInitializers.StartLocation = la.Location; + + Expect(35); + if (la.kind == 26 || la.kind == 147) { + MemberInitializer(out memberInitializer); + memberInitializers.CreateExpressions.Add(memberInitializer); + } else if (StartOf(24)) { + Expr(out anonymousMember); + memberInitializers.CreateExpressions.Add(anonymousMember); + } else SynErr(272); + while (la.kind == 22) { + Get(); + if (la.kind == 26 || la.kind == 147) { + MemberInitializer(out memberInitializer); + memberInitializers.CreateExpressions.Add(memberInitializer); + } else if (StartOf(24)) { + Expr(out anonymousMember); + memberInitializers.CreateExpressions.Add(anonymousMember); + } else SynErr(273); + } + Expect(36); + memberInitializers.EndLocation = t.Location; + if(oce is ObjectCreateExpression) + { + ((ObjectCreateExpression)oce).ObjectInitializer = memberInitializers; + } + + } else { + Get(); + CollectionInitializer(out initializer); + if(oce is ObjectCreateExpression) + ((ObjectCreateExpression)oce).ObjectInitializer = initializer; + + } + } + if (oce != null) { + oce.StartLocation = startLocation; + oce.EndLocation = t.EndLocation; + } + + } + + void AccessorDecls(out PropertyGetRegion getBlock, out PropertySetRegion setBlock) { + List attributes = new List(); + AttributeSection section; + getBlock = null; + setBlock = null; + + while (la.kind == 40) { + AttributeSection(out section); + attributes.Add(section); + } + if (StartOf(25)) { + GetAccessorDecl(out getBlock, attributes); + if (StartOf(26)) { + attributes = new List(); + while (la.kind == 40) { + AttributeSection(out section); + attributes.Add(section); + } + SetAccessorDecl(out setBlock, attributes); + } + } else if (StartOf(27)) { + SetAccessorDecl(out setBlock, attributes); + if (StartOf(28)) { + attributes = new List(); + while (la.kind == 40) { + AttributeSection(out section); + attributes.Add(section); + } + GetAccessorDecl(out getBlock, attributes); + } + } else SynErr(274); + } + + void EventAccessorDeclaration(out EventAddRemoveRegion eventAccessorDeclaration) { + Statement stmt = null; + List p = new List(); + AttributeSection section; + List attributes = new List(); + eventAccessorDeclaration = null; + + while (la.kind == 40) { + AttributeSection(out section); + attributes.Add(section); + } + if (la.kind == 56) { + Get(); + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + Expect(1); + Block(out stmt); + Expect(113); + Expect(56); + EndOfStmt(); + eventAccessorDeclaration = new EventAddRegion(attributes); + eventAccessorDeclaration.Block = (BlockStatement)stmt; + eventAccessorDeclaration.Parameters = p; + + } else if (la.kind == 193) { + Get(); + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + Expect(1); + Block(out stmt); + Expect(113); + Expect(193); + EndOfStmt(); + eventAccessorDeclaration = new EventRemoveRegion(attributes); + eventAccessorDeclaration.Block = (BlockStatement)stmt; + eventAccessorDeclaration.Parameters = p; + + } else if (la.kind == 189) { + Get(); + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + Expect(1); + Block(out stmt); + Expect(113); + Expect(189); + EndOfStmt(); + eventAccessorDeclaration = new EventRaiseRegion(attributes); + eventAccessorDeclaration.Block = (BlockStatement)stmt; + eventAccessorDeclaration.Parameters = p; + + } else SynErr(275); + } + + void OverloadableOperator(out OverloadableOperatorType operatorType) { + operatorType = OverloadableOperatorType.None; + switch (la.kind) { + case 31: { + Get(); + operatorType = OverloadableOperatorType.Add; + break; + } + case 30: { + Get(); + operatorType = OverloadableOperatorType.Subtract; + break; + } + case 34: { + Get(); + operatorType = OverloadableOperatorType.Multiply; + break; + } + case 24: { + Get(); + operatorType = OverloadableOperatorType.Divide; + break; + } + case 25: { + Get(); + operatorType = OverloadableOperatorType.DivideInteger; + break; + } + case 23: { + Get(); + operatorType = OverloadableOperatorType.Concat; + break; + } + case 150: { + Get(); + operatorType = OverloadableOperatorType.Like; + break; + } + case 154: { + Get(); + operatorType = OverloadableOperatorType.Modulus; + break; + } + case 60: { + Get(); + operatorType = OverloadableOperatorType.BitwiseAnd; + break; + } + case 175: { + Get(); + operatorType = OverloadableOperatorType.BitwiseOr; + break; + } + case 236: { + Get(); + operatorType = OverloadableOperatorType.ExclusiveOr; + break; + } + case 32: { + Get(); + operatorType = OverloadableOperatorType.Power; + break; + } + case 44: { + Get(); + operatorType = OverloadableOperatorType.ShiftLeft; + break; + } + case 45: { + Get(); + operatorType = OverloadableOperatorType.ShiftRight; + break; + } + case 20: { + Get(); + operatorType = OverloadableOperatorType.Equality; + break; + } + case 41: { + Get(); + operatorType = OverloadableOperatorType.InEquality; + break; + } + case 40: { + Get(); + operatorType = OverloadableOperatorType.LessThan; + break; + } + case 43: { + Get(); + operatorType = OverloadableOperatorType.LessThanOrEqual; + break; + } + case 39: { + Get(); + operatorType = OverloadableOperatorType.GreaterThan; + break; + } + case 42: { + Get(); + operatorType = OverloadableOperatorType.GreaterThanOrEqual; + break; + } + case 94: { + Get(); + operatorType = OverloadableOperatorType.CType; + break; + } + case 2: case 58: case 62: case 64: case 65: case 66: case 67: case 70: case 87: case 98: case 104: case 107: case 116: case 121: case 126: case 133: case 139: case 143: case 146: case 147: case 170: case 176: case 178: case 184: case 203: case 212: case 213: case 223: case 224: case 230: { + Identifier(); + string opName = t.val; + if (string.Equals(opName, "istrue", StringComparison.InvariantCultureIgnoreCase)) { + operatorType = OverloadableOperatorType.IsTrue; + } else if (string.Equals(opName, "isfalse", StringComparison.InvariantCultureIgnoreCase)) { + operatorType = OverloadableOperatorType.IsFalse; + } else { + Error("Invalid operator. Possible operators are '+', '-', 'Not', 'IsTrue', 'IsFalse'."); + } + + break; + } + default: SynErr(276); break; + } + } + + void FormalParameter(out ParameterDeclarationExpression p) { + AttributeSection section; + List attributes = new List(); + TypeReference type = null; + ParamModifierList mod = new ParamModifierList(this); + Expression expr = null; + p = null; + ArrayList arrayModifiers = null; + Location startLocation = la.Location; + + while (la.kind == 40) { + AttributeSection(out section); + attributes.Add(section); + } + while (StartOf(29)) { + ParameterModifier(mod); + } + Identifier(); + string parameterName = t.val; + if (IsDims()) { + ArrayTypeModifiers(out arrayModifiers); + } + if (la.kind == 63) { + Get(); + TypeName(out type); + } + if(type != null) { + if (arrayModifiers != null) { + if (type.RankSpecifier != null) { + Error("array rank only allowed one time"); + } else { + type.RankSpecifier = (int[])arrayModifiers.ToArray(typeof(int)); + } + } + } + + if (la.kind == 20) { + Get(); + Expr(out expr); + } + mod.Check(); + p = new ParameterDeclarationExpression(type, parameterName, mod.Modifier, expr); + p.Attributes = attributes; + p.StartLocation = startLocation; + p.EndLocation = t.EndLocation; + + } + + void GetAccessorDecl(out PropertyGetRegion getBlock, List attributes) { + Statement stmt = null; Modifiers m; + PropertyAccessorAccessModifier(out m); + Expect(128); + Location startLocation = t.Location; + Expect(1); + Block(out stmt); + getBlock = new PropertyGetRegion((BlockStatement)stmt, attributes); + Expect(113); + Expect(128); + getBlock.Modifier = m; + getBlock.StartLocation = startLocation; getBlock.EndLocation = t.EndLocation; + EndOfStmt(); + } + + void SetAccessorDecl(out PropertySetRegion setBlock, List attributes) { + Statement stmt = null; + List p = new List(); + Modifiers m; + + PropertyAccessorAccessModifier(out m); + Expect(198); + Location startLocation = t.Location; + if (la.kind == 37) { + Get(); + if (StartOf(7)) { + FormalParameterList(p); + } + Expect(38); + } + Expect(1); + Block(out stmt); + setBlock = new PropertySetRegion((BlockStatement)stmt, attributes); + setBlock.Modifier = m; + setBlock.Parameters = p; + + Expect(113); + Expect(198); + setBlock.StartLocation = startLocation; setBlock.EndLocation = t.EndLocation; + EndOfStmt(); + } + + void PropertyAccessorAccessModifier(out Modifiers m) { + m = Modifiers.None; + while (StartOf(30)) { + if (la.kind == 188) { + Get(); + m |= Modifiers.Public; + } else if (la.kind == 187) { + Get(); + m |= Modifiers.Protected; + } else if (la.kind == 125) { + Get(); + m |= Modifiers.Internal; + } else { + Get(); + m |= Modifiers.Private; + } + } + } + + void ArrayInitializationModifier(out List arrayModifiers) { + arrayModifiers = null; + + Expect(37); + InitializationRankList(out arrayModifiers); + Expect(38); + } + + void ArrayNameModifier(out ArrayList arrayModifiers) { + arrayModifiers = null; + + ArrayTypeModifiers(out arrayModifiers); + } + + void InitializationRankList(out List rank) { + rank = new List(); + Expression expr = null; + + Expr(out expr); + if (la.kind == 216) { + Get(); + EnsureIsZero(expr); + Expr(out expr); + } + if (expr != null) { rank.Add(expr); } + while (la.kind == 22) { + Get(); + Expr(out expr); + if (la.kind == 216) { + Get(); + EnsureIsZero(expr); + Expr(out expr); + } + if (expr != null) { rank.Add(expr); } + } + } + + void CollectionInitializer(out CollectionInitializerExpression outExpr) { + Expression expr = null; + CollectionInitializerExpression initializer = new CollectionInitializerExpression(); + Location startLocation = la.Location; + + Expect(35); + if (StartOf(24)) { + Expr(out expr); + if (expr != null) { initializer.CreateExpressions.Add(expr); } + + while (NotFinalComma()) { + Expect(22); + Expr(out expr); + if (expr != null) { initializer.CreateExpressions.Add(expr); } + } + } + Expect(36); + outExpr = initializer; + outExpr.StartLocation = startLocation; + outExpr.EndLocation = t.EndLocation; + + } + + void EventMemberSpecifier(out string name) { + string eventName; + if (StartOf(5)) { + Identifier(); + } else if (la.kind == 158) { + Get(); + } else if (la.kind == 153) { + Get(); + } else SynErr(277); + name = t.val; + Expect(26); + IdentifierOrKeyword(out eventName); + name = name + "." + eventName; + } + + void IdentifierOrKeyword(out string name) { + Get(); + name = t.val; + } + + void QueryExpr(out Expression expr) { + QueryExpression qexpr = new QueryExpression(); + qexpr.StartLocation = la.Location; + expr = qexpr; + + FromOrAggregateQueryOperator(qexpr.Clauses); + while (StartOf(31)) { + QueryOperator(qexpr.Clauses); + } + qexpr.EndLocation = t.EndLocation; + + } + + void LambdaExpr(out Expression expr) { + LambdaExpression lambda = null; + + if (la.kind == 210) { + SubLambdaExpression(out lambda); + } else if (la.kind == 127) { + FunctionLambdaExpression(out lambda); + } else SynErr(278); + expr = lambda; + } + + void DisjunctionExpr(out Expression outExpr) { + Expression expr; + BinaryOperatorType op = BinaryOperatorType.None; + Location startLocation = la.Location; + + ConjunctionExpr(out outExpr); + while (la.kind == 175 || la.kind == 177 || la.kind == 236) { + if (la.kind == 175) { + Get(); + op = BinaryOperatorType.BitwiseOr; + } else if (la.kind == 177) { + Get(); + op = BinaryOperatorType.LogicalOr; + } else { + Get(); + op = BinaryOperatorType.ExclusiveOr; + } + ConjunctionExpr(out expr); + outExpr = new BinaryOperatorExpression(outExpr, op, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } + } + + void AssignmentOperator(out AssignmentOperatorType op) { + op = AssignmentOperatorType.None; + switch (la.kind) { + case 20: { + Get(); + op = AssignmentOperatorType.Assign; + break; + } + case 54: { + Get(); + op = AssignmentOperatorType.ConcatString; + break; + } + case 46: { + Get(); + op = AssignmentOperatorType.Add; + break; + } + case 48: { + Get(); + op = AssignmentOperatorType.Subtract; + break; + } + case 49: { + Get(); + op = AssignmentOperatorType.Multiply; + break; + } + case 50: { + Get(); + op = AssignmentOperatorType.Divide; + break; + } + case 51: { + Get(); + op = AssignmentOperatorType.DivideInteger; + break; + } + case 47: { + Get(); + op = AssignmentOperatorType.Power; + break; + } + case 52: { + Get(); + op = AssignmentOperatorType.ShiftLeft; + break; + } + case 53: { + Get(); + op = AssignmentOperatorType.ShiftRight; + break; + } + default: SynErr(279); break; + } + } + + void SimpleExpr(out Expression pexpr) { + string name; Location startLocation = la.Location; + SimpleNonInvocationExpression(out pexpr); + while (StartOf(32)) { + if (la.kind == 26) { + Get(); + if (la.kind == 10) { + Get(); + IdentifierOrKeyword(out name); + Expect(11); + pexpr = new XmlMemberAccessExpression(pexpr, XmlAxisType.Element, name, true); + } else if (StartOf(33)) { + IdentifierOrKeyword(out name); + pexpr = new MemberReferenceExpression(pexpr, name) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } else SynErr(280); + if (la.kind == Tokens.OpenParenthesis && Peek(1).kind == Tokens.Of) { + Expect(37); + Expect(169); + TypeArgumentList(((MemberReferenceExpression)pexpr).TypeArguments); + Expect(38); + } + } else if (la.kind == 29) { + Get(); + IdentifierOrKeyword(out name); + pexpr = new BinaryOperatorExpression(pexpr, BinaryOperatorType.DictionaryAccess, new PrimitiveExpression(name, name) { StartLocation = t.Location, EndLocation = t.EndLocation }); + } else if (la.kind == 27 || la.kind == 28) { + XmlAxisType type = XmlAxisType.Attribute; bool isXmlName = false; + if (la.kind == 28) { + Get(); + } else { + Get(); + type = XmlAxisType.Descendents; + } + if (la.kind == 10) { + Get(); + isXmlName = true; + } + IdentifierOrKeyword(out name); + if (la.kind == 11) { + Get(); + } + pexpr = new XmlMemberAccessExpression(pexpr, type, name, isXmlName); + } else { + InvocationExpression(ref pexpr); + } + } + if (pexpr != null) { + pexpr.StartLocation = startLocation; + pexpr.EndLocation = t.EndLocation; + } + + } + + void SimpleNonInvocationExpression(out Expression pexpr) { + Expression expr; + CollectionInitializerExpression cie; + TypeReference type = null; + string name = String.Empty; + Location startLocation = la.Location; + pexpr = null; + + if (StartOf(34)) { + switch (la.kind) { + case 3: { + Get(); + pexpr = new PrimitiveExpression(t.literalValue, t.val) { LiteralFormat = t.literalFormat }; + break; + } + case 4: { + Get(); + pexpr = new PrimitiveExpression(t.literalValue, t.val) { LiteralFormat = t.literalFormat }; + break; + } + case 7: { + Get(); + pexpr = new PrimitiveExpression(t.literalValue, t.val) { LiteralFormat = t.literalFormat }; + break; + } + case 6: { + Get(); + pexpr = new PrimitiveExpression(t.literalValue, t.val) { LiteralFormat = t.literalFormat }; + break; + } + case 5: { + Get(); + pexpr = new PrimitiveExpression(t.literalValue, t.val) { LiteralFormat = t.literalFormat }; + break; + } + case 9: { + Get(); + pexpr = new PrimitiveExpression(t.literalValue, t.val) { LiteralFormat = t.literalFormat }; + break; + } + case 8: { + Get(); + pexpr = new PrimitiveExpression(t.literalValue, t.val) { LiteralFormat = t.literalFormat }; + break; + } + case 217: { + Get(); + pexpr = new PrimitiveExpression(true, "true"); + break; + } + case 122: { + Get(); + pexpr = new PrimitiveExpression(false, "false"); + break; + } + case 165: { + Get(); + pexpr = new PrimitiveExpression(null, "null"); + break; + } + case 37: { + Get(); + Expr(out expr); + Expect(38); + pexpr = new ParenthesizedExpression(expr); + break; + } + case 2: case 58: case 62: case 64: case 65: case 66: case 67: case 70: case 87: case 98: case 104: case 107: case 116: case 121: case 126: case 133: case 139: case 143: case 146: case 147: case 170: case 176: case 178: case 184: case 203: case 212: case 213: case 223: case 224: case 230: { + Identifier(); + pexpr = new IdentifierExpression(t.val); + pexpr.StartLocation = t.Location; pexpr.EndLocation = t.EndLocation; + + if (la.kind == Tokens.OpenParenthesis && Peek(1).kind == Tokens.Of) { + Expect(37); + Expect(169); + TypeArgumentList(((IdentifierExpression)pexpr).TypeArguments); + Expect(38); + } + break; + } + case 68: case 71: case 82: case 99: case 100: case 109: case 141: case 151: case 168: case 196: case 201: case 202: case 208: case 221: case 222: case 225: { + string val = String.Empty; + if (StartOf(13)) { + PrimitiveTypeName(out val); + } else { + Get(); + val = "System.Object"; + } + pexpr = new TypeReferenceExpression(new TypeReference(val, true)); + break; + } + case 153: { + Get(); + pexpr = new ThisReferenceExpression(); + break; + } + case 158: case 159: { + Expression retExpr = null; + if (la.kind == 158) { + Get(); + retExpr = new BaseReferenceExpression() { StartLocation = t.Location, EndLocation = t.EndLocation }; + } else { + Get(); + retExpr = new ClassReferenceExpression() { StartLocation = t.Location, EndLocation = t.EndLocation }; + } + Expect(26); + IdentifierOrKeyword(out name); + pexpr = new MemberReferenceExpression(retExpr, name) { StartLocation = startLocation, EndLocation = t.EndLocation }; + break; + } + case 130: { + Get(); + Expect(26); + Identifier(); + type = new TypeReference(t.val ?? ""); + type.IsGlobal = true; + pexpr = new TypeReferenceExpression(type); + break; + } + case 162: { + ObjectCreateExpression(out expr); + pexpr = expr; + break; + } + case 35: { + CollectionInitializer(out cie); + pexpr = cie; + break; + } + case 94: case 106: case 219: { + CastType castType = CastType.Cast; + if (la.kind == 106) { + Get(); + } else if (la.kind == 94) { + Get(); + castType = CastType.Conversion; + } else { + Get(); + castType = CastType.TryCast; + } + Expect(37); + Expr(out expr); + Expect(22); + TypeName(out type); + Expect(38); + pexpr = new CastExpression(type, expr, castType); + break; + } + case 76: case 77: case 78: case 79: case 80: case 81: case 83: case 85: case 86: case 90: case 91: case 92: case 93: case 95: case 96: case 97: { + CastTarget(out type); + Expect(37); + Expr(out expr); + Expect(38); + pexpr = new CastExpression(type, expr, CastType.PrimitiveConversion); + break; + } + case 57: { + Get(); + SimpleExpr(out expr); + pexpr = new AddressOfExpression(expr); + break; + } + case 129: { + Get(); + Expect(37); + GetTypeTypeName(out type); + Expect(38); + pexpr = new TypeOfExpression(type); + break; + } + case 220: { + Get(); + SimpleExpr(out expr); + Expect(144); + TypeName(out type); + pexpr = new TypeOfIsExpression(expr, type); + break; + } + case 135: { + ConditionalExpression(out pexpr); + break; + } + case 10: case 16: case 17: case 18: case 19: { + XmlLiteralExpression(out pexpr); + break; + } + } + } else if (StartOf(35)) { + if (la.kind == 26) { + Get(); + if (la.kind == 10) { + Get(); + IdentifierOrKeyword(out name); + Expect(11); + pexpr = new XmlMemberAccessExpression(null, XmlAxisType.Element, name, true) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } else if (StartOf(33)) { + IdentifierOrKeyword(out name); + pexpr = new MemberReferenceExpression(null, name) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } else SynErr(281); + } else if (la.kind == 29) { + Get(); + IdentifierOrKeyword(out name); + pexpr = new BinaryOperatorExpression(null, BinaryOperatorType.DictionaryAccess, new PrimitiveExpression(name, name) { StartLocation = t.Location, EndLocation = t.EndLocation }); + } else { + XmlAxisType axisType = XmlAxisType.Element; bool isXmlIdentifier = false; + if (la.kind == 27) { + Get(); + axisType = XmlAxisType.Descendents; + } else { + Get(); + axisType = XmlAxisType.Attribute; + } + if (la.kind == 10) { + Get(); + isXmlIdentifier = true; + } + IdentifierOrKeyword(out name); + if (la.kind == 11) { + Get(); + } + pexpr = new XmlMemberAccessExpression(null, axisType, name, isXmlIdentifier); + } + } else SynErr(282); + if (pexpr != null) { + pexpr.StartLocation = startLocation; + pexpr.EndLocation = t.EndLocation; + } + + } + + void TypeArgumentList(List typeArguments) { + TypeReference typeref; + + TypeName(out typeref); + if (typeref != null) typeArguments.Add(typeref); + while (la.kind == 22) { + Get(); + TypeName(out typeref); + if (typeref != null) typeArguments.Add(typeref); + } + } + + void InvocationExpression(ref Expression pexpr) { + List parameters = null; + Expect(37); + Location start = t.Location; + ArgumentList(out parameters); + Expect(38); + pexpr = new InvocationExpression(pexpr, parameters); + + pexpr.StartLocation = start; pexpr.EndLocation = t.Location; + } + + void PrimitiveTypeName(out string type) { + type = String.Empty; + switch (la.kind) { + case 68: { + Get(); + type = "System.Boolean"; + break; + } + case 99: { + Get(); + type = "System.DateTime"; + break; + } + case 82: { + Get(); + type = "System.Char"; + break; + } + case 208: { + Get(); + type = "System.String"; + break; + } + case 100: { + Get(); + type = "System.Decimal"; + break; + } + case 71: { + Get(); + type = "System.Byte"; + break; + } + case 201: { + Get(); + type = "System.Int16"; + break; + } + case 141: { + Get(); + type = "System.Int32"; + break; + } + case 151: { + Get(); + type = "System.Int64"; + break; + } + case 202: { + Get(); + type = "System.Single"; + break; + } + case 109: { + Get(); + type = "System.Double"; + break; + } + case 221: { + Get(); + type = "System.UInt32"; + break; + } + case 222: { + Get(); + type = "System.UInt64"; + break; + } + case 225: { + Get(); + type = "System.UInt16"; + break; + } + case 196: { + Get(); + type = "System.SByte"; + break; + } + default: SynErr(283); break; + } + } + + void CastTarget(out TypeReference type) { + type = null; + + switch (la.kind) { + case 76: { + Get(); + type = new TypeReference("System.Boolean", true); + break; + } + case 77: { + Get(); + type = new TypeReference("System.Byte", true); + break; + } + case 90: { + Get(); + type = new TypeReference("System.SByte", true); + break; + } + case 78: { + Get(); + type = new TypeReference("System.Char", true); + break; + } + case 79: { + Get(); + type = new TypeReference("System.DateTime", true); + break; + } + case 81: { + Get(); + type = new TypeReference("System.Decimal", true); + break; + } + case 80: { + Get(); + type = new TypeReference("System.Double", true); + break; + } + case 91: { + Get(); + type = new TypeReference("System.Int16", true); + break; + } + case 83: { + Get(); + type = new TypeReference("System.Int32", true); + break; + } + case 85: { + Get(); + type = new TypeReference("System.Int64", true); + break; + } + case 97: { + Get(); + type = new TypeReference("System.UInt16", true); + break; + } + case 95: { + Get(); + type = new TypeReference("System.UInt32", true); + break; + } + case 96: { + Get(); + type = new TypeReference("System.UInt64", true); + break; + } + case 86: { + Get(); + type = new TypeReference("System.Object", true); + break; + } + case 92: { + Get(); + type = new TypeReference("System.Single", true); + break; + } + case 93: { + Get(); + type = new TypeReference("System.String", true); + break; + } + default: SynErr(284); break; + } + } + + void GetTypeTypeName(out TypeReference typeref) { + ArrayList rank = null; + NonArrayTypeName(out typeref, true); + ArrayTypeModifiers(out rank); + if (rank != null && typeref != null) { + typeref.RankSpecifier = (int[])rank.ToArray(typeof(int)); + } + + } + + void ConditionalExpression(out Expression expr) { + ConditionalExpression conditionalExpression = new ConditionalExpression(); + BinaryOperatorExpression binaryOperatorExpression = new BinaryOperatorExpression(); + conditionalExpression.StartLocation = binaryOperatorExpression.StartLocation = la.Location; + + Expression condition = null; + Expression trueExpr = null; + Expression falseExpr = null; + + Expect(135); + Expect(37); + Expr(out condition); + Expect(22); + Expr(out trueExpr); + if (la.kind == 22) { + Get(); + Expr(out falseExpr); + } + Expect(38); + if(falseExpr != null) + { + conditionalExpression.Condition = condition; + conditionalExpression.TrueExpression = trueExpr; + conditionalExpression.FalseExpression = falseExpr; + conditionalExpression.EndLocation = t.EndLocation; + + expr = conditionalExpression; + } + else + { + binaryOperatorExpression.Left = condition; + binaryOperatorExpression.Right = trueExpr; + binaryOperatorExpression.Op = BinaryOperatorType.NullCoalescing; + binaryOperatorExpression.EndLocation = t.EndLocation; + + expr = binaryOperatorExpression; + } + + } + + void XmlLiteralExpression(out Expression pexpr) { + List exprs = new List(); + XmlExpression currentExpression = null; + + if (StartOf(36)) { + XmlContentExpression(exprs); + while (StartOf(36)) { + XmlContentExpression(exprs); + } + if (la.kind == 10) { + XmlElement(out currentExpression); + exprs.Add(currentExpression); + while (StartOf(36)) { + XmlContentExpression(exprs); + } + } + } else if (la.kind == 10) { + XmlElement(out currentExpression); + exprs.Add(currentExpression); + while (StartOf(36)) { + XmlContentExpression(exprs); + } + } else SynErr(285); + if (exprs.Count > 1) { + pexpr = new XmlDocumentExpression() { Expressions = exprs }; + } else { + pexpr = exprs[0]; + } + + } + + void XmlContentExpression(List exprs) { + XmlContentExpression expr = null; + if (la.kind == 16) { + Get(); + expr = new XmlContentExpression(t.val, XmlContentType.Text); + } else if (la.kind == 18) { + Get(); + expr = new XmlContentExpression(t.val, XmlContentType.CData); + } else if (la.kind == 17) { + Get(); + expr = new XmlContentExpression(t.val, XmlContentType.Comment); + } else if (la.kind == 19) { + Get(); + expr = new XmlContentExpression(t.val, XmlContentType.ProcessingInstruction); + } else SynErr(286); + expr.StartLocation = t.Location; + expr.EndLocation = t.EndLocation; + exprs.Add(expr); + + } + + void XmlElement(out XmlExpression expr) { + XmlElementExpression el = new XmlElementExpression(); + Expect(10); + el.StartLocation = t.Location; + if (la.kind == 12) { + Get(); + Expression innerExpression; + Expr(out innerExpression); + Expect(13); + el.NameExpression = new XmlEmbeddedExpression() { InlineVBExpression = innerExpression }; + } else if (StartOf(5)) { + Identifier(); + el.XmlName = t.val; + } else SynErr(287); + while (StartOf(37)) { + XmlAttribute(el.Attributes); + } + if (la.kind == 14) { + Get(); + el.EndLocation = t.EndLocation; + } else if (la.kind == 11) { + Get(); + while (StartOf(38)) { + XmlExpression child; + XmlNestedContent(out child); + el.Children.Add(child); + } + Expect(15); + while (StartOf(39)) { + Get(); + } + Expect(11); + el.EndLocation = t.EndLocation; + } else SynErr(288); + expr = el; + } + + void XmlNestedContent(out XmlExpression expr) { + XmlExpression tmpExpr = null; Location start = la.Location; + switch (la.kind) { + case 16: { + Get(); + tmpExpr = new XmlContentExpression(t.val, XmlContentType.Text); + break; + } + case 18: { + Get(); + tmpExpr = new XmlContentExpression(t.val, XmlContentType.CData); + break; + } + case 17: { + Get(); + tmpExpr = new XmlContentExpression(t.val, XmlContentType.Comment); + break; + } + case 19: { + Get(); + tmpExpr = new XmlContentExpression(t.val, XmlContentType.ProcessingInstruction); + break; + } + case 12: { + Get(); + Expression innerExpression; + Expr(out innerExpression); + Expect(13); + tmpExpr = new XmlEmbeddedExpression() { InlineVBExpression = innerExpression }; + break; + } + case 10: { + XmlElement(out tmpExpr); + break; + } + default: SynErr(289); break; + } + if (tmpExpr.StartLocation.IsEmpty) + tmpExpr.StartLocation = start; + if (tmpExpr.EndLocation.IsEmpty) + tmpExpr.EndLocation = t.EndLocation; + expr = tmpExpr; + + } + + void XmlAttribute(List attrs) { + Location start = la.Location; + if (StartOf(5)) { + Identifier(); + string name = t.val; + Expect(20); + string literalValue = null; Expression expressionValue = null; bool useDoubleQuotes = false; + if (la.kind == 3) { + Get(); + literalValue = t.literalValue.ToString(); useDoubleQuotes = t.val[0] == '"'; + } else if (la.kind == 12) { + Get(); + Expr(out expressionValue); + Expect(13); + } else SynErr(290); + attrs.Add(new XmlAttributeExpression() { Name = name, ExpressionValue = expressionValue, LiteralValue = literalValue, UseDoubleQuotes = useDoubleQuotes, StartLocation = start, EndLocation = t.EndLocation }); + } else if (la.kind == 12) { + Get(); + Expression innerExpression; + Expr(out innerExpression); + Expect(13); + attrs.Add(new XmlEmbeddedExpression() { InlineVBExpression = innerExpression, StartLocation = start, EndLocation = t.EndLocation }); + } else SynErr(291); + } + + void ArgumentList(out List arguments) { + arguments = new List(); + Expression expr = null; + + if (StartOf(24)) { + Argument(out expr); + } + while (la.kind == 22) { + Get(); + arguments.Add(expr ?? Expression.Null); expr = null; + if (StartOf(24)) { + Argument(out expr); + } + if (expr == null) expr = Expression.Null; + } + if (expr != null) arguments.Add(expr); + } + + void ConjunctionExpr(out Expression outExpr) { + Expression expr; + BinaryOperatorType op = BinaryOperatorType.None; + Location startLocation = la.Location; + + NotExpr(out outExpr); + while (la.kind == 60 || la.kind == 61) { + if (la.kind == 60) { + Get(); + op = BinaryOperatorType.BitwiseAnd; + } else { + Get(); + op = BinaryOperatorType.LogicalAnd; + } + NotExpr(out expr); + outExpr = new BinaryOperatorExpression(outExpr, op, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } + } + + void NotExpr(out Expression outExpr) { + UnaryOperatorType uop = UnaryOperatorType.None; + while (la.kind == 164) { + Get(); + uop = UnaryOperatorType.Not; + } + ComparisonExpr(out outExpr); + if (uop != UnaryOperatorType.None) + outExpr = new UnaryOperatorExpression(outExpr, uop); + + } + + void ComparisonExpr(out Expression outExpr) { + Expression expr; + BinaryOperatorType op = BinaryOperatorType.None; + Location startLocation = la.Location; + + ShiftExpr(out outExpr); + while (StartOf(40)) { + switch (la.kind) { + case 40: { + Get(); + op = BinaryOperatorType.LessThan; + break; + } + case 39: { + Get(); + op = BinaryOperatorType.GreaterThan; + break; + } + case 43: { + Get(); + op = BinaryOperatorType.LessThanOrEqual; + break; + } + case 42: { + Get(); + op = BinaryOperatorType.GreaterThanOrEqual; + break; + } + case 41: { + Get(); + op = BinaryOperatorType.InEquality; + break; + } + case 20: { + Get(); + op = BinaryOperatorType.Equality; + break; + } + case 150: { + Get(); + op = BinaryOperatorType.Like; + break; + } + case 144: { + Get(); + op = BinaryOperatorType.ReferenceEquality; + break; + } + case 145: { + Get(); + op = BinaryOperatorType.ReferenceInequality; + break; + } + } + if (StartOf(41)) { + ShiftExpr(out expr); + outExpr = new BinaryOperatorExpression(outExpr, op, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } else if (la.kind == 164) { + Location startLocation2 = la.Location; + Get(); + ShiftExpr(out expr); + outExpr = new BinaryOperatorExpression(outExpr, op, new UnaryOperatorExpression(expr, UnaryOperatorType.Not) { StartLocation = startLocation2, EndLocation = t.EndLocation }) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } else SynErr(292); + } + } + + void ShiftExpr(out Expression outExpr) { + Expression expr; + BinaryOperatorType op = BinaryOperatorType.None; + Location startLocation = la.Location; + + ConcatenationExpr(out outExpr); + while (la.kind == 44 || la.kind == 45) { + if (la.kind == 44) { + Get(); + op = BinaryOperatorType.ShiftLeft; + } else { + Get(); + op = BinaryOperatorType.ShiftRight; + } + ConcatenationExpr(out expr); + outExpr = new BinaryOperatorExpression(outExpr, op, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } + } + + void ConcatenationExpr(out Expression outExpr) { + Expression expr; Location startLocation = la.Location; + AdditiveExpr(out outExpr); + while (la.kind == 23) { + Get(); + AdditiveExpr(out expr); + outExpr = new BinaryOperatorExpression(outExpr, BinaryOperatorType.Concat, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } + } + + void AdditiveExpr(out Expression outExpr) { + Expression expr; + BinaryOperatorType op = BinaryOperatorType.None; + Location startLocation = la.Location; + + ModuloExpr(out outExpr); + while (la.kind == 30 || la.kind == 31) { + if (la.kind == 31) { + Get(); + op = BinaryOperatorType.Add; + } else { + Get(); + op = BinaryOperatorType.Subtract; + } + ModuloExpr(out expr); + outExpr = new BinaryOperatorExpression(outExpr, op, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } + } + + void ModuloExpr(out Expression outExpr) { + Expression expr; Location startLocation = la.Location; + IntegerDivisionExpr(out outExpr); + while (la.kind == 154) { + Get(); + IntegerDivisionExpr(out expr); + outExpr = new BinaryOperatorExpression(outExpr, BinaryOperatorType.Modulus, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } + } + + void IntegerDivisionExpr(out Expression outExpr) { + Expression expr; Location startLocation = la.Location; + MultiplicativeExpr(out outExpr); + while (la.kind == 25) { + Get(); + MultiplicativeExpr(out expr); + outExpr = new BinaryOperatorExpression(outExpr, BinaryOperatorType.DivideInteger, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } + } + + void MultiplicativeExpr(out Expression outExpr) { + Expression expr; + BinaryOperatorType op = BinaryOperatorType.None; + Location startLocation = la.Location; + + UnaryExpr(out outExpr); + while (la.kind == 24 || la.kind == 34) { + if (la.kind == 34) { + Get(); + op = BinaryOperatorType.Multiply; + } else { + Get(); + op = BinaryOperatorType.Divide; + } + UnaryExpr(out expr); + outExpr = new BinaryOperatorExpression(outExpr, op, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } + } + + void UnaryExpr(out Expression uExpr) { + Expression expr; + UnaryOperatorType uop = UnaryOperatorType.None; + Location startLocation = la.Location; + bool isUOp = false; + + while (la.kind == 30 || la.kind == 31 || la.kind == 34) { + if (la.kind == 31) { + Get(); + uop = UnaryOperatorType.Plus; isUOp = true; + } else if (la.kind == 30) { + Get(); + uop = UnaryOperatorType.Minus; isUOp = true; + } else { + Get(); + uop = UnaryOperatorType.Dereference; isUOp = true; + } + } + ExponentiationExpr(out expr); + if (isUOp) { + uExpr = new UnaryOperatorExpression(expr, uop) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } else { + uExpr = expr; + } + + } + + void ExponentiationExpr(out Expression outExpr) { + Expression expr; Location startLocation = la.Location; + SimpleExpr(out outExpr); + while (la.kind == 32) { + Get(); + SimpleExpr(out expr); + outExpr = new BinaryOperatorExpression(outExpr, BinaryOperatorType.Power, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } + } + + void NormalOrReDimArgumentList(out List arguments, out bool canBeNormal, out bool canBeRedim) { + arguments = new List(); + canBeNormal = true; canBeRedim = !IsNamedAssign(); + Expression expr = null; + + if (StartOf(24)) { + Argument(out expr); + if (la.kind == 216) { + Get(); + EnsureIsZero(expr); canBeNormal = false; + Expr(out expr); + } + } + while (la.kind == 22) { + Get(); + if (expr == null) canBeRedim = false; + arguments.Add(expr ?? Expression.Null); expr = null; + canBeRedim &= !IsNamedAssign(); + if (StartOf(24)) { + Argument(out expr); + if (la.kind == 216) { + Get(); + EnsureIsZero(expr); canBeNormal = false; + Expr(out expr); + } + } + if (expr == null) { canBeRedim = false; expr = Expression.Null; } + } + if (expr != null) arguments.Add(expr); else canBeRedim = false; + } + + void ArrayTypeModifiers(out ArrayList arrayModifiers) { + arrayModifiers = new ArrayList(); + int i = 0; + + while (IsDims()) { + Expect(37); + if (la.kind == 22 || la.kind == 38) { + RankList(out i); + } + arrayModifiers.Add(i); + + Expect(38); + } + if(arrayModifiers.Count == 0) { + arrayModifiers = null; + } + + } + + void MemberInitializer(out MemberInitializerExpression memberInitializer) { + memberInitializer = new MemberInitializerExpression(); + memberInitializer.StartLocation = la.Location; + Expression initExpr = null; + bool isKey = false; + string name = null; + + if (la.kind == 147) { + Get(); + isKey = true; + } + Expect(26); + IdentifierOrKeyword(out name); + Expect(20); + Expr(out initExpr); + memberInitializer.Name = name; + memberInitializer.Expression = initExpr; + memberInitializer.IsKey = isKey; + memberInitializer.EndLocation = t.EndLocation; + + } + + void SubLambdaExpression(out LambdaExpression lambda) { + lambda = new LambdaExpression(); + lambda.ReturnType = new TypeReference("System.Void", true); + Statement statement = null; + lambda.StartLocation = la.Location; + + Expect(210); + Expect(37); + if (StartOf(7)) { + FormalParameterList(lambda.Parameters); + } + Expect(38); + if (StartOf(1)) { + EmbeddedStatement(out statement); + lambda.StatementBody = statement; + lambda.EndLocation = t.EndLocation; + + } else if (la.kind == 1) { + Get(); + Block(out statement); + Expect(113); + Expect(210); + lambda.StatementBody = statement; + lambda.EndLocation = t.EndLocation; + + } else SynErr(293); + } + + void FunctionLambdaExpression(out LambdaExpression lambda) { + lambda = new LambdaExpression(); + TypeReference typeRef = null; + Expression inner = null; + Statement statement = null; + lambda.StartLocation = la.Location; + + Expect(127); + Expect(37); + if (StartOf(7)) { + FormalParameterList(lambda.Parameters); + } + Expect(38); + if (la.kind == 63) { + Get(); + TypeName(out typeRef); + lambda.ReturnType = typeRef; + } + if (StartOf(24)) { + Expr(out inner); + lambda.ExpressionBody = inner; + lambda.EndLocation = t.EndLocation; // la.Location? + + } else if (la.kind == 1) { + Get(); + Block(out statement); + Expect(113); + Expect(127); + lambda.StatementBody = statement; + lambda.EndLocation = t.EndLocation; + + } else SynErr(294); + } + + void EmbeddedStatement(out Statement statement) { + statement = null; + string name = String.Empty; + Location startLocation = la.Location; + + if (la.kind == 120) { + ExitStatement(out statement); + } else if (la.kind == 218) { + TryStatement(out statement); + } else if (la.kind == 89) { + ContinueStatement(out statement); + } else if (la.kind == 215) { + ThrowStatement(out statement); + } else if (la.kind == 195) { + ReturnStatement(out statement); + } else if (la.kind == 211) { + SyncLockStatement(out statement); + } else if (la.kind == 189) { + RaiseEventStatement(out statement); + } else if (la.kind == 233) { + WithStatement(out statement); + } else if (la.kind == 56) { + AddHandlerStatement(out statement); + } else if (la.kind == 193) { + RemoveHandlerStatement(out statement); + } else if (la.kind == 231) { + WhileStatement(out statement); + } else if (la.kind == 108) { + DoLoopStatement(out statement); + } else if (la.kind == 124) { + ForStatement(out statement); + } else if (la.kind == 118) { + ErrorStatement(out statement); + } else if (la.kind == 191) { + ReDimStatement(out statement); + } else if (la.kind == 117) { + EraseStatement(out statement); + } else if (la.kind == 206) { + StopStatement(out statement); + } else if (la.kind == 135) { + IfStatement(out statement); + } else if (la.kind == 197) { + SelectStatement(out statement); + } else if (la.kind == 171) { + OnErrorStatement onErrorStatement = null; + OnErrorStatement(out onErrorStatement); + statement = onErrorStatement; + } else if (la.kind == 132) { + GotoStatement goToStatement = null; + GotoStatement(out goToStatement); + statement = goToStatement; + } else if (la.kind == 194) { + ResumeStatement(out statement); + } else if (StartOf(42)) { + ExpressionStatement(out statement); + } else if (la.kind == 73) { + InvocationStatement(out statement); + } else if (la.kind == 226) { + UsingStatement(out statement); + } else if (StartOf(43)) { + LocalDeclarationStatement(out statement); + } else SynErr(295); + if (statement != null) { + statement.StartLocation = startLocation; + statement.EndLocation = t.EndLocation; + } + + } + + void FromOrAggregateQueryOperator(List middleClauses) { + QueryExpressionFromClause fromClause = null; + QueryExpressionAggregateClause aggregateClause = null; + + if (la.kind == 126) { + FromQueryOperator(out fromClause); + middleClauses.Add(fromClause); + } else if (la.kind == 58) { + AggregateQueryOperator(out aggregateClause); + middleClauses.Add(aggregateClause); + } else SynErr(296); + } + + void QueryOperator(List middleClauses) { + QueryExpressionJoinVBClause joinClause = null; + QueryExpressionGroupVBClause groupByClause = null; + QueryExpressionPartitionVBClause partitionClause = null; + QueryExpressionGroupJoinVBClause groupJoinClause = null; + QueryExpressionFromClause fromClause = null; + QueryExpressionAggregateClause aggregateClause = null; + + if (la.kind == 126) { + FromQueryOperator(out fromClause); + middleClauses.Add(fromClause); + } else if (la.kind == 58) { + AggregateQueryOperator(out aggregateClause); + middleClauses.Add(aggregateClause); + } else if (la.kind == 197) { + SelectQueryOperator(middleClauses); + } else if (la.kind == 107) { + DistinctQueryOperator(middleClauses); + } else if (la.kind == 230) { + WhereQueryOperator(middleClauses); + } else if (la.kind == 176) { + OrderByQueryOperator(middleClauses); + } else if (la.kind == 203 || la.kind == 212) { + PartitionQueryOperator(out partitionClause); + middleClauses.Add(partitionClause); + } else if (la.kind == 148) { + LetQueryOperator(middleClauses); + } else if (la.kind == 146) { + JoinQueryOperator(out joinClause); + middleClauses.Add(joinClause); + } else if (la.kind == Tokens.Group && Peek(1).kind == Tokens.Join) { + GroupJoinQueryOperator(out groupJoinClause); + middleClauses.Add(groupJoinClause); + } else if (la.kind == 133) { + GroupByQueryOperator(out groupByClause); + middleClauses.Add(groupByClause); + } else SynErr(297); + } + + void FromQueryOperator(out QueryExpressionFromClause fromClause) { + fromClause = new QueryExpressionFromClause(); + fromClause.StartLocation = la.Location; + + Expect(126); + CollectionRangeVariableDeclarationList(fromClause.Sources); + fromClause.EndLocation = t.EndLocation; + + } + + void AggregateQueryOperator(out QueryExpressionAggregateClause aggregateClause) { + aggregateClause = new QueryExpressionAggregateClause(); + aggregateClause.IntoVariables = new List(); + aggregateClause.StartLocation = la.Location; + CollectionRangeVariable source; + + Expect(58); + CollectionRangeVariableDeclaration(out source); + aggregateClause.Source = source; + + while (StartOf(31)) { + QueryOperator(aggregateClause.MiddleClauses); + } + Expect(143); + ExpressionRangeVariableDeclarationList(aggregateClause.IntoVariables); + aggregateClause.EndLocation = t.EndLocation; + + } + + void SelectQueryOperator(List middleClauses) { + QueryExpressionSelectVBClause selectClause = new QueryExpressionSelectVBClause(); + selectClause.StartLocation = la.Location; + + Expect(197); + ExpressionRangeVariableDeclarationList(selectClause.Variables); + selectClause.EndLocation = t.Location; + middleClauses.Add(selectClause); + + } + + void DistinctQueryOperator(List middleClauses) { + QueryExpressionDistinctClause distinctClause = new QueryExpressionDistinctClause(); + distinctClause.StartLocation = la.Location; + + Expect(107); + distinctClause.EndLocation = t.EndLocation; + middleClauses.Add(distinctClause); + + } + + void WhereQueryOperator(List middleClauses) { + QueryExpressionWhereClause whereClause = new QueryExpressionWhereClause(); + whereClause.StartLocation = la.Location; + Expression operand = null; + + Expect(230); + Expr(out operand); + whereClause.Condition = operand; + whereClause.EndLocation = t.EndLocation; + + middleClauses.Add(whereClause); + + } + + void OrderByQueryOperator(List middleClauses) { + QueryExpressionOrderClause orderClause = new QueryExpressionOrderClause(); + orderClause.StartLocation = la.Location; + List orderings = null; + + Expect(176); + Expect(70); + OrderExpressionList(out orderings); + orderClause.Orderings = orderings; + orderClause.EndLocation = t.EndLocation; + middleClauses.Add(orderClause); + + } + + void PartitionQueryOperator(out QueryExpressionPartitionVBClause partitionClause) { + partitionClause = new QueryExpressionPartitionVBClause(); + partitionClause.StartLocation = la.Location; + Expression expr = null; + + if (la.kind == 212) { + Get(); + partitionClause.PartitionType = QueryExpressionPartitionType.Take; + if (la.kind == 231) { + Get(); + partitionClause.PartitionType = QueryExpressionPartitionType.TakeWhile; + } + } else if (la.kind == 203) { + Get(); + partitionClause.PartitionType = QueryExpressionPartitionType.Skip; + if (la.kind == 231) { + Get(); + partitionClause.PartitionType = QueryExpressionPartitionType.SkipWhile; + } + } else SynErr(298); + Expr(out expr); + partitionClause.Expression = expr; + partitionClause.EndLocation = t.EndLocation; + + } + + void LetQueryOperator(List middleClauses) { + QueryExpressionLetVBClause letClause = new QueryExpressionLetVBClause(); + letClause.StartLocation = la.Location; + + Expect(148); + ExpressionRangeVariableDeclarationList(letClause.Variables); + letClause.EndLocation = t.EndLocation; + middleClauses.Add(letClause); + + } + + void JoinQueryOperator(out QueryExpressionJoinVBClause joinClause) { + joinClause = new QueryExpressionJoinVBClause(); + joinClause.StartLocation = la.Location; + CollectionRangeVariable joinVariable = null; + QueryExpressionJoinVBClause subJoin = null; + QueryExpressionJoinConditionVB condition = null; + + + Expect(146); + CollectionRangeVariableDeclaration(out joinVariable); + joinClause.JoinVariable = joinVariable; + if (la.kind == 146) { + JoinQueryOperator(out subJoin); + joinClause.SubJoin = subJoin; + } + Expect(171); + JoinCondition(out condition); + SafeAdd(joinClause, joinClause.Conditions, condition); + while (la.kind == 60) { + Get(); + JoinCondition(out condition); + SafeAdd(joinClause, joinClause.Conditions, condition); + } + joinClause.EndLocation = t.EndLocation; + + } + + void GroupJoinQueryOperator(out QueryExpressionGroupJoinVBClause groupJoinClause) { + groupJoinClause = new QueryExpressionGroupJoinVBClause(); + groupJoinClause.StartLocation = la.Location; + QueryExpressionJoinVBClause joinClause = null; + + Expect(133); + JoinQueryOperator(out joinClause); + Expect(143); + ExpressionRangeVariableDeclarationList(groupJoinClause.IntoVariables); + groupJoinClause.JoinClause = joinClause; + groupJoinClause.EndLocation = t.EndLocation; + + } + + void GroupByQueryOperator(out QueryExpressionGroupVBClause groupByClause) { + groupByClause = new QueryExpressionGroupVBClause(); + groupByClause.StartLocation = la.Location; + + Expect(133); + ExpressionRangeVariableDeclarationList(groupByClause.GroupVariables); + Expect(70); + ExpressionRangeVariableDeclarationList(groupByClause.ByVariables); + Expect(143); + ExpressionRangeVariableDeclarationList(groupByClause.IntoVariables); + groupByClause.EndLocation = t.EndLocation; + + } + + void OrderExpressionList(out List orderings) { + orderings = new List(); + QueryExpressionOrdering ordering = null; + + OrderExpression(out ordering); + orderings.Add(ordering); + while (la.kind == 22) { + Get(); + OrderExpression(out ordering); + orderings.Add(ordering); + } + } + + void OrderExpression(out QueryExpressionOrdering ordering) { + ordering = new QueryExpressionOrdering(); + ordering.StartLocation = la.Location; + ordering.Direction = QueryExpressionOrderingDirection.None; + Expression orderExpr = null; + + Expr(out orderExpr); + ordering.Criteria = orderExpr; + + if (la.kind == 64 || la.kind == 104) { + if (la.kind == 64) { + Get(); + ordering.Direction = QueryExpressionOrderingDirection.Ascending; + } else { + Get(); + ordering.Direction = QueryExpressionOrderingDirection.Descending; + } + } + ordering.EndLocation = t.EndLocation; + } + + void ExpressionRangeVariableDeclarationList(List variables) { + ExpressionRangeVariable variable = null; + + ExpressionRangeVariableDeclaration(out variable); + variables.Add(variable); + while (la.kind == 22) { + Get(); + ExpressionRangeVariableDeclaration(out variable); + variables.Add(variable); + } + } + + void CollectionRangeVariableDeclarationList(List rangeVariables) { + CollectionRangeVariable variableDeclaration; + CollectionRangeVariableDeclaration(out variableDeclaration); + rangeVariables.Add(variableDeclaration); + while (la.kind == 22) { + Get(); + CollectionRangeVariableDeclaration(out variableDeclaration); + rangeVariables.Add(variableDeclaration); + } + } + + void CollectionRangeVariableDeclaration(out CollectionRangeVariable rangeVariable) { + rangeVariable = new CollectionRangeVariable(); + rangeVariable.StartLocation = la.Location; + TypeReference typeName = null; + Expression inExpr = null; + + Identifier(); + rangeVariable.Identifier = t.val; + if (la.kind == 63) { + Get(); + TypeName(out typeName); + rangeVariable.Type = typeName; + } + Expect(138); + Expr(out inExpr); + rangeVariable.Expression = inExpr; + rangeVariable.EndLocation = t.EndLocation; + + } + + void ExpressionRangeVariableDeclaration(out ExpressionRangeVariable variable) { + variable = new ExpressionRangeVariable(); + variable.StartLocation = la.Location; + Expression rhs = null; + TypeReference typeName = null; + + if (IsIdentifiedExpressionRange()) { + Identifier(); + variable.Identifier = t.val; + if (la.kind == 63) { + Get(); + TypeName(out typeName); + variable.Type = typeName; + } + Expect(20); + } + Expr(out rhs); + variable.Expression = rhs; + variable.EndLocation = t.EndLocation; + + } + + void JoinCondition(out QueryExpressionJoinConditionVB condition) { + condition = new QueryExpressionJoinConditionVB(); + condition.StartLocation = la.Location; + + Expression lhs = null; + Expression rhs = null; + + Expr(out lhs); + Expect(116); + Expr(out rhs); + condition.LeftSide = lhs; + condition.RightSide = rhs; + condition.EndLocation = t.EndLocation; + + } + + void Argument(out Expression argumentexpr) { + Expression expr; + argumentexpr = null; + string name; + Location startLocation = la.Location; + + if (IsNamedAssign()) { + Identifier(); + name = t.val; + Expect(55); + Expr(out expr); + argumentexpr = new NamedArgumentExpression(name, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }; + + } else if (StartOf(24)) { + Expr(out argumentexpr); + } else SynErr(299); + } + + void QualIdentAndTypeArguments(out TypeReference typeref, bool canBeUnbound) { + string name; typeref = null; + Qualident(out name); + typeref = new TypeReference(name); + if (la.kind == Tokens.OpenParenthesis && Peek(1).kind == Tokens.Of) { + Expect(37); + Expect(169); + if (canBeUnbound && (la.kind == Tokens.CloseParenthesis || la.kind == Tokens.Comma)) { + typeref.GenericTypes.Add(NullTypeReference.Instance); + while (la.kind == 22) { + Get(); + typeref.GenericTypes.Add(NullTypeReference.Instance); + } + } else if (StartOf(9)) { + TypeArgumentList(typeref.GenericTypes); + } else SynErr(300); + Expect(38); + } + } + + void RankList(out int i) { + i = 0; + while (la.kind == 22) { + Get(); + ++i; + } + } + + void Attribute(out ASTAttribute attribute) { + string name; + List positional = new List(); + List named = new List(); + Location startLocation = la.Location; + + if (la.kind == 130) { + Get(); + Expect(26); + } + Qualident(out name); + if (la.kind == 37) { + AttributeArguments(positional, named); + } + attribute = new ASTAttribute(name, positional, named) { StartLocation = startLocation, EndLocation = t.EndLocation }; + + } + + void AttributeArguments(List positional, List named) { + bool nameFound = false; + string name = ""; + Expression expr; + + Expect(37); + if (IsNotClosingParenthesis()) { + Location startLocation = la.Location; + if (IsNamedAssign()) { + nameFound = true; + IdentifierOrKeyword(out name); + if (la.kind == 55) { + Get(); + } else if (la.kind == 20) { + Get(); + } else SynErr(301); + } + Expr(out expr); + if (expr != null) { + if (string.IsNullOrEmpty(name)) { positional.Add(expr); } + else { named.Add(new NamedArgumentExpression(name, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }); name = ""; } + } + + while (la.kind == 22) { + Get(); + if (IsNamedAssign()) { + nameFound = true; + IdentifierOrKeyword(out name); + if (la.kind == 55) { + Get(); + } else if (la.kind == 20) { + Get(); + } else SynErr(302); + } else if (StartOf(24)) { + if (nameFound) Error("no positional argument after named argument"); + } else SynErr(303); + Expr(out expr); + if (expr != null) { if(name == "") positional.Add(expr); + else { named.Add(new NamedArgumentExpression(name, expr) { StartLocation = startLocation, EndLocation = t.EndLocation }); name = ""; } + } + + } + } + Expect(38); + } + + void ParameterModifier(ParamModifierList m) { + if (la.kind == 72) { + Get(); + m.Add(ParameterModifiers.In); + } else if (la.kind == 69) { + Get(); + m.Add(ParameterModifiers.Ref); + } else if (la.kind == 174) { + Get(); + m.Add(ParameterModifiers.Optional); + } else if (la.kind == 182) { + Get(); + m.Add(ParameterModifiers.Params); + } else SynErr(304); + } + + void Statement() { + Statement stmt = null; + Location startPos = la.Location; + string label = String.Empty; + + if (IsLabel()) { + LabelName(out label); + AddChild(new LabelStatement(t.val)); + + Expect(21); + Statement(); + } else if (StartOf(1)) { + EmbeddedStatement(out stmt); + AddChild(stmt); + } else SynErr(305); + if (stmt != null) { + stmt.StartLocation = startPos; + stmt.EndLocation = t.Location; + } + + } + + void LabelName(out string name) { + name = string.Empty; + + if (StartOf(5)) { + Identifier(); + name = t.val; + } else if (la.kind == 5) { + Get(); + name = t.val; + } else SynErr(306); + } + + void LocalDeclarationStatement(out Statement statement) { + ModifierList m = new ModifierList(); + LocalVariableDeclaration localVariableDeclaration; + bool dimfound = false; + + while (la.kind == 88 || la.kind == 105 || la.kind == 204) { + if (la.kind == 88) { + Get(); + m.Add(Modifiers.Const, t.Location); + } else if (la.kind == 204) { + Get(); + m.Add(Modifiers.Static, t.Location); + } else { + Get(); + dimfound = true; + } + } + if(dimfound && (m.Modifier & Modifiers.Const) != 0) { + Error("Dim is not allowed on constants."); + } + + if(m.isNone && dimfound == false) { + Error("Const, Dim or Static expected"); + } + + localVariableDeclaration = new LocalVariableDeclaration(m.Modifier); + localVariableDeclaration.StartLocation = t.Location; + + VariableDeclarator(localVariableDeclaration.Variables); + while (la.kind == 22) { + Get(); + VariableDeclarator(localVariableDeclaration.Variables); + } + statement = localVariableDeclaration; + + } + + void ExitStatement(out Statement statement) { + Expect(120); + ExitType exitType = ExitType.None; + switch (la.kind) { + case 210: { + Get(); + exitType = ExitType.Sub; + break; + } + case 127: { + Get(); + exitType = ExitType.Function; + break; + } + case 186: { + Get(); + exitType = ExitType.Property; + break; + } + case 108: { + Get(); + exitType = ExitType.Do; + break; + } + case 124: { + Get(); + exitType = ExitType.For; + break; + } + case 218: { + Get(); + exitType = ExitType.Try; + break; + } + case 231: { + Get(); + exitType = ExitType.While; + break; + } + case 197: { + Get(); + exitType = ExitType.Select; + break; + } + default: SynErr(307); break; + } + statement = new ExitStatement(exitType); + } + + void TryStatement(out Statement tryStatement) { + Statement blockStmt = null; + Statement finallyStmt = null; + CatchClause clause = null; + List catchClauses = new List(); + + Expect(218); + EndOfStmt(); + Block(out blockStmt); + while (la.kind == 75) { + CatchClause(out clause); + if (clause != null) catchClauses.Add(clause); + } + if (la.kind == 123) { + Get(); + EndOfStmt(); + Block(out finallyStmt); + } + Expect(113); + Expect(218); + tryStatement = new TryCatchStatement(blockStmt, catchClauses, finallyStmt); + } + + void ContinueStatement(out Statement statement) { + Expect(89); + ContinueType continueType = ContinueType.None; + if (la.kind == 108 || la.kind == 124 || la.kind == 231) { + if (la.kind == 108) { + Get(); + continueType = ContinueType.Do; + } else if (la.kind == 124) { + Get(); + continueType = ContinueType.For; + } else { + Get(); + continueType = ContinueType.While; + } + } + statement = new ContinueStatement(continueType); + } + + void ThrowStatement(out Statement statement) { + Expression expr = null; + Expect(215); + if (StartOf(24)) { + Expr(out expr); + } + statement = new ThrowStatement(expr); + } + + void ReturnStatement(out Statement statement) { + Expression expr = null; + Expect(195); + if (StartOf(24)) { + Expr(out expr); + } + statement = new ReturnStatement(expr); + } + + void SyncLockStatement(out Statement statement) { + Expression expr; Statement embeddedStatement; + Expect(211); + Expr(out expr); + EndOfStmt(); + Block(out embeddedStatement); + Expect(113); + Expect(211); + statement = new LockStatement(expr, embeddedStatement); + } + + void RaiseEventStatement(out Statement statement) { + List arguments = null; + Expect(189); + Identifier(); + string name = t.val; + if (la.kind == 37) { + Get(); + ArgumentList(out arguments); + Expect(38); + } + statement = new RaiseEventStatement(name, arguments); + } + + void WithStatement(out Statement withStatement) { + Statement blockStmt = null; + Expression expr = null; + + Expect(233); + Location start = t.Location; + Expr(out expr); + EndOfStmt(); + withStatement = new WithStatement(expr); + withStatement.StartLocation = start; + + Block(out blockStmt); + ((WithStatement)withStatement).Body = (BlockStatement)blockStmt; + + Expect(113); + Expect(233); + withStatement.EndLocation = t.Location; + } + + void AddHandlerStatement(out Statement statement) { + Expression expr = null; + Expect(56); + Expression handlerExpr = null; + Expr(out expr); + Expect(22); + Expr(out handlerExpr); + statement = new AddHandlerStatement(expr, handlerExpr); + } + + void RemoveHandlerStatement(out Statement statement) { + Expression expr = null; + Expect(193); + Expression handlerExpr = null; + Expr(out expr); + Expect(22); + Expr(out handlerExpr); + statement = new RemoveHandlerStatement(expr, handlerExpr); + } + + void WhileStatement(out Statement statement) { + Expression expr = null; Statement embeddedStatement; + Expect(231); + Expr(out expr); + EndOfStmt(); + Block(out embeddedStatement); + Expect(113); + Expect(231); + statement = new DoLoopStatement(expr, embeddedStatement, ConditionType.While, ConditionPosition.Start); + } + + void DoLoopStatement(out Statement statement) { + Expression expr = null; Statement embeddedStatement; statement = null; + Expect(108); + ConditionType conditionType = ConditionType.None; + if (la.kind == 224 || la.kind == 231) { + WhileOrUntil(out conditionType); + Expr(out expr); + EndOfStmt(); + Block(out embeddedStatement); + Expect(152); + statement = new DoLoopStatement(expr, + embeddedStatement, + conditionType == ConditionType.While ? ConditionType.DoWhile : conditionType, + ConditionPosition.Start); + + } else if (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + Block(out embeddedStatement); + Expect(152); + if (la.kind == 224 || la.kind == 231) { + WhileOrUntil(out conditionType); + Expr(out expr); + } + statement = new DoLoopStatement(expr, embeddedStatement, conditionType, ConditionPosition.End); + } else SynErr(308); + } + + void ForStatement(out Statement statement) { + Expression expr = null; Statement embeddedStatement; statement = null; Location startLocation = la.Location; + Expect(124); + Expression group = null; + TypeReference typeReference; + string typeName; + + if (la.kind == 110) { + Get(); + LoopControlVariable(out typeReference, out typeName); + Expect(138); + Expr(out group); + EndOfStmt(); + Block(out embeddedStatement); + Expect(163); + if (StartOf(24)) { + Expr(out expr); + } + statement = new ForeachStatement(typeReference, + typeName, + group, + embeddedStatement, + expr); + statement.StartLocation = startLocation; + statement.EndLocation = t.EndLocation; + + + } else if (StartOf(42)) { + Expression start = null; + Expression end = null; + Expression step = null; + Expression variableExpr = null; + Expression nextExpr = null; + List nextExpressions = null; + + if (IsLoopVariableDeclaration()) { + LoopControlVariable(out typeReference, out typeName); + } else { + typeReference = null; typeName = null; + SimpleExpr(out variableExpr); + } + Expect(20); + Expr(out start); + Expect(216); + Expr(out end); + if (la.kind == 205) { + Get(); + Expr(out step); + } + EndOfStmt(); + Block(out embeddedStatement); + Expect(163); + if (StartOf(24)) { + Expr(out nextExpr); + nextExpressions = new List(); + nextExpressions.Add(nextExpr); + + while (la.kind == 22) { + Get(); + Expr(out nextExpr); + nextExpressions.Add(nextExpr); + } + } + statement = new ForNextStatement { + TypeReference = typeReference, + VariableName = typeName, + LoopVariableExpression = variableExpr, + Start = start, + End = end, + Step = step, + EmbeddedStatement = embeddedStatement, + NextExpressions = nextExpressions + }; + + } else SynErr(309); + } + + void ErrorStatement(out Statement statement) { + Expression expr = null; + Expect(118); + Expr(out expr); + statement = new ErrorStatement(expr); + } + + void ReDimStatement(out Statement statement) { + Expression expr = null; + Expect(191); + bool isPreserve = false; + if (la.kind == 184) { + Expect(184); + isPreserve = true; + } + ReDimClause(out expr); + ReDimStatement reDimStatement = new ReDimStatement(isPreserve); + statement = reDimStatement; + SafeAdd(reDimStatement, reDimStatement.ReDimClauses, expr as InvocationExpression); + + while (la.kind == 22) { + Get(); + ReDimClause(out expr); + SafeAdd(reDimStatement, reDimStatement.ReDimClauses, expr as InvocationExpression); + } + } + + void EraseStatement(out Statement statement) { + Expression expr = null; + Expect(117); + Expr(out expr); + EraseStatement eraseStatement = new EraseStatement(); + if (expr != null) { SafeAdd(eraseStatement, eraseStatement.Expressions, expr);} + + while (la.kind == 22) { + Get(); + Expr(out expr); + if (expr != null) { SafeAdd(eraseStatement, eraseStatement.Expressions, expr); } + } + statement = eraseStatement; + } + + void StopStatement(out Statement statement) { + Expect(206); + statement = new StopStatement(); + } + + void IfStatement(out Statement statement) { + Expression expr = null; Statement embeddedStatement; statement = null; + Expect(135); + Location ifStartLocation = t.Location; + Expr(out expr); + if (la.kind == 214) { + Get(); + } + if (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + Block(out embeddedStatement); + IfElseStatement ifStatement = new IfElseStatement(expr, embeddedStatement); + ifStatement.StartLocation = ifStartLocation; + Location elseIfStart; + + while (la.kind == 112 || (IsElseIf())) { + if (IsElseIf()) { + Expect(111); + elseIfStart = t.Location; + Expect(135); + } else { + Get(); + elseIfStart = t.Location; + } + Expression condition = null; Statement block = null; + Expr(out condition); + if (la.kind == 214) { + Get(); + } + EndOfStmt(); + Block(out block); + ElseIfSection elseIfSection = new ElseIfSection(condition, block); + elseIfSection.StartLocation = elseIfStart; + elseIfSection.EndLocation = t.Location; + elseIfSection.Parent = ifStatement; + ifStatement.ElseIfSections.Add(elseIfSection); + + } + if (la.kind == 111) { + Get(); + if (la.kind == 1 || la.kind == 21) { + EndOfStmt(); + } + Block(out embeddedStatement); + ifStatement.FalseStatement.Add(embeddedStatement); + + } + Expect(113); + Expect(135); + ifStatement.EndLocation = t.Location; + statement = ifStatement; + + } else if (StartOf(44)) { + IfElseStatement ifStatement = new IfElseStatement(expr); + ifStatement.StartLocation = ifStartLocation; + + SingleLineStatementList(ifStatement.TrueStatement); + if (la.kind == 111) { + Get(); + if (StartOf(44)) { + SingleLineStatementList(ifStatement.FalseStatement); + } + } + ifStatement.EndLocation = t.Location; statement = ifStatement; + } else SynErr(310); + } + + void SelectStatement(out Statement statement) { + Expression expr = null; + Expect(197); + if (la.kind == 74) { + Get(); + } + Expr(out expr); + EndOfStmt(); + List selectSections = new List(); + Statement block = null; + + while (la.kind == 74) { + List caseClauses = null; Location caseLocation = la.Location; + Get(); + CaseClauses(out caseClauses); + if (IsNotStatementSeparator()) { + Expect(21); + } + EndOfStmt(); + SwitchSection selectSection = new SwitchSection(caseClauses); + selectSection.StartLocation = caseLocation; + + Block(out block); + selectSection.Children = block.Children; + selectSection.EndLocation = t.EndLocation; + selectSections.Add(selectSection); + + } + statement = new SwitchStatement(expr, selectSections); + + Expect(113); + Expect(197); + } + + void OnErrorStatement(out OnErrorStatement stmt) { + stmt = null; + Location startLocation = la.Location; + GotoStatement goToStatement = null; + + Expect(171); + Expect(118); + if (IsNegativeLabelName()) { + Expect(132); + Expect(30); + Expect(5); + long intLabel = Int64.Parse(t.val); + if(intLabel != 1) { + Error("invalid label in on error statement."); + } + stmt = new OnErrorStatement(new GotoStatement((intLabel * -1).ToString())); + + } else if (la.kind == 132) { + GotoStatement(out goToStatement); + string val = goToStatement.Label; + + // if value is numeric, make sure that is 0 + try { + long intLabel = Int64.Parse(val); + if(intLabel != 0) { + Error("invalid label in on error statement."); + } + } catch { + } + stmt = new OnErrorStatement(goToStatement); + + } else if (la.kind == 194) { + Get(); + Expect(163); + stmt = new OnErrorStatement(new ResumeStatement(true)); + + } else SynErr(311); + if (stmt != null) { + stmt.StartLocation = startLocation; + stmt.EndLocation = t.EndLocation; + } + + } + + void GotoStatement(out GotoStatement goToStatement) { + string label = string.Empty; + Location startLocation = la.Location; + + Expect(132); + LabelName(out label); + goToStatement = new GotoStatement(label) { + StartLocation = startLocation, + EndLocation = t.EndLocation + }; + + } + + void ResumeStatement(out Statement resumeStatement) { + resumeStatement = null; + string label = string.Empty; + + Expect(194); + if (StartOf(45)) { + if (la.kind == 163) { + Get(); + resumeStatement = new ResumeStatement(true); + } else { + LabelName(out label); + } + } + resumeStatement = new ResumeStatement(label); + } + + void ExpressionStatement(out Statement statement) { + Expression expr = null; + Expression val = null; + AssignmentOperatorType op; + Location startLoc = la.Location; + + bool mustBeAssignment = la.kind == Tokens.Plus || la.kind == Tokens.Minus || + la.kind == Tokens.Not || la.kind == Tokens.Times; + + SimpleExpr(out expr); + if (StartOf(46)) { + AssignmentOperator(out op); + Expr(out val); + expr = new AssignmentExpression(expr, op, val); + expr.StartLocation = startLoc; + expr.EndLocation = t.EndLocation; + + } else if (la.kind == 1 || la.kind == 21 || la.kind == 111) { + if (mustBeAssignment) Error("error in assignment."); + } else SynErr(312); + if(expr is MemberReferenceExpression || expr is IdentifierExpression) { + Location endLocation = expr.EndLocation; + expr = new InvocationExpression(expr); + expr.StartLocation = startLoc; + expr.EndLocation = endLocation; + } + statement = new ExpressionStatement(expr); + + } + + void InvocationStatement(out Statement statement) { + Expression expr = null; + Expect(73); + SimpleExpr(out expr); + statement = new ExpressionStatement(expr); + } + + void UsingStatement(out Statement statement) { + Expression expr = null; Statement block; statement = null; + Expect(226); + if (Peek(1).kind == Tokens.As) { + LocalVariableDeclaration resourceAquisition = + new LocalVariableDeclaration(Modifiers.None); + VariableDeclarator(resourceAquisition.Variables); + while (la.kind == 22) { + Get(); + VariableDeclarator(resourceAquisition.Variables); + } + EndOfStmt(); + Block(out block); + statement = new UsingStatement(resourceAquisition, block); + } else if (StartOf(24)) { + Expr(out expr); + EndOfStmt(); + Block(out block); + statement = new UsingStatement(new ExpressionStatement(expr), block); + } else SynErr(313); + Expect(113); + Expect(226); + } + + void WhileOrUntil(out ConditionType conditionType) { + conditionType = ConditionType.None; + if (la.kind == 231) { + Get(); + conditionType = ConditionType.While; + } else if (la.kind == 224) { + Get(); + conditionType = ConditionType.Until; + } else SynErr(314); + } + + void LoopControlVariable(out TypeReference type, out string name) { + ArrayList arrayModifiers = null; + type = null; + + Qualident(out name); + if (IsDims()) { + ArrayTypeModifiers(out arrayModifiers); + } + if (la.kind == 63) { + Get(); + TypeName(out type); + if (name.IndexOf('.') > 0) { Error("No type def for 'for each' member indexer allowed."); } + } + if (type != null) { + if(type.RankSpecifier != null && arrayModifiers != null) { + Error("array rank only allowed one time"); + } else if (arrayModifiers != null) { + type.RankSpecifier = (int[])arrayModifiers.ToArray(typeof(int)); + } + } + + } + + void ReDimClause(out Expression expr) { + SimpleNonInvocationExpression(out expr); + ReDimClauseInternal(ref expr); + } + + void SingleLineStatementList(List list) { + Statement embeddedStatement = null; + if (la.kind == 113) { + Get(); + embeddedStatement = new EndStatement() { StartLocation = t.Location, EndLocation = t.EndLocation }; + } else if (StartOf(1)) { + EmbeddedStatement(out embeddedStatement); + } else SynErr(315); + if (embeddedStatement != null) list.Add(embeddedStatement); + while (la.kind == 21) { + Get(); + while (la.kind == 21) { + Get(); + } + if (la.kind == 113) { + Get(); + embeddedStatement = new EndStatement() { StartLocation = t.Location, EndLocation = t.EndLocation }; + } else if (StartOf(1)) { + EmbeddedStatement(out embeddedStatement); + } else SynErr(316); + if (embeddedStatement != null) list.Add(embeddedStatement); + } + } + + void CaseClauses(out List caseClauses) { + caseClauses = new List(); + CaseLabel caseClause = null; + + CaseClause(out caseClause); + if (caseClause != null) { caseClauses.Add(caseClause); } + while (la.kind == 22) { + Get(); + CaseClause(out caseClause); + if (caseClause != null) { caseClauses.Add(caseClause); } + } + } + + void ReDimClauseInternal(ref Expression expr) { + List arguments; bool canBeNormal; bool canBeRedim; string name; Location startLocation = la.Location; + while (la.kind == 26 || (la.kind == Tokens.OpenParenthesis && Peek(1).kind == Tokens.Of)) { + if (la.kind == 26) { + Get(); + IdentifierOrKeyword(out name); + expr = new MemberReferenceExpression(expr, name) { StartLocation = startLocation, EndLocation = t.EndLocation }; + } else { + InvocationExpression(ref expr); + expr.StartLocation = startLocation; + expr.EndLocation = t.EndLocation; + + } + } + Expect(37); + NormalOrReDimArgumentList(out arguments, out canBeNormal, out canBeRedim); + Expect(38); + expr = new InvocationExpression(expr, arguments); + if (canBeRedim == false || canBeNormal && (la.kind == Tokens.Dot || la.kind == Tokens.OpenParenthesis)) { + if (this.Errors.Count == 0) { + // don't recurse on parse errors - could result in endless recursion + ReDimClauseInternal(ref expr); + } + } + + } + + void CaseClause(out CaseLabel caseClause) { + Expression expr = null; + Expression sexpr = null; + BinaryOperatorType op = BinaryOperatorType.None; + caseClause = null; + + if (la.kind == 111) { + Get(); + caseClause = new CaseLabel(); + } else if (StartOf(47)) { + if (la.kind == 144) { + Get(); + } + switch (la.kind) { + case 40: { + Get(); + op = BinaryOperatorType.LessThan; + break; + } + case 39: { + Get(); + op = BinaryOperatorType.GreaterThan; + break; + } + case 43: { + Get(); + op = BinaryOperatorType.LessThanOrEqual; + break; + } + case 42: { + Get(); + op = BinaryOperatorType.GreaterThanOrEqual; + break; + } + case 20: { + Get(); + op = BinaryOperatorType.Equality; + break; + } + case 41: { + Get(); + op = BinaryOperatorType.InEquality; + break; + } + default: SynErr(317); break; + } + Expr(out expr); + caseClause = new CaseLabel(op, expr); + + } else if (StartOf(24)) { + Expr(out expr); + if (la.kind == 216) { + Get(); + Expr(out sexpr); + } + caseClause = new CaseLabel(expr, sexpr); + + } else SynErr(318); + } + + void CatchClause(out CatchClause catchClause) { + TypeReference type = null; + Statement blockStmt = null; + Expression expr = null; + string name = String.Empty; + + Expect(75); + if (StartOf(5)) { + Identifier(); + name = t.val; + if (la.kind == 63) { + Get(); + TypeName(out type); + } + } + if (la.kind == 229) { + Get(); + Expr(out expr); + } + EndOfStmt(); + Block(out blockStmt); + catchClause = new CatchClause(type, name, blockStmt, expr); + } + + + + public void ParseRoot() { + VB(); + Expect(0); // expect end-of-file automatically added + + } + + static readonly BitArray[] set = { + new BitArray(new int[] {2097155, 0, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {1007618044, 1191182376, -1051937, 1466973983, -1030969162, -1593504476, -21406146, 711}), + new BitArray(new int[] {0, 256, 1048576, 537395328, 402669568, 444596289, 131456, 0}), + new BitArray(new int[] {0, 256, 1048576, 537395328, 402669568, 444596288, 131456, 0}), + new BitArray(new int[] {0, 0, 0, 536870912, 268435456, 444596288, 384, 0}), + new BitArray(new int[] {4, 1140850688, 8388687, 1108347140, 821280, 17105920, -2144335872, 65}), + new BitArray(new int[] {4, 1140850688, 8388687, 1108347136, 821280, 17105920, -2144335872, 65}), + new BitArray(new int[] {4, 1140850944, 8388975, 1108347140, 821280, 21316608, -2144335872, 65}), + new BitArray(new int[] {4, 1140850688, 9699551, 1108355356, 9218084, 17106180, -533524976, 67}), + new BitArray(new int[] {4, 1140850688, 8650975, 1108355356, 9218084, 17106176, -533656048, 67}), + new BitArray(new int[] {4, 1140850944, 26214479, -493351964, 940361760, 1606227138, -2143942272, 3393}), + new BitArray(new int[] {0, 0, 0, 536871488, 805306368, 1522008256, 384, 3072}), + new BitArray(new int[] {4, 1140850688, 8388687, 1108347140, 821284, 17105920, -2144335872, 65}), + new BitArray(new int[] {0, 0, 262288, 8216, 8396800, 0, 1610679824, 2}), + new BitArray(new int[] {4, 1140850944, 8388687, 1108347140, 821280, 17105920, -2144335872, 65}), + new BitArray(new int[] {0, 256, 1048576, -1601699136, 939540480, 1589117120, 393600, 3072}), + new BitArray(new int[] {0, 1073741824, 4, -2147483648, 0, 0, -2147221504, 0}), + new BitArray(new int[] {2097154, 32, 0, 0, 256, 0, 0, 0}), + new BitArray(new int[] {0, 256, 0, 536870912, 1, 436207616, 64, 0}), + new BitArray(new int[] {0, 16777472, 0, 0, 0, 536870912, 2, 0}), + new BitArray(new int[] {0, 256, 0, -1602223552, 805306368, 1589117120, 262528, 3072}), + new BitArray(new int[] {0, 0, 1048576, 524416, 134234112, 0, 131072, 0}), + new BitArray(new int[] {-66123780, 1174405164, -51384097, 1175465247, -1030969178, 17106228, -97448432, 67}), + new BitArray(new int[] {7340034, -2147483648, 0, 32768, 0, 0, 0, 0}), + new BitArray(new int[] {-66123780, 1174405164, -51384097, -972018401, -1030969178, 17106228, -97186288, 67}), + new BitArray(new int[] {0, 0, 0, 536870912, 1, 436207616, 0, 0}), + new BitArray(new int[] {0, 256, 0, 536870912, 0, 436207616, 64, 0}), + new BitArray(new int[] {0, 0, 0, 536870912, 0, 436207616, 64, 0}), + new BitArray(new int[] {0, 256, 0, 536870912, 1, 436207616, 0, 0}), + new BitArray(new int[] {0, 0, 288, 0, 0, 4210688, 0, 0}), + new BitArray(new int[] {0, 0, 0, 536870912, 0, 436207616, 0, 0}), + new BitArray(new int[] {0, 67108864, 0, 1073743872, 1310752, 65536, 1050656, 64}), + new BitArray(new int[] {1006632960, 32, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {-2, -1, -1, -1, -1, -1, -1, -1}), + new BitArray(new int[] {985084, 1174405160, -51384097, 1175465247, -1030969178, 17106212, -97448432, 67}), + new BitArray(new int[] {1006632960, 0, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {983040, 0, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {4100, 1140850688, 8388687, 1108347140, 821280, 17105920, -2144335872, 65}), + new BitArray(new int[] {988160, 0, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {-2050, -1, -1, -1, -1, -1, -1, -1}), + new BitArray(new int[] {1048576, 3968, 0, 0, 4390912, 0, 0, 0}), + new BitArray(new int[] {-66123780, 1174405164, -51384097, 1175465247, -1030969178, 17106212, -97448432, 67}), + new BitArray(new int[] {1007618044, 1174405160, -51384097, 1175465247, -1030969178, 17106212, -97448432, 67}), + new BitArray(new int[] {4, 1140850688, 25165903, 1108347652, 821280, 17105920, -2144331776, 65}), + new BitArray(new int[] {1007618044, 1191182376, -1051937, 1467105055, -1030969162, -1593504476, -21406146, 711}), + new BitArray(new int[] {36, 1140850688, 8388687, 1108347140, 821280, 17105928, -2144335872, 65}), + new BitArray(new int[] {1048576, 8372224, 0, 0, 0, 0, 0, 0}), + new BitArray(new int[] {1048576, 3968, 0, 0, 65536, 0, 0, 0}) + + }; + + void SynErr(int line, int col, int errorNumber) + { + this.Errors.Error(line, col, GetMessage(errorNumber)); + } + + string GetMessage(int errorNumber) + { + switch (errorNumber) { + case 0: return "EOF expected"; + case 1: return "EOL expected"; + case 2: return "ident expected"; + case 3: return "LiteralString expected"; + case 4: return "LiteralCharacter expected"; + case 5: return "LiteralInteger expected"; + case 6: return "LiteralDouble expected"; + case 7: return "LiteralSingle expected"; + case 8: return "LiteralDecimal expected"; + case 9: return "LiteralDate expected"; + case 10: return "XmlOpenTag expected"; + case 11: return "XmlCloseTag expected"; + case 12: return "XmlStartInlineVB expected"; + case 13: return "XmlEndInlineVB expected"; + case 14: return "XmlCloseTagEmptyElement expected"; + case 15: return "XmlOpenEndTag expected"; + case 16: return "XmlContent expected"; + case 17: return "XmlComment expected"; + case 18: return "XmlCData expected"; + case 19: return "XmlProcessingInstruction expected"; + case 20: return "\"=\" expected"; + case 21: return "\":\" expected"; + case 22: return "\",\" expected"; + case 23: return "\"&\" expected"; + case 24: return "\"/\" expected"; + case 25: return "\"\\\\\" expected"; + case 26: return "\".\" expected"; + case 27: return "\"...\" expected"; + case 28: return "\".@\" expected"; + case 29: return "\"!\" expected"; + case 30: return "\"-\" expected"; + case 31: return "\"+\" expected"; + case 32: return "\"^\" expected"; + case 33: return "\"?\" expected"; + case 34: return "\"*\" expected"; + case 35: return "\"{\" expected"; + case 36: return "\"}\" expected"; + case 37: return "\"(\" expected"; + case 38: return "\")\" expected"; + case 39: return "\">\" expected"; + case 40: return "\"<\" expected"; + case 41: return "\"<>\" expected"; + case 42: return "\">=\" expected"; + case 43: return "\"<=\" expected"; + case 44: return "\"<<\" expected"; + case 45: return "\">>\" expected"; + case 46: return "\"+=\" expected"; + case 47: return "\"^=\" expected"; + case 48: return "\"-=\" expected"; + case 49: return "\"*=\" expected"; + case 50: return "\"/=\" expected"; + case 51: return "\"\\\\=\" expected"; + case 52: return "\"<<=\" expected"; + case 53: return "\">>=\" expected"; + case 54: return "\"&=\" expected"; + case 55: return "\":=\" expected"; + case 56: return "\"AddHandler\" expected"; + case 57: return "\"AddressOf\" expected"; + case 58: return "\"Aggregate\" expected"; + case 59: return "\"Alias\" expected"; + case 60: return "\"And\" expected"; + case 61: return "\"AndAlso\" expected"; + case 62: return "\"Ansi\" expected"; + case 63: return "\"As\" expected"; + case 64: return "\"Ascending\" expected"; + case 65: return "\"Assembly\" expected"; + case 66: return "\"Auto\" expected"; + case 67: return "\"Binary\" expected"; + case 68: return "\"Boolean\" expected"; + case 69: return "\"ByRef\" expected"; + case 70: return "\"By\" expected"; + case 71: return "\"Byte\" expected"; + case 72: return "\"ByVal\" expected"; + case 73: return "\"Call\" expected"; + case 74: return "\"Case\" expected"; + case 75: return "\"Catch\" expected"; + case 76: return "\"CBool\" expected"; + case 77: return "\"CByte\" expected"; + case 78: return "\"CChar\" expected"; + case 79: return "\"CDate\" expected"; + case 80: return "\"CDbl\" expected"; + case 81: return "\"CDec\" expected"; + case 82: return "\"Char\" expected"; + case 83: return "\"CInt\" expected"; + case 84: return "\"Class\" expected"; + case 85: return "\"CLng\" expected"; + case 86: return "\"CObj\" expected"; + case 87: return "\"Compare\" expected"; + case 88: return "\"Const\" expected"; + case 89: return "\"Continue\" expected"; + case 90: return "\"CSByte\" expected"; + case 91: return "\"CShort\" expected"; + case 92: return "\"CSng\" expected"; + case 93: return "\"CStr\" expected"; + case 94: return "\"CType\" expected"; + case 95: return "\"CUInt\" expected"; + case 96: return "\"CULng\" expected"; + case 97: return "\"CUShort\" expected"; + case 98: return "\"Custom\" expected"; + case 99: return "\"Date\" expected"; + case 100: return "\"Decimal\" expected"; + case 101: return "\"Declare\" expected"; + case 102: return "\"Default\" expected"; + case 103: return "\"Delegate\" expected"; + case 104: return "\"Descending\" expected"; + case 105: return "\"Dim\" expected"; + case 106: return "\"DirectCast\" expected"; + case 107: return "\"Distinct\" expected"; + case 108: return "\"Do\" expected"; + case 109: return "\"Double\" expected"; + case 110: return "\"Each\" expected"; + case 111: return "\"Else\" expected"; + case 112: return "\"ElseIf\" expected"; + case 113: return "\"End\" expected"; + case 114: return "\"EndIf\" expected"; + case 115: return "\"Enum\" expected"; + case 116: return "\"Equals\" expected"; + case 117: return "\"Erase\" expected"; + case 118: return "\"Error\" expected"; + case 119: return "\"Event\" expected"; + case 120: return "\"Exit\" expected"; + case 121: return "\"Explicit\" expected"; + case 122: return "\"False\" expected"; + case 123: return "\"Finally\" expected"; + case 124: return "\"For\" expected"; + case 125: return "\"Friend\" expected"; + case 126: return "\"From\" expected"; + case 127: return "\"Function\" expected"; + case 128: return "\"Get\" expected"; + case 129: return "\"GetType\" expected"; + case 130: return "\"Global\" expected"; + case 131: return "\"GoSub\" expected"; + case 132: return "\"GoTo\" expected"; + case 133: return "\"Group\" expected"; + case 134: return "\"Handles\" expected"; + case 135: return "\"If\" expected"; + case 136: return "\"Implements\" expected"; + case 137: return "\"Imports\" expected"; + case 138: return "\"In\" expected"; + case 139: return "\"Infer\" expected"; + case 140: return "\"Inherits\" expected"; + case 141: return "\"Integer\" expected"; + case 142: return "\"Interface\" expected"; + case 143: return "\"Into\" expected"; + case 144: return "\"Is\" expected"; + case 145: return "\"IsNot\" expected"; + case 146: return "\"Join\" expected"; + case 147: return "\"Key\" expected"; + case 148: return "\"Let\" expected"; + case 149: return "\"Lib\" expected"; + case 150: return "\"Like\" expected"; + case 151: return "\"Long\" expected"; + case 152: return "\"Loop\" expected"; + case 153: return "\"Me\" expected"; + case 154: return "\"Mod\" expected"; + case 155: return "\"Module\" expected"; + case 156: return "\"MustInherit\" expected"; + case 157: return "\"MustOverride\" expected"; + case 158: return "\"MyBase\" expected"; + case 159: return "\"MyClass\" expected"; + case 160: return "\"Namespace\" expected"; + case 161: return "\"Narrowing\" expected"; + case 162: return "\"New\" expected"; + case 163: return "\"Next\" expected"; + case 164: return "\"Not\" expected"; + case 165: return "\"Nothing\" expected"; + case 166: return "\"NotInheritable\" expected"; + case 167: return "\"NotOverridable\" expected"; + case 168: return "\"Object\" expected"; + case 169: return "\"Of\" expected"; + case 170: return "\"Off\" expected"; + case 171: return "\"On\" expected"; + case 172: return "\"Operator\" expected"; + case 173: return "\"Option\" expected"; + case 174: return "\"Optional\" expected"; + case 175: return "\"Or\" expected"; + case 176: return "\"Order\" expected"; + case 177: return "\"OrElse\" expected"; + case 178: return "\"Out\" expected"; + case 179: return "\"Overloads\" expected"; + case 180: return "\"Overridable\" expected"; + case 181: return "\"Overrides\" expected"; + case 182: return "\"ParamArray\" expected"; + case 183: return "\"Partial\" expected"; + case 184: return "\"Preserve\" expected"; + case 185: return "\"Private\" expected"; + case 186: return "\"Property\" expected"; + case 187: return "\"Protected\" expected"; + case 188: return "\"Public\" expected"; + case 189: return "\"RaiseEvent\" expected"; + case 190: return "\"ReadOnly\" expected"; + case 191: return "\"ReDim\" expected"; + case 192: return "\"Rem\" expected"; + case 193: return "\"RemoveHandler\" expected"; + case 194: return "\"Resume\" expected"; + case 195: return "\"Return\" expected"; + case 196: return "\"SByte\" expected"; + case 197: return "\"Select\" expected"; + case 198: return "\"Set\" expected"; + case 199: return "\"Shadows\" expected"; + case 200: return "\"Shared\" expected"; + case 201: return "\"Short\" expected"; + case 202: return "\"Single\" expected"; + case 203: return "\"Skip\" expected"; + case 204: return "\"Static\" expected"; + case 205: return "\"Step\" expected"; + case 206: return "\"Stop\" expected"; + case 207: return "\"Strict\" expected"; + case 208: return "\"String\" expected"; + case 209: return "\"Structure\" expected"; + case 210: return "\"Sub\" expected"; + case 211: return "\"SyncLock\" expected"; + case 212: return "\"Take\" expected"; + case 213: return "\"Text\" expected"; + case 214: return "\"Then\" expected"; + case 215: return "\"Throw\" expected"; + case 216: return "\"To\" expected"; + case 217: return "\"True\" expected"; + case 218: return "\"Try\" expected"; + case 219: return "\"TryCast\" expected"; + case 220: return "\"TypeOf\" expected"; + case 221: return "\"UInteger\" expected"; + case 222: return "\"ULong\" expected"; + case 223: return "\"Unicode\" expected"; + case 224: return "\"Until\" expected"; + case 225: return "\"UShort\" expected"; + case 226: return "\"Using\" expected"; + case 227: return "\"Variant\" expected"; + case 228: return "\"Wend\" expected"; + case 229: return "\"When\" expected"; + case 230: return "\"Where\" expected"; + case 231: return "\"While\" expected"; + case 232: return "\"Widening\" expected"; + case 233: return "\"With\" expected"; + case 234: return "\"WithEvents\" expected"; + case 235: return "\"WriteOnly\" expected"; + case 236: return "\"Xor\" expected"; + case 237: return "\"GetXmlNamespace\" expected"; + case 238: return "??? expected"; + case 239: return "this symbol not expected in EndOfStmt"; + case 240: return "invalid EndOfStmt"; + case 241: return "invalid OptionStmt"; + case 242: return "invalid OptionStmt"; + case 243: return "invalid GlobalAttributeSection"; + case 244: return "invalid GlobalAttributeSection"; + case 245: return "invalid NamespaceMemberDecl"; + case 246: return "invalid OptionValue"; + case 247: return "invalid ImportClause"; + case 248: return "invalid Identifier"; + case 249: return "invalid AttributeSection"; + case 250: return "invalid TypeModifier"; + case 251: return "invalid NonModuleDeclaration"; + case 252: return "invalid NonModuleDeclaration"; + case 253: return "invalid TypeParameterConstraints"; + case 254: return "invalid TypeParameterConstraint"; + case 255: return "invalid NonArrayTypeName"; + case 256: return "invalid MemberModifier"; + case 257: return "invalid StructureMemberDecl"; + case 258: return "invalid StructureMemberDecl"; + case 259: return "invalid StructureMemberDecl"; + case 260: return "invalid StructureMemberDecl"; + case 261: return "invalid StructureMemberDecl"; + case 262: return "invalid StructureMemberDecl"; + case 263: return "invalid StructureMemberDecl"; + case 264: return "invalid StructureMemberDecl"; + case 265: return "invalid InterfaceMemberDecl"; + case 266: return "invalid InterfaceMemberDecl"; + case 267: return "invalid Expr"; + case 268: return "invalid Block"; + case 269: return "invalid Charset"; + case 270: return "invalid IdentifierForFieldDeclaration"; + case 271: return "invalid VariableDeclaratorPartAfterIdentifier"; + case 272: return "invalid ObjectCreateExpression"; + case 273: return "invalid ObjectCreateExpression"; + case 274: return "invalid AccessorDecls"; + case 275: return "invalid EventAccessorDeclaration"; + case 276: return "invalid OverloadableOperator"; + case 277: return "invalid EventMemberSpecifier"; + case 278: return "invalid LambdaExpr"; + case 279: return "invalid AssignmentOperator"; + case 280: return "invalid SimpleExpr"; + case 281: return "invalid SimpleNonInvocationExpression"; + case 282: return "invalid SimpleNonInvocationExpression"; + case 283: return "invalid PrimitiveTypeName"; + case 284: return "invalid CastTarget"; + case 285: return "invalid XmlLiteralExpression"; + case 286: return "invalid XmlContentExpression"; + case 287: return "invalid XmlElement"; + case 288: return "invalid XmlElement"; + case 289: return "invalid XmlNestedContent"; + case 290: return "invalid XmlAttribute"; + case 291: return "invalid XmlAttribute"; + case 292: return "invalid ComparisonExpr"; + case 293: return "invalid SubLambdaExpression"; + case 294: return "invalid FunctionLambdaExpression"; + case 295: return "invalid EmbeddedStatement"; + case 296: return "invalid FromOrAggregateQueryOperator"; + case 297: return "invalid QueryOperator"; + case 298: return "invalid PartitionQueryOperator"; + case 299: return "invalid Argument"; + case 300: return "invalid QualIdentAndTypeArguments"; + case 301: return "invalid AttributeArguments"; + case 302: return "invalid AttributeArguments"; + case 303: return "invalid AttributeArguments"; + case 304: return "invalid ParameterModifier"; + case 305: return "invalid Statement"; + case 306: return "invalid LabelName"; + case 307: return "invalid ExitStatement"; + case 308: return "invalid DoLoopStatement"; + case 309: return "invalid ForStatement"; + case 310: return "invalid IfStatement"; + case 311: return "invalid OnErrorStatement"; + case 312: return "invalid ExpressionStatement"; + case 313: return "invalid UsingStatement"; + case 314: return "invalid WhileOrUntil"; + case 315: return "invalid SingleLineStatementList"; + case 316: return "invalid SingleLineStatementList"; + case 317: return "invalid CaseClause"; + case 318: return "invalid CaseClause"; + + default: return "error " + errorNumber; + } + } +} // end Parser + +} // end namespace diff --git a/ICSharpCode.NRefactory.VB/Parser/Parser.frame b/ICSharpCode.NRefactory.VB/Parser/Parser.frame new file mode 100644 index 000000000..4abbfccef --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Parser/Parser.frame @@ -0,0 +1,119 @@ +/*---------------------------------------------------------------------------*\ + Compiler Generator Coco/R, + Copyright (c) 1990, 2004 Hanspeter Moessenboeck, University of Linz + extended by M. Loeberbauer & A. Woess, Univ. of Linz + with improvements by Pat Terry, Rhodes University +------------------------------------------------------------------------------- +License + This file is part of Compiler Generator Coco/R + + This program is free software; you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the + Free Software Foundation; either version 2, or (at your option) any + later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + As an exception, it is allowed to write an extension of Coco/R that is + used as a plugin in non-free software. + + If not otherwise stated, any source code generated by Coco/R (other than + Coco/R itself) does not fall under the GNU General Public License. + +About this file + This is a so-called 'frame' file that contains skeleton code for + generating a final Scanner/Parser code. + + The '-->TAG' text markers are used to delimit code chunks and typically + correspond to places where additional information is added by the + DFA or ParserGen code. + + All information prior to the first 'begin' text marker is discarded. + If the grammar contains a '[copy]' .. '[/copy]' section, its contents + will added instead. +\*---------------------------------------------------------------------------*/ +-->begin + +-->namespace + +// ---------------------------------------------------------------------------- +// Parser +// ---------------------------------------------------------------------------- +//! A Coco/R Parser +partial class VBParser +{ +-->constants + const bool T = true; + const bool x = false; + const int minErrDist = 2; + + public Errors errors; + + +-->declarations + + void Get () { + lexer.NextToken(); +-->pragmas + } + + bool StartOf (int s) { + return set[s].Get(la.kind); + } + + void ExpectWeak (int n, int follow) { + if (la.kind == n) Get(); + else { + SynErr(n); + while (!StartOf(follow)) Get(); + } + } + + + bool WeakSeparator(int n, int syFol, int repFol) { + int kind = la.kind; + if (kind == n) {Get(); return true;} + else if (StartOf(repFol)) {return false;} + else { + SynErr(n); + while (!(set[syFol].Get(kind) || set[repFol].Get(kind) || set[0].Get(kind))) { + Get(); + kind = la.kind; + } + return StartOf(syFol); + } + } + + +-->productions + + public void ParseRoot() { +-->parseRoot + } + + static readonly BitArray[] set = { +-->initialization + }; + + void SynErr(int line, int col, int errorNumber) + { + this.Errors.Error(line, col, GetMessage(errorNumber)); + } + + string GetMessage(int errorNumber) + { + switch (errorNumber) { + -->errors + default: return "error " + errorNumber; + } + } +} // end Parser + +$$$ diff --git a/ICSharpCode.NRefactory.VB/Parser/VBParser.cs b/ICSharpCode.NRefactory.VB/Parser/VBParser.cs new file mode 100644 index 000000000..05c7c7a98 --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Parser/VBParser.cs @@ -0,0 +1,455 @@ +// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; + +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Visitors; + +namespace ICSharpCode.NRefactory.VB.Parser +{ + public partial class VBParser : IDisposable + { + VBLexer lexer; + Stack blockStack; + CompilationUnit compilationUnit; + int errDist = MinErrDist; + bool parseMethodContents = true; + + const int MinErrDist = 2; + const string ErrMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text + + public VBParser(VBLexer lexer) + { + this.errors = lexer.Errors; + errors.SynErr = new ErrorCodeProc(SynErr); + this.lexer = (VBLexer)lexer; + this.blockStack = new Stack(); + } + + void BlockStart(INode block) + { + blockStack.Push(block); + } + + void BlockEnd() + { + blockStack.Pop(); + } + + void AddChild(INode childNode) + { + if (childNode != null) { + INode parent = (INode)blockStack.Peek(); + parent.Children.Add(childNode); + childNode.Parent = parent; + } + } + + StringBuilder qualidentBuilder = new StringBuilder(); + + Token t + { + [System.Diagnostics.DebuggerStepThrough] + get { + return lexer.Token; + } + } + Token la + { + [System.Diagnostics.DebuggerStepThrough] + get { + return lexer.LookAhead; + } + } + + Token Peek (int n) + { + lexer.StartPeek(); + Token x = la; + while (n > 0) { + x = lexer.Peek(); + n--; + } + return x; + } + + public void Error(string s) + { + if (errDist >= MinErrDist) { + this.Errors.Error(la.line, la.col, s); + } + errDist = 0; + } + + public void Parse() + { + ParseRoot(); + compilationUnit.AcceptVisitor(new SetParentVisitor(), null); + } + + public TypeReference ParseTypeReference () + { + // TODO + return null; + } + + public Expression ParseExpression() + { + lexer.SetInitialContext(SnippetType.Expression); + lexer.NextToken(); + Location startLocation = la.Location; + Expression expr; + Expr(out expr); + while (la.kind == Tokens.EOL) lexer.NextToken(); + if (expr != null) { + expr.StartLocation = startLocation; + expr.EndLocation = t.EndLocation; + expr.AcceptVisitor(new SetParentVisitor(), null); + } + Expect(Tokens.EOF); + return expr; + } + + public BlockStatement ParseBlock() + { + lexer.NextToken(); + compilationUnit = new CompilationUnit(); + + Location startLocation = la.Location; + Statement st; + Block(out st); + if (st != null) { + st.StartLocation = startLocation; + if (t != null) + st.EndLocation = t.EndLocation; + else + st.EndLocation = la.Location; + st.AcceptVisitor(new SetParentVisitor(), null); + } + Expect(Tokens.EOF); + return st as BlockStatement; + } + + public List ParseTypeMembers() + { + lexer.NextToken(); + TypeDeclaration newType = new TypeDeclaration(Modifiers.None, null); + BlockStart(newType); + ClassBody(newType); + BlockEnd(); + Expect(Tokens.EOF); + newType.AcceptVisitor(new SetParentVisitor(), null); + return newType.Children; + } + + /* True, if "." is followed by an ident */ + bool DotAndIdentOrKw () { + int peek = Peek(1).kind; + return la.kind == Tokens.Dot && (peek == Tokens.Identifier || peek >= Tokens.AddHandler); + } + + static bool IsIdentifierToken(Token tk) + { + return Tokens.IdentifierTokens[tk.kind] || tk.kind == Tokens.Identifier; + } + + bool IsIdentifiedExpressionRange() + { + // t = Select + // la = Identifier + // Peek(1) = As or Assign + Token token = Peek(1); + return IsIdentifierToken(la) && (token.kind == Tokens.As || token.kind == Tokens.Assign); + } + + bool IsQueryExpression() + { + return (la.kind == Tokens.From || la.kind == Tokens.Aggregate) && IsIdentifierToken(Peek(1)); + } + + bool IsEndStmtAhead() + { + int peek = Peek(1).kind; + return la.kind == Tokens.End && (peek == Tokens.EOL || peek == Tokens.Colon); + } + + bool IsNotClosingParenthesis() { + return la.kind != Tokens.CloseParenthesis; + } + + /* + True, if ident is followed by "=" or by ":" and "=" + */ + bool IsNamedAssign() { + return Peek(1).kind == Tokens.ColonAssign; + } + + bool IsObjectCreation() { + return la.kind == Tokens.As && Peek(1).kind == Tokens.New; + } + + bool IsNewExpression() { + return la.kind == Tokens.New; + } + + /* + True, if "<" is followed by the ident "assembly" or "module" + */ + bool IsGlobalAttrTarget () { + Token pt = Peek(1); + return la.kind == Tokens.LessThan && ( string.Equals(pt.val, "assembly", StringComparison.InvariantCultureIgnoreCase) || string.Equals(pt.val, "module", StringComparison.InvariantCultureIgnoreCase)); + } + + /* + True if the next token is a "(" and is followed by "," or ")" + */ + bool IsDims() + { + int peek = Peek(1).kind; + return la.kind == Tokens.OpenParenthesis + && (peek == Tokens.Comma || peek == Tokens.CloseParenthesis); + } + + /* + True if the next token is an identifier + */ + bool IsLoopVariableDeclaration() + { + if (!IsIdentifierToken(la)) + return false; + lexer.StartPeek(); + Token x = lexer.Peek(); + if (x.kind == Tokens.OpenParenthesis) { + do { + x = lexer.Peek(); + } while (x.kind == Tokens.Comma); + if (x.kind != Tokens.CloseParenthesis) + return false; + x = lexer.Peek(); + } + return x.kind == Tokens.As || x.kind == Tokens.Assign; + } + + bool IsSize() + { + return la.kind == Tokens.OpenParenthesis; + } + + /* + True, if the comma is not a trailing one, + like the last one in: a, b, c, + */ + bool NotFinalComma() { + int peek = Peek(1).kind; + return la.kind == Tokens.Comma && + peek != Tokens.CloseCurlyBrace; + } + + /* + True, if the next token is "Else" and this one + if followed by "If" + */ + bool IsElseIf() + { + int peek = Peek(1).kind; + return la.kind == Tokens.Else && peek == Tokens.If; + } + + /* + True if the next token is goto and this one is + followed by minus ("-") (this is allowd in in + error clauses) + */ + bool IsNegativeLabelName() + { + int peek = Peek(1).kind; + return la.kind == Tokens.GoTo && peek == Tokens.Minus; + } + + /* + True if the next statement is a "Resume next" statement + */ + bool IsResumeNext() + { + int peek = Peek(1).kind; + return la.kind == Tokens.Resume && peek == Tokens.Next; + } + + /// + /// Returns True, if ident/literal integer is followed by ":" + /// + bool IsLabel() + { + return (la.kind == Tokens.Identifier || la.kind == Tokens.LiteralInteger) + && Peek(1).kind == Tokens.Colon; + } + + /// + /// Returns true if a property declaration is an automatic property. + /// + bool IsAutomaticProperty() + { + lexer.StartPeek(); + Token tn = la; + int braceCount = 0; + + // look for attributes + while (tn.kind == Tokens.LessThan) { + while (braceCount > 0 || tn.kind != Tokens.GreaterThan) { + tn = lexer.Peek(); + if (tn.kind == Tokens.OpenParenthesis) + braceCount++; + if (tn.kind == Tokens.CloseParenthesis) + braceCount--; + } + Debug.Assert(tn.kind == Tokens.GreaterThan); + tn = lexer.Peek(); + } + + // look for modifiers + var allowedTokens = new[] { + Tokens.Public, Tokens.Protected, + Tokens.Friend, Tokens.Private + }; + + while (allowedTokens.Contains(tn.kind)) + tn = lexer.Peek(); + + if (tn.Kind != Tokens.Get && tn.Kind != Tokens.Set) + return true; + + return false; + } + + bool IsNotStatementSeparator() + { + return la.kind == Tokens.Colon && Peek(1).kind == Tokens.EOL; + } + + static bool IsMustOverride(ModifierList m) + { + return m.Contains(Modifiers.Abstract); + } + + /* Writes the type name represented through the expression into the string builder. */ + /* Returns true when the expression was converted successfully, returns false when */ + /* There was an unknown expression (e.g. TypeReferenceExpression) in it */ + bool WriteFullTypeName(StringBuilder b, Expression expr) + { + MemberReferenceExpression fre = expr as MemberReferenceExpression; + if (fre != null) { + bool result = WriteFullTypeName(b, fre.TargetObject); + if (b.Length > 0) b.Append('.'); + b.Append(fre.MemberName); + return result; + } else if (expr is IdentifierExpression) { + b.Append(((IdentifierExpression)expr).Identifier); + return true; + } else { + return false; + } + } + + /* + True, if lookahead is a local attribute target specifier, + i.e. one of "event", "return", "field", "method", + "module", "param", "property", or "type" + */ + bool IsLocalAttrTarget() { + // TODO + return false; + } + + void EnsureIsZero(Expression expr) + { + if (!(expr is PrimitiveExpression) || (expr as PrimitiveExpression).StringValue != "0") + Error("lower bound of array must be zero"); + } + + /// + /// Adds a child item to a collection stored in the parent node. + /// Also set's the item's parent to . + /// Does nothing if item is null. + /// + static void SafeAdd(INode parent, List list, T item) where T : class, INode + { + Debug.Assert(parent != null); + Debug.Assert((parent is INullable) ? !(parent as INullable).IsNull : true); + if (item != null) { + list.Add(item); + item.Parent = parent; + } + } + + + + public bool ParseMethodBodies { + get { + return parseMethodContents; + } + set { + parseMethodContents = value; + } + } + + public VBLexer Lexer { + get { + return lexer; + } + } + + public Errors Errors { + get { + return errors; + } + } + + public CompilationUnit CompilationUnit { + get { + return compilationUnit; + } + } + + void SynErr(int n) + { + if (errDist >= MinErrDist) { + errors.SynErr(lexer.LookAhead.line, lexer.LookAhead.col, n); + } + errDist = 0; + } + + void SemErr(string msg) + { + if (errDist >= MinErrDist) { + errors.Error(lexer.Token.line, lexer.Token.col, msg); + } + errDist = 0; + } + + void Expect(int n) + { + if (lexer.LookAhead.kind == n) { + lexer.NextToken(); + } else { + SynErr(n); + } + } + + #region System.IDisposable interface implementation + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly")] + public void Dispose() + { + errors = null; + if (lexer != null) { + lexer.Dispose(); + } + lexer = null; + } + #endregion + } +} diff --git a/ICSharpCode.NRefactory.VB/Parser/vb.atg b/ICSharpCode.NRefactory.VB/Parser/vb.atg new file mode 100644 index 000000000..3df4fad5e --- /dev/null +++ b/ICSharpCode.NRefactory.VB/Parser/vb.atg @@ -0,0 +1,3811 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; +using System.Text; +using ICSharpCode.NRefactory.VB.Dom; +using ICSharpCode.NRefactory.VB.Parser; +using ASTAttribute = ICSharpCode.NRefactory.VB.Dom.Attribute; + +COMPILER VB + +/* START AUTOGENERATED TOKENS SECTION */ +TOKENS + /* ----- terminal classes ----- */ + /* EOF is 0 */ + EOL + ident + LiteralString + LiteralCharacter + LiteralInteger + LiteralDouble + LiteralSingle + LiteralDecimal + LiteralDate + XmlOpenTag + XmlCloseTag + XmlStartInlineVB + XmlEndInlineVB + XmlCloseTagEmptyElement + XmlOpenEndTag + XmlContent + XmlComment + XmlCData + XmlProcessingInstruction + + /* ----- special character ----- */ + "=" + ":" + "," + "&" + "/" + "\\" + "." + "..." + ".@" + "!" + "-" + "+" + "^" + "?" + "*" + "{" + "}" + "(" + ")" + ">" + "<" + "<>" + ">=" + "<=" + "<<" + ">>" + "+=" + "^=" + "-=" + "*=" + "/=" + "\\=" + "<<=" + ">>=" + "&=" + ":=" + + /* ----- keywords ----- */ + "AddHandler" + "AddressOf" + "Aggregate" + "Alias" + "And" + "AndAlso" + "Ansi" + "As" + "Ascending" + "Assembly" + "Auto" + "Binary" + "Boolean" + "ByRef" + "By" + "Byte" + "ByVal" + "Call" + "Case" + "Catch" + "CBool" + "CByte" + "CChar" + "CDate" + "CDbl" + "CDec" + "Char" + "CInt" + "Class" + "CLng" + "CObj" + "Compare" + "Const" + "Continue" + "CSByte" + "CShort" + "CSng" + "CStr" + "CType" + "CUInt" + "CULng" + "CUShort" + "Custom" + "Date" + "Decimal" + "Declare" + "Default" + "Delegate" + "Descending" + "Dim" + "DirectCast" + "Distinct" + "Do" + "Double" + "Each" + "Else" + "ElseIf" + "End" + "EndIf" + "Enum" + "Equals" + "Erase" + "Error" + "Event" + "Exit" + "Explicit" + "False" + "Finally" + "For" + "Friend" + "From" + "Function" + "Get" + "GetType" + "Global" + "GoSub" + "GoTo" + "Group" + "Handles" + "If" + "Implements" + "Imports" + "In" + "Infer" + "Inherits" + "Integer" + "Interface" + "Into" + "Is" + "IsNot" + "Join" + "Key" + "Let" + "Lib" + "Like" + "Long" + "Loop" + "Me" + "Mod" + "Module" + "MustInherit" + "MustOverride" + "MyBase" + "MyClass" + "Namespace" + "Narrowing" + "New" + "Next" + "Not" + "Nothing" + "NotInheritable" + "NotOverridable" + "Object" + "Of" + "Off" + "On" + "Operator" + "Option" + "Optional" + "Or" + "Order" + "OrElse" + "Out" + "Overloads" + "Overridable" + "Overrides" + "ParamArray" + "Partial" + "Preserve" + "Private" + "Property" + "Protected" + "Public" + "RaiseEvent" + "ReadOnly" + "ReDim" + "Rem" + "RemoveHandler" + "Resume" + "Return" + "SByte" + "Select" + "Set" + "Shadows" + "Shared" + "Short" + "Single" + "Skip" + "Static" + "Step" + "Stop" + "Strict" + "String" + "Structure" + "Sub" + "SyncLock" + "Take" + "Text" + "Then" + "Throw" + "To" + "True" + "Try" + "TryCast" + "TypeOf" + "UInteger" + "ULong" + "Unicode" + "Until" + "UShort" + "Using" + "Variant" + "Wend" + "When" + "Where" + "While" + "Widening" + "With" + "WithEvents" + "WriteOnly" + "Xor" + "GetXmlNamespace" +/* END AUTOGENERATED TOKENS SECTION */ + +PRODUCTIONS + +VB + (. + lexer.NextToken(); // get the first token + compilationUnit = new CompilationUnit(); + BlockStart(compilationUnit); + .) += + { EndOfStmt } + { OptionStmt { EndOfStmt } } + { ImportsStmt { EndOfStmt } } + { IF (IsGlobalAttrTarget()) GlobalAttributeSection { EndOfStmt } } + { NamespaceMemberDecl { EndOfStmt } } +. + +OptionStmt (. INode node = null; bool val = true; .) = + "Option" (. Location startPos = t.Location; .) + ( + "Explicit" [ OptionValue ] + (. node = new OptionDeclaration(OptionType.Explicit, val); .) + | + "Strict" [ OptionValue ] + (. node = new OptionDeclaration(OptionType.Strict, val); .) + | + "Compare" ( "Binary" (. node = new OptionDeclaration(OptionType.CompareBinary, val); .) + | "Text" (. node = new OptionDeclaration(OptionType.CompareText, val); .) + ) + | + "Infer" [ OptionValue ] + (. node = new OptionDeclaration(OptionType.Infer, val); .) + ) + EndOfStmt + (. + if (node != null) { + node.StartLocation = startPos; + node.EndLocation = t.Location; + AddChild(node); + } + .) +. + +OptionValue = + ( + "On" (. val = true; .) + | + "Off" (. val = false; .) + ) + . + +EndOfStmt = + SYNC ( EOL | ":" ) +. + +ImportsStmt + (.List usings = new List(); + .) = + "Imports" + (. + Location startPos = t.Location; + Using u; + .) + ImportClause (. if (u != null) { usings.Add(u); } .) + { + "," ImportClause (. if (u != null) { usings.Add(u); } .) + } + EndOfStmt + (. + UsingDeclaration usingDeclaration = new UsingDeclaration(usings); + usingDeclaration.StartLocation = startPos; + usingDeclaration.EndLocation = t.Location; + AddChild(usingDeclaration); + .) + . + +ImportClause + (. + string qualident = null; + TypeReference aliasedType = null; + u = null; + .) = + ( + Qualident + [ "=" TypeName ] + (. + if (qualident != null && qualident.Length > 0) { + if (aliasedType != null) { + u = new Using(qualident, aliasedType); + } else { + u = new Using(qualident); + } + } + .) + ) | ( (. string prefix = null; .) + XmlOpenTag Identifier (. prefix = t.val; .) "=" LiteralString (. u = new Using(t.literalValue as string, prefix); .) XmlCloseTag + ) + . + +/* 6.4.2 */ +NamespaceMemberDecl + (. + ModifierList m = new ModifierList(); + AttributeSection section; + List attributes = new List(); + string qualident; + .) = + ("Namespace" + (. + Location startPos = t.Location; + .) + Qualident + (. + INode node = new NamespaceDeclaration(qualident); + node.StartLocation = startPos; + AddChild(node); + BlockStart(node); + .) + EndOfStmt + NamespaceBody + (. + node.EndLocation = t.Location; + BlockEnd(); + .) + ) | ( + { AttributeSection (. attributes.Add(section); .) } + { TypeModifier } NonModuleDeclaration ) + . + +/* 4.9.1 */ +TypeParameterList<.List templates.> +(. + TemplateDefinition template; +.) += + [ + IF (la.kind == Tokens.OpenParenthesis && Peek(1).kind == Tokens.Of) + "(" "Of" TypeParameter + (. + if (template != null) templates.Add(template); + .) + { + "," TypeParameter + (. + if (template != null) templates.Add(template); + .) + } + ")" + ] +. + +/* 4.9.1 */ +TypeParameter + (. VarianceModifier modifier = VarianceModifier.Invariant; Location startLocation = la.Location; .) += + ( + [ "In" (. modifier = VarianceModifier.Contravariant; .) + | IF (la.kind == Tokens.Out && IsIdentifierToken(Peek(1))) "Out" (. modifier = VarianceModifier.Covariant; .) + ] + Identifier (. template = new TemplateDefinition(t.val, null) { VarianceModifier = modifier }; .) + [TypeParameterConstraints