Browse Source

Merge remote-tracking branch 'upstream/master' into simonl

Conflicts:
	ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj
	ICSharpCode.NRefactory/ICSharpCode.NRefactory.csproj
newNRvisualizers
Simon Lindgren 14 years ago
parent
commit
9a53205b0e
  1. 116
      ICSharpCode.NRefactory.CSharp.AstVerifier/ICSharpCode.NRefactory.CSharp.AstVerifier.csproj
  2. 16
      ICSharpCode.NRefactory.CSharp/Ast/AstNodeCollection.cs
  3. 79
      ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs
  4. 65
      ICSharpCode.NRefactory.CSharp/Completion/CompletionDataWrapper.cs
  5. 7
      ICSharpCode.NRefactory.CSharp/Completion/ICompletionDataFactory.cs
  6. 21
      ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj
  7. 1
      ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs
  8. 32
      ICSharpCode.NRefactory.CSharp/Parser/CSharpParser.cs
  9. 2
      ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolFile.cs
  10. 81
      ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolTable.cs
  11. 4
      ICSharpCode.NRefactory.CSharp/Parser/mcs/SourceMethodBuilder.cs
  12. 41
      ICSharpCode.NRefactory.CSharp/Parser/mcs/anonymous.cs
  13. 16
      ICSharpCode.NRefactory.CSharp/Parser/mcs/argument.cs
  14. 16
      ICSharpCode.NRefactory.CSharp/Parser/mcs/assign.cs
  15. 14
      ICSharpCode.NRefactory.CSharp/Parser/mcs/async.cs
  16. 45
      ICSharpCode.NRefactory.CSharp/Parser/mcs/attribute.cs
  17. 40
      ICSharpCode.NRefactory.CSharp/Parser/mcs/cfold.cs
  18. 27
      ICSharpCode.NRefactory.CSharp/Parser/mcs/class.cs
  19. 16
      ICSharpCode.NRefactory.CSharp/Parser/mcs/codegen.cs
  20. 2
      ICSharpCode.NRefactory.CSharp/Parser/mcs/const.cs
  21. 25
      ICSharpCode.NRefactory.CSharp/Parser/mcs/context.cs
  22. 7354
      ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.cs
  23. 205
      ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.jay
  24. 249
      ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-tokenizer.cs
  25. 2
      ICSharpCode.NRefactory.CSharp/Parser/mcs/decl.cs
  26. 5
      ICSharpCode.NRefactory.CSharp/Parser/mcs/delegate.cs
  27. 19
      ICSharpCode.NRefactory.CSharp/Parser/mcs/doc.cs
  28. 73
      ICSharpCode.NRefactory.CSharp/Parser/mcs/driver.cs
  29. 2
      ICSharpCode.NRefactory.CSharp/Parser/mcs/dynamic.cs
  30. 108
      ICSharpCode.NRefactory.CSharp/Parser/mcs/ecore.cs
  31. 9
      ICSharpCode.NRefactory.CSharp/Parser/mcs/eval.cs
  32. 67
      ICSharpCode.NRefactory.CSharp/Parser/mcs/expression.cs
  33. 5
      ICSharpCode.NRefactory.CSharp/Parser/mcs/field.cs
  34. 56
      ICSharpCode.NRefactory.CSharp/Parser/mcs/generic.cs
  35. 53
      ICSharpCode.NRefactory.CSharp/Parser/mcs/import.cs
  36. 54
      ICSharpCode.NRefactory.CSharp/Parser/mcs/location.cs
  37. 7
      ICSharpCode.NRefactory.CSharp/Parser/mcs/membercache.cs
  38. 71
      ICSharpCode.NRefactory.CSharp/Parser/mcs/method.cs
  39. 2
      ICSharpCode.NRefactory.CSharp/Parser/mcs/module.cs
  40. 135
      ICSharpCode.NRefactory.CSharp/Parser/mcs/namespace.cs
  41. 12
      ICSharpCode.NRefactory.CSharp/Parser/mcs/nullable.cs
  42. 18
      ICSharpCode.NRefactory.CSharp/Parser/mcs/outline.cs
  43. 19
      ICSharpCode.NRefactory.CSharp/Parser/mcs/property.cs
  44. 2
      ICSharpCode.NRefactory.CSharp/Parser/mcs/report.cs
  45. 23
      ICSharpCode.NRefactory.CSharp/Parser/mcs/settings.cs
  46. 45
      ICSharpCode.NRefactory.CSharp/Parser/mcs/statement.cs
  47. 10
      ICSharpCode.NRefactory.CSharp/Parser/mcs/support.cs
  48. 38
      ICSharpCode.NRefactory.CSharp/Parser/mcs/typemanager.cs
  49. 4
      ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/GeneratePropertyAction.cs
  50. 195
      ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ImplementInterfaceAction.cs
  51. 22
      ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantThisIssue.cs
  52. 23
      ICSharpCode.NRefactory.CSharp/Refactoring/RefactoringContext.cs
  53. 68
      ICSharpCode.NRefactory.CSharp/Refactoring/TypeSystemAstBuilder.cs
  54. 2
      ICSharpCode.NRefactory.CSharp/Resolver/CSharpAstResolver.cs
  55. 11
      ICSharpCode.NRefactory.CSharp/Resolver/CSharpInvocationResolveResult.cs
  56. 2
      ICSharpCode.NRefactory.CSharp/Resolver/CSharpResolver.cs
  57. 5
      ICSharpCode.NRefactory.CSharp/Resolver/Log.cs
  58. 55
      ICSharpCode.NRefactory.CSharp/Resolver/OverloadResolution.cs
  59. 148
      ICSharpCode.NRefactory.CSharp/Resolver/ResolveVisitor.cs
  60. 15
      ICSharpCode.NRefactory.CSharp/TypeSystem/TypeSystemConvertVisitor.cs
  61. 18
      ICSharpCode.NRefactory.ConsistencyCheck/ICSharpCode.NRefactory.ConsistencyCheck.csproj
  62. 30
      ICSharpCode.NRefactory.Demo/ICSharpCode.NRefactory.Demo.csproj
  63. 224
      ICSharpCode.NRefactory.GtkDemo/ICSharpCode.NRefactory.GtkDemo.csproj
  64. 6
      ICSharpCode.NRefactory.Tests/CSharp/CodeActions/ContextActionTestBase.cs
  65. 28
      ICSharpCode.NRefactory.Tests/CSharp/CodeActions/GeneratePropertyTests.cs
  66. 148
      ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/BrowsableAttributeTests.cs
  67. 78
      ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/CodeCompletionBugTests.cs
  68. 24
      ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/DelegateContextTests.cs
  69. 19
      ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/PreprocessorDirectiveTests.cs
  70. 70
      ICSharpCode.NRefactory.Tests/CSharp/Resolver/InvocationTests.cs
  71. 41
      ICSharpCode.NRefactory.Tests/CSharp/Resolver/MethodTests.cs
  72. 43
      ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj
  73. 8
      ICSharpCode.NRefactory.Tests/TypeSystem/CecilLoaderTests.cs
  74. 22
      ICSharpCode.NRefactory.Xml/ICSharpCode.NRefactory.Xml.csproj
  75. 73
      ICSharpCode.NRefactory/Completion/CompletionExtensionMethods.cs
  76. 37
      ICSharpCode.NRefactory/ICSharpCode.NRefactory.csproj
  77. 81
      ICSharpCode.NRefactory/Semantics/NamedArgumentResolveResult.cs
  78. 124
      ICSharpCode.NRefactory/TypeSystem/CecilLoader.cs
  79. 46
      ICSharpCode.NRefactory/TypeSystem/IAttribute.cs
  80. 20
      ICSharpCode.NRefactory/TypeSystem/IFreezable.cs
  81. 22
      ICSharpCode.NRefactory/TypeSystem/IInterningProvider.cs
  82. 26
      ICSharpCode.NRefactory/TypeSystem/ISupportsInterning.cs
  83. 1
      ICSharpCode.NRefactory/TypeSystem/IType.cs
  84. 20
      ICSharpCode.NRefactory/TypeSystem/ITypeDefinition.cs
  85. 18
      ICSharpCode.NRefactory/TypeSystem/ITypeReference.cs
  86. 36
      ICSharpCode.NRefactory/TypeSystem/IVariable.cs
  87. 97
      ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAttribute.cs
  88. 41
      ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultResolvedTypeDefinition.cs
  89. 3
      ICSharpCode.NRefactory/Utils/LazyInit.cs
  90. 134
      ICSharpCode.NRefactory/Utils/MultiDictionary.cs
  91. 78
      NRefactory.sln

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

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

16
ICSharpCode.NRefactory.CSharp/Ast/AstNodeCollection.cs

@ -204,5 +204,21 @@ namespace ICSharpCode.NRefactory.CSharp
{ {
node.InsertChildBefore(existingItem, newItem, role); node.InsertChildBefore(existingItem, newItem, role);
} }
/// <summary>
/// Applies the <paramref name="visitor"/> to all nodes in this collection.
/// </summary>
public void AcceptVisitor(IAstVisitor visitor)
{
AstNode next;
for (AstNode cur = node.FirstChild; cur != null; cur = next) {
Debug.Assert(cur.Parent == node);
// Remember next before yielding cur.
// This allows removing/replacing nodes while iterating through the list.
next = cur.NextSibling;
if (cur.Role == role)
cur.AcceptVisitor(visitor);
}
}
} }
} }

79
ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs

