Browse Source

Merge NRefactory '0b56b42bc817d29e14d231ac1f3a1b9ad3115b2d' into SharpDevelop newNR branch.

newNRvisualizers
Daniel Grunwald 13 years ago
parent
commit
e9cf96d653
  1. 32
      SharpDevelop.Tests.sln
  2. 24
      SharpDevelop.sln
  3. 6
      TODOnewNR.txt
  4. 4
      src/AddIns/Analysis/UnitTesting/Gui/UnitTestsPad.cs
  5. 4
      src/AddIns/Analysis/UnitTesting/Model/TestClass.cs
  6. 6
      src/AddIns/Analysis/UnitTesting/Model/TestProject.cs
  7. 2
      src/AddIns/Analysis/UnitTesting/Service/RegisteredTestFrameworks.cs
  8. 6
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/CSharpSemanticHighlighter.cs
  9. 6
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/CodeManipulation.cs
  10. 4
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpCompletionContext.cs
  11. 41
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpCompletionDataFactory.cs
  12. 8
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/ExtensionMethods.cs
  13. 8
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/CSharpFormattingStrategy.cs
  14. 18
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Parser/CSharpFullParseInformation.cs
  15. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Parser/CSharpSymbolSearch.cs
  16. 28
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Parser/Parser.cs
  17. 4
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Project/VBNetToCSharpConverter.cs
  18. 6
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Refactoring/SDScript.cs
  19. 2
      src/AddIns/BackendBindings/CSharpBinding/Tests/OverrideCompletionTests.cs
  20. 4
      src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlCompletionItemList.cs
  21. 12
      src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlFullParseInformation.cs
  22. 2
      src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlOutlineContentHost.xaml.cs
  23. 14
      src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlParsedFile.cs
  24. 8
      src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlParser.cs
  25. 2
      src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlResolver.cs
  26. 2
      src/AddIns/Debugger/Debugger.Tests/Tests/ExpressionEvaluatorVisitor_Tests.cs
  27. 6
      src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/CodeEditor.cs
  28. 2
      src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/IconBarManager.cs
  29. 2
      src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/ParserFoldingStrategy.cs
  30. 10
      src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/QuickClassBrowser.cs
  31. 2
      src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/Snippets/CodeSnippet.cs
  32. 10
      src/AddIns/DisplayBindings/XmlEditor/Test/Utils/MockDocument.cs
  33. 12
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Document/RopeTextSource.cs
  34. 12
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextDocument.cs
  35. 9
      src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Utils/CharRope.cs
  36. 2
      src/Libraries/NRefactory/.gitignore
  37. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.AstVerifier/.gitignore
  38. 116
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.AstVerifier/ICSharpCode.NRefactory.CSharp.AstVerifier.csproj
  39. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.AstVerifier/Main.cs
  40. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/.gitignore
  41. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DefiniteAssignmentAnalysis.cs
  42. 42
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNode.cs
  43. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/DepthFirstAstVisitor.cs
  44. 54
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayInitializerExpression.cs
  45. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/NamespaceDeclaration.cs
  46. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/IAstVisitor.cs
  47. 1292
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ObservableAstVisitor.cs
  48. 46
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SyntaxTree.cs
  49. 1201
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/old_ObservableAstVisitor.cs
  50. 103
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/CSharpProjectContent.cs
  51. 115
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs
  52. 33
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngineBase.cs
  53. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpParameterCompletionEngine.cs
  54. 65
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CompletionDataWrapper.cs
  55. 33
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionContextProvider.cs
  56. 7
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionDataFactory.cs
  57. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/AstFormattingVisitor.cs
  58. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/GeneratedCodeSettings.cs
  59. 31
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj
  60. 5
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs
  61. 20
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CodeDomConvertVisitor.cs
  62. 264
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CSharpParser.cs
  63. 103
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/SeekableStreamReader.cs
  64. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolFile.cs
  65. 81
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolTable.cs
  66. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/SourceMethodBuilder.cs
  67. 41
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/anonymous.cs
  68. 16
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/argument.cs
  69. 16
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assign.cs
  70. 14
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/async.cs
  71. 45
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/attribute.cs
  72. 40
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cfold.cs
  73. 27
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/class.cs
  74. 16
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/codegen.cs
  75. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/const.cs
  76. 25
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/context.cs
  77. 7354
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.cs
  78. 205
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.jay
  79. 282
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-tokenizer.cs
  80. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/decl.cs
  81. 5
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/delegate.cs
  82. 19
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/doc.cs
  83. 74
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/driver.cs
  84. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dynamic.cs
  85. 108
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ecore.cs
  86. 9
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/eval.cs
  87. 67
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/expression.cs
  88. 5
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/field.cs
  89. 56
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/generic.cs
  90. 53
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/import.cs
  91. 54
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/location.cs
  92. 7
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/membercache.cs
  93. 71
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/method.cs
  94. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/module.cs
  95. 135
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/namespace.cs
  96. 12
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/nullable.cs
  97. 18
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/outline.cs
  98. 19
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/property.cs
  99. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/report.cs
  100. 23
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/settings.cs
  101. Some files were not shown because too many files have changed in this diff Show More

32
SharpDevelop.Tests.sln

