Browse Source

Update to NRefactory commit 9d875d3

9d875d3 Bump NRefactory version number to 5.4.
ebe00cc ConsistencyCheck: Ensure mscorlib is added to the compilation (MSBuild doesn't return it for .NET 2.0 projects like IKVM)
d68853d Fix missing FreezeList() call to DefaultUnresolvedTypeParameter.Freeze().
a71bf19 Merge several bugfixes from SharpDevelop repository to NRefactory.
6856bd1 Remove System.Runtime hack -- type forwarding should handle this case.
17aefe2 Handle blob decoding errors in the type system instead of placing catch-all handlers in random spots.
877394a Mark DefaultAssemblyReference.Corlib as obsolete
f70e546 Updated mcs.
7a2614d Fixed null check
48bdfd7 Merge pull request #405 from DavidKarlas/paramBug
e6ce1e6 Fixing parameter code completion after using '>' e.g. if(a>b)Method(
6da0a7b Ignored failing unit test.
4d0b4a4 Fixed 'Bug 20110 - [Forms] Autocomplete doesn't work for the Placeholder property'.
e5958a8 Fixed another completion bug case.
37368af Fixed completion bug.
67a1d11 Disabled uncategorized/notworking code issues.
cf4fc70 Disabled notworking code issue. That's fixed in .NET 4.5 anyways and this code issue was very, very slow.
39bb34a Remap failing system.runtime references to mscorlib. Use case: Reference portable.NET assemblies from non portable .NET code.
44e1ff1 Fixed Bug 20125 - Fails to show abstract method when writing "override"
c47e3d1 Fixed little bug in resolver. It incorrectly resolved internal types sometimes.
6c4c6d3 Fixed wrong end location of RedundantAttributeParenthesesIssue. Due to a drawing error in monodevelop that wasn't visible before.
2b69be0 Fixed bug in inconsistent naming tests.
3c9256f Merge pull request #404 from mono-soc-2013/MateY-IndentEngine
4733874 Fixed issue 389.
c0aebb7 Fixed issue in ResolveAtLocation. On indexer 'this' the indexer should be resolved.
1c48cd2 Merge pull request #400 from DavidKarlas/parseExpression
242c141 Fixed parser bug when using ParseExpression
9d1cc09 Fixed parser bug.
13b0928 Catches exception for the IsBrowsable extension method. Fixed monodevelop bug https://bugzilla.xamarin.com/show_bug.cgi?id=18706.
3f78bdb Merge pull request #397 from khellang/patch-1
f6e7c08 Update README
0b743ac Merge pull request #396 from Therzok/master
36d6246 Optimize some Linq.
75640bf Merge pull request #395 from Therzok/master
5789870 [CodeIssues] Add simplified versions Math functions.
28d04ae Fixed potential blob reader exception.
22d8bc2 Fixed failing unit tests.
e2dced7 Merge branch 'master' of github.com:icsharpcode/NRefactory
705590d Merge pull request #392 from DavidKarlas/paramInfoAnywhere
800296d Merge pull request #393 from DavidKarlas/failRevert
63a63f2 Correcting bad revert. Sometimes it was returing 0 instead of -1.
27590b5 Improved resolving of target method for ParameterInfo so it can be triggered in middle of parameter and not only after '(',',','[' or '<'.
7aef513 Merge pull request #391 from DavidKarlas/revertPull390
a8141ef Reverting Pull #390
2132edc Merge pull request #390 from DavidKarlas/firstParameter
b6ccdb9 Always displaying first parameter discription in ParameterInfo tooltip
pull/507/head
Daniel Grunwald 11 years ago
parent
commit
fe566257de
  1. 12
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/NotWorking/AccessToClosureIssues/AccessToDisposedClosureIssue.cs
  2. 12
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/NotWorking/AccessToClosureIssues/AccessToModifiedClosureIssue.cs
  3. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/NotWorking/VariableDeclaredInWideScopeIssue.cs
  4. 16
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/ConstraintViolations/InconsistentNamingIssue/NamingRule.cs
  5. 123
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/PracticesAndImprovements/ReplaceWithSingleCallToAverageIssue.cs
  6. 43
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/PracticesAndImprovements/ReplaceWithSingleCallToMaxIssue.cs
  7. 43
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/PracticesAndImprovements/ReplaceWithSingleCallToMinIssue.cs
  8. 43
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/PracticesAndImprovements/ReplaceWithSingleCallToSumIssue.cs
  9. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/RedundanciesInCode/RedundantAttributeParenthesesIssue.cs
  10. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/AutoAsyncIssue.cs
  11. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/DisposeMethodInNonIDisposableTypeIssue.cs
  12. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/DontUseLinqWhenItsVerboseAndInefficientIssue.cs
  13. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/DuplicatedLinqToListOrArrayIssue.cs
  14. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/ExceptionRethrowIssue.cs
  15. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/ExplicitConversionInForEachIssue.cs
  16. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/IncorrectCallToObjectGetHashCodeIssue.cs
  17. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/RedundantBlockInDifferentBranchesIssue.cs
  18. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/RedundantNotNullAttributeInNonNullableTypeIssue.cs
  19. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/ResultOfAsyncCallShouldNotBeIgnoredIssue.cs
  20. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/SameGuardConditionExpressionInIfelseBranchesIssue.cs
  21. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/UnmatchedSizeSpecificationInArrayCreationIssue.cs
  22. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/UseOfMemberOfNullReference.cs
  23. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/ICSharpCode.NRefactory.CSharp.Refactoring.csproj
  24. 11
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs
  25. 27
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngineBase.cs
  26. 147
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpParameterCompletionEngine.cs
  27. 23
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IndentState.cs
  28. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/TextWriterOutputFormatter.cs
  29. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CSharpParser.cs
  30. 66
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolTable.cs
  31. 7
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/SourceMethodBuilder.cs
  32. 35
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/anonymous.cs
  33. 23
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assembly.cs
  34. 40
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assign.cs
  35. 37
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/async.cs
  36. 61
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/attribute.cs
  37. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cfold.cs
  38. 130
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/class.cs
  39. 44
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/codegen.cs
  40. 12
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/complete.cs
  41. 40
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/constant.cs
  42. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/context.cs
  43. 89
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/convert.cs
  44. 10006
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.cs
  45. 139
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.jay
  46. 46
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-tokenizer.cs
  47. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/delegate.cs
  48. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/doc.cs
  49. 148
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ecore.cs
  50. 81
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/eval.cs
  51. 139
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/expression.cs
  52. 39
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/field.cs
  53. 84
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/generic.cs
  54. 18
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/iterators.cs
  55. 14
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/membercache.cs
  56. 130
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/method.cs
  57. 38
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/nullable.cs
  58. 73
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/parameter.cs
  59. 128
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/property.cs
  60. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/report.cs
  61. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/settings.cs
  62. 651
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/statement.cs
  63. 11
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/typespec.cs
  64. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Script.cs
  65. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CSharpResolver.cs
  66. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/ResolveAtLocation.cs
  67. 5
      src/Libraries/NRefactory/ICSharpCode.NRefactory.ConsistencyCheck/CSharpProject.cs
  68. 9
      src/Libraries/NRefactory/ICSharpCode.NRefactory.ConsistencyCheck/Xml/XmlReaderTest.cs
  69. 83
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/ObjectInitializerTests.cs
  70. 54
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/ParameterCompletionTests.cs
  71. 14
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/InconsistentNamingTests.cs
  72. 77
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/ReplaceWithSingleCallToAverageIssueTests.cs
  73. 77
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/ReplaceWithSingleCallToMaxIssueTests.cs
  74. 77
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/ReplaceWithSingleCallToMinIssueTests.cs
  75. 77
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/ReplaceWithSingleCallToSumIssueTests.cs
  76. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/UnmatchedSizeSpeicificationInArrayCreationTests.cs
  77. 19
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Bugs/ParserBugTests.cs
  78. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/PropertyDeclarationTests.cs
  79. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj
  80. 181
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/IndentationTests/BlockTest.cs
  81. 5
      src/Libraries/NRefactory/ICSharpCode.NRefactory/Completion/CompletionExtensionMethods.cs
  82. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory/Properties/GlobalAssemblyInfo.cs
  83. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAssemblyReference.cs
  84. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedTypeParameter.cs
  85. 28
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/ResolvedAttributeBlob.cs
  86. 6
      src/Libraries/NRefactory/Packages/ICSharpCode.NRefactory.nuspec
  87. 1
      src/Libraries/NRefactory/README

12
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/NotWorking/AccessToClosureIssues/AccessToDisposedClosureIssue.cs

@ -32,12 +32,12 @@ using ICSharpCode.NRefactory.Refactoring; @@ -32,12 +32,12 @@ using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription ("Access to disposed closure variable",
Description = "Access to closure variable from anonymous method when the variable is" +
" disposed externally",
Category = IssueCategories.CodeQualityIssues,
Severity = Severity.Warning,
AnalysisDisableKeyword = "AccessToDisposedClosure")]
// [IssueDescription ("Access to disposed closure variable",
// Description = "Access to closure variable from anonymous method when the variable is" +
// " disposed externally",
// Category = IssueCategories.CodeQualityIssues,
// Severity = Severity.Warning,
// AnalysisDisableKeyword = "AccessToDisposedClosure")]
public class AccessToDisposedClosureIssue : AccessToClosureIssue
{
public AccessToDisposedClosureIssue ()

12
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/NotWorking/AccessToClosureIssues/AccessToModifiedClosureIssue.cs

@ -31,12 +31,12 @@ using ICSharpCode.NRefactory.Refactoring; @@ -31,12 +31,12 @@ using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Access to modified closure variable",
Description = "Access to closure variable from anonymous method when the variable is modified " +
"externally",
Category = IssueCategories.CodeQualityIssues,
Severity = Severity.Warning,
AnalysisDisableKeyword = "AccessToModifiedClosure")]
// [IssueDescription("Access to modified closure variable",
// Description = "Access to closure variable from anonymous method when the variable is modified " +
// "externally",
// Category = IssueCategories.CodeQualityIssues,
// Severity = Severity.Warning,
// AnalysisDisableKeyword = "AccessToModifiedClosure")]
public class AccessToModifiedClosureIssue : AccessToClosureIssue
{
public AccessToModifiedClosureIssue ()

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/NotWorking/VariableDeclaredInWideScopeIssue.cs

@ -134,7 +134,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -134,7 +134,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
}
// Restrict to locations outside of blacklisted node types
var firstBlackListedNode = path.Where(node => moveTargetBlacklist.Contains(node.GetType())).FirstOrDefault();
var firstBlackListedNode = path.FirstOrDefault(node => moveTargetBlacklist.Contains(node.GetType()));
if (firstBlackListedNode != null) {
path = GetPath(rootNode, firstBlackListedNode.Parent);
anchorNode = firstBlackListedNode;

16
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/ConstraintViolations/InconsistentNamingIssue/NamingRule.cs

@ -376,7 +376,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -376,7 +376,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
break;
case NamingStyle.CamelCase:
if (id.Length > 0 && char.IsUpper(id [0])) {
if (id.Length > 0 && !char.IsLower(id [0])) {
errorMessage = string.Format(ctx.TranslateString("'{0}' should start with a lower case letter. (Rule '{1}')"), name, Name);
} else if (!CheckUnderscore(id, UnderscoreHandling.Forbid)) {
errorMessage = string.Format(ctx.TranslateString("'{0}' should not separate words with an underscore. (Rule '{1}')"), name, Name);
@ -387,7 +387,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -387,7 +387,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
suggestedNames.Add(CamelCaseIdentifier(id));
break;
case NamingStyle.CamelCaseWithLowerLetterUnderscore:
if (id.Length > 0 && char.IsUpper(id [0])) {
if (id.Length > 0 && !char.IsLower(id [0])) {
errorMessage = string.Format(ctx.TranslateString("'{0}' should start with a lower case letter. (Rule '{1}')"), name, Name);
} else if (!CheckUnderscore(id, UnderscoreHandling.AllowWithLowerStartingLetter)) {
errorMessage = string.Format(ctx.TranslateString("after '_' a lower letter should follow. (Rule '{0}')"), Name);
@ -398,7 +398,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -398,7 +398,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
suggestedNames.Add(CamelCaseWithLowerLetterUnderscore(id));
break;
case NamingStyle.CamelCaseWithUpperLetterUnderscore:
if (id.Length > 0 && char.IsUpper(id [0])) {
if (id.Length > 0 && !char.IsLower(id [0])) {
errorMessage = string.Format(ctx.TranslateString("'{0}' should start with a lower case letter. (Rule '{1}')"), name, Name);
} else if (!CheckUnderscore(id, UnderscoreHandling.AllowWithUpperStartingLetter)) {
errorMessage = string.Format(ctx.TranslateString("after '_' an upper letter should follow. (Rule '{0}')"), Name);
@ -410,7 +410,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -410,7 +410,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
break;
case NamingStyle.PascalCase:
if (id.Length > 0 && char.IsLower(id [0])) {
if (id.Length > 0 && !char.IsUpper(id [0])) {
errorMessage = string.Format(ctx.TranslateString("'{0}' should start with an upper case letter. (Rule '{1}')"), name, Name);
} else if (!CheckUnderscore(id, UnderscoreHandling.Forbid)) {
errorMessage = string.Format(ctx.TranslateString("'{0}' should not separate words with an underscore. (Rule '{1}')"), name, Name);
@ -421,7 +421,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -421,7 +421,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
suggestedNames.Add(PascalCaseIdentifier(id));
break;
case NamingStyle.PascalCaseWithLowerLetterUnderscore:
if (id.Length > 0 && char.IsLower(id [0])) {
if (id.Length > 0 && !char.IsUpper(id [0])) {
errorMessage = string.Format(ctx.TranslateString("'{0}' should start with an upper case letter. (Rule '{1}')"), name, Name);
} else if (!CheckUnderscore(id, UnderscoreHandling.AllowWithLowerStartingLetter)) {
errorMessage = string.Format(ctx.TranslateString("after '_' a lower letter should follow. (Rule '{0}')"), Name);
@ -432,7 +432,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -432,7 +432,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
suggestedNames.Add(PascalCaseWithLowerLetterUnderscore(id));
break;
case NamingStyle.PascalCaseWithUpperLetterUnderscore:
if (id.Length > 0 && char.IsLower(id [0])) {
if (id.Length > 0 && !char.IsUpper(id [0])) {
errorMessage = string.Format(ctx.TranslateString("'{0}' should start with an upper case letter. (Rule '{1}')"), name, Name);
} else if (!CheckUnderscore(id, UnderscoreHandling.AllowWithUpperStartingLetter)) {
errorMessage = string.Format(ctx.TranslateString("after '_' an upper letter should follow. (Rule '{0}')"), Name);
@ -443,7 +443,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -443,7 +443,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
suggestedNames.Add(PascalCaseWithUpperLetterUnderscore(id));
break;
case NamingStyle.FirstUpper:
if (id.Length > 0 && char.IsLower(id [0])) {
if (id.Length > 0 && !char.IsUpper(id [0])) {
errorMessage = string.Format(ctx.TranslateString("'{0}' should start with an upper case letter. (Rule '{1}')"), name, Name);
} else if (id.Take(1).Any(ch => char.IsLetter(ch) && char.IsUpper(ch))) {
errorMessage = string.Format(ctx.TranslateString("'{0}' contains an upper case letter after the first. (Rule '{1}')"), name, Name);
@ -525,6 +525,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -525,6 +525,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
bool first = true;
for (int i = 0; i < id.Length; i++) {
char ch = id[i];
if (i == 0 && ch == '_')
continue;
if (first && char.IsLetter(ch)) {
sb.Append(firstCharFunc(ch));
firstCharFunc = followingCharFunc;

123
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/PracticesAndImprovements/ReplaceWithSingleCallToAverageIssue.cs

@ -0,0 +1,123 @@ @@ -0,0 +1,123 @@
//
// ReplaceWithSingleCallToAverageIssue.cs
//
// Author:
// Marius Ungureanu <marius.ungureanu@xamarin.com>
//
// Copyright (c) 2014 Xamarin <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.Linq;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.PatternMatching;
using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Replace with single call to Average(...)",
Description = "Replace with single call to Average(...)",
Category = IssueCategories.PracticesAndImprovements,
Severity = Severity.Suggestion,
AnalysisDisableKeyword = "ReplaceWithSingleCallToAverage")]
public class ReplaceWithSingleCallToAverageIssue : GatherVisitorCodeIssueProvider
{
static readonly AstNode pattern =
new InvocationExpression (
new MemberReferenceExpression (
new NamedNode ("selectInvoke",
new InvocationExpression (
new MemberReferenceExpression (new AnyNode ("target"), "Select"),
new AnyNode ())),
Pattern.AnyString));
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)
{
return new GatherVisitor<ReplaceWithSingleCallToAverageIssue>(context, "Average");
}
internal class GatherVisitor<T> : GatherVisitorBase<T> where T : GatherVisitorCodeIssueProvider
{
readonly string member;
public GatherVisitor (BaseRefactoringContext ctx, string member) : base (ctx)
{
this.member = member;
}
public override void VisitInvocationExpression (InvocationExpression invocationExpression)
{
base.VisitInvocationExpression (invocationExpression);
var match = pattern.Match (invocationExpression);
if (!match.Success)
return;
var averageResolve = ctx.Resolve (invocationExpression) as InvocationResolveResult;
if (averageResolve == null || !HasPredicateVersion(averageResolve.Member))
return;
var selectInvoke = match.Get<InvocationExpression> ("selectInvoke").Single ();
var selectResolve = ctx.Resolve (selectInvoke) as InvocationResolveResult;
if (selectResolve == null || selectResolve.Member.Name != "Select" || !IsQueryExtensionClass(selectResolve.Member.DeclaringTypeDefinition))
return;
if (selectResolve.Member.Parameters.Count != 2)
return;
var predResolve = selectResolve.Member.Parameters [1];
if (predResolve.Type.TypeParameterCount != 2)
return;
AddIssue(new CodeIssue(
invocationExpression, string.Format(ctx.TranslateString("Redundant Select() call with predicate followed by {0}()"), averageResolve.Member.Name),
new CodeAction (
string.Format(ctx.TranslateString("Replace with single call to '{0}'"), averageResolve.Member.Name),
script => {
var arg = selectInvoke.Arguments.Single ().Clone ();
var target = match.Get<Expression> ("target").Single ().Clone ();
script.Replace (invocationExpression, new InvocationExpression (new MemberReferenceExpression (target, averageResolve.Member.Name), arg));
},
invocationExpression
)
));
}
static bool IsQueryExtensionClass(ITypeDefinition typeDef)
{
if (typeDef == null || typeDef.Namespace != "System.Linq")
return false;
switch (typeDef.Name) {
case "Enumerable":
case "ParallelEnumerable":
case "Queryable":
return true;
default:
return false;
}
}
bool HasPredicateVersion(IParameterizedMember member)
{
if (!IsQueryExtensionClass(member.DeclaringTypeDefinition))
return false;
return member.Name == this.member;
}
}
}
}

43
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/PracticesAndImprovements/ReplaceWithSingleCallToMaxIssue.cs

@ -0,0 +1,43 @@ @@ -0,0 +1,43 @@
//
// ReplaceWithSingleCallToMaxIssue.cs
//
// Author:
// Marius Ungureanu <marius.ungureanu@xamarin.com>
//
// Copyright (c) 2014 Xamarin <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 ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Replace with single call to Max(...)",
Description = "Replace with single call to Max(...)",
Category = IssueCategories.PracticesAndImprovements,
Severity = Severity.Suggestion,
AnalysisDisableKeyword = "ReplaceWithSingleCallToMax")]
public class ReplaceWithSingleCallToMaxIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)
{
return new ReplaceWithSingleCallToAverageIssue.GatherVisitor<ReplaceWithSingleCallToMaxIssue>(context, "Max");
}
}
}

43
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/PracticesAndImprovements/ReplaceWithSingleCallToMinIssue.cs

@ -0,0 +1,43 @@ @@ -0,0 +1,43 @@
//
// ReplaceWithSingleCallToMinIssue.cs
//
// Author:
// Marius Ungureanu <marius.ungureanu@xamarin.com>
//
// Copyright (c) 2014 Xamarin <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 ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Replace with single call to Min(...)",
Description = "Replace with single call to Min(...)",
Category = IssueCategories.PracticesAndImprovements,
Severity = Severity.Suggestion,
AnalysisDisableKeyword = "ReplaceWithSingleCallToMin")]
public class ReplaceWithSingleCallToMinIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)
{
return new ReplaceWithSingleCallToAverageIssue.GatherVisitor<ReplaceWithSingleCallToMinIssue>(context, "Min");
}
}
}

43
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/PracticesAndImprovements/ReplaceWithSingleCallToSumIssue.cs

@ -0,0 +1,43 @@ @@ -0,0 +1,43 @@
//
// ReplaceWithSingleCallToSumIssue.cs
//
// Author:
// Marius Ungureanu <marius.ungureanu@xamarin.com>
//
// Copyright (c) 2014 Xamarin <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 ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Replace with single call to Sum(...)",
Description = "Replace with single call to Sum(...)",
Category = IssueCategories.PracticesAndImprovements,
Severity = Severity.Suggestion,
AnalysisDisableKeyword = "ReplaceWithSingleCallToSum")]
public class ReplaceWithSingleCallToSumIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)
{
return new ReplaceWithSingleCallToAverageIssue.GatherVisitor<ReplaceWithSingleCallToSumIssue>(context, "Sum");
}
}
}

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Synced/RedundanciesInCode/RedundantAttributeParenthesesIssue.cs

@ -55,7 +55,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -55,7 +55,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
if (attribute.Arguments.Count > 0 || !attribute.HasArgumentList)
return;
AddIssue(new CodeIssue(attribute.LParToken.StartLocation, attribute.RParToken.StartLocation, ctx.TranslateString("Parentheses are redundant if attribute has no arguments"), ctx.TranslateString("Remove '()'"), script =>
AddIssue(new CodeIssue(attribute.LParToken.StartLocation, attribute.RParToken.EndLocation, ctx.TranslateString("Parentheses are redundant if attribute has no arguments"), ctx.TranslateString("Remove '()'"), script =>
script.Replace(attribute, new Attribute { Type = attribute.Type.Clone() })) { IssueMarker = IssueMarker.GrayOut });
}
}

8
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/AutoAsyncIssue.cs

@ -39,10 +39,10 @@ using ICSharpCode.NRefactory.Refactoring; @@ -39,10 +39,10 @@ using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Old-style asynchronous function can be converted to C# 5 async",
Description = "Detects usage of old-style TaskCompletionSource/ContinueWith and suggests using async/await instead",
Category = IssueCategories.Opportunities,
Severity = Severity.Hint)]
// [IssueDescription("Old-style asynchronous function can be converted to C# 5 async",
// Description = "Detects usage of old-style TaskCompletionSource/ContinueWith and suggests using async/await instead",
// Category = IssueCategories.Opportunities,
// Severity = Severity.Hint)]
public class AutoAsyncIssue : GatherVisitorCodeIssueProvider
{
static readonly ReturnStatement ReturnTaskCompletionSourcePattern = new ReturnStatement {

8
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/DisposeMethodInNonIDisposableTypeIssue.cs

@ -32,10 +32,10 @@ using ICSharpCode.NRefactory.CSharp.Resolver; @@ -32,10 +32,10 @@ using ICSharpCode.NRefactory.CSharp.Resolver;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Type does not implement IDisposable despite having a Dispose method",
Description="This type declares a method named Dispose, but it does not implement the System.IDisposable interface",
Category=IssueCategories.CodeQualityIssues,
Severity=Severity.Warning)]
// [IssueDescription("Type does not implement IDisposable despite having a Dispose method",
// Description="This type declares a method named Dispose, but it does not implement the System.IDisposable interface",
// Category=IssueCategories.CodeQualityIssues,
// Severity=Severity.Warning)]
public class DisposeMethodInNonIDisposableTypeIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)

8
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/DontUseLinqWhenItsVerboseAndInefficientIssue.cs

@ -32,10 +32,10 @@ using ICSharpCode.NRefactory.CSharp.Resolver; @@ -32,10 +32,10 @@ using ICSharpCode.NRefactory.CSharp.Resolver;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Use of Linq methods when there's a better alternative",
Description="Detects usage of Linq when there's a simpler and faster alternative",
Category=IssueCategories.CodeQualityIssues,
Severity=Severity.Warning)]
// [IssueDescription("Use of Linq methods when there's a better alternative",
// Description="Detects usage of Linq when there's a simpler and faster alternative",
// Category=IssueCategories.CodeQualityIssues,
// Severity=Severity.Warning)]
public class DontUseLinqWhenItsVerboseAndInefficientIssue : GatherVisitorCodeIssueProvider
{
class LinqMethod {

8
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/DuplicatedLinqToListOrArrayIssue.cs

@ -36,10 +36,10 @@ using System.Linq; @@ -36,10 +36,10 @@ using System.Linq;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription ("Duplicated ToList() or ToArray() call",
Description = "Duplicated call to ToList() or ToArray()",
Category = IssueCategories.RedundanciesInCode,
Severity = Severity.Warning)]
// [IssueDescription ("Duplicated ToList() or ToArray() call",
// Description = "Duplicated call to ToList() or ToArray()",
// Category = IssueCategories.RedundanciesInCode,
// Severity = Severity.Warning)]
public class DuplicatedLinqToListOrArrayIssue : GatherVisitorCodeIssueProvider
{
const string MemberTarget = "target";

10
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/ExceptionRethrowIssue.cs

@ -31,11 +31,11 @@ using ICSharpCode.NRefactory.Refactoring; @@ -31,11 +31,11 @@ using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("A throw statement throws the caught exception by passing it explicitly",
Description = "Finds throws that throws the caught exception and therefore should be empty.",
Category = IssueCategories.CodeQualityIssues,
Severity = Severity.Warning,
AnalysisDisableKeyword = "PossibleIntendedRethrow")]
// [IssueDescription("A throw statement throws the caught exception by passing it explicitly",
// Description = "Finds throws that throws the caught exception and therefore should be empty.",
// Category = IssueCategories.CodeQualityIssues,
// Severity = Severity.Warning,
// AnalysisDisableKeyword = "PossibleIntendedRethrow")]
public class ExceptionRethrowIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)