@ -1,4 +1,4 @@
// //
// CSharpCompletionEngine.cs // CSharpCompletionEngine.cs
// //
// Author: // Author:
@ -48,7 +48,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
public string EolMarker { get; set; } public string EolMarker { get; set; }
public string IndentString { get; set; } public string IndentString { get; set; }
#endregion #endregion
#region Result properties #region Result properties
public bool AutoCompleteEmptyMatch; public bool AutoCompleteEmptyMatch;
@ -262,7 +262,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return contextList.Result; return contextList.Result;
} }
foreach (var m in initializerResult.Item1.Type.GetMembers (m => !m.IsSynthetic && m.IsPublic && (m.EntityType == EntityType.Property || m.EntityType == EntityType.Field))) { foreach (var m in initializerResult.Item1.Type.GetMembers (m => m.IsPublic && (m.EntityType == EntityType.Property || m.EntityType == EntityType.Field))) {
contextList.AddMember(m); contextList.AddMember(m);
} }
@ -543,7 +543,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var wrapper = new CompletionDataWrapper(this); var wrapper = new CompletionDataWrapper(this);
if (currentType != null) { if (currentType != null) {
// bool includeProtected = DomType.IncludeProtected (dom, typeFromDatabase, resolver.CallingType); // bool includeProtected = DomType.IncludeProtected (dom, typeFromDatabase, resolver.CallingType);
foreach (var method in currentType.Methods) { foreach (var method in ctx.CurrentTypeDefinition.Methods) {
if (MatchDelegate(delegateType, method) /*&& method.IsAccessibleFrom (dom, resolver.CallingType, resolver.CallingMember, includeProtected) &&*/) { if (MatchDelegate(delegateType, method) /*&& method.IsAccessibleFrom (dom, resolver.CallingType, resolver.CallingMember, includeProtected) &&*/) {
wrapper.AddMember(method); wrapper.AddMember(method);
// data.SetText (data.CompletionText + ";"); // data.SetText (data.CompletionText + ";");
@ -1200,16 +1200,16 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
wrapper.AddVariable(variable); wrapper.AddVariable(variable);
} }
} }
if (currentMember is IUnresolvedParameterizedMember && !(node is AstType)) { if (state.CurrentMember is IParameterizedMember && !(node is AstType)) {
var param = (IParameterizedMember)currentMember.CreateResolved(ctx); var param = (IParameterizedMember)state.CurrentMember;
foreach (var p in param.Parameters) { foreach (var p in param.Parameters) {
wrapper.AddVariable(p); wrapper.AddVariable(p);
} }
} }
if (currentMember is IUnresolvedMethod) { if (state.CurrentMember is IMethod) {
var method = (IUnresolvedMethod)currentMember; var method = (IMethod)state.CurrentMember;
foreach (var p in method.TypeParameters) { foreach (var p in method.TypeParameters) {
wrapper.AddTypeParameter(p); wrapper.AddTypeParameter(p);
} }
@ -1319,10 +1319,8 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
{ {
var lookup = new MemberLookup(ctx.CurrentTypeDefinition, Compilation.MainAssembly); var lookup = new MemberLookup(ctx.CurrentTypeDefinition, Compilation.MainAssembly);
if (currentType != null) { if (currentType != null) {
for (var ct = currentType; ct != null; ct = ct.DeclaringTypeDefinition) { for (var ct = ctx.CurrentTypeDefinition; ct != null; ct = ct.DeclaringTypeDefinition) {
foreach (var nestedType in ct.NestedTypes) { foreach (var nestedType in ct.NestedTypes) {
if (nestedType.IsSynthetic)
continue;
string name = nestedType.Name; string name = nestedType.Name;
if (IsAttributeContext(node) && name.EndsWith("Attribute") && name.Length > "Attribute".Length) { if (IsAttributeContext(node) && name.EndsWith("Attribute") && name.Length > "Attribute".Length) {
name = name.Substring(0, name.Length - "Attribute".Length); name = name.Substring(0, name.Length - "Attribute".Length);
@ -1333,7 +1331,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
continue; continue;
} }
var type = typePred(nestedType.Resolve(ctx)); var type = typePred(nestedType);
if (type != null) { if (type != null) {
var a2 = wrapper.AddType(type, name); var a2 = wrapper.AddType(type, name);
if (a2 != null && callback != null) { if (a2 != null && callback != null) {
@ -1351,8 +1349,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (member is IMethod && ((IMethod)member).FullName == "System.Object.Finalize") { if (member is IMethod && ((IMethod)member).FullName == "System.Object.Finalize") {
continue; continue;
} }
if (member.IsSynthetic)
continue;
if (member.EntityType == EntityType.Operator) { if (member.EntityType == EntityType.Operator) {
continue; continue;
} }
@ -1369,7 +1365,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
} }
var declaring = def.DeclaringTypeDefinition; var declaring = def.DeclaringTypeDefinition;
while (declaring != null) { while (declaring != null) {
foreach (var member in declaring.GetMembers (m => m.IsStatic && !m.IsSynthetic)) { foreach (var member in declaring.GetMembers (m => m.IsStatic)) {
if (memberPred == null || memberPred(member)) { if (memberPred == null || memberPred(member)) {
wrapper.AddMember(member); wrapper.AddMember(member);
} }
@ -1378,8 +1374,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
} }
} }
} }
foreach (var p in currentType.TypeParameters) { if (ctx.CurrentTypeDefinition != null) {
wrapper.AddTypeParameter(p); foreach (var p in ctx.CurrentTypeDefinition.TypeParameters) {
wrapper.AddTypeParameter(p);
}
} }
} }
var scope = ctx.CurrentUsingScope; var scope = ctx.CurrentUsingScope;
@ -1916,7 +1914,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return; return;
} }
foreach (var m in curType.GetMembers ().Reverse ()) { foreach (var m in curType.GetMembers ().Reverse ()) {
if (m.IsSynthetic || curType.Kind != TypeKind.Interface && !m.IsOverridable) { if (curType.Kind != TypeKind.Interface && !m.IsOverridable) {
continue; continue;
} }
// filter out the "Finalize" methods, because finalizers should be done with destructors. // filter out the "Finalize" methods, because finalizers should be done with destructors.
@ -1987,7 +1985,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return result; return result;
} }
bool MatchDelegate(IType delegateType, IUnresolvedMethod method) bool MatchDelegate(IType delegateType, IMethod method)
{ {
var delegateMethod = delegateType.GetDelegateInvokeMethod(); var delegateMethod = delegateType.GetDelegateInvokeMethod();
if (delegateMethod == null || delegateMethod.Parameters.Count != method.Parameters.Count) { if (delegateMethod == null || delegateMethod.Parameters.Count != method.Parameters.Count) {
@ -1995,7 +1993,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
} }
for (int i = 0; i < delegateMethod.Parameters.Count; i++) { for (int i = 0; i < delegateMethod.Parameters.Count; i++) {
if (!delegateMethod.Parameters [i].Type.Equals(method.Parameters [i].Type.Resolve(ctx))) { if (!delegateMethod.Parameters [i].Type.Equals(method.Parameters [i].Type)) {
return false; return false;
} }
} }
@ -2016,34 +2014,47 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
"delegate", "delegate",
"Creates anonymous delegate.", "Creates anonymous delegate.",
"delegate {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString "delegate {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
); );
} }
var sb = new StringBuilder("("); var sb = new StringBuilder("(");
var sbWithoutTypes = new StringBuilder("("); var sbWithoutTypes = new StringBuilder("(");
var state = GetState();
var builder = new TypeSystemAstBuilder(state);
for (int k = 0; k < delegateMethod.Parameters.Count; k++) { for (int k = 0; k < delegateMethod.Parameters.Count; k++) {
if (k > 0) { if (k > 0) {
sb.Append(", "); sb.Append(", ");
sbWithoutTypes.Append(", "); sbWithoutTypes.Append(", ");
} }
var parameterType = delegateMethod.Parameters [k].Type; var convertedParameter = builder.ConvertParameter (delegateMethod.Parameters [k]);
sb.Append(GetShortType(parameterType, GetState())); if (convertedParameter.ParameterModifier == ParameterModifier.Params)
sb.Append(" "); convertedParameter.ParameterModifier = ParameterModifier.None;
sb.Append(delegateMethod.Parameters [k].Name); sb.Append(convertedParameter.GetText (FormattingPolicy));
sbWithoutTypes.Append(delegateMethod.Parameters [k].Name); sbWithoutTypes.Append(delegateMethod.Parameters [k].Name);
} }
sb.Append(")"); sb.Append(")");
sbWithoutTypes.Append(")"); sbWithoutTypes.Append(")");
completionList.AddCustom( completionList.AddCustom(
"delegate" + sb, "delegate" + sb,
"Creates anonymous delegate.", "Creates anonymous delegate.",
"delegate" + sb + " {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString "delegate" + sb + " {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
); );
if (!completionList.Result.Any(data => data.DisplayText == sbWithoutTypes.ToString())) {
if (!completionList.Result.Any(data => data.DisplayText == sb.ToString())) {
completionList.AddCustom(
sb.ToString(),
"Creates typed lambda expression.",
sb + " => |" + (addSemicolon ? ";" : "")
);
}
if (!delegateMethod.Parameters.Any (p => p.IsOut || p.IsRef) && !completionList.Result.Any(data => data.DisplayText == sbWithoutTypes.ToString())) {
completionList.AddCustom( completionList.AddCustom(
sbWithoutTypes.ToString(), sbWithoutTypes.ToString(),
"Creates lambda expression.", "Creates lambda expression.",
sbWithoutTypes + " => |" + (addSemicolon ? ";" : "") sbWithoutTypes + " => |" + (addSemicolon ? ";" : "")
); );
} }
/* TODO:Make factory method out of it. /* TODO:Make factory method out of it.
// It's needed to temporarly disable inserting auto matching bracket because the anonymous delegates are selectable with '(' // It's needed to temporarly disable inserting auto matching bracket because the anonymous delegates are selectable with '('
@ -2057,7 +2068,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}*/ }*/
return sb.ToString(); return sb.ToString();
} }
bool IsAccessibleFrom(IEntity member, ITypeDefinition calledType, IMember currentMember, bool includeProtected) bool IsAccessibleFrom(IEntity member, ITypeDefinition calledType, IMember currentMember, bool includeProtected)
{ {
if (currentMember == null) { if (currentMember == null) {
@ -2151,8 +2162,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var nr = (NamespaceResolveResult)resolveResult; var nr = (NamespaceResolveResult)resolveResult;
if (!(resolvedNode.Parent is UsingDeclaration || resolvedNode.Parent != null && resolvedNode.Parent.Parent is UsingDeclaration)) { if (!(resolvedNode.Parent is UsingDeclaration || resolvedNode.Parent != null && resolvedNode.Parent.Parent is UsingDeclaration)) {
foreach (var cl in nr.Namespace.Types) { foreach (var cl in nr.Namespace.Types) {
if (cl.IsSynthetic)
continue;
string name = cl.Name; string name = cl.Name;
if (hintType != null && hintType.Kind != TypeKind.Array && cl.Kind == TypeKind.Interface) { if (hintType != null && hintType.Kind != TypeKind.Array && cl.Kind == TypeKind.Interface) {
continue; continue;
@ -2291,8 +2300,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var namespaceContents = new CompletionDataWrapper(this); var namespaceContents = new CompletionDataWrapper(this);
foreach (var cl in nr.Namespace.Types) { foreach (var cl in nr.Namespace.Types) {
if (cl.IsSynthetic)
continue;
IType addType = typePred != null ? typePred(cl) : cl; IType addType = typePred != null ? typePred(cl) : cl;
if (addType != null) if (addType != null)
namespaceContents.AddType(addType, addType.Name); namespaceContents.AddType(addType, addType.Name);
@ -2393,8 +2400,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var filteredList = new List<IMember>(); var filteredList = new List<IMember>();
foreach (var member in type.GetMembers ()) { foreach (var member in type.GetMembers ()) {
if (member.IsSynthetic)
continue;
if (member.EntityType == EntityType.Indexer || member.EntityType == EntityType.Operator || member.EntityType == EntityType.Constructor || member.EntityType == EntityType.Destructor) { if (member.EntityType == EntityType.Indexer || member.EntityType == EntityType.Operator || member.EntityType == EntityType.Constructor || member.EntityType == EntityType.Destructor) {
continue; continue;
} }
@ -2445,7 +2450,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
} }
if (resolveResult is TypeResolveResult || includeStaticMembers) { if (resolveResult is TypeResolveResult || includeStaticMembers) {
foreach (var nested in type.GetNestedTypes (t => !t.IsSynthetic)) { foreach (var nested in type.GetNestedTypes ()) {
if (!lookup.IsAccessible(nested.GetDefinition(), isProtectedAllowed)) if (!lookup.IsAccessible(nested.GetDefinition(), isProtectedAllowed))
continue; continue;
IType addType = typePred != null ? typePred(nested) : nested; IType addType = typePred != null ? typePred(nested) : nested;

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

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

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

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

21
ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj

@ -47,6 +47,27 @@
<DebugType>full</DebugType> <DebugType>full</DebugType>
<DebugSymbols>True</DebugSymbols> <DebugSymbols>True</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE;FULL_AST;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|AnyCPU' ">
<DebugType>full</DebugType>
<DebugSymbols>True</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE;FULL_AST;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' ">
<DebugType>PdbOnly</DebugType>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core"> <Reference Include="System.Core">

1
ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs

@ -2172,6 +2172,7 @@ namespace ICSharpCode.NRefactory.CSharp
WriteAttributes(indexerDeclaration.Attributes); WriteAttributes(indexerDeclaration.Attributes);
WriteModifiers(indexerDeclaration.ModifierTokens); WriteModifiers(indexerDeclaration.ModifierTokens);
indexerDeclaration.ReturnType.AcceptVisitor(this); indexerDeclaration.ReturnType.AcceptVisitor(this);
Space();
WritePrivateImplementationType(indexerDeclaration.PrivateImplementationType); WritePrivateImplementationType(indexerDeclaration.PrivateImplementationType);
WriteKeyword(IndexerDeclaration.ThisKeywordRole); WriteKeyword(IndexerDeclaration.ThisKeywordRole);
Space(policy.SpaceBeforeMethodDeclarationParentheses); Space(policy.SpaceBeforeMethodDeclarationParentheses);

32
ICSharpCode.NRefactory.CSharp/Parser/CSharpParser.cs

@ -2390,7 +2390,9 @@ namespace ICSharpCode.NRefactory.CSharp
if (binaryExpression.Left != null) if (binaryExpression.Left != null)
result.AddChild ((Expression)binaryExpression.Left.Accept (this), BinaryOperatorExpression.LeftRole); result.AddChild ((Expression)binaryExpression.Left.Accept (this), BinaryOperatorExpression.LeftRole);
result.AddChild (new CSharpTokenNode (Convert (binaryExpression.Location)), BinaryOperatorExpression.GetOperatorRole (result.Operator)); var location = LocationsBag.GetLocations (binaryExpression);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0])), BinaryOperatorExpression.GetOperatorRole (result.Operator));
if (binaryExpression.Right != null) if (binaryExpression.Right != null)
result.AddChild ((Expression)binaryExpression.Right.Accept (this), BinaryOperatorExpression.RightRole); result.AddChild ((Expression)binaryExpression.Right.Accept (this), BinaryOperatorExpression.RightRole);
return result; return result;
@ -2402,7 +2404,9 @@ namespace ICSharpCode.NRefactory.CSharp
result.Operator = BinaryOperatorType.NullCoalescing; result.Operator = BinaryOperatorType.NullCoalescing;
if (nullCoalescingOperator.LeftExpression != null) if (nullCoalescingOperator.LeftExpression != null)
result.AddChild ((Expression)nullCoalescingOperator.LeftExpression.Accept (this), BinaryOperatorExpression.LeftRole); result.AddChild ((Expression)nullCoalescingOperator.LeftExpression.Accept (this), BinaryOperatorExpression.LeftRole);
result.AddChild (new CSharpTokenNode (Convert (nullCoalescingOperator.Location)), BinaryOperatorExpression.NullCoalescingRole); var location = LocationsBag.GetLocations (nullCoalescingOperator);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0])), BinaryOperatorExpression.NullCoalescingRole);
if (nullCoalescingOperator.RightExpression != null) if (nullCoalescingOperator.RightExpression != null)
result.AddChild ((Expression)nullCoalescingOperator.RightExpression.Accept (this), BinaryOperatorExpression.RightRole); result.AddChild ((Expression)nullCoalescingOperator.RightExpression.Accept (this), BinaryOperatorExpression.RightRole);
return result; return result;
@ -3076,7 +3080,9 @@ namespace ICSharpCode.NRefactory.CSharp
result.Operator = AssignmentOperatorType.Assign; result.Operator = AssignmentOperatorType.Assign;
if (simpleAssign.Target != null) if (simpleAssign.Target != null)
result.AddChild ((Expression)simpleAssign.Target.Accept (this), AssignmentExpression.LeftRole); result.AddChild ((Expression)simpleAssign.Target.Accept (this), AssignmentExpression.LeftRole);
result.AddChild (new CSharpTokenNode (Convert (simpleAssign.Location)), AssignmentExpression.AssignRole); var location = LocationsBag.GetLocations (simpleAssign);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0])), AssignmentExpression.AssignRole);
if (simpleAssign.Source != null) { if (simpleAssign.Source != null) {
result.AddChild ((Expression)simpleAssign.Source.Accept (this), AssignmentExpression.RightRole); result.AddChild ((Expression)simpleAssign.Source.Accept (this), AssignmentExpression.RightRole);
} }
@ -3121,7 +3127,9 @@ namespace ICSharpCode.NRefactory.CSharp
if (compoundAssign.Target != null) if (compoundAssign.Target != null)
result.AddChild ((Expression)compoundAssign.Target.Accept (this), AssignmentExpression.LeftRole); result.AddChild ((Expression)compoundAssign.Target.Accept (this), AssignmentExpression.LeftRole);
result.AddChild (new CSharpTokenNode (Convert (compoundAssign.Location)), AssignmentExpression.GetOperatorRole (result.Operator)); var location = LocationsBag.GetLocations (compoundAssign);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0])), AssignmentExpression.GetOperatorRole (result.Operator));
if (compoundAssign.Source != null) if (compoundAssign.Source != null)
result.AddChild ((Expression)compoundAssign.Source.Accept (this), AssignmentExpression.RightRole); result.AddChild ((Expression)compoundAssign.Source.Accept (this), AssignmentExpression.RightRole);
return result; return result;
@ -3781,11 +3789,13 @@ namespace ICSharpCode.NRefactory.CSharp
var file = new SourceFile (fileName, fileName, 0); var file = new SourceFile (fileName, fileName, 0);
Location.Initialize (new List<SourceFile> (new [] { file })); Location.Initialize (new List<SourceFile> (new [] { file }));
var module = new ModuleContainer (ctx); var module = new ModuleContainer (ctx);
var parser = Driver.Parse (reader, file, module, lineModifier); var session = new ParserSession ();
session.LocationsBag = new LocationsBag ();
var report = new Report (ctx, errorReportPrinter);
var parser = Driver.Parse (reader, file, module, session, report, lineModifier);
var top = new CompilerCompilationUnit () { var top = new CompilerCompilationUnit () {
ModuleCompiled = module, ModuleCompiled = module,
LocationsBag = parser.LocationsBag, LocationsBag = session.LocationsBag,
SpecialsBag = parser.Lexer.sbag, SpecialsBag = parser.Lexer.sbag,
Conditionals = parser.Lexer.SourceFile.Conditionals Conditionals = parser.Lexer.SourceFile.Conditionals
}; };
@ -3882,10 +3892,12 @@ namespace ICSharpCode.NRefactory.CSharp
var file = new SourceFile("", "", 0); var file = new SourceFile("", "", 0);
Location.Initialize(new List<SourceFile> (new [] { file })); Location.Initialize(new List<SourceFile> (new [] { file }));
var module = new ModuleContainer(ctx); var module = new ModuleContainer(ctx);
module.DocumentationBuilder = new DocumentationBuilder(); module.DocumentationBuilder = new DocumentationBuilder(module);
var source_file = new CompilationSourceFile (module); var source_file = new CompilationSourceFile (module);
var report = new Report (ctx, errorReportPrinter); var report = new Report (ctx, errorReportPrinter);
var parser = new Mono.CSharp.CSharpParser (reader, source_file, report); ParserSession session = new ParserSession ();
session.LocationsBag = new LocationsBag ();
var parser = new Mono.CSharp.CSharpParser (reader, source_file, report, session);
parser.Lexer.putback_char = Tokenizer.DocumentationXref; parser.Lexer.putback_char = Tokenizer.DocumentationXref;
parser.Lexer.parsing_generic_declaration_doc = true; parser.Lexer.parsing_generic_declaration_doc = true;
parser.parse (); parser.parse ();
@ -3894,7 +3906,7 @@ namespace ICSharpCode.NRefactory.CSharp
// mc.GetSignatureForError (), cref); // mc.GetSignatureForError (), cref);
} }
ConversionVisitor conversionVisitor = new ConversionVisitor (false, parser.LocationsBag); ConversionVisitor conversionVisitor = new ConversionVisitor (false, session.LocationsBag);
DocumentationReference docRef = conversionVisitor.ConvertXmlDoc(module.DocumentationBuilder); DocumentationReference docRef = conversionVisitor.ConvertXmlDoc(module.DocumentationBuilder);
CompilerCallableEntryPoint.Reset(); CompilerCallableEntryPoint.Reset();
return docRef; return docRef;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File diff suppressed because it is too large Load Diff

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

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

249
ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-tokenizer.cs

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

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

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

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

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

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

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

73
ICSharpCode.NRefactory.CSharp/Parser/mcs/driver.cs

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

45
ICSharpCode.NRefactory.CSharp/Parser/mcs/statement.cs

@ -281,11 +281,16 @@ namespace Mono.CSharp {
public Expression expr; public Expression expr;
public Statement EmbeddedStatement; public Statement EmbeddedStatement;
public Do (Statement statement, BooleanExpression bool_expr, Location l) public Do (Statement statement, BooleanExpression bool_expr, Location doLocation, Location whileLocation)
{ {
expr = bool_expr; expr = bool_expr;
EmbeddedStatement = statement; EmbeddedStatement = statement;
loc = l; loc = doLocation;
WhileLocation = whileLocation;
}
public Location WhileLocation {
get; private set;
} }
public override bool Resolve (BlockContext ec) public override bool Resolve (BlockContext ec)
@ -332,7 +337,7 @@ namespace Mono.CSharp {
ec.MarkLabel (ec.LoopBegin); ec.MarkLabel (ec.LoopBegin);
// Mark start of while condition // Mark start of while condition
ec.Mark (expr.Location); ec.Mark (WhileLocation);
// //
// Dead code elimination // Dead code elimination
@ -461,7 +466,7 @@ namespace Mono.CSharp {
ec.MarkLabel (ec.LoopBegin); ec.MarkLabel (ec.LoopBegin);
ec.Mark (expr.Location); ec.Mark (loc);
expr.EmitBranchable (ec, while_loop, true); expr.EmitBranchable (ec, while_loop, true);
ec.MarkLabel (ec.LoopEnd); ec.MarkLabel (ec.LoopEnd);
@ -878,7 +883,6 @@ namespace Mono.CSharp {
return true; return true;
} }
// TODO: Better error message
if (async_type.Kind == MemberKind.Void) { if (async_type.Kind == MemberKind.Void) {
ec.Report.Error (127, loc, ec.Report.Error (127, loc,
"`{0}': A return keyword must not be followed by any expression when method returns void", "`{0}': A return keyword must not be followed by any expression when method returns void",
@ -909,6 +913,15 @@ namespace Mono.CSharp {
} }
} }
} else { } else {
// Same error code as .NET but better error message
if (block_return_type.Kind == MemberKind.Void) {
ec.Report.Error (127, loc,
"`{0}': A return keyword must not be followed by any expression when delegate returns void",
am.GetSignatureForError ());
return false;
}
var l = am as AnonymousMethodBody; var l = am as AnonymousMethodBody;
if (l != null && l.ReturnTypeInference != null && expr != null) { if (l != null && l.ReturnTypeInference != null && expr != null) {
l.ReturnTypeInference.AddCommonTypeBound (expr.Type); l.ReturnTypeInference.AddCommonTypeBound (expr.Type);
@ -1620,8 +1633,10 @@ namespace Mono.CSharp {
if (declarators != null) { if (declarators != null) {
foreach (var d in declarators) { foreach (var d in declarators) {
d.Variable.CreateBuilder (ec); d.Variable.CreateBuilder (ec);
if (d.Initializer != null) if (d.Initializer != null) {
ec.Mark (d.Variable.Location);
((ExpressionStatement) d.Initializer).EmitStatement (ec); ((ExpressionStatement) d.Initializer).EmitStatement (ec);
}
} }
} }
} }
@ -4236,10 +4251,10 @@ namespace Mono.CSharp {
Expression cond = null; Expression cond = null;
for (int ci = 0; ci < s.Labels.Count; ++ci) { for (int ci = 0; ci < s.Labels.Count; ++ci) {
var e = new Binary (Binary.Operator.Equality, value, s.Labels[ci].Converted, loc); var e = new Binary (Binary.Operator.Equality, value, s.Labels[ci].Converted);
if (ci > 0) { if (ci > 0) {
cond = new Binary (Binary.Operator.LogicalOr, cond, e, loc); cond = new Binary (Binary.Operator.LogicalOr, cond, e);
} else { } else {
cond = e; cond = e;
} }
@ -5130,8 +5145,8 @@ namespace Mono.CSharp {
// fixed (T* e_ptr = (e == null || e.Length == 0) ? null : converted [0]) // fixed (T* e_ptr = (e == null || e.Length == 0) ? null : converted [0])
// //
converted = new Conditional (new BooleanExpression (new Binary (Binary.Operator.LogicalOr, converted = new Conditional (new BooleanExpression (new Binary (Binary.Operator.LogicalOr,
new Binary (Binary.Operator.Equality, initializer, new NullLiteral (loc), loc), new Binary (Binary.Operator.Equality, initializer, new NullLiteral (loc)),
new Binary (Binary.Operator.Equality, new MemberAccess (initializer, "Length"), new IntConstant (bc.BuiltinTypes, 0, loc), loc), loc)), new Binary (Binary.Operator.Equality, new MemberAccess (initializer, "Length"), new IntConstant (bc.BuiltinTypes, 0, loc)))),
new NullLiteral (loc), new NullLiteral (loc),
converted, loc); converted, loc);
@ -5697,7 +5712,7 @@ namespace Mono.CSharp {
// Add conditional call when disposing possible null variable // Add conditional call when disposing possible null variable
if (!type.IsStruct || type.IsNullableType) if (!type.IsStruct || type.IsNullableType)
dispose = new If (new Binary (Binary.Operator.Inequality, lvr, new NullLiteral (loc), loc), dispose, dispose.loc); dispose = new If (new Binary (Binary.Operator.Inequality, lvr, new NullLiteral (loc)), dispose, dispose.loc);
return dispose; return dispose;
} }
@ -5711,7 +5726,7 @@ namespace Mono.CSharp {
{ {
for (int i = declarators.Count - 1; i >= 0; --i) { for (int i = declarators.Count - 1; i >= 0; --i) {
var d = declarators [i]; var d = declarators [i];
var vd = new VariableDeclaration (d.Variable, type_expr.Location); var vd = new VariableDeclaration (d.Variable, d.Variable.Location);
vd.Initializer = d.Initializer; vd.Initializer = d.Initializer;
vd.IsNested = true; vd.IsNested = true;
vd.dispose_call = CreateDisposeCall (bc, d.Variable); vd.dispose_call = CreateDisposeCall (bc, d.Variable);
@ -5947,7 +5962,7 @@ namespace Mono.CSharp {
if (variable_ref == null) if (variable_ref == null)
return false; return false;
for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, access, Location.Null), for_each.variable.Location)); for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, access, Location.Null), for_each.type.Location));
bool ok = true; bool ok = true;
@ -6043,7 +6058,7 @@ namespace Mono.CSharp {
var idisaposable_test = new Binary (Binary.Operator.Inequality, new CompilerAssign ( var idisaposable_test = new Binary (Binary.Operator.Inequality, new CompilerAssign (
dispose_variable.CreateReferenceExpression (bc, loc), dispose_variable.CreateReferenceExpression (bc, loc),
new As (lv.CreateReferenceExpression (bc, loc), new TypeExpression (dispose_variable.Type, loc), loc), new As (lv.CreateReferenceExpression (bc, loc), new TypeExpression (dispose_variable.Type, loc), loc),
loc), new NullLiteral (loc), loc); loc), new NullLiteral (loc));
var m = bc.Module.PredefinedMembers.IDisposableDispose.Resolve (loc); var m = bc.Module.PredefinedMembers.IDisposableDispose.Resolve (loc);
@ -6258,7 +6273,7 @@ namespace Mono.CSharp {
if (variable_ref == null) if (variable_ref == null)
return false; return false;
for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, current_pe, Location.Null), variable.Location)); for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, current_pe, Location.Null), for_each.type.Location));
var init = new Invocation (get_enumerator_mg, null); var init = new Invocation (get_enumerator_mg, null);

10
ICSharpCode.NRefactory.CSharp/Parser/mcs/support.cs

@ -137,21 +137,23 @@ namespace Mono.CSharp {
/// </summary> /// </summary>
public class SeekableStreamReader : IDisposable public class SeekableStreamReader : IDisposable
{ {
public const int DefaultReadAheadSize = 2048;
StreamReader reader; StreamReader reader;
Stream stream; Stream stream;
static char[] buffer; char[] buffer;
int read_ahead_length; // the length of read buffer int read_ahead_length; // the length of read buffer
int buffer_start; // in chars int buffer_start; // in chars
int char_count; // count of filled characters in buffer[] int char_count; // count of filled characters in buffer[]
int pos; // index into buffer[] int pos; // index into buffer[]
public SeekableStreamReader (Stream stream, Encoding encoding) public SeekableStreamReader (Stream stream, Encoding encoding, char[] sharedBuffer = null)
{ {
this.stream = stream; this.stream = stream;
this.buffer = sharedBuffer;
const int default_read_ahead = 2048; InitializeStream (DefaultReadAheadSize);
InitializeStream (default_read_ahead);
reader = new StreamReader (stream, encoding, true); reader = new StreamReader (stream, encoding, true);
} }

38
ICSharpCode.NRefactory.CSharp/Parser/mcs/typemanager.cs

@ -144,7 +144,7 @@ namespace Mono.CSharp
{ {
var ctx = module.Compiler; var ctx = module.Compiler;
foreach (var p in types) { foreach (var p in types) {
var found = PredefinedType.Resolve (module, p.Kind, p.Namespace, p.Name, p.Arity); var found = PredefinedType.Resolve (module, p.Kind, p.Namespace, p.Name, p.Arity, true, true);
if (found == null || found == p) if (found == null || found == p)
continue; continue;
@ -340,6 +340,7 @@ namespace Mono.CSharp
public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderSetStateMachine; public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderSetStateMachine;
public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderOnCompleted; public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderOnCompleted;
public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderOnCompletedUnsafe; public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderOnCompletedUnsafe;
public readonly PredefinedMember<MethodSpec> AsyncStateMachineAttributeCtor;
public readonly PredefinedMember<MethodSpec> DebuggerBrowsableAttributeCtor; public readonly PredefinedMember<MethodSpec> DebuggerBrowsableAttributeCtor;
public readonly PredefinedMember<MethodSpec> DecimalCtor; public readonly PredefinedMember<MethodSpec> DecimalCtor;
public readonly PredefinedMember<MethodSpec> DecimalCtorInt; public readonly PredefinedMember<MethodSpec> DecimalCtorInt;
@ -357,6 +358,7 @@ namespace Mono.CSharp
public readonly PredefinedMember<MethodSpec> IEnumerableGetEnumerator; public readonly PredefinedMember<MethodSpec> IEnumerableGetEnumerator;
public readonly PredefinedMember<MethodSpec> InterlockedCompareExchange; public readonly PredefinedMember<MethodSpec> InterlockedCompareExchange;
public readonly PredefinedMember<MethodSpec> InterlockedCompareExchange_T; public readonly PredefinedMember<MethodSpec> InterlockedCompareExchange_T;
public readonly PredefinedMember<MethodSpec> IteratorStateMachineAttributeCtor;
public readonly PredefinedMember<MethodSpec> FixedBufferAttributeCtor; public readonly PredefinedMember<MethodSpec> FixedBufferAttributeCtor;
public readonly PredefinedMember<MethodSpec> MethodInfoGetMethodFromHandle; public readonly PredefinedMember<MethodSpec> MethodInfoGetMethodFromHandle;
public readonly PredefinedMember<MethodSpec> MethodInfoGetMethodFromHandle2; public readonly PredefinedMember<MethodSpec> MethodInfoGetMethodFromHandle2;
@ -549,6 +551,10 @@ namespace Mono.CSharp
}, false), }, false),
btypes.Void)); btypes.Void));
AsyncStateMachineAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.AsyncStateMachine,
MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (
btypes.Type)));
DebuggerBrowsableAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.DebuggerBrowsable, DebuggerBrowsableAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.DebuggerBrowsable,
MemberFilter.Constructor (null)); MemberFilter.Constructor (null));
@ -625,6 +631,10 @@ namespace Mono.CSharp
}, false), }, false),
null)); null));
IteratorStateMachineAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.IteratorStateMachine,
MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (
btypes.Type)));
MethodInfoGetMethodFromHandle = new PredefinedMember<MethodSpec> (module, types.MethodBase, MethodInfoGetMethodFromHandle = new PredefinedMember<MethodSpec> (module, types.MethodBase,
"GetMethodFromHandle", MemberKind.Method, types.RuntimeMethodHandle); "GetMethodFromHandle", MemberKind.Method, types.RuntimeMethodHandle);
@ -748,7 +758,7 @@ namespace Mono.CSharp
if (type != null) if (type != null)
return true; return true;
type = Resolve (module, kind, ns, name, arity, false); type = Resolve (module, kind, ns, name, arity, false, false);
return type != null; return type != null;
} }
@ -757,17 +767,21 @@ namespace Mono.CSharp
return ns + "." + name; return ns + "." + name;
} }
public static TypeSpec Resolve (ModuleContainer module, MemberKind kind, string ns, string name, int arity) public static TypeSpec Resolve (ModuleContainer module, MemberKind kind, string ns, string name, int arity, bool required, bool reportErrors)
{ {
return Resolve (module, kind, ns, name, arity, true); //
} // Cannot call it with true because it could create non-existent namespaces for
// predefined types. It's set to true only for build-in types which all must
// exist therefore it does not matter, for predefined types we don't want to create
// fake namespaces when type is optional and does not exist (e.g. System.Linq).
//
Namespace type_ns = module.GlobalRootNamespace.GetNamespace (ns, required);
IList<TypeSpec> found = null;
if (type_ns != null)
found = type_ns.GetAllTypes (name);
public static TypeSpec Resolve (ModuleContainer module, MemberKind kind, string ns, string name, int arity, bool reportErrors)
{
Namespace type_ns = module.GlobalRootNamespace.GetNamespace (ns, true);
var found = type_ns.GetAllTypes (name);
if (found == null) { if (found == null) {
if (reportErrors) if (reportErrors )
module.Compiler.Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported", ns, name); module.Compiler.Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported", ns, name);
return null; return null;
@ -837,13 +851,13 @@ namespace Mono.CSharp
public TypeSpec Resolve () public TypeSpec Resolve ()
{ {
if (type == null) if (type == null)
type = Resolve (module, kind, ns, name, arity); type = Resolve (module, kind, ns, name, arity, false, true);
return type; return type;
} }
} }
class PredefinedMember<T> where T : MemberSpec public class PredefinedMember<T> where T : MemberSpec
{ {
readonly ModuleContainer module; readonly ModuleContainer module;
T member; T member;

4
ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/GeneratePropertyAction.cs

@ -1,4 +1,4 @@
// //
// GenerateProperty.cs // GenerateProperty.cs
// //
// Author: // Author:
@ -51,7 +51,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
} }
} }
var field = initializer.Parent as FieldDeclaration; var field = initializer.Parent as FieldDeclaration;
if (field == null) { if (field == null || field.HasModifier(Modifiers.Readonly) || field.HasModifier(Modifiers.Const)) {
yield break; yield break;
} }
var resolveResult = context.Resolve(initializer) as MemberResolveResult; var resolveResult = context.Resolve(initializer) as MemberResolveResult;