@ -310,37 +310,37 @@ Global @@ -310,37 +310,37 @@ Global
{70966F84-74C9-4067-A379-0C674A929233}.Release|x86.Build.0 = Release|Any CPU
{70966F84-74C9-4067-A379-0C674A929233}.Release|x86.ActiveCfg = Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|x86.Build.0 = Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|x86.ActiveCfg = Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|x86.ActiveCfg = net_4_5_Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|Any CPU.Build.0 = Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|x86.Build.0 = Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|x86.ActiveCfg = Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|x86.ActiveCfg = net_4_5_Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|x86.Build.0 = Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|x86.ActiveCfg = Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|x86.ActiveCfg = net_4_5_Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|Any CPU.Build.0 = Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|x86.Build.0 = Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|x86.ActiveCfg = Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|x86.ActiveCfg = net_4_5_Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|x86.Build.0 = Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|x86.ActiveCfg = Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|x86.ActiveCfg = net_4_5_Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|Any CPU.Build.0 = Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|x86.Build.0 = Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|x86.ActiveCfg = Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|x86.ActiveCfg = net_4_5_Release|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.Debug|x86.Build.0 = Debug|x86
{63D3B27A-D966-4902-90B3-30290E1692F1}.Debug|x86.ActiveCfg = Debug|x86
{63D3B27A-D966-4902-90B3-30290E1692F1}.Debug|x86.ActiveCfg = net_4_5_Debug|x86
{63D3B27A-D966-4902-90B3-30290E1692F1}.Release|Any CPU.Build.0 = Release|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.Release|x86.Build.0 = Release|x86
{63D3B27A-D966-4902-90B3-30290E1692F1}.Release|x86.ActiveCfg = Release|x86
{63D3B27A-D966-4902-90B3-30290E1692F1}.Release|x86.ActiveCfg = net_4_5_Release|x86
{52006F3F-3156-45DE-89D8-C4813694FBA4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{52006F3F-3156-45DE-89D8-C4813694FBA4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{52006F3F-3156-45DE-89D8-C4813694FBA4}.Debug|x86.Build.0 = Debug|Any CPU

24
SharpDevelop.sln

@ -234,29 +234,29 @@ Global @@ -234,29 +234,29 @@ Global
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.Release|x86.Build.0 = net_2_0_Debug|Any CPU
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.Release|x86.ActiveCfg = net_4_0_Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|x86.Build.0 = Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|x86.ActiveCfg = Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|x86.ActiveCfg = net_4_5_Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|Any CPU.Build.0 = Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|x86.Build.0 = Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|x86.ActiveCfg = Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|x86.ActiveCfg = net_4_5_Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|x86.Build.0 = Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|x86.ActiveCfg = Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Debug|x86.ActiveCfg = net_4_5_Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|Any CPU.Build.0 = Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|x86.Build.0 = Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|x86.ActiveCfg = Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.Release|x86.ActiveCfg = net_4_5_Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|x86.Build.0 = Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|x86.ActiveCfg = Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Debug|x86.ActiveCfg = net_4_5_Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|Any CPU.Build.0 = Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|x86.Build.0 = Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|x86.ActiveCfg = Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.Release|x86.ActiveCfg = net_4_5_Release|Any CPU
{E618A9CD-A39F-4925-A538-E8A3FEF24E54}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E618A9CD-A39F-4925-A538-E8A3FEF24E54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E618A9CD-A39F-4925-A538-E8A3FEF24E54}.Debug|x86.Build.0 = Debug|Any CPU

6
TODOnewNR.txt

@ -25,7 +25,7 @@ Stuff that was renamed/moved: @@ -25,7 +25,7 @@ Stuff that was renamed/moved:
ICSharpCode.SharpDevelop.Dom -> the type system and resolvers now are part of ICSharpCode.NRefactory
IDocument -> moved to ICSharpCode.NRefactory.Editor
IClass -> ITypeDefinition
ICompilationUnit -> IParsedFile
ISyntaxTree -> IUnresolvedFile
ITextBuffer -> ITextSource (in ICSharpCode.NRefactory.Editor)
IReturnType -> ITypeReference (unresolved) or IType (resolved)
Location -> TextLocation in ICSharpCode.NRefactory
@ -77,8 +77,8 @@ Functionality changes: @@ -77,8 +77,8 @@ Functionality changes:
The result of a parser run (ParseInformation) now may contain a fully parsed AST.
The ParserService may cache such full ASTs, but may also drop them from memory at any time.
This will be implemented by keeping the last N accessed files in the cache. (currently we just keep the caches around forever)
Every parse information also contains an IParsedFile instance with the type system information.
The IParsedFile is stored permanently (both in ParserService and in the IProjectContents).
Every parse information also contains an IUnresolvedFile instance with the type system information.
The IUnresolvedFile is stored permanently (both in ParserService and in the IProjectContents).
Context Actions vs. Member Context Menu:

4
src/AddIns/Analysis/UnitTesting/Gui/UnitTestsPad.cs

@ -24,7 +24,7 @@ namespace ICSharpCode.UnitTesting @@ -24,7 +24,7 @@ namespace ICSharpCode.UnitTesting
bool disposed;
DockPanel panel;
ToolBar toolBar;
List<Tuple<IParsedFile, IParsedFile>> pending = new List<Tuple<IParsedFile, IParsedFile>>();
List<Tuple<IUnresolvedFile, IUnresolvedFile>> pending = new List<Tuple<IUnresolvedFile, IUnresolvedFile>>();
static UnitTestsPad instance;
public UnitTestsPad()
@ -154,7 +154,7 @@ namespace ICSharpCode.UnitTesting @@ -154,7 +154,7 @@ namespace ICSharpCode.UnitTesting
/// <summary>
/// Protected method so we can test this method.
/// </summary>
protected void UpdateParseInfo(IParsedFile oldFile, IParsedFile newFile)
protected void UpdateParseInfo(IUnresolvedFile oldFile, IUnresolvedFile newFile)
{
RootUnitTestNode root = (RootUnitTestNode)treeView.Root;
if (root == null) {

4
src/AddIns/Analysis/UnitTesting/Model/TestClass.cs

@ -148,14 +148,14 @@ namespace ICSharpCode.UnitTesting @@ -148,14 +148,14 @@ namespace ICSharpCode.UnitTesting
int i = 0;
while (i < parts.Count) {
var part = parts[i];
if (!definition.Parts.Any(p => p.ParsedFile.FileName == part.ParsedFile.FileName && p.Region == part.Region))
if (!definition.Parts.Any(p => p.UnresolvedFile.FileName == part.UnresolvedFile.FileName && p.Region == part.Region))
parts.RemoveAt(i);
else
i++;
}
foreach (var part in definition.Parts) {
if (!parts.Any(p => p.ParsedFile.FileName == part.ParsedFile.FileName && p.Region == part.Region))
if (!parts.Any(p => p.UnresolvedFile.FileName == part.UnresolvedFile.FileName && p.Region == part.Region))
parts.Add(part);
}
testMembers.RemoveWhere(m => !definition.Methods.Any(dm => dm.ReflectionName == m.Method.ReflectionName && testFrameworks.IsTestMethod(dm, definition.Compilation)));

6
src/AddIns/Analysis/UnitTesting/Model/TestProject.cs

@ -45,11 +45,11 @@ namespace ICSharpCode.UnitTesting @@ -45,11 +45,11 @@ namespace ICSharpCode.UnitTesting
{
var context = new SimpleTypeResolveContext(SD.ParserService.GetCompilation(project).MainAssembly);
IEnumerable<ITypeDefinition> @new;
if (e.NewParsedFile != null)
@new = e.NewParsedFile.TopLevelTypeDefinitions.Select(utd => utd.Resolve(context).GetDefinition()).Where(x => x != null && testFrameworks.IsTestClass(x, SD.ParserService.GetCompilation(project)));
if (e.NewUnresolvedFile != null)
@new = e.NewUnresolvedFile.TopLevelTypeDefinitions.Select(utd => utd.Resolve(context).GetDefinition()).Where(x => x != null && testFrameworks.IsTestClass(x, SD.ParserService.GetCompilation(project)));
else
@new = Enumerable.Empty<ITypeDefinition>();
testClasses.UpdateTestClasses(testFrameworks, testClasses.Where(tc => tc.Parts.Any(td => td.ParsedFile.FileName == e.OldParsedFile.FileName)).Select(tc => new DefaultResolvedTypeDefinition(context, tc.Parts.ToArray())).ToList(), @new.ToList(), null, this);
testClasses.UpdateTestClasses(testFrameworks, testClasses.Where(tc => tc.Parts.Any(td => td.UnresolvedFile.FileName == e.OldUnresolvedFile.FileName)).Select(tc => new DefaultResolvedTypeDefinition(context, tc.Parts.ToArray())).ToList(), @new.ToList(), null, this);
}
public IProject Project {

2
src/AddIns/Analysis/UnitTesting/Service/RegisteredTestFrameworks.cs

@ -76,7 +76,7 @@ namespace ICSharpCode.UnitTesting @@ -76,7 +76,7 @@ namespace ICSharpCode.UnitTesting
IProject GetProject(ITypeDefinition c)
{
if (c != null && ProjectService.OpenSolution != null) {
return ProjectService.OpenSolution.FindProjectContainingFile(c.Parts[0].ParsedFile.FileName);
return ProjectService.OpenSolution.FindProjectContainingFile(c.Parts[0].UnresolvedFile.FileName);
}
return null;
}

6
src/AddIns/BackendBindings/CSharpBinding/Project/Src/CSharpSemanticHighlighter.cs

@ -241,10 +241,10 @@ namespace CSharpBinding @@ -241,10 +241,10 @@ namespace CSharpBinding
this.line = line;
this.lineNumber = lineNumber;
if (Debugger.IsAttached) {
parseInfo.CompilationUnit.AcceptVisitor(this);
parseInfo.SyntaxTree.AcceptVisitor(this);
} else {
try {
parseInfo.CompilationUnit.AcceptVisitor(this);
parseInfo.SyntaxTree.AcceptVisitor(this);
} catch (Exception ex) {
hasCrashed = true;
throw new ApplicationException("Error highlighting line " + lineNumber, ex);
@ -403,7 +403,7 @@ namespace CSharpBinding @@ -403,7 +403,7 @@ namespace CSharpBinding
string symbol = attr.PositionalArguments[0].ConstantValue as string;
if (symbol != null) {
hasConditionalAttribute = true;
var cu = this.resolver.RootNode as CompilationUnit;
var cu = this.resolver.RootNode as SyntaxTree;
if (cu != null) {
if (cu.ConditionalSymbols.Contains(symbol))
return false; // conditional is active

6
src/AddIns/BackendBindings/CSharpBinding/Project/Src/CodeManipulation.cs

@ -211,7 +211,7 @@ namespace CSharpBinding @@ -211,7 +211,7 @@ namespace CSharpBinding
}
// could work to extend selection to set of adjacent statements separated by blank lines
Selection ExtendSelection(ITextEditor editor, CompilationUnit parsedCU, IList<ISpecial> commentsBlankLines, out INode selectedResultNode, Type[] interestingNodeTypes)
Selection ExtendSelection(ITextEditor editor, SyntaxTree parsedCU, IList<ISpecial> commentsBlankLines, out INode selectedResultNode, Type[] interestingNodeTypes)
{
selectedResultNode = null;
@ -394,7 +394,7 @@ namespace CSharpBinding @@ -394,7 +394,7 @@ namespace CSharpBinding
}
// could depend just on IDocument
CompilationUnit ParseDocument(ITextEditor editor, out IList<ISpecial> parsedSpecials)
SyntaxTree ParseDocument(ITextEditor editor, out IList<ISpecial> parsedSpecials)
{
parsedSpecials = null;
var editorLang = EditorContext.GetEditorLanguage(editor);
@ -404,7 +404,7 @@ namespace CSharpBinding @@ -404,7 +404,7 @@ namespace CSharpBinding
parser.ParseMethodBodies = true;
parser.Lexer.SkipAllComments = false;
parser.Parse();
var parsedCU = parser.CompilationUnit;
var parsedCU = parser.SyntaxTree;
if (parsedCU == null) return null;
foreach (var node in parsedCU.Children) {
// fix StartLocation / EndLocation

4
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpCompletionContext.cs

@ -49,8 +49,8 @@ namespace CSharpBinding.Completion @@ -49,8 +49,8 @@ namespace CSharpBinding.Completion
this.ParseInformation = parseInfo;
this.Compilation = compilation;
this.ProjectContent = projectContent;
this.TypeResolveContextAtCaret = parseInfo.ParsedFile.GetTypeResolveContext(compilation, editor.Caret.Location);
this.CompletionContextProvider = new DefaultCompletionContextProvider(editor.Document, parseInfo.ParsedFile);
this.TypeResolveContextAtCaret = parseInfo.UnresolvedFile.GetTypeResolveContext(compilation, editor.Caret.Location);
this.CompletionContextProvider = new DefaultCompletionContextProvider(editor.Document, parseInfo.UnresolvedFile);
}
}
}

41
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpCompletionDataFactory.cs

@ -33,26 +33,12 @@ namespace CSharpBinding.Completion @@ -33,26 +33,12 @@ namespace CSharpBinding.Completion
}
#region ICompletionDataFactory implementation
public ICompletionData CreateEntityCompletionData(IUnresolvedEntity entity)
{
return new CompletionData(entity.Name) {
Image = ClassBrowserIconService.GetIcon(entity)
};
}
public ICompletionData CreateEntityCompletionData(IUnresolvedEntity entity, string text)
{
return new CompletionData(text) {
Image = ClassBrowserIconService.GetIcon(entity)
};
}
public ICompletionData CreateEntityCompletionData(IEntity entity)
ICompletionData ICompletionDataFactory.CreateEntityCompletionData(IEntity entity)
{
return new EntityCompletionData(entity);
}
public ICompletionData CreateEntityCompletionData(IEntity entity, string text)
ICompletionData ICompletionDataFactory.CreateEntityCompletionData(IEntity entity, string text)
{
return new EntityCompletionData(entity) {
CompletionText = text,
@ -60,19 +46,12 @@ namespace CSharpBinding.Completion @@ -60,19 +46,12 @@ namespace CSharpBinding.Completion
};
}
public ICompletionData CreateTypeCompletionData(IType type, string shortType)
ICompletionData ICompletionDataFactory.CreateTypeCompletionData(IType type, string shortType)
{
return new CompletionData(shortType);
}
public ICompletionData CreateTypeCompletionData(IUnresolvedTypeDefinition type, string shortType)
{
return new CompletionData(shortType) {
Image = ClassBrowserIconService.GetIcon(type)
};
}
public ICompletionData CreateLiteralCompletionData(string title, string description, string insertText)
ICompletionData ICompletionDataFactory.CreateLiteralCompletionData(string title, string description, string insertText)
{
return new CompletionData(title) {
Description = description,
@ -81,36 +60,36 @@ namespace CSharpBinding.Completion @@ -81,36 +60,36 @@ namespace CSharpBinding.Completion
};
}
public ICompletionData CreateNamespaceCompletionData(string name)
ICompletionData ICompletionDataFactory.CreateNamespaceCompletionData(string name)
{
return new CompletionData(name) {
Image = ClassBrowserIconService.Namespace
};
}
public ICompletionData CreateVariableCompletionData(IVariable variable)
ICompletionData ICompletionDataFactory.CreateVariableCompletionData(IVariable variable)
{
return new CompletionData(variable.Name) {
Image = ClassBrowserIconService.LocalVariable
};
}
public ICompletionData CreateVariableCompletionData(IUnresolvedTypeParameter parameter)
ICompletionData ICompletionDataFactory.CreateVariableCompletionData(ITypeParameter parameter)
{
return new CompletionData(parameter.Name);
}
public ICompletionData CreateEventCreationCompletionData(string varName, IType delegateType, IEvent evt, string parameterDefinition, IUnresolvedMember currentMember, IUnresolvedTypeDefinition currentType)
ICompletionData ICompletionDataFactory.CreateEventCreationCompletionData(string varName, IType delegateType, IEvent evt, string parameterDefinition, IUnresolvedMember currentMember, IUnresolvedTypeDefinition currentType)
{
return new CompletionData("TODO: event creation");
}
public ICompletionData CreateNewOverrideCompletionData(int declarationBegin, IUnresolvedTypeDefinition type, IMember m)
ICompletionData ICompletionDataFactory.CreateNewOverrideCompletionData(int declarationBegin, IUnresolvedTypeDefinition type, IMember m)
{
return new OverrideCompletionData(declarationBegin, m, contextAtCaret);
}
public ICompletionData CreateNewPartialCompletionData(int declarationBegin, IUnresolvedTypeDefinition type, IUnresolvedMember m)
ICompletionData ICompletionDataFactory.CreateNewPartialCompletionData(int declarationBegin, IUnresolvedTypeDefinition type, IUnresolvedMember m)
{
return new CompletionData("TODO: partial completion");
}

8
src/AddIns/BackendBindings/CSharpBinding/Project/Src/ExtensionMethods.cs

@ -16,13 +16,13 @@ namespace CSharpBinding @@ -16,13 +16,13 @@ namespace CSharpBinding
/// </summary>
public static class ExtensionMethods
{
public static async Task<CompilationUnit> GetCompilationUnitAsync(this EditorRefactoringContext editorContext)
public static async Task<SyntaxTree> GetSyntaxTreeAsync(this EditorRefactoringContext editorContext)
{
var parseInfo = (await editorContext.GetParseInformationAsync().ConfigureAwait(false)) as CSharpFullParseInformation;
if (parseInfo != null)
return parseInfo.CompilationUnit;
return parseInfo.SyntaxTree;
else
return new CompilationUnit();
return new SyntaxTree();
}
public static Task<CSharpAstResolver> GetAstResolverAsync(this EditorRefactoringContext editorContext)
@ -34,7 +34,7 @@ namespace CSharpBinding @@ -34,7 +34,7 @@ namespace CSharpBinding
if (parseInfo != null)
return parseInfo.GetResolver(compilation);
else
return new CSharpAstResolver(compilation, new CompilationUnit(), new CSharpParsedFile(ec.FileName));
return new CSharpAstResolver(compilation, new SyntaxTree(), new CSharpUnresolvedFile(ec.FileName));
});
}
}

8
src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/CSharpFormattingStrategy.cs

@ -181,12 +181,12 @@ namespace CSharpBinding.FormattingStrategy @@ -181,12 +181,12 @@ namespace CSharpBinding.FormattingStrategy
FileName fileName = editor.FileName;
IUnresolvedEntity nextElement = null;
if (fileName != null) {
IParsedFile parsedFile = SD.ParserService.ParseFile(fileName, editor.Document);
if (parsedFile != null) {
var currentClass = parsedFile.GetInnermostTypeDefinition(caretLine, 0);
IUnresolvedFile unresolvedFile = SD.ParserService.ParseFile(fileName, editor.Document);
if (unresolvedFile != null) {
var currentClass = unresolvedFile.GetInnermostTypeDefinition(caretLine, 0);
int nextElementLine = int.MaxValue;
if (currentClass == null) {
foreach (var c in parsedFile.TopLevelTypeDefinitions) {
foreach (var c in unresolvedFile.TopLevelTypeDefinitions) {
if (c.Region.BeginLine < nextElementLine && c.Region.BeginLine > caretLine) {
nextElementLine = c.Region.BeginLine;
nextElement = c;

18
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Parser/CSharpFullParseInformation.cs

@ -14,25 +14,25 @@ namespace CSharpBinding.Parser @@ -14,25 +14,25 @@ namespace CSharpBinding.Parser
{
public class CSharpFullParseInformation : ParseInformation
{
readonly CompilationUnit compilationUnit;
readonly SyntaxTree compilationUnit;
readonly ITextSourceVersion parsedVersion;
public CSharpFullParseInformation(CSharpParsedFile parsedFile, ITextSourceVersion parsedVersion, CompilationUnit compilationUnit)
: base(parsedFile, isFullParseInformation: true)
public CSharpFullParseInformation(CSharpUnresolvedFile unresolvedFile, ITextSourceVersion parsedVersion, SyntaxTree compilationUnit)
: base(unresolvedFile, isFullParseInformation: true)
{
if (parsedFile == null)
throw new ArgumentNullException("parsedFile");
if (unresolvedFile == null)
throw new ArgumentNullException("unresolvedFile");
if (compilationUnit == null)
throw new ArgumentNullException("compilationUnit");
this.parsedVersion = parsedVersion;
this.compilationUnit = compilationUnit;
}
public new CSharpParsedFile ParsedFile {
get { return (CSharpParsedFile)base.ParsedFile; }
public new CSharpUnresolvedFile UnresolvedFile {
get { return (CSharpUnresolvedFile)base.UnresolvedFile; }
}
public CompilationUnit CompilationUnit {
public SyntaxTree SyntaxTree {
get { return compilationUnit; }
}
@ -43,7 +43,7 @@ namespace CSharpBinding.Parser @@ -43,7 +43,7 @@ namespace CSharpBinding.Parser
public CSharpAstResolver GetResolver(ICompilation compilation)
{
return (CSharpAstResolver)compilation.CacheManager.GetOrAddShared(
this, _ => new CSharpAstResolver(compilation, compilationUnit, ParsedFile)
this, _ => new CSharpAstResolver(compilation, compilationUnit, UnresolvedFile)
);
}
}

2
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Parser/CSharpSymbolSearch.cs

@ -101,7 +101,7 @@ namespace CSharpBinding @@ -101,7 +101,7 @@ namespace CSharpBinding
ISyntaxHighlighter highlighter = null;
List<Reference> results = new List<Reference>();
fr.FindReferencesInFile(
searchScope, parseInfo.ParsedFile, parseInfo.CompilationUnit, compilation,
searchScope, parseInfo.UnresolvedFile, parseInfo.SyntaxTree, compilation,
delegate (AstNode node, ResolveResult result) {
if (document == null) {
document = new ReadOnlyDocument(textSource);

28
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Parser/Parser.cs

@ -37,7 +37,7 @@ namespace CSharpBinding.Parser @@ -37,7 +37,7 @@ namespace CSharpBinding.Parser
}
/*
void RetrieveRegions(ICompilationUnit cu, ICSharpCode.NRefactory.Parser.SpecialTracker tracker)
void RetrieveRegions(ISyntaxTree cu, ICSharpCode.NRefactory.Parser.SpecialTracker tracker)
{
for (int i = 0; i < tracker.CurrentSpecials.Count; ++i) {
ICSharpCode.NRefactory.PreprocessingDirective directive = tracker.CurrentSpecials[i] as ICSharpCode.NRefactory.PreprocessingDirective;
@ -76,10 +76,10 @@ namespace CSharpBinding.Parser @@ -76,10 +76,10 @@ namespace CSharpBinding.Parser
CSharpParser parser = new CSharpParser(csharpProject != null ? csharpProject.CompilerSettings : null);
parser.GenerateTypeSystemMode = !fullParseInformationRequested;
CompilationUnit cu = parser.Parse(fileContent, fileName);
SyntaxTree cu = parser.Parse(fileContent, fileName);
cu.Freeze();
CSharpParsedFile file = cu.ToTypeSystem();
CSharpUnresolvedFile file = cu.ToTypeSystem();
ParseInformation parseInfo;
if (fullParseInformationRequested)
@ -92,7 +92,7 @@ namespace CSharpBinding.Parser @@ -92,7 +92,7 @@ namespace CSharpBinding.Parser
return parseInfo;
}
void AddCommentTags(CompilationUnit cu, IList<TagComment> tagComments, ITextSource fileContent)
void AddCommentTags(SyntaxTree cu, IList<TagComment> tagComments, ITextSource fileContent)
{
ReadOnlyDocument document = null;
foreach (var comment in cu.Descendants.OfType<Comment>().Where(c => c.CommentType != CommentType.InactiveCode)) {
@ -125,22 +125,22 @@ namespace CSharpBinding.Parser @@ -125,22 +125,22 @@ namespace CSharpBinding.Parser
{
var csParseInfo = parseInfo as CSharpFullParseInformation;
if (csParseInfo == null)
throw new ArgumentException("Parse info does not have CompilationUnit");
throw new ArgumentException("Parse info does not have SyntaxTree");
return ResolveAtLocation.Resolve(compilation, csParseInfo.ParsedFile, csParseInfo.CompilationUnit, location, cancellationToken);
return ResolveAtLocation.Resolve(compilation, csParseInfo.UnresolvedFile, csParseInfo.SyntaxTree, location, cancellationToken);
}
public void FindLocalReferences(ParseInformation parseInfo, ITextSource fileContent, IVariable variable, ICompilation compilation, Action<Reference> callback, CancellationToken cancellationToken)
{
var csParseInfo = parseInfo as CSharpFullParseInformation;
if (csParseInfo == null)
throw new ArgumentException("Parse info does not have CompilationUnit");
throw new ArgumentException("Parse info does not have SyntaxTree");
ReadOnlyDocument document = null;
ISyntaxHighlighter highlighter = null;
new FindReferences().FindLocalReferences(
variable, csParseInfo.ParsedFile, csParseInfo.CompilationUnit, compilation,
variable, csParseInfo.UnresolvedFile, csParseInfo.SyntaxTree, compilation,
delegate (AstNode node, ResolveResult result) {
if (document == null) {
document = new ReadOnlyDocument(fileContent);
@ -164,11 +164,11 @@ namespace CSharpBinding.Parser @@ -164,11 +164,11 @@ namespace CSharpBinding.Parser
return assemblies.Select(asm => new CecilLoader().LoadAssemblyFile(asm.Location)).ToArray();
});
public ICompilation CreateCompilationForSingleFile(FileName fileName, IParsedFile parsedFile)
public ICompilation CreateCompilationForSingleFile(FileName fileName, IUnresolvedFile unresolvedFile)
{
return new CSharpProjectContent()
.AddAssemblyReferences(defaultReferences.Value)
.UpdateProjectContent(null, parsedFile)
.UpdateProjectContent(null, unresolvedFile)
.CreateCompilation();
}
@ -176,16 +176,16 @@ namespace CSharpBinding.Parser @@ -176,16 +176,16 @@ namespace CSharpBinding.Parser
{
var csParseInfo = parseInfo as CSharpFullParseInformation;
if (csParseInfo == null)
throw new ArgumentException("Parse info does not have CompilationUnit");
CSharpAstResolver contextResolver = new CSharpAstResolver(compilation, csParseInfo.CompilationUnit, csParseInfo.ParsedFile);
var node = csParseInfo.CompilationUnit.GetNodeAt(location);
throw new ArgumentException("Parse info does not have SyntaxTree");
CSharpAstResolver contextResolver = new CSharpAstResolver(compilation, csParseInfo.SyntaxTree, csParseInfo.UnresolvedFile);
var node = csParseInfo.SyntaxTree.GetNodeAt(location);
CSharpResolver context;
if (node != null)
context = contextResolver.GetResolverStateAfter(node, cancellationToken);
else
context = new CSharpResolver(compilation);
CSharpParser parser = new CSharpParser();
var expr = parser.ParseExpression(new StringReader(codeSnippet));
var expr = parser.ParseExpression(codeSnippet);
if (parser.HasErrors)
return new ErrorResolveResult(SpecialType.UnknownType, PrintErrorsAsString(parser.Errors), TextLocation.Empty);
CSharpAstResolver snippetResolver = new CSharpAstResolver(context, expr);

4
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Project/VBNetToCSharpConverter.cs

@ -64,7 +64,7 @@ namespace CSharpBinding @@ -64,7 +64,7 @@ namespace CSharpBinding
v => v.Replace(ProjectTypeGuids.VBNet, ProjectTypeGuids.CSharp, StringComparison.OrdinalIgnoreCase));
}
protected override void ConvertAst(CompilationUnit compilationUnit, List<ISpecial> specials, FileProjectItem sourceItem)
protected override void ConvertAst(SyntaxTree compilationUnit, List<ISpecial> specials, FileProjectItem sourceItem)
{
PreprocessingDirective.VBToCSharp(specials);
CompilableProject project = (CompilableProject)sourceItem.Project;
@ -82,7 +82,7 @@ namespace CSharpBinding @@ -82,7 +82,7 @@ namespace CSharpBinding
compilationUnit.AcceptVisitor(visitor, null);
}
void RemoveWindowsFormsSpecificCode(CompilationUnit compilationUnit, List<ISpecial> specials, bool keepCode)
void RemoveWindowsFormsSpecificCode(SyntaxTree compilationUnit, List<ISpecial> specials, bool keepCode)
{
for (int i = 0; i < specials.Count; i++) {
PreprocessingDirective ppd = specials[i] as PreprocessingDirective;

6
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Refactoring/SDScript.cs

@ -49,9 +49,9 @@ namespace CSharpBinding.Refactoring @@ -49,9 +49,9 @@ namespace CSharpBinding.Refactoring
if (parseInfo != null) {
//var startLocation = editor.Document.GetLocation(offset);
//var endLocation = editor.Document.GetLocation(offset + length);
//var node = parseInfo.CompilationUnit.GetNodeContaining(startLocation, endLocation);
//var node = parseInfo.SyntaxTree.GetNodeContaining(startLocation, endLocation);
var formatter = new AstFormattingVisitor(FormattingOptionsFactory.CreateSharpDevelop(), editor.Document, context.TextEditorOptions);
parseInfo.CompilationUnit.AcceptVisitor(formatter);
parseInfo.SyntaxTree.AcceptVisitor(formatter);
var segment = GetSegment(node);
formatter.ApplyChanges(segment.Offset, segment.Length);
} else {
@ -93,7 +93,7 @@ namespace CSharpBinding.Refactoring @@ -93,7 +93,7 @@ namespace CSharpBinding.Refactoring
{
if (parentType == null)
return completedTask;
var currentPart = parentType.Parts.FirstOrDefault(p => p.ParsedFile != null && string.Equals(p.ParsedFile.FileName, editor.FileName, StringComparison.OrdinalIgnoreCase));
var currentPart = parentType.Parts.FirstOrDefault(p => p.UnresolvedFile != null && string.Equals(p.UnresolvedFile.FileName, editor.FileName, StringComparison.OrdinalIgnoreCase));
if (currentPart != null) {
var insertionPoints = InsertionPoint.GetInsertionPoints(editor.Document, currentPart);
if (insertionPoints.Count > 0) {

2
src/AddIns/BackendBindings/CSharpBinding/Tests/OverrideCompletionTests.cs

@ -55,7 +55,7 @@ class DerivedClass : BaseClass { @@ -55,7 +55,7 @@ class DerivedClass : BaseClass {
textEditor.Document.Text = programStart + "override " + programEnd;
textEditor.Caret.Offset = programStart.Length + "override ".Length;
var parseInfo = textEditor.CreateParseInformation();
var pc = new CSharpProjectContent().UpdateProjectContent(null, parseInfo.ParsedFile);
var pc = new CSharpProjectContent().UpdateProjectContent(null, parseInfo.UnresolvedFile);
pc = pc.AddAssemblyReferences(new[] { Corlib });
var compilation = pc.CreateCompilation();
SD.Services.AddService(typeof(IParserService), MockRepository.GenerateStrictMock<IParserService>());

4
src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlCompletionItemList.cs

@ -144,7 +144,7 @@ namespace ICSharpCode.XamlBinding @@ -144,7 +144,7 @@ namespace ICSharpCode.XamlBinding
// static bool CreateEventHandlerCode(CompletionContext context, NewEventCompletionItem completionItem, out int discriminator)
// {
// ParseInformation p = ParserService.GetParseInformation(context.Editor.FileName);
// var unit = p.CompilationUnit;
// var unit = p.SyntaxTree;
// var loc = context.Editor.Document.OffsetToPosition(context.StartOffset);
// IClass c = unit.GetInnermostClass(loc.Line, loc.Column);
//
@ -188,7 +188,7 @@ namespace ICSharpCode.XamlBinding @@ -188,7 +188,7 @@ namespace ICSharpCode.XamlBinding
//
// node.Modifier = Modifiers.None;
//
// IViewContent viewContent = FileService.OpenFile(part.CompilationUnit.FileName, XamlBindingOptions.SwitchToCodeViewAfterInsertion);
// IViewContent viewContent = FileService.OpenFile(part.SyntaxTree.FileName, XamlBindingOptions.SwitchToCodeViewAfterInsertion);
// IFileDocumentProvider document = viewContent as IFileDocumentProvider;
//
// if (viewContent != null && document != null) {

12
src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlFullParseInformation.cs

@ -13,11 +13,11 @@ namespace ICSharpCode.XamlBinding @@ -13,11 +13,11 @@ namespace ICSharpCode.XamlBinding
readonly AXmlDocument document;
readonly ITextSource text;
public XamlFullParseInformation(XamlParsedFile parsedFile, AXmlDocument document, ITextSource text)
: base(parsedFile, true)
public XamlFullParseInformation(XamlUnresolvedFile unresolvedFile, AXmlDocument document, ITextSource text)
: base(unresolvedFile, true)
{
if (parsedFile == null)
throw new ArgumentNullException("parsedFile");
if (unresolvedFile == null)
throw new ArgumentNullException("unresolvedFile");
if (document == null)
throw new ArgumentNullException("document");
if (text == null)
@ -26,8 +26,8 @@ namespace ICSharpCode.XamlBinding @@ -26,8 +26,8 @@ namespace ICSharpCode.XamlBinding
this.text = text;
}
public new XamlParsedFile ParsedFile {
get { return (XamlParsedFile)base.ParsedFile; }
public new XamlUnresolvedFile UnresolvedFile {
get { return (XamlUnresolvedFile)base.UnresolvedFile; }
}
public AXmlDocument Document {

2
src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlOutlineContentHost.xaml.cs

@ -36,7 +36,7 @@ namespace ICSharpCode.XamlBinding @@ -36,7 +36,7 @@ namespace ICSharpCode.XamlBinding
return;
#warning Reimplement XAML outline
// var cu = e.NewCompilationUnit as XamlCompilationUnit;
// var cu = e.NewSyntaxTree as XamlSyntaxTree;
//
// if (cu != null && cu.TreeRootNode != null)
// UpdateTree(cu.TreeRootNode);

14
src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlParsedFile.cs

@ -22,23 +22,23 @@ using ICSharpCode.SharpDevelop.Refactoring; @@ -22,23 +22,23 @@ using ICSharpCode.SharpDevelop.Refactoring;
namespace ICSharpCode.XamlBinding
{
public sealed class XamlParsedFile : IParsedFile
public sealed class XamlUnresolvedFile : IUnresolvedFile
{
FileName fileName;
AXmlDocument document;
List<Error> errors;
IUnresolvedTypeDefinition[] topLevel;
XamlParsedFile(FileName fileName, AXmlDocument document)
XamlUnresolvedFile(FileName fileName, AXmlDocument document)
{
this.fileName = fileName;
this.document = document;
this.errors = new List<Error>();
}
public static XamlParsedFile Create(FileName fileName, ITextSource fileContent, AXmlDocument document)
public static XamlUnresolvedFile Create(FileName fileName, ITextSource fileContent, AXmlDocument document)
{
XamlParsedFile file = new XamlParsedFile(fileName, document);
XamlUnresolvedFile file = new XamlUnresolvedFile(fileName, document);
file.errors.AddRange(document.SyntaxErrors.Select(err => new Error(ErrorType.Error, err.Description)));
var visitor = new XamlDocumentVisitor(file, fileContent);
@ -114,11 +114,11 @@ namespace ICSharpCode.XamlBinding @@ -114,11 +114,11 @@ namespace ICSharpCode.XamlBinding
{
public DefaultUnresolvedTypeDefinition TypeDefinition { get; private set; }
IParsedFile file;
IUnresolvedFile file;
AXmlDocument currentDocument;
ReadOnlyDocument textDocument;
public XamlDocumentVisitor(IParsedFile file, ITextSource fileContent)
public XamlDocumentVisitor(IUnresolvedFile file, ITextSource fileContent)
{
this.file = file;
textDocument = new ReadOnlyDocument(fileContent);
@ -133,7 +133,7 @@ namespace ICSharpCode.XamlBinding @@ -133,7 +133,7 @@ namespace ICSharpCode.XamlBinding
if (className != null) {
TypeDefinition = new DefaultUnresolvedTypeDefinition(className) {
Kind = TypeKind.Class,
ParsedFile = file,
UnresolvedFile = file,
Region = new DomRegion(file.FileName, textDocument.GetLocation(rootElement.StartOffset), textDocument.GetLocation(rootElement.EndOffset))
};
TypeDefinition.Members.Add(

8
src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlParser.cs

@ -63,12 +63,12 @@ namespace ICSharpCode.XamlBinding @@ -63,12 +63,12 @@ namespace ICSharpCode.XamlBinding
document = parser.ParseIncremental(parserState, fileContent, out newParserState, cancellationToken);
}
parserState = newParserState;
XamlParsedFile parsedFile = XamlParsedFile.Create(fileName, fileContent, document);
XamlUnresolvedFile unresolvedFile = XamlUnresolvedFile.Create(fileName, fileContent, document);
ParseInformation parseInfo;
if (fullParseInformationRequested)
parseInfo = new XamlFullParseInformation(parsedFile, document, fileContent);
parseInfo = new XamlFullParseInformation(unresolvedFile, document, fileContent);
else
parseInfo = new ParseInformation(parsedFile, false);
parseInfo = new ParseInformation(unresolvedFile, false);
AddTagComments(document, parseInfo, fileContent);
return parseInfo;
}
@ -105,7 +105,7 @@ namespace ICSharpCode.XamlBinding @@ -105,7 +105,7 @@ namespace ICSharpCode.XamlBinding
throw new NotImplementedException();
}
public ICompilation CreateCompilationForSingleFile(FileName fileName, IParsedFile parsedFile)
public ICompilation CreateCompilationForSingleFile(FileName fileName, IUnresolvedFile unresolvedFile)
{
// TODO: create a simple compilation with WPF references?
return null;

2
src/AddIns/BackendBindings/XamlBinding/XamlBinding/XamlResolver.cs

@ -136,7 +136,7 @@ namespace ICSharpCode.XamlBinding @@ -136,7 +136,7 @@ namespace ICSharpCode.XamlBinding
ResolveResult ResolveAttributeValue(IMember propertyOrEvent, AXmlAttribute attribute)
{
IType type = parseInfo.ParsedFile.GetTopLevelTypeDefinition(location).Resolve(new SimpleTypeResolveContext(compilation.MainAssembly));
IType type = parseInfo.UnresolvedFile.GetTopLevelTypeDefinition(location).Resolve(new SimpleTypeResolveContext(compilation.MainAssembly));
if (propertyOrEvent is IEvent) {
var memberLookup = new MemberLookup(type.GetDefinition(), compilation.MainAssembly);
var rr = memberLookup.Lookup(new ThisResolveResult(type), attribute.Value, EmptyList<IType>.Instance, false);

2
src/AddIns/Debugger/Debugger.Tests/Tests/ExpressionEvaluatorVisitor_Tests.cs

@ -320,7 +320,7 @@ namespace Debugger.Tests @@ -320,7 +320,7 @@ namespace Debugger.Tests
else
context = new CSharpResolver(compilation);
CSharpParser parser = new CSharpParser();
var expr = parser.ParseExpression(new StringReader(codeSnippet));
var expr = parser.ParseExpression(codeSnippet);
Assert.IsFalse(parser.HasErrors);
CSharpAstResolver snippetResolver = new CSharpAstResolver(context, expr);
return snippetResolver.Resolve(expr, CancellationToken.None);

6
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/CodeEditor.cs

@ -595,14 +595,14 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -595,14 +595,14 @@ namespace ICSharpCode.AvalonEdit.AddIn
if (parseInfo != null && CodeEditorOptions.Instance.EnableQuickClassBrowser) {
// don't create quickClassBrowser for files that don't have any classes
// (but do keep the quickClassBrowser when the last class is removed from a file)
if (quickClassBrowser != null || parseInfo.ParsedFile.TopLevelTypeDefinitions.Count > 0) {
if (quickClassBrowser != null || parseInfo.UnresolvedFile.TopLevelTypeDefinitions.Count > 0) {
if (quickClassBrowser == null) {
quickClassBrowser = new QuickClassBrowser();
quickClassBrowser.JumpAction = (line, col) => ActiveTextEditor.JumpTo(line, col);
SetRow(quickClassBrowser, 0);
this.Children.Add(quickClassBrowser);
}
quickClassBrowser.Update(parseInfo.ParsedFile);
quickClassBrowser.Update(parseInfo.UnresolvedFile);
quickClassBrowser.SelectItemAtCaretPosition(this.ActiveTextEditor.TextArea.Caret.Location);
}
} else {
@ -611,7 +611,7 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -611,7 +611,7 @@ namespace ICSharpCode.AvalonEdit.AddIn
quickClassBrowser = null;
}
}
iconBarManager.UpdateClassMemberBookmarks(parseInfo != null ? parseInfo.ParsedFile : null, document);
iconBarManager.UpdateClassMemberBookmarks(parseInfo != null ? parseInfo.UnresolvedFile : null, document);
primaryTextEditor.UpdateParseInformationForFolding(parseInfo);
if (secondaryTextEditor != null)
secondaryTextEditor.UpdateParseInformationForFolding(parseInfo);

2
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/IconBarManager.cs

@ -42,7 +42,7 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -42,7 +42,7 @@ namespace ICSharpCode.AvalonEdit.AddIn
public event EventHandler RedrawRequested;
public void UpdateClassMemberBookmarks(IParsedFile parseInfo, IDocument document)
public void UpdateClassMemberBookmarks(IUnresolvedFile parseInfo, IDocument document)
{
for (int i = bookmarks.Count - 1; i >= 0; i--) {
if (bookmarks[i] is EntityBookmark)

2
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/ParserFoldingStrategy.cs

@ -52,7 +52,7 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -52,7 +52,7 @@ namespace ICSharpCode.AvalonEdit.AddIn
{
List<NewFolding> newFoldMarkers = new List<NewFolding>();
if (parseInfo != null) {
foreach (var c in parseInfo.ParsedFile.TopLevelTypeDefinitions) {
foreach (var c in parseInfo.UnresolvedFile.TopLevelTypeDefinitions) {
AddClassMembers(c, newFoldMarkers);
}
#warning Additional folding regions

10
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/QuickClassBrowser.cs

@ -117,7 +117,7 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -117,7 +117,7 @@ namespace ICSharpCode.AvalonEdit.AddIn
/// This causes the classes combo box to lose its current selection,
/// so the members combo box will be cleared.
/// </summary>
public void Update(IParsedFile compilationUnit)
public void Update(IUnresolvedFile compilationUnit)
{
runUpdateWhenDropDownClosed = true;
runUpdateWhenDropDownClosedCU = compilationUnit;
@ -130,7 +130,7 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -130,7 +130,7 @@ namespace ICSharpCode.AvalonEdit.AddIn
List<EntityItem> classItems = new List<EntityItem>();
List<EntityItem> memberItems = new List<EntityItem>();
void DoUpdate(IParsedFile compilationUnit)
void DoUpdate(IUnresolvedFile compilationUnit)
{
classItems = new List<EntityItem>();
if (compilationUnit != null) {
@ -146,7 +146,7 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -146,7 +146,7 @@ namespace ICSharpCode.AvalonEdit.AddIn
// Delayed execution - avoid changing combo boxes while the user is browsing the dropdown list.
bool runUpdateWhenDropDownClosed;
IParsedFile runUpdateWhenDropDownClosedCU;
IUnresolvedFile runUpdateWhenDropDownClosedCU;
bool runSelectItemWhenDropDownClosed;
TextLocation runSelectItemWhenDropDownClosedLocation;
@ -242,7 +242,7 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -242,7 +242,7 @@ namespace ICSharpCode.AvalonEdit.AddIn
IUnresolvedTypeDefinition selectedClass = item != null ? item.Entity as IUnresolvedTypeDefinition : null;
memberItems = new List<EntityItem>();
if (selectedClass != null) {
ICompilation compilation = SD.ParserService.GetCompilationForFile(FileName.Create(selectedClass.ParsedFile.FileName));
ICompilation compilation = SD.ParserService.GetCompilationForFile(FileName.Create(selectedClass.UnresolvedFile.FileName));
var context = new SimpleTypeResolveContext(compilation.MainAssembly);
ITypeDefinition compoundClass = selectedClass.Resolve(context).GetDefinition();
if (compoundClass != null) {
@ -250,7 +250,7 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -250,7 +250,7 @@ namespace ICSharpCode.AvalonEdit.AddIn
foreach (var member in compoundClass.Members) {
if (member.IsSynthetic)
continue;
bool isInSamePart = string.Equals(member.UnresolvedMember.ParsedFile.FileName, selectedClass.ParsedFile.FileName, StringComparison.OrdinalIgnoreCase);
bool isInSamePart = string.Equals(member.UnresolvedMember.UnresolvedFile.FileName, selectedClass.UnresolvedFile.FileName, StringComparison.OrdinalIgnoreCase);
memberItems.Add(new EntityItem(member, ambience) { IsInSamePart = isInSamePart });
}
memberItems.Sort();

2
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/Snippets/CodeSnippet.cs

@ -199,7 +199,7 @@ namespace ICSharpCode.AvalonEdit.AddIn.Snippets @@ -199,7 +199,7 @@ namespace ICSharpCode.AvalonEdit.AddIn.Snippets
static IUnresolvedTypeDefinition GetCurrentClass(ITextEditor editor)
{
var parseInfo = SD.ParserService.GetExistingParsedFile(editor.FileName);
var parseInfo = SD.ParserService.GetExistingUnresolvedFile(editor.FileName);
if (parseInfo != null) {
return parseInfo.GetInnermostTypeDefinition(editor.Caret.Location);
}

10
src/AddIns/DisplayBindings/XmlEditor/Test/Utils/MockDocument.cs

@ -238,5 +238,15 @@ namespace XmlEditor.Tests.Utils @@ -238,5 +238,15 @@ namespace XmlEditor.Tests.Utils
{
throw new NotImplementedException();
}
public void WriteTextTo(TextWriter writer)
{
throw new NotImplementedException();
}
public void WriteTextTo(TextWriter writer, int offset, int length)
{
throw new NotImplementedException();
}
}
}

12
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Document/RopeTextSource.cs

@ -136,5 +136,17 @@ namespace ICSharpCode.AvalonEdit.Document @@ -136,5 +136,17 @@ namespace ICSharpCode.AvalonEdit.Document
{
return rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
rope.WriteTo(writer, 0, rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
rope.WriteTo(writer, offset, length);
}
}
}

12
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextDocument.cs

@ -370,6 +370,18 @@ namespace ICSharpCode.AvalonEdit.Document @@ -370,6 +370,18 @@ namespace ICSharpCode.AvalonEdit.Document
return new RopeTextReader(rope.GetRange(offset, length));
}
}
public void WriteTextTo(System.IO.TextWriter writer)
{
VerifyAccess();
rope.WriteTo(writer, 0, rope.Length);
}
public void WriteTextTo(System.IO.TextWriter writer, int offset, int length)
{
VerifyAccess();
rope.WriteTo(writer, offset, length);
}
#endregion
#region BeginUpdate / EndUpdate

9
src/Libraries/AvalonEdit/ICSharpCode.AvalonEdit/Utils/CharRope.cs

@ -3,6 +3,7 @@ @@ -3,6 +3,7 @@
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace ICSharpCode.AvalonEdit.Utils
@ -42,14 +43,14 @@ namespace ICSharpCode.AvalonEdit.Utils @@ -42,14 +43,14 @@ namespace ICSharpCode.AvalonEdit.Utils
}
/// <summary>
/// Retrieves the text for a portion of the rope and writes it to the specified string builder.
/// Retrieves the text for a portion of the rope and writes it to the specified text writer.
/// Runs in O(lg N + M), where M=<paramref name="length"/>.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
/// <remarks>
/// This method counts as a read access and may be called concurrently to other read accesses.
/// </remarks>
public static void WriteTo(this Rope<char> rope, StringBuilder output, int startIndex, int length)
public static void WriteTo(this Rope<char> rope, TextWriter output, int startIndex, int length)
{
if (rope == null)
throw new ArgumentNullException("rope");
@ -111,7 +112,7 @@ namespace ICSharpCode.AvalonEdit.Utils @@ -111,7 +112,7 @@ namespace ICSharpCode.AvalonEdit.Utils
}
}
internal static void WriteTo(this RopeNode<char> node, int index, StringBuilder output, int count)
internal static void WriteTo(this RopeNode<char> node, int index, TextWriter output, int count)
{
if (node.height == 0) {
if (node.contents == null) {
@ -119,7 +120,7 @@ namespace ICSharpCode.AvalonEdit.Utils @@ -119,7 +120,7 @@ namespace ICSharpCode.AvalonEdit.Utils
node.GetContentNode().WriteTo(index, output, count);
} else {
// leaf node: append data
output.Append(node.contents, index, count);
output.Write(node.contents, index, count);
}
} else {
// concat node: do recursive calls

2
src/Libraries/NRefactory/.gitignore vendored

@ -1,3 +1,5 @@ @@ -1,3 +1,5 @@
bin
obj
/lib/*.dll
/ICSharpCode.NRefactory.Tests/PartCover/*
_ReSharper*/*

3
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.AstVerifier/.gitignore vendored

@ -1,3 +0,0 @@ @@ -1,3 +0,0 @@
bin/
obj/

116
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.AstVerifier/ICSharpCode.NRefactory.CSharp.AstVerifier.csproj

@ -1,49 +1,69 @@ @@ -1,49 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{961DADFA-7CE6-429F-BC22-47630D6DB826}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>ICSharpCode.NRefactory.CSharp.AstVerifier</RootNamespace>
<AssemblyName>AstVerifier</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Main.cs" />
<Compile Include="AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<ProjectReference Include="..\ICSharpCode.NRefactory.CSharp\ICSharpCode.NRefactory.CSharp.csproj">
<Project>{53DCA265-3C3C-42F9-B647-F72BA678122B}</Project>
<Name>ICSharpCode.NRefactory.CSharp</Name>
</ProjectReference>
<ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj">
<Project>{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}</Project>
<Name>ICSharpCode.NRefactory</Name>
</ProjectReference>
</ItemGroup>
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{961DADFA-7CE6-429F-BC22-47630D6DB826}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>ICSharpCode.NRefactory.CSharp.AstVerifier</RootNamespace>
<AssemblyName>AstVerifier</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Externalconsole>true</Externalconsole>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Externalconsole>true</Externalconsole>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Main.cs" />
<Compile Include="AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<ProjectReference Include="..\ICSharpCode.NRefactory.CSharp\ICSharpCode.NRefactory.CSharp.csproj">
<Project>{53DCA265-3C3C-42F9-B647-F72BA678122B}</Project>
<Name>ICSharpCode.NRefactory.CSharp</Name>
</ProjectReference>
<ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj">
<Project>{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}</Project>
<Name>ICSharpCode.NRefactory</Name>
</ProjectReference>
</ItemGroup>
</Project>

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.AstVerifier/Main.cs

@ -59,7 +59,7 @@ namespace ICSharpCode.NRefactory.CSharp.AstVerifier @@ -59,7 +59,7 @@ namespace ICSharpCode.NRefactory.CSharp.AstVerifier
if (!file.EndsWith (".cs"))
continue;
string text = File.ReadAllText (file);
var unit = CompilationUnit.Parse (text, file);
var unit = SyntaxTree.Parse (text, file);
if (unit == null)
continue;
string generated = unit.GetText ();

3
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/.gitignore vendored

@ -1,3 +0,0 @@ @@ -1,3 +0,0 @@
bin/
obj/

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/DefiniteAssignmentAnalysis.cs

@ -443,7 +443,7 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis @@ -443,7 +443,7 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
// the special values are valid as output only, not as input
Debug.Assert(data == CleanSpecialValues(data));
DefiniteAssignmentStatus status = data;
foreach (AstNode child in node.Children) {
for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) {
analysis.analysisCancellationToken.ThrowIfCancellationRequested();
Debug.Assert(!(child is Statement)); // statements are visited with the CFG, not with the visitor pattern

42
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNode.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// AstNode.cs
//
// Author:
@ -23,6 +23,7 @@ @@ -23,6 +23,7 @@
// 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 System.Collections;
using System.Collections.Generic;
@ -194,13 +195,13 @@ namespace ICSharpCode.NRefactory.CSharp @@ -194,13 +195,13 @@ namespace ICSharpCode.NRefactory.CSharp
/// <summary>
/// Gets the region from StartLocation to EndLocation for this node.
/// The file name of the region is set based on the parent CompilationUnit's file name.
/// The file name of the region is set based on the parent SyntaxTree's file name.
/// If this node is not connected to a whole compilation, the file name will be null.
/// </summary>
public ICSharpCode.NRefactory.TypeSystem.DomRegion GetRegion()
{
var cu = (this.Ancestors.LastOrDefault() ?? this) as CompilationUnit;
string fileName = (cu != null ? cu.FileName : null);
var syntaxTree = (this.Ancestors.LastOrDefault() ?? this) as SyntaxTree;
string fileName = (syntaxTree != null ? syntaxTree.FileName : null);
return new ICSharpCode.NRefactory.TypeSystem.DomRegion(fileName, this.StartLocation, this.EndLocation);
}
@ -288,17 +289,31 @@ namespace ICSharpCode.NRefactory.CSharp @@ -288,17 +289,31 @@ namespace ICSharpCode.NRefactory.CSharp
/// Gets all descendants of this node (excluding this node itself).
/// </summary>
public IEnumerable<AstNode> Descendants {
get {
return Utils.TreeTraversal.PreOrder (this.Children, n => n.Children);
}
get { return GetDescendants(false); }
}
/// <summary>
/// Gets all descendants of this node (including this node itself).
/// </summary>
public IEnumerable<AstNode> DescendantsAndSelf {
get {
return Utils.TreeTraversal.PreOrder (this, n => n.Children);
get { return GetDescendants(true); }
}
IEnumerable<AstNode> GetDescendants(bool includeSelf)
{
if (includeSelf)
yield return this;
Stack<AstNode> nextStack = new Stack<AstNode>();
nextStack.Push(null);
AstNode pos = firstChild;
while (pos != null) {
if (pos.nextSibling != null)
nextStack.Push(pos.nextSibling);
yield return pos;
if (pos.firstChild != null)
pos = pos.firstChild;
else
pos = nextStack.Pop();
}
}
@ -322,7 +337,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -322,7 +337,7 @@ namespace ICSharpCode.NRefactory.CSharp
{
return Ancestors.OfType<T>().FirstOrDefault();
}
public AstNodeCollection<T> GetChildrenByRole<T> (Role<T> role) where T : AstNode
{
return new AstNodeCollection<T> (this, role);
@ -367,13 +382,6 @@ namespace ICSharpCode.NRefactory.CSharp @@ -367,13 +382,6 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
public void InsertChildsBefore<T>(AstNode nextSibling, Role<T> role, params T[] child) where T : AstNode
{
foreach (var cur in child) {
InsertChildBefore(nextSibling, cur, role);
}
}
public void InsertChildBefore<T> (AstNode nextSibling, T child, Role<T> role) where T : AstNode
{
if (role == null)

8
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/DepthFirstAstVisitor.cs

@ -44,9 +44,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -44,9 +44,9 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
public virtual void VisitCompilationUnit (CompilationUnit unit)
public virtual void VisitSyntaxTree (SyntaxTree syntaxTree)
{
VisitChildren (unit);
VisitChildren (syntaxTree);
}
public virtual void VisitComment(Comment comment)
@ -642,7 +642,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -642,7 +642,7 @@ namespace ICSharpCode.NRefactory.CSharp
return default (T);
}
public virtual T VisitCompilationUnit (CompilationUnit unit)
public virtual T VisitSyntaxTree (SyntaxTree unit)
{
return VisitChildren (unit);
}
@ -1240,7 +1240,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1240,7 +1240,7 @@ namespace ICSharpCode.NRefactory.CSharp
return default (S);
}
public virtual S VisitCompilationUnit (CompilationUnit unit, T data)
public virtual S VisitSyntaxTree (SyntaxTree unit, T data)
{
return VisitChildren (unit, data);
}

54
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayInitializerExpression.cs

@ -34,7 +34,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -34,7 +34,7 @@ namespace ICSharpCode.NRefactory.CSharp
public class ArrayInitializerExpression : Expression
{
/// <summary>
/// For ease of use purposes in the resolver the ast representation
/// For ease of use purposes in the resolver the ast representation
/// of { a, b, c } is { {a}, {b}, {c} }.
/// If IsSingleElement is true then this array initializer expression is a generated one.
/// That has no meaning in the source code (and contains no brace tokens).
@ -73,7 +73,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -73,7 +73,7 @@ namespace ICSharpCode.NRefactory.CSharp
public override void AcceptVisitor (IAstVisitor visitor)
{
}
public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
{
return default (T);
@ -107,7 +107,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -107,7 +107,7 @@ namespace ICSharpCode.NRefactory.CSharp
{
visitor.VisitArrayInitializerExpression (this);
}
public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
{
return visitor.VisitArrayInitializerExpression (this);
@ -138,8 +138,54 @@ namespace ICSharpCode.NRefactory.CSharp @@ -138,8 +138,54 @@ namespace ICSharpCode.NRefactory.CSharp
return true;
}
}
}
#region PatternPlaceholder
public static implicit operator ArrayInitializerExpression(PatternMatching.Pattern pattern)
{
return pattern != null ? new PatternPlaceholder(pattern) : null;
}
sealed class PatternPlaceholder : ArrayInitializerExpression, PatternMatching.INode
{
readonly PatternMatching.Pattern child;
public PatternPlaceholder(PatternMatching.Pattern child)
{
this.child = child;
}
public override NodeType NodeType {
get { return NodeType.Pattern; }
}
public override void AcceptVisitor (IAstVisitor visitor)
{
visitor.VisitPatternPlaceholder(this, child);
}
public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
{
return visitor.VisitPatternPlaceholder(this, child);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitPatternPlaceholder(this, child, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
return child.DoMatch(other, match);
}
bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
{
return child.DoMatchCollection(role, pos, match, backtrackingInfo);
}
}
#endregion
}
}

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/NamespaceDeclaration.cs

@ -35,7 +35,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -35,7 +35,7 @@ namespace ICSharpCode.NRefactory.CSharp
/// </summary>
public class NamespaceDeclaration : AstNode
{
public static readonly Role<AstNode> MemberRole = CompilationUnit.MemberRole;
public static readonly Role<AstNode> MemberRole = SyntaxTree.MemberRole;
public override NodeType NodeType {
get {

6
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/IAstVisitor.cs

@ -129,7 +129,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -129,7 +129,7 @@ namespace ICSharpCode.NRefactory.CSharp
void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration);
void VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer);
void VisitCompilationUnit(CompilationUnit compilationUnit);
void VisitSyntaxTree(SyntaxTree syntaxTree);
void VisitSimpleType(SimpleType simpleType);
void VisitMemberType(MemberType memberType);
void VisitComposedType(ComposedType composedType);
@ -260,7 +260,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -260,7 +260,7 @@ namespace ICSharpCode.NRefactory.CSharp
S VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration);
S VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer);
S VisitCompilationUnit(CompilationUnit compilationUnit);
S VisitSyntaxTree(SyntaxTree syntaxTree);
S VisitSimpleType(SimpleType simpleType);
S VisitMemberType(MemberType memberType);
S VisitComposedType(ComposedType composedType);
@ -391,7 +391,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -391,7 +391,7 @@ namespace ICSharpCode.NRefactory.CSharp
S VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration, T data);
S VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer, T data);
S VisitCompilationUnit(CompilationUnit compilationUnit, T data);
S VisitSyntaxTree(SyntaxTree syntaxTree, T data);
S VisitSimpleType(SimpleType simpleType, T data);
S VisitMemberType(MemberType memberType, T data);
S VisitComposedType(ComposedType composedType, T data);

1292
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ObservableAstVisitor.cs

File diff suppressed because it is too large Load Diff

46
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/CompilationUnit.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SyntaxTree.cs

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
//
// CompilationUnit.cs
// SyntaxTree.cs
//
// Author:
// Mike Krüger <mkrueger@novell.com>
@ -23,6 +23,7 @@ @@ -23,6 +23,7 @@
// 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 System.Collections.Generic;
using ICSharpCode.NRefactory.CSharp.Resolver;
@ -35,7 +36,10 @@ using ICSharpCode.NRefactory.Editor; @@ -35,7 +36,10 @@ using ICSharpCode.NRefactory.Editor;
namespace ICSharpCode.NRefactory.CSharp
{
public class CompilationUnit : AstNode
[Obsolete("CompilationUnit was renamed to SyntaxTree", true)]
public class CompilationUnit {}
public class SyntaxTree : AstNode
{
public static readonly Role<AstNode> MemberRole = new Role<AstNode>("Member", AstNode.Null);
@ -48,7 +52,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -48,7 +52,7 @@ namespace ICSharpCode.NRefactory.CSharp
string fileName;
/// <summary>
/// Gets/Sets the file name of this compilation unit.
/// Gets/Sets the file name of this syntax tree.
/// </summary>
public string FileName {
get { return fileName; }
@ -97,7 +101,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -97,7 +101,7 @@ namespace ICSharpCode.NRefactory.CSharp
internal set;
}
public CompilationUnit ()
public SyntaxTree ()
{
}
@ -120,59 +124,59 @@ namespace ICSharpCode.NRefactory.CSharp @@ -120,59 +124,59 @@ namespace ICSharpCode.NRefactory.CSharp
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
CompilationUnit o = other as CompilationUnit;
SyntaxTree o = other as SyntaxTree;
return o != null && GetChildrenByRole(MemberRole).DoMatch(o.GetChildrenByRole(MemberRole), match);
}
public override void AcceptVisitor (IAstVisitor visitor)
{
visitor.VisitCompilationUnit (this);
visitor.VisitSyntaxTree (this);
}
public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
{
return visitor.VisitCompilationUnit (this);
return visitor.VisitSyntaxTree (this);
}
public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitCompilationUnit (this, data);
return visitor.VisitSyntaxTree (this, data);
}
/// <summary>
/// Converts this compilation unit into a parsed file that can be stored in the type system.
/// Converts this syntax tree into a parsed file that can be stored in the type system.
/// </summary>
public CSharpParsedFile ToTypeSystem ()
public CSharpUnresolvedFile ToTypeSystem ()
{
if (string.IsNullOrEmpty (this.FileName))
throw new InvalidOperationException ("Cannot use ToTypeSystem() on a compilation unit without file name.");
throw new InvalidOperationException ("Cannot use ToTypeSystem() on a syntax tree without file name.");
var v = new TypeSystemConvertVisitor (this.FileName);
v.VisitCompilationUnit (this);
return v.ParsedFile;
v.VisitSyntaxTree (this);
return v.UnresolvedFile;
}
public static CompilationUnit Parse (string text, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
public static SyntaxTree Parse (string program, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
{
var parser = new CSharpParser (settings);
return parser.Parse (text, fileName);
return parser.Parse (program, fileName);
}
public static CompilationUnit Parse (TextReader reader, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
public static SyntaxTree Parse (TextReader reader, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
{
var parser = new CSharpParser (settings);
return parser.Parse (reader, fileName, 0);
return parser.Parse (reader, fileName);
}
public static CompilationUnit Parse (Stream stream, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
public static SyntaxTree Parse (Stream stream, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
{
var parser = new CSharpParser (settings);
return parser.Parse (stream, fileName, 0);
return parser.Parse (stream, fileName);
}
public static CompilationUnit Parse (ITextSource textSource, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
public static SyntaxTree Parse (ITextSource textSource, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
{
var parser = new CSharpParser (settings);
return parser.Parse (textSource, fileName, 0);
return parser.Parse (textSource, fileName);
}
}
}

1201
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/old_ObservableAstVisitor.cs

File diff suppressed because it is too large Load Diff

103
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/CSharpProjectContent.cs

@ -31,15 +31,15 @@ namespace ICSharpCode.NRefactory.CSharp @@ -31,15 +31,15 @@ namespace ICSharpCode.NRefactory.CSharp
public class CSharpProjectContent : IProjectContent
{
string assemblyName;
string projectFileName;
string location;
Dictionary<string, IParsedFile> parsedFiles;
Dictionary<string, IUnresolvedFile> unresolvedFiles;
List<IAssemblyReference> assemblyReferences;
CompilerSettings compilerSettings;
public CSharpProjectContent()
{
this.assemblyName = string.Empty;
this.parsedFiles = new Dictionary<string, IParsedFile>(Platform.FileNameComparer);
this.unresolvedFiles = new Dictionary<string, IUnresolvedFile>(Platform.FileNameComparer);
this.assemblyReferences = new List<IAssemblyReference>();
this.compilerSettings = new CompilerSettings();
compilerSettings.Freeze();
@ -48,20 +48,25 @@ namespace ICSharpCode.NRefactory.CSharp @@ -48,20 +48,25 @@ namespace ICSharpCode.NRefactory.CSharp
protected CSharpProjectContent(CSharpProjectContent pc)
{
this.assemblyName = pc.assemblyName;
this.projectFileName = pc.projectFileName;
this.location = pc.location;
this.parsedFiles = new Dictionary<string, IParsedFile>(pc.parsedFiles, Platform.FileNameComparer);
this.unresolvedFiles = new Dictionary<string, IUnresolvedFile>(pc.unresolvedFiles, Platform.FileNameComparer);
this.assemblyReferences = new List<IAssemblyReference>(pc.assemblyReferences);
this.compilerSettings = pc.compilerSettings;
}
public IEnumerable<IParsedFile> Files {
get { return parsedFiles.Values; }
public IEnumerable<IUnresolvedFile> Files {
get { return unresolvedFiles.Values; }
}
public IEnumerable<IAssemblyReference> AssemblyReferences {
get { return assemblyReferences; }
}
public string ProjectFileName {
get { return projectFileName; }
}
public string AssemblyName {
get { return assemblyName; }
}
@ -96,10 +101,10 @@ namespace ICSharpCode.NRefactory.CSharp @@ -96,10 +101,10 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
public IParsedFile GetFile(string fileName)
public IUnresolvedFile GetFile(string fileName)
{
IParsedFile file;
if (parsedFiles.TryGetValue(fileName, out file))
IUnresolvedFile file;
if (unresolvedFiles.TryGetValue(fileName, out file))
return file;
else
return null;
@ -129,11 +134,18 @@ namespace ICSharpCode.NRefactory.CSharp @@ -129,11 +134,18 @@ namespace ICSharpCode.NRefactory.CSharp
pc.assemblyName = newAssemblyName;
return pc;
}
public IProjectContent SetProjectFileName(string newProjectFileName)
{
CSharpProjectContent pc = Clone();
pc.projectFileName = newProjectFileName;
return pc;
}
public IProjectContent SetLocation(string location)
public IProjectContent SetLocation(string newLocation)
{
CSharpProjectContent pc = Clone();
pc.location = location;
pc.location = newLocation;
return pc;
}
@ -148,6 +160,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -148,6 +160,11 @@ namespace ICSharpCode.NRefactory.CSharp
}
public IProjectContent AddAssemblyReferences(IEnumerable<IAssemblyReference> references)
{
return AddAssemblyReferences(references.ToArray());
}
public IProjectContent AddAssemblyReferences(params IAssemblyReference[] references)
{
CSharpProjectContent pc = Clone();
pc.assemblyReferences.AddRange(references);
@ -155,13 +172,62 @@ namespace ICSharpCode.NRefactory.CSharp @@ -155,13 +172,62 @@ namespace ICSharpCode.NRefactory.CSharp
}
public IProjectContent RemoveAssemblyReferences(IEnumerable<IAssemblyReference> references)
{
return RemoveAssemblyReferences(references.ToArray());
}
public IProjectContent RemoveAssemblyReferences(params IAssemblyReference[] references)
{
CSharpProjectContent pc = Clone();
pc.assemblyReferences.RemoveAll(r => references.Contains(r));
foreach (var r in references)
pc.assemblyReferences.Remove(r);
return pc;
}
public IProjectContent UpdateProjectContent(IParsedFile oldFile, IParsedFile newFile)
/// <summary>
/// Adds the specified files to the project content.
/// If a file with the same name already exists, updated the existing file.
/// </summary>
public IProjectContent AddOrUpdateFiles(IEnumerable<IUnresolvedFile> newFiles)
{
CSharpProjectContent pc = Clone();
foreach (var file in newFiles) {
pc.unresolvedFiles[file.FileName] = file;
}
return pc;
}
/// <summary>
/// Adds the specified files to the project content.
/// If a file with the same name already exists, this method updates the existing file.
/// </summary>
public IProjectContent AddOrUpdateFiles(params IUnresolvedFile[] newFiles)
{
return AddOrUpdateFiles((IEnumerable<IUnresolvedFile>)newFiles);
}
/// <summary>
/// Removes the files with the specified names.
/// </summary>
public IProjectContent RemoveFiles(IEnumerable<string> fileNames)
{
CSharpProjectContent pc = Clone();
foreach (var fileName in fileNames) {
pc.unresolvedFiles.Remove(fileName);
}
return pc;
}
/// <summary>
/// Removes the files with the specified names.
/// </summary>
public IProjectContent RemoveFiles(params string[] fileNames)
{
return RemoveFiles((IEnumerable<string>)fileNames);
}
[Obsolete("Use RemoveFiles/AddOrUpdateFiles instead")]
public IProjectContent UpdateProjectContent(IUnresolvedFile oldFile, IUnresolvedFile newFile)
{
if (oldFile == null && newFile == null)
return this;
@ -171,23 +237,24 @@ namespace ICSharpCode.NRefactory.CSharp @@ -171,23 +237,24 @@ namespace ICSharpCode.NRefactory.CSharp
}
CSharpProjectContent pc = Clone();
if (newFile == null)
pc.parsedFiles.Remove(oldFile.FileName);
pc.unresolvedFiles.Remove(oldFile.FileName);
else
pc.parsedFiles[newFile.FileName] = newFile;
pc.unresolvedFiles[newFile.FileName] = newFile;
return pc;
}
public IProjectContent UpdateProjectContent(IEnumerable<IParsedFile> oldFiles, IEnumerable<IParsedFile> newFiles)
[Obsolete("Use RemoveFiles/AddOrUpdateFiles instead")]
public IProjectContent UpdateProjectContent(IEnumerable<IUnresolvedFile> oldFiles, IEnumerable<IUnresolvedFile> newFiles)
{
CSharpProjectContent pc = Clone();
if (oldFiles != null) {
foreach (var oldFile in oldFiles) {
pc.parsedFiles.Remove(oldFile.FileName);
pc.unresolvedFiles.Remove(oldFile.FileName);
}
}
if (newFiles != null) {
foreach (var newFile in newFiles) {
pc.parsedFiles.Add(newFile.FileName, newFile);
pc.unresolvedFiles.Add(newFile.FileName, newFile);
}
}
return pc;

115
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs

@ -48,7 +48,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -48,7 +48,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
public string EolMarker { get; set; }
public string IndentString { get; set; }
#endregion
#endregion
#region Result properties
public bool AutoCompleteEmptyMatch;
@ -230,7 +230,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -230,7 +230,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return miniLexer.IsInPreprocessorDirective;
}
IEnumerable<ICompletionData> HandleObjectInitializer(CompilationUnit unit, AstNode n)
IEnumerable<ICompletionData> HandleObjectInitializer(SyntaxTree unit, AstNode n)
{
var p = n.Parent;
while (p != null && !(p is ObjectCreateExpression)) {
@ -262,7 +262,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -262,7 +262,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return contextList.Result;
}
foreach (var m in initializerResult.Item1.Type.GetMembers (m => !m.IsSynthetic && m.IsPublic && (m.EntityType == EntityType.Property || m.EntityType == EntityType.Field))) {
foreach (var m in initializerResult.Item1.Type.GetMembers (m => m.IsPublic && (m.EntityType == EntityType.Property || m.EntityType == EntityType.Field))) {
contextList.AddMember(m);
}
@ -543,7 +543,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -543,7 +543,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var wrapper = new CompletionDataWrapper(this);
if (currentType != null) {
// bool includeProtected = DomType.IncludeProtected (dom, typeFromDatabase, resolver.CallingType);
foreach (var method in currentType.Methods) {
foreach (var method in ctx.CurrentTypeDefinition.Methods) {
if (MatchDelegate(delegateType, method) /*&& method.IsAccessibleFrom (dom, resolver.CallingType, resolver.CallingMember, includeProtected) &&*/) {
wrapper.AddMember(method);
// data.SetText (data.CompletionText + ";");
@ -723,7 +723,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -723,7 +723,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
// var astResolver = new CSharpAstResolver(
// GetState(),
// identifierStart.Unit,
// CSharpParsedFile
// CSharpUnresolvedFile
// );
//
// foreach (var type in CreateFieldAction.GetValidTypes(astResolver, (Expression)n)) {
@ -1027,15 +1027,15 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1027,15 +1027,15 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
IEnumerable<ICompletionData> HandleEnumContext()
{
var cu = ParseStub("a", false);
if (cu == null) {
var syntaxTree = ParseStub("a", false);
if (syntaxTree == null) {
return null;
}
var curType = cu.GetNodeAt<TypeDeclaration>(location);
var curType = syntaxTree.GetNodeAt<TypeDeclaration>(location);
if (curType == null || curType.ClassType != ClassType.Enum) {
cu = ParseStub("a {}", false);
var node = cu.GetNodeAt<AstType>(location);
syntaxTree = ParseStub("a {}", false);
var node = syntaxTree.GetNodeAt<AstType>(location);
if (node != null) {
var wrapper = new CompletionDataWrapper(this);
AddKeywords(wrapper, validEnumBaseTypes);
@ -1043,7 +1043,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1043,7 +1043,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
}
var member = cu.GetNodeAt<EnumMemberDeclaration>(location);
var member = syntaxTree.GetNodeAt<EnumMemberDeclaration>(location);
if (member != null && member.NameToken.EndLocation < location) {
return DefaultControlSpaceItems();
}
@ -1102,7 +1102,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1102,7 +1102,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
xp = GetExpressionAtCursor();
}
AstNode node;
CompilationUnit unit;
SyntaxTree unit;
Tuple<ResolveResult, CSharpResolver> rr;
if (xp != null) {
node = xp.Node;
@ -1172,7 +1172,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1172,7 +1172,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (csResolver == null) {
if (node != null) {
csResolver = GetState();
//var astResolver = new CSharpAstResolver (csResolver, node, xp != null ? xp.Item1 : CSharpParsedFile);
//var astResolver = new CSharpAstResolver (csResolver, node, xp != null ? xp.Item1 : CSharpUnresolvedFile);
try {
//csResolver = astResolver.GetResolverStateBefore (node);
@ -1200,16 +1200,16 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1200,16 +1200,16 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
wrapper.AddVariable(variable);
}
}
if (currentMember is IUnresolvedParameterizedMember && !(node is AstType)) {
var param = (IParameterizedMember)currentMember.CreateResolved(ctx);
if (state.CurrentMember is IParameterizedMember && !(node is AstType)) {
var param = (IParameterizedMember)state.CurrentMember;
foreach (var p in param.Parameters) {
wrapper.AddVariable(p);
}
}
if (currentMember is IUnresolvedMethod) {
var method = (IUnresolvedMethod)currentMember;
if (state.CurrentMember is IMethod) {
var method = (IMethod)state.CurrentMember;
foreach (var p in method.TypeParameters) {
wrapper.AddTypeParameter(p);
}
@ -1319,10 +1319,8 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1319,10 +1319,8 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
{
var lookup = new MemberLookup(ctx.CurrentTypeDefinition, Compilation.MainAssembly);
if (currentType != null) {
for (var ct = currentType; ct != null; ct = ct.DeclaringTypeDefinition) {
for (var ct = ctx.CurrentTypeDefinition; ct != null; ct = ct.DeclaringTypeDefinition) {
foreach (var nestedType in ct.NestedTypes) {
if (nestedType.IsSynthetic)
continue;
string name = nestedType.Name;
if (IsAttributeContext(node) && name.EndsWith("Attribute") && name.Length > "Attribute".Length) {
name = name.Substring(0, name.Length - "Attribute".Length);
@ -1333,7 +1331,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1333,7 +1331,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
continue;
}
var type = typePred(nestedType.Resolve(ctx));
var type = typePred(nestedType);
if (type != null) {
var a2 = wrapper.AddType(type, name);
if (a2 != null && callback != null) {
@ -1351,8 +1349,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1351,8 +1349,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (member is IMethod && ((IMethod)member).FullName == "System.Object.Finalize") {
continue;
}
if (member.IsSynthetic)
continue;
if (member.EntityType == EntityType.Operator) {
continue;
}
@ -1369,7 +1365,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1369,7 +1365,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
var declaring = def.DeclaringTypeDefinition;
while (declaring != null) {
foreach (var member in declaring.GetMembers (m => m.IsStatic && !m.IsSynthetic)) {
foreach (var member in declaring.GetMembers (m => m.IsStatic)) {
if (memberPred == null || memberPred(member)) {
wrapper.AddMember(member);
}
@ -1378,8 +1374,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1378,8 +1374,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
}
}
foreach (var p in currentType.TypeParameters) {
wrapper.AddTypeParameter(p);
if (ctx.CurrentTypeDefinition != null) {
foreach (var p in ctx.CurrentTypeDefinition.TypeParameters) {
wrapper.AddTypeParameter(p);
}
}
}
var scope = ctx.CurrentUsingScope;
@ -1916,7 +1914,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1916,7 +1914,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return;
}
foreach (var m in curType.GetMembers ().Reverse ()) {
if (m.IsSynthetic || curType.Kind != TypeKind.Interface && !m.IsOverridable) {
if (curType.Kind != TypeKind.Interface && !m.IsOverridable) {
continue;
}
// filter out the "Finalize" methods, because finalizers should be done with destructors.
@ -1987,7 +1985,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1987,7 +1985,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return result;
}
bool MatchDelegate(IType delegateType, IUnresolvedMethod method)
bool MatchDelegate(IType delegateType, IMethod method)
{
var delegateMethod = delegateType.GetDelegateInvokeMethod();
if (delegateMethod == null || delegateMethod.Parameters.Count != method.Parameters.Count) {
@ -1995,7 +1993,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1995,7 +1993,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
for (int i = 0; i < delegateMethod.Parameters.Count; i++) {
if (!delegateMethod.Parameters [i].Type.Equals(method.Parameters [i].Type.Resolve(ctx))) {
if (!delegateMethod.Parameters [i].Type.Equals(method.Parameters [i].Type)) {
return false;
}
}
@ -2016,34 +2014,47 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2016,34 +2014,47 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
"delegate",
"Creates anonymous delegate.",
"delegate {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
);
);
}
var sb = new StringBuilder("(");
var sbWithoutTypes = new StringBuilder("(");
var state = GetState();
var builder = new TypeSystemAstBuilder(state);
for (int k = 0; k < delegateMethod.Parameters.Count; k++) {
if (k > 0) {
sb.Append(", ");
sbWithoutTypes.Append(", ");
}
var parameterType = delegateMethod.Parameters [k].Type;
sb.Append(GetShortType(parameterType, GetState()));
sb.Append(" ");
sb.Append(delegateMethod.Parameters [k].Name);
var convertedParameter = builder.ConvertParameter (delegateMethod.Parameters [k]);
if (convertedParameter.ParameterModifier == ParameterModifier.Params)
convertedParameter.ParameterModifier = ParameterModifier.None;
sb.Append(convertedParameter.GetText (FormattingPolicy));
sbWithoutTypes.Append(delegateMethod.Parameters [k].Name);
}
sb.Append(")");
sbWithoutTypes.Append(")");
completionList.AddCustom(
"delegate" + sb,
"Creates anonymous delegate.",
"delegate" + sb + " {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
);
if (!completionList.Result.Any(data => data.DisplayText == sbWithoutTypes.ToString())) {
);
if (!completionList.Result.Any(data => data.DisplayText == sb.ToString())) {
completionList.AddCustom(
sb.ToString(),
"Creates typed lambda expression.",
sb + " => |" + (addSemicolon ? ";" : "")
);
}
if (!delegateMethod.Parameters.Any (p => p.IsOut || p.IsRef) && !completionList.Result.Any(data => data.DisplayText == sbWithoutTypes.ToString())) {
completionList.AddCustom(
sbWithoutTypes.ToString(),
"Creates lambda expression.",
sbWithoutTypes + " => |" + (addSemicolon ? ";" : "")
);
);
}
/* TODO:Make factory method out of it.
// It's needed to temporarly disable inserting auto matching bracket because the anonymous delegates are selectable with '('
@ -2057,7 +2068,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2057,7 +2068,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}*/
return sb.ToString();
}
bool IsAccessibleFrom(IEntity member, ITypeDefinition calledType, IMember currentMember, bool includeProtected)
{
if (currentMember == null) {
@ -2140,7 +2151,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2140,7 +2151,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return null;
}
var exprParent = resolvedNode.GetParent<Expression>();
var unit = exprParent != null ? exprParent.GetParent<CompilationUnit>() : null;
var unit = exprParent != null ? exprParent.GetParent<SyntaxTree>() : null;
var astResolver = unit != null ? CompletionContextProvider.GetResolver(state, unit) : null;
IType hintType = exprParent != null && astResolver != null ?
@ -2151,8 +2162,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2151,8 +2162,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var nr = (NamespaceResolveResult)resolveResult;
if (!(resolvedNode.Parent is UsingDeclaration || resolvedNode.Parent != null && resolvedNode.Parent.Parent is UsingDeclaration)) {
foreach (var cl in nr.Namespace.Types) {
if (cl.IsSynthetic)
continue;
string name = cl.Name;
if (hintType != null && hintType.Kind != TypeKind.Array && cl.Kind == TypeKind.Interface) {
continue;
@ -2189,7 +2198,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2189,7 +2198,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
}
IEnumerable<ICompletionData> CreateParameterCompletion(MethodGroupResolveResult resolveResult, CSharpResolver state, AstNode invocation, CompilationUnit unit, int parameter, bool controlSpace)
IEnumerable<ICompletionData> CreateParameterCompletion(MethodGroupResolveResult resolveResult, CSharpResolver state, AstNode invocation, SyntaxTree unit, int parameter, bool controlSpace)
{
var result = new CompletionDataWrapper(this);
var addedEnums = new HashSet<string>();
@ -2291,8 +2300,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2291,8 +2300,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var namespaceContents = new CompletionDataWrapper(this);
foreach (var cl in nr.Namespace.Types) {
if (cl.IsSynthetic)
continue;
IType addType = typePred != null ? typePred(cl) : cl;
if (addType != null)
namespaceContents.AddType(addType, addType.Name);
@ -2393,8 +2400,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2393,8 +2400,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var filteredList = new List<IMember>();
foreach (var member in type.GetMembers ()) {
if (member.IsSynthetic)
continue;
if (member.EntityType == EntityType.Indexer || member.EntityType == EntityType.Operator || member.EntityType == EntityType.Constructor || member.EntityType == EntityType.Destructor) {
continue;
}
@ -2445,7 +2450,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2445,7 +2450,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
if (resolveResult is TypeResolveResult || includeStaticMembers) {
foreach (var nested in type.GetNestedTypes (t => !t.IsSynthetic)) {
foreach (var nested in type.GetNestedTypes ()) {
if (!lookup.IsAccessible(nested.GetDefinition(), isProtectedAllowed))
continue;
IType addType = typePred != null ? typePred(nested) : nested;
@ -2515,7 +2520,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2515,7 +2520,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
#region Parsing methods
ExpressionResult GetExpressionBeforeCursor()
{
CompilationUnit baseUnit;
SyntaxTree baseUnit;
if (currentMember == null) {
baseUnit = ParseStub("a", false);
var type = baseUnit.GetNodeAt<MemberType>(location);
@ -2746,9 +2751,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2746,9 +2751,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var sb = new StringBuilder(text);
sb.Append("a;");
AppendMissingClosingBrackets(sb, text, false);
var stream = new System.IO.StringReader(sb.ToString());
var completionUnit = parser.Parse(stream, "a.cs", 0);
stream.Close();
var completionUnit = parser.Parse(sb.ToString());
var loc = document.GetLocation(offset);
var expr = completionUnit.GetNodeAt(
@ -2769,9 +2772,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2769,9 +2772,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
sb.Append("a ();");
AppendMissingClosingBrackets(sb, text, false);
var stream = new System.IO.StringReader(sb.ToString());
var completionUnit = parser.Parse(stream, "a.cs", 0);
stream.Close();
var completionUnit = parser.Parse(sb.ToString());
var loc = document.GetLocation(offset);
var expr = completionUnit.GetNodeAt(loc, n => n is Expression);
@ -2780,9 +2781,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2780,9 +2781,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
sb = new StringBuilder(text);
sb.Append("a ()");
AppendMissingClosingBrackets(sb, text, false);
stream = new System.IO.StringReader(sb.ToString());
completionUnit = parser.Parse(stream, "a.cs", 0);
stream.Close();
completionUnit = parser.Parse(sb.ToString());
loc = document.GetLocation(offset);
expr = completionUnit.GetNodeAt(loc, n => n is Expression);

33
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngineBase.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// CSharpCompletionEngineBase.cs
//
// Author:
@ -494,13 +494,13 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -494,13 +494,13 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
state.CurrentMember = currentMember;
state.CurrentTypeDefinition = currentType;
state.CurrentUsingScope = CSharpParsedFile.GetUsingScope (location);
state.CurrentUsingScope = CSharpUnresolvedFile.GetUsingScope (location);
if (state.CurrentMember != null) {
var node = Unit.GetNodeAt (location);
if (node == null)
return state;
var navigator = new NodeListResolveVisitorNavigator (new[] { node });
var visitor = new ResolveVisitor (state, CSharpParsedFile, navigator);
var visitor = new ResolveVisitor (state, CSharpUnresolvedFile, navigator);
Unit.AcceptVisitor (visitor, null);
try {
var newState = visitor.GetResolverStateBefore (node);
@ -655,7 +655,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -655,7 +655,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
wrapper.Append (';');
}
protected CompilationUnit ParseStub(string continuation, bool appendSemicolon = true, string afterContinuation = null)
protected SyntaxTree ParseStub(string continuation, bool appendSemicolon = true, string afterContinuation = null)
{
var mt = GetMemberTextToCaret();
if (mt == null) {
@ -681,17 +681,12 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -681,17 +681,12 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (closingBrackets > 0) {
wrapper.Append(new string('}', closingBrackets));
}
using (var stream = new System.IO.StringReader (wrapper.ToString ())) {
try {
var parser = new CSharpParser ();
var result = parser.Parse(stream, "stub.cs", memberLocation.Line - 1 - generatedLines);
return result;
} catch (Exception) {
Console.WriteLine("------");
Console.WriteLine(wrapper);
throw;
}
}
var parser = new CSharpParser ();
foreach (var sym in CompletionContextProvider.ConditionalSymbols)
parser.CompilerSettings.ConditionalSymbols.Add (sym);
parser.InitialLocation = new TextLocation(memberLocation.Line - generatedLines, 1);
var result = parser.Parse(wrapper.ToString ());
return result;
}
// string cachedText = null;
@ -708,7 +703,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -708,7 +703,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
protected ExpressionResult GetInvocationBeforeCursor(bool afterBracket)
{
CompilationUnit baseUnit;
SyntaxTree baseUnit;
baseUnit = ParseStub("a", false);
var section = baseUnit.GetNodeAt<AttributeSection>(location.Line, location.Column - 2);
@ -763,10 +758,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -763,10 +758,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
public class ExpressionResult
{
public AstNode Node { get; private set; }
public CompilationUnit Unit { get; private set; }
public SyntaxTree Unit { get; private set; }
public ExpressionResult (AstNode item2, CompilationUnit item3)
public ExpressionResult (AstNode item2, SyntaxTree item3)
{
this.Node = item2;
this.Unit = item3;
@ -797,7 +792,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -797,7 +792,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
resolveNode = expr;
}
try {
var root = expr.AncestorsAndSelf.FirstOrDefault(n => n is EntityDeclaration || n is CompilationUnit);
var root = expr.AncestorsAndSelf.FirstOrDefault(n => n is EntityDeclaration || n is SyntaxTree);
if (root == null) {
return null;
}

8
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpParameterCompletionEngine.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// CSharpParameterCompletionEngine.cs
//
// Author:
@ -53,7 +53,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -53,7 +53,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
public ExpressionResult GetIndexerBeforeCursor()
{
CompilationUnit baseUnit;
SyntaxTree baseUnit;
if (currentMember == null && currentType == null) {
return null;
}
@ -73,7 +73,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -73,7 +73,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
public ExpressionResult GetConstructorInitializerBeforeCursor()
{
CompilationUnit baseUnit;
SyntaxTree baseUnit;
if (currentMember == null && currentType == null) {
return null;
}
@ -88,7 +88,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -88,7 +88,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
public ExpressionResult GetTypeBeforeCursor()
{
CompilationUnit baseUnit;
SyntaxTree baseUnit;
if (currentMember == null && currentType == null) {
return null;
}

65
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CompletionDataWrapper.cs

@ -75,31 +75,24 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -75,31 +75,24 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
HashSet<string> usedTypes = new HashSet<string> ();
public ICompletionData AddType(IType type, string shortType)
{
if (type == null || string.IsNullOrEmpty(shortType) || usedTypes.Contains(shortType))
return null;
if (type.Name == "Void" && type.Namespace == "System")
return null;
usedTypes.Add(shortType);
var iCompletionData = Factory.CreateTypeCompletionData(type, shortType);
result.Add(iCompletionData);
return iCompletionData;
}
public ICompletionData AddType(IUnresolvedTypeDefinition type, string shortType)
{
if (type == null || string.IsNullOrEmpty(shortType) || usedTypes.Contains(shortType))
return null;
if (type.Name == "Void" && type.Namespace == "System")
var def = type.GetDefinition ();
if (def != null && def.ParentAssembly != completion.ctx.CurrentAssembly && !def.IsBrowsable ())
return null;
usedTypes.Add(shortType);
var iCompletionData = Factory.CreateTypeCompletionData(type, shortType);
result.Add(iCompletionData);
return iCompletionData;
}
Dictionary<string, List<ICompletionData>> data = new Dictionary<string, List<ICompletionData>> ();
public ICompletionData AddVariable(IVariable variable)
@ -126,59 +119,25 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -126,59 +119,25 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return cd;
}
public void AddTypeParameter (IUnresolvedTypeParameter variable)
public void AddTypeParameter (ITypeParameter variable)
{
if (data.ContainsKey (variable.Name))
return;
data [variable.Name] = new List<ICompletionData> ();
result.Add (Factory.CreateVariableCompletionData (variable));
}
public ICompletionData AddMember (IUnresolvedMember member)
{
var newData = Factory.CreateEntityCompletionData (member);
// newData.HideExtensionParameter = HideExtensionParameter;
string memberKey = newData.DisplayText;
if (memberKey == null)
return null;
if (member is IMember) {
newData.CompletionCategory = GetCompletionCategory (member.DeclaringTypeDefinition.Resolve (completion.ctx));
}
List<ICompletionData> existingData;
data.TryGetValue (memberKey, out existingData);
if (existingData != null) {
var a = member as IEntity;
foreach (var d in existingData) {
if (!(d is IEntityCompletionData))
continue;
var b = ((IEntityCompletionData)d).Entity;
if (a == null || b == null || a.EntityType == b.EntityType) {
d.AddOverload (newData);
return d;
}
}
if (newData != null) {
result.Add (newData);
data [memberKey].Add (newData);
}
} else {
result.Add (newData);
data [memberKey] = new List<ICompletionData> ();
data [memberKey].Add (newData);
}
return newData;
}
public ICompletionData AddMember (IMember member)
{
var newData = Factory.CreateEntityCompletionData (member);
// newData.HideExtensionParameter = HideExtensionParameter;
if (member.ParentAssembly != completion.ctx.CurrentAssembly && !member.IsBrowsable ())
return null;
string memberKey = newData.DisplayText;
if (memberKey == null)
return null;
if (member is IMember) {
newData.CompletionCategory = GetCompletionCategory (member.DeclaringTypeDefinition);
}

33
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionContextProvider.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// IMemberProvider.cs
//
// Author:
@ -35,6 +35,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -35,6 +35,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
{
public interface ICompletionContextProvider
{
IList<string> ConditionalSymbols {
get;
}
void GetCurrentMembers (int offset, out IUnresolvedTypeDefinition currentType, out IUnresolvedMember currentMember);
Tuple<string, TextLocation> GetMemberTextToCaret(int caretOffset, IUnresolvedTypeDefinition currentType, IUnresolvedMember currentMember);
@ -45,18 +49,29 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -45,18 +49,29 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
public class DefaultCompletionContextProvider : ICompletionContextProvider
{
readonly IDocument document;
readonly CSharpParsedFile parsedFile;
readonly CSharpUnresolvedFile unresolvedFile;
readonly List<string> symbols = new List<string> ();
public IList<string> ConditionalSymbols {
get {
return symbols;
}
}
public DefaultCompletionContextProvider (IDocument document, CSharpParsedFile parsedFile)
public DefaultCompletionContextProvider (IDocument document, CSharpUnresolvedFile unresolvedFile)
{
if (document == null)
throw new ArgumentNullException("document");
if (parsedFile == null)
throw new ArgumentNullException("parsedFile");
if (unresolvedFile == null)
throw new ArgumentNullException("unresolvedFile");
this.document = document;
this.parsedFile = parsedFile;
this.unresolvedFile = unresolvedFile;
}
public void AddSymbol (string sym)
{
symbols.Add (sym);
}
public void GetCurrentMembers(int offset, out IUnresolvedTypeDefinition currentType, out IUnresolvedMember currentMember)
{
//var document = engine.document;
@ -64,7 +79,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -64,7 +79,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
currentType = null;
foreach (var type in parsedFile.TopLevelTypeDefinitions) {
foreach (var type in unresolvedFile.TopLevelTypeDefinitions) {
if (type.Region.Begin < location)
currentType = type;
}
@ -189,7 +204,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -189,7 +204,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
public CSharpAstResolver GetResolver (CSharpResolver resolver, AstNode rootNode)
{
return new CSharpAstResolver (resolver, rootNode, parsedFile);
return new CSharpAstResolver (resolver, rootNode, unresolvedFile);
}

7
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionDataFactory.cs

@ -32,14 +32,11 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -32,14 +32,11 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
{
public interface ICompletionDataFactory
{
ICompletionData CreateEntityCompletionData (IUnresolvedEntity entity);
ICompletionData CreateEntityCompletionData (IUnresolvedEntity entity, string text);
ICompletionData CreateEntityCompletionData (IEntity entity);
ICompletionData CreateEntityCompletionData (IEntity entity, string text);
ICompletionData CreateTypeCompletionData (IType type, string shortType);
ICompletionData CreateTypeCompletionData (IUnresolvedTypeDefinition type, string shortType);
/// <summary>
/// Creates a generic completion data.
/// </summary>
@ -58,7 +55,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -58,7 +55,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
ICompletionData CreateVariableCompletionData (IVariable variable);
ICompletionData CreateVariableCompletionData (IUnresolvedTypeParameter parameter);
ICompletionData CreateVariableCompletionData (ITypeParameter parameter);
ICompletionData CreateEventCreationCompletionData (string varName, IType delegateType, IEvent evt, string parameterDefinition, IUnresolvedMember currentMember, IUnresolvedTypeDefinition currentType);

6
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/AstFormattingVisitor.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// AstFormattingVisitor.cs
//
// Author:
@ -199,9 +199,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -199,9 +199,9 @@ namespace ICSharpCode.NRefactory.CSharp
changes.Clear();
}
public override void VisitCompilationUnit(CompilationUnit unit)
public override void VisitSyntaxTree(SyntaxTree unit)
{
base.VisitCompilationUnit(unit);
base.VisitSyntaxTree(unit);
}
public void EnsureBlankLinesAfter(AstNode node, int blankLines)

6
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/GeneratedCodeSettings.cs

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// GeneratedCodeSettings.cs
//
// Author:
@ -177,7 +177,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -177,7 +177,9 @@ namespace ICSharpCode.NRefactory.CSharp
var cmt = new Comment ("", CommentType.SingleLine);
var cmt2 = new Comment (" " + label, CommentType.SingleLine);
var cmt3 = new Comment ("", CommentType.SingleLine);
mem.Parent.InsertChildsBefore (mem, Roles.Comment, cmt, cmt2, cmt3);
mem.Parent.InsertChildBefore (mem, cmt, Roles.Comment);
mem.Parent.InsertChildBefore (mem, cmt2, Roles.Comment);
mem.Parent.InsertChildBefore (mem, cmt3, Roles.Comment);
if (cmt.PrevSibling is EntityDeclaration)
mem.Parent.InsertChildBefore (cmt, new UnixNewLine (), Roles.NewLine);

31
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj

@ -18,8 +18,9 @@ @@ -18,8 +18,9 @@
<AssemblyOriginatorKeyFile>..\ICSharpCode.NRefactory.snk</AssemblyOriginatorKeyFile>
<DelaySign>False</DelaySign>
<AssemblyOriginatorKeyMode>File</AssemblyOriginatorKeyMode>
<DocumentationFile>..\ICSharpCode.NRefactory\bin\$(Configuration)\ICSharpCode.NRefactory.CSharp.xml</DocumentationFile>
<DocumentationFile>..\bin\$(Configuration)\ICSharpCode.NRefactory.CSharp.xml</DocumentationFile>
<NoWarn>1591,1587,1570</NoWarn>
<OutputPath>..\bin\$(Configuration)\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@ -29,13 +30,11 @@ @@ -29,13 +30,11 @@
<FileAlignment>4096</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE;FULL_AST</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE;FULL_AST</DefineConstants>
@ -47,6 +46,25 @@ @@ -47,6 +46,25 @@
<DebugType>full</DebugType>
<DebugSymbols>True</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE;FULL_AST;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|AnyCPU' ">
<DebugType>full</DebugType>
<DebugSymbols>True</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE;FULL_AST;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' ">
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
@ -69,7 +87,7 @@ @@ -69,7 +87,7 @@
<Compile Include="Ast\AstType.cs" />
<Compile Include="Ast\DocumentationReference.cs" />
<Compile Include="Ast\IdentifierExpressionBackreference.cs" />
<Compile Include="Ast\CompilationUnit.cs" />
<Compile Include="Ast\SyntaxTree.cs" />
<Compile Include="Ast\ComposedType.cs" />
<Compile Include="Ast\CSharpModifierToken.cs" />
<Compile Include="Ast\CSharpTokenNode.cs" />
@ -130,6 +148,7 @@ @@ -130,6 +148,7 @@
<Compile Include="Ast\Modifiers.cs" />
<Compile Include="Ast\NodeType.cs" />
<Compile Include="Ast\ObservableAstVisitor.cs" />
<Compile Include="Ast\old_ObservableAstVisitor.cs" />
<Compile Include="Ast\PrimitiveType.cs" />
<Compile Include="Ast\SimpleType.cs" />
<Compile Include="Ast\Statements\BlockStatement.cs" />
@ -241,6 +260,7 @@ @@ -241,6 +260,7 @@
<Compile Include="Parser\mcs\typespec.cs" />
<Compile Include="Parser\mcs\visit.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="QueryExpressionExpander.cs" />
<Compile Include="Refactoring\CodeIssues\ExplicitConversionInForEachIssue.cs" />
<Compile Include="Refactoring\DocumentScript.cs" />
<Compile Include="Refactoring\PatternHelper.cs" />
@ -280,7 +300,7 @@ @@ -280,7 +300,7 @@
<Compile Include="TypeSystem\CSharpAssembly.cs" />
<Compile Include="TypeSystem\CSharpAttribute.cs" />
<Compile Include="TypeSystem\CSharpDocumentationComment.cs" />
<Compile Include="TypeSystem\CSharpParsedFile.cs" />
<Compile Include="TypeSystem\CSharpUnresolvedFile.cs" />
<Compile Include="TypeSystem\CSharpUnresolvedTypeDefinition.cs" />
<Compile Include="TypeSystem\CSharpTypeResolveContext.cs" />
<Compile Include="TypeSystem\ResolvedUsingScope.cs" />
@ -377,6 +397,7 @@ @@ -377,6 +397,7 @@
<Compile Include="Refactoring\CodeActions\ExtractFieldAction.cs" />
<Compile Include="Completion\ICompletionContextProvider.cs" />
<Compile Include="Refactoring\CodeActions\ExtractMethod\VariableUsageAnalyzation.cs" />
<Compile Include="Parser\SeekableStreamReader.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj">

5
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs

@ -2172,6 +2172,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2172,6 +2172,7 @@ namespace ICSharpCode.NRefactory.CSharp
WriteAttributes(indexerDeclaration.Attributes);
WriteModifiers(indexerDeclaration.ModifierTokens);
indexerDeclaration.ReturnType.AcceptVisitor(this);
Space();
WritePrivateImplementationType(indexerDeclaration.PrivateImplementationType);
WriteKeyword(IndexerDeclaration.ThisKeywordRole);
Space(policy.SpaceBeforeMethodDeclarationParentheses);
@ -2304,10 +2305,10 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2304,10 +2305,10 @@ namespace ICSharpCode.NRefactory.CSharp
EndNode(variableInitializer);
}
public void VisitCompilationUnit(CompilationUnit compilationUnit)
public void VisitSyntaxTree(SyntaxTree syntaxTree)
{
// don't do node tracking as we visit all children directly
foreach (AstNode node in compilationUnit.Children) {
foreach (AstNode node in syntaxTree.Children) {
node.AcceptVisitor(this);
}
}

20
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CodeDomConvertVisitor.cs

@ -60,24 +60,24 @@ namespace ICSharpCode.NRefactory.CSharp @@ -60,24 +60,24 @@ namespace ICSharpCode.NRefactory.CSharp
}
/// <summary>
/// Converts a compilation unit to CodeDom.
/// Converts a syntax tree to CodeDom.
/// </summary>
/// <param name="compilationUnit">The input compilation unit.</param>
/// <param name="syntaxTree">The input syntax tree.</param>
/// <param name="compilation">The current compilation.</param>
/// <param name="parsedFile">CSharpParsedFile, used for resolving.</param>
/// <param name="unresolvedFile">CSharpUnresolvedFile, used for resolving.</param>
/// <returns>Converted CodeCompileUnit</returns>
/// <remarks>
/// This conversion process requires a resolver because it needs to distinguish field/property/event references etc.
/// </remarks>
public CodeCompileUnit Convert(ICompilation compilation, CompilationUnit compilationUnit, CSharpParsedFile parsedFile)
public CodeCompileUnit Convert(ICompilation compilation, SyntaxTree syntaxTree, CSharpUnresolvedFile unresolvedFile)
{
if (compilationUnit == null)
throw new ArgumentNullException("compilationUnit");
if (syntaxTree == null)
throw new ArgumentNullException("syntaxTree");
if (compilation == null)
throw new ArgumentNullException("compilation");
CSharpAstResolver resolver = new CSharpAstResolver(compilation, compilationUnit, parsedFile);
return (CodeCompileUnit)Convert(compilationUnit, resolver);
CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
return (CodeCompileUnit)Convert(syntaxTree, resolver);
}
/// <summary>
@ -1236,10 +1236,10 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1236,10 +1236,10 @@ namespace ICSharpCode.NRefactory.CSharp
throw new NotSupportedException(); // should be handled by the parent node
}
CodeObject IAstVisitor<CodeObject>.VisitCompilationUnit(CompilationUnit compilationUnit)
CodeObject IAstVisitor<CodeObject>.VisitSyntaxTree(SyntaxTree syntaxTree)
{
CodeCompileUnit cu = new CodeCompileUnit();
foreach (AstNode node in compilationUnit.Children) {
foreach (AstNode node in syntaxTree.Children) {
CodeObject o = node.AcceptVisitor(this);
CodeNamespace ns = o as CodeNamespace;

264
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CSharpParser.cs

@ -40,10 +40,10 @@ namespace ICSharpCode.NRefactory.CSharp @@ -40,10 +40,10 @@ namespace ICSharpCode.NRefactory.CSharp
class ConversionVisitor : StructuralVisitor
{
CompilationUnit unit = new CompilationUnit ();
SyntaxTree unit = new SyntaxTree ();
internal bool convertTypeSystemMode;
public CompilationUnit Unit {
public SyntaxTree Unit {
get {
return unit;
}
@ -335,12 +335,16 @@ namespace ICSharpCode.NRefactory.CSharp @@ -335,12 +335,16 @@ namespace ICSharpCode.NRefactory.CSharp
if (loc != null && pos < loc.Count)
result.AddChild (new CSharpTokenNode (Convert (loc [pos++])), Roles.Colon);
}
int attributeCount = 0;
foreach (var attr in GetAttributes (optAttributes)) {
result.AddChild (attr, Roles.Attribute);
attributeCount++;
}
// Left and right bracket + commas between the attributes
int locCount = 2 + attributeCount - 1;
// optional comma
if (loc != null && pos < loc.Count - 1 && !loc [pos].Equals (loc [pos + 1]))
if (loc != null && pos < loc.Count - 1 && loc.Count == locCount + 1)
result.AddChild (new CSharpTokenNode (Convert (loc [pos++])), Roles.Comma);
if (loc != null && pos < loc.Count)
result.AddChild (new CSharpTokenNode (Convert (loc [pos++])), Roles.RBracket);
@ -668,7 +672,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -668,7 +672,7 @@ namespace ICSharpCode.NRefactory.CSharp
if (namespaceStack.Count > 0) {
namespaceStack.Peek ().AddChild (child, NamespaceDeclaration.MemberRole);
} else {
unit.AddChild (child, CompilationUnit.MemberRole);
unit.AddChild (child, SyntaxTree.MemberRole);
}
}
@ -2387,7 +2391,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2387,7 +2391,9 @@ namespace ICSharpCode.NRefactory.CSharp
if (binaryExpression.Left != null)
result.AddChild ((Expression)binaryExpression.Left.Accept (this), BinaryOperatorExpression.LeftRole);
result.AddChild (new CSharpTokenNode (Convert (binaryExpression.Location)), BinaryOperatorExpression.GetOperatorRole (result.Operator));
var location = LocationsBag.GetLocations (binaryExpression);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0])), BinaryOperatorExpression.GetOperatorRole (result.Operator));
if (binaryExpression.Right != null)
result.AddChild ((Expression)binaryExpression.Right.Accept (this), BinaryOperatorExpression.RightRole);
return result;
@ -2399,7 +2405,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2399,7 +2405,9 @@ namespace ICSharpCode.NRefactory.CSharp
result.Operator = BinaryOperatorType.NullCoalescing;
if (nullCoalescingOperator.LeftExpression != null)
result.AddChild ((Expression)nullCoalescingOperator.LeftExpression.Accept (this), BinaryOperatorExpression.LeftRole);
result.AddChild (new CSharpTokenNode (Convert (nullCoalescingOperator.Location)), BinaryOperatorExpression.NullCoalescingRole);
var location = LocationsBag.GetLocations (nullCoalescingOperator);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0])), BinaryOperatorExpression.NullCoalescingRole);
if (nullCoalescingOperator.RightExpression != null)
result.AddChild ((Expression)nullCoalescingOperator.RightExpression.Accept (this), BinaryOperatorExpression.RightRole);
return result;
@ -2794,8 +2802,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2794,8 +2802,8 @@ namespace ICSharpCode.NRefactory.CSharp
}
if (commaLoc != null && curComma < commaLoc.Count)
init.AddChild(new CSharpTokenNode(Convert(commaLoc [curComma++])), Roles.Comma);
}
if (initLoc != null) {
if (initLoc.Count == 3) // optional comma
init.AddChild(new CSharpTokenNode(Convert(initLoc [1])), Roles.Comma);
@ -2879,9 +2887,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2879,9 +2887,11 @@ namespace ICSharpCode.NRefactory.CSharp
initializer.AddChild (new CSharpTokenNode (Convert (commaLocations [i])), Roles.Comma);
}
}
if (initLocation != null)
if (initLocation != null) {
if (initLocation.Count == 2) // optional comma
initializer.AddChild (new CSharpTokenNode(Convert(initLocation [0])), Roles.Comma);
initializer.AddChild (new CSharpTokenNode (Convert (initLocation [initLocation.Count - 1])), Roles.RBrace);
}
result.AddChild (initializer, ArrayCreateExpression.InitializerRole);
}
@ -3073,7 +3083,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3073,7 +3083,9 @@ namespace ICSharpCode.NRefactory.CSharp
result.Operator = AssignmentOperatorType.Assign;
if (simpleAssign.Target != null)
result.AddChild ((Expression)simpleAssign.Target.Accept (this), AssignmentExpression.LeftRole);
result.AddChild (new CSharpTokenNode (Convert (simpleAssign.Location)), AssignmentExpression.AssignRole);
var location = LocationsBag.GetLocations (simpleAssign);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0])), AssignmentExpression.AssignRole);
if (simpleAssign.Source != null) {
result.AddChild ((Expression)simpleAssign.Source.Accept (this), AssignmentExpression.RightRole);
}
@ -3118,7 +3130,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3118,7 +3130,9 @@ namespace ICSharpCode.NRefactory.CSharp
if (compoundAssign.Target != null)
result.AddChild ((Expression)compoundAssign.Target.Accept (this), AssignmentExpression.LeftRole);
result.AddChild (new CSharpTokenNode (Convert (compoundAssign.Location)), AssignmentExpression.GetOperatorRole (result.Operator));
var location = LocationsBag.GetLocations (compoundAssign);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0])), AssignmentExpression.GetOperatorRole (result.Operator));
if (compoundAssign.Source != null)
result.AddChild ((Expression)compoundAssign.Source.Accept (this), AssignmentExpression.RightRole);
return result;
@ -3204,7 +3218,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3204,7 +3218,7 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null) {
if (location.Count == 2) // optional comma
result.AddChild (new CSharpTokenNode (Convert (location [1])), Roles.Comma);
result.AddChild (new CSharpTokenNode (Convert (location [0])), Roles.Comma);
result.AddChild (new CSharpTokenNode (Convert (location [location.Count - 1])), Roles.RBrace);
}
return result;
@ -3213,25 +3227,36 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3213,25 +3227,36 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region LINQ expressions
QueryOrderClause currentQueryOrderClause;
public override object Visit (Mono.CSharp.Linq.QueryExpression queryExpression)
{
var result = new QueryExpression ();
var currentClause = queryExpression.next;
while (currentClause != null) {
QueryClause clause = (QueryClause)currentClause.Accept (this);
if (clause is QueryContinuationClause) {
// insert preceding query at beginning of QueryContinuationClause
clause.InsertChildAfter (null, result, QueryContinuationClause.PrecedingQueryRole);
// create a new QueryExpression for the remaining query
result = new QueryExpression ();
var oldQueryOrderClause = currentQueryOrderClause;
try {
currentQueryOrderClause = null;
var result = new QueryExpression ();
var currentClause = queryExpression.next;
while (currentClause != null) {
QueryClause clause = (QueryClause)currentClause.Accept (this);
if (clause is QueryContinuationClause) {
// insert preceding query at beginning of QueryContinuationClause
clause.InsertChildAfter (null, result, QueryContinuationClause.PrecedingQueryRole);
// create a new QueryExpression for the remaining query
result = new QueryExpression ();
}
if (clause != null) {
result.AddChild (clause, QueryExpression.ClauseRole);
}
currentClause = currentClause.next;
}
result.AddChild (clause, QueryExpression.ClauseRole);
currentClause = currentClause.next;
return result;
}
finally {
currentQueryOrderClause = oldQueryOrderClause;
}
return result;
}
public override object Visit (Mono.CSharp.Linq.QueryStartClause queryStart)
@ -3397,7 +3422,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3397,7 +3422,7 @@ namespace ICSharpCode.NRefactory.CSharp
public override object Visit (Mono.CSharp.Linq.OrderByAscending orderByAscending)
{
var result = new QueryOrderClause ();
currentQueryOrderClause = new QueryOrderClause();
var ordering = new QueryOrdering ();
if (orderByAscending.Expr != null)
@ -3407,13 +3432,13 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3407,13 +3432,13 @@ namespace ICSharpCode.NRefactory.CSharp
ordering.Direction = QueryOrderingDirection.Ascending;
ordering.AddChild (new CSharpTokenNode (Convert (location [0])), QueryOrdering.AscendingKeywordRole);
}
result.AddChild (ordering, QueryOrderClause.OrderingRole);
return result;
currentQueryOrderClause.AddChild (ordering, QueryOrderClause.OrderingRole);
return currentQueryOrderClause;
}
public override object Visit (Mono.CSharp.Linq.OrderByDescending orderByDescending)
{
var result = new QueryOrderClause ();
currentQueryOrderClause = new QueryOrderClause ();
var ordering = new QueryOrdering ();
if (orderByDescending.Expr != null)
@ -3423,14 +3448,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3423,14 +3448,12 @@ namespace ICSharpCode.NRefactory.CSharp
ordering.Direction = QueryOrderingDirection.Descending;
ordering.AddChild (new CSharpTokenNode (Convert (location [0])), QueryOrdering.DescendingKeywordRole);
}
result.AddChild (ordering, QueryOrderClause.OrderingRole);
return result;
currentQueryOrderClause.AddChild (ordering, QueryOrderClause.OrderingRole);
return currentQueryOrderClause;
}
public override object Visit (Mono.CSharp.Linq.ThenByAscending thenByAscending)
{
var result = new QueryOrderClause ();
var ordering = new QueryOrdering ();
if (thenByAscending.Expr != null)
ordering.AddChild ((Expression)thenByAscending.Expr.Accept (this), Roles.Expression);
@ -3439,14 +3462,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3439,14 +3462,12 @@ namespace ICSharpCode.NRefactory.CSharp
ordering.Direction = QueryOrderingDirection.Ascending;
ordering.AddChild (new CSharpTokenNode (Convert (location [0])), QueryOrdering.AscendingKeywordRole);
}
result.AddChild (ordering, QueryOrderClause.OrderingRole);
return result;
currentQueryOrderClause.AddChild (ordering, QueryOrderClause.OrderingRole);
return null;
}
public override object Visit (Mono.CSharp.Linq.ThenByDescending thenByDescending)
{
var result = new QueryOrderClause ();
var ordering = new QueryOrdering ();
if (thenByDescending.Expr != null)
ordering.AddChild ((Expression)thenByDescending.Expr.Accept (this), Roles.Expression);
@ -3455,8 +3476,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3455,8 +3476,8 @@ namespace ICSharpCode.NRefactory.CSharp
ordering.Direction = QueryOrderingDirection.Descending;
ordering.AddChild (new CSharpTokenNode (Convert (location [0])), QueryOrdering.DescendingKeywordRole);
}
result.AddChild (ordering, QueryOrderClause.OrderingRole);
return result;
currentQueryOrderClause.AddChild (ordering, QueryOrderClause.OrderingRole);
return null;
}
public override object Visit (Await awaitExpr)
@ -3701,28 +3722,34 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3701,28 +3722,34 @@ namespace ICSharpCode.NRefactory.CSharp
get { return errorReportPrinter.Errors; }
}
public CompilationUnit Parse (ITextSource textSource, string fileName, int lineModifier = 0)
/// <summary>
/// Parses a C# code file.
/// </summary>
/// <param name="program">The source code to parse.</param>
/// <param name="fileName">The file name. Used to identify the file (e.g. when building a type system).
/// This can be an arbitrary identifier, NRefactory never tries to access the file on disk.</param>
/// <returns>Returns the syntax tree.</returns>
public SyntaxTree Parse (string program, string fileName = "")
{
return Parse (textSource.CreateReader (), fileName, lineModifier);
return Parse (new StringTextSource (program), fileName);
}
public CompilationUnit Parse (TextReader reader, string fileName, int lineModifier = 0)
/// <summary>
/// Parses a C# code file.
/// </summary>
/// <param name="reader">The text reader containing the source code to parse.</param>
/// <param name="fileName">The file name. Used to identify the file (e.g. when building a type system).
/// This can be an arbitrary identifier, NRefactory never tries to access the file on disk.</param>
/// <returns>Returns the syntax tree.</returns>
public SyntaxTree Parse (TextReader reader, string fileName = "")
{
// TODO: can we optimize this to avoid the text->stream->text roundtrip?
using (MemoryStream stream = new MemoryStream ()) {
StreamWriter w = new StreamWriter (stream, Encoding.UTF8);
char[] buffer = new char[2048];
int read;
while ((read = reader.ReadBlock(buffer, 0, buffer.Length)) > 0)
w.Write (buffer, 0, read);
w.Flush (); // we can't close the StreamWriter because that would also close the MemoryStream
stream.Position = 0;
return Parse (stream, fileName, lineModifier);
}
return Parse(new StringTextSource (reader.ReadToEnd ()), fileName);
}
public CompilationUnit Parse(CompilerCompilationUnit top, string fileName, int lineModifier = 0)
/// <summary>
/// Converts a Mono.CSharp syntax tree into an NRefactory syntax tree.
/// </summary>
public SyntaxTree Parse(CompilerCompilationUnit top, string fileName)
{
if (top == null) {
return null;
@ -3738,7 +3765,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3738,7 +3765,7 @@ namespace ICSharpCode.NRefactory.CSharp
}
conversionVisitor.Unit.FileName = fileName;
conversionVisitor.Unit.ConditionalSymbols = top.Conditionals.ToArray ();
conversionVisitor.Unit.ConditionalSymbols = top.Conditionals.Concat (compilerSettings.ConditionalSymbols).ToArray ();
return conversionVisitor.Unit;
}
@ -3751,55 +3778,104 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3751,55 +3778,104 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
/// <summary>
/// Callback that gets called with the Mono.CSharp syntax tree whenever some code is parsed.
/// </summary>
public Action<CompilerCompilationUnit> CompilationUnitCallback {
get;
set;
}
/// <summary>
/// Specifies whether to run the parser in a special mode for generating the type system.
/// If this property is true, the syntax tree will only contain nodes relevant for the
/// <see cref="SyntaxTree.ToTypeSystem()"/> call and might be missing other nodes (e.g. method bodies).
/// The default is false.
/// </summary>
public bool GenerateTypeSystemMode {
get;
set;
}
public CompilationUnit Parse (string program, string fileName)
{
return Parse (new StringReader (program), fileName);
TextLocation initialLocation = new TextLocation(1, 1);
/// <summary>
/// Specifies the text location where parsing starts.
/// This property can be used when parsing a part of a file to make the locations of the AstNodes
/// refer to the position in the whole file.
/// The default is (1,1).
/// </summary>
public TextLocation InitialLocation {
get { return initialLocation; }
set { initialLocation = value; }
}
internal static object parseLock = new object ();
public CompilationUnit Parse(Stream stream, string fileName, int lineModifier = 0)
/// <summary>
/// Parses a C# code file.
/// </summary>
/// <param name="stream">The stream containing the source code to parse.</param>
/// <param name="fileName">The file name. Used to identify the file (e.g. when building a type system).
/// This can be an arbitrary identifier, NRefactory never tries to access the file on disk.</param>
/// <returns>Returns the syntax tree.</returns>
public SyntaxTree Parse (Stream stream, string fileName = "")
{
return Parse (new StreamReader (stream), fileName);
}
/// <summary>
/// Parses a C# code file.
/// </summary>
/// <param name="program">The source code to parse.</param>
/// <param name="fileName">The file name. Used to identify the file (e.g. when building a type system).
/// This can be an arbitrary identifier, NRefactory never tries to access the file on disk.</param>
/// </param>
/// <returns>Returns the syntax tree.</returns>
public SyntaxTree Parse(ITextSource program, string fileName = "")
{
return Parse(program, fileName, initialLocation.Line, initialLocation.Column);
}
SyntaxTree Parse(ITextSource program, string fileName, int initialLine, int initialColumn)
{
lock (parseLock) {
errorReportPrinter = new ErrorReportPrinter ("");
var ctx = new CompilerContext (compilerSettings.ToMono(), errorReportPrinter);
ctx.Settings.TabSize = 1;
var reader = new SeekableStreamReader (stream, Encoding.UTF8);
var reader = new SeekableStreamReader (program);
var file = new SourceFile (fileName, fileName, 0);
Location.Initialize (new List<SourceFile> (new [] { file }));
var module = new ModuleContainer (ctx);
var parser = Driver.Parse (reader, file, module, lineModifier);
var session = new ParserSession ();
session.LocationsBag = new LocationsBag ();
var report = new Report (ctx, errorReportPrinter);
var parser = Driver.Parse (reader, file, module, session, report, initialLine - 1, initialColumn - 1);
var top = new CompilerCompilationUnit () {
ModuleCompiled = module,
LocationsBag = parser.LocationsBag,
LocationsBag = session.LocationsBag,
SpecialsBag = parser.Lexer.sbag,
Conditionals = parser.Lexer.SourceFile.Conditionals
};
var unit = Parse (top, fileName, lineModifier);
var unit = Parse (top, fileName);
unit.Errors.AddRange (errorReportPrinter.Errors);
CompilerCallableEntryPoint.Reset ();
return unit;
}
}
public IEnumerable<EntityDeclaration> ParseTypeMembers (TextReader reader, int lineModifier = 0)
public IEnumerable<EntityDeclaration> ParseTypeMembers (string code)
{
return ParseTypeMembers(code, initialLocation.Line, initialLocation.Column);
}
IEnumerable<EntityDeclaration> ParseTypeMembers (string code, int initialLine, int initialColumn)
{
string code = "unsafe partial class MyClass { " + Environment.NewLine + reader.ReadToEnd () + "}";
var cu = Parse (new StringReader (code), "parsed.cs", lineModifier - 1);
if (cu == null)
const string prefix = "unsafe partial class MyClass { ";
var syntaxTree = Parse (new StringTextSource (prefix + code + "}"), "parsed.cs", initialLine, initialColumn - prefix.Length);
if (syntaxTree == null)
return Enumerable.Empty<EntityDeclaration> ();
var td = cu.Children.FirstOrDefault () as TypeDeclaration;
var td = syntaxTree.FirstChild as TypeDeclaration;
if (td != null) {
var members = td.Members.ToArray();
// detach members from parent
@ -3810,10 +3886,16 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3810,10 +3886,16 @@ namespace ICSharpCode.NRefactory.CSharp
return Enumerable.Empty<EntityDeclaration> ();
}
public IEnumerable<Statement> ParseStatements (TextReader reader, int lineModifier = 0)
public IEnumerable<Statement> ParseStatements (string code)
{
return ParseStatements(code, initialLocation.Line, initialLocation.Column);
}
IEnumerable<Statement> ParseStatements (string code, int initialLine, int initialColumn)
{
string code = "void M() { " + Environment.NewLine + reader.ReadToEnd () + "}";
var members = ParseTypeMembers (new StringReader (code), lineModifier - 1);
// the dummy method is async so that 'await' expressions are parsed as expected
const string prefix = "async void M() { ";
var members = ParseTypeMembers (prefix + code + "}", initialLine, initialColumn - prefix.Length);
var method = members.FirstOrDefault () as MethodDeclaration;
if (method != null && method.Body != null) {
var statements = method.Body.Statements.ToArray();
@ -3825,10 +3907,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3825,10 +3907,9 @@ namespace ICSharpCode.NRefactory.CSharp
return Enumerable.Empty<Statement> ();
}
public AstType ParseTypeReference (TextReader reader)
public AstType ParseTypeReference (string code)
{
string code = reader.ReadToEnd () + " a;";
var members = ParseTypeMembers (new StringReader (code));
var members = ParseTypeMembers (code + " a;");
var field = members.FirstOrDefault () as FieldDeclaration;
if (field != null) {
AstType type = field.ReturnType;
@ -3838,9 +3919,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3838,9 +3919,11 @@ namespace ICSharpCode.NRefactory.CSharp
return AstType.Null;
}
public Expression ParseExpression (TextReader reader)
public Expression ParseExpression (string code)
{
var es = ParseStatements (new StringReader ("tmp = " + Environment.NewLine + reader.ReadToEnd () + ";"), -1).FirstOrDefault () as ExpressionStatement;
const string prefix = "tmp = ";
var statements = ParseStatements (prefix + code + ";", initialLocation.Line, initialLocation.Column - prefix.Length);
var es = statements.FirstOrDefault () as ExpressionStatement;
if (es != null) {
AssignmentExpression ae = es.Expression as AssignmentExpression;
if (ae != null) {
@ -3852,14 +3935,16 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3852,14 +3935,16 @@ namespace ICSharpCode.NRefactory.CSharp
return Expression.Null;
}
/*
/// <summary>
/// Parses a file snippet; guessing what the code snippet represents (compilation unit, type members, block, type reference, expression).
/// Parses a file snippet; guessing what the code snippet represents (whole file, type members, block, type reference, expression).
/// </summary>
public AstNode ParseSnippet (TextReader reader)
public AstNode ParseSnippet (string code)
{
// TODO: add support for parsing a part of a file
throw new NotImplementedException ();
}
*/
public DocumentationReference ParseDocumentationReference (string cref)
{
@ -3874,15 +3959,18 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3874,15 +3959,18 @@ namespace ICSharpCode.NRefactory.CSharp
errorReportPrinter = new ErrorReportPrinter("");
var ctx = new CompilerContext(compilerSettings.ToMono(), errorReportPrinter);
ctx.Settings.TabSize = 1;
var stream = new MemoryStream(Encoding.Unicode.GetBytes(cref));
var reader = new SeekableStreamReader(stream, Encoding.Unicode);
var reader = new SeekableStreamReader(new StringTextSource (cref));
var file = new SourceFile("", "", 0);
Location.Initialize(new List<SourceFile> (new [] { file }));
var module = new ModuleContainer(ctx);
module.DocumentationBuilder = new DocumentationBuilder();
module.DocumentationBuilder = new DocumentationBuilder(module);
var source_file = new CompilationSourceFile (module);
var report = new Report (ctx, errorReportPrinter);
var parser = new Mono.CSharp.CSharpParser (reader, source_file, report);
ParserSession session = new ParserSession ();
session.LocationsBag = new LocationsBag ();
var parser = new Mono.CSharp.CSharpParser (reader, source_file, report, session);
parser.Lexer.Line += initialLocation.Line - 1;
parser.Lexer.Column += initialLocation.Column - 1;
parser.Lexer.putback_char = Tokenizer.DocumentationXref;
parser.Lexer.parsing_generic_declaration_doc = true;
parser.parse ();
@ -3891,7 +3979,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3891,7 +3979,7 @@ namespace ICSharpCode.NRefactory.CSharp
// mc.GetSignatureForError (), cref);
}
ConversionVisitor conversionVisitor = new ConversionVisitor (false, parser.LocationsBag);
ConversionVisitor conversionVisitor = new ConversionVisitor (false, session.LocationsBag);
DocumentationReference docRef = conversionVisitor.ConvertXmlDoc(module.DocumentationBuilder);
CompilerCallableEntryPoint.Reset();
return docRef;

103
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/SeekableStreamReader.cs

@ -0,0 +1,103 @@ @@ -0,0 +1,103 @@
//
// SeekableStreamReader.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.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 ICSharpCode.NRefactory.Editor;
using System.IO;
using System.Text;
namespace Mono.CSharp
{
public class SeekableStreamReader : IDisposable
{
public const int DefaultReadAheadSize = 2048;
readonly ITextSource textSource;
int pos;
static string GetAllText(Stream stream, Encoding encoding) {
using (var rdr = new StreamReader(stream, encoding)) {
return rdr.ReadToEnd();
}
}
public SeekableStreamReader (Stream stream, Encoding encoding, char[] sharedBuffer = null) : this(new StringTextSource(GetAllText(stream, encoding)))
{
}
public SeekableStreamReader (ITextSource source)
{
this.textSource = source;
}
public void Dispose ()
{
}
/// <remarks>
/// This value corresponds to the current position in a stream of characters.
/// The StreamReader hides its manipulation of the underlying byte stream and all
/// character set/decoding issues. Thus, we cannot use this position to guess at
/// the corresponding position in the underlying byte stream even though there is
/// a correlation between them.
/// </remarks>
public int Position {
get {
return pos;
}
set {
pos = value;
}
}
public char GetChar (int position)
{
return textSource.GetCharAt (position);
}
public char[] ReadChars (int fromPosition, int toPosition)
{
return textSource.GetText (fromPosition, toPosition - fromPosition).ToCharArray ();
}
public int Peek ()
{
if (pos >= textSource.TextLength)
return -1;
return textSource.GetCharAt (pos);
}
public int Read ()
{
if (pos >= textSource.TextLength)
return -1;
return textSource.GetCharAt (pos++);
}
}
}

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolFile.cs

@ -53,7 +53,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -53,7 +53,7 @@ namespace Mono.CompilerServices.SymbolWriter
}
}
internal class MyBinaryWriter : BinaryWriter
sealed class MyBinaryWriter : BinaryWriter
{
public MyBinaryWriter (Stream stream)
: base (stream)

81
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolTable.cs

@ -183,6 +183,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -183,6 +183,7 @@ namespace Mono.CompilerServices.SymbolWriter
{
#region This is actually written to the symbol file
public readonly int Row;
public int Column;
public readonly int File;
public readonly int Offset;
public readonly bool IsHidden; // Obsolete is never used
@ -195,28 +196,35 @@ namespace Mono.CompilerServices.SymbolWriter @@ -195,28 +196,35 @@ namespace Mono.CompilerServices.SymbolWriter
public int Compare (LineNumberEntry l1, LineNumberEntry l2)
{
return l1.Row == l2.Row ?
l1.Offset.CompareTo (l2.Offset) :
l1.Column.CompareTo (l2.Column) :
l1.Row.CompareTo (l2.Row);
}
}
public static readonly LineNumberEntry Null = new LineNumberEntry (0, 0, 0);
public static readonly LineNumberEntry Null = new LineNumberEntry (0, 0, 0, 0);
public LineNumberEntry (int file, int row, int column, int offset)
: this (file, row, offset, column, false)
{
}
public LineNumberEntry (int file, int row, int offset)
: this (file, row, offset, false)
{ }
: this (file, row, -1, offset, false)
{
}
public LineNumberEntry (int file, int row, int offset, bool is_hidden)
public LineNumberEntry (int file, int row, int column, int offset, bool is_hidden)
{
this.File = file;
this.Row = row;
this.Column = column;
this.Offset = offset;
this.IsHidden = is_hidden;
}
public override string ToString ()
{
return String.Format ("[Line {0}:{1}:{2}]", File, Row, Offset);
return String.Format ("[Line {0}:{1,2}:{3}]", File, Row, Column, Offset);
}
}
@ -675,8 +683,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -675,8 +683,7 @@ namespace Mono.CompilerServices.SymbolWriter
creating = true;
}
public SourceFileEntry (MonoSymbolFile file, string file_name,
byte[] guid, byte[] checksum)
public SourceFileEntry (MonoSymbolFile file, string file_name, byte[] guid, byte[] checksum)
: this (file, file_name)
{
this.guid = guid;
@ -694,13 +701,15 @@ namespace Mono.CompilerServices.SymbolWriter @@ -694,13 +701,15 @@ namespace Mono.CompilerServices.SymbolWriter
DataOffset = (int) bw.BaseStream.Position;
bw.Write (file_name);
if (guid == null) {
guid = Guid.NewGuid ().ToByteArray ();
if (guid == null)
guid = new byte[16];
if (hash == null) {
try {
using (FileStream fs = new FileStream (file_name, FileMode.Open, FileAccess.Read)) {
MD5 md5 = MD5.Create ();
hash = md5.ComputeHash (fs);
}
using (FileStream fs = new FileStream (file_name, FileMode.Open, FileAccess.Read)) {
MD5 md5 = MD5.Create ();
hash = md5.ComputeHash (fs);
}
} catch {
hash = new byte [16];
}
@ -791,7 +800,6 @@ namespace Mono.CompilerServices.SymbolWriter @@ -791,7 +800,6 @@ namespace Mono.CompilerServices.SymbolWriter
public const int Default_LineRange = 8;
public const byte Default_OpcodeBase = 9;
public const bool SuppressDuplicates = true;
#endregion
public const byte DW_LNS_copy = 1;
@ -822,7 +830,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -822,7 +830,7 @@ namespace Mono.CompilerServices.SymbolWriter
this._line_numbers = lines;
}
internal void Write (MonoSymbolFile file, MyBinaryWriter bw)
internal void Write (MonoSymbolFile file, MyBinaryWriter bw, bool readColumnsInfo)
{
int start = (int) bw.BaseStream.Position;
@ -832,11 +840,6 @@ namespace Mono.CompilerServices.SymbolWriter @@ -832,11 +840,6 @@ namespace Mono.CompilerServices.SymbolWriter
int line_inc = LineNumbers [i].Row - last_line;
int offset_inc = LineNumbers [i].Offset - last_offset;
if (SuppressDuplicates && (i+1 < LineNumbers.Length)) {
if (LineNumbers [i+1].Equals (LineNumbers [i]))
continue;
}
if (LineNumbers [i].File != last_file) {
bw.Write (DW_LNS_set_file);
bw.WriteLeb128 (LineNumbers [i].File);
@ -884,17 +887,23 @@ namespace Mono.CompilerServices.SymbolWriter @@ -884,17 +887,23 @@ namespace Mono.CompilerServices.SymbolWriter
bw.Write ((byte) 1);
bw.Write (DW_LNE_end_sequence);
for (int i = 0; i < LineNumbers.Length; i++) {
var ln = LineNumbers [i];
if (ln.Row >= 0)
bw.WriteLeb128 (ln.Column);
}
file.ExtendedLineNumberSize += (int) bw.BaseStream.Position - start;
}
internal static LineNumberTable Read (MonoSymbolFile file, MyBinaryReader br)
internal static LineNumberTable Read (MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo)
{
LineNumberTable lnt = new LineNumberTable (file);
lnt.DoRead (file, br);
lnt.DoRead (file, br, readColumnsInfo);
return lnt;
}
void DoRead (MonoSymbolFile file, MyBinaryReader br)
void DoRead (MonoSymbolFile file, MyBinaryReader br, bool includesColumns)
{
var lines = new List<LineNumberEntry> ();
@ -911,7 +920,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -911,7 +920,7 @@ namespace Mono.CompilerServices.SymbolWriter
if (opcode == DW_LNE_end_sequence) {
if (modified)
lines.Add (new LineNumberEntry (
stm_file, stm_line, stm_offset, is_hidden));
stm_file, stm_line, -1, stm_offset, is_hidden));
break;
} else if (opcode == DW_LNE_MONO_negate_is_hidden) {
is_hidden = !is_hidden;
@ -929,7 +938,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -929,7 +938,7 @@ namespace Mono.CompilerServices.SymbolWriter
switch (opcode) {
case DW_LNS_copy:
lines.Add (new LineNumberEntry (
stm_file, stm_line, stm_offset, is_hidden));
stm_file, stm_line, -1, stm_offset, is_hidden));
modified = false;
break;
case DW_LNS_advance_pc:
@ -959,13 +968,20 @@ namespace Mono.CompilerServices.SymbolWriter @@ -959,13 +968,20 @@ namespace Mono.CompilerServices.SymbolWriter
stm_offset += opcode / LineRange;
stm_line += LineBase + (opcode % LineRange);
lines.Add (new LineNumberEntry (
stm_file, stm_line, stm_offset, is_hidden));
stm_file, stm_line, -1, stm_offset, is_hidden));
modified = false;
}
}
_line_numbers = new LineNumberEntry [lines.Count];
lines.CopyTo (_line_numbers, 0);
_line_numbers = lines.ToArray ();
if (includesColumns) {
for (int i = 0; i < _line_numbers.Length; ++i) {
var ln = _line_numbers[i];
if (ln.Row >= 0)
ln.Column = br.ReadLeb128 ();
}
}
}
public bool GetMethodBounds (out LineNumberEntry start, out LineNumberEntry end)
@ -1022,7 +1038,8 @@ namespace Mono.CompilerServices.SymbolWriter @@ -1022,7 +1038,8 @@ namespace Mono.CompilerServices.SymbolWriter
[Flags]
public enum Flags
{
LocalNamesAmbiguous = 1
LocalNamesAmbiguous = 1,
ColumnsInfoIncluded = 1 << 1
}
public const int Size = 12;
@ -1176,7 +1193,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -1176,7 +1193,7 @@ namespace Mono.CompilerServices.SymbolWriter
}
LineNumberTableOffset = (int) bw.BaseStream.Position;
lnt.Write (file, bw);
lnt.Write (file, bw, (flags & Flags.ColumnsInfoIncluded) != 0);
DataOffset = (int) bw.BaseStream.Position;
@ -1204,7 +1221,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -1204,7 +1221,7 @@ namespace Mono.CompilerServices.SymbolWriter
long old_pos = reader.BaseStream.Position;
reader.BaseStream.Position = LineNumberTableOffset;
lnt = LineNumberTable.Read (SymbolFile, reader);
lnt = LineNumberTable.Read (SymbolFile, reader, (flags & Flags.ColumnsInfoIncluded) != 0);
reader.BaseStream.Position = old_pos;
return lnt;

4
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/SourceMethodBuilder.cs

@ -64,7 +64,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -64,7 +64,7 @@ namespace Mono.CompilerServices.SymbolWriter
public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column, bool is_hidden)
{
int file_idx = file != null ? file.Index : 0;
var lne = new LineNumberEntry (file_idx, line, offset, is_hidden);
var lne = new LineNumberEntry (file_idx, line, column, offset, is_hidden);
if (method_lines.Count > 0) {
var prev = method_lines[method_lines.Count - 1];
@ -185,7 +185,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -185,7 +185,7 @@ namespace Mono.CompilerServices.SymbolWriter
{
MethodEntry entry = new MethodEntry (
file, _comp_unit.Entry, token, ScopeVariables,
Locals, method_lines.ToArray (), Blocks, null, 0, ns_id);
Locals, method_lines.ToArray (), Blocks, null, MethodEntry.Flags.ColumnsInfoIncluded, ns_id);
file.AddMethod (entry);
}

41
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/anonymous.cs

@ -816,7 +816,7 @@ namespace Mono.CSharp { @@ -816,7 +816,7 @@ namespace Mono.CSharp {
sealed class HoistedFieldAssign : CompilerAssign
{
public HoistedFieldAssign (Expression target, Expression source)
: base (target, source, source.Location)
: base (target, source, target.Location)
{
}
@ -1503,6 +1503,10 @@ namespace Mono.CSharp { @@ -1503,6 +1503,10 @@ namespace Mono.CSharp {
aec.Set (flags);
var bc = ec as BlockContext;
if (bc != null)
aec.FlowOffset = bc.FlowOffset;
var errors = ec.Report.Errors;
bool res = Block.Resolve (ec.CurrentBranching, aec, null);
@ -2013,11 +2017,11 @@ namespace Mono.CSharp { @@ -2013,11 +2017,11 @@ namespace Mono.CSharp {
IntConstant FNV_prime = new IntConstant (Compiler.BuiltinTypes, 16777619, loc);
rs_hashcode = new Binary (Binary.Operator.Multiply,
new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode, loc),
FNV_prime, loc);
new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
FNV_prime);
Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc), loc)),
new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc))),
new Invocation (new MemberAccess (
new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
new StringConstant (Compiler.BuiltinTypes, string.Empty, loc), loc);
@ -2028,9 +2032,7 @@ namespace Mono.CSharp { @@ -2028,9 +2032,7 @@ namespace Mono.CSharp {
string_concat,
new Binary (Binary.Operator.Addition,
new StringConstant (Compiler.BuiltinTypes, " " + p.Name + " = ", loc),
field_to_string,
loc),
loc);
field_to_string));
continue;
}
@ -2040,18 +2042,15 @@ namespace Mono.CSharp { @@ -2040,18 +2042,15 @@ namespace Mono.CSharp {
string_concat = new Binary (Binary.Operator.Addition,
new Binary (Binary.Operator.Addition,
string_concat,
new StringConstant (Compiler.BuiltinTypes, ", " + p.Name + " = ", loc),
loc),
field_to_string,
loc);
new StringConstant (Compiler.BuiltinTypes, ", " + p.Name + " = ", loc)),
field_to_string);
rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal, loc);
rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
}
string_concat = new Binary (Binary.Operator.Addition,
string_concat,
new StringConstant (Compiler.BuiltinTypes, " }", loc),
loc);
new StringConstant (Compiler.BuiltinTypes, " }", loc));
//
// Equals (object obj) override
@ -2062,9 +2061,9 @@ namespace Mono.CSharp { @@ -2062,9 +2061,9 @@ namespace Mono.CSharp {
new As (equals_block.GetParameterReference (0, loc),
current_type, loc), loc)));
Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc), loc);
Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
if (rs_equals != null)
equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals, loc);
equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
equals_block.AddStatement (new Return (equals_test, loc));
equals.Block = equals_block;
@ -2106,19 +2105,19 @@ namespace Mono.CSharp { @@ -2106,19 +2105,19 @@ namespace Mono.CSharp {
var hash_variable = new LocalVariableReference (li_hash, loc);
hashcode_block.AddStatement (new StatementExpression (
new CompoundAssign (Binary.Operator.Addition, hash_variable,
new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 13, loc), loc), loc)));
new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 13, loc)))));
hashcode_block.AddStatement (new StatementExpression (
new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 7, loc), loc), loc)));
new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 7, loc)))));
hashcode_block.AddStatement (new StatementExpression (
new CompoundAssign (Binary.Operator.Addition, hash_variable,
new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 3, loc), loc), loc)));
new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 3, loc)))));
hashcode_block.AddStatement (new StatementExpression (
new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 17, loc), loc), loc)));
new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 17, loc)))));
hashcode_block.AddStatement (new StatementExpression (
new CompoundAssign (Binary.Operator.Addition, hash_variable,
new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 5, loc), loc), loc)));
new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 5, loc)))));
hashcode_block.AddStatement (new Return (hash_variable, loc));
hashcode.Block = hashcode_top;