8
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/ExplicitConversionInForEachIssue.cs

@ -25,10 +25,10 @@ using ICSharpCode.NRefactory.Refactoring; @@ -25,10 +25,10 @@ using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Incorrect element type in foreach over generic collection",
Description= "Detects hidden explicit conversions in foreach loops.",
Category = IssueCategories.CodeQualityIssues,
Severity = Severity.Warning)]
// [IssueDescription("Incorrect element type in foreach over generic collection",
// Description= "Detects hidden explicit conversions in foreach loops.",
// Category = IssueCategories.CodeQualityIssues,
// Severity = Severity.Warning)]
public class ExplicitConversionInForEachIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)

10
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/IncorrectCallToObjectGetHashCodeIssue.cs

@ -30,11 +30,11 @@ using ICSharpCode.NRefactory.Refactoring; @@ -30,11 +30,11 @@ using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Call resolves to Object.GetHashCode, which is reference based",
Description = "Finds calls to Object.GetHashCode inside overridden GetHashCode.",
Category = IssueCategories.CodeQualityIssues,
Severity = Severity.Warning,
AnalysisDisableKeyword = "BaseObjectGetHashCodeCallInGetHashCode")]
// [IssueDescription("Call resolves to Object.GetHashCode, which is reference based",
// Description = "Finds calls to Object.GetHashCode inside overridden GetHashCode.",
// Category = IssueCategories.CodeQualityIssues,
// Severity = Severity.Warning,
// AnalysisDisableKeyword = "BaseObjectGetHashCodeCallInGetHashCode")]
public class IncorrectCallToObjectGetHashCodeIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)

10
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/RedundantBlockInDifferentBranchesIssue.cs

@ -29,11 +29,11 @@ using ICSharpCode.NRefactory.Refactoring; @@ -29,11 +29,11 @@ using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("RedundantBlockInDifferentBranches",
Description = "Blocks in if/else can be simplified to any of the branches if they have the same block.",
Category = IssueCategories.RedundanciesInCode,
Severity = Severity.Hint,
AnalysisDisableKeyword = "RedundantBlockInDifferentBranches")]
// [IssueDescription("RedundantBlockInDifferentBranches",
// Description = "Blocks in if/else can be simplified to any of the branches if they have the same block.",
// Category = IssueCategories.RedundanciesInCode,
// Severity = Severity.Hint,
// AnalysisDisableKeyword = "RedundantBlockInDifferentBranches")]
public class RedundantBlockInDifferentBranchesIssue : GatherVisitorCodeIssueProvider
{

8
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/RedundantNotNullAttributeInNonNullableTypeIssue.cs

@ -33,10 +33,10 @@ using ICSharpCode.NRefactory.TypeSystem; @@ -33,10 +33,10 @@ using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Use of NotNullAttribute in non-nullable type is redundant.",
Description = "Detects unnecessary usages of the NotNullAttribute.",
Category = IssueCategories.RedundanciesInDeclarations,
Severity = Severity.Warning)]
// [IssueDescription("Use of NotNullAttribute in non-nullable type is redundant.",
// Description = "Detects unnecessary usages of the NotNullAttribute.",
// Category = IssueCategories.RedundanciesInDeclarations,
// Severity = Severity.Warning)]
public class RedundantNotNullAttributeInNonNullableTypeIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)

10
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/ResultOfAsyncCallShouldNotBeIgnoredIssue.cs

@ -24,11 +24,11 @@ using ICSharpCode.NRefactory.Refactoring; @@ -24,11 +24,11 @@ using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Result of async call is ignored",
Description = "Warns when the task returned by an async call is ignored, which causes exceptions" +
" thrown by the call to be silently ignored.",
Category = IssueCategories.CodeQualityIssues,
Severity = Severity.Warning)]
// [IssueDescription("Result of async call is ignored",
// Description = "Warns when the task returned by an async call is ignored, which causes exceptions" +
// " thrown by the call to be silently ignored.",
// Category = IssueCategories.CodeQualityIssues,
// Severity = Severity.Warning)]
public class ResultOfAsyncCallShouldNotBeIgnoredIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)

8
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/SameGuardConditionExpressionInIfelseBranchesIssue.cs

@ -30,10 +30,10 @@ using ICSharpCode.NRefactory.Refactoring; @@ -30,10 +30,10 @@ using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Same guard condition expression in different if else branch",
Description = "A warning should be given for the case: if (condition) {…} else if (condition) {…}.",
Category = IssueCategories.Notifications,
Severity = Severity.Warning)]
// [IssueDescription("Same guard condition expression in different if else branch",
// Description = "A warning should be given for the case: if (condition) {…} else if (condition) {…}.",
// Category = IssueCategories.Notifications,
// Severity = Severity.Warning)]
public class SameGuardConditionExpressionInIfelseBranchesIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)

10
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/UnmatchedSizeSpecificationInArrayCreationIssue.cs

@ -33,11 +33,11 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -33,11 +33,11 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// <summary>
/// When array initializer has the different number of elements as specified in size creation, it is an error.
/// </summary>
[IssueDescription("Correct size specification in array creation",
Description= "When array initializer has the different number of elements as specified in size creation, it is an error.",
Category = IssueCategories.CompilerErrors,
Severity = Severity.Error,
AnalysisDisableKeyword = "UnmatchedSizeSpecificationInArrayCreation")]
// [IssueDescription("Correct size specification in array creation",
// Description= "When array initializer has the different number of elements as specified in size creation, it is an error.",
// Category = IssueCategories.CompilerErrors,
// Severity = Severity.Error,
// AnalysisDisableKeyword = "UnmatchedSizeSpecificationInArrayCreation")]
public class UnmatchedSizeSpecificationInArrayCreationIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)

8
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Uncategorized/UseOfMemberOfNullReference.cs