195
ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ImplementInterfaceAction.cs

@ -1,4 +1,4 @@
// //
// ImplementInterfaceAction.cs // ImplementInterfaceAction.cs
// //
// Author: // Author:
@ -68,7 +68,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
foreach (var member in toImplement) { foreach (var member in toImplement) {
if (!nodes.ContainsKey(member.Item1.DeclaringType)) if (!nodes.ContainsKey(member.Item1.DeclaringType))
nodes [member.Item1.DeclaringType] = new List<AstNode>(); nodes [member.Item1.DeclaringType] = new List<AstNode>();
nodes [member.Item1.DeclaringType].Add(GenerateMemberImplementation(context, member)); nodes [member.Item1.DeclaringType].Add(GenerateMemberImplementation(context, member.Item1, member.Item2));
} }
foreach (var kv in nodes) { foreach (var kv in nodes) {
@ -89,188 +89,21 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
} }
} }
static AstNode GenerateMemberImplementation(RefactoringContext context, Tuple<IMember, bool> member) static EntityDeclaration GenerateMemberImplementation(RefactoringContext context, IMember member, bool explicitImplementation)
{
switch (member.Item1.EntityType) {
case EntityType.Property:
return GenerateProperty(context, (IProperty)member.Item1, member.Item2);
case EntityType.Indexer:
return GenerateIndexer(context, (IProperty)member.Item1, member.Item2);
case EntityType.Event:
return GenerateEvent(context, (IEvent)member.Item1, member.Item2);
case EntityType.Method:
return GenerateMethod(context, (IMethod)member.Item1, member.Item2);
default:
throw new ArgumentOutOfRangeException();
}
}
static AstNode GenerateEvent(RefactoringContext context, IEvent evt, bool explicitImplementation)
{ {
if (!explicitImplementation) { var builder = context.CreateTypeSytemAstBuilder();
return new EventDeclaration() { builder.GenerateBody = true;
Modifiers = Modifiers.Public, builder.ShowConstantValues = !explicitImplementation;
Name = evt.Name, builder.ShowTypeParameterConstraints = !explicitImplementation;
ReturnType = context.CreateShortType (evt.ReturnType) builder.UseCustomEvents = explicitImplementation;
}; var decl = builder.ConvertEntity(member);
} if (explicitImplementation) {
return new CustomEventDeclaration() { decl.Modifiers = Modifiers.None;
Name = evt.Name, decl.AddChild(builder.ConvertType(member.DeclaringType), EntityDeclaration.PrivateImplementationTypeRole);
ReturnType = context.CreateShortType (evt.ReturnType),
PrivateImplementationType = context.CreateShortType(evt.DeclaringType),
AddAccessor = new Accessor {
Body = new BlockStatement() {
new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
}
},
RemoveAccessor = new Accessor {
Body = new BlockStatement() {
new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
}
}
};
}
static AstNode GenerateProperty(RefactoringContext context, IProperty property, bool explicitImplementation)
{
var result = new PropertyDeclaration() {
Name = property.Name,
ReturnType = context.CreateShortType (property.ReturnType)
};
if (!explicitImplementation) {
result.Modifiers = Modifiers.Public;
} else {
result.PrivateImplementationType = context.CreateShortType(property.DeclaringType);
}
if (property.CanGet) {
if (property.DeclaringType.Kind != TypeKind.Interface) {
result.Getter = new Accessor() {
Body = new BlockStatement () {
new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
}
};
} else {
result.Getter = new Accessor();
}
}
if (property.CanSet) {
if (property.DeclaringType.Kind != TypeKind.Interface) {
result.Setter = new Accessor() {
Body = new BlockStatement () {
new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
}
};
} else {
result.Setter = new Accessor();
}
}
return result;
}
static AstNode GenerateIndexer(RefactoringContext context, IProperty indexer, bool explicitImplementation)
{
var result = new IndexerDeclaration() {
ReturnType = context.CreateShortType (indexer.ReturnType)
};
if (!explicitImplementation) {
result.Modifiers = Modifiers.Public;
} else { } else {
result.PrivateImplementationType = context.CreateShortType(indexer.DeclaringType); decl.Modifiers = Modifiers.Public;
} }
return decl;
foreach (var p in indexer.Parameters) {
ParameterModifier modifier;
if (p.IsOut) {
modifier = ParameterModifier.Out;
} else if (p.IsRef) {
modifier = ParameterModifier.Ref;
} else if (p.IsParams) {
modifier = ParameterModifier.Params;
} else {
modifier = ParameterModifier.None;
}
result.Parameters.Add(new ParameterDeclaration(context.CreateShortType(p.Type), p.Name, modifier));
}
if (indexer.CanGet) {
result.Getter = new Accessor() {
Body = new BlockStatement () {
new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
}
};
}
if (indexer.CanSet) {
result.Setter = new Accessor() {
Body = new BlockStatement () {
new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
}
};
}
return result;
}
static AstNode GenerateMethod(RefactoringContext context, IMethod method, bool explicitImplementation)
{
var result = new MethodDeclaration() {
Name = method.Name,
ReturnType = context.CreateShortType (method.ReturnType),
Body = new BlockStatement() {
new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")))
}
};
if (!explicitImplementation) {
result.Modifiers = Modifiers.Public;
} else {
result.PrivateImplementationType = context.CreateShortType(method.DeclaringType);
}
foreach (var typeParam in method.TypeParameters) {
result.TypeParameters.Add(new TypeParameterDeclaration(typeParam.Name));
var constraint = new Constraint() {
TypeParameter = new SimpleType(typeParam.Name)
};
if (typeParam.HasDefaultConstructorConstraint) {
constraint.BaseTypes.Add(new PrimitiveType("new"));
} else if (typeParam.HasReferenceTypeConstraint) {
constraint.BaseTypes.Add(new PrimitiveType("class"));
} else if (typeParam.HasValueTypeConstraint) {
constraint.BaseTypes.Add(new PrimitiveType("struct"));
}
foreach (var type in typeParam.DirectBaseTypes) {
if (type.FullName == "System.Object")
continue;
if (type.FullName == "System.ValueType")
continue;
constraint.BaseTypes.Add(context.CreateShortType(type));
}
if (constraint.BaseTypes.Count == 0)
continue;
result.Constraints.Add(constraint);
}
foreach (var p in method.Parameters) {
ParameterModifier modifier;
if (p.IsOut) {
modifier = ParameterModifier.Out;
} else if (p.IsRef) {
modifier = ParameterModifier.Ref;
} else if (p.IsParams) {
modifier = ParameterModifier.Params;
} else {
modifier = ParameterModifier.None;
}
result.Parameters.Add(new ParameterDeclaration(context.CreateShortType(p.Type), p.Name, modifier));
}
return result;
} }
public static List<Tuple<IMember, bool>> CollectMembersToImplement(ITypeDefinition implementingType, IType interfaceType, bool explicitly) public static List<Tuple<IMember, bool>> CollectMembersToImplement(ITypeDefinition implementingType, IType interfaceType, bool explicitly)

22
ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantThisIssue.cs

@ -45,6 +45,21 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
IssueMarker = IssueMarker.GrayOut)] IssueMarker = IssueMarker.GrayOut)]
public class RedundantThisIssue : ICodeIssueProvider public class RedundantThisIssue : ICodeIssueProvider
{ {
bool ignoreConstructors = true;
/// <summary>
/// Specifies whether to ignore redundant 'this' in constructors.
/// "this.Name = name;"
/// </summary>
public bool IgnoreConstructors {
get {
return ignoreConstructors;
}
set {
ignoreConstructors = value;
}
}
public IEnumerable<CodeIssue> GetIssues(BaseRefactoringContext context) public IEnumerable<CodeIssue> GetIssues(BaseRefactoringContext context)
{ {
return new GatherVisitor(context, this).GetIssues(); return new GatherVisitor(context, this).GetIssues();
@ -69,6 +84,13 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
return null; return null;
} }
public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
{
if (inspector.IgnoreConstructors)
return;
base.VisitConstructorDeclaration(constructorDeclaration);
}
public override void VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression) public override void VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression)
{ {

23
ICSharpCode.NRefactory.CSharp/Refactoring/RefactoringContext.cs

@ -44,24 +44,23 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
} }
public abstract TextLocation Location { get; } public abstract TextLocation Location { get; }
public virtual AstType CreateShortType (IType fullType) public TypeSystemAstBuilder CreateTypeSytemAstBuilder()
{ {
var csResolver = Resolver.GetResolverStateBefore(GetNode()); var csResolver = Resolver.GetResolverStateBefore(GetNode());
var builder = new TypeSystemAstBuilder(csResolver); return new TypeSystemAstBuilder(csResolver);
}
public virtual AstType CreateShortType (IType fullType)
{
var builder = CreateTypeSytemAstBuilder();
return builder.ConvertType(fullType); return builder.ConvertType(fullType);
} }
public AstType CreateShortType(string ns, string name, int typeParameterCount = 0) public virtual AstType CreateShortType(string ns, string name, int typeParameterCount = 0)
{ {
foreach (var asm in Compilation.Assemblies) { var builder = CreateTypeSytemAstBuilder();
var def = asm.GetTypeDefinition(ns, name, typeParameterCount); return builder.ConvertType(ns, name, typeParameterCount);
if (def != null) {
return CreateShortType(def);
}
}
return new MemberType(new SimpleType(ns), name);
} }
public virtual IEnumerable<AstNode> GetSelectedNodes() public virtual IEnumerable<AstNode> GetSelectedNodes()

68
ICSharpCode.NRefactory.CSharp/Refactoring/TypeSystemAstBuilder.cs