16
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/argument.cs

@ -320,20 +320,20 @@ namespace Mono.CSharp @@ -320,20 +320,20 @@ namespace Mono.CSharp
if (a.Expr is Constant) {
info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "Constant", loc), loc);
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "Constant", loc));
} else if (a.ArgType == Argument.AType.Ref) {
info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsRef", loc), loc);
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsRef", loc));
info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc), loc);
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc));
} else if (a.ArgType == Argument.AType.Out) {
info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsOut", loc), loc);
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsOut", loc));
info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc), loc);
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc));
} else if (a.ArgType == Argument.AType.DynamicTypeName) {
info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsStaticType", loc), loc);
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsStaticType", loc));
}
var arg_type = a.Expr.Type;
@ -354,14 +354,14 @@ namespace Mono.CSharp @@ -354,14 +354,14 @@ namespace Mono.CSharp
}
info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc), loc);
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc));
}
string named_value;
NamedArgument na = a as NamedArgument;
if (na != null) {
info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "NamedArgument", loc), loc);
new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "NamedArgument", loc));
named_value = na.Name;
} else {

16
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assign.cs

@ -543,11 +543,11 @@ namespace Mono.CSharp { @@ -543,11 +543,11 @@ namespace Mono.CSharp {
ExpressionStatement resolved;
IMemberContext mc;
public FieldInitializer (FieldSpec spec, Expression expression, IMemberContext mc)
: base (new FieldExpr (spec, expression.Location), expression, expression.Location)
public FieldInitializer (FieldBase mc, Expression expression, Location loc)
: base (new FieldExpr (mc.Spec, expression.Location), expression, loc)
{
this.mc = mc;
if (!spec.IsStatic)
if (!mc.IsStatic)
((FieldExpr)target).InstanceExpression = new CompilerGeneratedThis (mc.CurrentType, expression.Location);
}
@ -660,15 +660,15 @@ namespace Mono.CSharp { @@ -660,15 +660,15 @@ namespace Mono.CSharp {
}
}
public CompoundAssign (Binary.Operator op, Expression target, Expression source, Location loc)
: base (target, source, loc)
public CompoundAssign (Binary.Operator op, Expression target, Expression source)
: base (target, source, target.Location)
{
right = source;
this.op = op;
}
public CompoundAssign (Binary.Operator op, Expression target, Expression source, Expression left, Location loc)
: this (op, target, source, loc)
public CompoundAssign (Binary.Operator op, Expression target, Expression source, Expression left)
: this (op, target, source)
{
this.left = left;
}
@ -731,7 +731,7 @@ namespace Mono.CSharp { @@ -731,7 +731,7 @@ namespace Mono.CSharp {
if (left == null)
left = new TargetExpression (target);
source = new Binary (op, left, right, true, loc);
source = new Binary (op, left, right, true);
if (target is DynamicMemberAssignable) {
Arguments targs = ((DynamicMemberAssignable) target).Arguments;

14
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/async.cs

@ -227,7 +227,9 @@ namespace Mono.CSharp @@ -227,7 +227,9 @@ namespace Mono.CSharp
//
// awaiter = expr.GetAwaiter ();
//
fe_awaiter.EmitAssign (ec, expr, false, false);
using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
fe_awaiter.EmitAssign (ec, expr, false, false);
}
Label skip_continuation = ec.DefineLabel ();
@ -284,14 +286,8 @@ namespace Mono.CSharp @@ -284,14 +286,8 @@ namespace Mono.CSharp
awaiter.IsAvailableForReuse = true;
if (ResultType.Kind != MemberKind.Void) {
var storey = (AsyncTaskStorey) machine_initializer.Storey;
if (storey.HoistedReturn != null)
storey.HoistedReturn.EmitAssign (ec);
else
ec.Emit (OpCodes.Pop);
}
if (ResultType.Kind != MemberKind.Void)
ec.Emit (OpCodes.Pop);
}
void Error_WrongAwaiterPattern (ResolveContext rc, TypeSpec awaiter)

45
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/attribute.cs

@ -1016,7 +1016,7 @@ namespace Mono.CSharp { @@ -1016,7 +1016,7 @@ namespace Mono.CSharp {
if (pos_args.Count == 1 && pos_args[0].Expr is Constant) {
var value = ((Constant) pos_args[0].Expr).GetValue () as string;
if (string.IsNullOrEmpty (value))
Error_AttributeEmitError ("DllName cannot be empty");
Error_AttributeEmitError ("DllName cannot be empty or null");
}
} else if (Type == predefined.MethodImpl && pt.BuiltinType == BuiltinTypeSpec.Type.Short &&
!System.Enum.IsDefined (typeof (MethodImplOptions), ((Constant) arg_expr).GetValue ().ToString ())) {
@ -1476,6 +1476,12 @@ namespace Mono.CSharp { @@ -1476,6 +1476,12 @@ namespace Mono.CSharp {
Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
}
public void EncodeTypeName (TypeContainer type)
{
Encode (type.GetSignatureForMetadata ());
}
//
// Encodes single property named argument per call
//
@ -1629,6 +1635,10 @@ namespace Mono.CSharp { @@ -1629,6 +1635,10 @@ namespace Mono.CSharp {
// New in .NET 4.0
public readonly PredefinedDynamicAttribute Dynamic;
// New in .NET 4.5
public readonly PredefinedStateMachineAttribute AsyncStateMachine;
public readonly PredefinedStateMachineAttribute IteratorStateMachine;
//
// Optional types which are used as types and for member lookup
//
@ -1690,6 +1700,11 @@ namespace Mono.CSharp { @@ -1690,6 +1700,11 @@ namespace Mono.CSharp {
StructLayout = new PredefinedAttribute (module, "System.Runtime.InteropServices", "StructLayoutAttribute");
FieldOffset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "FieldOffsetAttribute");
AsyncStateMachine = new PredefinedStateMachineAttribute (module, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute");
IteratorStateMachine = new PredefinedStateMachineAttribute (module, "System.Runtime.CompilerServices", "IteratorStateMachineAttribute") {
IsIterator = true
};
CallerMemberNameAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerMemberNameAttribute");
CallerLineNumberAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerLineNumberAttribute");
CallerFilePathAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerFilePathAttribute");
@ -1877,6 +1892,34 @@ namespace Mono.CSharp { @@ -1877,6 +1892,34 @@ namespace Mono.CSharp {
}
}
public class PredefinedStateMachineAttribute : PredefinedAttribute
{
public PredefinedStateMachineAttribute (ModuleContainer module, string ns, string name)
: base (module, ns, name)
{
}
public bool IsIterator { get; set; }
public void EmitAttribute (MethodBuilder builder, StateMachine type)
{
var predefined_ctor = IsIterator ?
module.PredefinedMembers.IteratorStateMachineAttributeCtor :
module.PredefinedMembers.AsyncStateMachineAttributeCtor;
var ctor = predefined_ctor.Get ();
if (ctor == null)
return;
AttributeEncoder encoder = new AttributeEncoder ();
encoder.EncodeTypeName (type);
encoder.EncodeEmptyNamedArguments ();
builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
}
}
public class PredefinedDynamicAttribute : PredefinedAttribute
{
MethodSpec tctor;

40
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cfold.cs

@ -187,7 +187,7 @@ namespace Mono.CSharp { @@ -187,7 +187,7 @@ namespace Mono.CSharp {
//
if ((lt.BuiltinType == BuiltinTypeSpec.Type.Bool && right is NullLiteral) ||
(rt.BuiltinType == BuiltinTypeSpec.Type.Bool && left is NullLiteral)) {
var b = new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
var b = new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec);
// false | null => null
// null | false => null
@ -231,7 +231,7 @@ namespace Mono.CSharp { @@ -231,7 +231,7 @@ namespace Mono.CSharp {
//
if ((lt.BuiltinType == BuiltinTypeSpec.Type.Bool && right is NullLiteral) ||
(rt.BuiltinType == BuiltinTypeSpec.Type.Bool && left is NullLiteral)) {
var b = new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
var b = new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec);
// false & null => false
// null & false => false
@ -469,7 +469,7 @@ namespace Mono.CSharp { @@ -469,7 +469,7 @@ namespace Mono.CSharp {
if (left is NullLiteral && right is NullLiteral) {
var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
lifted_int.ResolveAsType (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec);
}
if (!DoBinaryNumericPromotions (ec, ref left, ref right))
@ -566,7 +566,7 @@ namespace Mono.CSharp { @@ -566,7 +566,7 @@ namespace Mono.CSharp {
if (left is NullLiteral && right is NullLiteral) {
var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
lifted_int.ResolveAsType (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec);
}
if (!DoBinaryNumericPromotions (ec, ref left, ref right))
@ -662,7 +662,7 @@ namespace Mono.CSharp { @@ -662,7 +662,7 @@ namespace Mono.CSharp {
if (left is NullLiteral && right is NullLiteral) {
var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
lifted_int.ResolveAsType (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec);
}
if (!DoBinaryNumericPromotions (ec, ref left, ref right))
@ -762,7 +762,7 @@ namespace Mono.CSharp { @@ -762,7 +762,7 @@ namespace Mono.CSharp {
if (left is NullLiteral && right is NullLiteral) {
var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
lifted_int.ResolveAsType (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec);
}
if (!DoBinaryNumericPromotions (ec, ref left, ref right))
@ -852,7 +852,7 @@ namespace Mono.CSharp { @@ -852,7 +852,7 @@ namespace Mono.CSharp {
if (left is NullLiteral && right is NullLiteral) {
var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
lifted_int.ResolveAsType (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec);
}
IntConstant ic = right.ConvertImplicitly (ec.BuiltinTypes.Int) as IntConstant;
@ -873,7 +873,7 @@ namespace Mono.CSharp { @@ -873,7 +873,7 @@ namespace Mono.CSharp {
// null << value => null
if (left is NullLiteral)
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec);
left = left.ConvertImplicitly (ec.BuiltinTypes.Int);
if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Int)
@ -889,7 +889,7 @@ namespace Mono.CSharp { @@ -889,7 +889,7 @@ namespace Mono.CSharp {
if (left is NullLiteral && right is NullLiteral) {
var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
lifted_int.ResolveAsType (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec);
}
IntConstant sic = right.ConvertImplicitly (ec.BuiltinTypes.Int) as IntConstant;
@ -909,7 +909,7 @@ namespace Mono.CSharp { @@ -909,7 +909,7 @@ namespace Mono.CSharp {
// null >> value => null
if (left is NullLiteral)
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec);
left = left.ConvertImplicitly (ec.BuiltinTypes.Int);
if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Int)
@ -925,7 +925,7 @@ namespace Mono.CSharp { @@ -925,7 +925,7 @@ namespace Mono.CSharp {
if (left.IsNull || right.IsNull) {
return ReducedExpression.Create (
new BoolConstant (ec.BuiltinTypes, left.IsNull == right.IsNull, left.Location),
new Binary (oper, left, right, loc));
new Binary (oper, left, right));
}
if (left is StringConstant && right is StringConstant)
@ -969,7 +969,7 @@ namespace Mono.CSharp { @@ -969,7 +969,7 @@ namespace Mono.CSharp {
if (left.IsNull || right.IsNull) {
return ReducedExpression.Create (
new BoolConstant (ec.BuiltinTypes, left.IsNull != right.IsNull, left.Location),
new Binary (oper, left, right, loc));
new Binary (oper, left, right));
}
if (left is StringConstant && right is StringConstant)
@ -1011,11 +1011,11 @@ namespace Mono.CSharp { @@ -1011,11 +1011,11 @@ namespace Mono.CSharp {
if (left is NullLiteral) {
var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
lifted_int.ResolveAsType (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec);
}
if (left is Nullable.LiftedNull) {
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec);
}
}
@ -1051,11 +1051,11 @@ namespace Mono.CSharp { @@ -1051,11 +1051,11 @@ namespace Mono.CSharp {
if (left is NullLiteral) {
var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
lifted_int.ResolveAsType (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec);
}
if (left is Nullable.LiftedNull) {
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec);
}
}
@ -1091,11 +1091,11 @@ namespace Mono.CSharp { @@ -1091,11 +1091,11 @@ namespace Mono.CSharp {
if (left is NullLiteral) {
var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
lifted_int.ResolveAsType (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec);
}
if (left is Nullable.LiftedNull) {
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec);
}
}
@ -1131,11 +1131,11 @@ namespace Mono.CSharp { @@ -1131,11 +1131,11 @@ namespace Mono.CSharp {
if (left is NullLiteral) {
var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
lifted_int.ResolveAsType (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec);
}
if (left is Nullable.LiftedNull) {
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);
return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec);
}
}

27
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/class.cs

@ -346,6 +346,24 @@ namespace Mono.CSharp @@ -346,6 +346,24 @@ namespace Mono.CSharp
return MemberName.GetSignatureForError ();
}
public string GetSignatureForMetadata ()
{
#if STATIC
var name = TypeNameParser.Escape (MemberName.Basename);
if (Parent is TypeDefinition) {
return Parent.GetSignatureForMetadata () + "+" + name;
}
if (Parent != null && Parent.MemberName != null)
return Parent.GetSignatureForMetadata () + "." + name;
return name;
#else
throw new NotImplementedException ();
#endif
}
public virtual void RemoveContainer (TypeContainer cont)
{
if (containers != null)
@ -1845,13 +1863,20 @@ namespace Mono.CSharp @@ -1845,13 +1863,20 @@ namespace Mono.CSharp
return;
string class_indexer_name = null;
has_normal_indexers = true;
//
// Check normal indexers for consistent name, explicit interface implementation
// indexers are ignored
//
foreach (var indexer in indexers) {
//
// FindMembers can return unfiltered full hierarchy names
//
if (indexer.DeclaringType != spec)
continue;
has_normal_indexers = true;
if (class_indexer_name == null) {
indexer_name = class_indexer_name = indexer.Name;
continue;

16
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/codegen.cs

@ -944,10 +944,10 @@ namespace Mono.CSharp @@ -944,10 +944,10 @@ namespace Mono.CSharp
if (method.ReturnType.Kind == MemberKind.Void && method.IsConditionallyExcluded (ec.MemberContext, loc))
return;
EmitPredefined (ec, method, Arguments);
EmitPredefined (ec, method, Arguments, loc);
}
public void EmitPredefined (EmitContext ec, MethodSpec method, Arguments Arguments)
public void EmitPredefined (EmitContext ec, MethodSpec method, Arguments Arguments, Location? loc = null)
{
Expression instance_copy = null;
@ -1006,6 +1006,18 @@ namespace Mono.CSharp @@ -1006,6 +1006,18 @@ namespace Mono.CSharp
ec.Emit (OpCodes.Constrained, InstanceExpression.Type);
}
if (loc != null) {
//
// Emit explicit sequence point for expressions like Foo.Bar () to help debugger to
// break at right place when LHS expression can be stepped-into
//
// TODO: The list is probably not comprehensive, need to do more testing
//
if (InstanceExpression is PropertyExpr || InstanceExpression is Invocation || InstanceExpression is IndexerExpr ||
InstanceExpression is New || InstanceExpression is DelegateInvocation)
ec.Mark (loc.Value);
}
//
// Set instance expression to actual result expression. When it contains await it can be
// picked up by caller

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/const.cs

@ -59,7 +59,7 @@ namespace Mono.CSharp { @@ -59,7 +59,7 @@ namespace Mono.CSharp {
if ((field_attr & FieldAttributes.InitOnly) != 0)
Parent.PartialContainer.RegisterFieldForInitialization (this,
new FieldInitializer (spec, initializer, this));
new FieldInitializer (this, initializer, Location));
if (declarators != null) {
var t = new TypeExpression (MemberType, TypeExpression.Location);

25
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/context.cs

@ -13,6 +13,7 @@ @@ -13,6 +13,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
namespace Mono.CSharp
{
@ -730,4 +731,28 @@ namespace Mono.CSharp @@ -730,4 +731,28 @@ namespace Mono.CSharp
return new FlagsHandle (this, options, enable ? options : 0);
}
}
//
// Parser session objects. We could recreate all these objects for each parser
// instance but the best parser performance the session object can be reused
//
public class ParserSession
{
MD5 md5;
public readonly char[] StreamReaderBuffer = new char[SeekableStreamReader.DefaultReadAheadSize * 2];
public readonly Dictionary<char[], string>[] Identifiers = new Dictionary<char[], string>[Tokenizer.MaxIdentifierLength + 1];
public readonly List<Parameter> ParametersStack = new List<Parameter> (4);
public readonly char[] IDBuilder = new char[Tokenizer.MaxIdentifierLength];
public readonly char[] NumberBuilder = new char[Tokenizer.MaxNumberLength];
public LocationsBag LocationsBag { get; set; }
public bool UseJayGlobalArrays { get; set; }
public Tokenizer.LocatedToken[] LocatedTokens { get; set; }
public MD5 GetChecksumAlgorithm ()
{
return md5 ?? (md5 = MD5.Create ());
}
}
}

7354
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.cs

File diff suppressed because it is too large Load Diff

205
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.jay

@ -76,7 +76,7 @@ namespace Mono.CSharp @@ -76,7 +76,7 @@ namespace Mono.CSharp
///
/// An out-of-band stack.
///
static Stack<object> oob_stack;
Stack<object> oob_stack;
///
/// Controls the verbosity of the errors produced by the parser
@ -132,7 +132,7 @@ namespace Mono.CSharp @@ -132,7 +132,7 @@ namespace Mono.CSharp
// share the bucket for very common constructs which can never
// be recursive
//
static List<Parameter> parameters_bucket = new List<Parameter> (6);
List<Parameter> parameters_bucket;
//
// Full AST support members
@ -2662,6 +2662,21 @@ enum_member_declaration @@ -2662,6 +2662,21 @@ enum_member_declaration
if (doc_support)
em.DocComment = ConsumeStoredComment ();
$$ = em;
}
| opt_attributes IDENTIFIER error
{
Error_SyntaxError (yyToken);
var lt = (Tokenizer.LocatedToken) $2;
var em = new EnumMember ((Enum) current_type, new MemberName (lt.Value, lt.Location), (Attributes) $1);
((Enum) current_type).AddEnumMember (em);
if (doc_support) {
em.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
$$ = em;
}
| attributes_without_members
@ -3961,18 +3976,18 @@ multiplicative_expression @@ -3961,18 +3976,18 @@ multiplicative_expression
: prefixed_unary_expression
| multiplicative_expression STAR prefixed_unary_expression
{
$$ = new Binary (Binary.Operator.Multiply,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.Multiply, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| multiplicative_expression DIV prefixed_unary_expression
{
$$ = new Binary (Binary.Operator.Division,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.Division, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| multiplicative_expression PERCENT prefixed_unary_expression
{
$$ = new Binary (Binary.Operator.Modulus,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.Modulus, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
;
@ -3980,18 +3995,14 @@ additive_expression @@ -3980,18 +3995,14 @@ additive_expression
: multiplicative_expression
| additive_expression PLUS multiplicative_expression
{
$$ = new Binary (Binary.Operator.Addition,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.Addition, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| additive_expression MINUS multiplicative_expression
{
$$ = new Binary (Binary.Operator.Subtraction, (Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.Subtraction, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| parenthesized_expression MINUS multiplicative_expression
{
// Shift/Reduce conflict
$$ = new Binary (Binary.Operator.Subtraction, (Expression) $1, (Expression) $3, GetLocation ($2));
}
| additive_expression AS type
{
$$ = new As ((Expression) $1, (Expression) $3, GetLocation ($2));
@ -4006,13 +4017,13 @@ shift_expression @@ -4006,13 +4017,13 @@ shift_expression
: additive_expression
| shift_expression OP_SHIFT_LEFT additive_expression
{
$$ = new Binary (Binary.Operator.LeftShift,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.LeftShift, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| shift_expression OP_SHIFT_RIGHT additive_expression
{
$$ = new Binary (Binary.Operator.RightShift,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.RightShift, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
;
@ -4020,23 +4031,23 @@ relational_expression @@ -4020,23 +4031,23 @@ relational_expression
: shift_expression
| relational_expression OP_LT shift_expression
{
$$ = new Binary (Binary.Operator.LessThan,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.LessThan, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| relational_expression OP_GT shift_expression
{
$$ = new Binary (Binary.Operator.GreaterThan,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.GreaterThan, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| relational_expression OP_LE shift_expression
{
$$ = new Binary (Binary.Operator.LessThanOrEqual,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.LessThanOrEqual, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| relational_expression OP_GE shift_expression
{
$$ = new Binary (Binary.Operator.GreaterThanOrEqual,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.GreaterThanOrEqual, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
;
@ -4044,13 +4055,13 @@ equality_expression @@ -4044,13 +4055,13 @@ equality_expression
: relational_expression
| equality_expression OP_EQ relational_expression
{
$$ = new Binary (Binary.Operator.Equality,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.Equality, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| equality_expression OP_NE relational_expression
{
$$ = new Binary (Binary.Operator.Inequality,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.Inequality, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
;
@ -4058,8 +4069,8 @@ and_expression @@ -4058,8 +4069,8 @@ and_expression
: equality_expression
| and_expression BITWISE_AND equality_expression
{
$$ = new Binary (Binary.Operator.BitwiseAnd,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.BitwiseAnd, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
;
@ -4067,8 +4078,8 @@ exclusive_or_expression @@ -4067,8 +4078,8 @@ exclusive_or_expression
: and_expression
| exclusive_or_expression CARRET and_expression
{
$$ = new Binary (Binary.Operator.ExclusiveOr,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.ExclusiveOr, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
;
@ -4076,8 +4087,8 @@ inclusive_or_expression @@ -4076,8 +4087,8 @@ inclusive_or_expression
: exclusive_or_expression
| inclusive_or_expression BITWISE_OR exclusive_or_expression
{
$$ = new Binary (Binary.Operator.BitwiseOr,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.BitwiseOr, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
;
@ -4085,8 +4096,8 @@ conditional_and_expression @@ -4085,8 +4096,8 @@ conditional_and_expression
: inclusive_or_expression
| conditional_and_expression OP_AND inclusive_or_expression
{
$$ = new Binary (Binary.Operator.LogicalAnd,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.LogicalAnd, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
;
@ -4094,8 +4105,8 @@ conditional_or_expression @@ -4094,8 +4105,8 @@ conditional_or_expression
: conditional_and_expression
| conditional_or_expression OP_OR conditional_and_expression
{
$$ = new Binary (Binary.Operator.LogicalOr,
(Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Binary (Binary.Operator.LogicalOr, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
;
@ -4106,7 +4117,8 @@ null_coalescing_expression @@ -4106,7 +4117,8 @@ null_coalescing_expression
if (lang_version < LanguageVersion.ISO_2)
FeatureIsNotAvailable (GetLocation ($2), "null coalescing operator");
$$ = new Nullable.NullCoalescingOperator ((Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new Nullable.NullCoalescingOperator ((Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
;
@ -4127,57 +4139,58 @@ conditional_expression @@ -4127,57 +4139,58 @@ conditional_expression
assignment_expression
: prefixed_unary_expression ASSIGN expression
{
$$ = new SimpleAssign ((Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new SimpleAssign ((Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| prefixed_unary_expression OP_MULT_ASSIGN expression
{
$$ = new CompoundAssign (
Binary.Operator.Multiply, (Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new CompoundAssign (Binary.Operator.Multiply, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| prefixed_unary_expression OP_DIV_ASSIGN expression
{
$$ = new CompoundAssign (
Binary.Operator.Division, (Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new CompoundAssign (Binary.Operator.Division, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| prefixed_unary_expression OP_MOD_ASSIGN expression
{
$$ = new CompoundAssign (
Binary.Operator.Modulus, (Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new CompoundAssign (Binary.Operator.Modulus, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| prefixed_unary_expression OP_ADD_ASSIGN expression
{
$$ = new CompoundAssign (
Binary.Operator.Addition, (Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new CompoundAssign (Binary.Operator.Addition, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| prefixed_unary_expression OP_SUB_ASSIGN expression
{
$$ = new CompoundAssign (
Binary.Operator.Subtraction, (Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new CompoundAssign (Binary.Operator.Subtraction, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| prefixed_unary_expression OP_SHIFT_LEFT_ASSIGN expression
{
$$ = new CompoundAssign (
Binary.Operator.LeftShift, (Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new CompoundAssign (Binary.Operator.LeftShift, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| prefixed_unary_expression OP_SHIFT_RIGHT_ASSIGN expression
{
$$ = new CompoundAssign (
Binary.Operator.RightShift, (Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new CompoundAssign (Binary.Operator.RightShift, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| prefixed_unary_expression OP_AND_ASSIGN expression
{
$$ = new CompoundAssign (
Binary.Operator.BitwiseAnd, (Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new CompoundAssign (Binary.Operator.BitwiseAnd, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| prefixed_unary_expression OP_OR_ASSIGN expression
{
$$ = new CompoundAssign (
Binary.Operator.BitwiseOr, (Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new CompoundAssign (Binary.Operator.BitwiseOr, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
| prefixed_unary_expression OP_XOR_ASSIGN expression
{
$$ = new CompoundAssign (
Binary.Operator.ExclusiveOr, (Expression) $1, (Expression) $3, GetLocation ($2));
$$ = new CompoundAssign (Binary.Operator.ExclusiveOr, (Expression) $1, (Expression) $3);
lbag.AddLocation ($$, GetLocation ($2));
}
;
@ -4971,7 +4984,7 @@ identifier_inside_body @@ -4971,7 +4984,7 @@ identifier_inside_body
{
if (async_block) {
report.Error (4003, GetLocation ($1), "`await' cannot be used as an identifier within an async method or lambda expression");
$$ = Tokenizer.LocatedToken.Create ("await", GetLocation ($1));
$$ = new Tokenizer.LocatedToken ("await", GetLocation ($1));
}
}
;
@ -5353,19 +5366,19 @@ while_statement @@ -5353,19 +5366,19 @@ while_statement
do_statement
: DO embedded_statement WHILE open_parens_any boolean_expression CLOSE_PARENS SEMICOLON
{
$$ = new Do ((Statement) $2, (BooleanExpression) $5, GetLocation ($1));
$$ = new Do ((Statement) $2, (BooleanExpression) $5, GetLocation ($1), GetLocation ($3));
lbag.AddStatement ($$, GetLocation ($3), GetLocation ($4), GetLocation ($6), GetLocation ($7));
}
| DO embedded_statement error
{
Error_SyntaxError (yyToken);
$$ = new Do ((Statement) $2, null, GetLocation ($1));
$$ = new Do ((Statement) $2, null, GetLocation ($1), Location.Null);
}
| DO embedded_statement WHILE open_parens_any boolean_expression error
{
Error_SyntaxError (yyToken);
$$ = new Do ((Statement) $2, (BooleanExpression) $5, GetLocation ($1));
$$ = new Do ((Statement) $2, (BooleanExpression) $5, GetLocation ($1), GetLocation ($3));
lbag.AddStatement ($$, GetLocation ($3), GetLocation ($4));
}
;
@ -5634,6 +5647,11 @@ return_statement @@ -5634,6 +5647,11 @@ return_statement
$$ = new Return ((Expression) $2, GetLocation ($1));
lbag.AddStatement ($$, GetLocation ($3));
}
| RETURN expression error
{
Error_SyntaxError (yyToken);
$$ = new Return ((Expression) $2, GetLocation ($1));
}
| RETURN error
{
Error_SyntaxError (yyToken);
@ -5671,6 +5689,24 @@ yield_statement @@ -5671,6 +5689,24 @@ yield_statement
$$ = new Yield ((Expression) $3, lt.Location);
lbag.AddStatement ($$, GetLocation ($2), GetLocation ($4));
}
| identifier_inside_body RETURN expression error
{
Error_SyntaxError (yyToken);
var lt = (Tokenizer.LocatedToken) $1;
string s = lt.Value;
if (s != "yield"){
report.Error (1003, lt.Location, "; expected");
} else if ($3 == null) {
report.Error (1627, GetLocation ($4), "Expression expected after yield return");
} else if (lang_version == LanguageVersion.ISO_1){
FeatureIsNotAvailable (lt.Location, "iterators");
}
current_block.Explicit.RegisterIteratorYield ();
$$ = new Yield ((Expression) $3, lt.Location);
lbag.AddStatement ($$, GetLocation ($2));
}
| identifier_inside_body BREAK SEMICOLON
{
var lt = (Tokenizer.LocatedToken) $1;
@ -6769,17 +6805,12 @@ public Tokenizer Lexer { @@ -6769,17 +6805,12 @@ public Tokenizer Lexer {
}
}
static CSharpParser ()
public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, ParserSession session)
: this (reader, file, file.Compiler.Report, session)
{
oob_stack = new Stack<object> ();
}
public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file)
: this (reader, file, file.Compiler.Report)
{
}
public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, Report report)
public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, Report report, ParserSession session)
{
this.file = file;
current_container = current_namespace = file;
@ -6792,22 +6823,16 @@ public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, Re @@ -6792,22 +6823,16 @@ public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, Re
lang_version = settings.Version;
yacc_verbose_flag = settings.VerboseParserFlag;
doc_support = settings.DocumentationFile != null;
oob_stack.Clear ();
lexer = new Tokenizer (reader, file);
#if FULL_AST
lbag = new LocationsBag ();
#else
lbag = null;
#endif
use_global_stacks = true;
lexer = new Tokenizer (reader, file, session);
oob_stack = new Stack<object> ();
lbag = session.LocationsBag;
use_global_stacks = session.UseJayGlobalArrays;
parameters_bucket = session.ParametersStack;
}
public void parse ()
{
eof_token = Token.EOF;
Tokenizer.LocatedToken.Initialize ();
try {
if (yacc_verbose_flag > 1)
@ -6874,12 +6899,6 @@ Location GetLocation (object obj) @@ -6874,12 +6899,6 @@ Location GetLocation (object obj)
return lexer.Location;
}
public LocationsBag LocationsBag {
get {
return lbag;
}
}
void start_block (Location loc)
{
if (current_block == null) {

282
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-tokenizer.cs

@ -16,6 +16,7 @@ using System.Text; @@ -16,6 +16,7 @@ using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics;
using System.Collections;
namespace Mono.CSharp
{
@ -66,32 +67,62 @@ namespace Mono.CSharp @@ -66,32 +67,62 @@ namespace Mono.CSharp
}
//
// This class has to be used in the parser only, it reuses token
// details after each parse
// This class has to be used by parser only, it reuses token
// details after each file parse completion
//
public class LocatedToken
{
int row, column;
string value;
public int row, column;
public string value;
public SourceFile file;
static LocatedToken[] buffer = new LocatedToken[0];
static int pos;
private LocatedToken ()
public LocatedToken ()
{
}
public static LocatedToken Create (int row, int column)
public LocatedToken (string value, Location loc)
{
return Create (null, row, column);
this.value = value;
file = loc.SourceFile;
row = loc.Row;
column = loc.Column;
}
public static LocatedToken Create (string value, Location loc)
public override string ToString ()
{
return Create (value, loc.Row, loc.Column);
return string.Format ("Token '{0}' at {1},{2}", Value, row, column);
}
public static LocatedToken Create (string value, int row, int column)
public Location Location {
get { return new Location (file, row, column); }
}
public string Value {
get { return value; }
}
}
public class LocatedTokenBuffer
{
readonly LocatedToken[] buffer;
public int pos;
public LocatedTokenBuffer ()
{
buffer = new LocatedToken[0];
}
public LocatedTokenBuffer (LocatedToken[] buffer)
{
this.buffer = buffer ?? new LocatedToken[0];
}
public LocatedToken Create (SourceFile file, int row, int column)
{
return Create (null, file, row, column);
}
public LocatedToken Create (string value, SourceFile file, int row, int column)
{
//
// TODO: I am not very happy about the logic but it's the best
@ -105,15 +136,16 @@ namespace Mono.CSharp @@ -105,15 +136,16 @@ namespace Mono.CSharp
if (pos >= buffer.Length) {
entry = new LocatedToken ();
} else {
entry = buffer [pos];
entry = buffer[pos];
if (entry == null) {
entry = new LocatedToken ();
buffer [pos] = entry;
buffer[pos] = entry;
}
++pos;
}
entry.value = value;
entry.file = file;
entry.row = row;
entry.column = column;
return entry;
@ -123,31 +155,9 @@ namespace Mono.CSharp @@ -123,31 +155,9 @@ namespace Mono.CSharp
// Used for token not required by expression evaluator
//
[Conditional ("FULL_AST")]
public static void CreateOptional (int row, int col, ref object token)
public void CreateOptional (SourceFile file, int row, int col, ref object token)
{
token = Create (row, col);
}
public static void Initialize ()
{
#if !FULL_AST
if (buffer.Length == 0)
buffer = new LocatedToken [15000];
#endif
pos = 0;
}
public override string ToString ()
{
return string.Format ("Token '{0}' at {1},{2}", Value, row, column);
}
public Location Location {
get { return new Location (row, column); }
}
public string Value {
get { return value; }
token = Create (file, row, col);
}
}
@ -174,13 +184,7 @@ namespace Mono.CSharp @@ -174,13 +184,7 @@ namespace Mono.CSharp
readonly SeekableStreamReader reader;
readonly CompilationSourceFile source_file;
public CompilationSourceFile SourceFile {
get {
return source_file;
}
}
public CompilationSourceFile SourceFile { get { return source_file; } }
readonly CompilerContext context;
SourceFile current_source;
@ -199,6 +203,7 @@ namespace Mono.CSharp @@ -199,6 +203,7 @@ namespace Mono.CSharp
List<Location> escaped_identifiers;
int parsing_generic_less_than;
readonly bool doc_processing;
readonly LocatedTokenBuffer ltb;
//
// Used mainly for parser optimizations. Some expressions for instance
@ -362,27 +367,15 @@ namespace Mono.CSharp @@ -362,27 +367,15 @@ namespace Mono.CSharp
//
Stack<int> ifstack;
const int max_id_size = 512;
const int max_number_size = 512;
public const int MaxIdentifierLength = 512;
public const int MaxNumberLength = 512;
#if FULL_AST
readonly char [] id_builder = new char [max_id_size];
Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
char [] number_builder = new char [max_number_size];
readonly char[] id_builder;
readonly Dictionary<char[], string>[] identifiers;
readonly char[] number_builder;
int number_pos;
char[] value_builder = new char[256];
#else
static readonly char [] id_builder = new char [max_id_size];
static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
static char [] number_builder = new char [max_number_size];
static int number_pos;
static char[] value_builder = new char[256];
#endif
char[] value_builder = new char[64];
public int Line {
get {
@ -393,6 +386,15 @@ namespace Mono.CSharp @@ -393,6 +386,15 @@ namespace Mono.CSharp
}
}
public int Column {
get {
return col;
}
set {
col = value;
}
}
//
// This is used when the tokenizer needs to save
// the current position as it needs to do some parsing
@ -437,11 +439,15 @@ namespace Mono.CSharp @@ -437,11 +439,15 @@ namespace Mono.CSharp
}
}
public Tokenizer (SeekableStreamReader input, CompilationSourceFile file)
public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session)
{
this.source_file = file;
this.context = file.Compiler;
this.current_source = file.SourceFile;
this.identifiers = session.Identifiers;
this.id_builder = session.IDBuilder;
this.number_builder = session.NumberBuilder;
this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
reader = input;
@ -451,8 +457,6 @@ namespace Mono.CSharp @@ -451,8 +457,6 @@ namespace Mono.CSharp
doc_processing = context.Settings.DocumentationFile != null;
tab_size = context.Settings.TabSize;
Mono.CSharp.Location.Push (current_source);
}
public void PushPosition ()
@ -836,11 +840,13 @@ namespace Mono.CSharp @@ -836,11 +840,13 @@ namespace Mono.CSharp
PushPosition ();
xtoken ();
if (xtoken () != Token.ARROW)
res = -1;
goto default;
PopPosition ();
break;
default:
// peek_token could overwrite id_buffer
id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
res = -1;
break;
}
@ -898,7 +904,7 @@ namespace Mono.CSharp @@ -898,7 +904,7 @@ namespace Mono.CSharp
public Location Location {
get {
return new Location (ref_line, col);
return new Location (current_source, ref_line, col);
}
}
@ -1111,9 +1117,14 @@ namespace Mono.CSharp @@ -1111,9 +1117,14 @@ namespace Mono.CSharp
start:
int the_token = token ();
if (the_token == Token.OPEN_BRACKET) {
do {
while (true) {
the_token = token ();
} while (the_token != Token.CLOSE_BRACKET);
if (the_token == Token.EOF)
return true;
if (the_token == Token.CLOSE_BRACKET)
break;
}
the_token = token ();
} else if (the_token == Token.IN || the_token == Token.OUT) {
the_token = token ();
@ -1326,7 +1337,7 @@ namespace Mono.CSharp @@ -1326,7 +1337,7 @@ namespace Mono.CSharp
bool seen_digits = false;
if (c != -1){
if (number_pos == max_number_size)
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = (char) c;
}
@ -1337,7 +1348,7 @@ namespace Mono.CSharp @@ -1337,7 +1348,7 @@ namespace Mono.CSharp
//
while ((d = peek_char2 ()) != -1){
if (d >= '0' && d <= '9'){
if (number_pos == max_number_size)
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = (char) d;
get_char ();
@ -1602,23 +1613,23 @@ namespace Mono.CSharp @@ -1602,23 +1613,23 @@ namespace Mono.CSharp
if (c == 'e' || c == 'E'){
is_real = true;
if (number_pos == max_number_size)
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = (char) c;
c = get_char ();
if (c == '+'){
if (number_pos == max_number_size)
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = '+';
c = -1;
} else if (c == '-') {
if (number_pos == max_number_size)
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = '-';
c = -1;
} else {
if (number_pos == max_number_size)
if (number_pos == MaxNumberLength)
Error_NumericConstantTooLong ();
number_builder [number_pos++] = '+';
}
@ -1787,7 +1798,7 @@ namespace Mono.CSharp @@ -1787,7 +1798,7 @@ namespace Mono.CSharp
if (peek_char () == '\n') {
putback_char = -1;
}
x = '\n';
advance_line ();
} else if (x == '\n') {
@ -1798,6 +1809,26 @@ namespace Mono.CSharp @@ -1798,6 +1809,26 @@ namespace Mono.CSharp
return x;
}
int get_char_withwithoutskippingwindowseol ()
{
int x;
if (putback_char != -1) {
x = putback_char;
putback_char = -1;
} else {
x = reader.Read ();
}
if (x == '\r') {
} else if (x == '\n') {
advance_line ();
} else {
col++;
}
return x;
}
void advance_line ()
{
line++;
@ -1967,7 +1998,7 @@ namespace Mono.CSharp @@ -1967,7 +1998,7 @@ namespace Mono.CSharp
}
if (pos != 0) {
if (pos > max_id_size)
if (pos > MaxIdentifierLength)
arg = new string (value_builder, 0, pos);
else
arg = InternIdentifier (value_builder, pos);
@ -2002,7 +2033,6 @@ namespace Mono.CSharp @@ -2002,7 +2033,6 @@ namespace Mono.CSharp
}
//ref_line = line;
Location.Push (current_source);
return true;
}
@ -2089,7 +2119,6 @@ namespace Mono.CSharp @@ -2089,7 +2119,6 @@ namespace Mono.CSharp
if (new_file_name != null) {
current_source = context.LookupFile (source_file, new_file_name);
source_file.AddIncludeFile (current_source);
Location.Push (current_source);
}
if (!hidden_block_start.IsNull) {
@ -2187,6 +2216,8 @@ namespace Mono.CSharp @@ -2187,6 +2216,8 @@ namespace Mono.CSharp
//
// The syntax is ` "foo.txt" "{guid}" "hash"'
//
// guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
//
int c = get_char ();
if (c != '"')
@ -2249,6 +2280,7 @@ namespace Mono.CSharp @@ -2249,6 +2280,7 @@ namespace Mono.CSharp
// Any length of checksum
List<byte> checksum_bytes = new List<byte> (16);
var checksum_location = Location;
c = peek_char ();
while (c != '"' && c != -1) {
checksum_bytes.Add (read_hex (out error));
@ -2264,14 +2296,23 @@ namespace Mono.CSharp @@ -2264,14 +2296,23 @@ namespace Mono.CSharp
return false;
}
file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
current_source.AutoGenerated = true;
if (context.Settings.GenerateDebugInfo) {
var chsum = checksum_bytes.ToArray ();
if (file.HasChecksum) {
if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
// TODO: Report.SymbolRelatedToPreviousError
Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
}
}
file.SetChecksum (guid_bytes, chsum);
current_source.AutoGenerated = true;
}
return true;
}
#if !FULL_AST
static
#endif
bool IsTokenIdentifierEqual (char[] identifier)
{
for (int i = 0; i < identifier.Length; ++i) {
@ -2875,7 +2916,7 @@ namespace Mono.CSharp @@ -2875,7 +2916,7 @@ namespace Mono.CSharp
#endif
while (true){
c = get_char ();
c = get_char_withwithoutskippingwindowseol ();
if (c == '"') {
if (quoted && peek_char () == '"') {
if (pos == value_builder.Length)
@ -3013,7 +3054,7 @@ namespace Mono.CSharp @@ -3013,7 +3054,7 @@ namespace Mono.CSharp
if (id_builder [0] >= '_' && !quoted) {
int keyword = GetKeyword (id_builder, pos);
if (keyword != -1) {
val = LocatedToken.Create (keyword == Token.AWAIT ? "await" : null, ref_line, column);
val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
return keyword;
}
}
@ -3021,12 +3062,12 @@ namespace Mono.CSharp @@ -3021,12 +3062,12 @@ namespace Mono.CSharp
string s = InternIdentifier (id_builder, pos);
#if FULL_AST
if (quoted) {
val = LocatedToken.Create ("@" + s, ref_line, column - 1);
val = ltb.Create ("@" + s, current_source, ref_line, column - 1);
} else {
val = LocatedToken.Create (s, ref_line, column);
val = ltb.Create (s, current_source, ref_line, column);
}
#else
val = LocatedToken.Create (s, ref_line, column);
val = ltb.Create (s, current_source, ref_line, column);
#endif
if (quoted && parsing_attribute_section)
AddEscapedIdentifier (((LocatedToken) val).Location);
@ -3034,9 +3075,6 @@ namespace Mono.CSharp @@ -3034,9 +3075,6 @@ namespace Mono.CSharp
return Token.IDENTIFIER;
}
#if !FULL_AST
static
#endif
string InternIdentifier (char[] charBuffer, int length)
{
//
@ -3102,17 +3140,17 @@ namespace Mono.CSharp @@ -3102,17 +3140,17 @@ namespace Mono.CSharp
return consume_identifier (c);
case '{':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
return Token.OPEN_BRACE;
case '}':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
return Token.CLOSE_BRACE;
case '[':
// To block doccomment inside attribute declaration.
if (doc_state == XmlCommentState.Allowed)
doc_state = XmlCommentState.NotAllowed;
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
if (parsing_block == 0 || lambda_arguments_parsing)
return Token.OPEN_BRACKET;
@ -3138,10 +3176,10 @@ namespace Mono.CSharp @@ -3138,10 +3176,10 @@ namespace Mono.CSharp
return Token.OPEN_BRACKET_EXPR;
}
case ']':
LocatedToken.CreateOptional (ref_line, col, ref val);
ltb.CreateOptional (current_source, ref_line, col, ref val);
return Token.CLOSE_BRACKET;
case '(':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
//
// An expression versions of parens can appear in block context only
//
@ -3186,29 +3224,29 @@ namespace Mono.CSharp @@ -3186,29 +3224,29 @@ namespace Mono.CSharp
return Token.OPEN_PARENS;
case ')':
LocatedToken.CreateOptional (ref_line, col, ref val);
ltb.CreateOptional (current_source, ref_line, col, ref val);
return Token.CLOSE_PARENS;
case ',':
LocatedToken.CreateOptional (ref_line, col, ref val);
ltb.CreateOptional (current_source, ref_line, col, ref val);
return Token.COMMA;
case ';':
LocatedToken.CreateOptional (ref_line, col, ref val);
ltb.CreateOptional (current_source, ref_line, col, ref val);
return Token.SEMICOLON;
case '~':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
return Token.TILDE;
case '?':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
return TokenizePossibleNullableType ();
case '<':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
if (parsing_generic_less_than++ > 0)
return Token.OP_GENERICS_LT;
return TokenizeLessThan ();
case '>':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '=') {
@ -3235,7 +3273,7 @@ namespace Mono.CSharp @@ -3235,7 +3273,7 @@ namespace Mono.CSharp
return Token.OP_GT;
case '+':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '+') {
d = Token.OP_INC;
@ -3248,7 +3286,7 @@ namespace Mono.CSharp @@ -3248,7 +3286,7 @@ namespace Mono.CSharp
return d;
case '-':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '-') {
d = Token.OP_DEC;
@ -3263,15 +3301,15 @@ namespace Mono.CSharp @@ -3263,15 +3301,15 @@ namespace Mono.CSharp
return d;
case '!':
val = LocatedToken.Create (ref_line, col);
if (peek_char () == '=') {
val = ltb.Create (current_source, ref_line, col);
if (peek_char () == '='){
get_char ();
return Token.OP_NE;
}
return Token.BANG;
case '=':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '=') {
get_char ();
@ -3285,7 +3323,7 @@ namespace Mono.CSharp @@ -3285,7 +3323,7 @@ namespace Mono.CSharp
return Token.ASSIGN;
case '&':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '&') {
get_char ();
@ -3298,7 +3336,7 @@ namespace Mono.CSharp @@ -3298,7 +3336,7 @@ namespace Mono.CSharp
return Token.BITWISE_AND;
case '|':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
d = peek_char ();
if (d == '|') {
get_char ();
@ -3311,8 +3349,8 @@ namespace Mono.CSharp @@ -3311,8 +3349,8 @@ namespace Mono.CSharp
return Token.BITWISE_OR;
case '*':
val = LocatedToken.Create (ref_line, col);
if (peek_char () == '=') {
val = ltb.Create (current_source, ref_line, col);
if (peek_char () == '='){
get_char ();
return Token.OP_MULT_ASSIGN;
}
@ -3320,8 +3358,8 @@ namespace Mono.CSharp @@ -3320,8 +3358,8 @@ namespace Mono.CSharp
case '/':
d = peek_char ();
if (d == '=') {
val = LocatedToken.Create (ref_line, col);
if (d == '='){
val = ltb.Create (current_source, ref_line, col);
get_char ();
return Token.OP_DIV_ASSIGN;
}
@ -3430,11 +3468,11 @@ namespace Mono.CSharp @@ -3430,11 +3468,11 @@ namespace Mono.CSharp
update_formatted_doc_comment (current_comment_start);
continue;
}
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
return Token.DIV;
case '%':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
if (peek_char () == '='){
get_char ();
return Token.OP_MOD_ASSIGN;
@ -3442,7 +3480,7 @@ namespace Mono.CSharp @@ -3442,7 +3480,7 @@ namespace Mono.CSharp
return Token.PERCENT;
case '^':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
if (peek_char () == '='){
get_char ();
return Token.OP_XOR_ASSIGN;
@ -3450,7 +3488,7 @@ namespace Mono.CSharp @@ -3450,7 +3488,7 @@ namespace Mono.CSharp
return Token.CARRET;
case ':':
val = LocatedToken.Create (ref_line, col);
val = ltb.Create (current_source, ref_line, col);
if (peek_char () == ':') {
get_char ();
return Token.DOUBLE_COLON;
@ -3474,7 +3512,7 @@ namespace Mono.CSharp @@ -3474,7 +3512,7 @@ namespace Mono.CSharp
if (d >= '0' && d <= '9')
return is_number (c);
LocatedToken.CreateOptional (ref_line, col, ref val);
ltb.CreateOptional (current_source, ref_line, col, ref val);
return Token.DOT;
case '#':

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/decl.cs

@ -608,7 +608,7 @@ namespace Mono.CSharp { @@ -608,7 +608,7 @@ namespace Mono.CSharp {
if (al == Modifiers.PRIVATE) {
var decl = mc.Parent;
do {
same_access_restrictions = decl.CurrentType == p_parent;
same_access_restrictions = decl.CurrentType.MemberDefinition == p_parent.MemberDefinition;
} while (!same_access_restrictions && !decl.PartialContainer.IsTopLevel && (decl = decl.Parent) != null);
}

5
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/delegate.cs

@ -520,8 +520,11 @@ namespace Mono.CSharp { @@ -520,8 +520,11 @@ namespace Mono.CSharp {
}
TypeSpec rt = delegate_method.ReturnType;
if (rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
rt = ec.BuiltinTypes.Object;
if (!Delegate.IsTypeCovariant (ec, rt, invoke_method.ReturnType)) {
Expression ret_expr = new TypeExpression (rt, loc);
Expression ret_expr = new TypeExpression (delegate_method.ReturnType, loc);
Error_ConversionFailed (ec, delegate_method, ret_expr);
}

19
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/doc.cs

@ -47,6 +47,8 @@ namespace Mono.CSharp @@ -47,6 +47,8 @@ namespace Mono.CSharp
//
Dictionary<string, XmlDocument> StoredDocuments = new Dictionary<string, XmlDocument> ();
ParserSession session;
public DocumentationBuilder (ModuleContainer module)
{
doc_module = new ModuleContainer (module.Compiler);
@ -56,11 +58,6 @@ namespace Mono.CSharp @@ -56,11 +58,6 @@ namespace Mono.CSharp
XmlDocumentation = new XmlDocument ();
XmlDocumentation.PreserveWhitespace = false;
}
internal DocumentationBuilder()
{
// for NRefactory CSharpParser.ParseDocumentationReference
}
Report Report {
get {
@ -329,12 +326,18 @@ namespace Mono.CSharp @@ -329,12 +326,18 @@ namespace Mono.CSharp
var encoding = module.Compiler.Settings.Encoding;
var s = new MemoryStream (encoding.GetBytes (cref));
SeekableStreamReader seekable = new SeekableStreamReader (s, encoding);
var source_file = new CompilationSourceFile (doc_module);
var source_file = new CompilationSourceFile (doc_module, mc.Location.SourceFile);
var report = new Report (doc_module.Compiler, new NullReportPrinter ());
var parser = new CSharpParser (seekable, source_file, report);
if (session == null)
session = new ParserSession () {
UseJayGlobalArrays = true
};
SeekableStreamReader seekable = new SeekableStreamReader (s, encoding, session.StreamReaderBuffer);
var parser = new CSharpParser (seekable, source_file, report, session);
ParsedParameters = null;
ParsedName = null;
ParsedBuiltinType = null;

74
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/driver.cs

@ -20,6 +20,7 @@ using System.IO; @@ -20,6 +20,7 @@ using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics;
using System.Threading;
namespace Mono.CSharp
{
@ -41,7 +42,7 @@ namespace Mono.CSharp @@ -41,7 +42,7 @@ namespace Mono.CSharp
}
}
void tokenize_file (SourceFile sourceFile, ModuleContainer module)
void tokenize_file (SourceFile sourceFile, ModuleContainer module, ParserSession session)
{
Stream input;
@ -56,7 +57,7 @@ namespace Mono.CSharp @@ -56,7 +57,7 @@ namespace Mono.CSharp
SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding);
var file = new CompilationSourceFile (module, sourceFile);
Tokenizer lexer = new Tokenizer (reader, file);
Tokenizer lexer = new Tokenizer (reader, file, session);
int token, tokens = 0, errors = 0;
while ((token = lexer.token ()) != Token.EOF){
@ -77,49 +78,97 @@ namespace Mono.CSharp @@ -77,49 +78,97 @@ namespace Mono.CSharp
Location.Initialize (sources);
var session = new ParserSession () {
UseJayGlobalArrays = true,
LocatedTokens = new Tokenizer.LocatedToken[15000]
};
for (int i = 0; i < sources.Count; ++i) {
if (tokenize_only) {
tokenize_file (sources[i], module);
tokenize_file (sources[i], module, session);
} else {
Parse (sources[i], module);
Parse (sources[i], module, session, Report);
}
}
}
public void Parse (SourceFile file, ModuleContainer module)
#if false
void ParseParallel (ModuleContainer module)
{
var sources = module.Compiler.SourceFiles;
Location.Initialize (sources);
var pcount = Environment.ProcessorCount;
var threads = new Thread[System.Math.Max (2, pcount - 1)];
for (int i = 0; i < threads.Length; ++i) {
var t = new Thread (l => {
var session = new ParserSession () {
//UseJayGlobalArrays = true,
};
var report = new Report (ctx, Report.Printer); // TODO: Implement flush at once printer
for (int ii = (int) l; ii < sources.Count; ii += threads.Length) {
Parse (sources[ii], module, session, report);
}
// TODO: Merge warning regions
});
t.Start (i);
threads[i] = t;
}
for (int t = 0; t < threads.Length; ++t) {
threads[t].Join ();
}
}
#endif
public void Parse (SourceFile file, ModuleContainer module, ParserSession session, Report report)
{
Stream input;
try {
input = File.OpenRead (file.Name);
} catch {
Report.Error (2001, "Source file `{0}' could not be found", file.Name);
report.Error (2001, "Source file `{0}' could not be found", file.Name);
return;
}
// Check 'MZ' header
if (input.ReadByte () == 77 && input.ReadByte () == 90) {
Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
input.Close ();
return;
}
input.Position = 0;
SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding);
SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding, session.StreamReaderBuffer);
Parse (reader, file, module, session, report);
if (ctx.Settings.GenerateDebugInfo && report.Errors == 0 && !file.HasChecksum) {
input.Position = 0;
var checksum = session.GetChecksumAlgorithm ();
file.SetChecksum (checksum.ComputeHash (input));
}
Parse (reader, file, module);
reader.Dispose ();
input.Close ();
}
public static CSharpParser Parse(SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, int lineModifier = 0)
public static CSharpParser Parse (SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, ParserSession session, Report report, int lineModifier = 0, int colModifier = 0)
{
var file = new CompilationSourceFile (module, sourceFile);
module.AddTypeContainer(file);
CSharpParser parser = new CSharpParser (reader, file);
CSharpParser parser = new CSharpParser (reader, file, report, session);
parser.Lexer.Line += lineModifier;
parser.Lexer.Column += colModifier;
parser.Lexer.sbag = new SpecialsBag ();
parser.parse ();
return parser;
@ -347,7 +396,8 @@ namespace Mono.CSharp @@ -347,7 +396,8 @@ namespace Mono.CSharp
tr.Stop (TimeReporter.TimerType.CloseTypes);
tr.Start (TimeReporter.TimerType.Resouces);
assembly.EmbedResources ();
if (!settings.WriteMetadataOnly)
assembly.EmbedResources ();
tr.Stop (TimeReporter.TimerType.Resouces);
if (Report.Errors > 0)

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dynamic.cs

@ -502,7 +502,7 @@ namespace Mono.CSharp @@ -502,7 +502,7 @@ namespace Mono.CSharp
using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
if (s.Resolve (bc)) {
Statement init = new If (new Binary (Binary.Operator.Equality, site_field_expr, new NullLiteral (loc), loc), s, loc);
Statement init = new If (new Binary (Binary.Operator.Equality, site_field_expr, new NullLiteral (loc)), s, loc);
init.Emit (ec);
}

108
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ecore.cs

@ -2277,9 +2277,11 @@ namespace Mono.CSharp { @@ -2277,9 +2277,11 @@ namespace Mono.CSharp {
}
}
var report = ctx.Module.Compiler.Report;
var retval = ctx.LookupNamespaceOrType (Name, Arity, LookupMode.IgnoreAccessibility, loc);
if (retval != null) {
ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (retval.Type);
report.SymbolRelatedToPreviousError (retval.Type);
ErrorIsInaccesible (ctx, retval.GetSignatureForError (), loc);
return;
}
@ -2290,7 +2292,17 @@ namespace Mono.CSharp { @@ -2290,7 +2292,17 @@ namespace Mono.CSharp {
return;
}
NamespaceContainer.Error_NamespaceNotFound (loc, Name, ctx.Module.Compiler.Report);
var ns_candidates = ctx.Module.GlobalRootNamespace.FindTypeNamespaces (ctx, Name, Arity);
if (ns_candidates != null) {
string usings = string.Join ("' or `", ns_candidates.ToArray ());
report.Error (246, loc,
"The type or namespace name `{0}' could not be found. Are you missing `{1}' using directive?",
Name, usings);
} else {
report.Error (246, loc,
"The type or namespace name `{0}' could not be found. Are you missing an assembly reference?",
Name);
}
}
public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
@ -3176,8 +3188,12 @@ namespace Mono.CSharp { @@ -3176,8 +3188,12 @@ namespace Mono.CSharp {
}
var me = ExtensionExpression as MemberExpr;
if (me != null)
if (me != null) {
me.ResolveInstanceExpression (ec, null);
var fe = me as FieldExpr;
if (fe != null)
fe.Spec.MemberDefinition.SetIsUsed ();
}
InstanceExpression = null;
return this;
@ -3447,6 +3463,21 @@ namespace Mono.CSharp { @@ -3447,6 +3463,21 @@ namespace Mono.CSharp {
best_candidate_return = best_candidate.ReturnType;
}
if (best_candidate.IsGeneric && TypeParameterSpec.HasAnyTypeParameterConstrained (best_candidate.GenericDefinition)) {
ConstraintChecker cc = new ConstraintChecker (ec);
cc.CheckAll (best_candidate.GetGenericMethodDefinition (), best_candidate.TypeArguments, best_candidate.Constraints, loc);
}
//
// Additional check for possible imported base override method which
// could not be done during IsOverrideMethodBaseTypeAccessible
//
if (best_candidate.IsVirtual && (best_candidate.DeclaringType.Modifiers & Modifiers.PROTECTED) != 0 &&
best_candidate.MemberDefinition.IsImported && !best_candidate.DeclaringType.IsAccessible (ec)) {
ec.Report.SymbolRelatedToPreviousError (best_candidate);
ErrorIsInaccesible (ec, best_candidate.GetSignatureForError (), loc);
}
return this;
}
@ -3738,7 +3769,9 @@ namespace Mono.CSharp { @@ -3738,7 +3769,9 @@ namespace Mono.CSharp {
if (!TypeSpecComparer.Equals (p_m.Parameters.Types, q_m.Parameters.Types))
return 0;
var orig_p = p;
p = p_m.ReturnType;
var orig_q = q;
q = q_m.ReturnType;
//
@ -3755,14 +3788,14 @@ namespace Mono.CSharp { @@ -3755,14 +3788,14 @@ namespace Mono.CSharp {
return p.Kind != MemberKind.Void ? 1: 0;
}
var am = (AnonymousMethodExpression) a.Expr;
//
// When anonymous method is an asynchronous, and P has a return type Task<Y1>, and Q has a return type Task<Y2>
// better conversion is performed between underlying types Y1 and Y2
//
if (p.IsGenericTask || q.IsGenericTask) {
var async_am = a.Expr as AnonymousMethodExpression;
if (async_am != null && async_am.Block.IsAsync) {
if (am.Block.IsAsync) {
if (p.IsGenericTask != q.IsGenericTask) {
return 0;
}
@ -3770,6 +3803,19 @@ namespace Mono.CSharp { @@ -3770,6 +3803,19 @@ namespace Mono.CSharp {
q = q.TypeArguments[0];
p = p.TypeArguments[0];
}
} else if (q != p) {
//
// LAMESPEC: Lambda expression returning dynamic type has identity (better) conversion to delegate returning object type
//
if (q.BuiltinType == BuiltinTypeSpec.Type.Object) {
var am_rt = am.InferReturnType (ec, null, orig_q);
if (am_rt != null && am_rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
return 2;
} else if (p.BuiltinType == BuiltinTypeSpec.Type.Object) {
var am_rt = am.InferReturnType (ec, null, orig_p);
if (am_rt != null && am_rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
return 1;
}
}
//
@ -4048,6 +4094,32 @@ namespace Mono.CSharp { @@ -4048,6 +4094,32 @@ namespace Mono.CSharp {
return false;
}
static bool CheckInflatedArguments (MethodSpec ms)
{
if (!TypeParameterSpec.HasAnyTypeParameterTypeConstrained (ms.GenericDefinition))
return true;
// Setup constraint checker for probing only
ConstraintChecker cc = new ConstraintChecker (null);
var mp = ms.Parameters.Types;
for (int i = 0; i < mp.Length; ++i) {
var type = mp[i] as InflatedTypeSpec;
if (type == null)
continue;
var targs = type.TypeArguments;
if (targs.Length == 0)
continue;
// TODO: Checking inflated MVAR arguments should be enough
if (!cc.CheckAll (type.GetDefinition (), targs, type.Constraints, Location.Null))
return false;
}
return true;
}
public static void Error_ConstructorMismatch (ResolveContext rc, TypeSpec type, int argCount, Location loc)
{
rc.Report.Error (1729, loc,
@ -4203,9 +4275,6 @@ namespace Mono.CSharp { @@ -4203,9 +4275,6 @@ namespace Mono.CSharp {
TypeSpec[] ptypes;
var ms = candidate as MethodSpec;
if (ms != null && ms.IsGeneric) {
// Setup constraint checker for probing only
ConstraintChecker cc = new ConstraintChecker (null);
if (type_arguments != null) {
var g_args_count = ms.Arity;
if (g_args_count != type_arguments.Count)
@ -4251,14 +4320,12 @@ namespace Mono.CSharp { @@ -4251,14 +4320,12 @@ namespace Mono.CSharp {
if (i_args.Length != 0) {
ms = ms.MakeGenericMethod (ec, i_args);
}
cc.IgnoreInferredDynamic = true;
}
//
// Type arguments constraints have to match for the method to be applicable
//
if (!cc.CheckAll (ms.GetGenericMethodDefinition (), ms.TypeArguments, ms.Constraints, loc)) {
if (!CheckInflatedArguments (ms)) {
candidate = ms;
return int.MaxValue - 25000;
}
@ -4485,7 +4552,7 @@ namespace Mono.CSharp { @@ -4485,7 +4552,7 @@ namespace Mono.CSharp {
return p;
if (specific == ac_q.Element)
return q;
} else if (TypeManager.IsGenericType (p)) {
} else if (p.IsGeneric && q.IsGeneric) {
var pargs = TypeManager.GetTypeArguments (p);
var qargs = TypeManager.GetTypeArguments (q);
@ -4721,6 +4788,17 @@ namespace Mono.CSharp { @@ -4721,6 +4788,17 @@ namespace Mono.CSharp {
args [0].Type.GetSignatureForError (), best_candidate.Name, best_candidate.GetSignatureForError ());
}
//
// Check type constraints only when explicit type arguments are used
//
if (best_candidate.IsGeneric && type_arguments != null) {
MethodSpec bc = best_candidate as MethodSpec;
if (bc != null && TypeParameterSpec.HasAnyTypeParameterConstrained (bc.GenericDefinition)) {
ConstraintChecker cc = new ConstraintChecker (rc);
cc.CheckAll (bc.GetGenericMethodDefinition (), bc.TypeArguments, bc.Constraints, loc);
}
}
BestCandidateIsDynamic = true;
return null;
}
@ -5279,6 +5357,8 @@ namespace Mono.CSharp { @@ -5279,6 +5357,8 @@ namespace Mono.CSharp {
protected override Expression DoResolve (ResolveContext ec)
{
spec.MemberDefinition.SetIsUsed ();
return DoResolve (ec, null);
}
@ -5498,8 +5578,6 @@ namespace Mono.CSharp { @@ -5498,8 +5578,6 @@ namespace Mono.CSharp {
{
bool is_volatile = (spec.Modifiers & Modifiers.VOLATILE) != 0;
spec.MemberDefinition.SetIsUsed ();
if (IsStatic){
if (is_volatile)
ec.Emit (OpCodes.Volatile);

9
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/eval.cs

@ -79,7 +79,7 @@ namespace Mono.CSharp @@ -79,7 +79,7 @@ namespace Mono.CSharp
module = new ModuleContainer (ctx);
module.Evaluator = this;
source_file = new CompilationSourceFile (module);
source_file = new CompilationSourceFile (module, null);
module.AddTypeContainer (source_file);
startup_files = ctx.SourceFiles.Count;
@ -115,9 +115,10 @@ namespace Mono.CSharp @@ -115,9 +115,10 @@ namespace Mono.CSharp
Location.Initialize (ctx.SourceFiles);
var parser_session = new ParserSession ();
for (int i = 0; i < startup_files; ++i) {
var sf = ctx.SourceFiles [i];
d.Parse (sf, module);
d.Parse (sf, module, parser_session, ctx.Report);
}
}
@ -442,7 +443,7 @@ namespace Mono.CSharp @@ -442,7 +443,7 @@ namespace Mono.CSharp
//
InputKind ToplevelOrStatement (SeekableStreamReader seekable)
{
Tokenizer tokenizer = new Tokenizer (seekable, source_file);
Tokenizer tokenizer = new Tokenizer (seekable, source_file, new ParserSession ());
int t = tokenizer.token ();
switch (t){
@ -571,7 +572,7 @@ namespace Mono.CSharp @@ -571,7 +572,7 @@ namespace Mono.CSharp
seekable.Position = 0;
source_file.DeclarationFound = false;
CSharpParser parser = new CSharpParser (seekable, source_file);
CSharpParser parser = new CSharpParser (seekable, source_file, new ParserSession ());
if (kind == InputKind.StatementOrExpression){
parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;

67
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/expression.cs

@ -1211,7 +1211,7 @@ namespace Mono.CSharp @@ -1211,7 +1211,7 @@ namespace Mono.CSharp
var one = new IntConstant (ec.BuiltinTypes, 1, loc);
var op = IsDecrement ? Binary.Operator.Subtraction : Binary.Operator.Addition;
operation = new Binary (op, source, one, loc);
operation = new Binary (op, source, one);
operation = operation.Resolve (ec);
if (operation == null)
throw new NotImplementedException ("should not be reached");
@ -1527,7 +1527,7 @@ namespace Mono.CSharp @@ -1527,7 +1527,7 @@ namespace Mono.CSharp
// Turn is check into simple null check for implicitly convertible reference types
//
return ReducedExpression.Create (
new Binary (Binary.Operator.Inequality, expr, new NullLiteral (loc), loc).Resolve (ec),
new Binary (Binary.Operator.Inequality, expr, new NullLiteral (loc)).Resolve (ec),
this).Resolve (ec);
}
@ -2014,7 +2014,7 @@ namespace Mono.CSharp @@ -2014,7 +2014,7 @@ namespace Mono.CSharp
// b = b.left >> b.right & (0x1f|0x3f)
//
b.right = new Binary (Operator.BitwiseAnd,
b.right, new IntConstant (ec.BuiltinTypes, right_mask, b.right.Location), b.loc).Resolve (ec);
b.right, new IntConstant (ec.BuiltinTypes, right_mask, b.right.Location)).Resolve (ec);
//
// Expression tree representation does not use & mask
@ -2202,19 +2202,19 @@ namespace Mono.CSharp @@ -2202,19 +2202,19 @@ namespace Mono.CSharp
protected State state;
Expression enum_conversion;
public Binary (Operator oper, Expression left, Expression right, bool isCompound, Location loc)
: this (oper, left, right, loc)
public Binary (Operator oper, Expression left, Expression right, bool isCompound)
: this (oper, left, right)
{
if (isCompound)
state |= State.Compound;
}
public Binary (Operator oper, Expression left, Expression right, Location loc)
public Binary (Operator oper, Expression left, Expression right)
{
this.oper = oper;
this.left = left;
this.right = right;
this.loc = loc;
this.loc = left.Location;
}
#region Properties
@ -2319,7 +2319,7 @@ namespace Mono.CSharp @@ -2319,7 +2319,7 @@ namespace Mono.CSharp
public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
{
new Binary (oper, left, right, loc).Error_OperatorCannotBeApplied (ec, left, right);
new Binary (oper, left, right).Error_OperatorCannotBeApplied (ec, left, right);
}
public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
@ -3031,7 +3031,7 @@ namespace Mono.CSharp @@ -3031,7 +3031,7 @@ namespace Mono.CSharp
(TypeSpec.IsValueType (left.Type) && right is NullLiteral) ||
(right.Type.IsNullableType && (left is NullLiteral || left.Type.IsNullableType || TypeSpec.IsValueType (left.Type))) ||
(TypeSpec.IsValueType (right.Type) && left is NullLiteral))) {
var lifted = new Nullable.LiftedBinaryOperator (oper, left, right, loc);
var lifted = new Nullable.LiftedBinaryOperator (oper, left, right);
lifted.state = state;
return lifted.Resolve (ec);
}
@ -4409,7 +4409,7 @@ namespace Mono.CSharp @@ -4409,7 +4409,7 @@ namespace Mono.CSharp
// TODO: Should be the checks resolve context sensitive?
ResolveContext rc = new ResolveContext (ec.MemberContext, ResolveContext.Options.UnsafeScope);
right = new Binary (Binary.Operator.Multiply, right, right_const, loc).Resolve (rc);
right = new Binary (Binary.Operator.Multiply, right, right_const).Resolve (rc);
if (right == null)
return;
}
@ -5264,8 +5264,10 @@ namespace Mono.CSharp @@ -5264,8 +5264,10 @@ namespace Mono.CSharp
{
this.expr = expr;
this.arguments = arguments;
if (expr != null)
loc = expr.Location;
if (expr != null) {
var ma = expr as MemberAccess;
loc = ma != null ? ma.GetLeftExpressionLocation () : expr.Location;
}
}
#region Properties
@ -6154,7 +6156,7 @@ namespace Mono.CSharp @@ -6154,7 +6156,7 @@ namespace Mono.CSharp
{
if (initializers != null && bounds == null) {
//
// We use this to store all the date values in the order in which we
// We use this to store all the data values in the order in which we
// will need to store them in the byte blob later
//
array_data = new List<Expression> ();
@ -6212,7 +6214,16 @@ namespace Mono.CSharp @@ -6212,7 +6214,16 @@ namespace Mono.CSharp
ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
return false;
}
// When we don't have explicitly specified dimensions, record whatever dimension we first encounter at each level
if (!bounds.ContainsKey(idx + 1))
bounds[idx + 1] = sub_probe.Count;
if (bounds[idx + 1] != sub_probe.Count) {
ec.Report.Error(847, sub_probe.Location, "An array initializer of length `{0}' was expected", bounds[idx + 1].ToString());
return false;
}
bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
if (!ret)
return false;
@ -7932,6 +7943,18 @@ namespace Mono.CSharp @@ -7932,6 +7943,18 @@ namespace Mono.CSharp
expr.Error_OperatorCannotBeApplied (rc, loc, ".", type);
}
public Location GetLeftExpressionLocation ()
{
Expression expr = LeftExpression;
MemberAccess ma = expr as MemberAccess;
while (ma != null && ma.LeftExpression != null) {
expr = ma.LeftExpression;
ma = expr as MemberAccess;
}
return expr == null ? Location : expr.Location;
}
public static bool IsValidDotExpression (TypeSpec type)
{
const MemberKind dot_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.Delegate | MemberKind.Enum |
@ -8252,9 +8275,19 @@ namespace Mono.CSharp @@ -8252,9 +8275,19 @@ namespace Mono.CSharp
{
if (ec.Module.Compiler.Settings.Version > LanguageVersion.ISO_2 && !ec.IsRuntimeBinder && MethodGroupExpr.IsExtensionMethodArgument (expr)) {
ec.Report.SymbolRelatedToPreviousError (type);
var cand = ec.Module.GlobalRootNamespace.FindExtensionMethodNamespaces (ec, type, name, Arity);
string missing;
// a using directive or an assembly reference
if (cand != null) {
missing = "`" + string.Join ("' or `", cand.ToArray ()) + "' using directive";
} else {
missing = "an assembly reference";
}
ec.Report.Error (1061, loc,
"Type `{0}' does not contain a definition for `{1}' and no extension method `{1}' of type `{0}' could be found (are you missing a using directive or an assembly reference?)",
type.GetSignatureForError (), name);
"Type `{0}' does not contain a definition for `{1}' and no extension method `{1}' of type `{0}' could be found. Are you missing {2}?",
type.GetSignatureForError (), name, missing);
return;
}
@ -9461,7 +9494,7 @@ namespace Mono.CSharp @@ -9461,7 +9494,7 @@ namespace Mono.CSharp
this.left = left;
this.spec = spec;
this.loc = spec.Location;
this.loc = left.Location;
}
public override TypeSpec ResolveAsType (IMemberContext ec)

5
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/field.cs

@ -640,13 +640,12 @@ namespace Mono.CSharp @@ -640,13 +640,12 @@ namespace Mono.CSharp
}
if (initializer != null) {
Parent.RegisterFieldForInitialization (this,
new FieldInitializer (spec, initializer, this));
Parent.RegisterFieldForInitialization (this, new FieldInitializer (this, initializer, TypeExpression.Location));
}
if (declarators != null) {
var t = new TypeExpression (MemberType, TypeExpression.Location);
foreach (var d in declarators) {
var t = new TypeExpression (MemberType, d.Name.Location);
var f = new Field (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
if (d.Initializer != null)
f.initializer = d.Initializer;

56
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/generic.cs

@ -737,6 +737,12 @@ namespace Mono.CSharp { @@ -737,6 +737,12 @@ namespace Mono.CSharp {
}
}
public bool HasAnyTypeConstraint {
get {
return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
}
}
public bool HasTypeConstraint {
get {
var bt = BaseType.BuiltinType;
@ -1226,6 +1232,30 @@ namespace Mono.CSharp { @@ -1226,6 +1232,30 @@ namespace Mono.CSharp {
return false;
}
public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
{
var tps = md.TypeParameters;
for (int i = 0; i < md.TypeParametersCount; ++i) {
if (tps[i].HasAnyTypeConstraint) {
return true;
}
}
return false;
}
public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
{
var tps = md.TypeParameters;
for (int i = 0; i < md.TypeParametersCount; ++i) {
if (tps[i].IsConstrained) {
return true;
}
}
return false;
}
public override TypeSpec Mutate (TypeParameterMutator mutator)
{
return mutator.Mutate (this);
@ -2224,29 +2254,14 @@ namespace Mono.CSharp { @@ -2224,29 +2254,14 @@ namespace Mono.CSharp {
struct ConstraintChecker
{
IMemberContext mc;
bool ignore_inferred_dynamic;
bool recursive_checks;
public ConstraintChecker (IMemberContext ctx)
{
this.mc = ctx;
ignore_inferred_dynamic = false;
recursive_checks = false;
}
#region Properties
public bool IgnoreInferredDynamic {
get {
return ignore_inferred_dynamic;
}
set {
ignore_inferred_dynamic = value;
}
}
#endregion
//
// Checks the constraints of open generic type against type
// arguments. This version is used for types which could not be
@ -2296,9 +2311,6 @@ namespace Mono.CSharp { @@ -2296,9 +2311,6 @@ namespace Mono.CSharp {
public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
{
for (int i = 0; i < tparams.Length; i++) {
if (ignore_inferred_dynamic && targs[i].BuiltinType == BuiltinTypeSpec.Type.Dynamic)
continue;
var targ = targs[i];
if (!CheckConstraint (context, targ, tparams [i], loc))
return false;
@ -2446,14 +2458,6 @@ namespace Mono.CSharp { @@ -2446,14 +2458,6 @@ namespace Mono.CSharp {
return true;
}
//
// When partial/full type inference finds a dynamic type argument delay
// the constraint check to runtime, it can succeed for real underlying
// dynamic type
//
if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
return true;
if (mc != null) {
mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
if (atype.IsGenericParameter) {

53
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/import.cs

@ -90,7 +90,7 @@ namespace Mono.CSharp @@ -90,7 +90,7 @@ namespace Mono.CSharp
if (cad.Count > 0) {
foreach (var ca in cad) {
var dt = ca.Constructor.DeclaringType;
if (dt.Name != "DynamicAttribute" && dt.Namespace != CompilerServicesNamespace)
if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace)
continue;
if (ca.ConstructorArguments.Count == 0) {
@ -390,18 +390,21 @@ namespace Mono.CSharp @@ -390,18 +390,21 @@ namespace Mono.CSharp
if ((mod & Modifiers.OVERRIDE) != 0) {
bool is_real_override = false;
if (kind == MemberKind.Method && declaringType.BaseType != null) {
var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
var candidate = MemberCache.FindMember (declaringType.BaseType, filter, BindingRestriction.None);
//
// For imported class method do additional validation to be sure that metadata
// override flag was correct
//
// Difference between protected internal and protected is ok
//
const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
is_real_override = true;
var btype = declaringType.BaseType;
if (IsOverrideMethodBaseTypeAccessible (btype)) {
var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
//
// For imported class method do additional validation to be sure that metadata
// override flag was correct
//
// Difference between protected internal and protected is ok
//
const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
is_real_override = true;
}
}
}
@ -434,6 +437,30 @@ namespace Mono.CSharp @@ -434,6 +437,30 @@ namespace Mono.CSharp
return ms;
}
bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
{
switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
case Modifiers.PUBLIC:
return true;
case Modifiers.INTERNAL:
//
// Check whether imported method in base type is accessible from compiled
// context
//
return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
case Modifiers.PRIVATE:
return false;
default:
// protected
// protected internal
//
// Method accessibility checks will be done later based on context
// where the method is called (CS0122 error will be reported for inaccessible)
//
return true;
}
}
//
// Imports System.Reflection parameters
//

54
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/location.cs

@ -52,13 +52,15 @@ namespace Mono.CSharp @@ -52,13 +52,15 @@ namespace Mono.CSharp
}
}
static readonly byte[] MD5Algorith = { 96, 166, 110, 64, 207, 100, 130, 76, 182, 240, 66, 212, 129, 114, 167, 153 };
public readonly string Name;
public readonly string FullPathName;
public readonly int Index;
public bool AutoGenerated;
SourceFileEntry file;
byte[] guid, checksum;
byte[] algGuid, checksum;
List<LocationRegion> hidden_lines;
public SourceFile (string name, string path, int index)
@ -68,15 +70,32 @@ namespace Mono.CSharp @@ -68,15 +70,32 @@ namespace Mono.CSharp
this.FullPathName = path;
}
public byte[] Checksum {
get {
return checksum;
}
}
public bool HasChecksum {
get {
return checksum != null;
}
}
public SourceFileEntry SourceFileEntry {
get {
return file;
}
}
public void SetChecksum (byte[] guid, byte[] checksum)
public void SetChecksum (byte[] checksum)
{
this.guid = guid;
SetChecksum (MD5Algorith, checksum);
}
public void SetChecksum (byte[] algorithmGuid, byte[] checksum)
{
this.algGuid = algorithmGuid;
this.checksum = checksum;
}
@ -85,13 +104,9 @@ namespace Mono.CSharp @@ -85,13 +104,9 @@ namespace Mono.CSharp
if (hidden_lines != null)
hidden_lines.Sort ();
if (guid != null) {
file = new SourceFileEntry (symwriter, FullPathName, guid, checksum);
} else {
file = new SourceFileEntry (symwriter, FullPathName);
if (AutoGenerated)
file.SetAutoGenerated ();
}
file = new SourceFileEntry (symwriter, FullPathName, algGuid, checksum);
if (AutoGenerated)
file.SetAutoGenerated ();
return file;
}
@ -177,7 +192,6 @@ namespace Mono.CSharp @@ -177,7 +192,6 @@ namespace Mono.CSharp
const int max_column = column_mask;
static List<SourceFile> source_list;
static int current_source;
static Checkpoint [] checkpoints;
static int checkpoint_index;
@ -192,7 +206,6 @@ namespace Mono.CSharp @@ -192,7 +206,6 @@ namespace Mono.CSharp
public static void Reset ()
{
source_list = new List<SourceFile> ();
current_source = 0;
checkpoint_index = 0;
}
@ -220,13 +233,7 @@ namespace Mono.CSharp @@ -220,13 +233,7 @@ namespace Mono.CSharp
checkpoints [0] = new Checkpoint (0, 0);
}
static public void Push (SourceFile file)
{
current_source = file != null ? file.Index : -1;
// File is always pushed before being changed.
}
public Location (int row, int column)
public Location (SourceFile file, int row, int column)
{
if (row <= 0)
token = 0;
@ -237,6 +244,9 @@ namespace Mono.CSharp @@ -237,6 +244,9 @@ namespace Mono.CSharp
long target = -1;
long delta = 0;
// TODO: For eval only, need better handling of empty
int file_index = file == null ? 0 : file.Index;
// FIXME: This value is certainly wrong but what was the intension
int max = checkpoint_index < 10 ?
checkpoint_index : 10;
@ -245,13 +255,13 @@ namespace Mono.CSharp @@ -245,13 +255,13 @@ namespace Mono.CSharp
delta = row - offset;
if (delta >= 0 &&
delta < (1 << line_delta_bits) &&
checkpoints [checkpoint_index - i].File == current_source) {
checkpoints[checkpoint_index - i].File == file_index) {
target = checkpoint_index - i;
break;
}
}
if (target == -1) {
AddCheckpoint (current_source, row);
AddCheckpoint (file_index, row);
target = checkpoint_index;
delta = row % (1 << line_delta_bits);
}
@ -269,7 +279,7 @@ namespace Mono.CSharp @@ -269,7 +279,7 @@ namespace Mono.CSharp
public static Location operator - (Location loc, int columns)
{
return new Location (loc.Row, loc.Column - columns);
return new Location (loc.SourceFile, loc.Row, loc.Column - columns);
}
static void AddCheckpoint (int file, int row)

7
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/membercache.cs

@ -435,12 +435,15 @@ namespace Mono.CSharp { @@ -435,12 +435,15 @@ namespace Mono.CSharp {
// A special method to work with member lookup only. It returns a list of all members named @name
// starting from @container. It's very performance sensitive
//
public static IList<MemberSpec> FindMembers (TypeSpec container, string name, bool declaredOnly)
// declaredOnlyClass cannot be used interfaces. Manual filtering is required because names are
// compacted
//
public static IList<MemberSpec> FindMembers (TypeSpec container, string name, bool declaredOnlyClass)
{
IList<MemberSpec> applicable;
do {
if (container.MemberCache.member_hash.TryGetValue (name, out applicable) || declaredOnly)
if (container.MemberCache.member_hash.TryGetValue (name, out applicable) || declaredOnlyClass)
return applicable;
container = container.BaseType;

71
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/method.cs

@ -1213,6 +1213,9 @@ namespace Mono.CSharp { @@ -1213,6 +1213,9 @@ namespace Mono.CSharp {
block = (ToplevelBlock) block.ConvertToAsyncTask (this, Parent.PartialContainer, parameters, ReturnType, Location);
ModFlags |= Modifiers.DEBUGGER_HIDDEN;
}
if (Compiler.Settings.WriteMetadataOnly)
block = null;
}
if ((ModFlags & Modifiers.STATIC) == 0)
@ -1301,10 +1304,18 @@ namespace Mono.CSharp { @@ -1301,10 +1304,18 @@ namespace Mono.CSharp {
}
}
base.Emit ();
if (block != null && block.StateMachine != null) {
var psm = block.StateMachine is IteratorStorey ?
Module.PredefinedAttributes.IteratorStateMachine :
Module.PredefinedAttributes.AsyncStateMachine;
psm.EmitAttribute (MethodBuilder, block.StateMachine);
}
if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
base.Emit ();
} catch {
Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
Location, MethodBuilder);
@ -1617,10 +1628,15 @@ namespace Mono.CSharp { @@ -1617,10 +1628,15 @@ namespace Mono.CSharp {
Parent.MemberCache.AddMember (spec);
// It's here only to report an error
if (block != null && block.IsIterator) {
member_type = Compiler.BuiltinTypes.Void;
Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
if (block != null) {
// It's here only to report an error
if (block.IsIterator) {
member_type = Compiler.BuiltinTypes.Void;
Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
}
if (Compiler.Settings.WriteMetadataOnly)
block = null;
}
return true;
@ -1656,14 +1672,14 @@ namespace Mono.CSharp { @@ -1656,14 +1672,14 @@ namespace Mono.CSharp {
BlockContext bc = new BlockContext (this, block, Compiler.BuiltinTypes.Void);
bc.Set (ResolveContext.Options.ConstructorScope);
//
// If we use a "this (...)" constructor initializer, then
// do not emit field initializers, they are initialized in the other constructor
//
if (!(Initializer is ConstructorThisInitializer))
Parent.PartialContainer.ResolveFieldInitializers (bc);
if (block != null) {
//
// If we use a "this (...)" constructor initializer, then
// do not emit field initializers, they are initialized in the other constructor
//
if (!(Initializer is ConstructorThisInitializer))
Parent.PartialContainer.ResolveFieldInitializers (bc);
if (!IsStatic) {
if (Initializer == null) {
if (Parent.PartialContainer.Kind == MemberKind.Struct) {
@ -2155,6 +2171,16 @@ namespace Mono.CSharp { @@ -2155,6 +2171,16 @@ namespace Mono.CSharp {
return true;
}
public override bool Define ()
{
base.Define ();
if (Compiler.Settings.WriteMetadataOnly)
block = null;
return true;
}
public override void Emit()
{
var base_type = Parent.PartialContainer.BaseType;
@ -2518,13 +2544,18 @@ namespace Mono.CSharp { @@ -2518,13 +2544,18 @@ namespace Mono.CSharp {
if (!base.Define ())
return false;
if (block != null && block.IsIterator) {
//
// Current method is turned into automatically generated
// wrapper which creates an instance of iterator
//
Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
ModFlags |= Modifiers.DEBUGGER_HIDDEN;
if (block != null) {
if (block.IsIterator) {
//
// Current method is turned into automatically generated
// wrapper which creates an instance of iterator
//
Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
ModFlags |= Modifiers.DEBUGGER_HIDDEN;
}
if (Compiler.Settings.WriteMetadataOnly)
block = null;
}
// imlicit and explicit operator of same types are not allowed

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/module.cs

@ -429,7 +429,7 @@ namespace Mono.CSharp @@ -429,7 +429,7 @@ namespace Mono.CSharp
base.EmitContainer ();
if (Compiler.Report.Errors == 0)
if (Compiler.Report.Errors == 0 && !Compiler.Settings.WriteMetadataOnly)
VerifyMembers ();
if (anonymous_types != null) {

135
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/namespace.cs

@ -41,6 +41,46 @@ namespace Mono.CSharp { @@ -41,6 +41,46 @@ namespace Mono.CSharp {
report.Error (1681, loc, "The global extern alias cannot be redefined");
}
//
// For better error reporting where we try to guess missing using directive
//
public List<string> FindTypeNamespaces (IMemberContext ctx, string name, int arity)
{
List<string> res = null;
foreach (var ns in all_namespaces) {
var type = ns.Value.LookupType (ctx, name, arity, LookupMode.Normal, Location.Null);
if (type != null) {
if (res == null)
res = new List<string> ();
res.Add (ns.Key);
}
}
return res;
}
//
// For better error reporting where compiler tries to guess missing using directive
//
public List<string> FindExtensionMethodNamespaces (IMemberContext ctx, TypeSpec extensionType, string name, int arity)
{
List<string> res = null;
foreach (var ns in all_namespaces) {
var methods = ns.Value.LookupExtensionMethod (ctx, extensionType, name, arity);
if (methods != null) {
if (res == null)
res = new List<string> ();
res.Add (ns.Key);
}
}
return res;
}
public void RegisterNamespace (Namespace child)
{
if (child != this)
@ -181,14 +221,51 @@ namespace Mono.CSharp { @@ -181,14 +221,51 @@ namespace Mono.CSharp {
return;
}
string assembly = null;
string possible_name = fullname + "." + name;
// Only assembly unique name should be added
switch (possible_name) {
case "System.Drawing":
case "System.Web.Services":
case "System.Web":
case "System.Data":
case "System.Configuration":
case "System.Data.Services":
case "System.DirectoryServices":
case "System.Json":
case "System.Net.Http":
case "System.Numerics":
case "System.Runtime.Caching":
case "System.ServiceModel":
case "System.Transactions":
case "System.Web.Routing":
case "System.Xml.Linq":
case "System.Xml":
assembly = possible_name;
break;
case "System.Linq":
case "System.Linq.Expressions":
assembly = "System.Core";
break;
case "System.Windows.Forms":
case "System.Windows.Forms.Layout":
assembly = "System.Windows.Name";
break;
}
assembly = assembly == null ? "an" : "`" + assembly + "'";
if (this is GlobalRootNamespace) {
ctx.Module.Compiler.Report.Error (400, loc,
"The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
name);
"The type or namespace name `{0}' could not be found in the global namespace. Are you missing {1} assembly reference?",
name, assembly);
} else {
ctx.Module.Compiler.Report.Error (234, loc,
"The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
name, GetSignatureForError ());
"The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing {2} assembly reference?",
name, GetSignatureForError (), assembly);
}
}
@ -209,10 +286,16 @@ namespace Mono.CSharp { @@ -209,10 +286,16 @@ namespace Mono.CSharp {
ns_parent = this;
}
return ns_parent.TryAddNamespace (name.Basename);
}
Namespace TryAddNamespace (string name)
{
Namespace ns;
if (!ns_parent.namespaces.TryGetValue (name.Basename, out ns)) {
ns = new Namespace (ns_parent, name.Basename);
ns_parent.namespaces.Add (name.Basename, ns);
if (!namespaces.TryGetValue (name, out ns)) {
ns = new Namespace (this, name);
namespaces.Add (name, ns);
}
return ns;
@ -1110,44 +1193,6 @@ namespace Mono.CSharp { @@ -1110,44 +1193,6 @@ namespace Mono.CSharp {
return match;
}
static void MsgtryRef (string s)
{
Console.WriteLine (" Try using -r:" + s);
}
static void MsgtryPkg (string s)
{
Console.WriteLine (" Try using -pkg:" + s);
}
public static void Error_NamespaceNotFound (Location loc, string name, Report Report)
{
Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
name);
switch (name) {
case "Gtk": case "GtkSharp":
MsgtryPkg ("gtk-sharp-2.0");
break;
case "Gdk": case "GdkSharp":
MsgtryPkg ("gdk-sharp-2.0");
break;
case "Glade": case "GladeSharp":
MsgtryPkg ("glade-sharp-2.0");
break;
case "System.Drawing":
case "System.Web.Services":
case "System.Web":
case "System.Data":
case "System.Windows.Forms":
MsgtryRef (name);
break;
}
}
protected override void DefineNamespace ()
{
if (namespace_using_table == null)

12
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/nullable.cs

@ -539,8 +539,8 @@ namespace Mono.CSharp.Nullable @@ -539,8 +539,8 @@ namespace Mono.CSharp.Nullable
Expression user_operator;
MethodSpec wrap_ctor;
public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right, Location loc)
: base (op, left, right, loc)
public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right)
: base (op, left, right)
{
}
@ -583,7 +583,7 @@ namespace Mono.CSharp.Nullable @@ -583,7 +583,7 @@ namespace Mono.CSharp.Nullable
Constant c = new BoolConstant (ec.BuiltinTypes, Oper == Operator.Inequality, loc);
if ((Oper & Operator.EqualityMask) != 0) {
ec.Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is `{1}'",
ec.Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is always `{1}'",
TypeManager.CSharpName (expr.Type), c.GetValueAsLiteral ());
} else {
ec.Report.Warning (464, 2, loc, "The result of comparing type `{0}' with null is always `{1}'",
@ -1000,12 +1000,12 @@ namespace Mono.CSharp.Nullable @@ -1000,12 +1000,12 @@ namespace Mono.CSharp.Nullable
{
Expression left, right;
Unwrap unwrap;
public NullCoalescingOperator (Expression left, Expression right, Location loc)
public NullCoalescingOperator (Expression left, Expression right)
{
this.left = left;
this.right = right;
this.loc = loc;
this.loc = left.Location;
}
public Expression LeftExpression {

18
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/outline.cs

@ -142,7 +142,6 @@ public class Outline { @@ -142,7 +142,6 @@ public class Outline {
first = true;
foreach (ConstructorInfo ci in t.GetConstructors (DefaultFlags)) {
if (! ShowMember (ci))
continue;
@ -150,6 +149,7 @@ public class Outline { @@ -150,6 +149,7 @@ public class Outline {
o.WriteLine ();
first = false;
OutlineMemberAttribute (ci);
OutlineConstructor (ci);
o.WriteLine ();
@ -169,7 +169,8 @@ public class Outline { @@ -169,7 +169,8 @@ public class Outline {
if (first)
o.WriteLine ();
first = false;
OutlineMemberAttribute (m);
OutlineMethod (m);
o.WriteLine ();
@ -191,6 +192,7 @@ public class Outline { @@ -191,6 +192,7 @@ public class Outline {
o.WriteLine ();
first = false;
OutlineMemberAttribute (m);
OutlineOperator (m);
o.WriteLine ();
@ -208,6 +210,7 @@ public class Outline { @@ -208,6 +210,7 @@ public class Outline {
o.WriteLine ();
first = false;
OutlineMemberAttribute (pi);
OutlineProperty (pi);
o.WriteLine ();
@ -224,6 +227,7 @@ public class Outline { @@ -224,6 +227,7 @@ public class Outline {
o.WriteLine ();
first = false;
OutlineMemberAttribute (fi);
OutlineField (fi);
o.WriteLine ();
@ -240,6 +244,7 @@ public class Outline { @@ -240,6 +244,7 @@ public class Outline {
o.WriteLine ();
first = false;
OutlineMemberAttribute (ei);
OutlineEvent (ei);
o.WriteLine ();
@ -286,6 +291,15 @@ public class Outline { @@ -286,6 +291,15 @@ public class Outline {
o.WriteLine ("[Obsolete]");
}
void OutlineMemberAttribute (MemberInfo mi)
{
if (!mi.IsDefined (typeof (System.ObsoleteAttribute), false))
return;
var oa = mi.GetCustomAttributes (typeof (System.ObsoleteAttribute), false) [0] as ObsoleteAttribute;
var msg = oa.Message;
o.WriteLine ("[Obsolete{0}]", msg == null || msg == "" ? "" : string.Format ("(\"{0}\")", msg));
}
void OutlineEvent (EventInfo ei)
{
MethodBase accessor = ei.GetAddMethod (true);

19
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/property.cs

@ -362,8 +362,13 @@ namespace Mono.CSharp @@ -362,8 +362,13 @@ namespace Mono.CSharp
CheckAbstractAndExtern (block != null);
CheckProtectedModifier ();
if (block != null && block.IsIterator)
Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
if (block != null) {
if (block.IsIterator)
Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
if (Compiler.Settings.WriteMetadataOnly)
block = null;
}
return null;
}
@ -906,7 +911,7 @@ namespace Mono.CSharp @@ -906,7 +911,7 @@ namespace Mono.CSharp
public override void Emit (TypeDefinition parent)
{
if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
IsCompilerGenerated = true
};
@ -938,11 +943,10 @@ namespace Mono.CSharp @@ -938,11 +943,10 @@ namespace Mono.CSharp
var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location),
Location));
new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
var body = new ExplicitBlock (block, Location, Location);
block.AddStatement (new Do (body, cond, Location));
block.AddStatement (new Do (body, cond, Location, Location));
body.AddStatement (new StatementExpression (
new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
@ -1194,6 +1198,9 @@ namespace Mono.CSharp @@ -1194,6 +1198,9 @@ namespace Mono.CSharp
if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
return null;
if (Compiler.Settings.WriteMetadataOnly)
block = null;
MethodBuilder mb = method_data.MethodBuilder;
Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, mb, ParameterInfo, method.ModFlags);

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/report.cs

@ -49,7 +49,7 @@ namespace Mono.CSharp { @@ -49,7 +49,7 @@ namespace Mono.CSharp {
809, 824,
1030, 1058, 1060, 1066,
1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
1607, 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1699,
1607, 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1697, 1699,
1700, 1701, 1702, 1709, 1711, 1717, 1718, 1720, 1735,
1901, 1956, 1981, 1998,
2002, 2023, 2029,

23
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/settings.cs

@ -159,6 +159,8 @@ namespace Mono.CSharp { @@ -159,6 +159,8 @@ namespace Mono.CSharp {
public RuntimeVersion StdLibRuntimeVersion;
public bool WriteMetadataOnly;
readonly List<string> conditional_symbols;
readonly List<SourceFile> source_files;
@ -180,10 +182,8 @@ namespace Mono.CSharp { @@ -180,10 +182,8 @@ namespace Mono.CSharp {
StdLibRuntimeVersion = RuntimeVersion.v4;
WarningLevel = 4;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
TabSize = 4;
else
TabSize = 8;
// Default to 1 or mdb files would be platform speficic
TabSize = 1;
AssemblyReferences = new List<string> ();
AssemblyReferencesAliases = new List<Tuple<string, string>> ();
@ -224,11 +224,7 @@ namespace Mono.CSharp { @@ -224,11 +224,7 @@ namespace Mono.CSharp {
return source_files;
}
}
public IList<string> ConditionalSymbols {
get { return conditional_symbols; }
}
#endregion
public void AddConditionalSymbol (string symbol)
@ -674,8 +670,9 @@ namespace Mono.CSharp { @@ -674,8 +670,9 @@ namespace Mono.CSharp {
{
output.WriteLine (
"Other flags in the compiler\n" +
" --fatal[=COUNT] Makes errors after COUNT fatal\n" +
" --fatal[=COUNT] Makes error after COUNT fatal\n" +
" --lint Enhanced warnings\n" +
" --metadata-only Produced assembly will contain metadata only\n" +
" --parse Only parses the source file\n" +
" --runtime:VERSION Sets mscorlib.dll metadata version: v1, v2, v4\n" +
" --stacktrace Shows stack trace at error location\n" +
@ -937,7 +934,7 @@ namespace Mono.CSharp { @@ -937,7 +934,7 @@ namespace Mono.CSharp {
return ParseResult.Success;
case "/debug":
if (value == "full" || value == "pdbonly" || idx < 0) {
if (value.Equals ("full", StringComparison.OrdinalIgnoreCase) || value.Equals ("pdbonly", StringComparison.OrdinalIgnoreCase) || idx < 0) {
settings.GenerateDebugInfo = true;
return ParseResult.Success;
}
@ -1429,6 +1426,10 @@ namespace Mono.CSharp { @@ -1429,6 +1426,10 @@ namespace Mono.CSharp {
settings.LoadDefaultReferences = false;
return ParseResult.Success;
case "--metadata-only":
settings.WriteMetadataOnly = true;
return ParseResult.Success;
default:
if (arg.StartsWith ("--fatal", StringComparison.Ordinal)){
int fatal = 1;

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save