@ -34,10 +34,10 @@ using ICSharpCode.NRefactory.CSharp.Analysis; @@ -34,10 +34,10 @@ using ICSharpCode.NRefactory.CSharp.Analysis;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Use of (non-extension method) member of null value will cause a NullReferenceException",
Description = "Detects when a member of a null value is used",
Category = IssueCategories.CodeQualityIssues,
Severity = Severity.Warning)]
// [IssueDescription("Use of (non-extension method) member of null value will cause a NullReferenceException",
// Description = "Detects when a member of a null value is used",
// Category = IssueCategories.CodeQualityIssues,
// Severity = Severity.Warning)]
public class UseOfMemberOfNullReference : GatherVisitorCodeIssueProvider
{
static readonly ISet<NullValueStatus> ProblematicNullStates = new HashSet<NullValueStatus> {

4
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/ICSharpCode.NRefactory.CSharp.Refactoring.csproj

@ -427,6 +427,10 @@ @@ -427,6 +427,10 @@
<Compile Include="CodeIssues\Custom\CompilerErrors\ExpressionIsNeverOfProvidedTypeIssue.cs" />
<Compile Include="CodeIssues\Custom\RedundantAssignmentIssue.cs" />
<Compile Include="CodeIssues\Custom\UnreachableCodeIssue.cs" />
<Compile Include="CodeIssues\Synced\PracticesAndImprovements\ReplaceWithSingleCallToMinIssue.cs" />
<Compile Include="CodeIssues\Synced\PracticesAndImprovements\ReplaceWithSingleCallToMaxIssue.cs" />
<Compile Include="CodeIssues\Synced\PracticesAndImprovements\ReplaceWithSingleCallToAverageIssue.cs" />
<Compile Include="CodeIssues\Synced\PracticesAndImprovements\ReplaceWithSingleCallToSumIssue.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>

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

@ -349,6 +349,8 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -349,6 +349,8 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return contextList.Result;
}
var lookup = new MemberLookup(ctx.CurrentTypeDefinition, Compilation.MainAssembly);
var list = typeof(System.Collections.IList).ToTypeReference().Resolve(Compilation);
var list1 = typeof(System.Collections.Generic.IList<>).ToTypeReference().Resolve(Compilation);
bool isProtectedAllowed = ctx.CurrentTypeDefinition != null && initializerType.GetDefinition() != null ?
ctx.CurrentTypeDefinition.IsDerivedFrom(initializerType.GetDefinition()) :
false;
@ -364,7 +366,9 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -364,7 +366,9 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
foreach (IProperty m in initializerType.GetMembers (m => m.SymbolKind == SymbolKind.Property)) {
if (m.CanSet && lookup.IsAccessible(m.Setter, isProtectedAllowed)) {
if (m.CanSet && lookup.IsAccessible(m.Setter, isProtectedAllowed) ||
m.CanGet && lookup.IsAccessible(m.Getter, isProtectedAllowed) && m.ReturnType.GetDefinition() != null &&
(m.ReturnType.GetDefinition().IsDerivedFrom(list.GetDefinition()) || m.ReturnType.GetDefinition().IsDerivedFrom(list1.GetDefinition()))) {
var data = contextList.AddMember(m);
if (data != null)
data.DisplayFlags |= DisplayFlags.NamedArgument;
@ -379,10 +383,9 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -379,10 +383,9 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
// case 1)
// check if the object is a list, if not only provide object initalizers
var list = typeof(System.Collections.IList).ToTypeReference().Resolve(Compilation);
if (initializerType.Kind != TypeKind.Array && list != null) {
var def = initializerType.GetDefinition();
if (def != null && !def.IsDerivedFrom(list.GetDefinition()))
if (def != null && !def.IsDerivedFrom(list.GetDefinition()) && !def.IsDerivedFrom(list1.GetDefinition()))
return contextList.Result;
}
@ -2354,7 +2357,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2354,7 +2357,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return null;
}
// check for valid constructors
if (t.GetConstructors().Count() > 0) {
if (t.GetConstructors().Any()) {
bool isProtectedAllowed = currentType != null ?
currentType.Resolve(ctx).GetDefinition().IsDerivedFrom(t.GetDefinition()) : false;
if (!t.GetConstructors().Any(m => lookup.IsAccessible(m, isProtectedAllowed))) {

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

@ -340,12 +340,27 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -340,12 +340,27 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
this.text = text;
}
public void Parse(Action<char> act = null)
/// <summary>
/// Parsing all text and calling act delegate on almost every character.
/// Skipping begining of comments, begining of verbatim strings and escaped characters.
/// </summary>
/// <param name="act">Return true to abort parsing. Integer argument represent offset in text.</param>
/// <returns>True if aborted.</returns>
public bool Parse(Func<char, int, bool> act = null)
{
Parse(0, text.Length, act);
return Parse(0, text.Length, act);
}
public void Parse(int start, int length, Action<char> act = null)
/// <summary>
/// Parsing text from start to start+length and calling act delegate on almost every character.
/// Skipping begining of comments, begining of verbatim strings and escaped characters.
/// </summary>
/// <param name="start">Start offset.</param>
/// <param name="length">Lenght to parse.</param>
/// <param name="act">Return true to abort parsing. Integer argument represent offset in text.</param>
/// <returns>True if aborted.</returns>
public bool Parse(int start, int length, Func<char, int, bool> act = null)
{
for (int i = start; i < length; i++) {
char ch = text [i];
@ -416,9 +431,11 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -416,9 +431,11 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
break;
}
if (act != null)
act(ch);
if (act (ch, i))
return true;
IsFistNonWs &= ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
}
return false;
}
}
@ -677,7 +694,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -677,7 +694,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
while (o >= "try".Length) {
char ch = memberText [o];
if (!char.IsWhiteSpace (ch)) {
if (ch == 'y' && memberText [o - 1] == 'r' && memberText [o - 2] == 't') {
if (ch == 'y' && memberText [o - 1] == 'r' && memberText [o - 2] == 't' && (o - 3 < 0 || !char.IsLetterOrDigit(memberText [o - 3]))) {
wrapper.Append ("} catch {}");
didAppendCatch = true;
}

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

@ -57,7 +57,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -57,7 +57,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (currentMember == null && currentType == null) {
return null;
}
baseUnit = ParseStub("x] = a[1");
baseUnit = ParseStub("x]");
//var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
var mref = baseUnit.GetNodeAt(location, n => n is IndexerExpression);
@ -183,20 +183,93 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -183,20 +183,93 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
public IParameterDataProvider GetParameterDataProvider(int offset, char completionChar)
{
if (offset <= 0) {
//Ignoring completionChar == '\0' because it usually means moving with arrow keys, tab or enter
//we don't want to trigger on those events but it probably should be handled somewhere else
//since our job is to resolve method and not to decide when to display tooltip or not
if (offset <= 0 || completionChar == '\0') {
return null;
}
if (completionChar != '(' && completionChar != '<' && completionChar != '[' && completionChar != ',') {
return null;
SetOffset (offset);
int startOffset;
string text;
if (currentMember == null && currentType == null) {
//In case of attributes parse all file
startOffset = 0;
text = document.Text;
} else {
var memberText = GetMemberTextToCaret ();
text = memberText.Item1;
startOffset = document.GetOffset (memberText.Item2);
}
SetOffset(offset);
if (IsInsideCommentStringOrDirective()) {
var parenStack = new Stack<int> ();
var chevronStack = new Stack<int> ();
var squareStack = new Stack<int> ();
var bracketStack = new Stack<int> ();
var lex = new MiniLexer (text);
bool failed = lex.Parse ((ch, off) => {
if (lex.IsInString || lex.IsInChar || lex.IsInVerbatimString || lex.IsInSingleComment || lex.IsInMultiLineComment || lex.IsInPreprocessorDirective)
return false;
switch (ch) {
case '(':
parenStack.Push (startOffset + off);
break;
case ')':
if (parenStack.Count == 0) {
return true;
}
parenStack.Pop ();
break;
case '<':
chevronStack.Push (startOffset + off);
break;
case '>':
//Don't abort if we don't have macthing '<' for '>' it could be if (i > 0) Foo($
if (chevronStack.Count == 0) {
return false;
}
chevronStack.Pop ();
break;
case '[':
squareStack.Push (startOffset + off);
break;
case ']':
if (squareStack.Count == 0) {
return true;
}
squareStack.Pop ();
break;
case '{':
bracketStack.Push (startOffset + off);
break;
case '}':
if (bracketStack.Count == 0) {
return true;
}
bracketStack.Pop ();
break;
}
return false;
});
if (failed)
return null;
}
int result = -1;
if (parenStack.Count > 0)
result = parenStack.Pop ();
if (squareStack.Count > 0)
result = Math.Max (result, squareStack.Pop ());
if (chevronStack.Count > 0)
result = Math.Max (result, chevronStack.Pop ());
//If we are inside { bracket we don't want to display anything
if (bracketStack.Count > 0 && bracketStack.Pop () > result)
return null;
if (result == -1)
return null;
SetOffset (result + 1);
ResolveResult resolveResult;
switch (completionChar) {
switch (document.GetCharAt (result)) {
case '(':
var invoke = GetInvocationBeforeCursor(true) ?? GetConstructorInitializerBeforeCursor();
if (invoke == null) {
@ -259,62 +332,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -259,62 +332,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
// return new NRefactoryParameterDataProvider (textEditorData, result.Expression, resolvedType);
// }
break;
case ',':
invoke = GetInvocationBeforeCursor(true) ?? GetIndexerBeforeCursor();
if (invoke == null) {
invoke = GetTypeBeforeCursor();
if (invoke != null) {
if (GetCurrentParameterIndex(document.GetOffset(invoke.Node.StartLocation), offset) < 0)
return null;
var typeExpression = ResolveExpression(invoke);
if (typeExpression == null || typeExpression.Result == null || typeExpression.Result.IsError) {
return null;
}
return factory.CreateTypeParameterDataProvider(document.GetOffset(invoke.Node.StartLocation), CollectAllTypes(typeExpression.Result.Type));
}
return null;
}
if (GetCurrentParameterIndex(document.GetOffset(invoke.Node.StartLocation), offset) < 0)
return null;
if (invoke.Node is ArrayCreateExpression)
return null;
if (invoke.Node is ObjectCreateExpression) {
var createType = ResolveExpression(((ObjectCreateExpression)invoke.Node).Type);
return factory.CreateConstructorProvider(document.GetOffset(invoke.Node.StartLocation), createType.Result.Type);
}
if (invoke.Node is ICSharpCode.NRefactory.CSharp.Attribute) {
var attribute = ResolveExpression(invoke);
if (attribute == null || attribute.Result == null) {
return null;
}
return factory.CreateConstructorProvider(document.GetOffset(invoke.Node.StartLocation), attribute.Result.Type);
}
invocationExpression = ResolveExpression(invoke);
if (invocationExpression == null || invocationExpression.Result == null || invocationExpression.Result.IsError) {
return null;
}
resolveResult = invocationExpression.Result;
if (resolveResult is MethodGroupResolveResult) {
return factory.CreateMethodDataProvider(document.GetOffset(invoke.Node.StartLocation), CollectMethods(invoke.Node, resolveResult as MethodGroupResolveResult));
}
if (resolveResult is MemberResolveResult) {
if (resolveResult.Type.Kind == TypeKind.Delegate) {
return factory.CreateDelegateDataProvider(document.GetOffset(invoke.Node.StartLocation), resolveResult.Type);
}
var mr = resolveResult as MemberResolveResult;
if (mr.Member is IMethod) {
return factory.CreateMethodDataProvider(document.GetOffset(invoke.Node.StartLocation), new [] { (IMethod)mr.Member });
}
}
if (resolveResult != null) {
return factory.CreateIndexerParameterDataProvider(document.GetOffset(invoke.Node.StartLocation), resolveResult.Type, GetAccessibleIndexers (resolveResult.Type), invoke.Node);
}
break;
case '<':
invoke = GetMethodTypeArgumentInvocationBeforeCursor();
if (invoke != null) {

23
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IndentState.cs

@ -516,10 +516,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -516,10 +516,8 @@ namespace ICSharpCode.NRefactory.CSharp
var parent = Parent as BracesBodyState;
if (parent == null || parent.LastBlockIndent == null || !Engine.EnableCustomIndentLevels)
{
if (!Engine.formattingOptions.IndentBlocksInsideExpressions) {
NextLineIndent.RemoveAlignment();
NextLineIndent.PopIf(IndentType.Continuation);
}
NextLineIndent.RemoveAlignment();
NextLineIndent.PopIf(IndentType.Continuation);
}
else
{
@ -545,7 +543,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -545,7 +543,7 @@ namespace ICSharpCode.NRefactory.CSharp
public override void OnExit()
{
if (Parent is BracesBodyState)
if (Parent is BracesBodyState && !((BracesBodyState)Parent).IsRightHandExpression)
{
((BracesBodyState)Parent).OnStatementExit();
}
@ -878,8 +876,16 @@ namespace ICSharpCode.NRefactory.CSharp @@ -878,8 +876,16 @@ namespace ICSharpCode.NRefactory.CSharp
/// </summary>
void AddIndentation(Body body)
{
var isExpression = Parent is ParenthesesBodyState || Parent is SquareBracketsBodyState ||
(Parent is BracesBodyState && ((BracesBodyState)Parent).IsRightHandExpression);
if (isExpression && Engine.formattingOptions.IndentBlocksInsideExpressions && Engine.isLineStart)
{
AddIndentation(BraceStyle.NextLineShifted);
}
BraceStyle style;
if (TryGetBraceStyle (body, out style)) {
if (TryGetBraceStyle(body, out style))
{
AddIndentation(style);
} else {
NextLineIndent.Push(IndentType.Empty);
@ -973,6 +979,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -973,6 +979,8 @@ namespace ICSharpCode.NRefactory.CSharp
if (ch == ClosedBracket)
{
ExitState();
if (Parent is BracesBodyState)
Parent.OnExit();
}
base.Push(ch);
@ -1031,9 +1039,10 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1031,9 +1039,10 @@ namespace ICSharpCode.NRefactory.CSharp
base.CheckKeyword(keyword);
}
public override void OnExit()
{
Parent.OnExit();
//Parent.OnExit();
}
public override IndentState Clone(CSharpIndentEngine engine)

6
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/TextWriterOutputFormatter.cs

@ -321,7 +321,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -321,7 +321,11 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
static string ConvertCharLiteral(char ch)
/// <summary>
/// Gets the escape sequence for the specified character within a char literal.
/// Does not include the single quotes surrounding the char literal.
/// </summary>
public static string ConvertCharLiteral(char ch)
{
if (ch == '\'') {
return "\\'";

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

@ -207,6 +207,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -207,6 +207,7 @@ namespace ICSharpCode.NRefactory.CSharp
memberType.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.DoubleColon), Roles.DoubleColon);
memberType.MemberNameToken = Identifier.Create(qam.Name, loc != null ? Convert(loc [1]) : TextLocation.Empty);
AddTypeArguments(qam, memberType);
return memberType;
}
@ -2167,6 +2168,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2167,6 +2168,7 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null && location.Count > 0)
result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.DoubleColon), Roles.DoubleColon);
AddTypeArguments(result, qualifiedAliasMember);
result.AddChild(Identifier.Create(qualifiedAliasMember.Name, location != null && location.Count > 1 ? Convert(location [1]) : TextLocation.Empty), Roles.Identifier);
return new TypeReferenceExpression { Type = result };
}

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

@ -184,6 +184,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -184,6 +184,7 @@ namespace Mono.CompilerServices.SymbolWriter
#region This is actually written to the symbol file
public readonly int Row;
public int Column;
public int EndRow, EndColumn;
public readonly int File;
public readonly int Offset;
public readonly bool IsHidden; // Obsolete is never used
@ -214,17 +215,24 @@ namespace Mono.CompilerServices.SymbolWriter @@ -214,17 +215,24 @@ namespace Mono.CompilerServices.SymbolWriter
}
public LineNumberEntry (int file, int row, int column, int offset, bool is_hidden)
: this (file, row, column, -1, -1, offset, is_hidden)
{
}
public LineNumberEntry (int file, int row, int column, int end_row, int end_column, int offset, bool is_hidden)
{
this.File = file;
this.Row = row;
this.Column = column;
this.EndRow = end_row;
this.EndColumn = end_column;
this.Offset = offset;
this.IsHidden = is_hidden;
}
public override string ToString ()
{
return String.Format ("[Line {0}:{1,2}:{3}]", File, Row, Column, Offset);
return String.Format ("[Line {0}:{1,2}-{3,4}:{5}]", File, Row, Column, EndRow, EndColumn, Offset);
}
}
@ -836,7 +844,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -836,7 +844,7 @@ namespace Mono.CompilerServices.SymbolWriter
this._line_numbers = lines;
}
internal void Write (MonoSymbolFile file, MyBinaryWriter bw, bool readColumnsInfo)
internal void Write (MonoSymbolFile file, MyBinaryWriter bw, bool hasColumnsInfo, bool hasEndInfo)
{
int start = (int) bw.BaseStream.Position;
@ -893,23 +901,37 @@ namespace Mono.CompilerServices.SymbolWriter @@ -893,23 +901,37 @@ 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);
if (hasColumnsInfo) {
for (int i = 0; i < LineNumbers.Length; i++) {
var ln = LineNumbers [i];
if (ln.Row >= 0)
bw.WriteLeb128 (ln.Column);
}
}
if (hasEndInfo) {
for (int i = 0; i < LineNumbers.Length; i++) {
var ln = LineNumbers [i];
if (ln.EndRow == -1 || ln.EndColumn == -1 || ln.Row > ln.EndRow) {
bw.WriteLeb128 (0xffffff);
} else {
bw.WriteLeb128 (ln.EndRow - ln.Row);
bw.WriteLeb128 (ln.EndColumn);
}
}
}
file.ExtendedLineNumberSize += (int) bw.BaseStream.Position - start;
}
internal static LineNumberTable Read (MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo)
internal static LineNumberTable Read (MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo, bool readEndInfo)
{
LineNumberTable lnt = new LineNumberTable (file);
lnt.DoRead (file, br, readColumnsInfo);
lnt.DoRead (file, br, readColumnsInfo, readEndInfo);
return lnt;
}
void DoRead (MonoSymbolFile file, MyBinaryReader br, bool includesColumns)
void DoRead (MonoSymbolFile file, MyBinaryReader br, bool includesColumns, bool includesEnds)
{
var lines = new List<LineNumberEntry> ();
@ -988,6 +1010,20 @@ namespace Mono.CompilerServices.SymbolWriter @@ -988,6 +1010,20 @@ namespace Mono.CompilerServices.SymbolWriter
ln.Column = br.ReadLeb128 ();
}
}
if (includesEnds) {
for (int i = 0; i < _line_numbers.Length; ++i) {
var ln = _line_numbers[i];
int row = br.ReadLeb128 ();
if (row == 0xffffff) {
ln.EndRow = -1;
ln.EndColumn = -1;
} else {
ln.EndRow = ln.Row + row;
ln.EndColumn = br.ReadLeb128 ();
}
}
}
}
public bool GetMethodBounds (out LineNumberEntry start, out LineNumberEntry end)
@ -1045,7 +1081,8 @@ namespace Mono.CompilerServices.SymbolWriter @@ -1045,7 +1081,8 @@ namespace Mono.CompilerServices.SymbolWriter
public enum Flags
{
LocalNamesAmbiguous = 1,
ColumnsInfoIncluded = 1 << 1
ColumnsInfoIncluded = 1 << 1,
EndInfoIncluded = 1 << 2
}
public const int Size = 12;
@ -1198,8 +1235,13 @@ namespace Mono.CompilerServices.SymbolWriter @@ -1198,8 +1235,13 @@ namespace Mono.CompilerServices.SymbolWriter
bw.Write (real_name);
}
foreach (var lne in lnt.LineNumbers) {
if (lne.EndRow != -1 || lne.EndColumn != -1)
flags |= Flags.EndInfoIncluded;
}
LineNumberTableOffset = (int) bw.BaseStream.Position;
lnt.Write (file, bw, (flags & Flags.ColumnsInfoIncluded) != 0);
lnt.Write (file, bw, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
DataOffset = (int) bw.BaseStream.Position;
@ -1236,7 +1278,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -1236,7 +1278,7 @@ namespace Mono.CompilerServices.SymbolWriter
long old_pos = reader.BaseStream.Position;
reader.BaseStream.Position = LineNumberTableOffset;
lnt = LineNumberTable.Read (SymbolFile, reader, (flags & Flags.ColumnsInfoIncluded) != 0);
lnt = LineNumberTable.Read (SymbolFile, reader, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
reader.BaseStream.Position = old_pos;
return lnt;

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

@ -58,9 +58,14 @@ namespace Mono.CompilerServices.SymbolWriter @@ -58,9 +58,14 @@ namespace Mono.CompilerServices.SymbolWriter
}
public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column, bool is_hidden)
{
MarkSequencePoint (offset, file, line, column, -1, -1, is_hidden);
}
public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column, int end_line, int end_column, bool is_hidden)
{
int file_idx = file != null ? file.Index : 0;
var lne = new LineNumberEntry (file_idx, line, column, offset, is_hidden);
var lne = new LineNumberEntry (file_idx, line, column, end_line, end_column, offset, is_hidden);
if (method_lines.Count > 0) {
var prev = method_lines[method_lines.Count - 1];

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

@ -1273,7 +1273,7 @@ namespace Mono.CSharp { @@ -1273,7 +1273,7 @@ namespace Mono.CSharp {
throw new InternalErrorException (e, loc);
}
if (!ec.IsInProbingMode) {
if (!ec.IsInProbingMode && !etree_conversion) {
compatibles.Add (type, am ?? EmptyExpression.Null);
}
@ -1363,9 +1363,12 @@ namespace Mono.CSharp { @@ -1363,9 +1363,12 @@ namespace Mono.CSharp {
// nothing, as we only exist to not do anything.
}
public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
public static void Error_AddressOfCapturedVar (ResolveContext rc, IVariableReference var, Location loc)
{
ec.Report.Error (1686, loc,
if (rc.CurrentAnonymousMethod is AsyncInitializer)
return;
rc.Report.Error (1686, loc,
"Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method, lambda expression or query expression",
var.Name);
}
@ -1605,6 +1608,7 @@ namespace Mono.CSharp { @@ -1605,6 +1608,7 @@ namespace Mono.CSharp {
var da_ontrue = fc.DefiniteAssignmentOnTrue;
var da_onfalse = fc.DefiniteAssignmentOnFalse;
fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = null;
block.FlowAnalysis (fc);
fc.ParametersBlock = prev_pb;
@ -1727,6 +1731,7 @@ namespace Mono.CSharp { @@ -1727,6 +1731,7 @@ namespace Mono.CSharp {
Modifiers modifiers;
TypeDefinition parent = null;
TypeParameters hoisted_tparams = null;
var src_block = Block.Original.Explicit;
if (src_block.HasCapturedVariable || src_block.HasCapturedThis) {
@ -1758,6 +1763,7 @@ namespace Mono.CSharp { @@ -1758,6 +1763,7 @@ namespace Mono.CSharp {
// use ldftn on non-boxed instances either to share mutated state
//
parent = sm_parent.Parent.PartialContainer;
hoisted_tparams = sm_parent.OriginalTypeParameters;
} else if (sm is IteratorStorey) {
//
// For iterators we can host everything in one class
@ -1775,6 +1781,9 @@ namespace Mono.CSharp { @@ -1775,6 +1781,9 @@ namespace Mono.CSharp {
modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
}
if (storey == null && hoisted_tparams == null)
hoisted_tparams = ec.CurrentTypeParameters;
if (parent == null)
parent = ec.CurrentTypeDefinition.Parent.PartialContainer;
@ -1782,9 +1791,7 @@ namespace Mono.CSharp { @@ -1782,9 +1791,7 @@ namespace Mono.CSharp {
"m", null, parent.PartialContainer.CounterAnonymousMethods++);
MemberName member_name;
if (storey == null && ec.CurrentTypeParameters != null) {
var hoisted_tparams = ec.CurrentTypeParameters;
if (hoisted_tparams != null) {
var type_params = new TypeParameters (hoisted_tparams.Count);
for (int i = 0; i < hoisted_tparams.Count; ++i) {
type_params.Add (hoisted_tparams[i].CreateHoistedCopy (null));
@ -1905,8 +1912,17 @@ namespace Mono.CSharp { @@ -1905,8 +1912,17 @@ namespace Mono.CSharp {
ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
} else {
if (delegate_method.IsGeneric)
delegate_method = delegate_method.MakeGenericMethod (ec.MemberContext, method.TypeParameters);
if (delegate_method.IsGeneric) {
TypeParameterSpec[] tparams;
var sm = ec.CurrentAnonymousMethod == null ? null : ec.CurrentAnonymousMethod.Storey as StateMachine;
if (sm != null && sm.OriginalTypeParameters != null) {
tparams = sm.CurrentTypeParameters.Types;
} else {
tparams = method.TypeParameters;
}
delegate_method = delegate_method.MakeGenericMethod (ec.MemberContext, tparams);
}
ec.Emit (OpCodes.Ldftn, delegate_method);
}
@ -2167,7 +2183,6 @@ namespace Mono.CSharp { @@ -2167,7 +2183,6 @@ namespace Mono.CSharp {
equals.Block = equals_block;
equals.Define ();
equals.PrepareEmit ();
Members.Add (equals);
//
@ -2222,7 +2237,6 @@ namespace Mono.CSharp { @@ -2222,7 +2237,6 @@ namespace Mono.CSharp {
hashcode_block.AddStatement (new Return (hash_variable, loc));
hashcode.Block = hashcode_top;
hashcode.Define ();
hashcode.PrepareEmit ();
Members.Add (hashcode);
//
@ -2233,7 +2247,6 @@ namespace Mono.CSharp { @@ -2233,7 +2247,6 @@ namespace Mono.CSharp {
tostring_block.AddStatement (new Return (string_concat, loc));
tostring.Block = tostring_block;
tostring.Define ();
tostring.PrepareEmit ();
Members.Add (tostring);
return true;

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

@ -207,7 +207,7 @@ namespace Mono.CSharp @@ -207,7 +207,7 @@ namespace Mono.CSharp
return;
if (Compiler.Settings.Target == Target.Exe) {
a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
Report.Error (7059, a.Location, "Executables cannot be satellite assemblies. Remove the attribute or keep it empty");
return;
}
@ -231,7 +231,8 @@ namespace Mono.CSharp @@ -231,7 +231,8 @@ namespace Mono.CSharp
var vinfo = IsValidAssemblyVersion (value, true);
if (vinfo == null) {
a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
Report.Error (7034, a.Location, "The specified version string `{0}' does not conform to the required format - major[.minor[.build[.revision]]]",
value);
return;
}
@ -322,13 +323,18 @@ namespace Mono.CSharp @@ -322,13 +323,18 @@ namespace Mono.CSharp
if (a.Type == pa.InternalsVisibleTo) {
string assembly_name = a.GetString ();
if (assembly_name == null) {
Report.Error (7030, a.Location, "Friend assembly reference cannot have `null' value");
return;
}
if (assembly_name.Length == 0)
return;
#if STATIC
ParsedAssemblyName aname;
ParseAssemblyResult r = Fusion.ParseAssemblyName (assembly_name, out aname);
if (r != ParseAssemblyResult.OK) {
Report.Warning (1700, 3, a.Location, "Assembly reference `{0}' is invalid and cannot be resolved",
Report.Warning (1700, 3, a.Location, "Friend assembly reference `{0}' is invalid and cannot be resolved",
assembly_name);
return;
}
@ -353,10 +359,15 @@ namespace Mono.CSharp @@ -353,10 +359,15 @@ namespace Mono.CSharp
} else if (a.Type == pa.AssemblyFileVersion) {
vi_product_version = a.GetString ();
if (string.IsNullOrEmpty (vi_product_version) || IsValidAssemblyVersion (vi_product_version, false) == null) {
Report.Warning (1607, 1, a.Location, "The version number `{0}' specified for `{1}' is invalid",
Report.Warning (7035, 1, a.Location, "The specified version string `{0}' does not conform to the recommended format major.minor.build.revision",
vi_product_version, a.Name);
return;
}
// File version info decoding from blob is not supported
var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), new object[] { vi_product_version });
Builder.SetCustomAttribute (cab);
return;
} else if (a.Type == pa.AssemblyProduct) {
vi_product = a.GetString ();
} else if (a.Type == pa.AssemblyCompany) {
@ -394,8 +405,8 @@ namespace Mono.CSharp @@ -394,8 +405,8 @@ namespace Mono.CSharp
}
var ci = a.Assembly.GetName ().CultureInfo;
if (!ci.Equals (System.Globalization.CultureInfo.InvariantCulture)) {
Report.Warning (1607, 1, "Referenced assembly `{0}' has different culture setting of `{1}'",
if (!ci.Equals (CultureInfo.InvariantCulture)) {
Report.Warning (8009, 1, "Referenced assembly `{0}' has different culture setting of `{1}'",
a.Name, ci.Name);
}

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

@ -334,7 +334,7 @@ namespace Mono.CSharp { @@ -334,7 +334,7 @@ namespace Mono.CSharp {
if (source == null) {
ok = false;
source = EmptyExpression.Null;
source = ErrorExpression.Instance;
}
target = target.ResolveLValue (ec, source);
@ -569,6 +569,9 @@ namespace Mono.CSharp { @@ -569,6 +569,9 @@ namespace Mono.CSharp {
{
flags |= Options.FieldInitializerScope | Options.ConstructorScope;
this.ctor_block = constructorContext.CurrentBlock.Explicit;
if (ctor_block.IsCompilerGenerated)
CurrentBlock = ctor_block;
}
public override ExplicitBlock ConstructorBlock {
@ -594,6 +597,12 @@ namespace Mono.CSharp { @@ -594,6 +597,12 @@ namespace Mono.CSharp {
public int AssignmentOffset { get; private set; }
public FieldBase Field {
get {
return mc;
}
}
public override Location StartLocation {
get {
return loc;
@ -606,8 +615,8 @@ namespace Mono.CSharp { @@ -606,8 +615,8 @@ namespace Mono.CSharp {
if (source == null)
return null;
var bc = (BlockContext) rc;
if (resolved == null) {
var bc = (BlockContext) rc;
var ctx = new FieldInitializerContext (mc, bc);
resolved = base.DoResolve (ctx) as ExpressionStatement;
AssignmentOffset = ctx.AssignmentInfoOffset - bc.AssignmentInfoOffset;
@ -661,6 +670,33 @@ namespace Mono.CSharp { @@ -661,6 +670,33 @@ namespace Mono.CSharp {
}
}
class PrimaryConstructorAssign : SimpleAssign
{
readonly Field field;
readonly Parameter parameter;
public PrimaryConstructorAssign (Field field, Parameter parameter)
: base (null, null, parameter.Location)
{
this.field = field;
this.parameter = parameter;
}
protected override Expression DoResolve (ResolveContext rc)
{
target = new FieldExpr (field, loc);
source = rc.CurrentBlock.ParametersBlock.GetParameterInfo (parameter).CreateReferenceExpression (rc, loc);
return base.DoResolve (rc);
}
public override void EmitStatement (EmitContext ec)
{
using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
base.EmitStatement (ec);
}
}
}
//
// This class is used for compound assignments.
//

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

@ -80,10 +80,6 @@ namespace Mono.CSharp @@ -80,10 +80,6 @@ namespace Mono.CSharp
protected override Expression DoResolve (ResolveContext rc)
{
if (rc.HasSet (ResolveContext.Options.FinallyScope)) {
rc.Report.Error (1984, loc, "The `await' operator cannot be used in the body of a finally clause");
}
if (rc.HasSet (ResolveContext.Options.LockScope)) {
rc.Report.Error (1996, loc,
"The `await' operator cannot be used in the body of a lock statement");
@ -250,7 +246,7 @@ namespace Mono.CSharp @@ -250,7 +246,7 @@ namespace Mono.CSharp
var fe_awaiter = new FieldExpr (awaiter, loc);
fe_awaiter.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
Label skip_continuation = ec.DefineLabel ();
Label skip_continuation = ec.DefineLabel ();
using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
//
@ -330,10 +326,6 @@ namespace Mono.CSharp @@ -330,10 +326,6 @@ namespace Mono.CSharp
return false;
}
if (bc.HasSet (ResolveContext.Options.CatchScope)) {
bc.Report.Error (1985, loc, "The `await' operator cannot be used in the body of a catch clause");
}
if (!base.Resolve (bc))
return false;
@ -453,6 +445,10 @@ namespace Mono.CSharp @@ -453,6 +445,10 @@ namespace Mono.CSharp
get; set;
}
public StackFieldExpr HoistedReturnState {
get; set;
}
public override bool IsIterator {
get {
return false;
@ -470,9 +466,9 @@ namespace Mono.CSharp @@ -470,9 +466,9 @@ namespace Mono.CSharp
protected override BlockContext CreateBlockContext (BlockContext bc)
{
var ctx = base.CreateBlockContext (bc);
var lambda = bc.CurrentAnonymousMethod as LambdaMethod;
if (lambda != null)
return_inference = lambda.ReturnTypeInference;
var am = bc.CurrentAnonymousMethod as AnonymousMethodBody;
if (am != null)
return_inference = am.ReturnTypeInference;
ctx.Set (ResolveContext.Options.TryScope);
@ -515,7 +511,6 @@ namespace Mono.CSharp @@ -515,7 +511,6 @@ namespace Mono.CSharp
MethodSpec builder_factory;
MethodSpec builder_start;
PropertySpec task;
LocalVariable hoisted_return;
int locals_captured;
Dictionary<TypeSpec, List<Field>> stack_fields;
Dictionary<TypeSpec, List<Field>> awaiter_fields;
@ -529,11 +524,7 @@ namespace Mono.CSharp @@ -529,11 +524,7 @@ namespace Mono.CSharp
#region Properties
public LocalVariable HoistedReturn {
get {
return hoisted_return;
}
}
public Expression HoistedReturnValue { get; set; }
public TypeSpec ReturnType {
get {
@ -582,7 +573,7 @@ namespace Mono.CSharp @@ -582,7 +573,7 @@ namespace Mono.CSharp
return field;
}
public Field AddCapturedLocalVariable (TypeSpec type)
public Field AddCapturedLocalVariable (TypeSpec type, bool requiresUninitialized = false)
{
if (mutator != null)
type = mutator.Mutate (type);
@ -590,7 +581,7 @@ namespace Mono.CSharp @@ -590,7 +581,7 @@ namespace Mono.CSharp
List<Field> existing_fields = null;
if (stack_fields == null) {
stack_fields = new Dictionary<TypeSpec, List<Field>> ();
} else if (stack_fields.TryGetValue (type, out existing_fields)) {
} else if (stack_fields.TryGetValue (type, out existing_fields) && !requiresUninitialized) {
foreach (var f in existing_fields) {
if (f.IsAvailableForReuse) {
f.IsAvailableForReuse = false;
@ -723,7 +714,7 @@ namespace Mono.CSharp @@ -723,7 +714,7 @@ namespace Mono.CSharp
set_state_machine.Block.AddStatement (new StatementExpression (new Invocation (mg, args)));
if (has_task_return_type) {
hoisted_return = LocalVariable.CreateCompilerGenerated (bt.TypeArguments[0], StateMachineMethod.Block, Location);
HoistedReturnValue = TemporaryVariableReference.Create (bt.TypeArguments [0], StateMachineMethod.Block, Location);
}
return true;
@ -910,11 +901,11 @@ namespace Mono.CSharp @@ -910,11 +901,11 @@ namespace Mono.CSharp
};
Arguments args;
if (hoisted_return == null) {
if (HoistedReturnValue == null) {
args = new Arguments (0);
} else {
args = new Arguments (1);
args.Add (new Argument (new LocalVariableReference (hoisted_return, Location)));
args.Add (new Argument (HoistedReturnValue));
}
using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {

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

@ -257,19 +257,22 @@ namespace Mono.CSharp { @@ -257,19 +257,22 @@ namespace Mono.CSharp {
Report.Error (1970, loc, "Do not use `{0}' directly. Use `dynamic' keyword instead", GetSignatureForError ());
}
/// <summary>
/// This is rather hack. We report many emit attribute error with same error to be compatible with
/// csc. But because csc has to report them this way because error came from ilasm we needn't.
/// </summary>
public void Error_AttributeEmitError (string inner)
void Error_AttributeEmitError (string inner)
{
Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
Type.GetSignatureForError (), inner);
}
public void Error_InvalidArgumentValue (TypeSpec attributeType)
{
Report.Error (591, Location, "Invalid value for argument to `{0}' attribute", attributeType.GetSignatureForError ());
}
public void Error_InvalidSecurityParent ()
{
Error_AttributeEmitError ("it is attached to invalid parent");
Report.Error (7070, Location,
"Security attribute `{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations",
Type.GetSignatureForError ());
}
Attributable Owner {
@ -411,7 +414,7 @@ namespace Mono.CSharp { @@ -411,7 +414,7 @@ namespace Mono.CSharp {
return ((MethodImplOptions) value | all) == all;
}
static bool IsValidArgumentType (TypeSpec t)
public static bool IsValidArgumentType (TypeSpec t)
{
if (t.IsArray) {
var ac = (ArrayContainer) t;
@ -836,6 +839,7 @@ namespace Mono.CSharp { @@ -836,6 +839,7 @@ namespace Mono.CSharp {
{
SecurityAction action = GetSecurityActionValue ();
bool for_assembly = Target == AttributeTargets.Assembly || Target == AttributeTargets.Module;
var c = (Constant)pos_args [0].Expr;
switch (action) {
#pragma warning disable 618
@ -858,11 +862,22 @@ namespace Mono.CSharp { @@ -858,11 +862,22 @@ namespace Mono.CSharp {
#pragma warning restore 618
default:
Error_AttributeEmitError ("SecurityAction is out of range");
Report.Error (7049, c.Location, "Security attribute `{0}' has an invalid SecurityAction value `{1}'",
Type.GetSignatureForError (), c.GetValueAsLiteral());
return false;
}
Error_AttributeEmitError (String.Concat ("SecurityAction `", action, "' is not valid for this declaration"));
switch (Target) {
case AttributeTargets.Assembly:
Report.Error (7050, c.Location, "SecurityAction value `{0}' is invalid for security attributes applied to an assembly",
c.GetSignatureForError ());
break;
default:
Report.Error (7051, c.Location, "SecurityAction value `{0}' is invalid for security attributes applied to a type or a method",
c.GetSignatureForError ());
break;
}
return false;
}
@ -1031,44 +1046,42 @@ namespace Mono.CSharp { @@ -1031,44 +1046,42 @@ namespace Mono.CSharp {
return;
}
} else if (Type == predefined.Guid) {
string v = ((StringConstant) arg_expr).Value;
try {
string v = ((StringConstant) arg_expr).Value;
new Guid (v);
} catch (Exception e) {
Error_AttributeEmitError (e.Message);
} catch {
Error_InvalidArgumentValue (Type);
return;
}
} else if (Type == predefined.AttributeUsage) {
int v = ((IntConstant) ((EnumConstant) arg_expr).Child).Value;
if (v == 0) {
context.Module.Compiler.Report.Error (591, Location, "Invalid value for argument to `{0}' attribute",
"System.AttributeUsage");
}
if (v == 0)
Error_InvalidArgumentValue (Type);
} else if (Type == predefined.MarshalAs) {
if (pos_args.Count == 1) {
var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
Report.Error (7055, pos_args [0].Expr.Location, "Unmanaged type `ByValArray' is only valid for fields");
}
}
} else if (Type == predefined.DllImport) {
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 or null");
Error_InvalidArgumentValue (Type);
}
} else if (Type == predefined.MethodImpl) {
if (pos_args.Count == 1) {
var value = (int) ((Constant) arg_expr).GetValueAsLong ();
if (!IsValidMethodImplOption (value)) {
Error_AttributeEmitError ("Incorrect argument value");
Error_InvalidArgumentValue (Type);
}
}
}
}
arg_expr.EncodeAttributeValue (context, encoder, pt);
arg_expr.EncodeAttributeValue (context, encoder, pt, pt);
}
}
@ -1082,7 +1095,7 @@ namespace Mono.CSharp { @@ -1082,7 +1095,7 @@ namespace Mono.CSharp {
encoder.Encode (na.Key.Type);
encoder.Encode (na.Value.Name);
na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type);
na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type, na.Key.Type);
}
} else {
encoder.EncodeEmptyNamedArguments ();
@ -1546,7 +1559,7 @@ namespace Mono.CSharp { @@ -1546,7 +1559,7 @@ namespace Mono.CSharp {
Encode ((byte) 0x54); // property
Encode (property.MemberType);
Encode (property.Name);
value.EncodeAttributeValue (null, this, property.MemberType);
value.EncodeAttributeValue (null, this, property.MemberType, property.MemberType);
}
//
@ -1558,7 +1571,7 @@ namespace Mono.CSharp { @@ -1558,7 +1571,7 @@ namespace Mono.CSharp {
Encode ((byte) 0x53); // field
Encode (field.MemberType);
Encode (field.Name);
value.EncodeAttributeValue (null, this, field.MemberType);
value.EncodeAttributeValue (null, this, field.MemberType, field.MemberType);
}
public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
@ -1578,7 +1591,7 @@ namespace Mono.CSharp { @@ -1578,7 +1591,7 @@ namespace Mono.CSharp {
Encode (member.MemberType);
Encode (member.Name);
values [i].EncodeAttributeValue (null, this, member.MemberType);
values [i].EncodeAttributeValue (null, this, member.MemberType, member.MemberType);
}
}

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

@ -367,8 +367,8 @@ namespace Mono.CSharp { @@ -367,8 +367,8 @@ namespace Mono.CSharp {
return null;
result = result.Reduce (ec, lt);
if (result == null)
return null;
if (result == null || lt.IsEnum)
return result;
return new EnumConstant (result, lt);
}

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

@ -424,7 +424,7 @@ namespace Mono.CSharp @@ -424,7 +424,7 @@ namespace Mono.CSharp
}
public TypeSpec CurrentType {
get { return tc.Parent.CurrentType; }
get { return tc.PartialContainer.CurrentType; }
}
public TypeParameters CurrentTypeParameters {
@ -736,6 +736,8 @@ namespace Mono.CSharp @@ -736,6 +736,8 @@ namespace Mono.CSharp
}
}
public ParametersCompiled PrimaryConstructorParameters { get; set; }
public TypeParameters TypeParametersAll {
get {
return all_type_parameters;
@ -833,6 +835,9 @@ namespace Mono.CSharp @@ -833,6 +835,9 @@ namespace Mono.CSharp
if (symbol is TypeParameter) {
Report.Error (692, symbol.Location,
"Duplicate type parameter `{0}'", symbol.GetSignatureForError ());
} else if (symbol is PrimaryConstructorField && mc is TypeParameter) {
Report.Error (9003, symbol.Location, "Primary constructor of type `{0}' has parameter of same name as type parameter `{1}'",
symbol.Parent.GetSignatureForError (), symbol.GetSignatureForError ());
} else {
Report.Error (102, symbol.Location,
"The type `{0}' already contains a definition for `{1}'",
@ -1033,9 +1038,20 @@ namespace Mono.CSharp @@ -1033,9 +1038,20 @@ namespace Mono.CSharp
for (int i = 0; i < initialized_fields.Count; ++i) {
FieldInitializer fi = initialized_fields [i];
//
// Clone before resolving otherwise when field initializer is needed
// in more than 1 constructor any resolve after the initial one would
// only took the resolved expression which is problem for expressions
// that generate extra expressions or code during Resolve phase
//
var cloned = fi.Clone (new CloneContext ());
ExpressionStatement s = fi.ResolveStatement (ec);
if (s == null)
if (s == null) {
initialized_fields [i] = new FieldInitializer (fi.Field, ErrorExpression.Instance, Location.Null);
continue;
}
//
// Field is re-initialized to its default value => removed
@ -1045,6 +1061,7 @@ namespace Mono.CSharp @@ -1045,6 +1061,7 @@ namespace Mono.CSharp
ec.AssignmentInfoOffset += fi.AssignmentOffset;
ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
initialized_fields [i] = (FieldInitializer) cloned;
}
}
@ -1530,6 +1547,14 @@ namespace Mono.CSharp @@ -1530,6 +1547,14 @@ namespace Mono.CSharp
PartialContainer.containers.AddRange (containers);
}
if (PrimaryConstructorParameters != null) {
if (PartialContainer.PrimaryConstructorParameters != null) {
Report.Error (9001, Location, "Only one part of a partial type can declare primary constructor parameters");
} else {
PartialContainer.PrimaryConstructorParameters = PrimaryConstructorParameters;
}
}
members_defined = members_defined_ok = true;
caching_flags |= Flags.CloseTypeCreated;
} else {
@ -1682,6 +1707,10 @@ namespace Mono.CSharp @@ -1682,6 +1707,10 @@ namespace Mono.CSharp
return;
foreach (var member in members) {
var pbm = member as PropertyBasedMember;
if (pbm != null)
pbm.PrepareEmit ();
var pm = member as IParametersMember;
if (pm != null) {
var mc = member as MethodOrOperator;
@ -1694,6 +1723,7 @@ namespace Mono.CSharp @@ -1694,6 +1723,7 @@ namespace Mono.CSharp
continue;
((ParametersCompiled) p).ResolveDefaultValues (member);
continue;
}
var c = member as Const;
@ -2033,10 +2063,10 @@ namespace Mono.CSharp @@ -2033,10 +2063,10 @@ namespace Mono.CSharp
foreach (var member in members) {
if (member is Event) {
//
// An event can be assigned from same class only, so we can report
// An event can be assigned from same class only, report
// this warning for all accessibility modes
//
if (!member.IsUsed)
if (!member.IsUsed && !PartialContainer.HasStructLayout)
Report.Warning (67, 3, member.Location, "The event `{0}' is never used", member.GetSignatureForError ());
continue;
@ -2054,12 +2084,15 @@ namespace Mono.CSharp @@ -2054,12 +2084,15 @@ namespace Mono.CSharp
continue;
if (!member.IsUsed) {
if ((member.caching_flags & Flags.IsAssigned) == 0) {
Report.Warning (169, 3, member.Location, "The private field `{0}' is never used", member.GetSignatureForError ());
} else {
Report.Warning (414, 3, member.Location, "The private field `{0}' is assigned but its value is never used",
member.GetSignatureForError ());
if (!PartialContainer.HasStructLayout) {
if ((member.caching_flags & Flags.IsAssigned) == 0) {
Report.Warning (169, 3, member.Location, "The private field `{0}' is never used", member.GetSignatureForError ());
} else {
Report.Warning (414, 3, member.Location, "The private field `{0}' is assigned but its value is never used",
member.GetSignatureForError ());
}
}
continue;
}
@ -2522,12 +2555,15 @@ namespace Mono.CSharp @@ -2522,12 +2555,15 @@ namespace Mono.CSharp
public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
SecurityType declarative_security;
protected Constructor generated_primary_constructor;
protected ClassOrStruct (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind)
: base (parent, name, attrs, kind)
{
}
public Arguments PrimaryConstructorBaseArguments { get; set; }
protected override TypeAttributes TypeAttr {
get {
TypeAttributes ta = base.TypeAttr;
@ -2555,6 +2591,12 @@ namespace Mono.CSharp @@ -2555,6 +2591,12 @@ namespace Mono.CSharp
symbol.GetSignatureForError ());
return;
}
if (symbol is PrimaryConstructorField) {
Report.Error (9004, symbol.Location, "Primary constructor of type `{0}' has parameter of same name as containing type",
symbol.Parent.GetSignatureForError ());
return;
}
InterfaceMemberBase imb = symbol as InterfaceMemberBase;
if (imb == null || !imb.IsExplicitImpl) {
@ -2605,11 +2647,15 @@ namespace Mono.CSharp @@ -2605,11 +2647,15 @@ namespace Mono.CSharp
mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
}
var c = new Constructor (this, MemberName.Name, mods, null, ParametersCompiled.EmptyReadOnlyParameters, Location);
c.Initializer = new GeneratedBaseInitializer (Location);
var c = new Constructor (this, MemberName.Name, mods, null, PrimaryConstructorParameters ?? ParametersCompiled.EmptyReadOnlyParameters, Location);
if (Kind == MemberKind.Class)
c.Initializer = new GeneratedBaseInitializer (Location, PrimaryConstructorBaseArguments);
if (PrimaryConstructorParameters != null)
c.IsPrimaryConstructor = true;
AddConstructor (c, true);
c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location) {
c.Block = new ToplevelBlock (Compiler, c.ParameterInfo, Location) {
IsCompilerGenerated = true
};
@ -2620,6 +2666,19 @@ namespace Mono.CSharp @@ -2620,6 +2666,19 @@ namespace Mono.CSharp
{
CheckProtectedModifier ();
if (PrimaryConstructorParameters != null) {
foreach (Parameter p in PrimaryConstructorParameters.FixedParameters) {
if ((p.ModFlags & Parameter.Modifier.RefOutMask) != 0)
continue;
var f = new PrimaryConstructorField (this, p);
AddField (f);
generated_primary_constructor.Block.AddStatement (
new StatementExpression (new PrimaryConstructorAssign (f, p), p.Location));
}
}
base.DoDefineMembers ();
return true;
@ -2659,7 +2718,7 @@ namespace Mono.CSharp @@ -2659,7 +2718,7 @@ namespace Mono.CSharp
Modifiers.SEALED |
Modifiers.STATIC |
Modifiers.UNSAFE;
public Class (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs)
: base (parent, name, attrs, MemberKind.Class)
{
@ -2729,6 +2788,11 @@ namespace Mono.CSharp @@ -2729,6 +2788,11 @@ namespace Mono.CSharp
}
if (IsStatic) {
if (PrimaryConstructorParameters != null) {
Report.Error (-800, Location, "`{0}': Static classes cannot have primary constructor", GetSignatureForError ());
PrimaryConstructorParameters = null;
}
foreach (var m in Members) {
if (m is Operator) {
Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
@ -2756,8 +2820,8 @@ namespace Mono.CSharp @@ -2756,8 +2820,8 @@ namespace Mono.CSharp
Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
}
} else {
if (!PartialContainer.HasInstanceConstructor)
DefineDefaultConstructor (false);
if (!PartialContainer.HasInstanceConstructor || PrimaryConstructorParameters != null)
generated_primary_constructor = DefineDefaultConstructor (false);
}
return base.DoDefineMembers ();
@ -2979,6 +3043,14 @@ namespace Mono.CSharp @@ -2979,6 +3043,14 @@ namespace Mono.CSharp
return fts.CheckStructCycles ();
}
protected override bool DoDefineMembers ()
{
if (PrimaryConstructorParameters != null)
generated_primary_constructor = DefineDefaultConstructor (false);
return base.DoDefineMembers ();
}
public override void Emit ()
{
CheckStructCycles ();
@ -3687,25 +3759,29 @@ namespace Mono.CSharp @@ -3687,25 +3759,29 @@ namespace Mono.CSharp
Report.SymbolRelatedToPreviousError (MemberType);
if (this is Property)
Report.Error (53, Location,
"Inconsistent accessibility: property type `" +
MemberType.GetSignatureForError () + "' is less " +
"accessible than property `" + GetSignatureForError () + "'");
"Inconsistent accessibility: property type `" +
MemberType.GetSignatureForError () + "' is less " +
"accessible than property `" + GetSignatureForError () + "'");
else if (this is Indexer)
Report.Error (54, Location,
"Inconsistent accessibility: indexer return type `" +
MemberType.GetSignatureForError () + "' is less " +
"accessible than indexer `" + GetSignatureForError () + "'");
"Inconsistent accessibility: indexer return type `" +
MemberType.GetSignatureForError () + "' is less " +
"accessible than indexer `" + GetSignatureForError () + "'");
else if (this is MethodCore) {
if (this is Operator)
Report.Error (56, Location,
"Inconsistent accessibility: return type `" +
MemberType.GetSignatureForError () + "' is less " +
"accessible than operator `" + GetSignatureForError () + "'");
"Inconsistent accessibility: return type `" +
MemberType.GetSignatureForError () + "' is less " +
"accessible than operator `" + GetSignatureForError () + "'");
else
Report.Error (50, Location,
"Inconsistent accessibility: return type `" +
MemberType.GetSignatureForError () + "' is less " +
"accessible than method `" + GetSignatureForError () + "'");
"Inconsistent accessibility: return type `" +
MemberType.GetSignatureForError () + "' is less " +
"accessible than method `" + GetSignatureForError () + "'");
} else if (this is Event) {
Report.Error (7025, Location,
"Inconsistent accessibility: event type `{0}' is less accessible than event `{1}'",
MemberType.GetSignatureForError (), GetSignatureForError ());
} else {
Report.Error (52, Location,
"Inconsistent accessibility: field type `" +

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

@ -175,6 +175,12 @@ namespace Mono.CSharp @@ -175,6 +175,12 @@ namespace Mono.CSharp
}
}
public bool NotifyEvaluatorOnStore {
get {
return Module.Evaluator != null && Module.Evaluator.ModificationListener != null;
}
}
// Has to be used for specific emitter errors only any
// possible resolver errors have to be reported during Resolve
public Report Report {
@ -204,6 +210,10 @@ namespace Mono.CSharp @@ -204,6 +210,10 @@ namespace Mono.CSharp
}
}
public LocalVariable AsyncThrowVariable { get; set; }
public List<TryFinally> TryFinallyUnwind { get; set; }
#endregion
public void AddStatementEpilog (IExpressionCleanup cleanupExpression)
@ -279,11 +289,21 @@ namespace Mono.CSharp @@ -279,11 +289,21 @@ namespace Mono.CSharp
ig.BeginCatchBlock (type.GetMetaInfo ());
}
public void BeginFilterHandler ()
{
ig.BeginCatchBlock (null);
}
public void BeginExceptionBlock ()
{
ig.BeginExceptionBlock ();
}
public void BeginExceptionFilterBlock ()
{
ig.BeginExceptFilterBlock ();
}
public void BeginFinallyBlock ()
{
ig.BeginFinallyBlock ();
@ -370,9 +390,9 @@ namespace Mono.CSharp @@ -370,9 +390,9 @@ namespace Mono.CSharp
//
// Creates temporary field in current async storey
//
public StackFieldExpr GetTemporaryField (TypeSpec type)
public StackFieldExpr GetTemporaryField (TypeSpec type, bool initializedFieldRequired = false)
{
var f = AsyncTaskStorey.AddCapturedLocalVariable (type);
var f = AsyncTaskStorey.AddCapturedLocalVariable (type, initializedFieldRequired);
var fexpr = new StackFieldExpr (f);
fexpr.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location.Null);
return fexpr;
@ -508,8 +528,16 @@ namespace Mono.CSharp @@ -508,8 +528,16 @@ namespace Mono.CSharp
type = EnumSpec.GetUnderlyingType (type);
switch (type.BuiltinType) {
case BuiltinTypeSpec.Type.Byte:
case BuiltinTypeSpec.Type.Bool:
//
// Workaround MSIL limitation. Load bool element as single bit,
// bool array can actually store any byte value
//
ig.Emit (OpCodes.Ldelem_U1);
ig.Emit (OpCodes.Ldc_I4_1);
ig.Emit (OpCodes.And);
break;
case BuiltinTypeSpec.Type.Byte:
ig.Emit (OpCodes.Ldelem_U1);
break;
case BuiltinTypeSpec.Type.SByte:
@ -724,8 +752,12 @@ namespace Mono.CSharp @@ -724,8 +752,12 @@ namespace Mono.CSharp
ig.Emit (OpCodes.Ldind_U1);
break;
case BuiltinTypeSpec.Type.SByte:
ig.Emit (OpCodes.Ldind_I1);
break;
case BuiltinTypeSpec.Type.Bool:
ig.Emit (OpCodes.Ldind_I1);
ig.Emit (OpCodes.Ldc_I4_1);
ig.Emit (OpCodes.And);
break;
case BuiltinTypeSpec.Type.ULong:
case BuiltinTypeSpec.Type.Long:
@ -1026,7 +1058,7 @@ namespace Mono.CSharp @@ -1026,7 +1058,7 @@ namespace Mono.CSharp
}
}
if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStruct)) {
if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStructOrEnum)) {
ec.Emit (OpCodes.Constrained, InstanceExpression.Type);
}
@ -1066,7 +1098,7 @@ namespace Mono.CSharp @@ -1066,7 +1098,7 @@ namespace Mono.CSharp
//
// Push the instance expression
//
if ((instance_type.IsStruct && (callOpcode == OpCodes.Callvirt || (callOpcode == OpCodes.Call && declaringType.IsStruct))) ||
if ((instance_type.IsStructOrEnum && (callOpcode == OpCodes.Callvirt || (callOpcode == OpCodes.Call && declaringType.IsStruct))) ||
instance_type.IsGenericParameter || declaringType.IsNullableType) {
//
// If the expression implements IMemoryLocation, then
@ -1088,7 +1120,7 @@ namespace Mono.CSharp @@ -1088,7 +1120,7 @@ namespace Mono.CSharp
return ReferenceContainer.MakeType (ec.Module, instance_type);
}
if (instance_type.IsEnum || instance_type.IsStruct) {
if (instance_type.IsStructOrEnum) {
instance.Emit (ec);
ec.Emit (OpCodes.Box, instance_type);
return ec.BuiltinTypes.Object;

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

@ -210,5 +210,17 @@ namespace Mono.CSharp { @@ -210,5 +210,17 @@ namespace Mono.CSharp {
// Nothing
}
}
public class EmptyCompletion : CompletingExpression
{
protected override void CloneTo (CloneContext clonectx, Expression target)
{
}
protected override Expression DoResolve (ResolveContext rc)
{
throw new CompletionResult ("", new string [0]);
}
}
}

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

@ -528,7 +528,7 @@ namespace Mono.CSharp { @@ -528,7 +528,7 @@ namespace Mono.CSharp {
return Value ? 1 : 0;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode (Value);
}
@ -579,7 +579,7 @@ namespace Mono.CSharp { @@ -579,7 +579,7 @@ namespace Mono.CSharp {
Value = v;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode (Value);
}
@ -679,7 +679,7 @@ namespace Mono.CSharp { @@ -679,7 +679,7 @@ namespace Mono.CSharp {
Value = v;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode ((ushort) Value);
}
@ -807,7 +807,7 @@ namespace Mono.CSharp { @@ -807,7 +807,7 @@ namespace Mono.CSharp {
Value = v;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode (Value);
}
@ -910,7 +910,7 @@ namespace Mono.CSharp { @@ -910,7 +910,7 @@ namespace Mono.CSharp {
Value = v;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode (Value);
}
@ -1023,7 +1023,7 @@ namespace Mono.CSharp { @@ -1023,7 +1023,7 @@ namespace Mono.CSharp {
Value = v;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode (Value);
}
@ -1132,7 +1132,7 @@ namespace Mono.CSharp { @@ -1132,7 +1132,7 @@ namespace Mono.CSharp {
Value = v;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode (Value);
}
@ -1308,7 +1308,7 @@ namespace Mono.CSharp { @@ -1308,7 +1308,7 @@ namespace Mono.CSharp {
Value = v;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode (Value);
}
@ -1425,7 +1425,7 @@ namespace Mono.CSharp { @@ -1425,7 +1425,7 @@ namespace Mono.CSharp {
Value = v;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode (Value);
}
@ -1556,7 +1556,7 @@ namespace Mono.CSharp { @@ -1556,7 +1556,7 @@ namespace Mono.CSharp {
Value = v;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode (Value);
}
@ -1680,7 +1680,7 @@ namespace Mono.CSharp { @@ -1680,7 +1680,7 @@ namespace Mono.CSharp {
return base.ConvertImplicitly (type);
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode (Value);
}
@ -1809,7 +1809,7 @@ namespace Mono.CSharp { @@ -1809,7 +1809,7 @@ namespace Mono.CSharp {
Value = v;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
enc.Encode (Value);
}
@ -2094,7 +2094,7 @@ namespace Mono.CSharp { @@ -2094,7 +2094,7 @@ namespace Mono.CSharp {
ec.Emit (OpCodes.Ldstr, Value);
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
// cast to object
if (type != targetType)
@ -2159,7 +2159,7 @@ namespace Mono.CSharp { @@ -2159,7 +2159,7 @@ namespace Mono.CSharp {
return base.CreateExpressionTree (ec);
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
switch (targetType.BuiltinType) {
case BuiltinTypeSpec.Type.Object:
@ -2180,7 +2180,7 @@ namespace Mono.CSharp { @@ -2180,7 +2180,7 @@ namespace Mono.CSharp {
break;
}
base.EncodeAttributeValue (rc, enc, targetType);
base.EncodeAttributeValue (rc, enc, targetType, parameterType);
}
public override void Emit (EmitContext ec)
@ -2320,6 +2320,11 @@ namespace Mono.CSharp { @@ -2320,6 +2320,11 @@ namespace Mono.CSharp {
}
}
public override bool ContainsEmitWithAwait ()
{
return side_effect.ContainsEmitWithAwait ();
}
public override object GetValue ()
{
return value.GetValue ();
@ -2347,6 +2352,11 @@ namespace Mono.CSharp { @@ -2347,6 +2352,11 @@ namespace Mono.CSharp {
value.EmitSideEffect (ec);
}
public override void FlowAnalysis (FlowAnalysisContext fc)
{
side_effect.FlowAnalysis (fc);
}
public override bool IsDefaultValue {
get { return value.IsDefaultValue; }
}

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

@ -664,7 +664,7 @@ namespace Mono.CSharp @@ -664,7 +664,7 @@ namespace Mono.CSharp
ConstructorScope = 1 << 3,
AsyncBody = 1 << 4
AsyncBody = 1 << 4,
}
// utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements

89
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/convert.cs

@ -71,19 +71,14 @@ namespace Mono.CSharp { @@ -71,19 +71,14 @@ namespace Mono.CSharp {
// From T to a type parameter U, provided T depends on U
//
if (target_type.IsGenericParameter) {
if (expr_type.TypeArguments != null) {
foreach (var targ in expr_type.TypeArguments) {
if (!TypeSpecComparer.Override.IsEqual (target_type, targ))
continue;
if (expr == null)
return EmptyExpression.Null;
if (expr_type.TypeArguments != null && expr_type.HasDependencyOn (target_type)) {
if (expr == null)
return EmptyExpression.Null;
if (expr_type.IsReferenceType && !((TypeParameterSpec)target_type).IsReferenceType)
return new BoxedCast (expr, target_type);
if (expr_type.IsReferenceType && !((TypeParameterSpec) target_type).IsReferenceType)
return new BoxedCast (expr, target_type);
return new ClassCast (expr, target_type);
}
return new ClassCast (expr, target_type);
}
return null;
@ -131,38 +126,39 @@ namespace Mono.CSharp { @@ -131,38 +126,39 @@ namespace Mono.CSharp {
return null;
}
static Expression ExplicitTypeParameterConversion (Expression source, TypeSpec source_type, TypeSpec target_type)
static Expression ExplicitTypeParameterConversionFromT (Expression source, TypeSpec source_type, TypeSpec target_type)
{
var target_tp = target_type as TypeParameterSpec;
if (target_tp != null) {
if (target_tp.TypeArguments != null) {
foreach (var targ in target_tp.TypeArguments) {
if (!TypeSpecComparer.Override.IsEqual (source_type, targ))
continue;
return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
}
}
/*
if (target_tp.Interfaces != null) {
foreach (TypeSpec iface in target_tp.Interfaces) {
if (!TypeManager.IsGenericParameter (iface))
continue;
if (TypeManager.IsSubclassOf (source_type, iface))
return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
}
//
// From a type parameter U to T, provided T depends on U
//
if (target_tp.TypeArguments != null && target_tp.HasDependencyOn (source_type)) {
return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
}
*/
return null;
}
//
// From T to any interface-type I provided there is not already an implicit conversion from T to I
//
if (target_type.IsInterface)
return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
return null;
}
static Expression ExplicitTypeParameterConversionToT (Expression source, TypeSpec source_type, TypeParameterSpec target_type)
{
//
// From the effective base class C of T to T and from any base class of C to T
//
var effective = target_type.GetEffectiveBase ();
if (TypeSpecComparer.IsEqual (effective, source_type) || TypeSpec.IsBaseClass (effective, source_type, false))
return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
return null;
}
public static Expression ImplicitReferenceConversion (Expression expr, TypeSpec target_type, bool explicit_cast)
{
TypeSpec expr_type = expr.Type;
@ -1467,6 +1463,7 @@ namespace Mono.CSharp { @@ -1467,6 +1463,7 @@ namespace Mono.CSharp {
return e;
source.Error_ValueCannotBeConverted (ec, target_type, false);
return null;
}
@ -1820,10 +1817,10 @@ namespace Mono.CSharp { @@ -1820,10 +1817,10 @@ namespace Mono.CSharp {
return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
//
// Explicit type parameter conversion.
// Explicit type parameter conversion from T
//
if (source_type.Kind == MemberKind.TypeParameter)
return ExplicitTypeParameterConversion (source, source_type, target_type);
return ExplicitTypeParameterConversionFromT (source, source_type, target_type);
bool target_is_value_type = target_type.Kind == MemberKind.Struct || target_type.Kind == MemberKind.Enum;
@ -1857,6 +1854,9 @@ namespace Mono.CSharp { @@ -1857,6 +1854,9 @@ namespace Mono.CSharp {
// From any interface-type S to to any class type T, provided T is not
// sealed, or provided T implements S.
//
// This also covers Explicit conversions involving type parameters
// section From any interface type to T
//
if (source_type.Kind == MemberKind.Interface) {
if (!target_type.IsSealed || target_type.ImplementsInterface (source_type, true)) {
if (source == null)
@ -1901,10 +1901,23 @@ namespace Mono.CSharp { @@ -1901,10 +1901,23 @@ namespace Mono.CSharp {
if (source_array.Rank == target_array.Rank) {
source_type = source_array.Element;
if (!TypeSpec.IsReferenceType (source_type))
return null;
var target_element = target_array.Element;
//
// LAMESPEC: Type parameters are special cased somehow but
// only when both source and target elements are type parameters
//
if ((source_type.Kind & target_element.Kind & MemberKind.TypeParameter) == MemberKind.TypeParameter) {
//
// Conversion is allowed unless source element type has struct constrain
//
if (TypeSpec.IsValueType (source_type))
return null;
} else {
if (!TypeSpec.IsReferenceType (source_type))
return null;
}
if (!TypeSpec.IsReferenceType (target_element))
return null;
@ -1979,6 +1992,10 @@ namespace Mono.CSharp { @@ -1979,6 +1992,10 @@ namespace Mono.CSharp {
return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
}
var tps = target_type as TypeParameterSpec;
if (tps != null)
return ExplicitTypeParameterConversionToT (source, source_type, tps);
return null;
}

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

File diff suppressed because it is too large Load Diff

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

@ -35,7 +35,8 @@ namespace Mono.CSharp @@ -35,7 +35,8 @@ namespace Mono.CSharp
Arglist = 1 << 5,
DefaultValue = 1 << 6,
All = Ref | Out | This | Params | Arglist | DefaultValue
All = Ref | Out | This | Params | Arglist | DefaultValue,
PrimaryConstructor = Ref | Out | Params | DefaultValue
}
static readonly object ModifierNone = 0;
@ -926,10 +927,12 @@ class_member_declarations @@ -926,10 +927,12 @@ class_member_declarations
: class_member_declaration
{
lexer.parsing_modifiers = true;
lexer.parsing_block = 0;
}
| class_member_declarations class_member_declaration
{
lexer.parsing_modifiers = true;
lexer.parsing_block = 0;
}
;
@ -965,16 +968,22 @@ struct_declaration @@ -965,16 +968,22 @@ struct_declaration
type_declaration_name
{
lexer.ConstraintsParsing = true;
valid_param_mod = ParameterModifierType.PrimaryConstructor;
push_current_container (new Struct (current_container, (MemberName) $6, (Modifiers) $2, (Attributes) $1), $3);
lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($4));
}
opt_primary_parameters
opt_class_base
opt_type_parameter_constraints_clauses
{
valid_param_mod = 0;
lexer.ConstraintsParsing = false;
if ($9 != null)
current_container.SetConstraints ((List<Constraints>) $9);
if ($8 != null)
current_type.PrimaryConstructorParameters = (ParametersCompiled) $8;
if ($10 != null)
current_container.SetConstraints ((List<Constraints>) $10);
if (doc_support)
current_container.PartialContainer.DocComment = Lexer.consume_doc_comment ();
@ -996,9 +1005,9 @@ struct_declaration @@ -996,9 +1005,9 @@ struct_declaration
opt_semicolon
{
if ($16 == null) {
lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($14));
lbag.AppendToMember (current_container, GetLocation ($12), GetLocation ($15));
} else {
lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($14), GetLocation ($16));
lbag.AppendToMember (current_container, GetLocation ($12), GetLocation ($15), GetLocation ($17));
}
$$ = pop_current_class ();
}
@ -2016,10 +2025,12 @@ interface_member_declarations @@ -2016,10 +2025,12 @@ interface_member_declarations
: interface_member_declaration
{
lexer.parsing_modifiers = true;
lexer.parsing_block = 0;
}
| interface_member_declarations interface_member_declaration
{
lexer.parsing_modifiers = true;
lexer.parsing_block = 0;
}
;
@ -3268,6 +3279,12 @@ member_access @@ -3268,6 +3279,12 @@ member_access
$$ = new MemberAccess (new BaseThis (GetLocation ($1)), lt.Value, (TypeArguments) $4, lt.Location);
lbag.AddLocation ($$, GetLocation ($2));
}
| AWAIT DOT identifier_inside_body opt_type_argument_list
{
var lt = (LocatedToken) $3;
$$ = new MemberAccess (new SimpleName ("await", ((LocatedToken) $1).Location), lt.Value, (TypeArguments) $4, lt.Location);
lbag.AddLocation ($$, GetLocation ($2));
}
| qualified_alias_member identifier_inside_body opt_type_argument_list
{
var lt1 = (LocatedToken) $1;
@ -3680,6 +3697,10 @@ anonymous_type_expression @@ -3680,6 +3697,10 @@ anonymous_type_expression
// TODO: lbag comma location
lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
}
| NEW OPEN_BRACE GENERATE_COMPLETION
{
$$ = new EmptyCompletion ();
}
;
anonymous_type_parameters_opt_comma
@ -3707,6 +3728,14 @@ anonymous_type_parameters @@ -3707,6 +3728,14 @@ anonymous_type_parameters
$$ = a;
}
| COMPLETE_COMPLETION
{
$$ = new EmptyCompletion ();
}
| anonymous_type_parameter COMPLETE_COMPLETION
{
$$ = $1;
}
;
anonymous_type_parameter
@ -4245,6 +4274,16 @@ additive_expression @@ -4245,6 +4274,16 @@ additive_expression
$$ = new Is ((Expression) $1, null, GetLocation ($2));
}
| AWAIT IS type
{
var lt = (LocatedToken) $1;
$$ = new Is (new SimpleName (lt.Value, lt.Location), (Expression) $3, GetLocation ($2));
}
| AWAIT AS type
{
var lt = (LocatedToken) $1;
$$ = new As (new SimpleName (lt.Value, lt.Location), (Expression) $3, GetLocation ($2));
}
;
shift_expression
@ -4733,6 +4772,51 @@ boolean_expression @@ -4733,6 +4772,51 @@ boolean_expression
}
;
opt_primary_parameters
: /* empty */
{
$$ = null;
}
| primary_parameters
;
primary_parameters
: OPEN_PARENS opt_formal_parameter_list CLOSE_PARENS
{
$$ = $2;
// Cannot use opt_formal_parameter_list because it can be shared instance for empty parameters
lbag.AppendToMember (current_container, GetLocation ($1), GetLocation ($3));
}
;
opt_primary_parameters_with_class_base
: /* empty */
{
$$ = null;
}
| class_base
{
$$ = null;
}
| primary_parameters
{
$$ = $1;
}
| primary_parameters class_base OPEN_PARENS
{
++lexer.parsing_block;
}
opt_argument_list CLOSE_PARENS
{
lbag.AppendToMember (current_container, GetLocation ($3), GetLocation ($6));
((Class)current_type).PrimaryConstructorBaseArguments = (Arguments) $5;
--lexer.parsing_block;
$$ = $1;
}
;
//
// 10 classes
//
@ -4754,12 +4838,17 @@ class_declaration @@ -4754,12 +4838,17 @@ class_declaration
push_current_container (c, $3);
lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($4));
valid_param_mod = ParameterModifierType.PrimaryConstructor;
}
opt_class_base
opt_primary_parameters_with_class_base
opt_type_parameter_constraints_clauses
{
valid_param_mod = 0;
lexer.ConstraintsParsing = false;
if ($8 != null)
current_type.PrimaryConstructorParameters = (ParametersCompiled) $8;
if ($9 != null)
current_container.SetConstraints ((List<Constraints>) $9);
@ -4912,7 +5001,11 @@ modifier @@ -4912,7 +5001,11 @@ modifier
opt_class_base
: /* empty */
| COLON type_list
| class_base
;
class_base
: COLON type_list
{
current_type.SetBaseTypes ((List<FullNamedExpression>) $2);
lbag.AppendToMember (current_type, GetLocation ($1));
@ -6108,7 +6201,8 @@ catch_clauses @@ -6108,7 +6201,8 @@ catch_clauses
var l = (List<Catch>) $1;
Catch c = (Catch) $2;
if (l [l.Count - 1].IsGeneral) {
var prev_catch = l [l.Count - 1];
if (prev_catch.IsGeneral && prev_catch.Filter == null) {
report.Error (1017, c.loc, "Try statement already has an empty catch block");
}
@ -6123,9 +6217,11 @@ opt_identifier @@ -6123,9 +6217,11 @@ opt_identifier
;
catch_clause
: CATCH block
: CATCH opt_catch_filter block
{
$$ = new Catch ((ExplicitBlock) $2, GetLocation ($1));
var c = new Catch ((ExplicitBlock) $3, GetLocation ($1));
c.Filter = (CatchFilterExpression) $2;
$$ = c;
}
| CATCH open_parens_any type opt_identifier CLOSE_PARENS
{
@ -6142,8 +6238,9 @@ catch_clause @@ -6142,8 +6238,9 @@ catch_clause
lbag.AddLocation (c, GetLocation ($2), GetLocation ($5));
$$ = c;
}
block_prepared_strict
opt_catch_filter block_prepared
{
((Catch) $6).Filter = (CatchFilterExpression) $7;
$$ = $6;
}
| CATCH open_parens_any error
@ -6182,6 +6279,18 @@ catch_clause @@ -6182,6 +6279,18 @@ catch_clause
}
;
opt_catch_filter
: /* empty */
| IF open_parens_any expression CLOSE_PARENS
{
if (lang_version <= LanguageVersion.V_5)
FeatureIsNotAvailable (GetLocation ($1), "exception filter");
$$ = new CatchFilterExpression ((Expression) $3, GetLocation ($1));
lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
}
;
checked_statement
: CHECKED block
{
@ -6936,6 +7045,12 @@ doc_cref @@ -6936,6 +7045,12 @@ doc_cref
module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)$2;
$$ = null;
}
| VOID opt_doc_method_sig
{
module.DocumentationBuilder.ParsedBuiltinType = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation ($1));
module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)$2;
$$ = null;
}
| builtin_types DOT IDENTIFIER opt_doc_method_sig
{
module.DocumentationBuilder.ParsedBuiltinType = (TypeExpression)$1;
@ -6974,7 +7089,7 @@ doc_cref @@ -6974,7 +7089,7 @@ doc_cref
}
| OPERATOR overloadable_operator opt_doc_method_sig
{
var p = (List<DocumentationParameter>)$3 ?? new List<DocumentationParameter> (1);
var p = (List<DocumentationParameter>)$3;
module.DocumentationBuilder.ParsedParameters = p;
module.DocumentationBuilder.ParsedOperator = (Operator.OpType) $2;
$$ = null;

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

@ -947,7 +947,27 @@ namespace Mono.CSharp @@ -947,7 +947,27 @@ namespace Mono.CSharp
if (c < 0x80)
return false;
return Char.IsLetter (c) || Char.GetUnicodeCategory (c) == UnicodeCategory.ConnectorPunctuation;
return is_identifier_part_character_slow_part (c);
}
static bool is_identifier_part_character_slow_part (char c)
{
if (Char.IsLetter (c))
return true;
switch (Char.GetUnicodeCategory (c)) {
case UnicodeCategory.ConnectorPunctuation:
// combining-character: A Unicode character of classes Mn or Mc
case UnicodeCategory.NonSpacingMark:
case UnicodeCategory.SpacingCombiningMark:
// decimal-digit-character: A Unicode character of the class Nd
case UnicodeCategory.DecimalDigitNumber:
return true;
}
return false;
}
public static bool IsKeyword (string s)
@ -1250,7 +1270,7 @@ namespace Mono.CSharp @@ -1250,7 +1270,7 @@ namespace Mono.CSharp
// Tonizes `?' using custom disambiguous rules to return one
// of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
//
// Tricky expression look like:
// Tricky expression looks like:
//
// Foo ? a = x ? b : c;
//
@ -1329,18 +1349,27 @@ namespace Mono.CSharp @@ -1329,18 +1349,27 @@ namespace Mono.CSharp
int interrs = 1;
int colons = 0;
int braces = 0;
int parens = 0;
//
// All shorcuts failed, do it hard way
//
while ((ntoken = xtoken ()) != Token.EOF) {
if (ntoken == Token.OPEN_BRACE) {
switch (ntoken) {
case Token.OPEN_BRACE:
++braces;
continue;
}
if (ntoken == Token.CLOSE_BRACE) {
case Token.OPEN_PARENS:
case Token.OPEN_PARENS_CAST:
case Token.OPEN_PARENS_LAMBDA:
++parens;
continue;
case Token.CLOSE_BRACE:
--braces;
continue;
case Token.CLOSE_PARENS:
if (parens > 0)
--parens;
continue;
}
if (braces != 0)
@ -1348,6 +1377,9 @@ namespace Mono.CSharp @@ -1348,6 +1377,9 @@ namespace Mono.CSharp
if (ntoken == Token.SEMICOLON)
break;
if (parens != 0)
continue;
if (ntoken == Token.COLON) {
if (++colons == interrs)
@ -3130,7 +3162,7 @@ namespace Mono.CSharp @@ -3130,7 +3162,7 @@ namespace Mono.CSharp
continue;
}
} else if (Char.IsLetter ((char) c) || Char.GetUnicodeCategory ((char) c) == UnicodeCategory.ConnectorPunctuation) {
} else if (is_identifier_part_character_slow_part ((char) c)) {
id_builder [pos++] = (char) c;
continue;
}

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

@ -446,7 +446,8 @@ namespace Mono.CSharp { @@ -446,7 +446,8 @@ namespace Mono.CSharp {
public override bool ContainsEmitWithAwait ()
{
return false;
var instance = method_group.InstanceExpression;
return instance != null && instance.ContainsEmitWithAwait ();
}
public static Arguments CreateDelegateMethodArguments (ResolveContext rc, AParametersCollection pd, TypeSpec[] types, Location loc)
@ -581,6 +582,11 @@ namespace Mono.CSharp { @@ -581,6 +582,11 @@ namespace Mono.CSharp {
ec.Emit (OpCodes.Newobj, constructor_method);
}
public override void FlowAnalysis (FlowAnalysisContext fc) {
base.FlowAnalysis (fc);
method_group.FlowAnalysis (fc);
}
void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
{
var invoke_method = Delegate.GetInvokeMethod (type);

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

@ -303,7 +303,7 @@ namespace Mono.CSharp @@ -303,7 +303,7 @@ namespace Mono.CSharp
TypeExpr texpr = left as TypeExpr;
if (texpr != null) {
var found = MemberCache.FindNestedType (texpr.Type, ParsedName.Name, ParsedName.Arity);
var found = MemberCache.FindNestedType (texpr.Type, mn.Name, mn.Arity);
if (found != null)
return new TypeExpression (found, Location.Null);

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

@ -540,10 +540,16 @@ namespace Mono.CSharp { @@ -540,10 +540,16 @@ namespace Mono.CSharp {
return c;
}
public virtual void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public virtual void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
rc.Module.Compiler.Report.Error (182, loc,
"An attribute argument must be a constant expression, typeof expression or array creation expression");
if (Attribute.IsValidArgumentType (parameterType)) {
rc.Module.Compiler.Report.Error (182, loc,
"An attribute argument must be a constant expression, typeof expression or array creation expression");
} else {
rc.Module.Compiler.Report.Error (181, loc,
"Attribute constructor parameter has type `{0}', which is not a valid attribute parameter type",
targetType.GetSignatureForError ());
}
}
/// <summary>
@ -1582,9 +1588,9 @@ namespace Mono.CSharp { @@ -1582,9 +1588,9 @@ namespace Mono.CSharp {
Child.Emit (ec);
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
Child.EncodeAttributeValue (rc, enc, Child.Type);
Child.EncodeAttributeValue (rc, enc, Child.Type, parameterType);
}
public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
@ -1702,16 +1708,16 @@ namespace Mono.CSharp { @@ -1702,16 +1708,16 @@ namespace Mono.CSharp {
return this;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
// Only boxing to object type is supported
if (targetType.BuiltinType != BuiltinTypeSpec.Type.Object) {
base.EncodeAttributeValue (rc, enc, targetType);
base.EncodeAttributeValue (rc, enc, targetType, parameterType);
return;
}
enc.Encode (child.Type);
child.EncodeAttributeValue (rc, enc, child.Type);
child.EncodeAttributeValue (rc, enc, child.Type, parameterType);
}
public override void Emit (EmitContext ec)
@ -2113,15 +2119,15 @@ namespace Mono.CSharp { @@ -2113,15 +2119,15 @@ namespace Mono.CSharp {
return c;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
//
// LAMESPEC: Reduced conditional expression is allowed as an attribute argument
//
if (orig_expr is Conditional)
child.EncodeAttributeValue (rc, enc, targetType);
child.EncodeAttributeValue (rc, enc, targetType,parameterType);
else
base.EncodeAttributeValue (rc, enc, targetType);
base.EncodeAttributeValue (rc, enc, targetType, parameterType);
}
}
@ -2780,6 +2786,17 @@ namespace Mono.CSharp { @@ -2780,6 +2786,17 @@ namespace Mono.CSharp {
ct = ct.DeclaringType;
} while (ct != null);
} else {
var cos = rc.CurrentMemberDefinition.Parent as ClassOrStruct;
if (cos != null && cos.PrimaryConstructorParameters != null) {
foreach (var p in cos.PrimaryConstructorParameters.FixedParameters) {
if (p.Name == Name) {
rc.Report.Error (9007, loc, "Primary constructor parameter `{0}' is not available in this context when using ref or out modifier",
Name);
return null;
}
}
}
}
if ((restrictions & MemberLookupRestrictions.InvocableOnly) == 0) {
@ -3421,14 +3438,25 @@ namespace Mono.CSharp { @@ -3421,14 +3438,25 @@ namespace Mono.CSharp {
if (InstanceExpression == null || InstanceExpression is TypeExpr) {
if (InstanceExpression != null || !This.IsThisAvailable (rc, true)) {
if (rc.HasSet (ResolveContext.Options.FieldInitializerScope))
if (rc.HasSet (ResolveContext.Options.FieldInitializerScope)) {
rc.Report.Error (236, loc,
"A field initializer cannot reference the nonstatic field, method, or property `{0}'",
GetSignatureForError ());
else
rc.Report.Error (120, loc,
"An object reference is required to access non-static member `{0}'",
GetSignatureForError ());
} else {
var fe = this as FieldExpr;
if (fe != null && fe.Spec.MemberDefinition is PrimaryConstructorField) {
if (rc.HasSet (ResolveContext.Options.BaseInitializer)) {
rc.Report.Error (9005, loc, "Constructor initializer cannot access primary constructor parameters");
} else {
rc.Report.Error (9006, loc, "An object reference is required to access primary constructor parameter `{0}'",
fe.Name);
}
} else {
rc.Report.Error (120, loc,
"An object reference is required to access non-static member `{0}'",
GetSignatureForError ());
}
}
InstanceExpression = new CompilerGeneratedThis (rc.CurrentType, loc).Resolve (rc);
return false;
@ -4460,7 +4488,7 @@ namespace Mono.CSharp { @@ -4460,7 +4488,7 @@ namespace Mono.CSharp {
//
// We have not reached end of parameters list due to params or used default parameters
//
if (j < candidate_pd.Count && j < best_pd.Count) {
while (j < candidate_pd.Count && j < best_pd.Count) {
var cand_param = candidate_pd.FixedParameters [j];
var best_param = best_pd.FixedParameters [j];
@ -4468,11 +4496,16 @@ namespace Mono.CSharp { @@ -4468,11 +4496,16 @@ namespace Mono.CSharp {
//
// LAMESPEC:
//
// void Foo (params int[]) is better than void Foo (int i = 0) for Foo ()
// void Foo (string[] s, string value = null) is better than Foo (string s, params string[]) for Foo (null)
// void Foo (int i = 0) is better than void Foo (params int[]) for Foo ()
// void Foo (string[] s, string value = null) is better than Foo (string s, params string[]) for Foo (null) or Foo ()
//
if (cand_param.HasDefaultValue != best_param.HasDefaultValue)
return !candidate_params;
return cand_param.HasDefaultValue;
if (cand_param.HasDefaultValue) {
++j;
continue;
}
} else {
//
// Neither is better when not all arguments are provided
@ -4484,6 +4517,8 @@ namespace Mono.CSharp { @@ -4484,6 +4517,8 @@ namespace Mono.CSharp {
if (cand_param.HasDefaultValue && best_param.HasDefaultValue)
return false;
}
break;
}
if (candidate_pd.Count != best_pd.Count)
@ -4668,7 +4703,10 @@ namespace Mono.CSharp { @@ -4668,7 +4703,10 @@ namespace Mono.CSharp {
++arg_count;
temp = null;
} else {
temp = arguments[index];
if (index == arg_count)
return (i + 1) * 3;
temp = arguments [index];
// The slot has been taken by positional argument
if (temp != null && !(temp is NamedArgument))
@ -5418,8 +5456,7 @@ namespace Mono.CSharp { @@ -5418,8 +5456,7 @@ namespace Mono.CSharp {
// For candidates which match on parameters count report more details about incorrect arguments
//
if (pm != null) {
int unexpanded_count = ((IParametersMember) best_candidate).Parameters.HasParams ? pm.Parameters.Count - 1 : pm.Parameters.Count;
if (pm.Parameters.Count == arg_count || params_expanded || unexpanded_count == arg_count) {
if (pm.Parameters.Count == arg_count || params_expanded || HasUnfilledParams (best_candidate, pm, args)) {
// Reject any inaccessible member
if (!best_candidate.IsAccessible (rc) || !best_candidate.DeclaringType.IsAccessible (rc)) {
rc.Report.SymbolRelatedToPreviousError (best_candidate);
@ -5473,6 +5510,39 @@ namespace Mono.CSharp { @@ -5473,6 +5510,39 @@ namespace Mono.CSharp {
}
}
static bool HasUnfilledParams (MemberSpec best_candidate, IParametersMember pm, Arguments args)
{
var p = ((IParametersMember)best_candidate).Parameters;
if (!p.HasParams)
return false;
string name = null;
for (int i = p.Count - 1; i != 0; --i) {
var fp = p.FixedParameters [i];
if ((fp.ModFlags & Parameter.Modifier.PARAMS) == 0)
continue;
name = fp.Name;
break;
}
foreach (var arg in args) {
var na = arg as NamedArgument;
if (na == null)
continue;
if (na.Name == name) {
name = null;
break;
}
}
if (name == null)
return false;
return args.Count + 1 == pm.Parameters.Count;
}
bool VerifyArguments (ResolveContext ec, ref Arguments args, MemberSpec member, IParametersMember pm, bool chose_params_expanded)
{
var pd = pm.Parameters;
@ -5797,6 +5867,14 @@ namespace Mono.CSharp { @@ -5797,6 +5867,14 @@ namespace Mono.CSharp {
}
}
protected override void CloneTo (CloneContext clonectx, Expression target)
{
var t = (FieldExpr) target;
if (InstanceExpression != null)
t.InstanceExpression = InstanceExpression.Clone (clonectx);
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
return CreateExpressionTree (ec, true);
@ -6047,7 +6125,7 @@ namespace Mono.CSharp { @@ -6047,7 +6125,7 @@ namespace Mono.CSharp {
return;
}
if (TypeSpec.IsValueType (InstanceExpression.Type))
if (TypeSpec.IsValueType (InstanceExpression.Type) && InstanceExpression is VariableReference)
return;
}
@ -6130,13 +6208,8 @@ namespace Mono.CSharp { @@ -6130,13 +6208,8 @@ namespace Mono.CSharp {
public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
{
bool has_await_source = ec.HasSet (BuilderContext.Options.AsyncBody) && source.ContainsEmitWithAwait ();
if (isCompound && !(source is DynamicExpressionStatement)) {
if (has_await_source) {
if (IsInstance)
InstanceExpression = InstanceExpression.EmitToField (ec);
} else {
prepared = true;
}
if (isCompound && !(source is DynamicExpressionStatement) && !has_await_source) {
prepared = true;
}
if (IsInstance) {
@ -6148,7 +6221,7 @@ namespace Mono.CSharp { @@ -6148,7 +6221,7 @@ namespace Mono.CSharp {
source.Emit (ec);
if (leave_copy) {
if (leave_copy || ec.NotifyEvaluatorOnStore) {
ec.Emit (OpCodes.Dup);
if (!IsStatic) {
temp = new LocalTemporary (this.Type);
@ -6165,6 +6238,16 @@ namespace Mono.CSharp { @@ -6165,6 +6238,16 @@ namespace Mono.CSharp {
ec.Emit (OpCodes.Stsfld, spec);
else
ec.Emit (OpCodes.Stfld, spec);
if (ec.NotifyEvaluatorOnStore) {
if (!IsStatic)
throw new NotImplementedException ("instance field write");
if (leave_copy)
ec.Emit (OpCodes.Dup);
ec.Module.Evaluator.EmitValueChangedCallback (ec, Name, type, loc);
}
if (temp != null) {
temp.Emit (ec);
@ -6227,7 +6310,6 @@ namespace Mono.CSharp { @@ -6227,7 +6310,6 @@ namespace Mono.CSharp {
var temp = ec.GetTemporaryLocal (type);
ec.Emit (OpCodes.Stloc, temp);
ec.Emit (OpCodes.Ldloca, temp);
ec.FreeTemporaryLocal (temp, type);
return;
}

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

@ -71,6 +71,8 @@ namespace Mono.CSharp @@ -71,6 +71,8 @@ namespace Mono.CSharp
readonly ModuleContainer module;
readonly ReflectionImporter importer;
readonly CompilationSourceFile source_file;
int? listener_id;
public Evaluator (CompilerContext ctx)
{
@ -288,6 +290,30 @@ namespace Mono.CSharp @@ -288,6 +290,30 @@ namespace Mono.CSharp
return compiled;
}
static MethodInfo listener_proxy_value;
internal void EmitValueChangedCallback (EmitContext ec, string name, TypeSpec type, Location loc)
{
if (listener_id == null)
listener_id = ListenerProxy.Register (ModificationListener);
if (listener_proxy_value == null)
listener_proxy_value = typeof (ListenerProxy).GetMethod ("ValueChanged");
#if STATIC
throw new NotSupportedException ();
#else
// object value, int row, int col, string name, int listenerId
if (type.IsStructOrEnum)
ec.Emit (OpCodes.Box, type);
ec.EmitInt (loc.Row);
ec.EmitInt (loc.Column);
ec.Emit (OpCodes.Ldstr, name);
ec.EmitInt (listener_id.Value);
ec.Emit (OpCodes.Call, listener_proxy_value);
#endif
}
/// <summary>
/// Evaluates and expression or statement and returns any result values.
/// </summary>
@ -338,6 +364,11 @@ namespace Mono.CSharp @@ -338,6 +364,11 @@ namespace Mono.CSharp
Console.WriteLine ("Interrupted!\n{0}", e);
} finally {
invoking = false;
if (listener_id != null) {
ListenerProxy.Unregister (listener_id.Value);
listener_id = null;
}
}
//
@ -445,6 +476,9 @@ namespace Mono.CSharp @@ -445,6 +476,9 @@ namespace Mono.CSharp
return result;
}
// Experimental
public Action<string, int, int, object> ModificationListener { get; set; }
enum InputKind {
EOF,
StatementOrExpression,
@ -734,6 +768,7 @@ namespace Mono.CSharp @@ -734,6 +768,7 @@ namespace Mono.CSharp
}
module.EmitContainer ();
if (Report.Errors != 0){
if (undo != null)
undo.ExecuteUndo ();
@ -1230,10 +1265,13 @@ namespace Mono.CSharp @@ -1230,10 +1265,13 @@ namespace Mono.CSharp
if (undo_actions == null)
undo_actions = new List<Action> ();
var existing = current_container.Containers.FirstOrDefault (l => l.Basename == tc.Basename);
if (existing != null) {
current_container.RemoveContainer (existing);
undo_actions.Add (() => current_container.AddTypeContainer (existing));
if (current_container.Containers != null)
{
var existing = current_container.Containers.FirstOrDefault (l => l.Basename == tc.Basename);
if (existing != null) {
current_container.RemoveContainer (existing);
undo_actions.Add (() => current_container.AddTypeContainer (existing));
}
}
undo_actions.Add (() => current_container.RemoveContainer (tc));
@ -1251,5 +1289,38 @@ namespace Mono.CSharp @@ -1251,5 +1289,38 @@ namespace Mono.CSharp
undo_actions = null;
}
}
static class ListenerProxy
{
static readonly Dictionary<int, Action<string, int, int, object>> listeners = new Dictionary<int, Action<string, int, int, object>> ();
static int counter;
public static int Register (Action<string, int, int, object> listener)
{
lock (listeners) {
var id = counter++;
listeners.Add (id, listener);
return id;
}
}
public static void Unregister (int listenerId)
{
lock (listeners) {
listeners.Remove (listenerId);
}
}
public static void ValueChanged (object value, int row, int col, string name, int listenerId)
{
Action<string, int, int, object> action;
lock (listeners) {
if (!listeners.TryGetValue (listenerId, out action))
return;
}
action (name, row, col, value);
}
}
}

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

@ -301,10 +301,33 @@ namespace Mono.CSharp @@ -301,10 +301,33 @@ namespace Mono.CSharp
return new ULongConstant (ec.BuiltinTypes, ~((ULongConstant) e).Value, e.Location);
}
if (e is EnumConstant) {
e = TryReduceConstant (ec, ((EnumConstant)e).Child);
if (e != null)
e = new EnumConstant (e, expr_type);
return e;
var res = TryReduceConstant (ec, ((EnumConstant)e).Child);
if (res != null) {
//
// Numeric promotion upgraded types to int but for enum constant
// original underlying constant type is needed
//
if (res.Type.BuiltinType == BuiltinTypeSpec.Type.Int) {
int v = ((IntConstant) res).Value;
switch (((EnumConstant) e).Child.Type.BuiltinType) {
case BuiltinTypeSpec.Type.UShort:
res = new UShortConstant (ec.BuiltinTypes, (ushort) v, e.Location);
break;
case BuiltinTypeSpec.Type.Short:
res = new ShortConstant (ec.BuiltinTypes, (short) v, e.Location);
break;
case BuiltinTypeSpec.Type.Byte:
res = new ByteConstant (ec.BuiltinTypes, (byte) v, e.Location);
break;
case BuiltinTypeSpec.Type.SByte:
res = new SByteConstant (ec.BuiltinTypes, (sbyte) v, e.Location);
break;
}
}
res = new EnumConstant (res, expr_type);
}
return res;
}
return null;
}
@ -1406,8 +1429,9 @@ namespace Mono.CSharp @@ -1406,8 +1429,9 @@ namespace Mono.CSharp
return null;
if (probe_type_expr.IsStatic) {
ec.Report.Error (-244, loc, "The `{0}' operator cannot be applied to an operand of a static type",
OperatorName);
ec.Report.Error (7023, loc, "The second operand of `is' or `as' operator cannot be static type `{0}'",
probe_type_expr.GetSignatureForError ());
return null;
}
if (expr.Type.IsPointer || probe_type_expr.IsPointer) {
@ -1425,6 +1449,11 @@ namespace Mono.CSharp @@ -1425,6 +1449,11 @@ namespace Mono.CSharp
return this;
}
public override void EmitSideEffect (EmitContext ec)
{
expr.EmitSideEffect (ec);
}
public override void FlowAnalysis (FlowAnalysisContext fc)
{
expr.FlowAnalysis (fc);
@ -1495,17 +1524,20 @@ namespace Mono.CSharp @@ -1495,17 +1524,20 @@ namespace Mono.CSharp
}
ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
}
Expression CreateConstantResult (ResolveContext ec, bool result)
Expression CreateConstantResult (ResolveContext rc, bool result)
{
if (result)
ec.Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
rc.Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
probe_type_expr.GetSignatureForError ());
else
ec.Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
rc.Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
probe_type_expr.GetSignatureForError ());
return ReducedExpression.Create (new BoolConstant (ec.BuiltinTypes, result, loc), this);
var c = new BoolConstant (rc.BuiltinTypes, result, loc);
return expr.IsSideEffectFree ?
ReducedExpression.Create (c, this) :
new SideEffectConstant (c, this, loc);
}
protected override Expression DoResolve (ResolveContext ec)
@ -1604,12 +1636,15 @@ namespace Mono.CSharp @@ -1604,12 +1636,15 @@ namespace Mono.CSharp
return CreateConstantResult (ec, !c.IsNull);
//
// Do not optimize for imported type
// Do not optimize for imported type or dynamic type
//
if (d.MemberDefinition.IsImported && d.BuiltinType != BuiltinTypeSpec.Type.None &&
d.MemberDefinition.DeclaringAssembly != t.MemberDefinition.DeclaringAssembly) {
return this;
}
if (d.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
return this;
//
// Turn is check into simple null check for implicitly convertible reference types
@ -2584,7 +2619,9 @@ namespace Mono.CSharp @@ -2584,7 +2619,9 @@ namespace Mono.CSharp
public override void FlowAnalysis (FlowAnalysisContext fc)
{
if ((oper & Operator.LogicalMask) == 0) {
fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment;
left.FlowAnalysis (fc);
fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment;
right.FlowAnalysis (fc);
return;
}
@ -2936,8 +2973,8 @@ namespace Mono.CSharp @@ -2936,8 +2973,8 @@ namespace Mono.CSharp
}
}
left = ConvertEnumOperandToUnderlyingType (rc, left);
right = ConvertEnumOperandToUnderlyingType (rc, right);
left = ConvertEnumOperandToUnderlyingType (rc, left, r.IsNullableType);
right = ConvertEnumOperandToUnderlyingType (rc, right, l.IsNullableType);
return expr;
}
} else if ((oper == Operator.Addition || oper == Operator.Subtraction)) {
@ -2952,8 +2989,8 @@ namespace Mono.CSharp @@ -2952,8 +2989,8 @@ namespace Mono.CSharp
// which is not ambiguous with predefined enum operators
//
if (expr != null) {
left = ConvertEnumOperandToUnderlyingType (rc, left);
right = ConvertEnumOperandToUnderlyingType (rc, right);
left = ConvertEnumOperandToUnderlyingType (rc, left, false);
right = ConvertEnumOperandToUnderlyingType (rc, right, false);
return expr;
}
@ -3451,6 +3488,13 @@ namespace Mono.CSharp @@ -3451,6 +3488,13 @@ namespace Mono.CSharp
} else {
LocalVariable temp = LocalVariable.CreateCompilerGenerated (rc.BuiltinTypes.Bool, rc.CurrentBlock, loc);
if (!Convert.ImplicitConversionExists (rc, left, temp.Type) && (oper == Operator.LogicalAnd ? GetOperatorFalse (rc, left, loc) : GetOperatorTrue (rc, left, loc)) == null) {
rc.Report.Error (7083, left.Location,
"Expression must be implicitly convertible to Boolean or its type `{0}' must define operator `{1}'",
lt.GetSignatureForError (), oper == Operator.LogicalAnd ? "false" : "true");
return null;
}
args.Add (new Argument (temp.CreateReferenceExpression (rc, loc).Resolve (rc)));
args.Add (new Argument (right));
right = new DynamicExpressionStatement (this, args, loc);
@ -3756,7 +3800,7 @@ namespace Mono.CSharp @@ -3756,7 +3800,7 @@ namespace Mono.CSharp
return null;
}
static Expression ConvertEnumOperandToUnderlyingType (ResolveContext rc, Expression expr)
static Expression ConvertEnumOperandToUnderlyingType (ResolveContext rc, Expression expr, bool liftType)
{
TypeSpec underlying_type;
if (expr.Type.IsNullableType) {
@ -3780,7 +3824,7 @@ namespace Mono.CSharp @@ -3780,7 +3824,7 @@ namespace Mono.CSharp
break;
}
if (expr.Type.IsNullableType)
if (expr.Type.IsNullableType || liftType)
underlying_type = rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { underlying_type });
if (expr.Type == underlying_type)
@ -4062,12 +4106,12 @@ namespace Mono.CSharp @@ -4062,12 +4106,12 @@ namespace Mono.CSharp
if (!TypeSpec.IsReferenceType (l) || !TypeSpec.IsReferenceType (r))
return null;
if (l.BuiltinType == BuiltinTypeSpec.Type.String || l.BuiltinType == BuiltinTypeSpec.Type.Delegate || MemberCache.GetUserOperator (l, CSharp.Operator.OpType.Equality, false) != null)
if (l.BuiltinType == BuiltinTypeSpec.Type.String || l.BuiltinType == BuiltinTypeSpec.Type.Delegate || l.IsDelegate || MemberCache.GetUserOperator (l, CSharp.Operator.OpType.Equality, false) != null)
ec.Report.Warning (253, 2, loc,
"Possible unintended reference comparison. Consider casting the right side expression to type `{0}' to get value comparison",
l.GetSignatureForError ());
if (r.BuiltinType == BuiltinTypeSpec.Type.String || r.BuiltinType == BuiltinTypeSpec.Type.Delegate || MemberCache.GetUserOperator (r, CSharp.Operator.OpType.Equality, false) != null)
if (r.BuiltinType == BuiltinTypeSpec.Type.String || r.BuiltinType == BuiltinTypeSpec.Type.Delegate || r.IsDelegate || MemberCache.GetUserOperator (r, CSharp.Operator.OpType.Equality, false) != null)
ec.Report.Warning (252, 2, loc,
"Possible unintended reference comparison. Consider casting the left side expression to type `{0}' to get value comparison",
r.GetSignatureForError ());
@ -6746,7 +6790,7 @@ namespace Mono.CSharp @@ -6746,7 +6790,7 @@ namespace Mono.CSharp
if (!Emit (ec, v))
v.Emit (ec);
}
public override void EmitStatement (EmitContext ec)
{
LocalTemporary v = null;
@ -7552,7 +7596,9 @@ namespace Mono.CSharp @@ -7552,7 +7596,9 @@ namespace Mono.CSharp
public override void Emit (EmitContext ec)
{
EmitToFieldSource (ec);
var await_field = EmitToFieldSource (ec);
if (await_field != null)
await_field.Emit (ec);
}
protected sealed override FieldExpr EmitToFieldSource (EmitContext ec)
@ -7606,18 +7652,18 @@ namespace Mono.CSharp @@ -7606,18 +7652,18 @@ namespace Mono.CSharp
return await_stack_field;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
// no multi dimensional or jagged arrays
if (arguments.Count != 1 || array_element_type.IsArray) {
base.EncodeAttributeValue (rc, enc, targetType);
base.EncodeAttributeValue (rc, enc, targetType, parameterType);
return;
}
// No array covariance, except for array -> object
if (type != targetType) {
if (targetType.BuiltinType != BuiltinTypeSpec.Type.Object) {
base.EncodeAttributeValue (rc, enc, targetType);
base.EncodeAttributeValue (rc, enc, targetType, parameterType);
return;
}
@ -7631,7 +7677,7 @@ namespace Mono.CSharp @@ -7631,7 +7677,7 @@ namespace Mono.CSharp
if (array_data == null) {
IntConstant ic = arguments[0] as IntConstant;
if (ic == null || !ic.IsDefaultValue) {
base.EncodeAttributeValue (rc, enc, targetType);
base.EncodeAttributeValue (rc, enc, targetType, parameterType);
} else {
enc.Encode (0);
}
@ -7641,7 +7687,7 @@ namespace Mono.CSharp @@ -7641,7 +7687,7 @@ namespace Mono.CSharp
enc.Encode (array_data.Count);
foreach (var element in array_data) {
element.EncodeAttributeValue (rc, enc, array_element_type);
element.EncodeAttributeValue (rc, enc, array_element_type, parameterType);
}
}
@ -8369,7 +8415,7 @@ namespace Mono.CSharp @@ -8369,7 +8415,7 @@ namespace Mono.CSharp
return false;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
{
// Target type is not System.Type therefore must be object
// and we need to use different encoding sequence
@ -8804,7 +8850,7 @@ namespace Mono.CSharp @@ -8804,7 +8850,7 @@ namespace Mono.CSharp
// with disable flow analysis as we don't know whether left side expression
// is used as variable or type
//
if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess) {
if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess || expr is EventExpr) {
expr = expr.Resolve (rc);
} else if (expr is TypeParameterExpr) {
expr.Error_UnexpectedKind (rc, flags, sn.Location);
@ -9429,6 +9475,10 @@ namespace Mono.CSharp @@ -9429,6 +9475,10 @@ namespace Mono.CSharp
{
var ac = (ArrayContainer) ea.Expr.Type;
if (!has_await_args.HasValue && ec.HasSet (BuilderContext.Options.AsyncBody) && ea.Arguments.ContainsEmitWithAwait ()) {
LoadInstanceAndArguments (ec, false, true);
}
LoadInstanceAndArguments (ec, false, false);
if (ac.Element.IsGenericParameter && mode == AddressOp.Load)
@ -9625,6 +9675,7 @@ namespace Mono.CSharp @@ -9625,6 +9675,7 @@ namespace Mono.CSharp
// CallRef (ref a[await Task.Factory.StartNew (() => 1)]);
//
ea.Expr = ea.Expr.EmitToField (ec);
ea.Arguments = ea.Arguments.Emit (ec, false, true);
return this;
}
@ -10026,6 +10077,10 @@ namespace Mono.CSharp @@ -10026,6 +10077,10 @@ namespace Mono.CSharp
loc = Location.Null;
}
protected override void CloneTo (CloneContext clonectx, Expression target)
{
}
public override bool ContainsEmitWithAwait ()
{
return false;
@ -11079,6 +11134,20 @@ namespace Mono.CSharp @@ -11079,6 +11134,20 @@ namespace Mono.CSharp
return e;
}
public override void Emit (EmitContext ec)
{
if (method == null && TypeSpec.IsValueType (type) && initializers.Initializers.Count > 1 && ec.HasSet (BuilderContext.Options.AsyncBody) && initializers.ContainsEmitWithAwait ()) {
var fe = ec.GetTemporaryField (type);
if (!Emit (ec, fe))
fe.Emit (ec);
return;
}
base.Emit (ec);
}
public override bool Emit (EmitContext ec, IMemoryLocation target)
{
bool left_on_stack;
@ -11095,6 +11164,8 @@ namespace Mono.CSharp @@ -11095,6 +11164,8 @@ namespace Mono.CSharp
LocalTemporary temp = null;
instance = target as LocalTemporary;
if (instance == null)
instance = target as StackFieldExpr;
if (instance == null) {
if (!left_on_stack) {
@ -11203,6 +11274,7 @@ namespace Mono.CSharp @@ -11203,6 +11274,7 @@ namespace Mono.CSharp
type.Define ();
if ((ec.Report.Errors - errors) == 0) {
parent.Module.AddAnonymousType (type);
type.PrepareEmit ();
}
return type;
@ -11333,4 +11405,13 @@ namespace Mono.CSharp @@ -11333,4 +11405,13 @@ namespace Mono.CSharp
Name, initializer);
}
}
public class CatchFilterExpression : BooleanExpression
{
public CatchFilterExpression (Expression expr, Location loc)
: base (expr)
{
this.loc = loc;
}
}
}

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

@ -222,7 +222,9 @@ namespace Mono.CSharp @@ -222,7 +222,9 @@ namespace Mono.CSharp
if (MemberType.IsStatic)
Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
CheckBase ();
if (!IsCompilerGenerated)
CheckBase ();
IsTypePermitted ();
}
@ -693,4 +695,39 @@ namespace Mono.CSharp @@ -693,4 +695,39 @@ namespace Mono.CSharp
return true;
}
}
class PrimaryConstructorField : Field
{
//
// Proxy resolved parameter type expression to avoid type double resolve
// and problems with correct resolve context on partial classes
//
sealed class TypeExpressionFromParameter : TypeExpr
{
Parameter parameter;
public TypeExpressionFromParameter (Parameter parameter)
{
this.parameter = parameter;
eclass = ExprClass.Type;
loc = parameter.Location;
}
public override TypeSpec ResolveAsType (IMemberContext mc)
{
return parameter.Type;
}
}
public PrimaryConstructorField (TypeDefinition parent, Parameter parameter)
: base (parent, new TypeExpressionFromParameter (parameter), Modifiers.PRIVATE, new MemberName (parameter.Name, parameter.Location), null)
{
caching_flags |= Flags.IsUsed | Flags.IsAssigned;
}
public override string GetSignatureForError ()
{
return MemberName.Name;
}
}
}

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

@ -268,8 +268,7 @@ namespace Mono.CSharp { @@ -268,8 +268,7 @@ namespace Mono.CSharp {
iface_found = true;
continue;
}
var constraint_tp = type as TypeParameterSpec;
if (constraint_tp != null) {
if (tparam_types == null) {
@ -320,6 +319,12 @@ namespace Mono.CSharp { @@ -320,6 +319,12 @@ namespace Mono.CSharp {
}
}
if (constraint_tp.TypeArguments != null) {
var eb = constraint_tp.GetEffectiveBase ();
if (eb != null && !CheckConflictingInheritedConstraint (spec, eb, spec.BaseType, context, constraint.Location))
break;
}
if (constraint_tp.HasSpecialStruct) {
context.Module.Compiler.Report.Error (456, constraint.Location,
"Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
@ -770,6 +775,7 @@ namespace Mono.CSharp { @@ -770,6 +775,7 @@ namespace Mono.CSharp {
int tp_pos;
TypeSpec[] targs;
TypeSpec[] ifaces_defined;
TypeSpec effective_base;
//
// Creates type owned type parameter
@ -1033,23 +1039,27 @@ namespace Mono.CSharp { @@ -1033,23 +1039,27 @@ namespace Mono.CSharp {
return BaseType.IsStruct ? BaseType.BaseType : BaseType;
}
var types = targs;
if (HasTypeConstraint) {
Array.Resize (ref types, types.Length + 1);
if (effective_base != null)
return effective_base;
var types = new TypeSpec [HasTypeConstraint ? targs.Length + 1 : targs.Length];
for (int i = 0; i < types.Length - 1; ++i) {
types[i] = types[i].BaseType;
for (int i = 0; i < targs.Length; ++i) {
var t = targs [i];
// Same issue as above, inherited constraints can be of struct type
if (t.IsStruct) {
types [i] = t.BaseType;
continue;
}
types[types.Length - 1] = BaseType;
} else {
types = types.Select (l => l.BaseType).ToArray ();
types [i] = ((TypeParameterSpec)t).GetEffectiveBase ();
}
if (types != null)
return Convert.FindMostEncompassedType (types);
if (HasTypeConstraint)
types [types.Length - 1] = BaseType;
return BaseType;
return effective_base = Convert.FindMostEncompassedType (types);
}
public override string GetSignatureForDocumentation ()
@ -1313,12 +1323,17 @@ namespace Mono.CSharp { @@ -1313,12 +1323,17 @@ namespace Mono.CSharp {
if (targs != null) {
foreach (var ta in targs) {
var b_type = ta.BaseType;
if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
cache.AddBaseType (b_type);
var tps = ta as TypeParameterSpec;
var ifaces = tps != null ? tps.InterfacesDefined : ta.Interfaces;
IList<TypeSpec> ifaces;
if (tps != null) {
var b_type = tps.GetEffectiveBase ();
if (b_type != null && b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
cache.AddBaseType (b_type);
ifaces = tps.InterfacesDefined;
} else {
ifaces = ta.Interfaces;
}
if (ifaces != null) {
foreach (var iface_type in ifaces) {
@ -1340,7 +1355,15 @@ namespace Mono.CSharp { @@ -1340,7 +1355,15 @@ namespace Mono.CSharp {
if (TypeArguments != null) {
foreach (var t in TypeArguments) {
if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
var tps = t as TypeParameterSpec;
if (tps != null) {
if (tps.IsConvertibleToInterface (iface))
return true;
continue;
}
if (t.ImplementsInterface (iface, false))
return true;
}
}
@ -1448,13 +1471,18 @@ namespace Mono.CSharp { @@ -1448,13 +1471,18 @@ namespace Mono.CSharp {
if (tp != null)
return Inflate (tp);
var ac = type as ArrayContainer;
if (ac != null) {
var et = Inflate (ac.Element);
if (et != ac.Element)
return ArrayContainer.MakeType (context.Module, et, ac.Rank);
var ec = type as ElementTypeSpec;
if (ec != null) {
var et = Inflate (ec.Element);
if (et != ec.Element) {
var ac = ec as ArrayContainer;
if (ac != null)
return ArrayContainer.MakeType (context.Module, et, ac.Rank);
throw new NotImplementedException ();
}
return ac;
return ec;
}
if (type.Kind == MemberKind.MissingType)
@ -2163,6 +2191,8 @@ namespace Mono.CSharp { @@ -2163,6 +2191,8 @@ namespace Mono.CSharp {
atypes = new TypeSpec [count];
var errors = ec.Module.Compiler.Report.Errors;
for (int i = 0; i < count; i++){
var te = args[i].ResolveAsType (ec);
if (te == null) {
@ -2186,7 +2216,7 @@ namespace Mono.CSharp { @@ -2186,7 +2216,7 @@ namespace Mono.CSharp {
}
}
if (!ok)
if (!ok || errors != ec.Module.Compiler.Report.Errors)
atypes = null;
return ok;
@ -2406,6 +2436,8 @@ namespace Mono.CSharp { @@ -2406,6 +2436,8 @@ namespace Mono.CSharp {
return null;
TypeSpec[] atypes = args.Arguments;
if (atypes == null)
return null;
//
// Now bind the parameters

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

@ -204,10 +204,13 @@ namespace Mono.CSharp @@ -204,10 +204,13 @@ namespace Mono.CSharp
protected StateMachine (ParametersBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
: base (block, parent, host, tparams, name, kind)
{
OriginalTypeParameters = tparams;
}
#region Properties
public TypeParameters OriginalTypeParameters { get; private set; }
public StateMachineMethod StateMachineMethod {
get {
return method;
@ -721,7 +724,6 @@ namespace Mono.CSharp @@ -721,7 +724,6 @@ namespace Mono.CSharp
// The state as we generate the machine
//
Label move_next_ok;
Label iterator_body_end;
protected Label move_next_error;
LocalBuilder skip_finally;
protected LocalBuilder current_pc;
@ -735,11 +737,7 @@ namespace Mono.CSharp @@ -735,11 +737,7 @@ namespace Mono.CSharp
#region Properties
public Label BodyEnd {
get {
return iterator_body_end;
}
}
public Label BodyEnd { get; set; }
public LocalBuilder CurrentPC
{
@ -827,11 +825,11 @@ namespace Mono.CSharp @@ -827,11 +825,11 @@ namespace Mono.CSharp
// We only care if the PC is zero (start executing) or non-zero (don't do anything)
ec.Emit (OpCodes.Brtrue, move_next_error);
iterator_body_end = ec.DefineLabel ();
BodyEnd = ec.DefineLabel ();
block.EmitEmbedded (ec);
ec.MarkLabel (iterator_body_end);
ec.MarkLabel (BodyEnd);
EmitMoveNextEpilogue (ec);
@ -890,11 +888,11 @@ namespace Mono.CSharp @@ -890,11 +888,11 @@ namespace Mono.CSharp
ec.MarkLabel (labels[0]);
iterator_body_end = ec.DefineLabel ();
BodyEnd = ec.DefineLabel ();
block.EmitEmbedded (ec);
ec.MarkLabel (iterator_body_end);
ec.MarkLabel (BodyEnd);
if (async_init != null) {
var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location);

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

@ -566,11 +566,7 @@ namespace Mono.CSharp { @@ -566,11 +566,7 @@ namespace Mono.CSharp {
for (int i = 0; i < applicable.Count; ++i) {
var entry = applicable [i];
if ((entry.Modifiers & Modifiers.PRIVATE) != 0)
continue;
if ((entry.Modifiers & Modifiers.AccessibilityMask) == Modifiers.INTERNAL &&
!entry.DeclaringType.MemberDefinition.IsInternalAsPublic (member.Module.DeclaringAssembly))
if ((entry.Modifiers & Modifiers.PUBLIC) == 0 && !entry.IsAccessible (member))
continue;
//
@ -701,6 +697,14 @@ namespace Mono.CSharp { @@ -701,6 +697,14 @@ namespace Mono.CSharp {
if ((name_entry.Modifiers & Modifiers.STATIC) != 0)
continue;
//
// Ignore user private fields for definite assignment. This is sort of unexpected but
// rationale is to have consistent results when using reference assemblies which don't
// include any private fields and full assemblies
//
if ((name_entry.Modifiers & (Modifiers.PRIVATE | Modifiers.BACKING_FIELD)) == Modifiers.PRIVATE)
continue;
//
// Fixed size buffers are not subject to definite assignment checking
//

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

@ -563,6 +563,12 @@ namespace Mono.CSharp { @@ -563,6 +563,12 @@ namespace Mono.CSharp {
if ((ModFlags & extern_static) != extern_static) {
Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
}
if (MemberName.IsGeneric || Parent.IsGenericOrParentIsGeneric) {
Report.Error (7042, a.Location,
"The DllImport attribute cannot be applied to a method that is generic or contained in a generic type");
}
is_external_implementation = true;
}
@ -719,6 +725,11 @@ namespace Mono.CSharp { @@ -719,6 +725,11 @@ namespace Mono.CSharp {
if (MethodData != null)
MethodData.Emit (Parent);
if (block != null && block.StateMachine is AsyncTaskStorey) {
var psm = Module.PredefinedAttributes.AsyncStateMachine;
psm.EmitAttribute (MethodBuilder, block.StateMachine);
}
if ((ModFlags & Modifiers.PARTIAL) == 0)
Block = null;
}
@ -1101,61 +1112,61 @@ namespace Mono.CSharp { @@ -1101,61 +1112,61 @@ namespace Mono.CSharp {
}
for (int i = 0; i < tparams.Count; ++i) {
var tp = tparams[i];
var tp = tparams [i];
if (!tp.ResolveConstraints (this))
if (base_tparams == null) {
tp.ResolveConstraints (this);
continue;
}
//
// Copy base constraints for override/explicit methods
//
if (base_tparams != null) {
var base_tparam = base_tparams[i];
var local_tparam = tp.Type;
local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
var base_tparam = base_tparams [i];
var local_tparam = tp.Type;
local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
var inflator = new TypeParameterInflator (this, CurrentType, base_decl_tparams, base_targs);
base_tparam.InflateConstraints (inflator, local_tparam);
var inflator = new TypeParameterInflator (this, CurrentType, base_decl_tparams, base_targs);
base_tparam.InflateConstraints (inflator, local_tparam);
//
// Check all type argument constraints for possible collision or unification
// introduced by inflating inherited constraints in this context
//
// Conflict example:
//
// class A<T> { virtual void Foo<U> () where U : class, T {} }
// class B : A<int> { override void Foo<U> {} }
//
var local_tparam_targs = local_tparam.TypeArguments;
if (local_tparam_targs != null) {
for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
var ta = local_tparam_targs [ii];
if (!ta.IsClass && !ta.IsStruct)
continue;
TypeSpec[] unique_tparams = null;
for (int iii = ii + 1; iii < local_tparam_targs.Length; ++iii) {
//
// Remove any identical or unified constraint types
//
var tparam_checked = local_tparam_targs[iii];
if (TypeSpecComparer.IsEqual (ta, tparam_checked) || TypeSpec.IsBaseClass (ta, tparam_checked, false)) {
unique_tparams = new TypeSpec[local_tparam_targs.Length - 1];
Array.Copy (local_tparam_targs, 0, unique_tparams, 0, iii);
Array.Copy (local_tparam_targs, iii + 1, unique_tparams, iii, local_tparam_targs.Length - iii - 1);
} else if (!TypeSpec.IsBaseClass (tparam_checked, ta, false)) {
Constraints.Error_ConflictingConstraints (this, local_tparam, ta, tparam_checked, Location);
}
}
if (unique_tparams != null) {
local_tparam_targs = unique_tparams;
local_tparam.TypeArguments = local_tparam_targs;
continue;
//
// Check all type argument constraints for possible collision or unification
// introduced by inflating inherited constraints in this context
//
// Conflict example:
//
// class A<T> { virtual void Foo<U> () where U : class, T {} }
// class B : A<int> { override void Foo<U> {} }
//
var local_tparam_targs = local_tparam.TypeArguments;
if (local_tparam_targs != null) {
for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
var ta = local_tparam_targs [ii];
if (!ta.IsClass && !ta.IsStruct)
continue;
TypeSpec[] unique_tparams = null;
for (int iii = ii + 1; iii < local_tparam_targs.Length; ++iii) {
//
// Remove any identical or unified constraint types
//
var tparam_checked = local_tparam_targs [iii];
if (TypeSpecComparer.IsEqual (ta, tparam_checked) || TypeSpec.IsBaseClass (ta, tparam_checked, false)) {
unique_tparams = new TypeSpec[local_tparam_targs.Length - 1];
Array.Copy (local_tparam_targs, 0, unique_tparams, 0, iii);
Array.Copy (local_tparam_targs, iii + 1, unique_tparams, iii, local_tparam_targs.Length - iii - 1);
} else if (!TypeSpec.IsBaseClass (tparam_checked, ta, false)) {
Constraints.Error_ConflictingConstraints (this, local_tparam, ta, tparam_checked, Location);
}
}
Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location);
if (unique_tparams != null) {
local_tparam_targs = unique_tparams;
local_tparam.TypeArguments = local_tparam_targs;
continue;
}
Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location);
}
}
}
@ -1343,12 +1354,6 @@ namespace Mono.CSharp { @@ -1343,12 +1354,6 @@ namespace Mono.CSharp {
}
}
if (block != null && block.StateMachine is AsyncTaskStorey) {
var psm = Module.PredefinedAttributes.AsyncStateMachine;
psm.EmitAttribute (MethodBuilder, block.StateMachine);
}
if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
@ -1524,8 +1529,8 @@ namespace Mono.CSharp { @@ -1524,8 +1529,8 @@ namespace Mono.CSharp {
}
class GeneratedBaseInitializer: ConstructorBaseInitializer {
public GeneratedBaseInitializer (Location loc):
base (null, loc)
public GeneratedBaseInitializer (Location loc, Arguments arguments)
: base (arguments, loc)
{
}
}
@ -1585,6 +1590,8 @@ namespace Mono.CSharp { @@ -1585,6 +1590,8 @@ namespace Mono.CSharp {
}
}
public bool IsPrimaryConstructor { get; set; }
MethodBase IMethodDefinition.Metadata {
get {
@ -1673,6 +1680,16 @@ namespace Mono.CSharp { @@ -1673,6 +1680,16 @@ namespace Mono.CSharp {
if (!CheckBase ())
return false;
if (Parent.PrimaryConstructorParameters != null && !IsPrimaryConstructor) {
if (Parent.Kind == MemberKind.Struct) {
Report.Error (9009, Location, "`{0}': Structs with primary constructor cannot have explicit constructor",
GetSignatureForError ());
} else if (Initializer == null || Initializer is ConstructorBaseInitializer) {
Report.Error (9002, Location, "`{0}': Instance constructor of type with primary constructor must specify `this' constructor initializer",
GetSignatureForError ());
}
}
var ca = ModifiersExtensions.MethodAttr (ModFlags) | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
@ -1744,7 +1761,7 @@ namespace Mono.CSharp { @@ -1744,7 +1761,7 @@ namespace Mono.CSharp {
//
block.AddThisVariable (bc);
} else if (Parent.PartialContainer.Kind == MemberKind.Class) {
Initializer = new GeneratedBaseInitializer (Location);
Initializer = new GeneratedBaseInitializer (Location, null);
}
}
@ -1975,7 +1992,7 @@ namespace Mono.CSharp { @@ -1975,7 +1992,7 @@ namespace Mono.CSharp {
return false;
}
} else {
if (implementing != null) {
if (implementing != null && !optional) {
if (!method.IsAccessor) {
if (implementing.IsAccessor) {
container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
@ -2461,6 +2478,11 @@ namespace Mono.CSharp { @@ -2461,6 +2478,11 @@ namespace Mono.CSharp {
return false;
}
public void PrepareEmit ()
{
method_data.DefineMethodBuilder (Parent.PartialContainer, ParameterInfo);
}
public override void WriteDebugSymbol (MonoSymbolFile file)
{
if (method_data != null)

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

@ -529,6 +529,11 @@ namespace Mono.CSharp.Nullable @@ -529,6 +529,11 @@ namespace Mono.CSharp.Nullable
return null;
Expression res = base.ResolveOperator (ec, unwrap);
if (res == null) {
Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
return null;
}
if (res != this) {
if (user_operator == null)
return res;
@ -1153,26 +1158,25 @@ namespace Mono.CSharp.Nullable @@ -1153,26 +1158,25 @@ namespace Mono.CSharp.Nullable
//
Constant lc = left as Constant;
if (lc != null && !lc.IsDefaultValue)
return ReducedExpression.Create (lc, this);
return ReducedExpression.Create (lc, this, false);
//
// Reduce (left ?? null) to left OR (null-constant ?? right) to right
//
if (right.IsNull || lc != null)
return ReducedExpression.Create (lc != null ? right : left, this);
if (right.IsNull || lc != null) {
//
// Special case null ?? null
//
if (right.IsNull && ltype == right.Type)
return null;
return ReducedExpression.Create (lc != null ? right : left, this, false);
}
right = Convert.ImplicitConversion (ec, right, ltype, loc);
type = ltype;
return this;
}
//
// Special case null ?? null
//
if (ltype == right.Type) {
type = ltype;
return this;
}
} else {
return null;
}
@ -1185,7 +1189,7 @@ namespace Mono.CSharp.Nullable @@ -1185,7 +1189,7 @@ namespace Mono.CSharp.Nullable
// Reduce (null ?? right) to right
//
if (left.IsNull)
return ReducedExpression.Create (right, this).Resolve (ec);
return ReducedExpression.Create (right, this, false).Resolve (ec);
left = Convert.ImplicitConversion (ec, unwrap ?? left, rtype, loc);
type = rtype;
@ -1229,7 +1233,15 @@ namespace Mono.CSharp.Nullable @@ -1229,7 +1233,15 @@ namespace Mono.CSharp.Nullable
unwrap.EmitCheck (ec);
ec.Emit (OpCodes.Brfalse, is_null_label);
left.Emit (ec);
//
// When both expressions are nullable the unwrap
// is needed only for null check not for value uwrap
//
if (type.IsNullableType && TypeSpecComparer.IsEqual (NullableInfo.GetUnderlyingType (type), unwrap.Type))
unwrap.Load (ec);
else
left.Emit (ec);
ec.Emit (OpCodes.Br, end_label);
ec.MarkLabel (is_null_label);

73
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/parameter.cs

@ -223,6 +223,7 @@ namespace Mono.CSharp { @@ -223,6 +223,7 @@ namespace Mono.CSharp {
}
static readonly string[] attribute_targets = new string[] { "param" };
static readonly string[] attribute_targets_primary = new string[] { "param", "field" };
FullNamedExpression texpr;
Modifier modFlags;
@ -233,6 +234,7 @@ namespace Mono.CSharp { @@ -233,6 +234,7 @@ namespace Mono.CSharp {
protected int idx;
public bool HasAddressTaken;
Constructor primary_constructor;
TemporaryVariableReference expr_tree_variable;
HoistedParameter hoisted_variant;
@ -307,7 +309,7 @@ namespace Mono.CSharp { @@ -307,7 +309,7 @@ namespace Mono.CSharp {
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
return primary_constructor != null ? attribute_targets_primary : attribute_targets;
}
}
@ -315,6 +317,12 @@ namespace Mono.CSharp { @@ -315,6 +317,12 @@ namespace Mono.CSharp {
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
if (a.Target == AttributeTargets.Field) {
var field = MemberCache.FindMember (primary_constructor.Spec.DeclaringType, MemberFilter.Field (name, parameter_type), BindingRestriction.DeclaredOnly);
((Field)field.MemberDefinition).ApplyAttributeBuilder (a, ctor, cdata, pa);
return;
}
if (a.Type == pa.In && ModFlags == Modifier.OUT) {
a.Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute");
return;
@ -371,6 +379,15 @@ namespace Mono.CSharp { @@ -371,6 +379,15 @@ namespace Mono.CSharp {
return member.IsAccessibleAs (parameter_type);
}
bool IsValidCallerContext (MemberCore memberContext)
{
var m = memberContext as Method;
if (m != null)
return !m.IsPartialImplementation;
return true;
}
// <summary>
// Resolve is used in method definitions
// </summary>
@ -382,6 +399,10 @@ namespace Mono.CSharp { @@ -382,6 +399,10 @@ namespace Mono.CSharp {
if (attributes != null)
attributes.AttachTo (this, rc);
var ctor = rc.CurrentMemberDefinition as Constructor;
if (ctor != null && ctor.IsPrimaryConstructor)
primary_constructor = ctor;
parameter_type = texpr.ResolveAsType (rc);
if (parameter_type == null)
return null;
@ -416,6 +437,7 @@ namespace Mono.CSharp { @@ -416,6 +437,7 @@ namespace Mono.CSharp {
{
var pa = rc.Module.PredefinedAttributes;
TypeSpec caller_type;
Attribute callerMemberName = null, callerFilePath = null;
foreach (var attr in attributes.Attrs) {
var atype = attr.ResolveTypeForComparison ();
@ -430,7 +452,14 @@ namespace Mono.CSharp { @@ -430,7 +452,14 @@ namespace Mono.CSharp {
caller_type.GetSignatureForError (), parameter_type.GetSignatureForError ());
}
if (!IsValidCallerContext (rc.CurrentMemberDefinition)) {
rc.Report.Warning (4026, 1, attr.Location,
"The CallerMemberName applied to parameter `{0}' will have no effect because it applies to a member that is used in context that do not allow optional arguments",
name);
}
modFlags |= Modifier.CallerMemberName;
callerMemberName = attr;
continue;
}
@ -438,10 +467,16 @@ namespace Mono.CSharp { @@ -438,10 +467,16 @@ namespace Mono.CSharp {
caller_type = rc.BuiltinTypes.Int;
if (caller_type != parameter_type && !Convert.ImplicitNumericConversionExists (caller_type, parameter_type)) {
rc.Report.Error (4017, attr.Location,
"The CallerMemberName attribute cannot be applied because there is no standard conversion from `{0}' to `{1}'",
"The CallerLineNumberAttribute attribute cannot be applied because there is no standard conversion from `{0}' to `{1}'",
caller_type.GetSignatureForError (), parameter_type.GetSignatureForError ());
}
if (!IsValidCallerContext (rc.CurrentMemberDefinition)) {
rc.Report.Warning (4024, 1, attr.Location,
"The CallerLineNumberAttribute applied to parameter `{0}' will have no effect because it applies to a member that is used in context that do not allow optional arguments",
name);
}
modFlags |= Modifier.CallerLineNumber;
continue;
}
@ -454,10 +489,40 @@ namespace Mono.CSharp { @@ -454,10 +489,40 @@ namespace Mono.CSharp {
caller_type.GetSignatureForError (), parameter_type.GetSignatureForError ());
}
if (!IsValidCallerContext (rc.CurrentMemberDefinition)) {
rc.Report.Warning (4025, 1, attr.Location,
"The CallerFilePath applied to parameter `{0}' will have no effect because it applies to a member that is used in context that do not allow optional arguments",
name);
}
modFlags |= Modifier.CallerFilePath;
callerFilePath = attr;
continue;
}
}
if ((modFlags & Modifier.CallerLineNumber) != 0) {
if (callerMemberName != null) {
rc.Report.Warning (7081, 1, callerMemberName.Location,
"The CallerMemberNameAttribute applied to parameter `{0}' will have no effect. It is overridden by the CallerLineNumberAttribute",
Name);
}
if (callerFilePath != null) {
rc.Report.Warning (7082, 1, callerFilePath.Location,
"The CallerFilePathAttribute applied to parameter `{0}' will have no effect. It is overridden by the CallerLineNumberAttribute",
name);
}
}
if ((modFlags & Modifier.CallerMemberName) != 0) {
if (callerFilePath != null) {
rc.Report.Warning (7080, 1, callerFilePath.Location,
"The CallerMemberNameAttribute applied to parameter `{0}' will have no effect. It is overridden by the CallerFilePathAttribute",
name);
}
}
}
public void ResolveDefaultValue (ResolveContext rc)
@ -648,9 +713,9 @@ namespace Mono.CSharp { @@ -648,9 +713,9 @@ namespace Mono.CSharp {
} else {
builder.SetConstant (c.GetValue ());
}
} else if (default_expr.Type.IsStruct) {
} else if (default_expr.Type.IsStruct || default_expr.Type.IsGenericParameter) {
//
// Handles special case where default expression is used with value-type
// Handles special case where default expression is used with value-type or type parameter
//
// void Foo (S s = default (S)) {}
//

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

@ -82,6 +82,8 @@ namespace Mono.CSharp @@ -82,6 +82,8 @@ namespace Mono.CSharp
}
}
public abstract void PrepareEmit ();
protected override bool VerifyClsCompliance ()
{
if (!base.VerifyClsCompliance ())
@ -197,7 +199,7 @@ namespace Mono.CSharp @@ -197,7 +199,7 @@ namespace Mono.CSharp
{
}
public override MethodBuilder Define (TypeContainer parent)
public override void Define (TypeContainer parent)
{
base.Define (parent);
@ -205,12 +207,7 @@ namespace Mono.CSharp @@ -205,12 +207,7 @@ namespace Mono.CSharp
method_data = new MethodData (method, ModFlags, flags, this);
if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
return null;
method_data.DefineMethodBuilder (parent.PartialContainer, ParameterInfo);
return method_data.MethodBuilder;
method_data.Define (parent.PartialContainer, method.GetFullName (MemberName));
}
public override TypeSpec ReturnType {
@ -262,7 +259,7 @@ namespace Mono.CSharp @@ -262,7 +259,7 @@ namespace Mono.CSharp
}
}
public override MethodBuilder Define (TypeContainer parent)
public override void Define (TypeContainer parent)
{
parameters.Resolve (this);
@ -272,12 +269,7 @@ namespace Mono.CSharp @@ -272,12 +269,7 @@ namespace Mono.CSharp
method_data = new MethodData (method, ModFlags, flags, this);
if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
return null;
method_data.DefineMethodBuilder (parent.PartialContainer, ParameterInfo);
return method_data.MethodBuilder;
method_data.Define (parent.PartialContainer, method.GetFullName (MemberName));
}
public override TypeSpec ReturnType {
@ -334,7 +326,7 @@ namespace Mono.CSharp @@ -334,7 +326,7 @@ namespace Mono.CSharp
return method.IsClsComplianceRequired ();
}
public virtual MethodBuilder Define (TypeContainer parent)
public virtual void Define (TypeContainer parent)
{
var container = parent.PartialContainer;
@ -369,8 +361,6 @@ namespace Mono.CSharp @@ -369,8 +361,6 @@ namespace Mono.CSharp
if (Compiler.Settings.WriteMetadataOnly)
block = null;
}
return null;
}
public bool HasCustomAccessModifier {
@ -522,7 +512,16 @@ namespace Mono.CSharp @@ -522,7 +512,16 @@ namespace Mono.CSharp
// Check base property accessors conflict
//
var base_prop = (PropertySpec) base_member;
if (Get != null) {
if (Get == null) {
if ((ModFlags & Modifiers.SEALED) != 0 && base_prop.HasGet && !base_prop.Get.IsAccessible (this)) {
// TODO: Should be different error code but csc uses for some reason same
Report.SymbolRelatedToPreviousError (base_prop);
Report.Error (545, Location,
"`{0}': cannot override because `{1}' does not have accessible get accessor",
GetSignatureForError (), base_prop.GetSignatureForError ());
ok = false;
}
} else {
if (!base_prop.HasGet) {
if (ok) {
Report.SymbolRelatedToPreviousError (base_prop);
@ -539,7 +538,16 @@ namespace Mono.CSharp @@ -539,7 +538,16 @@ namespace Mono.CSharp
}
}
if (Set != null) {
if (Set == null) {
if ((ModFlags & Modifiers.SEALED) != 0 && base_prop.HasSet && !base_prop.Set.IsAccessible (this)) {
// TODO: Should be different error code but csc uses for some reason same
Report.SymbolRelatedToPreviousError (base_prop);
Report.Error (546, Location,
"`{0}': cannot override because `{1}' does not have accessible set accessor",
GetSignatureForError (), base_prop.GetSignatureForError ());
ok = false;
}
} else {
if (!base_prop.HasSet) {
if (ok) {
Report.SymbolRelatedToPreviousError (base_prop);
@ -624,24 +632,14 @@ namespace Mono.CSharp @@ -624,24 +632,14 @@ namespace Mono.CSharp
if (Get != null) {
spec.Get = Get.Spec;
var method = Get.Spec.GetMetaInfo () as MethodBuilder;
if (method != null) {
PropertyBuilder.SetGetMethod (method);
Parent.MemberCache.AddMember (this, method.Name, Get.Spec);
}
Parent.MemberCache.AddMember (this, Get.Spec.Name, Get.Spec);
} else {
CheckMissingAccessor (kind, parameters, true);
}
if (Set != null) {
spec.Set = Set.Spec;
var method = Set.Spec.GetMetaInfo () as MethodBuilder;
if (method != null) {
PropertyBuilder.SetSetMethod (method);
Parent.MemberCache.AddMember (this, method.Name, Set.Spec);
}
Parent.MemberCache.AddMember (this, Set.Spec.Name, Set.Spec);
} else {
CheckMissingAccessor (kind, parameters, false);
}
@ -681,6 +679,25 @@ namespace Mono.CSharp @@ -681,6 +679,25 @@ namespace Mono.CSharp
}
}
public override void PrepareEmit ()
{
AccessorFirst.PrepareEmit ();
if (AccessorSecond != null)
AccessorSecond.PrepareEmit ();
if (get != null) {
var method = Get.Spec.GetMetaInfo () as MethodBuilder;
if (method != null)
PropertyBuilder.SetGetMethod (method);
}
if (set != null) {
var method = Set.Spec.GetMetaInfo () as MethodBuilder;
if (method != null)
PropertyBuilder.SetSetMethod (method);
}
}
protected override void SetMemberName (MemberName new_name)
{
base.SetMemberName (new_name);
@ -859,10 +876,10 @@ namespace Mono.CSharp @@ -859,10 +876,10 @@ namespace Mono.CSharp
{
}
public override MethodBuilder Define (TypeContainer ds)
public override void Define (TypeContainer ds)
{
CheckAbstractAndExtern (block != null);
return base.Define (ds);
base.Define (ds);
}
public override string GetSignatureForError ()
@ -1129,9 +1146,6 @@ namespace Mono.CSharp @@ -1129,9 +1146,6 @@ namespace Mono.CSharp
return true;
}
if (Add.IsInterfaceImplementation)
SetIsUsed ();
backing_field = new Field (Parent,
new TypeExpression (MemberType, Location),
Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
@ -1205,7 +1219,7 @@ namespace Mono.CSharp @@ -1205,7 +1219,7 @@ namespace Mono.CSharp
return method.IsClsComplianceRequired ();
}
public virtual MethodBuilder Define (TypeContainer parent)
public virtual void Define (TypeContainer parent)
{
// Fill in already resolved event type to speed things up and
// avoid confusing duplicate errors
@ -1216,17 +1230,13 @@ namespace Mono.CSharp @@ -1216,17 +1230,13 @@ namespace Mono.CSharp
method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
return null;
method_data.DefineMethodBuilder (parent.PartialContainer, ParameterInfo);
return;
if (Compiler.Settings.WriteMetadataOnly)
block = null;
Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
Spec.IsAccessor = true;
return method_data.MethodBuilder;
}
public override TypeSpec ReturnType {
@ -1240,6 +1250,12 @@ namespace Mono.CSharp @@ -1240,6 +1250,12 @@ namespace Mono.CSharp
return method.GetAttributeObsolete ();
}
public MethodData MethodData {
get {
return method_data;
}
}
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
@ -1338,23 +1354,16 @@ namespace Mono.CSharp @@ -1338,23 +1354,16 @@ namespace Mono.CSharp
//
// Now define the accessors
//
var AddBuilder = Add.Define (Parent);
if (AddBuilder == null)
return false;
var RemoveBuilder = remove.Define (Parent);
if (RemoveBuilder == null)
return false;
add.Define (Parent);
remove.Define (Parent);
EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
EventBuilder.SetAddOnMethod (AddBuilder);
EventBuilder.SetRemoveOnMethod (RemoveBuilder);
spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
Parent.MemberCache.AddMember (this, AddBuilder.Name, Add.Spec);
Parent.MemberCache.AddMember (this, RemoveBuilder.Name, remove.Spec);
Parent.MemberCache.AddMember (this, Add.Spec.Name, Add.Spec);
Parent.MemberCache.AddMember (this, Remove.Spec.Name, remove.Spec);
return true;
}
@ -1376,6 +1385,15 @@ namespace Mono.CSharp @@ -1376,6 +1385,15 @@ namespace Mono.CSharp
base.Emit ();
}
public override void PrepareEmit ()
{
add.PrepareEmit ();
remove.PrepareEmit ();
EventBuilder.SetAddOnMethod (add.MethodData.MethodBuilder);
EventBuilder.SetRemoveOnMethod (remove.MethodData.MethodBuilder);
}
public override void WriteDebugSymbol (MonoSymbolFile file)
{
add.WriteDebugSymbol (file);
@ -1465,7 +1483,7 @@ namespace Mono.CSharp @@ -1465,7 +1483,7 @@ namespace Mono.CSharp
this.parameters = parameters;
}
public override MethodBuilder Define (TypeContainer parent)
public override void Define (TypeContainer parent)
{
// Disable reporting, parameters are resolved twice
Report.DisableReporting ();
@ -1475,7 +1493,7 @@ namespace Mono.CSharp @@ -1475,7 +1493,7 @@ namespace Mono.CSharp
Report.EnableReporting ();
}
return base.Define (parent);
base.Define (parent);
}
public override ParametersCompiled ParameterInfo {

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

@ -56,7 +56,9 @@ namespace Mono.CSharp { @@ -56,7 +56,9 @@ namespace Mono.CSharp {
3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
3021, 3022, 3023, 3024, 3026, 3027,
4014
4014, 4024, 4025, 4026,
7035, 7080, 7081, 7082, 7095,
8009,
};
static HashSet<int> AllWarningsHashSet;

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

@ -28,9 +28,10 @@ namespace Mono.CSharp { @@ -28,9 +28,10 @@ namespace Mono.CSharp {
V_3 = 3,
V_4 = 4,
V_5 = 5,
V_6 = 6,
Future = 100,
Default = LanguageVersion.V_5,
Default = LanguageVersion.Future,
}
public enum RuntimeVersion
@ -1136,11 +1137,13 @@ namespace Mono.CSharp { @@ -1136,11 +1137,13 @@ namespace Mono.CSharp {
switch (value.ToLowerInvariant ()) {
case "iso-1":
case "1":
settings.Version = LanguageVersion.ISO_1;
return ParseResult.Success;
case "default":
settings.Version = LanguageVersion.Default;
return ParseResult.Success;
case "2":
case "iso-2":
settings.Version = LanguageVersion.ISO_2;
return ParseResult.Success;
@ -1153,12 +1156,15 @@ namespace Mono.CSharp { @@ -1153,12 +1156,15 @@ namespace Mono.CSharp {
case "5":
settings.Version = LanguageVersion.V_5;
return ParseResult.Success;
case "6":
settings.Version = LanguageVersion.V_6;
return ParseResult.Success;
case "future":
settings.Version = LanguageVersion.Future;
return ParseResult.Success;
}
report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', `3', `4', `5', `Default' or `Future'", value);
report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', Default or value in range 1 to 6", value);
return ParseResult.Error;
case "/codepage":

651
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/statement.cs

File diff suppressed because it is too large Load Diff

11
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/typespec.cs

@ -295,6 +295,12 @@ namespace Mono.CSharp @@ -295,6 +295,12 @@ namespace Mono.CSharp
}
}
public bool IsStructOrEnum {
get {
return (Kind & (MemberKind.Struct | MemberKind.Enum)) != 0;
}
}
public bool IsTypeBuilder {
get {
#if STATIC
@ -1930,6 +1936,11 @@ namespace Mono.CSharp @@ -1930,6 +1936,11 @@ namespace Mono.CSharp
return ac;
}
public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
{
return Element.ResolveMissingDependencies (caller);
}
}
class ReferenceContainer : ElementTypeSpec

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/Script.cs

@ -624,7 +624,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -624,7 +624,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
}
}
public static class ExtMethods
static class ExtMethods
{
public static void ContinueScript (this Task task, Action act)
{

3
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CSharpResolver.cs

@ -1586,7 +1586,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver @@ -1586,7 +1586,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
resultType = def;
if (firstResult == null || !TopLevelTypeDefinitionIsAccessible(firstResult.GetDefinition())) {
firstResult = resultType;
if (TopLevelTypeDefinitionIsAccessible(resultType.GetDefinition()))
firstResult = resultType;
} else if (TopLevelTypeDefinitionIsAccessible(def)) {
return new AmbiguousTypeResolveResult(firstResult);
}

4
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/ResolveAtLocation.cs

@ -93,8 +93,10 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver @@ -93,8 +93,10 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return null;
if (node.Parent is ObjectCreateExpression && node.Role == Roles.Type) {
node = node.Parent;
} else if (node is ThisReferenceExpression && node.Parent is IndexerExpression) {
node = node.Parent;
}
InvocationExpression parentInvocation = null;
if ((node is IdentifierExpression || node is MemberReferenceExpression || node is PointerReferenceExpression) && node.Role != Roles.Argument) {
// we also need to resolve the invocation

5
src/Libraries/NRefactory/ICSharpCode.NRefactory.ConsistencyCheck/CSharpProject.cs

@ -126,7 +126,10 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck @@ -126,7 +126,10 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck
projectInstance.Build("ResolveAssemblyReferences", new [] { new ConsoleLogger(LoggerVerbosity.Minimal) });
var items = projectInstance.GetItems("_ResolveAssemblyReferenceResolvedFiles");
string baseDirectory = Path.GetDirectoryName(this.FileName);
return items.Select(i => Path.Combine(baseDirectory, i.GetMetadataValue("Identity")));
var result = items.Select(i => Path.Combine(baseDirectory, i.GetMetadataValue("Identity"))).ToList();
if (!result.Any(t => t.Contains("mscorlib") || t.Contains("System.Runtime")))
result.Add(typeof(object).Assembly.Location);
return result;
}
static bool? GetBoolProperty(Microsoft.Build.Evaluation.Project p, string propertyName)

9
src/Libraries/NRefactory/ICSharpCode.NRefactory.ConsistencyCheck/Xml/XmlReaderTest.cs

@ -89,14 +89,7 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck.Xml @@ -89,14 +89,7 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck.Xml
static string ToString(object val)
{
if (val == null)
return "null";
else if (val is string)
return "\"" + TextWriterTokenWriter.ConvertString((string)val) + "\"";
else if (val is char)
return "'" + TextWriterTokenWriter.ConvertChar((char)val) + "'";
else
return val.ToString();
return TextWriterTokenWriter.PrintPrimitiveValue(val);
}
}
}

83
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/ObjectInitializerTests.cs

@ -751,7 +751,7 @@ class C : S @@ -751,7 +751,7 @@ class C : S
public void TestUnfinishedDictionaryInitializer()
{
CodeCompletionBugTests.CombinedProviderTest(
@"class Test
@"class Test
{
public static void Main(string [] args)
{
@ -764,7 +764,88 @@ class C : S @@ -764,7 +764,88 @@ class C : S
provider => {
Assert.IsNotNull(provider.Find("args"), "'args' not found.");
});
}
/// <summary>
/// Bug 19908 - [Forms] Autocomplete doesn't work for the Children property of Forms layouts
/// </summary>
[Test]
public void TestBug19908()
{
CodeCompletionBugTests.CombinedProviderTest(
@"using System.Collections.Generic;
class Foo
{
public List<int> Children { get {} }
}
class Test
{
public static void Main(string [] args)
{
var dict = new Foo {
$c$
}
}
}
",
provider => Assert.IsNotNull(provider.Find("Children"), "'Children' not found."));
}
[Test]
public void TestBug19908_Case2()
{
CodeCompletionBugTests.CombinedProviderTest(
@"using System.Collections.Generic;
class Foo
{
public IList<int> Children { get {} }
}
class Test
{
public static void Main(string [] args)
{
var dict = new Foo {
$c$
}
}
}
",
provider => {
Assert.IsNotNull(provider.Find("Children"), "'Children' not found.");
});
}
/// <summary>
/// Bug 20110 - [Forms] Autocomplete doesn't work for the Placeholder property
/// </summary>
[Test]
public void TestBug20110()
{
CodeCompletionBugTests.CombinedProviderTest(
@"
public class Entry
{
public string Placeholder { get; set; }
}
class Test
{
public static void Main(string [] args)
{
var dict = new Entry {
$c$
};
}
}
",
provider => Assert.IsNotNull(provider.Find("Placeholder"), "'Children' not found."));
}
}
}

54
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/ParameterCompletionTests.cs

@ -632,6 +632,41 @@ class TestClass @@ -632,6 +632,41 @@ class TestClass
Assert.IsNotNull (provider, "provider was not created.");
Assert.AreEqual (1, provider.Count);
}
[Test]
public void TestMethodParameterWithSpacesTabsNewLines ()
{
var provider = CreateProvider (@"class TestClass
{
public int TestMe (int x) { return 0; }
public void Test ()
{
$TestMe (
$
}
}");
Assert.IsNotNull (provider, "provider was not created.");
Assert.AreEqual (1, provider.Count);
}
[Test]
public void TestMethodParameterNestedArray ()
{
var provider = CreateProvider (@"using System;
class TestClass
{
TestClass ()
{
var str = new string[2,2];
$Console.WriteLine ( str [1,$
}
}
");
Assert.IsNotNull (provider, "provider was not created.");
Assert.AreEqual (1, provider.Count);
}
/// Bug 599 - Regression: No intellisense over Func delegate
@ -1230,7 +1265,6 @@ class NUnitTestClass { @@ -1230,7 +1265,6 @@ class NUnitTestClass {
/// <summary>
/// Bug 12824 - Invalid argument intellisense inside lambda
/// </summary>
[Ignore("Parser bug.")]
[Test]
public void TestBug12824 ()
{
@ -1250,5 +1284,23 @@ public class MyEventArgs @@ -1250,5 +1284,23 @@ public class MyEventArgs
string name = provider.Data.First().FullName;
Assert.AreEqual ("System.Exception..ctor", name);
}
[Test]
public void TestAfterGreaterSign ()
{
var provider = CreateProvider (@"
class Test
{
static void Foo (int num) {}
public static void Main (string[] args)
{
int i = 0;
if (i > 0)
Foo ($
}
}");
Assert.AreEqual (1, provider.Count);
Assert.AreEqual (1, provider.GetParameterCount (0));
}
}
}

14
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/InconsistentNamingTests.cs

@ -516,7 +516,19 @@ class MyClass : Base { public override int Method (int Param) {} }"; @@ -516,7 +516,19 @@ class MyClass : Base { public override int Method (int Param) {} }";
rule.GetErrorMessage(new TestRefactoringContext (null, TextLocation.Empty, null), "pascalCase_12_____12323", out suggestedNames);
Assert.IsTrue(suggestedNames.Contains("PascalCase_12_12323"));
}
/// <summary>
/// Bug in Xamarin Studio "Warning: no known errors"
/// </summary>
[Test]
public void TestCase70925()
{
var rule = new NamingRule(AffectedEntity.Field);
rule.NamingStyle = NamingStyle.PascalCase;
System.Collections.Generic.IList<string> suggestedNames;
rule.GetErrorMessage(new TestRefactoringContext (null, TextLocation.Empty, null), "_taskStatus", out suggestedNames);
Assert.IsTrue(suggestedNames.Contains("TaskStatus"));
}
}
}

77
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/ReplaceWithSingleCallToAverageIssueTests.cs

@ -0,0 +1,77 @@ @@ -0,0 +1,77 @@
//
// ReplaceWithSingleCallToAverageTests.cs
//
// Author:
// Marius Ungureanu <marius.ungureanu@xamarin.com>
//
// Copyright (c) 2014 Xamarin <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 NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.CodeActions;
namespace ICSharpCode.NRefactory.CSharp.CodeIssues
{
[TestFixture]
public class ReplaceWithSingleCallToAverageIssueTests : InspectionActionTestBase
{
[Test]
public void TestSimpleCase()
{
var input = @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
var bla = arr.Select (x => x * 2).Average ();
}
}";
TestRefactoringContext context;
var issues = GetIssues(new ReplaceWithSingleCallToAverageIssue(), input, out context);
Assert.AreEqual(1, issues.Count);
CheckFix(context, issues, @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
var bla = arr.Average (x => x * 2);
}
}");
}
[Test]
public void TestDisable()
{
var input = @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
// ReSharper disable ReplaceWithSingleCallToAverage
var bla = arr.Select (x => x * 2).Average ();
}
}";
TestRefactoringContext context;
var issues = GetIssues(new ReplaceWithSingleCallToAverageIssue(), input, out context);
Assert.AreEqual(0, issues.Count);
}
}
}

77
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/ReplaceWithSingleCallToMaxIssueTests.cs

@ -0,0 +1,77 @@ @@ -0,0 +1,77 @@
//
// ReplaceWithSingleCallToMaxTests.cs
//
// Author:
// Marius Ungureanu <marius.ungureanu@xamarin.com>
//
// Copyright (c) 2014 Xamarin <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 NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.CodeActions;
namespace ICSharpCode.NRefactory.CSharp.CodeIssues
{
[TestFixture]
public class ReplaceWithSingleCallToMaxIssueTests : InspectionActionTestBase
{
[Test]
public void TestSimpleCase()
{
var input = @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
var bla = arr.Select (x => x * 2).Max ();
}
}";
TestRefactoringContext context;
var issues = GetIssues(new ReplaceWithSingleCallToMaxIssue(), input, out context);
Assert.AreEqual(1, issues.Count);
CheckFix(context, issues, @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
var bla = arr.Max (x => x * 2);
}
}");
}
[Test]
public void TestDisable()
{
var input = @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
// ReSharper disable ReplaceWithSingleCallToMax
var bla = arr.Select (x => x * 2).Max ();
}
}";
TestRefactoringContext context;
var issues = GetIssues(new ReplaceWithSingleCallToMaxIssue(), input, out context);
Assert.AreEqual(0, issues.Count);
}
}
}

77
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/ReplaceWithSingleCallToMinIssueTests.cs

@ -0,0 +1,77 @@ @@ -0,0 +1,77 @@
//
// ReplaceWithSingleCallToMinTests.cs
//
// Author:
// Marius Ungureanu <marius.ungureanu@xamarin.com>
//
// Copyright (c) 2014 Xamarin <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 NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.CodeActions;
namespace ICSharpCode.NRefactory.CSharp.CodeIssues
{
[TestFixture]
public class ReplaceWithSingleCallToMinIssueTests : InspectionActionTestBase
{
[Test]
public void TestSimpleCase()
{
var input = @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
var bla = arr.Select (x => x * 2).Min ();
}
}";
TestRefactoringContext context;
var issues = GetIssues(new ReplaceWithSingleCallToMinIssue(), input, out context);
Assert.AreEqual(1, issues.Count);
CheckFix(context, issues, @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
var bla = arr.Min (x => x * 2);
}
}");
}
[Test]
public void TestDisable()
{
var input = @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
// ReSharper disable ReplaceWithSingleCallToMin
var bla = arr.Select (x => x * 2).Min ();
}
}";
TestRefactoringContext context;
var issues = GetIssues(new ReplaceWithSingleCallToMinIssue(), input, out context);
Assert.AreEqual(0, issues.Count);
}
}
}

77
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/ReplaceWithSingleCallToSumIssueTests.cs

@ -0,0 +1,77 @@ @@ -0,0 +1,77 @@
//
// ReplaceWithSingleCallToSumTests.cs
//
// Author:
// Marius Ungureanu <marius.ungureanu@xamarin.com>
//
// Copyright (c) 2014 Xamarin <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 NUnit.Framework;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.CodeActions;
namespace ICSharpCode.NRefactory.CSharp.CodeIssues
{
[TestFixture]
public class ReplaceWithSingleCallToSumIssueTests : InspectionActionTestBase
{
[Test]
public void TestSimpleCase()
{
var input = @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
var bla = arr.Select (x => x * 2).Sum ();
}
}";
TestRefactoringContext context;
var issues = GetIssues(new ReplaceWithSingleCallToSumIssue(), input, out context);
Assert.AreEqual(1, issues.Count);
CheckFix(context, issues, @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
var bla = arr.Sum (x => x * 2);
}
}");
}
[Test]
public void TestDisable()
{
var input = @"using System.Linq;
public class CSharpDemo {
public void Bla () {
int[] arr;
// ReSharper disable ReplaceWithSingleCallToSum
var bla = arr.Select (x => x * 2).Sum ();
}
}";
TestRefactoringContext context;
var issues = GetIssues(new ReplaceWithSingleCallToSumIssue(), input, out context);
Assert.AreEqual(0, issues.Count);
}
}
}

1
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/UnmatchedSizeSpeicificationInArrayCreationTests.cs

@ -109,6 +109,7 @@ namespace ICSharpCode.NRefactory.CSharp.CodeIssues @@ -109,6 +109,7 @@ namespace ICSharpCode.NRefactory.CSharp.CodeIssues
");
}
[Ignore("Issue was disabled.")]
[Test]
public void TestResharperDisableRestore()
{

19
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Bugs/ParserBugTests.cs

@ -691,6 +691,25 @@ class C @@ -691,6 +691,25 @@ class C
Assert.IsNotNull(member, "M() not found.");
Assert.That(member.Modifiers, Is.EqualTo(Modifiers.Async));
}
[Test]
public void TestParseTypeReferenceBug()
{
var s = "global::Thing<int>.Done<string>";
var type = new CSharpParser().ParseTypeReference(s);
Assert.AreEqual(s, type.ToString());
}
[Test]
public void TestParseExpressionBug()
{
var s = "global::Thing<int>.Done<string>";
var expr = new CSharpParser().ParseExpression(s);
Assert.AreEqual(s, expr.ToString());
}
}
}

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeMembers/PropertyDeclarationTests.cs

@ -73,7 +73,7 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.TypeMembers @@ -73,7 +73,7 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.TypeMembers
CSharpParser parser = new CSharpParser();
SyntaxTree syntaxTree = parser.Parse(code);
PropertyDeclaration pd = (PropertyDeclaration)syntaxTree.Children.Where (c => c.Role != Roles.NewLine).Single().GetChildByRole(Roles.TypeMemberRole);
PropertyDeclaration pd = (PropertyDeclaration)syntaxTree.Children.Single(c => c.Role != Roles.NewLine).GetChildByRole(Roles.TypeMemberRole);
Assert.AreEqual(new TextLocation(2, code.IndexOf("{\n\t\tget") - line2Pos + 1), pd.GetChildByRole(Roles.LBrace).StartLocation);
Assert.AreEqual(new TextLocation(5, 3), pd.EndLocation);
Assert.AreEqual(new TextLocation(3, code.IndexOf("{ return") - line3Pos + 1), pd.Getter.Body.StartLocation);

4
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj

@ -618,6 +618,10 @@ @@ -618,6 +618,10 @@
<Compile Include="CSharp\CodeIssues\StaticEventSubscriptionIssueTests.cs" />
<Compile Include="CSharp\CodeActions\CS1105ExtensionMethodMustBeDeclaredStaticActionTests.cs" />
<Compile Include="CSharp\CodeIssues\UnmatchedSizeSpeicificationInArrayCreationTests.cs" />
<Compile Include="CSharp\CodeIssues\ReplaceWithSingleCallToMaxIssueTests.cs" />
<Compile Include="CSharp\CodeIssues\ReplaceWithSingleCallToMinIssueTests.cs" />
<Compile Include="CSharp\CodeIssues\ReplaceWithSingleCallToSumIssueTests.cs" />
<Compile Include="CSharp\CodeIssues\ReplaceWithSingleCallToAverageIssueTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\cecil\Mono.Cecil.csproj">

181
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/IndentationTests/BlockTest.cs

@ -867,7 +867,7 @@ class Foo @@ -867,7 +867,7 @@ class Foo
class Foo
{
void Test ()
{
{
Foo (delegate
{$
", policy);
@ -884,7 +884,7 @@ class Foo @@ -884,7 +884,7 @@ class Foo
class Foo
{
void Test ()
{
{
Foo (delegate
{
}$
@ -892,6 +892,163 @@ class Foo @@ -892,6 +892,163 @@ class Foo
Assert.AreEqual("\t\t", indent.ThisLineIndent);
}
[Test]
public void TestBrackets_IndentBlocksInsideExpressions()
{
var policy = FormattingOptionsFactory.CreateAllman();
policy.IndentBlocksInsideExpressions = true;
var indent = Helper.CreateEngine(@"
class Foo
{
void Test ()
{
Foo (delegate
{$
", policy);
Assert.AreEqual("\t\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t\t", indent.NextLineIndent);
}
[Test]
public void TestBrackets_IndentBlocksInsideExpressions_ClosingBracket()
{
var policy = FormattingOptionsFactory.CreateAllman();
policy.IndentBlocksInsideExpressions = true;
var indent = Helper.CreateEngine(@"
class Foo
{
void Test ()
{
Foo (delegate
{
}$
", policy);
Assert.AreEqual("\t\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t", indent.NextLineIndent);
}
[Test]
public void TestBrackets_IndentBlocksInsideExpressions_AfterBlockAlignment()
{
var policy = FormattingOptionsFactory.CreateAllman();
policy.IndentBlocksInsideExpressions = false;
var indent = Helper.CreateEngine(@"
class Foo
{
void Test ()
{
Foo (delegate
{
},
42,$
", policy);
Assert.AreEqual("\t\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t", indent.NextLineIndent);
}
[Test]
public void TestBrackets_IndentBlocksInsideExpressions_OpenBracketOnNonEmptyLine()
{
var policy = FormattingOptionsFactory.CreateAllman();
policy.IndentBlocksInsideExpressions = true;
var indent = Helper.CreateEngine(@"
class Foo
{
void Test ()
{
Foo (delegate {
$
", policy);
Assert.AreEqual("\t\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t", indent.NextLineIndent);
}
[Test]
public void TestBrackets_IndentBlocksInsideExpressions_OpenBracketOnNonEmptyLine_ClosingBracket()
{
var policy = FormattingOptionsFactory.CreateAllman();
policy.IndentBlocksInsideExpressions = true;
var indent = Helper.CreateEngine(@"
class Foo
{
void Test ()
{
Foo (delegate {
//
},$
", policy);
Assert.AreEqual("\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t", indent.NextLineIndent);
}
[Test]
public void TestBrackets_IndentBlocksInsideExpressions_RightHandExpression()
{
var policy = FormattingOptionsFactory.CreateAllman();
policy.IndentBlocksInsideExpressions = true;
var indent = Helper.CreateEngine(@"
class Foo
{
void Test ()
{
var foo = delegate
{$
", policy);
Assert.AreEqual("\t\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t\t", indent.NextLineIndent);
}
[Test]
public void TestBrackets_IndentBlocksInsideExpressions_RightHandExpression_ClosingBracket()
{
var policy = FormattingOptionsFactory.CreateAllman();
policy.IndentBlocksInsideExpressions = true;
var indent = Helper.CreateEngine(@"
class Foo
{
void Test ()
{
var foo = delegate
{
}$
", policy);
Assert.AreEqual("\t\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t", indent.NextLineIndent);
}
[Test]
public void TestBrackets_IndentBlocksInsideExpressions_RightHandExpression_OpenBracketOnNonEmptyLine()
{
var policy = FormattingOptionsFactory.CreateAllman();
policy.IndentBlocksInsideExpressions = true;
var indent = Helper.CreateEngine(@"
class Foo
{
void Test ()
{
var foo = delegate {$
", policy);
Assert.AreEqual("\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t", indent.NextLineIndent);
}
[Test]
public void TestBrackets_IndentBlocksInsideExpressions_RightHandExpression_OpenBracketOnNonEmptyLine_ClosingBracket()
{
var policy = FormattingOptionsFactory.CreateAllman();
policy.IndentBlocksInsideExpressions = true;
var indent = Helper.CreateEngine(@"
class Foo
{
void Test ()
{
var foo = delegate {
}$
", policy);
Assert.AreEqual("\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t", indent.NextLineIndent);
}
[Test]
public void TestBrackets_ArrayCreationAsFirstParameterWithoutAlignment()
{
@ -1187,7 +1344,7 @@ class Foo @@ -1187,7 +1344,7 @@ class Foo
}
[Test]
public void TestBrackets_IndentBlocksInsideExpressions()
public void TestBrackets_IndentBlocksInsideExpressions_Allman()
{
var policy = FormattingOptionsFactory.CreateAllman();
@ -1234,5 +1391,23 @@ namespace FooBar @@ -1234,5 +1391,23 @@ namespace FooBar
Assert.AreEqual("\t\t\t\t", indent.NextLineIndent);
}
[Test]
public void TestIssue389()
{
var policy = FormattingOptionsFactory.CreateAllman();
var indent = Helper.CreateEngine(@"
public class Test
{
public void FooBar()
{
if (true)
{$
}
}
}", policy);
Assert.AreEqual("\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t", indent.NextLineIndent);
}
}
}

5
src/Libraries/NRefactory/ICSharpCode.NRefactory/Completion/CompletionExtensionMethods.cs

@ -47,9 +47,8 @@ namespace ICSharpCode.NRefactory.Completion @@ -47,9 +47,8 @@ namespace ICSharpCode.NRefactory.Completion
var browsableState = entity.Attributes.FirstOrDefault(attr => attr.AttributeType.Name == "EditorBrowsableAttribute" && attr.AttributeType.Namespace == "System.ComponentModel");
if (browsableState != null && browsableState.PositionalArguments.Count == 1) {
try {
return (System.ComponentModel.EditorBrowsableState)browsableState.PositionalArguments [0].ConstantValue;
} catch (Exception) {}
if (browsableState.PositionalArguments [0].ConstantValue is int)
return (System.ComponentModel.EditorBrowsableState)(int)browsableState.PositionalArguments [0].ConstantValue;
}
return System.ComponentModel.EditorBrowsableState.Always;
}

4
src/Libraries/NRefactory/ICSharpCode.NRefactory/Properties/GlobalAssemblyInfo.cs

@ -29,7 +29,7 @@ using System.Runtime.InteropServices; @@ -29,7 +29,7 @@ using System.Runtime.InteropServices;
// associated with an assembly.
[assembly: AssemblyCompany("ICSharpCode")]
[assembly: AssemblyProduct("SharpDevelop/MonoDevelop")]
[assembly: AssemblyCopyright("Copyright 2010-2013 AlphaSierraPapa and Xamarin Inc.")]
[assembly: AssemblyCopyright("Copyright 2010-2014 AlphaSierraPapa and Xamarin Inc.")]
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
@ -42,4 +42,4 @@ using System.Runtime.InteropServices; @@ -42,4 +42,4 @@ using System.Runtime.InteropServices;
// [AssemblyFileVersion] is the version of the NuGet package,
// Versions with breaking changes / new features should increment the 'minor' (2nd) number.
// Bugfix releases should increment the 'build' (3rd) number.
[assembly: AssemblyFileVersion("5.3.0")]
[assembly: AssemblyFileVersion("5.4.0")]

2
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAssemblyReference.cs

@ -27,6 +27,8 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation @@ -27,6 +27,8 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
public sealed class DefaultAssemblyReference : IAssemblyReference, ISupportsInterning
{
public static readonly IAssemblyReference CurrentAssembly = new CurrentAssemblyReference();
[Obsolete("The corlib is not always called 'mscorlib' (as returned by this property), but might be 'System.Runtime'.")]
public static readonly IAssemblyReference Corlib = new DefaultAssemblyReference("mscorlib");
readonly string shortName;

1
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedTypeParameter.cs

@ -55,6 +55,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation @@ -55,6 +55,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
protected virtual void FreezeInternal()
{
attributes = FreezableHelper.FreezeListAndElements(attributes);
constraints = FreezableHelper.FreezeList(constraints);
}
public DefaultUnresolvedTypeParameter(SymbolKind ownerType, int index, string name = null)

28
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/ResolvedAttributeBlob.cs

@ -142,9 +142,17 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation @@ -142,9 +142,17 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
return;
}
foreach (var ctorParameter in ctorParameterTypes.Resolve(context)) {
ResolveResult arg = reader.ReadFixedArg(ctorParameter);
positionalArguments.Add(arg);
if (arg.IsError) {
ResolveResult arg;
bool isError;
try {
arg = reader.ReadFixedArg (ctorParameter);
positionalArguments.Add(arg);
isError = arg.IsError;
} catch (Exception ex) {
Debug.WriteLine("Crash during blob decoding: " + ex);
isError = true;
}
if (isError) {
// After a decoding error, we must stop decoding the blob because
// we might have read too few bytes due to the error.
// Just fill up the remaining arguments with ErrorResolveResult:
@ -153,11 +161,15 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation @@ -153,11 +161,15 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
return;
}
}
ushort numNamed = reader.ReadUInt16();
for (int i = 0; i < numNamed; i++) {
var namedArg = reader.ReadNamedArg(attributeType);
if (namedArg.Key != null)
namedArguments.Add(namedArg);
try {
ushort numNamed = reader.ReadUInt16();
for (int i = 0; i < numNamed; i++) {
var namedArg = reader.ReadNamedArg(attributeType);
if (namedArg.Key != null)
namedArguments.Add(namedArg);
}
} catch (Exception ex) {
Debug.WriteLine("Crash during blob decoding: " + ex);
}
}
}

6
src/Libraries/NRefactory/Packages/ICSharpCode.NRefactory.nuspec

@ -2,7 +2,7 @@ @@ -2,7 +2,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
<metadata>
<id>ICSharpCode.NRefactory</id>
<version>5.3.0</version>
<version>5.4.0</version>
<title>NRefactory</title>
<authors>Daniel Grunwald, Mike Krüger, Erik Källén</authors>
<owners>Daniel Grunwald</owners>
@ -12,10 +12,10 @@ @@ -12,10 +12,10 @@
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>NRefactory supports analysis of C# source code: it includes a parser, abstract syntax tree, type system, semantic analysis (resolver), code completion, and several refactorings.</description>
<!--<releaseNotes></releaseNotes>-->
<copyright>Copyright 2010-2013 AlphaSierraPapa</copyright>
<copyright>Copyright 2010-2014 AlphaSierraPapa</copyright>
<tags>C# Parser Semantic Analysis SharpDevelop</tags>
<dependencies>
<dependency id="Mono.Cecil" version="0.9.5.2" />
<dependency id="Mono.Cecil" version="0.9.5.4" />
</dependencies>
</metadata>
<files>

1
src/Libraries/NRefactory/README

@ -123,7 +123,6 @@ Q: What is the difference between NRefactory and Roslyn? @@ -123,7 +123,6 @@ Q: What is the difference between NRefactory and Roslyn?
- NRefactory does not have VB support.
- NRefactory cannot compile code to IL; it's not a full compiler, just a frontend.
- NRefactory C# AST is mutable and supports pattern matching; Roslyn is immutable and does not have built-in pattern matching.
- NRefactory is Open Source, if you somehow can't get at the information you need, you can modify the code.
Q: What is the difference between types and type definitions?

Loading…
Cancel
Save