@ -111,6 +111,18 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// The default value is <c>false</c>. /// The default value is <c>false</c>.
/// </summary> /// </summary>
public bool AlwaysUseShortTypeNames { get; set; } public bool AlwaysUseShortTypeNames { get; set; }
/// <summary>
/// Controls whether to generate a body that throws a <c>System.NotImplementedException</c>.
/// The default value is <c>false</c>.
/// </summary>
public bool GenerateBody { get; set; }
/// <summary>
/// Controls whether to generate custom events.
/// The default value is <c>false</c>.
/// </summary>
public bool UseCustomEvents { get; set; }
#endregion #endregion
#region Convert Type #region Convert Type
@ -124,6 +136,19 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
return astType; return astType;
} }
public AstType ConvertType(string ns, string name, int typeParameterCount = 0)
{
if (resolver != null) {
foreach (var asm in resolver.Compilation.Assemblies) {
var def = asm.GetTypeDefinition(ns, name, typeParameterCount);
if (def != null) {
return ConvertType(def);
}
}
}
return new MemberType(new SimpleType(ns), name);
}
AstType ConvertTypeHelper(IType type) AstType ConvertTypeHelper(IType type)
{ {
TypeWithElementType typeWithElementType = type as TypeWithElementType; TypeWithElementType typeWithElementType = type as TypeWithElementType;
@ -557,12 +582,24 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
return decl; return decl;
} }
BlockStatement GenerateBodyBlock()
{
if (GenerateBody) {
return new BlockStatement {
new ThrowStatement(new ObjectCreateExpression(ConvertType("System", "NotImplementedException")))
};
} else {
return BlockStatement.Null;
}
}
Accessor ConvertAccessor(IMethod accessor) Accessor ConvertAccessor(IMethod accessor)
{ {
if (accessor == null) if (accessor == null)
return Accessor.Null; return Accessor.Null;
Accessor decl = new Accessor(); Accessor decl = new Accessor();
decl.Modifiers = ModifierFromAccessibility(accessor.Accessibility); decl.Modifiers = ModifierFromAccessibility(accessor.Accessibility);
decl.Body = GenerateBodyBlock();
return decl; return decl;
} }
@ -590,13 +627,23 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
return decl; return decl;
} }
EventDeclaration ConvertEvent(IEvent ev) EntityDeclaration ConvertEvent(IEvent ev)
{ {
EventDeclaration decl = new EventDeclaration(); if (this.UseCustomEvents) {
decl.Modifiers = GetMemberModifiers(ev); CustomEventDeclaration decl = new CustomEventDeclaration();
decl.ReturnType = ConvertType(ev.ReturnType); decl.Modifiers = GetMemberModifiers(ev);
decl.Variables.Add(new VariableInitializer(ev.Name)); decl.ReturnType = ConvertType(ev.ReturnType);
return decl; decl.Name = ev.Name;
decl.AddAccessor = ConvertAccessor(ev.AddAccessor);
decl.RemoveAccessor = ConvertAccessor(ev.RemoveAccessor);
return decl;
} else {
EventDeclaration decl = new EventDeclaration();
decl.Modifiers = GetMemberModifiers(ev);
decl.ReturnType = ConvertType(ev.ReturnType);
decl.Variables.Add(new VariableInitializer(ev.Name));
return decl;
}
} }
MethodDeclaration ConvertMethod(IMethod method) MethodDeclaration ConvertMethod(IMethod method)
@ -625,6 +672,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
decl.Constraints.Add(constraint); decl.Constraints.Add(constraint);
} }
} }
decl.Body = GenerateBodyBlock();
return decl; return decl;
} }
@ -641,6 +689,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
foreach (IParameter p in op.Parameters) { foreach (IParameter p in op.Parameters) {
decl.Parameters.Add(ConvertParameter(p)); decl.Parameters.Add(ConvertParameter(p));
} }
decl.Body = GenerateBodyBlock();
return decl; return decl;
} }
@ -652,6 +701,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
foreach (IParameter p in ctor.Parameters) { foreach (IParameter p in ctor.Parameters) {
decl.Parameters.Add(ConvertParameter(p)); decl.Parameters.Add(ConvertParameter(p));
} }
decl.Body = GenerateBodyBlock();
return decl; return decl;
} }
@ -659,6 +709,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
{ {
DestructorDeclaration decl = new DestructorDeclaration(); DestructorDeclaration decl = new DestructorDeclaration();
decl.Name = dtor.DeclaringTypeDefinition.Name; decl.Name = dtor.DeclaringTypeDefinition.Name;
decl.Body = GenerateBodyBlock();
return decl; return decl;
} }
#endregion #endregion
@ -687,12 +738,13 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
Modifiers GetMemberModifiers(IMember member) Modifiers GetMemberModifiers(IMember member)
{ {
Modifiers m = ModifierFromAccessibility(member.Accessibility); bool isInterfaceMember = member.DeclaringType.Kind == TypeKind.Interface;
Modifiers m = isInterfaceMember ? Modifiers.None : ModifierFromAccessibility(member.Accessibility);
if (this.ShowModifiers) { if (this.ShowModifiers) {
if (member.IsStatic) { if (member.IsStatic) {
m |= Modifiers.Static; m |= Modifiers.Static;
} else { } else {
if (member.IsAbstract) if (member.IsAbstract && !isInterfaceMember)
m |= Modifiers.Abstract; m |= Modifiers.Abstract;
if (member.IsOverride) if (member.IsOverride)
m |= Modifiers.Override; m |= Modifiers.Override;

2
ICSharpCode.NRefactory.CSharp/Resolver/CSharpAstResolver.cs

@ -275,7 +275,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} }
return true; return true;
} }
return (node.NodeType == NodeType.Whitespace || node is ArraySpecifier || node is NamedArgumentExpression); return (node.NodeType == NodeType.Whitespace || node is ArraySpecifier);
} }
} }
} }

11
ICSharpCode.NRefactory.CSharp/Resolver/CSharpInvocationResolveResult.cs

@ -96,10 +96,15 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
mappedTo = IsExpandedForm ? Math.Min(i, results.Length - 1) : i; mappedTo = IsExpandedForm ? Math.Min(i, results.Length - 1) : i;
if (mappedTo >= 0 && mappedTo < results.Length) { if (mappedTo >= 0 && mappedTo < results.Length) {
if (IsExpandedForm && mappedTo == results.Length - 1) if (IsExpandedForm && mappedTo == results.Length - 1) {
paramsArguments.Add(Arguments[i]); paramsArguments.Add(Arguments[i]);
else } else {
results[mappedTo] = Arguments[i]; var narr = Arguments[i] as NamedArgumentResolveResult;
if (narr != null)
results[mappedTo] = narr.Argument;
else
results[mappedTo] = Arguments[i];
}
} }
} }
if (IsExpandedForm) if (IsExpandedForm)

2
ICSharpCode.NRefactory.CSharp/Resolver/CSharpResolver.cs

@ -1954,7 +1954,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
or.AddCandidate(invokeMethod); or.AddCandidate(invokeMethod);
return new CSharpInvocationResolveResult( return new CSharpInvocationResolveResult(
target, invokeMethod, //invokeMethod.ReturnType.Resolve(context), target, invokeMethod, //invokeMethod.ReturnType.Resolve(context),
or.GetArgumentsWithConversions(), or.BestCandidateErrors, or.GetArgumentsWithConversionsAndNames(), or.BestCandidateErrors,
isExpandedForm: or.BestCandidateIsExpandedForm, isExpandedForm: or.BestCandidateIsExpandedForm,
isDelegateInvocation: true, isDelegateInvocation: true,
argumentToParameterMap: or.GetArgumentToParameterMap()); argumentToParameterMap: or.GetArgumentToParameterMap());

5
ICSharpCode.NRefactory.CSharp/Resolver/Log.cs

@ -19,12 +19,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Globalization;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.CSharp.Resolver namespace ICSharpCode.NRefactory.CSharp.Resolver
{ {

55
ICSharpCode.NRefactory.CSharp/Resolver/OverloadResolution.cs

@ -781,15 +781,35 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return null; return null;
} }
/// <summary>
/// Returns the arguments for the method call in the order they were provided (not in the order of the parameters).
/// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied
/// to them when calling the method.
/// </summary>
public IList<ResolveResult> GetArgumentsWithConversions() public IList<ResolveResult> GetArgumentsWithConversions()
{ {
if (bestCandidate == null) if (bestCandidate == null)
return arguments; return arguments;
else else
return GetArgumentsWithConversions(null); return GetArgumentsWithConversions(null, null);
}
/// <summary>
/// Returns the arguments for the method call in the order they were provided (not in the order of the parameters).
/// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied
/// to them when calling the method.
/// For arguments where an explicit argument name was provided, the argument will
/// be wrapped in a <see cref="NamedArgumentResolveResult"/>.
/// </summary>
public IList<ResolveResult> GetArgumentsWithConversionsAndNames()
{
if (bestCandidate == null)
return arguments;
else
return GetArgumentsWithConversions(null, GetBestCandidateWithSubstitutedTypeArguments());
} }
IList<ResolveResult> GetArgumentsWithConversions(ResolveResult targetResolveResult) IList<ResolveResult> GetArgumentsWithConversions(ResolveResult targetResolveResult, IParameterizedMember bestCandidateForNamedArguments)
{ {
var conversions = this.ArgumentConversions; var conversions = this.ArgumentConversions;
ResolveResult[] args = new ResolveResult[arguments.Length]; ResolveResult[] args = new ResolveResult[arguments.Length];
@ -797,22 +817,27 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
var argument = arguments[i]; var argument = arguments[i];
if (this.IsExtensionMethodInvocation && i == 0 && targetResolveResult != null) if (this.IsExtensionMethodInvocation && i == 0 && targetResolveResult != null)
argument = targetResolveResult; argument = targetResolveResult;
if (conversions[i] == Conversion.IdentityConversion) { int parameterIndex = bestCandidate.ArgumentToParameterMap[i];
args[i] = argument; if (parameterIndex >= 0 && conversions[i] != Conversion.IdentityConversion) {
} else { // Wrap argument in ConversionResolveResult
int parameterIndex = bestCandidate.ArgumentToParameterMap[i]; IType parameterType = bestCandidate.ParameterTypes[parameterIndex];
IType parameterType; if (parameterType.Kind != TypeKind.Unknown) {
if (parameterIndex >= 0) { if (arguments[i].IsCompileTimeConstant && conversions[i] != Conversion.None) {
parameterType = bestCandidate.ParameterTypes[parameterIndex]; argument = new CSharpResolver(compilation).WithCheckForOverflow(CheckForOverflow).ResolveCast(parameterType, argument);
} else { } else {
parameterType = SpecialType.UnknownType; argument = new ConversionResolveResult(parameterType, argument, conversions[i], CheckForOverflow);
}
} }
if (arguments[i].IsCompileTimeConstant && conversions[i] != Conversion.None) { }
args[i] = new CSharpResolver(compilation).WithCheckForOverflow(CheckForOverflow).ResolveCast(parameterType, argument); if (bestCandidateForNamedArguments != null && argumentNames[i] != null) {
// Wrap argument in NamedArgumentResolveResult
if (parameterIndex >= 0) {
argument = new NamedArgumentResolveResult(bestCandidateForNamedArguments.Parameters[parameterIndex], argument, bestCandidateForNamedArguments);
} else { } else {
args[i] = new ConversionResolveResult(parameterType, argument, conversions[i], CheckForOverflow); argument = new NamedArgumentResolveResult(argumentNames[i], argument);
} }
} }
args[i] = argument;
} }
return args; return args;
} }
@ -857,7 +882,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return new CSharpInvocationResolveResult( return new CSharpInvocationResolveResult(
this.IsExtensionMethodInvocation ? new TypeResolveResult(member.DeclaringType) : targetResolveResult, this.IsExtensionMethodInvocation ? new TypeResolveResult(member.DeclaringType) : targetResolveResult,
member, member,
GetArgumentsWithConversions(targetResolveResult), GetArgumentsWithConversions(targetResolveResult, member),
this.BestCandidateErrors, this.BestCandidateErrors,
this.IsExtensionMethodInvocation, this.IsExtensionMethodInvocation,
this.BestCandidateIsExpandedForm, this.BestCandidateIsExpandedForm,

148
ICSharpCode.NRefactory.CSharp/Resolver/ResolveVisitor.cs

@ -27,7 +27,6 @@ using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation; using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp.Resolver namespace ICSharpCode.NRefactory.CSharp.Resolver
{ {
@ -393,10 +392,21 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} }
} }
void MarkUnknownNamedArguments(IEnumerable<Expression> arguments)
{
foreach (var nae in arguments.OfType<NamedArgumentExpression>()) {
StoreCurrentState(nae);
StoreResult(nae, new NamedArgumentResolveResult(nae.Name, resolveResultCache[nae.Expression]));
}
}
void ProcessConversionsInInvocation(Expression target, IEnumerable<Expression> arguments, CSharpInvocationResolveResult invocation) void ProcessConversionsInInvocation(Expression target, IEnumerable<Expression> arguments, CSharpInvocationResolveResult invocation)
{ {
if (invocation == null) if (invocation == null) {
// we still need to handle the named arguments if invocation==null
MarkUnknownNamedArguments(arguments);
return; return;
}
int i = 0; int i = 0;
if (invocation.IsExtensionMethodInvocation) { if (invocation.IsExtensionMethodInvocation) {
Debug.Assert(arguments.Count() + 1 == invocation.Arguments.Count); Debug.Assert(arguments.Count() + 1 == invocation.Arguments.Count);
@ -406,11 +416,17 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
Debug.Assert(arguments.Count() == invocation.Arguments.Count); Debug.Assert(arguments.Count() == invocation.Arguments.Count);
} }
foreach (Expression arg in arguments) { foreach (Expression arg in arguments) {
ResolveResult argRR = invocation.Arguments[i++];
NamedArgumentExpression nae = arg as NamedArgumentExpression; NamedArgumentExpression nae = arg as NamedArgumentExpression;
if (nae != null) NamedArgumentResolveResult nrr = argRR as NamedArgumentResolveResult;
ProcessConversionResult(nae.Expression, invocation.Arguments[i++] as ConversionResolveResult); Debug.Assert((nae == null) == (nrr == null));
else if (nae != null && nrr != null) {
ProcessConversionResult(arg, invocation.Arguments[i++] as ConversionResolveResult); StoreCurrentState(nae);
StoreResult(nae, nrr);
ProcessConversionResult(nae.Expression, nrr.Argument as ConversionResolveResult);
} else {
ProcessConversionResult(arg, argRR as ConversionResolveResult);
}
} }
} }
#endregion #endregion
@ -659,7 +675,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (node.Role == Roles.Variable) { if (node.Role == Roles.Variable) {
IMember member; IMember member;
if (parsedFile != null) { if (parsedFile != null) {
member = GetMemberFromLocation(node.StartLocation); member = GetMemberFromLocation(node);
} else { } else {
string name = ((VariableInitializer)node).Name; string name = ((VariableInitializer)node).Name;
member = AbstractUnresolvedMember.Resolve(resolver.CurrentTypeResolveContext, entityType, name); member = AbstractUnresolvedMember.Resolve(resolver.CurrentTypeResolveContext, entityType, name);
@ -676,11 +692,12 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return voidResult; return voidResult;
} }
IMember GetMemberFromLocation(TextLocation location) IMember GetMemberFromLocation(AstNode node)
{ {
ITypeDefinition typeDef = resolver.CurrentTypeDefinition; ITypeDefinition typeDef = resolver.CurrentTypeDefinition;
if (typeDef == null) if (typeDef == null)
return null; return null;
TextLocation location = TypeSystemConvertVisitor.GetStartLocationAfterAttributes(node);
return typeDef.GetMembers( return typeDef.GetMembers(
delegate (IUnresolvedMember m) { delegate (IUnresolvedMember m) {
if (m.ParsedFile != parsedFile) if (m.ParsedFile != parsedFile)
@ -777,7 +794,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
try { try {
IMember member; IMember member;
if (parsedFile != null) { if (parsedFile != null) {
member = GetMemberFromLocation(memberDeclaration.StartLocation); member = GetMemberFromLocation(memberDeclaration);
} else { } else {
// Re-discover the method: // Re-discover the method:
EntityType entityType = memberDeclaration.EntityType; EntityType entityType = memberDeclaration.EntityType;
@ -840,7 +857,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
try { try {
IMember member; IMember member;
if (parsedFile != null) { if (parsedFile != null) {
member = GetMemberFromLocation(propertyOrIndexerDeclaration.StartLocation); member = GetMemberFromLocation(propertyOrIndexerDeclaration);
} else { } else {
// Re-discover the property: // Re-discover the property:
string name = propertyOrIndexerDeclaration.Name; string name = propertyOrIndexerDeclaration.Name;
@ -896,7 +913,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
try { try {
IMember member; IMember member;
if (parsedFile != null) { if (parsedFile != null) {
member = GetMemberFromLocation(eventDeclaration.StartLocation); member = GetMemberFromLocation(eventDeclaration);
} else { } else {
string name = eventDeclaration.Name; string name = eventDeclaration.Name;
AstType explicitInterfaceAstType = eventDeclaration.PrivateImplementationType; AstType explicitInterfaceAstType = eventDeclaration.PrivateImplementationType;
@ -1019,7 +1036,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
IMember member = null; IMember member = null;
if (parsedFile != null) { if (parsedFile != null) {
member = GetMemberFromLocation(enumMemberDeclaration.StartLocation); member = GetMemberFromLocation(enumMemberDeclaration);
} else if (resolver.CurrentTypeDefinition != null) { } else if (resolver.CurrentTypeDefinition != null) {
string name = enumMemberDeclaration.Name; string name = enumMemberDeclaration.Name;
member = resolver.CurrentTypeDefinition.GetFields(f => f.Name == name, GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault(); member = resolver.CurrentTypeDefinition.GetFields(f => f.Name == name, GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault();
@ -1397,7 +1414,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<ResolveResult>.VisitIndexerExpression(IndexerExpression indexerExpression) ResolveResult IAstVisitor<ResolveResult>.VisitIndexerExpression(IndexerExpression indexerExpression)
{ {
if (resolverEnabled) { if (resolverEnabled || NeedsResolvingDueToNamedArguments(indexerExpression)) {
Expression target = indexerExpression.Target; Expression target = indexerExpression.Target;
ResolveResult targetResult = Resolve(target); ResolveResult targetResult = Resolve(target);
string[] argumentNames; string[] argumentNames;
@ -1405,6 +1422,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult rr = resolver.ResolveIndexer(targetResult, arguments, argumentNames); ResolveResult rr = resolver.ResolveIndexer(targetResult, arguments, argumentNames);
ArrayAccessResolveResult aarr = rr as ArrayAccessResolveResult; ArrayAccessResolveResult aarr = rr as ArrayAccessResolveResult;
if (aarr != null) { if (aarr != null) {
MarkUnknownNamedArguments(indexerExpression.Arguments);
ProcessConversionResults(indexerExpression.Arguments, aarr.Indexes); ProcessConversionResults(indexerExpression.Arguments, aarr.Indexes);
} else { } else {
ProcessConversionsInInvocation(target, indexerExpression.Arguments, rr as CSharpInvocationResolveResult); ProcessConversionsInInvocation(target, indexerExpression.Arguments, rr as CSharpInvocationResolveResult);
@ -1436,8 +1454,12 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// by calling GetArguments(). // by calling GetArguments().
// This method gets called only when scanning, or when the named argument is used // This method gets called only when scanning, or when the named argument is used
// in an invalid context. // in an invalid context.
Scan(namedArgumentExpression.Expression); if (resolverEnabled) {
return null; return new NamedArgumentResolveResult(namedArgumentExpression.Name, Resolve(namedArgumentExpression.Expression));
} else {
Scan(namedArgumentExpression.Expression);
return null;
}
} }
// NamedExpression is "identifier = Expression" in object initializers and attributes // NamedExpression is "identifier = Expression" in object initializers and attributes
@ -1476,48 +1498,44 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<ResolveResult>.VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression) ResolveResult IAstVisitor<ResolveResult>.VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression)
{ {
if (resolverEnabled || !objectCreateExpression.Initializer.IsNull) { var typeResolveResult = Resolve(objectCreateExpression.Type);
var typeResolveResult = Resolve(objectCreateExpression.Type); if (typeResolveResult.IsError) {
if (typeResolveResult.IsError) { ScanChildren (objectCreateExpression);
ScanChildren (objectCreateExpression); return typeResolveResult;
return typeResolveResult; }
} IType type = typeResolveResult.Type;
IType type = typeResolveResult.Type;
List<ResolveResult> initializerStatements = null;
List<ResolveResult> initializerStatements = null; var initializer = objectCreateExpression.Initializer;
var initializer = objectCreateExpression.Initializer; if (!initializer.IsNull) {
if (!initializer.IsNull) { initializerStatements = new List<ResolveResult>();
initializerStatements = new List<ResolveResult>(); HandleObjectInitializer(new InitializedObjectResolveResult(type), initializer, initializerStatements);
HandleObjectInitializer(new InitializedObjectResolveResult(type), initializer, initializerStatements); }
}
string[] argumentNames;
string[] argumentNames; ResolveResult[] arguments = GetArguments(objectCreateExpression.Arguments, out argumentNames);
ResolveResult[] arguments = GetArguments(objectCreateExpression.Arguments, out argumentNames);
ResolveResult rr = resolver.ResolveObjectCreation(type, arguments, argumentNames, false, initializerStatements);
ResolveResult rr = resolver.ResolveObjectCreation(type, arguments, argumentNames, false, initializerStatements); if (arguments.Length == 1 && rr.Type.Kind == TypeKind.Delegate) {
if (arguments.Length == 1 && rr.Type.Kind == TypeKind.Delegate) { MarkUnknownNamedArguments(objectCreateExpression.Arguments);
// Apply conversion to argument if it directly wraps the argument // Apply conversion to argument if it directly wraps the argument
// (but not when creating a delegate from a delegate, as then there would be a MGRR for .Invoke in between) // (but not when creating a delegate from a delegate, as then there would be a MGRR for .Invoke in between)
// This is necessary for lambda type inference. // This is necessary for lambda type inference.
var crr = rr as ConversionResolveResult; var crr = rr as ConversionResolveResult;
if (crr != null && crr.Input == arguments[0]) { if (crr != null && crr.Input == arguments[0]) {
ProcessConversionResult(objectCreateExpression.Arguments.Single(), crr); ProcessConversionResult(objectCreateExpression.Arguments.Single(), crr);
// wrap the result so that the delegate creation is not handled as a reference // wrap the result so that the delegate creation is not handled as a reference
// to the target method - otherwise FindReferencedEntities would produce two results for // to the target method - otherwise FindReferencedEntities would produce two results for
// the same delegate creation. // the same delegate creation.
return WrapResult(rr); return WrapResult(rr);
} else {
return rr;
}
} else { } else {
// process conversions in all other cases
ProcessConversionsInInvocation(null, objectCreateExpression.Arguments, rr as CSharpInvocationResolveResult);
return rr; return rr;
} }
} else { } else {
ScanChildren(objectCreateExpression); // process conversions in all other cases
return null; ProcessConversionsInInvocation(null, objectCreateExpression.Arguments, rr as CSharpInvocationResolveResult);
return rr;
} }
} }
@ -1700,6 +1718,15 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return result; return result;
} }
/// <summary>
/// Gets and resolves the arguments; unpacking any NamedArgumentExpressions.
/// </summary>
/// <remarks>
/// Callers of GetArguments must also call either ProcessConversionsInInvocation or MarkUnknownNamedArguments
/// to ensure the named arguments get resolved.
/// Also, as named arguments get resolved by the parent node, the parent node must not scan
/// into the argument list without being resolved - see NeedsResolvingDueToNamedArguments().
/// </remarks>
ResolveResult[] GetArguments(IEnumerable<Expression> argumentExpressions, out string[] argumentNames) ResolveResult[] GetArguments(IEnumerable<Expression> argumentExpressions, out string[] argumentNames)
{ {
argumentNames = null; argumentNames = null;
@ -1721,6 +1748,15 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return arguments; return arguments;
} }
bool NeedsResolvingDueToNamedArguments(Expression nodeWithArguments)
{
for (AstNode child = nodeWithArguments.FirstChild; child != null; child = child.NextSibling) {
if (child is NamedArgumentExpression)
return true;
}
return false;
}
static NameLookupMode GetNameLookupMode(Expression expr) static NameLookupMode GetNameLookupMode(Expression expr)
{ {
InvocationExpression ie = expr.Parent as InvocationExpression; InvocationExpression ie = expr.Parent as InvocationExpression;
@ -1839,7 +1875,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} }
} else { } else {
// Regular code path // Regular code path
if (resolverEnabled) { if (resolverEnabled || NeedsResolvingDueToNamedArguments(invocationExpression)) {
ResolveResult target = Resolve(invocationExpression.Target); ResolveResult target = Resolve(invocationExpression.Target);
return ResolveInvocationOnGivenTarget(target, invocationExpression); return ResolveInvocationOnGivenTarget(target, invocationExpression);
} else { } else {
@ -3778,10 +3814,6 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
#region Constructor Initializer #region Constructor Initializer
ResolveResult IAstVisitor<ResolveResult>.VisitConstructorInitializer(ConstructorInitializer constructorInitializer) ResolveResult IAstVisitor<ResolveResult>.VisitConstructorInitializer(ConstructorInitializer constructorInitializer)
{ {
if (!resolverEnabled) {
ScanChildren(constructorInitializer);
return null;
}
ResolveResult target; ResolveResult target;
if (constructorInitializer.ConstructorInitializerType == ConstructorInitializerType.Base) { if (constructorInitializer.ConstructorInitializerType == ConstructorInitializerType.Base) {
target = resolver.ResolveBaseReference(); target = resolver.ResolveBaseReference();

15
ICSharpCode.NRefactory.CSharp/TypeSystem/TypeSystemConvertVisitor.cs

@ -22,13 +22,10 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using ICSharpCode.NRefactory.CSharp.Analysis;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem; using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.CSharp.TypeSystem.ConstantValues; using ICSharpCode.NRefactory.CSharp.TypeSystem.ConstantValues;
using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation; using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp.TypeSystem namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{ {
@ -100,7 +97,17 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
if (node == null || node.IsNull) if (node == null || node.IsNull)
return DomRegion.Empty; return DomRegion.Empty;
else else
return MakeRegion(node.StartLocation, node.EndLocation); return MakeRegion(GetStartLocationAfterAttributes(node), node.EndLocation);
}
internal static TextLocation GetStartLocationAfterAttributes(AstNode node)
{
AstNode child = node.FirstChild;
// Skip attributes and comments between attributes for the purpose of
// getting a declaration's region.
while (child != null && (child is AttributeSection || child.NodeType == NodeType.Whitespace))
child = child.NextSibling;
return (child ?? node).StartLocation;
} }
DomRegion MakeBraceRegion(AstNode node) DomRegion MakeBraceRegion(AstNode node)

18
ICSharpCode.NRefactory.ConsistencyCheck/ICSharpCode.NRefactory.ConsistencyCheck.csproj

@ -38,6 +38,24 @@
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' "> <PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>true</DebugSymbols>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>bin\Release\</OutputPath>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Build" /> <Reference Include="Microsoft.Build" />
<Reference Include="System" /> <Reference Include="System" />

30
ICSharpCode.NRefactory.Demo/ICSharpCode.NRefactory.Demo.csproj

@ -45,6 +45,36 @@
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>True</DebugSymbols>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|x86' ">
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|AnyCPU' ">
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>bin\Release\</OutputPath>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|x86' ">
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' ">
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core"> <Reference Include="System.Core">

224
ICSharpCode.NRefactory.GtkDemo/ICSharpCode.NRefactory.GtkDemo.csproj

@ -1,103 +1,123 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion> <ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A7EEF7F8-238F-459D-95A9-96467539641D}</ProjectGuid> <ProjectGuid>{A7EEF7F8-238F-459D-95A9-96467539641D}</ProjectGuid>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<RootNamespace>ICSharpCode.NRefactory.GtkDemo</RootNamespace> <RootNamespace>ICSharpCode.NRefactory.GtkDemo</RootNamespace>
<AssemblyName>ICSharpCode.NRefactory.GtkDemo</AssemblyName> <AssemblyName>ICSharpCode.NRefactory.GtkDemo</AssemblyName>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath> <OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants> <DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause> <ConsolePause>false</ConsolePause>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType> <DebugType>none</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Release</OutputPath> <OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause> <ConsolePause>false</ConsolePause>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|AnyCPU' ">
<Reference Include="System" /> <DebugSymbols>true</DebugSymbols>
<Reference Include="gtk-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f"> <DebugType>full</DebugType>
<Package>gtk-sharp-2.0</Package> <Optimize>false</Optimize>
</Reference> <OutputPath>bin\Debug</OutputPath>
<Reference Include="gdk-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f"> <DefineConstants>DEBUG;</DefineConstants>
<Package>gtk-sharp-2.0</Package> <ErrorReport>prompt</ErrorReport>
</Reference> <WarningLevel>4</WarningLevel>
<Reference Include="glib-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f"> <ConsolePause>false</ConsolePause>
<Package>glib-sharp-2.0</Package> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</Reference> </PropertyGroup>
<Reference Include="glade-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f"> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' ">
<Package>glade-sharp-2.0</Package> <DebugType>none</DebugType>
</Reference> <Optimize>false</Optimize>
<Reference Include="pango-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f"> <OutputPath>bin\Release</OutputPath>
<Package>gtk-sharp-2.0</Package> <ErrorReport>prompt</ErrorReport>
</Reference> <WarningLevel>4</WarningLevel>
<Reference Include="atk-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f"> <ConsolePause>false</ConsolePause>
<Package>gtk-sharp-2.0</Package> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</Reference> </PropertyGroup>
<Reference Include="Mono.Posix" /> <ItemGroup>
<Reference Include="System.Core" /> <Reference Include="System" />
</ItemGroup> <Reference Include="gtk-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f">
<ItemGroup> <Package>gtk-sharp-2.0</Package>
<EmbeddedResource Include="gtk-gui\gui.stetic"> </Reference>
<LogicalName>gui.stetic</LogicalName> <Reference Include="gdk-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f">
</EmbeddedResource> <Package>gtk-sharp-2.0</Package>
<EmbeddedResource Include="pixbuf\comment.png"> </Reference>
<LogicalName>comment.png</LogicalName> <Reference Include="glib-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f">
</EmbeddedResource> <Package>glib-sharp-2.0</Package>
<EmbeddedResource Include="pixbuf\element-class-16.png"> </Reference>
<LogicalName>class.png</LogicalName> <Reference Include="glade-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f">
</EmbeddedResource> <Package>glade-sharp-2.0</Package>
<EmbeddedResource Include="pixbuf\element-field-16.png"> </Reference>
<LogicalName>expression.png</LogicalName> <Reference Include="pango-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f">
</EmbeddedResource> <Package>gtk-sharp-2.0</Package>
<EmbeddedResource Include="pixbuf\element-literal-16.png"> </Reference>
<LogicalName>token.png</LogicalName> <Reference Include="atk-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f">
</EmbeddedResource> <Package>gtk-sharp-2.0</Package>
<EmbeddedResource Include="pixbuf\element-method-16.png"> </Reference>
<LogicalName>statement.png</LogicalName> <Reference Include="Mono.Posix" />
</EmbeddedResource> <Reference Include="System.Core" />
<EmbeddedResource Include="pixbuf\element-namespace-16.png"> </ItemGroup>
<LogicalName>namespace.png</LogicalName> <ItemGroup>
</EmbeddedResource> <EmbeddedResource Include="gtk-gui\gui.stetic">
</ItemGroup> <LogicalName>gui.stetic</LogicalName>
<ItemGroup> </EmbeddedResource>
<Compile Include="gtk-gui\generated.cs" /> <EmbeddedResource Include="pixbuf\comment.png">
<Compile Include="Main.cs" /> <LogicalName>comment.png</LogicalName>
<Compile Include="AssemblyInfo.cs" /> </EmbeddedResource>
<Compile Include="MainWindow.cs" /> <EmbeddedResource Include="pixbuf\element-class-16.png">
<Compile Include="gtk-gui\ICSharpCode.NRefactory.GtkDemo.MainWindow.cs" /> <LogicalName>class.png</LogicalName>
</ItemGroup> </EmbeddedResource>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <EmbeddedResource Include="pixbuf\element-field-16.png">
<ItemGroup> <LogicalName>expression.png</LogicalName>
<ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj"> </EmbeddedResource>
<Project>{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}</Project> <EmbeddedResource Include="pixbuf\element-literal-16.png">
<Name>ICSharpCode.NRefactory</Name> <LogicalName>token.png</LogicalName>
</ProjectReference> </EmbeddedResource>
<ProjectReference Include="..\ICSharpCode.NRefactory.CSharp\ICSharpCode.NRefactory.CSharp.csproj"> <EmbeddedResource Include="pixbuf\element-method-16.png">
<Project>{53DCA265-3C3C-42F9-B647-F72BA678122B}</Project> <LogicalName>statement.png</LogicalName>
<Name>ICSharpCode.NRefactory.CSharp</Name> </EmbeddedResource>
</ProjectReference> <EmbeddedResource Include="pixbuf\element-namespace-16.png">
</ItemGroup> <LogicalName>namespace.png</LogicalName>
<ItemGroup> </EmbeddedResource>
<None Include="CSharpDemo.cs"> </ItemGroup>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <ItemGroup>
</None> <Compile Include="gtk-gui\generated.cs" />
</ItemGroup> <Compile Include="Main.cs" />
<ItemGroup> <Compile Include="AssemblyInfo.cs" />
<Folder Include="pixbuf\" /> <Compile Include="MainWindow.cs" />
</ItemGroup> <Compile Include="gtk-gui\ICSharpCode.NRefactory.GtkDemo.MainWindow.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj">
<Project>{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}</Project>
<Name>ICSharpCode.NRefactory</Name>
</ProjectReference>
<ProjectReference Include="..\ICSharpCode.NRefactory.CSharp\ICSharpCode.NRefactory.CSharp.csproj">
<Project>{53DCA265-3C3C-42F9-B647-F72BA678122B}</Project>
<Name>ICSharpCode.NRefactory.CSharp</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="CSharpDemo.cs">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="pixbuf\" />
</ItemGroup>
</Project> </Project>

6
ICSharpCode.NRefactory.Tests/CSharp/CodeActions/ContextActionTestBase.cs

@ -86,7 +86,11 @@ namespace ICSharpCode.NRefactory.CSharp.CodeActions
protected static void TestWrongContext<T> (string input) where T : ICodeActionProvider, new () protected static void TestWrongContext<T> (string input) where T : ICodeActionProvider, new ()
{ {
ICodeActionProvider action = new T (); TestWrongContext (new T(), input);
}
protected static void TestWrongContext (ICodeActionProvider action, string input)
{
var context = TestRefactoringContext.Create (input); var context = TestRefactoringContext.Create (input);
bool isValid = action.GetActions (context).Any (); bool isValid = action.GetActions (context).Any ();
if (!isValid) if (!isValid)

28
ICSharpCode.NRefactory.Tests/CSharp/CodeActions/GeneratePropertyTests.cs

@ -1,4 +1,4 @@
// //
// GeneratePropertyTests.cs // GeneratePropertyTests.cs
// //
// Author: // Author:
@ -107,5 +107,31 @@ class TestClass
int myField, myOtherField; int myField, myOtherField;
}"); }");
} }
[Test]
public void CannotGeneratePropertyForReadOnlyField()
{
TestWrongContext (
new GeneratePropertyAction (),
"using System;" + Environment.NewLine +
"class TestClass" + Environment.NewLine +
"{" + Environment.NewLine +
" readonly int $myField;" + Environment.NewLine +
"}"
);
}
[Test]
public void CannotGeneratePropertyForConst()
{
TestWrongContext (
new GeneratePropertyAction (),
"using System;" + Environment.NewLine +
"class TestClass" + Environment.NewLine +
"{" + Environment.NewLine +
" const int $myField = 0;" + Environment.NewLine +
"}"
);
}
} }
} }

148
ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/BrowsableAttributeTests.cs

@ -0,0 +1,148 @@
//
// BrowsableAttributeTests.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using NUnit.Framework;
using System.Diagnostics;
namespace ICSharpCode.NRefactory.CSharp.CodeCompletion
{
[TestFixture]
public class BrowsableAttributeTests : TestBase
{
[Test()]
public void TestEditorBrowsableAttributeClasses ()
{
int cp;
var engine1 = CodeCompletionBugTests.CreateEngine (
@"
using System;
using System.ComponentModel;
[EditorBrowsable(EditorBrowsableState.Always)]
public class BrowsableTest {}
[EditorBrowsable(EditorBrowsableState.Never)]
public class NotBrowsableTest {}
", out cp);
CompletionDataList provider = CodeCompletionBugTests.CreateProvider (
@"class Test
{
void Test ()
{
$B$
}
}", false, engine1.ctx.CurrentAssembly.UnresolvedAssembly);
Assert.IsNotNull (provider, "provider == null");
Assert.IsNotNull (provider.Find ("BrowsableTest"), "'BrowsableTest' not found.");
Assert.IsNull (provider.Find ("NotBrowsableTest"), "'NotBrowsableTest' found.");
}
[Test()]
public void TestEditorBrowsableAttributeClassesSameAssembly ()
{
CompletionDataList provider = CodeCompletionBugTests.CreateProvider (
@"
using System;
using System.ComponentModel;
[EditorBrowsable(EditorBrowsableState.Always)]
public class BrowsableTest {}
[EditorBrowsable(EditorBrowsableState.Never)]
public class NotBrowsableTest {}
class Test
{
void Test ()
{
$B$
}
}");
Assert.IsNotNull (provider, "provider == null");
Assert.IsNotNull (provider.Find ("BrowsableTest"), "'BrowsableTest' not found.");
Assert.IsNotNull (provider.Find ("NotBrowsableTest"), "'NotBrowsableTest' not found.");
}
[Test()]
public void TestEditorBrowsableAttributeMembers ()
{
int cp;
var engine1 = CodeCompletionBugTests.CreateEngine (
@"
using System;
using System.ComponentModel;
public class FooBar
{
[EditorBrowsable(EditorBrowsableState.Always)]
public int BrowsableTest { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
public int NotBrowsableTest { get; set; }
}
", out cp);
CompletionDataList provider = CodeCompletionBugTests.CreateProvider (
@"class Test : FooBar
{
void Test ()
{
$B$
}
}", false, engine1.ctx.CurrentAssembly.UnresolvedAssembly);
Assert.IsNotNull (provider, "provider == null");
Assert.IsNotNull (provider.Find ("BrowsableTest"), "'BrowsableTest' not found.");
Assert.IsNull (provider.Find ("NotBrowsableTest"), "'NotBrowsableTest' found.");
}
[Test()]
public void TestEditorBrowsableAttributeMembersSameAssembly ()
{
CompletionDataList provider = CodeCompletionBugTests.CreateProvider (
@"
using System;
using System.ComponentModel;
class Test
{
[EditorBrowsable(EditorBrowsableState.Always)]
int BrowsableTest { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
int NotBrowsableTest { get; set; }
void Test ()
{
$B$
}
}");
Assert.IsNotNull (provider, "provider == null");
Assert.IsNotNull (provider.Find ("BrowsableTest"), "'BrowsableTest' not found.");
Assert.IsNotNull (provider.Find ("NotBrowsableTest"), "'NotBrowsableTest' not found.");
}
}
}

78
ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/CodeCompletionBugTests.cs

@ -136,15 +136,6 @@ namespace ICSharpCode.NRefactory.CSharp.CodeCompletion
return new CompletionData (entity.Name); return new CompletionData (entity.Name);
} }
public ICompletionData CreateEntityCompletionData (ICSharpCode.NRefactory.TypeSystem.IUnresolvedEntity entity, string text)
{
return new CompletionData (text);
}
public ICompletionData CreateTypeCompletionData (ICSharpCode.NRefactory.TypeSystem.IUnresolvedTypeDefinition type, string shortType)
{
return new CompletionData (shortType);
}
public ICompletionData CreateTypeCompletionData (ICSharpCode.NRefactory.TypeSystem.IType type, string shortType) public ICompletionData CreateTypeCompletionData (ICSharpCode.NRefactory.TypeSystem.IType type, string shortType)
{ {
@ -166,7 +157,7 @@ namespace ICSharpCode.NRefactory.CSharp.CodeCompletion
return new CompletionData (variable.Name); return new CompletionData (variable.Name);
} }
public ICompletionData CreateVariableCompletionData (ICSharpCode.NRefactory.TypeSystem.IUnresolvedTypeParameter parameter) public ICompletionData CreateVariableCompletionData (ICSharpCode.NRefactory.TypeSystem.ITypeParameter parameter)
{ {
return new CompletionData (parameter.Name); return new CompletionData (parameter.Name);
} }
@ -199,52 +190,71 @@ namespace ICSharpCode.NRefactory.CSharp.CodeCompletion
#endregion #endregion
} }
static CompletionDataList CreateProvider(string text, bool isCtrlSpace) public static IUnresolvedAssembly SystemAssembly { get { return systemAssembly.Value; } }
static readonly Lazy<IUnresolvedAssembly> systemAssembly = new Lazy<IUnresolvedAssembly>(
delegate {
return new CecilLoader().LoadAssemblyFile(typeof(System.ComponentModel.BrowsableAttribute).Assembly.Location);
});
public static CSharpCompletionEngine CreateEngine(string text, out int cursorPosition, params IUnresolvedAssembly[] references)
{ {
string parsedText; string parsedText;
string editorText; string editorText;
int cursorPosition = text.IndexOf('$'); cursorPosition = text.IndexOf('$');
int endPos = text.IndexOf('$', cursorPosition + 1); int endPos = text.IndexOf('$', cursorPosition + 1);
if (endPos == -1) { if (endPos == -1) {
parsedText = editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1); if (cursorPosition < 0) {
parsedText = editorText = text;
} else {
parsedText = editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1);
}
} else { } else {
parsedText = text.Substring(0, cursorPosition) + new string(' ', endPos - cursorPosition) + text.Substring(endPos + 1); parsedText = text.Substring(0, cursorPosition) + new string(' ', endPos - cursorPosition) + text.Substring(endPos + 1);
editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring(endPos + 1); editorText = text.Substring(0, cursorPosition) + text.Substring(cursorPosition + 1, endPos - cursorPosition - 1) + text.Substring(endPos + 1);
cursorPosition = endPos - 1; cursorPosition = endPos - 1;
} }
var doc = new ReadOnlyDocument(editorText); var doc = new ReadOnlyDocument(editorText);
IProjectContent pctx = new CSharpProjectContent(); IProjectContent pctx = new CSharpProjectContent();
pctx = pctx.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); var refs = new List<IUnresolvedAssembly> { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore, SystemAssembly };
if (references != null)
refs.AddRange (references);
pctx = pctx.AddAssemblyReferences(refs);
var compilationUnit = new CSharpParser().Parse(parsedText, "program.cs"); var compilationUnit = new CSharpParser().Parse(parsedText, "program.cs");
compilationUnit.Freeze(); compilationUnit.Freeze();
var parsedFile = compilationUnit.ToTypeSystem(); var parsedFile = compilationUnit.ToTypeSystem();
pctx = pctx.UpdateProjectContent(null, parsedFile); pctx = pctx.UpdateProjectContent(null, parsedFile);
var cmp = pctx.CreateCompilation(); var cmp = pctx.CreateCompilation();
var loc = doc.GetLocation(cursorPosition); var loc = cursorPosition > 0 ? doc.GetLocation(cursorPosition) : new TextLocation (1, 1);
var rctx = new CSharpTypeResolveContext(cmp.MainAssembly); var rctx = new CSharpTypeResolveContext(cmp.MainAssembly);
rctx = rctx.WithUsingScope(parsedFile.GetUsingScope(loc).Resolve(cmp)); rctx = rctx.WithUsingScope(parsedFile.GetUsingScope(loc).Resolve(cmp));
var curDef = parsedFile.GetInnermostTypeDefinition(loc); var curDef = parsedFile.GetInnermostTypeDefinition(loc);
if (curDef != null) { if (curDef != null) {
var resolvedDef = curDef.Resolve(rctx).GetDefinition(); var resolvedDef = curDef.Resolve(rctx).GetDefinition();
rctx = rctx.WithCurrentTypeDefinition(resolvedDef); rctx = rctx.WithCurrentTypeDefinition(resolvedDef);
var curMember = resolvedDef.Members.FirstOrDefault(m => m.Region.Begin <= loc && loc < m.BodyRegion.End); var curMember = resolvedDef.Members.FirstOrDefault(m => m.Region.Begin <= loc && loc < m.BodyRegion.End);
if (curMember != null) { if (curMember != null) {
rctx = rctx.WithCurrentMember(curMember); rctx = rctx.WithCurrentMember(curMember);
} }
} }
var mb = new DefaultCompletionContextProvider(doc, parsedFile); var mb = new DefaultCompletionContextProvider(doc, parsedFile);
var engine = new CSharpCompletionEngine (doc, mb, new TestFactory (), pctx, rctx); var engine = new CSharpCompletionEngine(doc, mb, new TestFactory(), pctx, rctx);
engine.EolMarker = Environment.NewLine; engine.EolMarker = Environment.NewLine;
engine.FormattingPolicy = FormattingOptionsFactory.CreateMono (); engine.FormattingPolicy = FormattingOptionsFactory.CreateMono();
return engine;
}
public static CompletionDataList CreateProvider(string text, bool isCtrlSpace, params IUnresolvedAssembly[] references)
{
int cursorPosition;
var engine = CreateEngine(text, out cursorPosition, references);
var data = engine.GetCompletionData (cursorPosition, isCtrlSpace); var data = engine.GetCompletionData (cursorPosition, isCtrlSpace);
return new CompletionDataList () { return new CompletionDataList () {

24
ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/DelegateContextTests.cs

@ -97,6 +97,30 @@ public class Test
Assert.IsNotNull(provider.Find("(arg1, arg2)")); Assert.IsNotNull(provider.Find("(arg1, arg2)"));
}); });
} }
[Test()]
public void TestRefOutParams()
{
CodeCompletionBugTests.CombinedProviderTest(
@"using System;
public delegate void FooBar (out int foo, ref int bar, params object[] additional);
public class Test
{
FooBar foo;
void TestFoo()
{
$foo = d$
}
}
", provider => {
Assert.IsFalse(provider.AutoSelect);
Assert.IsNotNull(provider.Find("(out int foo, ref int bar, object[] additional)"));
Assert.IsNull(provider.Find("(foo, bar, additional)"));
});
}
} }
} }

19
ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/PreprocessorDirectiveTests.cs

@ -245,5 +245,24 @@ class B { }
Assert.AreEqual(PreProcessorDirectiveType.Elif, bbb.Type); Assert.AreEqual(PreProcessorDirectiveType.Elif, bbb.Type);
Assert.AreEqual("BBB", bbb.Argument); Assert.AreEqual("BBB", bbb.Argument);
} }
[Test]
[Ignore("parser bug (BBB is missing)")]
public void ConditionalSymbolTest()
{
const string program = @"// Test
#if AAA
#undef AAA
#define CCC
#else
#define DDD
#endif
class C {}";
CSharpParser parser = new CSharpParser();
parser.CompilerSettings.ConditionalSymbols.Add("AAA");
parser.CompilerSettings.ConditionalSymbols.Add("BBB");
var cu = parser.Parse(program, "elif.cs");
Assert.AreEqual(new[] { "BBB", "CCC" }, cu.ConditionalSymbols);
}
} }
} }

70
ICSharpCode.NRefactory.Tests/CSharp/Resolver/InvocationTests.cs

@ -539,5 +539,75 @@ class D : B {
Assert.IsFalse(rr.IsError); Assert.IsFalse(rr.IsError);
Assert.IsFalse(rr.IsVirtualCall); Assert.IsFalse(rr.IsVirtualCall);
} }
[Test]
public void NamedArgument()
{
string program = @"
class Test {
public void F(int x) {}
public void Test() {
F($x: 0$);
}
}";
var narr = Resolve<NamedArgumentResolveResult>(program);
Assert.IsInstanceOf<ConstantResolveResult>(narr.Argument);
Assert.AreEqual("x", narr.ParameterName);
Assert.AreEqual("Test.F", narr.Member.FullName);
Assert.AreSame(narr.Member.Parameters.Single(), narr.Parameter);
}
[Test]
public void NamedArgumentInInvocation()
{
string program = @"
class Test {
public void F(int x) {}
public void Test() {
$F(x: 0)$;
}
}";
var rr = Resolve<CSharpInvocationResolveResult>(program);
Assert.IsInstanceOf<NamedArgumentResolveResult>(rr.Arguments.Single());
var narr = (NamedArgumentResolveResult)rr.Arguments.Single();
Assert.IsInstanceOf<ConstantResolveResult>(narr.Argument);
Assert.AreEqual("x", narr.ParameterName);
Assert.AreEqual("Test.F", narr.Member.FullName);
Assert.AreSame(narr.Member.Parameters.Single(), narr.Parameter);
// but GetArgumentsForCall() should directly return the constant:
Assert.IsInstanceOf<ConstantResolveResult>(rr.GetArgumentsForCall().Single());
}
[Test]
public void UnknownNamedArgument()
{
string program = @"
class Test {
public void F(int x) {}
public void Test() {
F($y: 0$);
}
}";
var narr = Resolve<NamedArgumentResolveResult>(program);
Assert.IsInstanceOf<ConstantResolveResult>(narr.Argument);
Assert.AreEqual("y", narr.ParameterName);
Assert.IsNull(narr.Parameter);
}
[Test]
public void NamedArgumentInMissingMethod()
{
string program = @"
class Test {
public void Test() {
Missing($x: 0$);
}
}";
var narr = Resolve<NamedArgumentResolveResult>(program);
Assert.IsInstanceOf<ConstantResolveResult>(narr.Argument);
Assert.AreEqual("x", narr.ParameterName);
Assert.IsNull(narr.Parameter);
}
} }
} }

41
ICSharpCode.NRefactory.Tests/CSharp/Resolver/MethodTests.cs

@ -1,14 +1,45 @@
using System; // Copyright (c) AlphaSierraPapa for the SharpDevelop Team
using System.Collections.Generic; //
// 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 System.Linq; using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem;
using NUnit.Framework; using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp.Resolver { namespace ICSharpCode.NRefactory.CSharp.Resolver
{
[TestFixture] [TestFixture]
public class MethodTests : ResolverTestBase { public class MethodTests : ResolverTestBase
{
[Test]
public void MethodDeclarationWithAttribute()
{
string code = @"using System;
class TestClass {
$[Obsolete(""test"")]
public void M() {
}$
}";
var mrr = Resolve<MemberResolveResult>(code);
Assert.AreEqual("TestClass.M", mrr.Member.FullName);
}
[Test] [Test]
public void ParameterIdentityInNormalMethod() public void ParameterIdentityInNormalMethod()
{ {

43
ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj

@ -65,6 +65,48 @@
<PropertyGroup Condition=" '$(Platform)' == 'x86' "> <PropertyGroup Condition=" '$(Platform)' == 'x86' ">
<PlatformTarget>x86</PlatformTarget> <PlatformTarget>x86</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>true</DebugSymbols>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|AnyCPU' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<BaseAddress>4194304</BaseAddress>
<FileAlignment>4096</FileAlignment>
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|x86' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>bin\Release\</OutputPath>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<BaseAddress>4194304</BaseAddress>
<FileAlignment>4096</FileAlignment>
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|x86' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System" /> <Reference Include="System" />
@ -298,6 +340,7 @@
<Compile Include="CSharp\CodeIssues\IncorrectCallToGetHashCodeTests.cs" /> <Compile Include="CSharp\CodeIssues\IncorrectCallToGetHashCodeTests.cs" />
<Compile Include="CSharp\CodeIssues\FormatStringIssues\FormatStringTests.cs" /> <Compile Include="CSharp\CodeIssues\FormatStringIssues\FormatStringTests.cs" />
<Compile Include="CSharp\CodeActions\ConvertToInitializer\ConvertInitializerToExplicitIntializationsTests.cs" /> <Compile Include="CSharp\CodeActions\ConvertToInitializer\ConvertInitializerToExplicitIntializationsTests.cs" />
<Compile Include="CSharp\CodeCompletion\BrowsableAttributeTests.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\Mono.Cecil\Mono.Cecil.csproj"> <ProjectReference Include="..\..\Mono.Cecil\Mono.Cecil.csproj">

8
ICSharpCode.NRefactory.Tests/TypeSystem/CecilLoaderTests.cs

@ -35,12 +35,12 @@ namespace ICSharpCode.NRefactory.TypeSystem
static readonly Lazy<IUnresolvedAssembly> systemCore = new Lazy<IUnresolvedAssembly>( static readonly Lazy<IUnresolvedAssembly> systemCore = new Lazy<IUnresolvedAssembly>(
delegate { delegate {
return new CecilLoader().LoadAssemblyFile(typeof(System.Linq.Enumerable).Assembly.Location); return new CecilLoader().LoadAssemblyFile(typeof(System.Linq.Enumerable).Assembly.Location);
}); });
public static IUnresolvedAssembly Mscorlib { get { return mscorlib.Value; } } public static IUnresolvedAssembly Mscorlib { get { return mscorlib.Value; } }
public static IUnresolvedAssembly SystemCore { get { return systemCore.Value; } } public static IUnresolvedAssembly SystemCore { get { return systemCore.Value; } }
[TestFixtureSetUp] [TestFixtureSetUp]
public void FixtureSetUp() public void FixtureSetUp()
{ {

22
ICSharpCode.NRefactory.Xml/ICSharpCode.NRefactory.Xml.csproj

@ -47,6 +47,28 @@
<DebugType>PdbOnly</DebugType> <DebugType>PdbOnly</DebugType>
<DebugSymbols>false</DebugSymbols> <DebugSymbols>false</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|AnyCPU' ">
<DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' ">
<DebugType>PdbOnly</DebugType>
<DebugSymbols>false</DebugSymbols>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core"> <Reference Include="System.Core">

73
ICSharpCode.NRefactory/Completion/CompletionExtensionMethods.cs

@ -0,0 +1,73 @@
//
// CompletionExtensionMethods.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using ICSharpCode.NRefactory.TypeSystem;
using System.Linq;
namespace ICSharpCode.NRefactory.Completion
{
public static class CompletionExtensionMethods
{
/// <summary>
/// Gets the EditorBrowsableState of an entity.
/// </summary>
/// <returns>
/// The editor browsable state.
/// </returns>
/// <param name='entity'>
/// Entity.
/// </param>
public static System.ComponentModel.EditorBrowsableState GetEditorBrowsableState(this IEntity entity)
{
if (entity == null)
throw new ArgumentNullException ("entity");
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) {}
}
return System.ComponentModel.EditorBrowsableState.Always;
}
/// <summary>
/// Determines if an entity should be shown in the code completion window. This is the same as:
/// <c>GetEditorBrowsableState (entity) != System.ComponentModel.EditorBrowsableState.Never</c>
/// </summary>
/// <returns>
/// <c>true</c> if the entity should be shown; otherwise, <c>false</c>.
/// </returns>
/// <param name='entity'>
/// The entity.
/// </param>
public static bool IsBrowsable(this IEntity entity)
{
return GetEditorBrowsableState (entity) != System.ComponentModel.EditorBrowsableState.Never;
}
}
}

37
ICSharpCode.NRefactory/ICSharpCode.NRefactory.csproj

@ -15,7 +15,7 @@
<TreatWarningsAsErrors>false</TreatWarningsAsErrors> <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<RunCodeAnalysis>False</RunCodeAnalysis> <RunCodeAnalysis>False</RunCodeAnalysis>
<CodeAnalysisRules>-Microsoft.Design#CA1000;-Microsoft.Design#CA1004;-Microsoft.Design#CA1005;-Microsoft.Design#CA1006;-Microsoft.Design#CA1026;-Microsoft.Design#CA1033;-Microsoft.Design#CA1051;-Microsoft.Design#CA1063;-Microsoft.Naming#CA1702;-Microsoft.Naming#CA1704;-Microsoft.Naming#CA1710;-Microsoft.Naming#CA1716;-Microsoft.Naming#CA1720;-Microsoft.Performance#CA1800;-Microsoft.Security#CA2104</CodeAnalysisRules> <CodeAnalysisRules>-Microsoft.Design#CA1000;-Microsoft.Design#CA1004;-Microsoft.Design#CA1005;-Microsoft.Design#CA1006;-Microsoft.Design#CA1026;-Microsoft.Design#CA1033;-Microsoft.Design#CA1051;-Microsoft.Design#CA1063;-Microsoft.Naming#CA1702;-Microsoft.Naming#CA1704;-Microsoft.Naming#CA1710;-Microsoft.Naming#CA1716;-Microsoft.Naming#CA1720;-Microsoft.Performance#CA1800;-Microsoft.Security#CA2104</CodeAnalysisRules>
<SignAssembly>true</SignAssembly> <SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>..\ICSharpCode.NRefactory.snk</AssemblyOriginatorKeyFile> <AssemblyOriginatorKeyFile>..\ICSharpCode.NRefactory.snk</AssemblyOriginatorKeyFile>
<DelaySign>False</DelaySign> <DelaySign>False</DelaySign>
<AssemblyOriginatorKeyMode>File</AssemblyOriginatorKeyMode> <AssemblyOriginatorKeyMode>File</AssemblyOriginatorKeyMode>
@ -44,12 +44,33 @@
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugType>Full</DebugType> <DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>True</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>PdbOnly</DebugType> <DebugType>none</DebugType>
<DebugSymbols>false</DebugSymbols> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<Optimize>False</Optimize>
<DefineConstants>DEBUG;TRACE;NET45</DefineConstants>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<StartAction>Project</StartAction>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|AnyCPU' ">
<DebugType>full</DebugType>
<DebugSymbols>True</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>bin\Release\</OutputPath>
<Optimize>True</Optimize>
<DefineConstants>TRACE;NET45</DefineConstants>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' ">
<DebugType>none</DebugType>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
@ -99,6 +120,7 @@
<Compile Include="Semantics\InvocationResolveResult.cs" /> <Compile Include="Semantics\InvocationResolveResult.cs" />
<Compile Include="Semantics\LocalResolveResult.cs" /> <Compile Include="Semantics\LocalResolveResult.cs" />
<Compile Include="Semantics\MemberResolveResult.cs" /> <Compile Include="Semantics\MemberResolveResult.cs" />
<Compile Include="Semantics\NamedArgumentResolveResult.cs" />
<Compile Include="Semantics\NamespaceResolveResult.cs" /> <Compile Include="Semantics\NamespaceResolveResult.cs" />
<Compile Include="Semantics\OperatorResolveResult.cs" /> <Compile Include="Semantics\OperatorResolveResult.cs" />
<Compile Include="Semantics\ResolveResult.cs" /> <Compile Include="Semantics\ResolveResult.cs" />
@ -139,6 +161,7 @@
<Compile Include="TypeSystem\Implementation\AccessorOwnerMemberReference.cs" /> <Compile Include="TypeSystem\Implementation\AccessorOwnerMemberReference.cs" />
<Compile Include="TypeSystem\Implementation\BaseTypeCollector.cs" /> <Compile Include="TypeSystem\Implementation\BaseTypeCollector.cs" />
<Compile Include="TypeSystem\Implementation\DefaultAssemblyReference.cs" /> <Compile Include="TypeSystem\Implementation\DefaultAssemblyReference.cs" />
<Compile Include="TypeSystem\Implementation\DefaultAttribute.cs" />
<Compile Include="TypeSystem\Implementation\DefaultMemberReference.cs" /> <Compile Include="TypeSystem\Implementation\DefaultMemberReference.cs" />
<Compile Include="TypeSystem\Implementation\DefaultParameter.cs" /> <Compile Include="TypeSystem\Implementation\DefaultParameter.cs" />
<Compile Include="TypeSystem\Implementation\DefaultResolvedEvent.cs" /> <Compile Include="TypeSystem\Implementation\DefaultResolvedEvent.cs" />
@ -220,6 +243,7 @@
<Compile Include="Utils\ImmutableStack.cs" /> <Compile Include="Utils\ImmutableStack.cs" />
<Compile Include="Utils\KeyComparer.cs" /> <Compile Include="Utils\KeyComparer.cs" />
<Compile Include="Utils\LazyInit.cs" /> <Compile Include="Utils\LazyInit.cs" />
<Compile Include="Utils\MultiDictionary.cs" />
<Compile Include="Utils\Platform.cs" /> <Compile Include="Utils\Platform.cs" />
<Compile Include="Utils\ProjectedList.cs" /> <Compile Include="Utils\ProjectedList.cs" />
<Compile Include="Utils\ReferenceComparer.cs" /> <Compile Include="Utils\ReferenceComparer.cs" />
@ -239,6 +263,7 @@
<Compile Include="Utils\CompositeFormatStringParser\FormatStringSegmentBase.cs" /> <Compile Include="Utils\CompositeFormatStringParser\FormatStringSegmentBase.cs" />
<Compile Include="Utils\CompositeFormatStringParser\IFormatStringSegment.cs" /> <Compile Include="Utils\CompositeFormatStringParser\IFormatStringSegment.cs" />
<Compile Include="Utils\CompositeFormatStringParser\IFormatStringError.cs" /> <Compile Include="Utils\CompositeFormatStringParser\IFormatStringError.cs" />
<Compile Include="Completion\CompletionExtensionMethods.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="Completion\" /> <Folder Include="Completion\" />
@ -260,4 +285,4 @@
</None> </None>
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project> </Project>

81
ICSharpCode.NRefactory/Semantics/NamedArgumentResolveResult.cs

@ -0,0 +1,81 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// 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 System.Collections.Generic;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.Semantics
{
/// <summary>
/// Represents a named argument.
/// </summary>
public class NamedArgumentResolveResult : ResolveResult
{
/// <summary>
/// Gets the member to which the parameter belongs.
/// This field can be null.
/// </summary>
public readonly IParameterizedMember Member;
/// <summary>
/// Gets the parameter.
/// This field can be null.
/// </summary>
public readonly IParameter Parameter;
/// <summary>
/// Gets the parameter name.
/// </summary>
public readonly string ParameterName;
/// <summary>
/// Gets the argument passed to the parameter.
/// </summary>
public readonly ResolveResult Argument;
public NamedArgumentResolveResult(IParameter parameter, ResolveResult argument, IParameterizedMember member = null)
: base(argument.Type)
{
if (parameter == null)
throw new ArgumentNullException("parameter");
if (argument == null)
throw new ArgumentNullException("argument");
this.Member = member;
this.Parameter = parameter;
this.ParameterName = parameter.Name;
this.Argument = argument;
}
public NamedArgumentResolveResult(string parameterName, ResolveResult argument)
: base(argument.Type)
{
if (parameterName == null)
throw new ArgumentNullException("parameterName");
if (argument == null)
throw new ArgumentNullException("argument");
this.ParameterName = parameterName;
this.Argument = argument;
}
public override IEnumerable<ResolveResult> GetChildResults()
{
return new [] { Argument };
}
}
}

124
ICSharpCode.NRefactory/TypeSystem/CecilLoader.cs

@ -55,6 +55,12 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// the Cecil objects to stay in memory (which can significantly increase memory usage). /// the Cecil objects to stay in memory (which can significantly increase memory usage).
/// It also prevents serialization of the Cecil-loaded type system. /// It also prevents serialization of the Cecil-loaded type system.
/// </summary> /// </summary>
/// <remarks>
/// Because the type system can be used on multiple threads, but Cecil is not
/// thread-safe for concurrent read access, the CecilLoader will lock on the <see cref="ModuleDefinition"/> instance
/// for every delay-loading operation.
/// If you access the Cecil objects directly in your application, you may need to take the same lock.
/// </remarks>
public bool LazyLoad { get; set; } public bool LazyLoad { get; set; }
/// <summary> /// <summary>
@ -72,6 +78,17 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary> /// </summary>
public CancellationToken CancellationToken { get; set; } public CancellationToken CancellationToken { get; set; }
/// <summary>
/// This delegate gets executed whenever an entity was loaded.
/// </summary>
/// <remarks>
/// This callback may be to build a dictionary that maps between
/// entities and cecil objects.
/// Warning: if delay-loading is used and the type system is accessed by multiple threads,
/// the callback may be invoked concurrently on multiple threads.
/// </remarks>
public Action<IUnresolvedEntity, MemberReference> OnEntityLoaded { get; set; }
/// <summary> /// <summary>
/// Gets a value indicating whether this instance stores references to the cecil objects. /// Gets a value indicating whether this instance stores references to the cecil objects.
/// </summary> /// </summary>
@ -84,19 +101,26 @@ namespace ICSharpCode.NRefactory.TypeSystem
ModuleDefinition currentModule; ModuleDefinition currentModule;
CecilUnresolvedAssembly currentAssembly; CecilUnresolvedAssembly currentAssembly;
/// <summary>
/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.CecilLoader"/> class.
/// </summary>
public CecilLoader()
{
// Enable interning by default.
this.InterningProvider = new SimpleInterningProvider();
}
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.CecilLoader"/> class. /// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.CecilLoader"/> class.
/// </summary> /// </summary>
/// <param name='createCecilReferences'> /// <param name='createCecilReferences'>
/// If true references to the cecil objects are hold. In this case the cecil loader can do a type system -> cecil mapping. /// If true references to the cecil objects are hold. In this case the cecil loader can do a type system -> cecil mapping.
/// </param> /// </param>
public CecilLoader (bool createCecilReferences = false) [Obsolete("The built-in entity<->cecil mapping is obsolete. Use the OnEntityLoaded callback instead!")]
public CecilLoader(bool createCecilReferences) : this()
{ {
if (createCecilReferences) if (createCecilReferences)
typeSystemTranslationTable = new Dictionary<object, object> (); typeSystemTranslationTable = new Dictionary<object, object> ();
// Enable interning by default.
this.InterningProvider = new SimpleInterningProvider();
} }
/// <summary> /// <summary>
@ -108,6 +132,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
this.typeSystemTranslationTable = loader.typeSystemTranslationTable; this.typeSystemTranslationTable = loader.typeSystemTranslationTable;
this.IncludeInternalMembers = loader.IncludeInternalMembers; this.IncludeInternalMembers = loader.IncludeInternalMembers;
this.LazyLoad = loader.LazyLoad; this.LazyLoad = loader.LazyLoad;
this.OnEntityLoaded = loader.OnEntityLoaded;
this.currentModule = loader.currentModule; this.currentModule = loader.currentModule;
this.currentAssembly = loader.currentAssembly; this.currentAssembly = loader.currentAssembly;
// don't use interning - the interning provider is most likely not thread-safe // don't use interning - the interning provider is most likely not thread-safe
@ -169,12 +194,15 @@ namespace ICSharpCode.NRefactory.TypeSystem
continue; continue;
if (this.LazyLoad) { if (this.LazyLoad) {
currentAssembly.AddTypeDefinition(new LazyCecilTypeDefinition(cecilLoaderCloneForLazyLoading, td)); var t = new LazyCecilTypeDefinition(cecilLoaderCloneForLazyLoading, td);
currentAssembly.AddTypeDefinition(t);
RegisterCecilObject(t, td);
} else { } else {
var t = CreateTopLevelTypeDefinition(td); var t = CreateTopLevelTypeDefinition(td);
cecilTypeDefs.Add(td); cecilTypeDefs.Add(td);
typeDefs.Add(t); typeDefs.Add(t);
currentAssembly.AddTypeDefinition(t); currentAssembly.AddTypeDefinition(t);
// The registration will happen after the members are initialized
} }
} }
} }
@ -184,7 +212,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
InitTypeDefinition(cecilTypeDefs[i], typeDefs[i]); InitTypeDefinition(cecilTypeDefs[i], typeDefs[i]);
} }
RegisterCecilObject(this.currentAssembly, assemblyDefinition); AddToTypeSystemTranslationTable(this.currentAssembly, assemblyDefinition);
var result = this.currentAssembly; var result = this.currentAssembly;
this.currentAssembly = null; this.currentAssembly = null;
@ -249,9 +277,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
throw new ArgumentNullException("fileName"); throw new ArgumentNullException("fileName");
var param = new ReaderParameters { AssemblyResolver = new DummyAssemblyResolver() }; var param = new ReaderParameters { AssemblyResolver = new DummyAssemblyResolver() };
AssemblyDefinition asm = AssemblyDefinition.ReadAssembly(fileName, param); AssemblyDefinition asm = AssemblyDefinition.ReadAssembly(fileName, param);
var result = LoadAssembly(asm); return LoadAssembly(asm);
RegisterCecilObject(result, asm);
return result;
} }
// used to prevent Cecil from loading referenced assemblies // used to prevent Cecil from loading referenced assemblies
@ -941,7 +967,16 @@ namespace ICSharpCode.NRefactory.TypeSystem
return; return;
} }
foreach (var ctorParameter in ctorParameterTypes.Resolve(context)) { foreach (var ctorParameter in ctorParameterTypes.Resolve(context)) {
positionalArguments.Add(reader.ReadFixedArg(ctorParameter)); ResolveResult arg = reader.ReadFixedArg(ctorParameter);
positionalArguments.Add(arg);
if (arg.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:
while (positionalArguments.Count < ctorParameterTypes.Count)
positionalArguments.Add(ErrorResolveResult.UnknownError);
return;
}
} }
ushort numNamed = reader.ReadUInt16(); ushort numNamed = reader.ReadUInt16();
for (int i = 0; i < numNamed; i++) { for (int i = 0; i < numNamed; i++) {
@ -1105,6 +1140,9 @@ namespace ICSharpCode.NRefactory.TypeSystem
ResolveResult[] elements = new ResolveResult[numElem]; ResolveResult[] elements = new ResolveResult[numElem];
for (int i = 0; i < elements.Length; i++) { for (int i = 0; i < elements.Length; i++) {
elements[i] = ReadElem(elementType); elements[i] = ReadElem(elementType);
// Stop decoding when encountering an error:
if (elements[i].IsError)
return ErrorResolveResult.UnknownError;
} }
return new ArrayCreateResolveResult(argType, null, elements); return new ArrayCreateResolveResult(argType, null, elements);
} }
@ -1395,11 +1433,10 @@ namespace ICSharpCode.NRefactory.TypeSystem
namedArgs.Add(namedArg); namedArgs.Add(namedArg);
} }
attributes[i] = new ResolvedSecurityAttribute { attributes[i] = new DefaultAttribute(
AttributeType = attributeType, attributeType,
NamedArguments = namedArgs, positionalArguments: new ResolveResult[] { securityActionRR },
PositionalArguments = new ResolveResult[] { securityActionRR } namedArguments: namedArgs);
};
} }
} }
@ -1442,37 +1479,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
return secDecl.Resolve(context.CurrentAssembly)[index]; return secDecl.Resolve(context.CurrentAssembly)[index];
} }
} }
sealed class ResolvedSecurityAttribute : IAttribute
{
public IType AttributeType { get; internal set; }
DomRegion IAttribute.Region {
get { return DomRegion.Empty; }
}
volatile IMethod constructor;
public IMethod Constructor {
get {
IMethod ctor = this.constructor;
if (ctor == null) {
foreach (IMethod candidate in this.AttributeType.GetConstructors(m => m.Parameters.Count == 1)) {
if (candidate.Parameters[0].Type.Equals(this.PositionalArguments[0].Type)) {
ctor = candidate;
break;
}
}
this.constructor = ctor;
}
return ctor;
}
}
public IList<ResolveResult> PositionalArguments { get; internal set; }
public IList<KeyValuePair<IMember, ResolveResult>> NamedArguments { get; internal set; }
}
#endregion #endregion
#endregion #endregion
@ -1742,7 +1748,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
this.ApplyInterningProvider(loader.InterningProvider); this.ApplyInterningProvider(loader.InterningProvider);
} }
this.Freeze(); this.Freeze();
loader.RegisterCecilObject(this, typeDefinition);
} }
public override string Namespace { public override string Namespace {
@ -1772,7 +1777,8 @@ namespace ICSharpCode.NRefactory.TypeSystem
var result = LazyInit.VolatileRead(ref this.baseTypes); var result = LazyInit.VolatileRead(ref this.baseTypes);
if (result != null) { if (result != null) {
return result; return result;
} else { }
lock (loader.currentModule) {
result = new List<ITypeReference>(); result = new List<ITypeReference>();
loader.InitBaseTypes(cecilTypeDef, result); loader.InitBaseTypes(cecilTypeDef, result);
return LazyInit.GetOrSet(ref this.baseTypes, FreezableHelper.FreezeList(result)); return LazyInit.GetOrSet(ref this.baseTypes, FreezableHelper.FreezeList(result));
@ -1785,7 +1791,10 @@ namespace ICSharpCode.NRefactory.TypeSystem
var result = LazyInit.VolatileRead(ref this.nestedTypes); var result = LazyInit.VolatileRead(ref this.nestedTypes);
if (result != null) { if (result != null) {
return result; return result;
} else { }
lock (loader.currentModule) {
if (this.nestedTypes != null)
return this.nestedTypes;
result = new List<IUnresolvedTypeDefinition>(); result = new List<IUnresolvedTypeDefinition>();
loader.InitNestedTypes(cecilTypeDef, this, result); loader.InitNestedTypes(cecilTypeDef, this, result);
return LazyInit.GetOrSet(ref this.nestedTypes, FreezableHelper.FreezeList(result)); return LazyInit.GetOrSet(ref this.nestedTypes, FreezableHelper.FreezeList(result));
@ -1798,7 +1807,10 @@ namespace ICSharpCode.NRefactory.TypeSystem
var result = LazyInit.VolatileRead(ref this.members); var result = LazyInit.VolatileRead(ref this.members);
if (result != null) { if (result != null) {
return result; return result;
} else { }
lock (loader.currentModule) {
if (this.members != null)
return this.members;
result = new List<IUnresolvedMember>(); result = new List<IUnresolvedMember>();
loader.InitMembers(cecilTypeDef, this, result); loader.InitMembers(cecilTypeDef, this, result);
return LazyInit.GetOrSet(ref this.members, FreezableHelper.FreezeList(result)); return LazyInit.GetOrSet(ref this.members, FreezableHelper.FreezeList(result));
@ -2160,7 +2172,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
} }
#endregion #endregion
void FinishReadMember(AbstractUnresolvedMember member, object cecilDefinition) void FinishReadMember(AbstractUnresolvedMember member, MemberReference cecilDefinition)
{ {
if (this.InterningProvider != null) if (this.InterningProvider != null)
member.ApplyInterningProvider(this.InterningProvider); member.ApplyInterningProvider(this.InterningProvider);
@ -2171,7 +2183,15 @@ namespace ICSharpCode.NRefactory.TypeSystem
#region Type system translation table #region Type system translation table
readonly Dictionary<object, object> typeSystemTranslationTable; readonly Dictionary<object, object> typeSystemTranslationTable;
void RegisterCecilObject(object typeSystemObject, object cecilObject) void RegisterCecilObject(IUnresolvedEntity typeSystemObject, MemberReference cecilObject)
{
if (OnEntityLoaded != null)
OnEntityLoaded(typeSystemObject, cecilObject);
AddToTypeSystemTranslationTable(typeSystemObject, cecilObject);
}
void AddToTypeSystemTranslationTable(object typeSystemObject, object cecilObject)
{ {
if (typeSystemTranslationTable != null) { if (typeSystemTranslationTable != null) {
// When lazy-loading, the dictionary might be shared between multiple cecil-loaders that are used concurrently // When lazy-loading, the dictionary might be shared between multiple cecil-loaders that are used concurrently

46
ICSharpCode.NRefactory/TypeSystem/IAttribute.cs

@ -18,7 +18,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.Contracts;
using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.Semantics;
@ -27,9 +26,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <summary> /// <summary>
/// Represents an unresolved attribute. /// Represents an unresolved attribute.
/// </summary> /// </summary>
#if WITH_CONTRACTS
[ContractClass(typeof(IUnresolvedAttributeContract))]
#endif
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public interface IUnresolvedAttribute public interface IUnresolvedAttribute
{ {
@ -38,8 +34,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary> /// </summary>
DomRegion Region { get; } DomRegion Region { get; }
//ITypeReference AttributeType { get; }
/// <summary> /// <summary>
/// Resolves the attribute. /// Resolves the attribute.
/// </summary> /// </summary>
@ -49,9 +43,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <summary> /// <summary>
/// Represents an attribute. /// Represents an attribute.
/// </summary> /// </summary>
#if WITH_CONTRACTS
[ContractClass(typeof(IAttributeContract))]
#endif
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public interface IAttribute public interface IAttribute
{ {
@ -81,41 +72,4 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary> /// </summary>
IList<KeyValuePair<IMember, ResolveResult>> NamedArguments { get; } IList<KeyValuePair<IMember, ResolveResult>> NamedArguments { get; }
} }
#if WITH_CONTRACTS
[ContractClassFor(typeof(IAttribute))]
abstract class IAttributeContract : IFreezableContract, IAttribute
{
DomRegion IAttribute.Region {
get { return DomRegion.Empty; }
}
ITypeReference IAttribute.AttributeType {
get {
Contract.Ensures(Contract.Result<ITypeReference>() != null);
return null;
}
}
IList<IConstantValue> IAttribute.GetPositionalArguments(ITypeResolveContext context)
{
Contract.Requires(context != null);
Contract.Ensures(Contract.Result<IList<IConstantValue>>() != null);
return null;
}
IList<KeyValuePair<string, IConstantValue>> IAttribute.GetNamedArguments(ITypeResolveContext context)
{
Contract.Requires(context != null);
Contract.Ensures(Contract.Result<IList<KeyValuePair<string, IConstantValue>>>() != null);
return null;
}
IMethod IAttribute.ResolveConstructor(ITypeResolveContext context)
{
Contract.Requires(context != null);
return null;
}
}
#endif
} }

20
ICSharpCode.NRefactory/TypeSystem/IFreezable.cs

@ -17,13 +17,9 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Diagnostics.Contracts;
namespace ICSharpCode.NRefactory.TypeSystem namespace ICSharpCode.NRefactory.TypeSystem
{ {
#if WITH_CONTRACTS
[ContractClass(typeof(IFreezableContract))]
#endif
public interface IFreezable public interface IFreezable
{ {
/// <summary> /// <summary>
@ -36,20 +32,4 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary> /// </summary>
void Freeze(); void Freeze();
} }
#if WITH_CONTRACTS
[ContractClassFor(typeof(IFreezable))]
abstract class IFreezableContract : IFreezable
{
bool IFreezable.IsFrozen {
get { return default(bool); }
}
void IFreezable.Freeze()
{
IFreezable self = this;
Contract.Ensures(self.IsFrozen);
}
}
#endif
} }

22
ICSharpCode.NRefactory/TypeSystem/IInterningProvider.cs

@ -18,7 +18,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace ICSharpCode.NRefactory.TypeSystem namespace ICSharpCode.NRefactory.TypeSystem
{ {
@ -40,9 +39,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// and which are used only within a single type definition. Then a persistent file format could be organized so /// and which are used only within a single type definition. Then a persistent file format could be organized so
/// that shared objects are loaded only once, yet non-shared objects get loaded lazily together with the class. /// that shared objects are loaded only once, yet non-shared objects get loaded lazily together with the class.
/// </remarks> /// </remarks>
#if WITH_CONTRACTS
[ContractClass(typeof(IInterningProviderContract))]
#endif
public interface IInterningProvider public interface IInterningProvider
{ {
/// <summary> /// <summary>
@ -55,22 +51,4 @@ namespace ICSharpCode.NRefactory.TypeSystem
IList<T> InternList<T>(IList<T> list) where T : class; IList<T> InternList<T>(IList<T> list) where T : class;
} }
#if WITH_CONTRACTS
[ContractClassFor(typeof(IInterningProvider))]
abstract class IInterningProviderContract : IInterningProvider
{
T IInterningProvider.Intern<T>(T obj)
{
Contract.Ensures((Contract.Result<T>() == null) == (obj == null));
return obj;
}
IList<T> IInterningProvider.InternList<T>(IList<T> list)
{
Contract.Ensures((Contract.Result<IList<T>>() == null) == (list == null));
return list;
}
}
#endif
} }

26
ICSharpCode.NRefactory/TypeSystem/ISupportsInterning.cs

@ -17,8 +17,6 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace ICSharpCode.NRefactory.TypeSystem namespace ICSharpCode.NRefactory.TypeSystem
{ {
@ -26,9 +24,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// Interface for TypeSystem objects that support interning. /// Interface for TypeSystem objects that support interning.
/// See <see cref="IInterningProvider"/> for more information. /// See <see cref="IInterningProvider"/> for more information.
/// </summary> /// </summary>
#if WITH_CONTRACTS
[ContractClass(typeof(ISupportsInterningContract))]
#endif
public interface ISupportsInterning public interface ISupportsInterning
{ {
/// <summary> /// <summary>
@ -46,25 +41,4 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary> /// </summary>
bool EqualsForInterning(ISupportsInterning other); bool EqualsForInterning(ISupportsInterning other);
} }
#if WITH_CONTRACTS
[ContractClassFor(typeof(ISupportsInterning))]
abstract class ISupportsInterningContract : ISupportsInterning
{
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
{
Contract.Requires(provider != null);
}
int ISupportsInterning.GetHashCodeForInterning()
{
return 0;
}
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
return false;
}
}
#endif
} }

1
ICSharpCode.NRefactory/TypeSystem/IType.cs

@ -18,7 +18,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace ICSharpCode.NRefactory.TypeSystem namespace ICSharpCode.NRefactory.TypeSystem
{ {

20
ICSharpCode.NRefactory/TypeSystem/ITypeDefinition.cs

@ -130,5 +130,25 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary> /// </summary>
/// <remarks>This property is used to speed up the search for extension methods.</remarks> /// <remarks>This property is used to speed up the search for extension methods.</remarks>
bool HasExtensionMethods { get; } bool HasExtensionMethods { get; }
/// <summary>
/// Determines how this type is implementing the specified interface member.
/// </summary>
/// <returns>
/// The method on this type that implements the interface member;
/// or null if the type does not implement the interface.
/// </returns>
IMember GetInterfaceImplementation(IMember interfaceMember);
/// <summary>
/// Determines how this type is implementing the specified interface members.
/// </summary>
/// <returns>
/// For each interface member, this method returns the class member
/// that implements the interface member.
/// For interface members that are missing an implementation, the
/// result collection will contain a null element.
/// </returns>
IList<IMember> GetInterfaceImplementation(IList<IMember> interfaceMembers);
} }
} }

18
ICSharpCode.NRefactory/TypeSystem/ITypeReference.cs

@ -17,8 +17,6 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace ICSharpCode.NRefactory.TypeSystem namespace ICSharpCode.NRefactory.TypeSystem
{ {
@ -26,9 +24,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// Represents a reference to a type. /// Represents a reference to a type.
/// Must be resolved before it can be used as type. /// Must be resolved before it can be used as type.
/// </summary> /// </summary>
#if WITH_CONTRACTS
[ContractClass(typeof(ITypeReferenceContract))]
#endif
public interface ITypeReference public interface ITypeReference
{ {
// Keep this interface simple: I decided against having GetMethods/GetEvents etc. here, // Keep this interface simple: I decided against having GetMethods/GetEvents etc. here,
@ -81,17 +76,4 @@ namespace ICSharpCode.NRefactory.TypeSystem
ITypeResolveContext WithCurrentTypeDefinition(ITypeDefinition typeDefinition); ITypeResolveContext WithCurrentTypeDefinition(ITypeDefinition typeDefinition);
ITypeResolveContext WithCurrentMember(IMember member); ITypeResolveContext WithCurrentMember(IMember member);
} }
#if WITH_CONTRACTS
[ContractClassFor(typeof(ITypeReference))]
abstract class ITypeReferenceContract : ITypeReference
{
IType ITypeReference.Resolve(ITypeResolveContext context)
{
Contract.Requires(context != null);
Contract.Ensures(Contract.Result<IType>() != null);
return null;
}
}
#endif
} }

36
ICSharpCode.NRefactory/TypeSystem/IVariable.cs

@ -17,16 +17,12 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Diagnostics.Contracts;
namespace ICSharpCode.NRefactory.TypeSystem namespace ICSharpCode.NRefactory.TypeSystem
{ {
/// <summary> /// <summary>
/// Represents a variable (name/type pair). /// Represents a variable (name/type pair).
/// </summary> /// </summary>
#if WITH_CONTRACTS
[ContractClass(typeof(IVariableContract))]
#endif
public interface IVariable public interface IVariable
{ {
/// <summary> /// <summary>
@ -55,36 +51,4 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary> /// </summary>
object ConstantValue { get; } object ConstantValue { get; }
} }
#if WITH_CONTRACTS
[ContractClassFor(typeof(IVariable))]
abstract class IVariableContract : IVariable
{
string IVariable.Name {
get {
Contract.Ensures(Contract.Result<string>() != null);
return null;
}
}
ITypeReference IVariable.Type {
get {
Contract.Ensures(Contract.Result<ITypeReference>() != null);
return null;
}
}
bool IVariable.IsConst {
get {
IVariable @this = this;
Contract.Ensures(Contract.Result<bool>() == (@this.ConstantValue != null));
return false;
}
}
object IVariable.ConstantValue {
get { return null; }
}
}
#endif
} }

97
ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAttribute.cs

@ -0,0 +1,97 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// 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 System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.Semantics;
namespace ICSharpCode.NRefactory.TypeSystem.Implementation
{
/// <summary>
/// IAttribute implementation for already-resolved attributes.
/// </summary>
public class DefaultAttribute : IAttribute
{
readonly IType attributeType;
readonly IList<ResolveResult> positionalArguments;
readonly IList<KeyValuePair<IMember, ResolveResult>> namedArguments;
readonly DomRegion region;
volatile IMethod constructor;
public DefaultAttribute(IType attributeType, IList<ResolveResult> positionalArguments = null,
IList<KeyValuePair<IMember, ResolveResult>> namedArguments = null,
DomRegion region = default(DomRegion))
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
this.attributeType = attributeType;
this.positionalArguments = positionalArguments ?? EmptyList<ResolveResult>.Instance;
this.namedArguments = namedArguments ?? EmptyList<KeyValuePair<IMember, ResolveResult>>.Instance;
this.region = region;
}
public DefaultAttribute(IMethod constructor, IList<ResolveResult> positionalArguments = null,
IList<KeyValuePair<IMember, ResolveResult>> namedArguments = null,
DomRegion region = default(DomRegion))
{
if (constructor == null)
throw new ArgumentNullException("constructor");
this.constructor = constructor;
this.attributeType = constructor.DeclaringType;
this.positionalArguments = positionalArguments ?? EmptyList<ResolveResult>.Instance;
this.namedArguments = namedArguments ?? EmptyList<KeyValuePair<IMember, ResolveResult>>.Instance;
this.region = region;
if (this.positionalArguments.Count != constructor.Parameters.Count) {
throw new ArgumentException("Positional argument count must match the constructor's parameter count");
}
}
public IType AttributeType {
get { return attributeType; }
}
public DomRegion Region {
get { return region; }
}
public IMethod Constructor {
get {
IMethod ctor = this.constructor;
if (ctor == null) {
foreach (IMethod candidate in this.AttributeType.GetConstructors(m => m.Parameters.Count == positionalArguments.Count)) {
if (candidate.Parameters.Select(p => p.Type).SequenceEqual(this.PositionalArguments.Select(a => a.Type))) {
ctor = candidate;
break;
}
}
this.constructor = ctor;
}
return ctor;
}
}
public IList<ResolveResult> PositionalArguments {
get { return positionalArguments; }
}
public IList<KeyValuePair<IMember, ResolveResult>> NamedArguments {
get { return namedArguments; }
}
}
}

41
ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultResolvedTypeDefinition.cs

@ -18,7 +18,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq; using System.Linq;
using ICSharpCode.NRefactory.Documentation; using ICSharpCode.NRefactory.Documentation;
using ICSharpCode.NRefactory.Utils; using ICSharpCode.NRefactory.Utils;
@ -861,6 +860,46 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
} }
#endregion #endregion
#region GetInterfaceImplementation
public IMember GetInterfaceImplementation(IMember interfaceMember)
{
return GetInterfaceImplementation(new[] { interfaceMember })[0];
}
public IList<IMember> GetInterfaceImplementation(IList<IMember> interfaceMembers)
{
// TODO: review the subtle rules for interface reimplementation,
// write tests and fix this method.
// Also virtual/override is going to be tricky -
// I think we'll need to consider the 'virtual' method first for
// reimplemenatation purposes, but then actually return the 'override'
// (as that's the method that ends up getting called)
interfaceMembers = interfaceMembers.ToList(); // avoid evaluating more than once
var result = new IMember[interfaceMembers.Count];
var signatureToIndexDict = new MultiDictionary<IMember, int>(SignatureComparer.Ordinal);
for (int i = 0; i < interfaceMembers.Count; i++) {
signatureToIndexDict.Add(interfaceMembers[i], i);
}
foreach (var member in GetMembers(m => !m.IsExplicitInterfaceImplementation)) {
foreach (int interfaceMemberIndex in signatureToIndexDict[member]) {
result[interfaceMemberIndex] = member;
}
}
foreach (var explicitImpl in GetMembers(m => m.IsExplicitInterfaceImplementation)) {
foreach (var interfaceMember in explicitImpl.ImplementedInterfaceMembers) {
foreach (int potentialMatchingIndex in signatureToIndexDict[interfaceMember]) {
if (interfaceMember.Equals(interfaceMembers[potentialMatchingIndex])) {
result[potentialMatchingIndex] = explicitImpl;
}
}
}
}
return result;
}
#endregion
public bool Equals(IType other) public bool Equals(IType other)
{ {
return this == other; return this == other;

3
ICSharpCode.NRefactory/Utils/LazyInit.cs

@ -17,10 +17,7 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading; using System.Threading;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.Utils namespace ICSharpCode.NRefactory.Utils
{ {

134
ICSharpCode.NRefactory/Utils/MultiDictionary.cs

@ -0,0 +1,134 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// 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 System.Collections.Generic;
using System.Linq;
namespace ICSharpCode.NRefactory.Utils
{
/// <summary>
/// A dictionary that allows multiple pairs with the same key.
/// </summary>
public class MultiDictionary<TKey, TValue> : ILookup<TKey, TValue>
{
readonly Dictionary<TKey, List<TValue>> dict;
public MultiDictionary()
{
dict = new Dictionary<TKey, List<TValue>>();
}
public MultiDictionary(IEqualityComparer<TKey> comparer)
{
dict = new Dictionary<TKey, List<TValue>>(comparer);
}
public void Add(TKey key, TValue value)
{
List<TValue> valueList;
if (!dict.TryGetValue(key, out valueList)) {
valueList = new List<TValue>();
dict.Add(key, valueList);
}
valueList.Add(value);
}
public bool Remove(TKey key, TValue value)
{
List<TValue> valueList;
if (dict.TryGetValue(key, out valueList)) {
if (valueList.Remove(value)) {
if (valueList.Count == 0)
dict.Remove(key);
return true;
}
}
return false;
}
public void Clear()
{
dict.Clear();
}
#if NET45
public IReadOnlyList<TValue> this[TKey key] {
#else
public IList<TValue> this[TKey key] {
#endif
get {
List<TValue> list;
if (dict.TryGetValue(key, out list))
return list;
else
return EmptyList<TValue>.Instance;
}
}
public int Count {
get { return dict.Count; }
}
IEnumerable<TValue> ILookup<TKey, TValue>.this[TKey key] {
get { return this[key]; }
}
bool ILookup<TKey, TValue>.Contains(TKey key)
{
return dict.ContainsKey(key);
}
public IEnumerator<IGrouping<TKey, TValue>> GetEnumerator()
{
foreach (var pair in dict)
yield return new Grouping(pair.Key, pair.Value);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
sealed class Grouping : IGrouping<TKey, TValue>
{
readonly TKey key;
readonly List<TValue> values;
public Grouping(TKey key, List<TValue> values)
{
this.key = key;
this.values = values;
}
public TKey Key {
get { return key; }
}
public IEnumerator<TValue> GetEnumerator()
{
return values.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return values.GetEnumerator();
}
}
}
}

78
NRefactory.sln

@ -1,7 +1,7 @@
 
Microsoft Visual Studio Solution File, Format Version 11.00 Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010 # Visual Studio 2010
# SharpDevelop 4.2.0.8783 # SharpDevelop 4.3
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DC98210E-1646-483B-819A-2BB8272461E4}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DC98210E-1646-483B-819A-2BB8272461E4}"
ProjectSection(SolutionItems) = preProject ProjectSection(SolutionItems) = preProject
Packages\ICSharpCode.NRefactory.nuspec = Packages\ICSharpCode.NRefactory.nuspec Packages\ICSharpCode.NRefactory.nuspec = Packages\ICSharpCode.NRefactory.nuspec
@ -34,6 +34,10 @@ Global
Debug|x86 = Debug|x86 Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
Release|x86 = Release|x86 Release|x86 = Release|x86
net_4_5_Debug|Any CPU = net_4_5_Debug|Any CPU
net_4_5_Debug|x86 = net_4_5_Debug|x86
net_4_5_Release|Any CPU = net_4_5_Release|Any CPU
net_4_5_Release|x86 = net_4_5_Release|x86
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
@ -108,6 +112,78 @@ Global
{9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.Release|Any CPU.ActiveCfg = Release|Any CPU {9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.Release|x86.Build.0 = Release|x86 {9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.Release|x86.Build.0 = Release|x86
{9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.Release|x86.ActiveCfg = Release|x86 {9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.Release|x86.ActiveCfg = Release|x86
{9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU
{9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{961DADFA-7CE6-429F-BC22-47630D6DB826}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU
{961DADFA-7CE6-429F-BC22-47630D6DB826}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{D81206EF-3DCA-4A30-897B-E262A2AD9EE3}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU
{D81206EF-3DCA-4A30-897B-E262A2AD9EE3}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{A7EEF7F8-238F-459D-95A9-96467539641D}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU
{A7EEF7F8-238F-459D-95A9-96467539641D}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_5_Debug|Any CPU.Build.0 = winphone_Release|Any CPU
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_0_Debug|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.net_4_5_Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.net_4_5_Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.net_4_5_Debug|x86.Build.0 = net_4_5_Debug|x86
{9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.net_4_5_Debug|x86.ActiveCfg = net_4_5_Debug|x86
{961DADFA-7CE6-429F-BC22-47630D6DB826}.net_4_5_Debug|x86.Build.0 = net_4_5_Debug|Any CPU
{961DADFA-7CE6-429F-BC22-47630D6DB826}.net_4_5_Debug|x86.ActiveCfg = net_4_5_Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.net_4_5_Debug|x86.Build.0 = net_4_5_Debug|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.net_4_5_Debug|x86.ActiveCfg = net_4_5_Debug|Any CPU
{D81206EF-3DCA-4A30-897B-E262A2AD9EE3}.net_4_5_Debug|x86.Build.0 = net_4_5_Debug|x86
{D81206EF-3DCA-4A30-897B-E262A2AD9EE3}.net_4_5_Debug|x86.ActiveCfg = net_4_5_Debug|x86
{A7EEF7F8-238F-459D-95A9-96467539641D}.net_4_5_Debug|x86.Build.0 = net_4_5_Debug|Any CPU
{A7EEF7F8-238F-459D-95A9-96467539641D}.net_4_5_Debug|x86.ActiveCfg = net_4_5_Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.net_4_5_Debug|x86.Build.0 = net_4_5_Debug|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.net_4_5_Debug|x86.ActiveCfg = net_4_5_Debug|Any CPU
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_5_Debug|x86.Build.0 = winphone_Release|Any CPU
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_5_Debug|x86.ActiveCfg = net_4_0_Debug|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.net_4_5_Debug|x86.Build.0 = net_4_5_Debug|x86
{63D3B27A-D966-4902-90B3-30290E1692F1}.net_4_5_Debug|x86.ActiveCfg = net_4_5_Debug|x86
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.net_4_5_Debug|x86.Build.0 = net_4_5_Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.net_4_5_Debug|x86.ActiveCfg = net_4_5_Debug|Any CPU
{9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU
{9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{961DADFA-7CE6-429F-BC22-47630D6DB826}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU
{961DADFA-7CE6-429F-BC22-47630D6DB826}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{D81206EF-3DCA-4A30-897B-E262A2AD9EE3}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU
{D81206EF-3DCA-4A30-897B-E262A2AD9EE3}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{A7EEF7F8-238F-459D-95A9-96467539641D}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU
{A7EEF7F8-238F-459D-95A9-96467539641D}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_5_Release|Any CPU.Build.0 = winphone_Release|Any CPU
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_5_Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.net_4_5_Release|Any CPU.Build.0 = net_4_5_Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.net_4_5_Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
{9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.net_4_5_Release|x86.Build.0 = net_4_5_Release|x86
{9C19E629-C93E-4ACB-9A4B-13072B5AEF9D}.net_4_5_Release|x86.ActiveCfg = net_4_5_Release|x86
{961DADFA-7CE6-429F-BC22-47630D6DB826}.net_4_5_Release|x86.Build.0 = net_4_5_Release|Any CPU
{961DADFA-7CE6-429F-BC22-47630D6DB826}.net_4_5_Release|x86.ActiveCfg = net_4_5_Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.net_4_5_Release|x86.Build.0 = net_4_5_Release|Any CPU
{DC393B66-92ED-4CAD-AB25-CFEF23F3D7C6}.net_4_5_Release|x86.ActiveCfg = net_4_5_Release|Any CPU
{D81206EF-3DCA-4A30-897B-E262A2AD9EE3}.net_4_5_Release|x86.Build.0 = net_4_5_Release|x86
{D81206EF-3DCA-4A30-897B-E262A2AD9EE3}.net_4_5_Release|x86.ActiveCfg = net_4_5_Release|x86
{A7EEF7F8-238F-459D-95A9-96467539641D}.net_4_5_Release|x86.Build.0 = net_4_5_Release|Any CPU
{A7EEF7F8-238F-459D-95A9-96467539641D}.net_4_5_Release|x86.ActiveCfg = net_4_5_Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.net_4_5_Release|x86.Build.0 = net_4_5_Release|Any CPU
{53DCA265-3C3C-42F9-B647-F72BA678122B}.net_4_5_Release|x86.ActiveCfg = net_4_5_Release|Any CPU
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_5_Release|x86.Build.0 = winphone_Release|Any CPU
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.net_4_5_Release|x86.ActiveCfg = net_4_0_Release|Any CPU
{63D3B27A-D966-4902-90B3-30290E1692F1}.net_4_5_Release|x86.Build.0 = net_4_5_Release|x86
{63D3B27A-D966-4902-90B3-30290E1692F1}.net_4_5_Release|x86.ActiveCfg = net_4_5_Release|x86
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.net_4_5_Release|x86.Build.0 = net_4_5_Release|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.net_4_5_Release|x86.ActiveCfg = net_4_5_Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

Loading…
Cancel
Save