Browse Source

Merge NRefactory 'b1804fd9df13d063830207a14cb4a1f0902c06a3' into SharpDevelop (newNR branch)

newNRvisualizers
Daniel Grunwald 14 years ago
parent
commit
0ad0b46621
  1. 53
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/OutputVisitorTests.cs
  2. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AnonymousTypeCreateExpressionTests.cs
  3. 13
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ArrayCreateExpressionTests.cs
  4. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AssignmentExpressionTests.cs
  5. 94
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ObjectCreateExpressionTests.cs
  6. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/PrimitiveExpressionTests.cs
  7. 54
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/AttributeSectionTests.cs
  8. 119
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/ParseSelfTests.cs
  9. 26
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeSystemConvertVisitorTests.cs
  10. 23
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Resolver/LambdaTests.cs
  11. 55
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ObjectCreationTests.cs
  12. 7
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj
  13. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/TypeSystem/CecilLoaderTests.cs
  14. 42
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/TypeSystem/SerializedCecilLoaderTests.cs
  15. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemTests.cs
  16. 28
      src/Libraries/NRefactory/ICSharpCode.NRefactory.VB/Visitors/CSharpToVBConverterVisitor.cs
  17. 5
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Ast/DepthFirstAstVisitor.cs
  18. 14
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Ast/Expressions/ArrayInitializerExpression.cs
  19. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Ast/Expressions/AssignmentExpression.cs
  20. 86
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Ast/Expressions/NamedExpression.cs
  21. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Ast/IAstVisitor.cs
  22. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Ast/ObservableAstVisitor.cs
  23. 18
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/OutputVisitor/OutputVisitor.cs
  24. 100
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Parser/CSharpParser.cs
  25. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Parser/ParsedFile.cs
  26. 1292
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Parser/mcs/cs-parser.cs
  27. 12
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Parser/mcs/cs-parser.jay
  28. 14
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Parser/mcs/expression.cs
  29. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/AliasNamespaceReference.cs
  30. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/CSharpAttribute.cs
  31. 59
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/CSharpResolver.cs
  32. 13
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/ConstantValues.cs
  33. 12
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/Log.cs
  34. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/MemberTypeOrNamespaceReference.cs
  35. 159
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/ResolveVisitor.cs
  36. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/SimpleTypeOrNamespaceReference.cs
  37. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/UsingScope.cs
  38. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory/Documentation/XmlDocumentationProvider.cs
  39. 14
      src/Libraries/NRefactory/ICSharpCode.NRefactory/ICSharpCode.NRefactory.csproj
  40. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory/Properties/AssemblyInfo.cs
  41. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/ArrayType.cs
  42. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/ByReferenceType.cs
  43. 34
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/CecilLoader.cs
  44. 31
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Error.cs
  45. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractFreezable.cs
  46. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractMember.cs
  47. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractType.cs
  48. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAccessor.cs
  49. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAttribute.cs
  50. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultEvent.cs
  51. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultField.cs
  52. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultMethod.cs
  53. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultParameter.cs
  54. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultProperty.cs
  55. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultTypeDefinition.cs
  56. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultTypeParameter.cs
  57. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/GetClassTypeReference.cs
  58. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/NestedTypeReference.cs
  59. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/ProxyTypeResolveContext.cs
  60. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleConstantValue.cs
  61. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleInterningProvider.cs
  62. 55
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleProjectContent.cs
  63. 36
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/TypeStorage.cs
  64. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/TypeWithElementType.cs
  65. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/VoidTypeDefinition.cs
  66. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/IntersectionType.cs
  67. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/ParameterizedType.cs
  68. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/PointerType.cs
  69. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/SharedTypes.cs
  70. 117
      src/Libraries/NRefactory/ICSharpCode.NRefactory/Utils/7BitEncodedInts.cs
  71. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/Utils/BitVector16.cs
  72. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory/Utils/EmptyList.cs
  73. 1316
      src/Libraries/NRefactory/ICSharpCode.NRefactory/Utils/FastSerializer.cs

53
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/OutputVisitorTests.cs

@ -0,0 +1,53 @@
// 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.IO;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp
{
[TestFixture]
public class OutputVisitorTests
{
void AssertOutput(string expected, Expression expr, CSharpFormattingOptions policy = null)
{
if (policy == null)
policy = new CSharpFormattingOptions();;
StringWriter w = new StringWriter();
w.NewLine = "\n";
expr.AcceptVisitor(new OutputVisitor(new TextWriterOutputFormatter(w) { IndentationString = "\t" }, policy), null);
Assert.AreEqual(expected.Replace("\r", ""), w.ToString());
}
[Test, Ignore("Incorrect whitespace")]
public void AssignmentInCollectionInitialize()
{
Expression expr = new ObjectCreateExpression {
Type = new SimpleType("List"),
Initializer = new ArrayInitializerExpression(
new ArrayInitializerExpression(
new AssignmentExpression(new IdentifierExpression("a"), new PrimitiveExpression(1))
)
)
};
AssertOutput("new List {\n {\n a = 1\n }\n}", expr);
}
}
}

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AnonymousTypeCreateExpressionTests.cs

@ -31,7 +31,7 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
"new { Name = \"Test\", Price, Something.Property }", "new { Name = \"Test\", Price, Something.Property }",
new AnonymousTypeCreateExpression { new AnonymousTypeCreateExpression {
Initializers = { Initializers = {
new NamedArgumentExpression("Name", new PrimitiveExpression("Test")), new NamedExpression("Name", new PrimitiveExpression("Test")),
new IdentifierExpression("Price"), new IdentifierExpression("Price"),
new IdentifierExpression("Something").Member("Property") new IdentifierExpression("Something").Member("Property")
}}); }});

13
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ArrayCreateExpressionTests.cs

@ -121,5 +121,18 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
} }
}}); }});
} }
[Test]
public void AssignmentInArrayInitializer()
{
ParseUtilCSharp.AssertExpression(
"new [] { a = 10 }",
new ArrayCreateExpression {
Initializer = new ArrayInitializerExpression {
Elements = {
new AssignmentExpression(new IdentifierExpression("a"), new PrimitiveExpression(10))
}
}});
}
} }
} }

4
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AssignmentExpressionTests.cs

@ -105,7 +105,9 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
{ {
ParseUtilCSharp.AssertExpression( ParseUtilCSharp.AssertExpression(
"a = b = c", "a = b = c",
new AssignmentExpression("a", new AssignmentExpression("b", new IdentifierExpression("c")))); new AssignmentExpression(
new IdentifierExpression("a"),
new AssignmentExpression(new IdentifierExpression("b"), new IdentifierExpression("c"))));
} }
} }
} }

94
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/ObjectCreateExpressionTests.cs

@ -58,8 +58,8 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
Type = new SimpleType("Point"), Type = new SimpleType("Point"),
Initializer = new ArrayInitializerExpression { Initializer = new ArrayInitializerExpression {
Elements = { Elements = {
new AssignmentExpression("X", new PrimitiveExpression(0)), new NamedExpression("X", new PrimitiveExpression(0)),
new AssignmentExpression("Y", new PrimitiveExpression(1)) new NamedExpression("Y", new PrimitiveExpression(1))
} }
}}); }});
} }
@ -73,8 +73,8 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
Type = new SimpleType("Point"), Type = new SimpleType("Point"),
Initializer = new ArrayInitializerExpression { Initializer = new ArrayInitializerExpression {
Elements = { Elements = {
new AssignmentExpression("X", new PrimitiveExpression(0)), new NamedExpression("X", new PrimitiveExpression(0)),
new AssignmentExpression("Y", new PrimitiveExpression(1)) new NamedExpression("Y", new PrimitiveExpression(1))
} }
}}); }});
} }
@ -88,8 +88,8 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
Type = new SimpleType("Point"), Type = new SimpleType("Point"),
Initializer = new ArrayInitializerExpression { Initializer = new ArrayInitializerExpression {
Elements = { Elements = {
new AssignmentExpression("X", new PrimitiveExpression(0)), new NamedExpression("X", new PrimitiveExpression(0)),
new AssignmentExpression("Y", new PrimitiveExpression(1)) new NamedExpression("Y", new PrimitiveExpression(1))
} }
}}); }});
} }
@ -103,24 +103,24 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
Type = new SimpleType("Rectangle"), Type = new SimpleType("Rectangle"),
Initializer = new ArrayInitializerExpression { Initializer = new ArrayInitializerExpression {
Elements = { Elements = {
new AssignmentExpression( new NamedExpression(
"P1", "P1",
new ObjectCreateExpression { new ObjectCreateExpression {
Type = new SimpleType("Point"), Type = new SimpleType("Point"),
Initializer = new ArrayInitializerExpression { Initializer = new ArrayInitializerExpression {
Elements = { Elements = {
new AssignmentExpression("X", new PrimitiveExpression(0)), new NamedExpression("X", new PrimitiveExpression(0)),
new AssignmentExpression("Y", new PrimitiveExpression(1)) new NamedExpression("Y", new PrimitiveExpression(1))
} }
}}), }}),
new AssignmentExpression( new NamedExpression(
"P2", "P2",
new ObjectCreateExpression { new ObjectCreateExpression {
Type = new SimpleType("Point"), Type = new SimpleType("Point"),
Initializer = new ArrayInitializerExpression { Initializer = new ArrayInitializerExpression {
Elements = { Elements = {
new AssignmentExpression("X", new PrimitiveExpression(2)), new NamedExpression("X", new PrimitiveExpression(2)),
new AssignmentExpression("Y", new PrimitiveExpression(3)) new NamedExpression("Y", new PrimitiveExpression(3))
} }
}}) }})
}}}); }}});
@ -135,20 +135,20 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
Type = new SimpleType("Rectangle"), Type = new SimpleType("Rectangle"),
Initializer = new ArrayInitializerExpression { Initializer = new ArrayInitializerExpression {
Elements = { Elements = {
new AssignmentExpression( new NamedExpression(
"P1", "P1",
new ArrayInitializerExpression { new ArrayInitializerExpression {
Elements = { Elements = {
new AssignmentExpression("X", new PrimitiveExpression(0)), new NamedExpression("X", new PrimitiveExpression(0)),
new AssignmentExpression("Y", new PrimitiveExpression(1)) new NamedExpression("Y", new PrimitiveExpression(1))
} }
}), }),
new AssignmentExpression( new NamedExpression(
"P2", "P2",
new ArrayInitializerExpression { new ArrayInitializerExpression {
Elements = { Elements = {
new AssignmentExpression("X", new PrimitiveExpression(2)), new NamedExpression("X", new PrimitiveExpression(2)),
new AssignmentExpression("Y", new PrimitiveExpression(3)) new NamedExpression("Y", new PrimitiveExpression(3))
} }
}) })
}}}); }}});
@ -163,9 +163,9 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
Type = new SimpleType("List", new PrimitiveType("int")), Type = new SimpleType("List", new PrimitiveType("int")),
Initializer = new ArrayInitializerExpression { Initializer = new ArrayInitializerExpression {
Elements = { Elements = {
new PrimitiveExpression(0), new ArrayInitializerExpression(new PrimitiveExpression(0)),
new PrimitiveExpression(1), new ArrayInitializerExpression(new PrimitiveExpression(1)),
new PrimitiveExpression(2) new ArrayInitializerExpression(new PrimitiveExpression(2))
}}}); }}});
} }
@ -204,34 +204,48 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
}", }",
new ObjectCreateExpression { new ObjectCreateExpression {
Type = new SimpleType("List", new SimpleType("Contact")), Type = new SimpleType("List", new SimpleType("Contact")),
Initializer = new ArrayInitializerExpression { Initializer = new ArrayInitializerExpression(
Elements = { new ArrayInitializerExpression(
new ObjectCreateExpression { new ObjectCreateExpression {
Type = new SimpleType("Contact"), Type = new SimpleType("Contact"),
Initializer = new ArrayInitializerExpression { Initializer = new ArrayInitializerExpression {
Elements = { Elements = {
new AssignmentExpression("Name", new PrimitiveExpression("Chris")), new NamedExpression("Name", new PrimitiveExpression("Chris")),
new AssignmentExpression( new NamedExpression("PhoneNumbers", new ArrayInitializerExpression () {
"PhoneNumbers", Elements = { new ArrayInitializerExpression(new PrimitiveExpression("206-555-0101")) }
new ArrayInitializerExpression { })
Elements = { new PrimitiveExpression("206-555-0101") } }}}),
}) new ArrayInitializerExpression(
}}},
new ObjectCreateExpression { new ObjectCreateExpression {
Type = new SimpleType("Contact"), Type = new SimpleType("Contact"),
Arguments = { new IdentifierExpression("additionalParameter") }, Arguments = { new IdentifierExpression("additionalParameter") },
Initializer = new ArrayInitializerExpression { Initializer = new ArrayInitializerExpression {
Elements = { Elements = {
new AssignmentExpression("Name", new PrimitiveExpression("Bob")), new NamedExpression("Name", new PrimitiveExpression("Bob")),
new AssignmentExpression( new NamedExpression("PhoneNumbers", new ArrayInitializerExpression () {
"PhoneNumbers", Elements = {
new ArrayInitializerExpression { new ArrayInitializerExpression(new PrimitiveExpression("650-555-0199")),
Elements = { new ArrayInitializerExpression(new PrimitiveExpression("425-882-8080"))
new PrimitiveExpression("650-555-0199"), }
new PrimitiveExpression("425-882-8080") })
} }}})
}) )});
}}} }
[Test]
public void AssignmentInCollectionInitializer()
{
ParseUtilCSharp.AssertExpression(
@"new List<int> { { a = 1 } }",
new ObjectCreateExpression {
Type = new SimpleType("List", new PrimitiveType("int")),
Initializer = new ArrayInitializerExpression {
Elements = {
new ArrayInitializerExpression {
Elements = {
new AssignmentExpression(new IdentifierExpression("a"), new PrimitiveExpression(1))
}
}
}}}); }}});
} }
} }

8
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/PrimitiveExpressionTests.cs

@ -214,5 +214,13 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
CheckLiteral(@"'\x0041'", '\x0041'); CheckLiteral(@"'\x0041'", '\x0041');
CheckLiteral(@"'\U00000041'", '\U00000041'); CheckLiteral(@"'\U00000041'", '\U00000041');
} }
[Test, Ignore(@"Parser includes \r in integer literal")]
public void TestPositionOfIntegerAtEndOfLine()
{
var pe = ParseUtilCSharp.ParseExpression<PrimitiveExpression>("0\r\n");
Assert.AreEqual(new AstLocation(1, 1), pe.StartLocation);
Assert.AreEqual(new AstLocation(1, 2), pe.EndLocation);
}
} }
} }

54
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/GeneralScope/AttributeSectionTests.cs

@ -30,7 +30,7 @@ namespace ICSharpCode.NRefactory.CSharp.Parser.GeneralScope
public class AttributeSectionTests public class AttributeSectionTests
{ {
[Test] [Test]
public void GlobalAttributeCSharp() public void AttributesUsingNamespaceAlias()
{ {
string program = @"[global::Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] string program = @"[global::Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
[someprefix::DesignerGenerated()] [someprefix::DesignerGenerated()]
@ -45,7 +45,7 @@ public class Form1 {
} }
[Test] [Test]
public void AssemblyAttributeCSharp() public void AssemblyAttribute()
{ {
string program = @"[assembly: System.Attribute()]"; string program = @"[assembly: System.Attribute()]";
AttributeSection decl = ParseUtilCSharp.ParseGlobal<AttributeSection>(program); AttributeSection decl = ParseUtilCSharp.ParseGlobal<AttributeSection>(program);
@ -53,30 +53,8 @@ public class Form1 {
Assert.AreEqual("assembly", decl.AttributeTarget); Assert.AreEqual("assembly", decl.AttributeTarget);
} }
[Test, Ignore("assembly/module attributes are broken")] [Test]
public void AssemblyAttributeCSharpWithNamedArguments() public void ModuleAttribute()
{
string program = @"[assembly: Foo(1, namedArg: 2, prop = 3)]";
AttributeSection decl = ParseUtilCSharp.ParseGlobal<AttributeSection>(program);
Assert.AreEqual("assembly", decl.AttributeTarget);
var a = decl.Attributes.Single();
Assert.AreEqual("Foo", a.Type);
Assert.AreEqual(3, a.Arguments.Count());
Assert.IsTrue(a.Arguments.ElementAt(0).IsMatch(new PrimitiveExpression(1)));
Assert.IsTrue(a.Arguments.ElementAt(1).IsMatch(new NamedArgumentExpression {
Identifier = "namedArg",
Expression = new PrimitiveExpression(2)
}));
Assert.IsTrue(a.Arguments.ElementAt(2).IsMatch(new AssignmentExpression {
Left = new IdentifierExpression("prop"),
Operator = AssignmentOperatorType.Assign,
Right = new PrimitiveExpression(3)
}));
}
[Test, Ignore("assembly/module attributes are broken")]
public void ModuleAttributeCSharp()
{ {
string program = @"[module: System.Attribute()]"; string program = @"[module: System.Attribute()]";
AttributeSection decl = ParseUtilCSharp.ParseGlobal<AttributeSection>(program); AttributeSection decl = ParseUtilCSharp.ParseGlobal<AttributeSection>(program);
@ -85,7 +63,7 @@ public class Form1 {
} }
[Test] [Test]
public void TypeAttributeCSharp() public void TypeAttribute()
{ {
string program = @"[type: System.Attribute()] class Test {}"; string program = @"[type: System.Attribute()] class Test {}";
TypeDeclaration type = ParseUtilCSharp.ParseGlobal<TypeDeclaration>(program); TypeDeclaration type = ParseUtilCSharp.ParseGlobal<TypeDeclaration>(program);
@ -94,6 +72,22 @@ public class Form1 {
Assert.AreEqual("type", decl.AttributeTarget); Assert.AreEqual("type", decl.AttributeTarget);
} }
[Test]
public void TwoAttributesInSameSection()
{
ParseUtilCSharp.AssertGlobal(
@"[A, B] class Test {}",
new TypeDeclaration {
Name = "Test",
Attributes = {
new AttributeSection {
Attributes = {
new Attribute { Type = new SimpleType("A") },
new Attribute { Type = new SimpleType("B") }
}
}}});
}
[Test, Ignore("Parser doesn't support attributes on type parameters")] [Test, Ignore("Parser doesn't support attributes on type parameters")]
public void AttributesOnTypeParameter() public void AttributesOnTypeParameter()
{ {
@ -154,7 +148,7 @@ public class Form1 {
// TODO: Tests for other contexts where attributes can appear // TODO: Tests for other contexts where attributes can appear
[Test, Ignore("Parser doesn't support named arguments in attributes")] [Test, Ignore("Parser does not support NamedArgumentExpression in attributes")]
public void AttributeWithNamedArguments() public void AttributeWithNamedArguments()
{ {
ParseUtilCSharp.AssertTypeMember( ParseUtilCSharp.AssertTypeMember(
@ -168,8 +162,8 @@ public class Form1 {
Type = new SimpleType("A"), Type = new SimpleType("A"),
Arguments = { Arguments = {
new PrimitiveExpression(0), new PrimitiveExpression(0),
new NamedArgumentExpression { Identifier = "a", Expression = new PrimitiveExpression(1) }, new NamedArgumentExpression("a", new PrimitiveExpression(1)),
new AssignmentExpression(new IdentifierExpression("b"), new PrimitiveExpression(2)) new NamedExpression("b", new PrimitiveExpression(2))
} }
} }
} }

119
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/ParseSelfTests.cs

@ -0,0 +1,119 @@
// 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.IO;
using ICSharpCode.Editor;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp.Parser
{
/// <summary>
/// Test fixture that parses NRefactory itself,
/// ensures that there are no parser crashes while doing so,
/// and that the returned positions are consistent.
/// </summary>
[TestFixture]
public class ParseSelfTests
{
string[] fileNames;
[TestFixtureSetUp]
public void SetUp()
{
string path = Path.GetFullPath(@"..\..\..");
if (!File.Exists(Path.Combine(path, "NRefactory.sln")))
throw new InvalidOperationException("Test cannot find the NRefactory source code in " + path);
fileNames = Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories);
}
[Test]
public void GenerateTypeSystem()
{
SimpleProjectContent pc = new SimpleProjectContent();
CSharpParser parser = new CSharpParser();
parser.GenerateTypeSystemMode = true;
foreach (string fileName in fileNames) {
CompilationUnit cu;
using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
cu = parser.Parse(fs);
}
TypeSystemConvertVisitor cv = new TypeSystemConvertVisitor(pc, fileName);
pc.UpdateProjectContent(null, cv.Convert(cu));
}
}
#region ParseAndCheckPositions
string currentFileName;
ReadOnlyDocument currentDocument;
[Test]
public void ParseAndCheckPositions()
{
CSharpParser parser = new CSharpParser();
foreach (string fileName in fileNames) {
this.currentDocument = new ReadOnlyDocument(File.ReadAllText(fileName));
CompilationUnit cu = parser.Parse(currentDocument.CreateReader());
this.currentFileName = fileName;
CheckPositionConsistency(cu);
CheckMissingTokens(cu);
}
}
void CheckPositionConsistency(AstNode node)
{
string comment = "(" + node.GetType().Name + " at " + node.StartLocation + " in " + currentFileName + ")";
Assert.IsTrue(node.StartLocation <= node.EndLocation, "StartLocation must be before EndLocation " + comment);
var prevNodeEnd = node.StartLocation;
for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) {
Assert.IsTrue(child.StartLocation >= prevNodeEnd, "Child must start after previous sibling " + comment);
CheckPositionConsistency(child);
prevNodeEnd = child.EndLocation;
}
Assert.IsTrue(prevNodeEnd <= node.EndLocation, "Last child must end before parent node ends " + comment);
}
void CheckMissingTokens(AstNode node)
{
if (node is IRelocatable) {
Assert.IsNull(node.FirstChild, "Token nodes should not have children");
} else {
var prevNodeEnd = node.StartLocation;
for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) {
CheckWhitespace(prevNodeEnd, child.StartLocation);
CheckMissingTokens(child);
prevNodeEnd = child.EndLocation;
}
CheckWhitespace(prevNodeEnd, node.EndLocation);
}
}
void CheckWhitespace(AstLocation whitespaceStart, AstLocation whitespaceEnd)
{
if (whitespaceStart == whitespaceEnd)
return;
int start = currentDocument.GetOffset(whitespaceStart.Line, whitespaceStart.Column);
int end = currentDocument.GetOffset(whitespaceEnd.Line, whitespaceEnd.Column);
string text = currentDocument.GetText(start, end - start);
Assert.IsTrue(string.IsNullOrWhiteSpace(text), "Expected whitespace between " + whitespaceStart + " and " + whitespaceEnd
+ ", but got '" + text + "' (in " + currentFileName + ")");
}
#endregion
}
}

26
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeSystemConvertVisitorTests.cs

@ -20,6 +20,7 @@ using System;
using System.IO; using System.IO;
using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation; using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
using NUnit.Framework; using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp.Parser namespace ICSharpCode.NRefactory.CSharp.Parser
@ -27,10 +28,13 @@ namespace ICSharpCode.NRefactory.CSharp.Parser
[TestFixture] [TestFixture]
public class TypeSystemConvertVisitorTests : TypeSystemTests public class TypeSystemConvertVisitorTests : TypeSystemTests
{ {
ITypeResolveContext ctx = CecilLoaderTests.Mscorlib;
[TestFixtureSetUp] [TestFixtureSetUp]
public void FixtureSetUp() public void FixtureSetUp()
{
testCasePC = ParseTestCase();
}
internal static IProjectContent ParseTestCase()
{ {
const string fileName = "TypeSystemTests.TestCase.cs"; const string fileName = "TypeSystemTests.TestCase.cs";
@ -40,10 +44,26 @@ namespace ICSharpCode.NRefactory.CSharp.Parser
cu = parser.Parse(s); cu = parser.Parse(s);
} }
testCasePC = new SimpleProjectContent(); var testCasePC = new SimpleProjectContent();
ParsedFile parsedFile = new TypeSystemConvertVisitor(testCasePC, fileName).Convert(cu); ParsedFile parsedFile = new TypeSystemConvertVisitor(testCasePC, fileName).Convert(cu);
parsedFile.Freeze(); parsedFile.Freeze();
testCasePC.UpdateProjectContent(null, parsedFile); testCasePC.UpdateProjectContent(null, parsedFile);
return testCasePC;
}
}
[TestFixture]
public class SerializedTypeSystemConvertVisitorTests : TypeSystemTests
{
[TestFixtureSetUp]
public void FixtureSetUp()
{
FastSerializer serializer = new FastSerializer();
using (MemoryStream ms = new MemoryStream()) {
serializer.Serialize(ms, TypeSystemConvertVisitorTests.ParseTestCase());
ms.Position = 0;
testCasePC = (IProjectContent)serializer.Deserialize(ms);
}
} }
} }
} }

23
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Resolver/LambdaTests.cs

@ -159,7 +159,7 @@ class TestClass {
#endregion #endregion
#region Lambda In Collection Initializer #region Lambda In Collection Initializer
[Test, Ignore("Parser doesn't support collection initializers yet")] [Test]
public void LambdaInCollectionInitializer1() public void LambdaInCollectionInitializer1()
{ {
string program = @"using System; using System.Collections.Generic; string program = @"using System; using System.Collections.Generic;
@ -174,7 +174,7 @@ class TestClass {
Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); Assert.AreEqual("System.Int32", lrr.Type.ReflectionName);
} }
[Test, Ignore("Parser doesn't support collection initializers yet")] [Test]
public void LambdaInCollectionInitializer2() public void LambdaInCollectionInitializer2()
{ {
string program = @"using System; using System.Collections.Generic; string program = @"using System; using System.Collections.Generic;
@ -189,8 +189,7 @@ class TestClass {
Assert.AreEqual("System.Char", lrr.Type.ReflectionName); Assert.AreEqual("System.Char", lrr.Type.ReflectionName);
} }
[Test]
[Test, Ignore("Parser doesn't support collection initializers yet")]
public void LambdaInCollectionInitializer3() public void LambdaInCollectionInitializer3()
{ {
string program = @"using System; using System.Collections.Generic; string program = @"using System; using System.Collections.Generic;
@ -206,7 +205,7 @@ class TestClass {
} }
#endregion #endregion
[Test, Ignore("Parser doesn't support object initializers yet")] [Test]
public void LambdaInObjectInitializerTest() public void LambdaInObjectInitializerTest()
{ {
string program = @"using System; string program = @"using System;
@ -238,6 +237,20 @@ static class TestClass {
Assert.AreEqual("System.Int32", lrr.Type.ReflectionName); Assert.AreEqual("System.Int32", lrr.Type.ReflectionName);
} }
[Test]
public void LambdaExpressionInDelegateCreateExpression()
{
string program = @"using System;
static class TestClass {
static void Main(string[] args) {
var f = new Func<int, string>( i => $i$ );
}
public delegate R Func<T, R>(T arg);
}";
var lrr = Resolve<LocalResolveResult>(program);
Assert.AreEqual("System.Int32", lrr.Type.ReflectionName);
}
[Test] [Test]
public void LambdaExpressionInReturnStatement() public void LambdaExpressionInReturnStatement()
{ {

55
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Resolver/ObjectCreationTests.cs

@ -141,5 +141,60 @@ class C : B {
mrr = Resolve<InvocationResolveResult>(program, "this(0)"); mrr = Resolve<InvocationResolveResult>(program, "this(0)");
Assert.AreEqual("C..ctor", mrr.Member.FullName); Assert.AreEqual("C..ctor", mrr.Member.FullName);
} }
[Test]
public void FieldReferenceInObjectInitializer()
{
string program = @"class A {
public int Property;
}
class B {
void Method() {
var x = new A() { $Property = 0$ };
}
}";
MemberResolveResult result = Resolve<MemberResolveResult>(program);
Assert.AreEqual("A.Property", result.Member.FullName);
}
[Test]
public void FieldReferenceInNestedObjectInitializer()
{
string program = @"class Point { public float X, Y; }
class Rect { public Point TopLeft, BottomRight; }
class B {
void Method() {
var x = new Rect() { TopLeft = { $X = 1$ } };
}
}";
MemberResolveResult result = Resolve<MemberResolveResult>(program);
Assert.AreEqual("Point.X", result.Member.FullName);
}
[Test, Ignore("Parser returns incorrect positions")]
public void CollectionInitializerTest()
{
string program = @"using System.Collections.Generic;
class B {
void Method() {
var x = new List<int>() { ${ 0 }$ };
}
}";
InvocationResolveResult result = Resolve<InvocationResolveResult>(program);
Assert.AreEqual("System.Collections.Generic.List.Add", result.Member.FullName);
}
[Test, Ignore("Parser returns incorrect positions")]
public void DictionaryInitializerTest()
{
string program = @"using System.Collections.Generic;
class B {
void Method() {
var x = new Dictionary<char, int>() { ${ 'a', 0 }$ };
}
}";
InvocationResolveResult result = Resolve<InvocationResolveResult>(program);
Assert.AreEqual("System.Collections.Generic.Dictionary.Add", result.Member.FullName);
}
} }
} }

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

@ -57,12 +57,14 @@
<Compile Include="CSharp\Analysis\DefiniteAssignmentTests.cs" /> <Compile Include="CSharp\Analysis\DefiniteAssignmentTests.cs" />
<Compile Include="CSharp\AstStructureTests.cs" /> <Compile Include="CSharp\AstStructureTests.cs" />
<Compile Include="CSharp\InsertParenthesesVisitorTests.cs" /> <Compile Include="CSharp\InsertParenthesesVisitorTests.cs" />
<Compile Include="CSharp\OutputVisitorTests.cs" />
<Compile Include="CSharp\Parser\Expression\AnonymousTypeCreateExpressionTests.cs" /> <Compile Include="CSharp\Parser\Expression\AnonymousTypeCreateExpressionTests.cs" />
<Compile Include="CSharp\Parser\Expression\ObjectCreateExpressionTests.cs" /> <Compile Include="CSharp\Parser\Expression\ObjectCreateExpressionTests.cs" />
<Compile Include="CSharp\Parser\GeneralScope\DelegateDeclarationTests.cs" /> <Compile Include="CSharp\Parser\GeneralScope\DelegateDeclarationTests.cs" />
<Compile Include="CSharp\Parser\GeneralScope\NamespaceDeclarationTests.cs" /> <Compile Include="CSharp\Parser\GeneralScope\NamespaceDeclarationTests.cs" />
<Compile Include="CSharp\Parser\GeneralScope\TypeDeclarationTests.cs" /> <Compile Include="CSharp\Parser\GeneralScope\TypeDeclarationTests.cs" />
<Compile Include="CSharp\Parser\GeneralScope\UsingDeclarationTests.cs" /> <Compile Include="CSharp\Parser\GeneralScope\UsingDeclarationTests.cs" />
<Compile Include="CSharp\Parser\ParseSelfTests.cs" />
<Compile Include="CSharp\Parser\Statements\BlockStatementTests.cs" /> <Compile Include="CSharp\Parser\Statements\BlockStatementTests.cs" />
<Compile Include="CSharp\Parser\Statements\CheckedStatementTests.cs" /> <Compile Include="CSharp\Parser\Statements\CheckedStatementTests.cs" />
<Compile Include="CSharp\Parser\Statements\EmptyStatementTests.cs" /> <Compile Include="CSharp\Parser\Statements\EmptyStatementTests.cs" />
@ -148,6 +150,7 @@
<Compile Include="TypeSystem\GetAllBaseTypesTest.cs" /> <Compile Include="TypeSystem\GetAllBaseTypesTest.cs" />
<Compile Include="TypeSystem\GetMembersTests.cs" /> <Compile Include="TypeSystem\GetMembersTests.cs" />
<Compile Include="TypeSystem\ReflectionHelperTests.cs" /> <Compile Include="TypeSystem\ReflectionHelperTests.cs" />
<Compile Include="TypeSystem\SerializedCecilLoaderTests.cs" />
<Compile Include="TypeSystem\StructureTests.cs" /> <Compile Include="TypeSystem\StructureTests.cs" />
<Compile Include="TypeSystem\TestInterningProvider.cs" /> <Compile Include="TypeSystem\TestInterningProvider.cs" />
<Compile Include="TypeSystem\TypeSystemTests.cs" /> <Compile Include="TypeSystem\TypeSystemTests.cs" />
@ -159,6 +162,10 @@
<Compile Include="FormattingTests\TestBlankLineFormatting.cs" /> <Compile Include="FormattingTests\TestBlankLineFormatting.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\ICSharpCode.Editor\ICSharpCode.Editor.csproj">
<Project>{F054A788-B591-4561-A8BA-AE745BBEB817}</Project>
<Name>ICSharpCode.Editor</Name>
</ProjectReference>
<ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj"> <ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj">
<Project>{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}</Project> <Project>{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}</Project>
<Name>ICSharpCode.NRefactory</Name> <Name>ICSharpCode.NRefactory</Name>

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/TypeSystem/CecilLoaderTests.cs

@ -78,7 +78,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
IProperty def = c.Properties.Single(p => p.Name == "Default"); IProperty def = c.Properties.Single(p => p.Name == "Default");
ParameterizedType pt = (ParameterizedType)def.ReturnType.Resolve(ctx); ParameterizedType pt = (ParameterizedType)def.ReturnType.Resolve(ctx);
Assert.AreEqual("System.Collections.Generic.Comparer", pt.FullName); Assert.AreEqual("System.Collections.Generic.Comparer", pt.FullName);
Assert.AreSame(c.TypeParameters[0], pt.TypeArguments[0]); Assert.AreEqual(c.TypeParameters[0], pt.TypeArguments[0]);
} }
[Test] [Test]

42
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/TypeSystem/SerializedCecilLoaderTests.cs

@ -0,0 +1,42 @@
// 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.IO;
using ICSharpCode.NRefactory.Utils;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.TypeSystem
{
[TestFixture]
public class SerializedCecilLoaderTests : TypeSystemTests
{
[TestFixtureSetUp]
public void FixtureSetUp()
{
CecilLoader loader = new CecilLoader() { IncludeInternalMembers = true };
IProjectContent pc = loader.LoadAssemblyFile(typeof(TestCase.SimplePublicClass).Assembly.Location);
FastSerializer serializer = new FastSerializer();
using (MemoryStream ms = new MemoryStream()) {
serializer.Serialize(ms, pc);
ms.Position = 0;
testCasePC = (IProjectContent)serializer.Deserialize(ms);
}
}
}
}

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemTests.cs

@ -84,7 +84,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
public void DynamicType() public void DynamicType()
{ {
ITypeDefinition testClass = testCasePC.GetTypeDefinition(typeof(DynamicTest)); ITypeDefinition testClass = testCasePC.GetTypeDefinition(typeof(DynamicTest));
Assert.AreSame(SharedTypes.Dynamic, testClass.Properties.Single().ReturnType.Resolve(ctx)); Assert.AreEqual(SharedTypes.Dynamic, testClass.Properties.Single().ReturnType.Resolve(ctx));
Assert.AreEqual(0, testClass.Properties.Single().Attributes.Count); Assert.AreEqual(0, testClass.Properties.Single().Attributes.Count);
} }

28
src/Libraries/NRefactory/ICSharpCode.NRefactory.VB/Visitors/CSharpToVBConverterVisitor.cs

@ -418,24 +418,24 @@ namespace ICSharpCode.NRefactory.VB.Visitors
public AstNode VisitNamedArgumentExpression(CSharp.NamedArgumentExpression namedArgumentExpression, object data) public AstNode VisitNamedArgumentExpression(CSharp.NamedArgumentExpression namedArgumentExpression, object data)
{ {
Expression expr; Expression expr = new NamedArgumentExpression {
Identifier = namedArgumentExpression.Identifier,
if (namedArgumentExpression.Parent is CSharp.ArrayInitializerExpression) { Expression = (Expression)namedArgumentExpression.Expression.AcceptVisitor(this, data)
expr = new FieldInitializerExpression { };
IsKey = true,
Identifier = namedArgumentExpression.Identifier,
Expression = (Expression)namedArgumentExpression.Expression.AcceptVisitor(this, data)
};
} else {
expr = new NamedArgumentExpression {
Identifier = namedArgumentExpression.Identifier,
Expression = (Expression)namedArgumentExpression.Expression.AcceptVisitor(this, data)
};
}
return EndNode(namedArgumentExpression, expr); return EndNode(namedArgumentExpression, expr);
} }
public AstNode VisitNamedExpression(CSharp.NamedExpression namedExpression, object data)
{
Expression expr = new FieldInitializerExpression {
IsKey = true,
Identifier = namedExpression.Identifier,
Expression = (Expression)namedExpression.Expression.AcceptVisitor(this, data)
};
return EndNode(namedExpression, expr);
}
public AstNode VisitNullReferenceExpression(CSharp.NullReferenceExpression nullReferenceExpression, object data) public AstNode VisitNullReferenceExpression(CSharp.NullReferenceExpression nullReferenceExpression, object data)
{ {
return EndNode(nullReferenceExpression, new PrimitiveExpression(null)); return EndNode(nullReferenceExpression, new PrimitiveExpression(null));

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

@ -585,6 +585,11 @@ namespace ICSharpCode.NRefactory.CSharp
return VisitChildren (namedArgumentExpression, data); return VisitChildren (namedArgumentExpression, data);
} }
public virtual S VisitNamedExpression (NamedExpression namedExpression, T data)
{
return VisitChildren (namedExpression, data);
}
public virtual S VisitEmptyExpression (EmptyExpression emptyExpression, T data) public virtual S VisitEmptyExpression (EmptyExpression emptyExpression, T data)
{ {
return VisitChildren (emptyExpression, data); return VisitChildren (emptyExpression, data);

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

@ -33,6 +33,20 @@ namespace ICSharpCode.NRefactory.CSharp
/// </summary> /// </summary>
public class ArrayInitializerExpression : Expression public class ArrayInitializerExpression : Expression
{ {
public ArrayInitializerExpression()
{
}
public ArrayInitializerExpression(IEnumerable<Expression> elements)
{
this.Elements.AddRange(elements);
}
public ArrayInitializerExpression(params Expression[] elements)
{
this.Elements.AddRange(elements);
}
#region Null #region Null
public new static readonly ArrayInitializerExpression Null = new NullArrayInitializerExpression (); public new static readonly ArrayInitializerExpression Null = new NullArrayInitializerExpression ();

6
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Ast/Expressions/AssignmentExpression.cs

@ -48,12 +48,6 @@ namespace ICSharpCode.NRefactory.CSharp
this.Right = right; this.Right = right;
} }
public AssignmentExpression(string left, Expression right)
{
this.Left = new IdentifierExpression(left);
this.Right = right;
}
public AssignmentExpression(Expression left, AssignmentOperatorType op, Expression right) public AssignmentExpression(Expression left, AssignmentOperatorType op, Expression right)
{ {
this.Left = left; this.Left = left;

86
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Ast/Expressions/NamedExpression.cs

@ -0,0 +1,86 @@
//
// NamedExpression.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2011 Xamarin
//
// 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.Collections.Generic;
using System.Linq;
namespace ICSharpCode.NRefactory.CSharp
{
/// <summary>
/// name = expression
/// This isn't the same as 'assign' even if it has the same syntax. This expression is used in object initializers.
/// </summary>
public class NamedExpression : Expression
{
public NamedExpression()
{
}
public NamedExpression (string identifier, Expression expression)
{
this.Identifier = identifier;
this.Expression = expression;
}
public string Identifier {
get {
return GetChildByRole (Roles.Identifier).Name;
}
set {
SetChildByRole(Roles.Identifier, CSharp.Identifier.Create (value, AstLocation.Empty));
}
}
public Identifier IdentifierToken {
get {
return GetChildByRole (Roles.Identifier);
}
set {
SetChildByRole(Roles.Identifier, value);
}
}
public CSharpTokenNode AssignToken {
get { return GetChildByRole (Roles.Assign); }
}
public Expression Expression {
get { return GetChildByRole (Roles.Expression); }
set { SetChildByRole (Roles.Expression, value); }
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitNamedExpression(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
var o = other as NamedExpression;
return o != null && MatchString(this.Identifier, o.Identifier) && this.Expression.DoMatch(o.Expression, match);
}
}
}

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

@ -45,6 +45,7 @@ namespace ICSharpCode.NRefactory.CSharp
S VisitLambdaExpression(LambdaExpression lambdaExpression, T data); S VisitLambdaExpression(LambdaExpression lambdaExpression, T data);
S VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression, T data); S VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression, T data);
S VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, T data); S VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, T data);
S VisitNamedExpression(NamedExpression namedExpression, T data);
S VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression, T data); S VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression, T data);
S VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, T data); S VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, T data);
S VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, T data); S VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, T data);

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

@ -1121,6 +1121,16 @@ namespace ICSharpCode.NRefactory.CSharp
return VisitChildren (namedArgumentExpression, data); return VisitChildren (namedArgumentExpression, data);
} }
public event Action<NamedExpression, T> NamedExpressionVisited;
S IAstVisitor<T, S>.VisitNamedExpression (NamedExpression namedExpression, T data)
{
var handler = NamedExpressionVisited;
if (handler != null)
handler (namedExpression, data);
return VisitChildren (namedExpression, data);
}
public event Action<EmptyExpression, T> EmptyExpressionVisited; public event Action<EmptyExpression, T> EmptyExpressionVisited;
S IAstVisitor<T, S>.VisitEmptyExpression (EmptyExpression emptyExpression, T data) S IAstVisitor<T, S>.VisitEmptyExpression (EmptyExpression emptyExpression, T data)

18
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/OutputVisitor/OutputVisitor.cs

@ -819,17 +819,23 @@ namespace ICSharpCode.NRefactory.CSharp
{ {
StartNode (namedArgumentExpression); StartNode (namedArgumentExpression);
WriteIdentifier (namedArgumentExpression.Identifier); WriteIdentifier (namedArgumentExpression.Identifier);
if (namedArgumentExpression.Parent is AnonymousTypeCreateExpression) { WriteToken(":", NamedArgumentExpression.Roles.Colon);
Space();
WriteToken("=", NamedArgumentExpression.Roles.Assign);
} else {
WriteToken(":", NamedArgumentExpression.Roles.Colon);
}
Space (); Space ();
namedArgumentExpression.Expression.AcceptVisitor (this, data); namedArgumentExpression.Expression.AcceptVisitor (this, data);
return EndNode (namedArgumentExpression); return EndNode (namedArgumentExpression);
} }
public object VisitNamedExpression (NamedExpression namedExpression, object data)
{
StartNode (namedExpression);
WriteIdentifier (namedExpression.Identifier);
Space();
WriteToken("=", NamedArgumentExpression.Roles.Assign);
Space ();
namedExpression.Expression.AcceptVisitor (this, data);
return EndNode (namedExpression);
}
public object VisitNullReferenceExpression (NullReferenceExpression nullReferenceExpression, object data) public object VisitNullReferenceExpression (NullReferenceExpression nullReferenceExpression, object data)
{ {
StartNode (nullReferenceExpression); StartNode (nullReferenceExpression);

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

@ -200,14 +200,13 @@ namespace ICSharpCode.NRefactory.CSharp
} }
if (attr.NamedArguments != null) { if (attr.NamedArguments != null) {
foreach (NamedArgument na in attr.NamedArguments) { foreach (NamedArgument na in attr.NamedArguments) {
var newArg = new AssignmentExpression (); var newArg = new NamedExpression ();
newArg.Operator = AssignmentOperatorType.Assign; newArg.AddChild (Identifier.Create (na.Name, Convert (na.Location)), NamedExpression.Roles.Identifier);
newArg.AddChild (new IdentifierExpression (na.Name, Convert (na.Location)), AssignmentExpression.LeftRole);
var argLoc = LocationsBag.GetLocations (na); var argLoc = LocationsBag.GetLocations (na);
if (argLoc != null) if (argLoc != null)
newArg.AddChild (new CSharpTokenNode (Convert (argLoc[0]), 1), AssignmentExpression.Roles.Assign); newArg.AddChild (new CSharpTokenNode (Convert (argLoc[0]), 1), NamedExpression.Roles.Assign);
newArg.AddChild ((Expression)na.Expr.Accept (this), AssignmentExpression.RightRole); newArg.AddChild ((Expression)na.Expr.Accept (this), NamedExpression.Roles.Expression);
result.AddChild (newArg, Attribute.Roles.Argument); result.AddChild (newArg, Attribute.Roles.Argument);
} }
} }
@ -2262,7 +2261,6 @@ namespace ICSharpCode.NRefactory.CSharp
return; return;
var commaLocations = LocationsBag.GetLocations (args); var commaLocations = LocationsBag.GetLocations (args);
for (int i = 0; i < args.Count; i++) { for (int i = 0; i < args.Count; i++) {
parent.AddChild (ConvertArgument (args[i]), InvocationExpression.Roles.Argument); parent.AddChild (ConvertArgument (args[i]), InvocationExpression.Roles.Argument);
if (commaLocations != null && i > 0) { if (commaLocations != null && i > 0) {
@ -2279,7 +2277,8 @@ namespace ICSharpCode.NRefactory.CSharp
{ {
var result = new InvocationExpression (); var result = new InvocationExpression ();
var location = LocationsBag.GetLocations (invocationExpression); var location = LocationsBag.GetLocations (invocationExpression);
result.AddChild ((Expression)invocationExpression.Expression.Accept (this), InvocationExpression.Roles.TargetExpression); if (invocationExpression.Expression != null)
result.AddChild ((Expression)invocationExpression.Expression.Accept (this), InvocationExpression.Roles.TargetExpression);
if (location != null) if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), InvocationExpression.Roles.LPar); result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), InvocationExpression.Roles.LPar);
AddArguments (result, location, invocationExpression.Arguments); AddArguments (result, location, invocationExpression.Arguments);
@ -2292,7 +2291,6 @@ namespace ICSharpCode.NRefactory.CSharp
public override object Visit (New newExpression) public override object Visit (New newExpression)
{ {
var result = new ObjectCreateExpression (); var result = new ObjectCreateExpression ();
var location = LocationsBag.GetLocations (newExpression); var location = LocationsBag.GetLocations (newExpression);
result.AddChild (new CSharpTokenNode (Convert (newExpression.Location), "new".Length), ObjectCreateExpression.Roles.Keyword); result.AddChild (new CSharpTokenNode (Convert (newExpression.Location), "new".Length), ObjectCreateExpression.Roles.Keyword);
@ -2319,16 +2317,88 @@ namespace ICSharpCode.NRefactory.CSharp
if (location == null) { if (location == null) {
result.AddChild ((Expression)par.Expr.Accept (this), AnonymousTypeCreateExpression.Roles.Expression); result.AddChild ((Expression)par.Expr.Accept (this), AnonymousTypeCreateExpression.Roles.Expression);
} else { } else {
var namedArgument = new NamedArgumentExpression (); var namedExpression = new NamedExpression ();
namedArgument.AddChild (Identifier.Create (par.Name, Convert (par.Location)), AnonymousTypeCreateExpression.Roles.Identifier); namedExpression.AddChild (Identifier.Create (par.Name, Convert (par.Location)), AnonymousTypeCreateExpression.Roles.Identifier);
namedArgument.AddChild (new CSharpTokenNode (Convert (location[0]), 1), AnonymousTypeCreateExpression.Roles.Assign); namedExpression.AddChild (new CSharpTokenNode (Convert (location[0]), 1), AnonymousTypeCreateExpression.Roles.Assign);
namedArgument.AddChild ((Expression)par.Expr.Accept (this), AnonymousTypeCreateExpression.Roles.Expression); namedExpression.AddChild ((Expression)par.Expr.Accept (this), AnonymousTypeCreateExpression.Roles.Expression);
result.AddChild (namedArgument, AnonymousTypeCreateExpression.Roles.Expression); result.AddChild (namedExpression, AnonymousTypeCreateExpression.Roles.Expression);
} }
} }
return result; return result;
} }
ArrayInitializerExpression ConvertCollectionOrObjectInitializers (CollectionOrObjectInitializers minit)
{
if (minit == null)
return null;
var init = new ArrayInitializerExpression ();
var braceLocs = LocationsBag.GetLocations (minit);
if (braceLocs != null)
init.AddChild (new CSharpTokenNode (Convert (braceLocs[0]), 1), ArrayInitializerExpression.Roles.LBrace);
AddConvertCollectionOrObjectInitializers (init, minit);
if (braceLocs != null)
init.AddChild (new CSharpTokenNode (Convert (braceLocs[1]), 1), ArrayInitializerExpression.Roles.RBrace);
return init;
}
void AddConvertCollectionOrObjectInitializers (Expression init, CollectionOrObjectInitializers minit)
{
var initLoc = LocationsBag.GetLocations (minit);
var commaLoc = LocationsBag.GetLocations (minit.Initializers);
int curComma = commaLoc != null ? commaLoc.Count - 1 : -1;
foreach (var expr in minit.Initializers) {
var collectionInit = expr as CollectionElementInitializer;
if (collectionInit != null) {
var parent = new ArrayInitializerExpression ();
var braceLocs = LocationsBag.GetLocations (expr);
if (braceLocs != null)
parent.AddChild (new CSharpTokenNode (Convert (braceLocs[0]), 1), ArrayInitializerExpression.Roles.LBrace);
for (int i = 0; i < collectionInit.Arguments.Count; i++) {
var arg = collectionInit.Arguments[i] as CollectionElementInitializer.ElementInitializerArgument;
if (arg == null)
continue;
parent.AddChild ((ICSharpCode.NRefactory.CSharp.Expression)arg.Expr.Accept (this), ArrayInitializerExpression.Roles.Expression);
if (curComma >= 0)
parent.AddChild (new CSharpTokenNode (Convert (commaLoc[curComma--]), 1), ArrayInitializerExpression.Roles.Comma);
}
if (braceLocs != null)
parent.AddChild (new CSharpTokenNode (Convert (braceLocs[1]), 1), ArrayInitializerExpression.Roles.RBrace);
init.AddChild (parent, ArrayInitializerExpression.Roles.Expression);
continue;
}
var eleInit = expr as ElementInitializer;
if (eleInit != null) {
var nexpr = new NamedExpression ();
nexpr.AddChild (Identifier.Create (eleInit.Name, Convert(eleInit.Location)), NamedArgumentExpression.Roles.Identifier);
var assignLoc = LocationsBag.GetLocations (eleInit);
if (assignLoc != null)
nexpr.AddChild (new CSharpTokenNode (Convert (assignLoc[0]), 1), NamedArgumentExpression.Roles.Assign);
if (eleInit.Source != null) {
if (eleInit.Source is CollectionOrObjectInitializers) {
var arrInit = new ArrayInitializerExpression ();
AddConvertCollectionOrObjectInitializers (arrInit, eleInit.Source as CollectionOrObjectInitializers);
nexpr.AddChild (arrInit, NamedArgumentExpression.Roles.Expression);
} else {
nexpr.AddChild ((Expression)eleInit.Source.Accept (this), NamedArgumentExpression.Roles.Expression);
}
}
init.AddChild (nexpr, ArrayInitializerExpression.Roles.Expression);
}
}
if (initLoc != null) {
if (initLoc.Count == 3) // optional comma
init.AddChild (new CSharpTokenNode (Convert (initLoc[1]), 1), ArrayInitializerExpression.Roles.Comma);
init.AddChild (new CSharpTokenNode (Convert (initLoc[initLoc.Count - 1]), 1), ArrayInitializerExpression.Roles.RBrace);
}
}
public override object Visit (NewInitialize newInitializeExpression) public override object Visit (NewInitialize newInitializeExpression)
{ {
@ -2345,6 +2415,10 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null) if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), ObjectCreateExpression.Roles.RPar); result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), ObjectCreateExpression.Roles.RPar);
var init = ConvertCollectionOrObjectInitializers (newInitializeExpression.Initializers);
if (init != null)
result.AddChild (init, ObjectCreateExpression.InitializerRole);
return result; return result;
} }

1
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Parser/ParsedFile.cs

@ -27,6 +27,7 @@ namespace ICSharpCode.NRefactory.CSharp
/// <summary> /// <summary>
/// Represents a file that was parsed and converted for the type system. /// Represents a file that was parsed and converted for the type system.
/// </summary> /// </summary>
[Serializable]
public sealed class ParsedFile : AbstractFreezable, IParsedFile public sealed class ParsedFile : AbstractFreezable, IParsedFile
{ {
readonly string fileName; readonly string fileName;

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

File diff suppressed because it is too large Load Diff

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

@ -679,7 +679,6 @@ attribute_sections
attrs = new Attributes (sect); attrs = new Attributes (sect);
else else
attrs.AddAttributes (sect); attrs.AddAttributes (sect);
lbag.AddLocation (sect, savedOpenLocation, savedCloseLocation);
$$ = attrs; $$ = attrs;
} }
; ;
@ -753,6 +752,7 @@ attribute_list
{ {
var attrs = (List<Attribute>) $1; var attrs = (List<Attribute>) $1;
attrs.Add ((Attribute) $3); attrs.Add ((Attribute) $3);
lbag.AppendTo (attrs, GetLocation ($2));
$$ = attrs; $$ = attrs;
} }
@ -2984,6 +2984,7 @@ type_list
{ {
var types = (List<FullNamedExpression>) $1; var types = (List<FullNamedExpression>) $1;
types.Add ((FullNamedExpression) $3); types.Add ((FullNamedExpression) $3);
lbag.AppendTo (types, GetLocation ($2));
$$ = types; $$ = types;
} }
; ;
@ -3179,13 +3180,13 @@ object_or_collection_initializer
// TODO: lbag // TODO: lbag
} else { } else {
$$ = new CollectionOrObjectInitializers ((List<Expression>) $2, GetLocation ($1)); $$ = new CollectionOrObjectInitializers ((List<Expression>) $2, GetLocation ($1));
lbag.AddLocation ($$, GetLocation ($3)); lbag.AddLocation ($$, GetLocation ($1), GetLocation ($3));
} }
} }
| OPEN_BRACE member_initializer_list COMMA CLOSE_BRACE | OPEN_BRACE member_initializer_list COMMA CLOSE_BRACE
{ {
$$ = new CollectionOrObjectInitializers ((List<Expression>) $2, GetLocation ($1)); $$ = new CollectionOrObjectInitializers ((List<Expression>) $2, GetLocation ($1));
lbag.AddLocation ($$, GetLocation ($3), GetLocation ($4)); lbag.AddLocation ($$, GetLocation ($1), GetLocation ($3), GetLocation ($4));
} }
; ;
@ -3208,6 +3209,7 @@ member_initializer_list
{ {
var a = (List<Expression>)$1; var a = (List<Expression>)$1;
a.Add ((Expression) $3); a.Add ((Expression) $3);
lbag.AppendTo (a, GetLocation ($2));
$$ = a; $$ = a;
} }
| member_initializer_list error { | member_initializer_list error {
@ -3536,6 +3538,8 @@ anonymous_type_parameters
{ {
var a = (List<AnonymousTypeParameter>) $1; var a = (List<AnonymousTypeParameter>) $1;
a.Add ((AnonymousTypeParameter) $3); a.Add ((AnonymousTypeParameter) $3);
lbag.AppendTo (a, GetLocation ($2));
$$ = a; $$ = a;
} }
; ;
@ -4121,6 +4125,8 @@ lambda_parameter_list
} }
pars.Add (p); pars.Add (p);
lbag.AppendTo (pars, GetLocation ($2));
$$ = pars; $$ = pars;
} }
; ;

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

@ -8855,7 +8855,7 @@ namespace Mono.CSharp
public override void EmitSideEffect (EmitContext ec) public override void EmitSideEffect (EmitContext ec)
{ {
} }
public override object Accept (StructuralVisitor visitor) public override object Accept (StructuralVisitor visitor)
{ {
return visitor.Visit (this); return visitor.Visit (this);
@ -9527,6 +9527,12 @@ namespace Mono.CSharp
} }
} }
public IList<Expression> Initializers {
get {
return initializers;
}
}
protected override void CloneTo (CloneContext clonectx, Expression target) protected override void CloneTo (CloneContext clonectx, Expression target)
{ {
CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target; CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
@ -9681,6 +9687,12 @@ namespace Mono.CSharp
CollectionOrObjectInitializers initializers; CollectionOrObjectInitializers initializers;
IMemoryLocation instance; IMemoryLocation instance;
public CollectionOrObjectInitializers Initializers {
get {
return initializers;
}
}
public NewInitialize (FullNamedExpression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l) public NewInitialize (FullNamedExpression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
: base (requested_type, arguments, l) : base (requested_type, arguments, l)
{ {

1
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/AliasNamespaceReference.cs

@ -28,6 +28,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// The member lookup performed by the :: operator is handled /// The member lookup performed by the :: operator is handled
/// by <see cref="MemberTypeOrNamespaceReference"/>. /// by <see cref="MemberTypeOrNamespaceReference"/>.
/// </remarks> /// </remarks>
[Serializable]
public class AliasNamespaceReference : ITypeOrNamespaceReference public class AliasNamespaceReference : ITypeOrNamespaceReference
{ {
readonly UsingScope parentUsingScope; readonly UsingScope parentUsingScope;

2
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/CSharpAttribute.cs

@ -24,6 +24,7 @@ using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.CSharp.Resolver namespace ICSharpCode.NRefactory.CSharp.Resolver
{ {
[Serializable]
public sealed class CSharpAttribute : Immutable, IAttribute public sealed class CSharpAttribute : Immutable, IAttribute
{ {
ITypeReference attributeType; ITypeReference attributeType;
@ -128,6 +129,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// Type reference used within an attribute. /// Type reference used within an attribute.
/// Looks up both 'withoutSuffix' and 'withSuffix' and returns the type that exists. /// Looks up both 'withoutSuffix' and 'withSuffix' and returns the type that exists.
/// </summary> /// </summary>
[Serializable]
public sealed class AttributeTypeReference : ITypeReference, ISupportsInterning public sealed class AttributeTypeReference : ITypeReference, ISupportsInterning
{ {
ITypeReference withoutSuffix, withSuffix; ITypeReference withoutSuffix, withSuffix;

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

@ -269,6 +269,48 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} }
#endregion #endregion
#region Object Initializer Context
sealed class ObjectInitializerContext
{
internal readonly IType type;
internal readonly ObjectInitializerContext prev;
public ObjectInitializerContext(IType type, CSharpResolver.ObjectInitializerContext prev)
{
this.type = type;
this.prev = prev;
}
}
ObjectInitializerContext objectInitializerStack;
/// <summary>
/// Pushes the type of the object that is currently being initialized.
/// </summary>
public void PushInitializerType(IType type)
{
if (type == null)
throw new ArgumentNullException("type");
objectInitializerStack = new ObjectInitializerContext(type, objectInitializerStack);
}
public void PopInitializerType()
{
if (objectInitializerStack == null)
throw new InvalidOperationException();
objectInitializerStack = objectInitializerStack.prev;
}
/// <summary>
/// Gets the type of the object currently being initialized.
/// Returns SharedTypes.Unknown if no object initializer is currently open (or if the object initializer
/// has unknown type).
/// </summary>
public IType CurrentObjectInitializerType {
get { return objectInitializerStack != null ? objectInitializerStack.type : SharedTypes.UnknownType; }
}
#endregion
#region Clone #region Clone
/// <summary> /// <summary>
/// Creates a copy of this CSharp resolver. /// Creates a copy of this CSharp resolver.
@ -2067,12 +2109,24 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return ErrorResult; return ErrorResult;
} }
MemberLookup CreateMemberLookup() /// <summary>
/// Creates a MemberLookup instance using this resolver's settings.
/// </summary>
public MemberLookup CreateMemberLookup()
{ {
return new MemberLookup(context, this.CurrentTypeDefinition, this.UsingScope != null ? this.UsingScope.ProjectContent : null); return new MemberLookup(context, this.CurrentTypeDefinition, this.UsingScope != null ? this.UsingScope.ProjectContent : null);
} }
#endregion #endregion
#region ResolveIdentifierInObjectInitializer
public ResolveResult ResolveIdentifierInObjectInitializer(string identifier)
{
MemberLookup memberLookup = CreateMemberLookup();
ResolveResult target = new ResolveResult(this.CurrentObjectInitializerType);
return memberLookup.Lookup(target, identifier, EmptyList<IType>.Instance, false);
}
#endregion
#region GetExtensionMethods #region GetExtensionMethods
/// <summary> /// <summary>
/// Gets the extension methods that are called 'name' /// Gets the extension methods that are called 'name'
@ -2377,6 +2431,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
if (type.Kind == TypeKind.Delegate && arguments.Length == 1) {
return Convert(arguments[0], type);
}
OverloadResolution or = new OverloadResolution(context, arguments, argumentNames, new IType[0]); OverloadResolution or = new OverloadResolution(context, arguments, argumentNames, new IType[0]);
MemberLookup lookup = CreateMemberLookup(); MemberLookup lookup = CreateMemberLookup();
bool allowProtectedAccess = lookup.IsProtectedAccessAllowed(type); bool allowProtectedAccess = lookup.IsProtectedAccessAllowed(type);

13
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/ConstantValues.cs

@ -29,6 +29,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
// Contains representations for constant C# expressions. // Contains representations for constant C# expressions.
// We use these instead of storing the full AST to reduce the memory usage. // We use these instead of storing the full AST to reduce the memory usage.
[Serializable]
public sealed class CSharpConstantValue : Immutable, IConstantValue, ISupportsInterning public sealed class CSharpConstantValue : Immutable, IConstantValue, ISupportsInterning
{ {
ConstantExpression expression; ConstantExpression expression;
@ -125,6 +126,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
/// <summary> /// <summary>
/// Increments an integer <see cref="IConstantValue"/> by a fixed amount without changing the type. /// Increments an integer <see cref="IConstantValue"/> by a fixed amount without changing the type.
/// </summary> /// </summary>
[Serializable]
public sealed class IncrementConstantValue : Immutable, IConstantValue, ISupportsInterning public sealed class IncrementConstantValue : Immutable, IConstantValue, ISupportsInterning
{ {
IConstantValue baseValue; IConstantValue baseValue;
@ -178,6 +180,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
} }
} }
[Serializable]
public abstract class ConstantExpression public abstract class ConstantExpression
{ {
public abstract ResolveResult Resolve(CSharpResolver resolver); public abstract ResolveResult Resolve(CSharpResolver resolver);
@ -186,6 +189,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
/// <summary> /// <summary>
/// C#'s equivalent to the SimpleConstantValue. /// C#'s equivalent to the SimpleConstantValue.
/// </summary> /// </summary>
[Serializable]
public sealed class PrimitiveConstantExpression : ConstantExpression, ISupportsInterning public sealed class PrimitiveConstantExpression : ConstantExpression, ISupportsInterning
{ {
ITypeReference type; ITypeReference type;
@ -233,6 +237,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
} }
} }
[Serializable]
public sealed class ConstantCast : ConstantExpression, ISupportsInterning public sealed class ConstantCast : ConstantExpression, ISupportsInterning
{ {
ITypeReference targetType; ITypeReference targetType;
@ -274,6 +279,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
} }
} }
[Serializable]
public sealed class ConstantIdentifierReference : ConstantExpression, ISupportsInterning public sealed class ConstantIdentifierReference : ConstantExpression, ISupportsInterning
{ {
string identifier; string identifier;
@ -327,6 +333,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
} }
} }
[Serializable]
public sealed class ConstantMemberReference : ConstantExpression, ISupportsInterning public sealed class ConstantMemberReference : ConstantExpression, ISupportsInterning
{ {
ITypeReference targetType; ITypeReference targetType;
@ -398,6 +405,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
} }
} }
[Serializable]
public sealed class ConstantCheckedExpression : ConstantExpression, ISupportsInterning public sealed class ConstantCheckedExpression : ConstantExpression, ISupportsInterning
{ {
bool checkForOverflow; bool checkForOverflow;
@ -441,6 +449,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
} }
} }
[Serializable]
public sealed class ConstantDefaultValue : ConstantExpression, ISupportsInterning public sealed class ConstantDefaultValue : ConstantExpression, ISupportsInterning
{ {
ITypeReference type; ITypeReference type;
@ -474,6 +483,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
} }
} }
[Serializable]
public sealed class ConstantUnaryOperator : ConstantExpression, ISupportsInterning public sealed class ConstantUnaryOperator : ConstantExpression, ISupportsInterning
{ {
UnaryOperatorType operatorType; UnaryOperatorType operatorType;
@ -513,6 +523,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
} }
} }
[Serializable]
public sealed class ConstantBinaryOperator : ConstantExpression, ISupportsInterning public sealed class ConstantBinaryOperator : ConstantExpression, ISupportsInterning
{ {
ConstantExpression left; ConstantExpression left;
@ -559,6 +570,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
} }
} }
[Serializable]
public sealed class ConstantConditionalOperator : ConstantExpression, ISupportsInterning public sealed class ConstantConditionalOperator : ConstantExpression, ISupportsInterning
{ {
ConstantExpression condition, trueExpr, falseExpr; ConstantExpression condition, trueExpr, falseExpr;
@ -614,6 +626,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
/// <summary> /// <summary>
/// Represents an array creation (as used within an attribute argument) /// Represents an array creation (as used within an attribute argument)
/// </summary> /// </summary>
[Serializable]
public sealed class ConstantArrayCreation : ConstantExpression, ISupportsInterning public sealed class ConstantArrayCreation : ConstantExpression, ISupportsInterning
{ {
// type may be null when the element is being inferred // type may be null when the element is being inferred

12
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/Log.cs

@ -35,19 +35,21 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// </summary> /// </summary>
static class Log static class Log
{ {
[Conditional("DEBUG")] const bool logEnabled = false;
[Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
internal static void WriteLine(string text) internal static void WriteLine(string text)
{ {
Debug.WriteLine(text); Debug.WriteLine(text);
} }
[Conditional("DEBUG")] [Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
internal static void WriteLine(string format, params object[] args) internal static void WriteLine(string format, params object[] args)
{ {
Debug.WriteLine(format, args); Debug.WriteLine(format, args);
} }
[Conditional("DEBUG")] [Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
internal static void WriteCollection<T>(string text, IEnumerable<T> lines) internal static void WriteCollection<T>(string text, IEnumerable<T> lines)
{ {
#if DEBUG #if DEBUG
@ -63,13 +65,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
#endif #endif
} }
[Conditional("DEBUG")] [Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
public static void Indent() public static void Indent()
{ {
Debug.Indent(); Debug.Indent();
} }
[Conditional("DEBUG")] [Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
public static void Unindent() public static void Unindent()
{ {
Debug.Unindent(); Debug.Unindent();

1
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/MemberTypeOrNamespaceReference.cs

@ -25,6 +25,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <summary> /// <summary>
/// Reference to a qualified type or namespace name. /// Reference to a qualified type or namespace name.
/// </summary> /// </summary>
[Serializable]
public sealed class MemberTypeOrNamespaceReference : ITypeOrNamespaceReference public sealed class MemberTypeOrNamespaceReference : ITypeOrNamespaceReference
{ {
readonly ITypeOrNamespaceReference target; readonly ITypeOrNamespaceReference target;

159
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/ResolveVisitor.cs

@ -221,6 +221,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
protected override ResolveResult VisitChildren(AstNode node, object data) protected override ResolveResult VisitChildren(AstNode node, object data)
{ {
Log.WriteLine("ResolveVisitor: unhandled node " + node.GetType().Name);
ScanChildren(node); ScanChildren(node);
return null; return null;
} }
@ -369,7 +370,10 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
resolver.UsingScope = parsedFile.GetUsingScope(namespaceDeclaration.StartLocation); resolver.UsingScope = parsedFile.GetUsingScope(namespaceDeclaration.StartLocation);
} }
ScanChildren(namespaceDeclaration); ScanChildren(namespaceDeclaration);
return new NamespaceResolveResult(resolver.UsingScope.NamespaceName); if (resolver.UsingScope != null)
return new NamespaceResolveResult(resolver.UsingScope.NamespaceName);
else
return null;
} finally { } finally {
resolver.UsingScope = previousUsingScope; resolver.UsingScope = previousUsingScope;
} }
@ -751,8 +755,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
static string GetAnonymousTypePropertyName(Expression expr, out Expression resolveExpr) static string GetAnonymousTypePropertyName(Expression expr, out Expression resolveExpr)
{ {
if (expr is NamedArgumentExpression) { if (expr is NamedExpression) {
var namedArgExpr = (NamedArgumentExpression)expr; var namedArgExpr = (NamedExpression)expr;
resolveExpr = namedArgExpr.Expression; resolveExpr = namedArgExpr.Expression;
return namedArgExpr.Identifier; return namedArgExpr.Identifier;
} }
@ -771,29 +775,35 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public override ResolveResult VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, object data) public override ResolveResult VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, object data)
{ {
ScanChildren(anonymousTypeCreateExpression);
// 7.6.10.6 Anonymous object creation expressions // 7.6.10.6 Anonymous object creation expressions
var anonymousType = new DefaultTypeDefinition(resolver.CurrentTypeDefinition, "$Anonymous$"); if (resolver.UsingScope == null) {
ScanChildren(anonymousTypeCreateExpression);
return errorResult;
}
var anonymousType = new DefaultTypeDefinition(resolver.UsingScope.ProjectContent, string.Empty, "$Anonymous$");
anonymousType.IsSynthetic = true; anonymousType.IsSynthetic = true;
resolver.PushInitializerType(anonymousType);
foreach (var expr in anonymousTypeCreateExpression.Initializers) { foreach (var expr in anonymousTypeCreateExpression.Initializers) {
Expression resolveExpr; Expression resolveExpr;
var name = GetAnonymousTypePropertyName(expr, out resolveExpr); var name = GetAnonymousTypePropertyName(expr, out resolveExpr);
if (string.IsNullOrEmpty(name)) if (!string.IsNullOrEmpty(name)) {
continue; var property = new DefaultProperty(anonymousType, name) {
Accessibility = Accessibility.Public,
var property = new DefaultProperty(anonymousType, name) { ReturnType = new VarTypeReference(this, resolver.Clone(), resolveExpr, false)
Accessibility = Accessibility.Public, };
ReturnType = new VarTypeReference(this, resolver.Clone(), resolveExpr, false) anonymousType.Properties.Add(property);
}; }
anonymousType.Properties.Add(property); Scan(expr);
} }
ScanChildren(anonymousTypeCreateExpression);
resolver.PopInitializerType();
return new ResolveResult(anonymousType); return new ResolveResult(anonymousType);
} }
public override ResolveResult VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data) public override ResolveResult VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data)
{ {
ScanChildren(arrayCreateExpression);
if (!resolverEnabled) { if (!resolverEnabled) {
ScanChildren(arrayCreateExpression);
return null; return null;
} }
@ -973,15 +983,34 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return null; return null;
} }
// NamedArgumentExpression is "identifier: Expression"
public override ResolveResult VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, object data) public override ResolveResult VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, object data)
{ {
// Usually, the parent expression takes care of handling NamedArgumentExpressions // The parent expression takes care of handling NamedArgumentExpressions
// by calling GetArguments(). // by calling GetArguments().
if (resolverEnabled) { // This method gets called only when scanning, or when the named argument is used
return Resolve(namedArgumentExpression.Expression); // in an invalid context.
Scan(namedArgumentExpression.Expression);
return errorResult;
}
// NamedExpression is "identifier = Expression" in object initializers and attributes
public override ResolveResult VisitNamedExpression(NamedExpression namedExpression, object data)
{
Expression rhs = namedExpression.Expression;
if (rhs is ArrayInitializerExpression) {
ResolveResult result = resolver.ResolveIdentifierInObjectInitializer(namedExpression.Identifier);
HandleObjectInitializer(result.Type, (ArrayInitializerExpression)rhs);
return result;
} else { } else {
Scan(namedArgumentExpression.Expression); if (resolverEnabled) {
return null; ResolveResult result = resolver.ResolveIdentifierInObjectInitializer(namedExpression.Identifier);
ResolveAndProcessConversion(rhs, result.Type);
return result;
} else {
ScanChildren(namedExpression);
return null;
}
} }
} }
@ -996,20 +1025,69 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public override ResolveResult VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, object data) public override ResolveResult VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, object data)
{ {
if (resolverEnabled) { if (resolverEnabled || !objectCreateExpression.Initializer.IsNull) {
IType type = ResolveType(objectCreateExpression.Type); IType type = ResolveType(objectCreateExpression.Type);
string[] argumentNames;
ResolveResult[] arguments = GetArguments(objectCreateExpression.Arguments, out argumentNames);
Scan(objectCreateExpression.Initializer); // TODO var initializer = objectCreateExpression.Initializer;
if (!initializer.IsNull) {
HandleObjectInitializer(type, initializer);
}
return resolver.ResolveObjectCreation(type, arguments, argumentNames); if (resolverEnabled) {
string[] argumentNames;
ResolveResult[] arguments = GetArguments(objectCreateExpression.Arguments, out argumentNames);
return resolver.ResolveObjectCreation(type, arguments, argumentNames);
} else {
foreach (AstNode node in objectCreateExpression.Arguments) {
Scan(node);
}
return null;
}
} else { } else {
ScanChildren(objectCreateExpression); ScanChildren(objectCreateExpression);
return null; return null;
} }
} }
void HandleObjectInitializer(IType type, ArrayInitializerExpression initializer)
{
resolver.PushInitializerType(type);
foreach (Expression element in initializer.Elements) {
ArrayInitializerExpression aie = element as ArrayInitializerExpression;
if (aie != null) {
if (resolveResultCache.ContainsKey(aie)) {
// Don't resolve the add call again if we already did so
continue;
}
StoreState(aie, resolver.Clone());
// constructor argument list in collection initializer
ResolveResult[] addArguments = new ResolveResult[aie.Elements.Count];
int i = 0;
foreach (var addArgument in aie.Elements) {
addArguments[i++] = Resolve(addArgument);
}
MemberLookup memberLookup = resolver.CreateMemberLookup();
ResolveResult targetResult = new ResolveResult(type);
var addRR = memberLookup.Lookup(targetResult, "Add", EmptyList<IType>.Instance, true);
var mgrr = addRR as MethodGroupResolveResult;
if (mgrr != null) {
OverloadResolution or = mgrr.PerformOverloadResolution(resolver.Context, addArguments, null, false, false);
var invocationRR = new InvocationResolveResult(targetResult, or, resolver.Context);
StoreResult(aie, invocationRR);
ProcessConversionsInResult(invocationRR);
} else {
StoreResult(aie, addRR);
}
} else {
// assignment in object initializer (NamedExpression),
// or some unknown kind of expression
Scan(element);
}
}
resolver.PopInitializerType();
}
public override ResolveResult VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, object data) public override ResolveResult VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, object data)
{ {
if (resolverEnabled) { if (resolverEnabled) {
@ -2096,6 +2174,14 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} }
#endregion #endregion
#region Other statements
public override ResolveResult VisitExpressionStatement(ExpressionStatement expressionStatement, object data)
{
ScanChildren(expressionStatement);
return voidResult;
}
#endregion
#region Local Variable Type Inference #region Local Variable Type Inference
/// <summary> /// <summary>
/// Creates a type reference for the specified type node. /// Creates a type reference for the specified type node.
@ -2221,23 +2307,26 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
#region Attributes #region Attributes
public override ResolveResult VisitAttribute(Attribute attribute, object data) public override ResolveResult VisitAttribute(Attribute attribute, object data)
{ {
var type = ResolveType(attribute.Type);
// Separate arguments into ctor arguments and non-ctor arguments:
var constructorArguments = attribute.Arguments.Where(a => !(a is NamedExpression));
var nonConstructorArguments = attribute.Arguments.Where(a => a is NamedExpression);
// Scan the non-constructor arguments
resolver.PushInitializerType(type);
foreach (var arg in nonConstructorArguments)
Scan(arg);
resolver.PopInitializerType();
if (resolverEnabled) { if (resolverEnabled) {
var type = ResolveType(attribute.Type);
// Separate arguments into ctor arguments and non-ctor arguments:
var constructorArguments = attribute.Arguments.Where(a => !(a is AssignmentExpression));
var nonConstructorArguments = attribute.Arguments.Where(a => a is AssignmentExpression);
// Scan the non-constructor arguments
foreach (var arg in nonConstructorArguments)
Scan(arg); // TODO: handle these like object initializers
// Resolve the ctor arguments and find the matching ctor overload // Resolve the ctor arguments and find the matching ctor overload
string[] argumentNames; string[] argumentNames;
ResolveResult[] arguments = GetArguments(constructorArguments, out argumentNames); ResolveResult[] arguments = GetArguments(constructorArguments, out argumentNames);
return resolver.ResolveObjectCreation(type, arguments, argumentNames); return resolver.ResolveObjectCreation(type, arguments, argumentNames);
} else { } else {
ScanChildren(attribute); foreach (var node in constructorArguments)
Scan(node);
return null; return null;
} }
} }

1
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/SimpleTypeOrNamespaceReference.cs

@ -25,6 +25,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <summary> /// <summary>
/// Represents a simple C# name. (a single non-qualified identifier with an optional list of type arguments) /// Represents a simple C# name. (a single non-qualified identifier with an optional list of type arguments)
/// </summary> /// </summary>
[Serializable]
public sealed class SimpleTypeOrNamespaceReference : ITypeOrNamespaceReference public sealed class SimpleTypeOrNamespaceReference : ITypeOrNamespaceReference
{ {
readonly ITypeDefinition parentTypeDefinition; readonly ITypeDefinition parentTypeDefinition;

1
src/Libraries/NRefactory/ICSharpCode.NRefactory/CSharp/Resolver/UsingScope.cs

@ -28,6 +28,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// Represents a scope that contains "using" statements. /// Represents a scope that contains "using" statements.
/// This is either the file itself, or a namespace declaration. /// This is either the file itself, or a namespace declaration.
/// </summary> /// </summary>
[Serializable]
public class UsingScope : AbstractFreezable public class UsingScope : AbstractFreezable
{ {
readonly IProjectContent projectContent; readonly IProjectContent projectContent;

6
src/Libraries/NRefactory/ICSharpCode.NRefactory/Documentation/XmlDocumentationProvider.cs

@ -33,6 +33,7 @@ namespace ICSharpCode.NRefactory.Documentation
/// This class first creates an in-memory index of the .xml file, and then uses that to read only the requested members. /// This class first creates an in-memory index of the .xml file, and then uses that to read only the requested members.
/// This way, we avoid keeping all the documentation in memory. /// This way, we avoid keeping all the documentation in memory.
/// </remarks> /// </remarks>
[Serializable]
public class XmlDocumentationProvider : IDocumentationProvider public class XmlDocumentationProvider : IDocumentationProvider
{ {
#region Cache #region Cache
@ -66,6 +67,7 @@ namespace ICSharpCode.NRefactory.Documentation
} }
#endregion #endregion
[Serializable]
struct IndexEntry : IComparable<IndexEntry> struct IndexEntry : IComparable<IndexEntry>
{ {
/// <summary> /// <summary>
@ -90,7 +92,9 @@ namespace ICSharpCode.NRefactory.Documentation
} }
} }
[NonSerialized]
readonly XmlDocumentationCache cache = new XmlDocumentationCache(); readonly XmlDocumentationCache cache = new XmlDocumentationCache();
readonly string fileName; readonly string fileName;
DateTime lastWriteDate; DateTime lastWriteDate;
IndexEntry[] index; // SORTED array of index entries IndexEntry[] index; // SORTED array of index entries
@ -265,6 +269,8 @@ namespace ICSharpCode.NRefactory.Documentation
#endregion #endregion
#region Save index / Restore from index #region Save index / Restore from index
// TODO: consider removing this code, we're just using serialization instead
// FILE FORMAT FOR BINARY DOCUMENTATION // FILE FORMAT FOR BINARY DOCUMENTATION
// long magic = 0x4244636f446c6d58 (identifies file type = 'XmlDocDB') // long magic = 0x4244636f446c6d58 (identifies file type = 'XmlDocDB')
const long magic = 0x4244636f446c6d58; const long magic = 0x4244636f446c6d58;

14
src/Libraries/NRefactory/ICSharpCode.NRefactory/ICSharpCode.NRefactory.csproj

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build"> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup> <PropertyGroup>
<ProjectGuid>{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}</ProjectGuid> <ProjectGuid>{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}</ProjectGuid>
@ -7,7 +7,6 @@
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<RootNamespace>ICSharpCode.NRefactory</RootNamespace> <RootNamespace>ICSharpCode.NRefactory</RootNamespace>
<AssemblyName>ICSharpCode.NRefactory</AssemblyName> <AssemblyName>ICSharpCode.NRefactory</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<ProductVersion>10.0.0</ProductVersion> <ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
@ -17,7 +16,7 @@
<NoWarn>1591,0618</NoWarn> <NoWarn>1591,0618</NoWarn>
<RunCodeAnalysis>False</RunCodeAnalysis> <RunCodeAnalysis>False</RunCodeAnalysis>
<CodeAnalysisRules>-Microsoft.Design#CA1026;-Microsoft.Security#CA2104</CodeAnalysisRules> <CodeAnalysisRules>-Microsoft.Design#CA1026;-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>
@ -52,11 +51,9 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core"> <Reference Include="System.Core" />
</Reference>
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq"> <Reference Include="System.Xml.Linq" />
</Reference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="CSharp\Analysis\ControlFlow.cs" /> <Compile Include="CSharp\Analysis\ControlFlow.cs" />
@ -339,6 +336,7 @@
<Compile Include="CSharp\Parser\mcs\support.cs" /> <Compile Include="CSharp\Parser\mcs\support.cs" />
<Compile Include="CSharp\Parser\mcs\complete.cs" /> <Compile Include="CSharp\Parser\mcs\complete.cs" />
<Compile Include="CSharp\Parser\mcs\literal.cs" /> <Compile Include="CSharp\Parser\mcs\literal.cs" />
<Compile Include="Utils\7BitEncodedInts.cs" />
<Compile Include="Utils\BitVector16.cs" /> <Compile Include="Utils\BitVector16.cs" />
<Compile Include="Utils\BusyManager.cs" /> <Compile Include="Utils\BusyManager.cs" />
<Compile Include="Utils\CacheManager.cs" /> <Compile Include="Utils\CacheManager.cs" />
@ -346,6 +344,7 @@
<Compile Include="Utils\DotNet35Compat.cs" /> <Compile Include="Utils\DotNet35Compat.cs" />
<Compile Include="Utils\EmptyList.cs" /> <Compile Include="Utils\EmptyList.cs" />
<Compile Include="Utils\ExtensionMethods.cs" /> <Compile Include="Utils\ExtensionMethods.cs" />
<Compile Include="Utils\FastSerializer.cs" />
<Compile Include="Utils\GraphVizGraph.cs" /> <Compile Include="Utils\GraphVizGraph.cs" />
<Compile Include="Utils\Platform.cs" /> <Compile Include="Utils\Platform.cs" />
<Compile Include="Utils\TreeTraversal.cs" /> <Compile Include="Utils\TreeTraversal.cs" />
@ -412,6 +411,7 @@
<Compile Include="TypeSystem\Error.cs" /> <Compile Include="TypeSystem\Error.cs" />
<Compile Include="TypeSystem\IAnnotatable.cs" /> <Compile Include="TypeSystem\IAnnotatable.cs" />
<Compile Include="CSharp\Ast\ErrorNode.cs" /> <Compile Include="CSharp\Ast\ErrorNode.cs" />
<Compile Include="CSharp\Ast\Expressions\NamedExpression.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="CSharp\" /> <Folder Include="CSharp\" />

2
src/Libraries/NRefactory/ICSharpCode.NRefactory/Properties/AssemblyInfo.cs

@ -28,4 +28,4 @@ using System.Runtime.InteropServices;
// //
// You can specify all the values or you can use the default the Revision and // You can specify all the values or you can use the default the Revision and
// Build Numbers by using the '*' as shown below: // Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("5.0.0.0")]

2
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/ArrayType.cs

@ -25,6 +25,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <summary> /// <summary>
/// Represents an array type. /// Represents an array type.
/// </summary> /// </summary>
[Serializable]
public sealed class ArrayType : TypeWithElementType public sealed class ArrayType : TypeWithElementType
{ {
readonly int dimensions; readonly int dimensions;
@ -135,6 +136,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
} }
} }
[Serializable]
public sealed class ArrayTypeReference : ITypeReference, ISupportsInterning public sealed class ArrayTypeReference : ITypeReference, ISupportsInterning
{ {
ITypeReference elementType; ITypeReference elementType;

2
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/ByReferenceType.cs

@ -21,6 +21,7 @@ using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.TypeSystem namespace ICSharpCode.NRefactory.TypeSystem
{ {
[Serializable]
public sealed class ByReferenceType : TypeWithElementType public sealed class ByReferenceType : TypeWithElementType
{ {
public ByReferenceType(IType elementType) : base(elementType) public ByReferenceType(IType elementType) : base(elementType)
@ -68,6 +69,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
} }
} }
[Serializable]
public class ByReferenceTypeReference : ITypeReference public class ByReferenceTypeReference : ITypeReference
{ {
readonly ITypeReference elementType; readonly ITypeReference elementType;

34
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/CecilLoader.cs

@ -23,6 +23,7 @@ using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Threading; using System.Threading;
using ICSharpCode.NRefactory.TypeSystem.Implementation; using ICSharpCode.NRefactory.TypeSystem.Implementation;
using Mono.Cecil; using Mono.Cecil;
@ -84,6 +85,9 @@ namespace ICSharpCode.NRefactory.TypeSystem
{ {
if (createCecilReferences) if (createCecilReferences)
typeSystemTranslationTable = new Dictionary<object, object> (); typeSystemTranslationTable = new Dictionary<object, object> ();
// Enable interning by default.
this.InterningProvider = new SimpleInterningProvider();
} }
#region Load From AssemblyDefinition #region Load From AssemblyDefinition
@ -164,6 +168,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
#endregion #endregion
#region IProjectContent implementation #region IProjectContent implementation
[Serializable]
sealed class CecilProjectContent : ProxyTypeResolveContext, IProjectContent, ISynchronizedTypeResolveContext, IDocumentationProvider sealed class CecilProjectContent : ProxyTypeResolveContext, IProjectContent, ISynchronizedTypeResolveContext, IDocumentationProvider
{ {
readonly string assemblyName; readonly string assemblyName;
@ -234,6 +239,33 @@ namespace ICSharpCode.NRefactory.TypeSystem
else else
return null; return null;
} }
IEnumerable<object> IAnnotatable.Annotations {
get { return EmptyList<object>.Instance; }
}
T IAnnotatable.Annotation<T>()
{
return null;
}
object IAnnotatable.Annotation(Type type)
{
return null;
}
void IAnnotatable.AddAnnotation(object annotation)
{
throw new NotSupportedException();
}
void IAnnotatable.RemoveAnnotations<T>()
{
}
void IAnnotatable.RemoveAnnotations(Type type)
{
}
} }
#endregion #endregion
@ -844,8 +876,10 @@ namespace ICSharpCode.NRefactory.TypeSystem
#endregion #endregion
#region Read Type Definition #region Read Type Definition
[Serializable]
sealed class CecilTypeDefinition : DefaultTypeDefinition sealed class CecilTypeDefinition : DefaultTypeDefinition
{ {
[NonSerialized]
internal TypeDefinition typeDefinition; internal TypeDefinition typeDefinition;
public CecilTypeDefinition(IProjectContent pc, TypeDefinition typeDefinition) public CecilTypeDefinition(IProjectContent pc, TypeDefinition typeDefinition)

31
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Error.cs

@ -1,4 +1,4 @@
// //
// Error.cs // Error.cs
// //
// Author: // Author:
@ -42,22 +42,27 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <summary> /// <summary>
/// Descibes an error during parsing. /// Descibes an error during parsing.
/// </summary> /// </summary>
[Serializable]
public class Error public class Error
{ {
readonly ErrorType errorType;
readonly string message;
readonly DomRegion region;
/// <summary> /// <summary>
/// The type of the error. /// The type of the error.
/// </summary> /// </summary>
public ErrorType ErrorType { get; private set; } public ErrorType ErrorType { get { return errorType; } }
/// <summary> /// <summary>
/// The error description. /// The error description.
/// </summary> /// </summary>
public string Message { get; private set; } public string Message { get { return message; } }
/// <summary> /// <summary>
/// The region of the error. /// The region of the error.
/// </summary> /// </summary>
public DomRegion Region { get; private set; } public DomRegion Region { get { return region; } }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.Error"/> class. /// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.Error"/> class.
@ -73,9 +78,9 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </param> /// </param>
public Error (ErrorType errorType, string message, DomRegion region) public Error (ErrorType errorType, string message, DomRegion region)
{ {
this.ErrorType = errorType; this.errorType = errorType;
this.Message = message; this.message = message;
this.Region = region; this.region = region;
} }
/// <summary> /// <summary>
@ -92,9 +97,9 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </param> /// </param>
public Error (ErrorType errorType, string message, AstLocation location) public Error (ErrorType errorType, string message, AstLocation location)
{ {
this.ErrorType = errorType; this.errorType = errorType;
this.Message = message; this.message = message;
this.Region = new DomRegion (location, location); this.region = new DomRegion (location, location);
} }
/// <summary> /// <summary>
@ -127,9 +132,9 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </param> /// </param>
public Error (ErrorType errorType, string message) public Error (ErrorType errorType, string message)
{ {
this.ErrorType = errorType; this.errorType = errorType;
this.Message = message; this.message = message;
this.Region = DomRegion.Empty; this.region = DomRegion.Empty;
} }
} }
} }

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

@ -27,6 +27,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// Base class for immutable objects. Provides implementation for IFreezable that reports the /// Base class for immutable objects. Provides implementation for IFreezable that reports the
/// object as always-frozen. /// object as always-frozen.
/// </summary> /// </summary>
[Serializable]
public abstract class Immutable : IFreezable public abstract class Immutable : IFreezable
{ {
bool IFreezable.IsFrozen { bool IFreezable.IsFrozen {
@ -38,6 +39,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
} }
} }
[Serializable]
public abstract class AbstractFreezable : IFreezable public abstract class AbstractFreezable : IFreezable
{ {
bool isFrozen; bool isFrozen;

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

@ -25,6 +25,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Base class for <see cref="IMember"/> implementations. /// Base class for <see cref="IMember"/> implementations.
/// </summary> /// </summary>
[Serializable]
public abstract class AbstractMember : AbstractFreezable, IMember public abstract class AbstractMember : AbstractFreezable, IMember
{ {
// possible optimizations to reduce the memory usage of AbstractMember: // possible optimizations to reduce the memory usage of AbstractMember:

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

@ -26,6 +26,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Default implementation for IType interface. /// Default implementation for IType interface.
/// </summary> /// </summary>
[Serializable]
public abstract class AbstractType : IType public abstract class AbstractType : IType
{ {
public virtual string FullName { public virtual string FullName {

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

@ -25,6 +25,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Default implementation of <see cref="IAccessor"/>. /// Default implementation of <see cref="IAccessor"/>.
/// </summary> /// </summary>
[Serializable]
public sealed class DefaultAccessor : AbstractFreezable, IAccessor, ISupportsInterning public sealed class DefaultAccessor : AbstractFreezable, IAccessor, ISupportsInterning
{ {
static readonly DefaultAccessor[] defaultAccessors = CreateDefaultAccessors(); static readonly DefaultAccessor[] defaultAccessors = CreateDefaultAccessors();

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

@ -27,6 +27,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Default implementation of <see cref="IAttribute"/>. /// Default implementation of <see cref="IAttribute"/>.
/// </summary> /// </summary>
[Serializable]
public sealed class DefaultAttribute : AbstractFreezable, IAttribute, ISupportsInterning public sealed class DefaultAttribute : AbstractFreezable, IAttribute, ISupportsInterning
{ {
ITypeReference attributeType; ITypeReference attributeType;

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

@ -23,6 +23,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Default implementation of <see cref="IEvent"/>. /// Default implementation of <see cref="IEvent"/>.
/// </summary> /// </summary>
[Serializable]
public class DefaultEvent : AbstractMember, IEvent public class DefaultEvent : AbstractMember, IEvent
{ {
IAccessor addAccessor, removeAccessor, invokeAccessor; IAccessor addAccessor, removeAccessor, invokeAccessor;

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

@ -23,6 +23,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Default implementation of <see cref="IField"/>. /// Default implementation of <see cref="IField"/>.
/// </summary> /// </summary>
[Serializable]
public class DefaultField : AbstractMember, IField public class DefaultField : AbstractMember, IField
{ {
IConstantValue constantValue; IConstantValue constantValue;

6
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultMethod.cs

@ -25,6 +25,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Default implementation of <see cref="IMethod" /> interface. /// Default implementation of <see cref="IMethod" /> interface.
/// </summary> /// </summary>
[Serializable]
public class DefaultMethod : AbstractMember, IMethod public class DefaultMethod : AbstractMember, IMethod
{ {
IList<IAttribute> returnTypeAttributes; IList<IAttribute> returnTypeAttributes;
@ -123,7 +124,10 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
var p = this.Parameters; var p = this.Parameters;
for (int i = 0; i < p.Count; i++) { for (int i = 0; i < p.Count; i++) {
if (i > 0) b.Append(", "); if (i > 0) b.Append(", ");
b.Append(p[i].ToString()); if (p[i] == null)
b.Append("null");
else
b.Append(p[i].ToString());
} }
b.Append("):"); b.Append("):");
b.Append(ReturnType.ToString()); b.Append(ReturnType.ToString());

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

@ -26,6 +26,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Default implementation for IParameter. /// Default implementation for IParameter.
/// </summary> /// </summary>
[Serializable]
public sealed class DefaultParameter : AbstractFreezable, IParameter, ISupportsInterning public sealed class DefaultParameter : AbstractFreezable, IParameter, ISupportsInterning
{ {
string name = string.Empty; string name = string.Empty;

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

@ -24,6 +24,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Default implementation of <see cref="IProperty"/>. /// Default implementation of <see cref="IProperty"/>.
/// </summary> /// </summary>
[Serializable]
public class DefaultProperty : AbstractMember, IProperty public class DefaultProperty : AbstractMember, IProperty
{ {
IAccessor getter, setter; IAccessor getter, setter;

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

@ -25,6 +25,7 @@ using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.TypeSystem.Implementation namespace ICSharpCode.NRefactory.TypeSystem.Implementation
{ {
[Serializable]
public class DefaultTypeDefinition : AbstractFreezable, ITypeDefinition public class DefaultTypeDefinition : AbstractFreezable, ITypeDefinition
{ {
readonly IProjectContent projectContent; readonly IProjectContent projectContent;

10
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultTypeParameter.cs

@ -27,6 +27,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Default implementation of <see cref="ITypeParameter"/>. /// Default implementation of <see cref="ITypeParameter"/>.
/// </summary> /// </summary>
[Serializable]
public sealed class DefaultTypeParameter : AbstractFreezable, ITypeParameter, ISupportsInterning public sealed class DefaultTypeParameter : AbstractFreezable, ITypeParameter, ISupportsInterning
{ {
string name; string name;
@ -348,8 +349,13 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
void ISupportsInterning.PrepareForInterning(IInterningProvider provider) void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
{ {
constraints = provider.InternList(constraints); // protect against cyclic constraints
attributes = provider.InternList(attributes); using (var busyLock = BusyManager.Enter(this)) {
if (busyLock.Success) {
constraints = provider.InternList(constraints);
attributes = provider.InternList(attributes);
}
}
} }
int ISupportsInterning.GetHashCodeForInterning() int ISupportsInterning.GetHashCodeForInterning()

3
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/GetClassTypeReference.cs

@ -25,11 +25,12 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Type Reference used when the fully qualified type name is known. /// Type Reference used when the fully qualified type name is known.
/// </summary> /// </summary>
[Serializable]
public sealed class GetClassTypeReference : ITypeReference, ISupportsInterning public sealed class GetClassTypeReference : ITypeReference, ISupportsInterning
{ {
string nameSpace, name; string nameSpace, name;
int typeParameterCount; int typeParameterCount;
//volatile CachedResult v_cachedResult; // [NonSerialized] volatile CachedResult v_cachedResult;
public GetClassTypeReference(string nameSpace, string name, int typeParameterCount) public GetClassTypeReference(string nameSpace, string name, int typeParameterCount)
{ {

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

@ -23,6 +23,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Type reference used to reference nested types. /// Type reference used to reference nested types.
/// </summary> /// </summary>
[Serializable]
public sealed class NestedTypeReference : ITypeReference, ISupportsInterning public sealed class NestedTypeReference : ITypeReference, ISupportsInterning
{ {
ITypeReference declaringTypeRef; ITypeReference declaringTypeRef;

3
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/ProxyTypeResolveContext.cs

@ -25,7 +25,8 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// Proxy that forwards calls to another TypeResolveContext. /// Proxy that forwards calls to another TypeResolveContext.
/// Useful as base class for decorators. /// Useful as base class for decorators.
/// </summary> /// </summary>
public class ProxyTypeResolveContext : AbstractAnnotatable, ITypeResolveContext [Serializable]
public class ProxyTypeResolveContext : ITypeResolveContext
{ {
protected readonly ITypeResolveContext target; protected readonly ITypeResolveContext target;

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

@ -23,6 +23,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// A simple constant value that is independent of the resolve context. /// A simple constant value that is independent of the resolve context.
/// </summary> /// </summary>
[Serializable]
public sealed class SimpleConstantValue : Immutable, IConstantValue, ISupportsInterning public sealed class SimpleConstantValue : Immutable, IConstantValue, ISupportsInterning
{ {
ITypeReference type; ITypeReference type;

10
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleInterningProvider.cs

@ -104,6 +104,8 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
Dictionary<ISupportsInterning, ISupportsInterning> supportsInternDict = new Dictionary<ISupportsInterning, ISupportsInterning>(new InterningComparer()); Dictionary<ISupportsInterning, ISupportsInterning> supportsInternDict = new Dictionary<ISupportsInterning, ISupportsInterning>(new InterningComparer());
Dictionary<IEnumerable, IEnumerable> listDict = new Dictionary<IEnumerable, IEnumerable>(new ListComparer()); Dictionary<IEnumerable, IEnumerable> listDict = new Dictionary<IEnumerable, IEnumerable>(new ListComparer());
int stackDepth = 0;
public T Intern<T>(T obj) where T : class public T Intern<T>(T obj) where T : class
{ {
if (obj == null) if (obj == null)
@ -127,6 +129,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
else else
byValueDict.Add(obj, obj); byValueDict.Add(obj, obj);
} }
stackDepth--;
return obj; return obj;
} }
@ -138,8 +141,11 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
T oldItem = list[i]; T oldItem = list[i];
T newItem = Intern(oldItem); T newItem = Intern(oldItem);
if (oldItem != newItem) { if (oldItem != newItem) {
if (list.IsReadOnly) if (list.IsReadOnly) {
list = new T[list.Count]; T[] array = new T[list.Count];
list.CopyTo(array, 0);
list = array;
}
list[i] = newItem; list[i] = newItem;
} }
} }

55
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleProjectContent.cs

@ -20,8 +20,8 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Threading; using System.Threading;
using ICSharpCode.NRefactory.Utils; using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.TypeSystem.Implementation namespace ICSharpCode.NRefactory.TypeSystem.Implementation
@ -34,12 +34,22 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// Compared with <see cref="TypeStorage"/>, this class adds support for the IProjectContent interface, /// Compared with <see cref="TypeStorage"/>, this class adds support for the IProjectContent interface,
/// for partial classes, and for multi-threading. /// for partial classes, and for multi-threading.
/// </remarks> /// </remarks>
public class SimpleProjectContent : AbstractAnnotatable, IProjectContent [Serializable]
public class SimpleProjectContent : AbstractAnnotatable, IProjectContent, ISerializable, IDeserializationCallback
{ {
readonly TypeStorage types = new TypeStorage(); readonly TypeStorage types = new TypeStorage();
readonly ReaderWriterLockSlim readerWriterLock = new ReaderWriterLockSlim(); readonly ReaderWriterLockSlim readerWriterLock = new ReaderWriterLockSlim();
readonly Dictionary<string, IParsedFile> fileDict = new Dictionary<string, IParsedFile>(Platform.FileNameComparer); readonly Dictionary<string, IParsedFile> fileDict = new Dictionary<string, IParsedFile>(Platform.FileNameComparer);
#region Constructor
/// <summary>
/// Creates a new SimpleProjectContent instance.
/// </summary>
public SimpleProjectContent()
{
}
#endregion
public virtual string AssemblyName { public virtual string AssemblyName {
get { return string.Empty; } get { return string.Empty; }
} }
@ -288,5 +298,46 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
} }
} }
#endregion #endregion
#region Serialization
SerializationInfo serializationInfo;
protected SimpleProjectContent(SerializationInfo info, StreamingContext context)
{
this.serializationInfo = info;
assemblyAttributes.AddRange((IAttribute[])info.GetValue("AssemblyAttributes", typeof(IAttribute[])));
readOnlyAssemblyAttributes = assemblyAttributes.ToArray();
moduleAttributes.AddRange((IAttribute[])info.GetValue("ModuleAttributes", typeof(IAttribute[])));
readOnlyModuleAttributes = moduleAttributes.ToArray();
}
public virtual void OnDeserialization(object sender)
{
// We need to do this in OnDeserialization because at the time the deserialization
// constructor runs, type.FullName/file.FileName may not be deserialized yet.
if (serializationInfo != null) {
foreach (var typeDef in (ITypeDefinition[])serializationInfo.GetValue("Types", typeof(ITypeDefinition[]))) {
types.UpdateType(typeDef);
}
foreach (IParsedFile file in (IParsedFile[])serializationInfo.GetValue("Files", typeof(IParsedFile[]))) {
fileDict.Add(file.FileName, file);
}
serializationInfo = null;
}
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
readerWriterLock.EnterReadLock();
try {
info.AddValue("Types", types.GetTypes().ToArray());
info.AddValue("AssemblyAttributes", readOnlyAssemblyAttributes);
info.AddValue("ModuleAttributes", readOnlyModuleAttributes);
info.AddValue("Files", fileDict.Values.ToArray());
} finally {
readerWriterLock.ExitReadLock();
}
}
#endregion
} }
} }

36
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/Implementation/TypeStorage.cs

@ -19,8 +19,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Threading; using System.Threading;
using ICSharpCode.NRefactory.Utils; using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.TypeSystem.Implementation namespace ICSharpCode.NRefactory.TypeSystem.Implementation
@ -31,7 +31,8 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <remarks> /// <remarks>
/// Concurrent read accesses are thread-safe, but a write access concurrent to any other access is not safe. /// Concurrent read accesses are thread-safe, but a write access concurrent to any other access is not safe.
/// </remarks> /// </remarks>
public sealed class TypeStorage : ITypeResolveContext [Serializable]
public sealed class TypeStorage : ITypeResolveContext, ISerializable, IDeserializationCallback
{ {
#region FullNameAndTypeParameterCount #region FullNameAndTypeParameterCount
struct FullNameAndTypeParameterCount struct FullNameAndTypeParameterCount
@ -362,5 +363,36 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
} }
} }
#endregion #endregion
#region Serialization
/// <summary>
/// Creates a new TypeStorage instance.
/// </summary>
public TypeStorage()
{
}
SerializationInfo serializationInfo;
private TypeStorage(SerializationInfo info, StreamingContext context)
{
this.serializationInfo = info;
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Types", this.GetTypes().ToArray());
}
void IDeserializationCallback.OnDeserialization(object sender)
{
if (serializationInfo == null)
return;
foreach (var typeDef in (ITypeDefinition[])serializationInfo.GetValue("Types", typeof(ITypeDefinition[]))) {
UpdateType(typeDef);
}
serializationInfo = null;
}
#endregion
} }
} }

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

@ -20,6 +20,7 @@ using System;
namespace ICSharpCode.NRefactory.TypeSystem.Implementation namespace ICSharpCode.NRefactory.TypeSystem.Implementation
{ {
[Serializable]
public abstract class TypeWithElementType : AbstractType public abstract class TypeWithElementType : AbstractType
{ {
protected readonly IType elementType; protected readonly IType elementType;

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

@ -24,6 +24,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
/// <summary> /// <summary>
/// Special type definition for 'void'. /// Special type definition for 'void'.
/// </summary> /// </summary>
[Serializable]
public class VoidTypeDefinition : DefaultTypeDefinition public class VoidTypeDefinition : DefaultTypeDefinition
{ {
public VoidTypeDefinition(IProjectContent projectContent) public VoidTypeDefinition(IProjectContent projectContent)

1
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/IntersectionType.cs

@ -30,6 +30,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <summary> /// <summary>
/// Represents the intersection of several types. /// Represents the intersection of several types.
/// </summary> /// </summary>
[Serializable]
public class IntersectionType : AbstractType public class IntersectionType : AbstractType
{ {
readonly ReadOnlyCollection<IType> types; readonly ReadOnlyCollection<IType> types;

2
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/ParameterizedType.cs

@ -36,6 +36,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// type parameters in the signatures of the members are replaced with /// type parameters in the signatures of the members are replaced with
/// the type arguments. /// the type arguments.
/// </remarks> /// </remarks>
[Serializable]
public sealed class ParameterizedType : Immutable, IType public sealed class ParameterizedType : Immutable, IType
{ {
readonly ITypeDefinition genericType; readonly ITypeDefinition genericType;
@ -327,6 +328,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// ParameterizedTypeReference is a reference to generic class that specifies the type parameters. /// ParameterizedTypeReference is a reference to generic class that specifies the type parameters.
/// Example: List&lt;string&gt; /// Example: List&lt;string&gt;
/// </summary> /// </summary>
[Serializable]
public sealed class ParameterizedTypeReference : ITypeReference, ISupportsInterning public sealed class ParameterizedTypeReference : ITypeReference, ISupportsInterning
{ {
public static ITypeReference Create(ITypeReference genericType, IEnumerable<ITypeReference> typeArguments) public static ITypeReference Create(ITypeReference genericType, IEnumerable<ITypeReference> typeArguments)

2
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/PointerType.cs

@ -22,6 +22,7 @@ using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.TypeSystem namespace ICSharpCode.NRefactory.TypeSystem
{ {
[Serializable]
public sealed class PointerType : TypeWithElementType public sealed class PointerType : TypeWithElementType
{ {
public PointerType(IType elementType) : base(elementType) public PointerType(IType elementType) : base(elementType)
@ -69,6 +70,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
} }
} }
[Serializable]
public class PointerTypeReference : ITypeReference public class PointerTypeReference : ITypeReference
{ {
readonly ITypeReference elementType; readonly ITypeReference elementType;

1
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/SharedTypes.cs

@ -70,6 +70,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
* would have to return true even though these are two distinct definitions. * would have to return true even though these are two distinct definitions.
*/ */
[Serializable]
sealed class SharedTypeImpl : AbstractType sealed class SharedTypeImpl : AbstractType
{ {
readonly TypeKind kind; readonly TypeKind kind;

117
src/Libraries/NRefactory/ICSharpCode.NRefactory/Utils/7BitEncodedInts.cs

@ -0,0 +1,117 @@
// Copyright (c) 2011 Daniel Grunwald
//
// 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.IO;
namespace ICSharpCode.NRefactory.Utils
{
/// <summary>
/// A binary reader that can read the output of BinaryWriterWith7BitEncodedInts.
/// </summary>
public sealed class BinaryReaderWith7BitEncodedInts : BinaryReader
{
public BinaryReaderWith7BitEncodedInts(Stream stream) : base(stream)
{
}
public override short ReadInt16()
{
return unchecked((short)(ushort)base.Read7BitEncodedInt());
}
public override ushort ReadUInt16()
{
return unchecked((ushort)base.Read7BitEncodedInt());
}
public override int ReadInt32()
{
return base.Read7BitEncodedInt();
}
public override uint ReadUInt32()
{
return unchecked((uint)base.Read7BitEncodedInt());
}
public override long ReadInt64()
{
return unchecked((long)this.ReadUInt64());
}
public override ulong ReadUInt64()
{
ulong num = 0;
int shift = 0;
while (shift < 64) {
byte b = this.ReadByte();
num |= (ulong)(b & 127) << shift;
shift += 7;
if ((b & 128) == 0) {
return num;
}
}
throw new FormatException("Invalid 7-bit int64");
}
}
/// <summary>
/// A binary writer that encodes all integers as 7-bit-encoded-ints.
/// </summary>
public sealed class BinaryWriterWith7BitEncodedInts : BinaryWriter
{
public BinaryWriterWith7BitEncodedInts(Stream stream) : base(stream)
{
}
public override void Write(short value)
{
base.Write7BitEncodedInt(unchecked((ushort)value));
}
public override void Write(ushort value)
{
base.Write7BitEncodedInt(value);
}
public override void Write(int value)
{
base.Write7BitEncodedInt(value);
}
public override void Write(uint value)
{
base.Write7BitEncodedInt(unchecked((int)value));
}
public override void Write(long value)
{
this.Write(unchecked((ulong)value));
}
public override void Write(ulong value)
{
while (value >= 128) {
this.Write(unchecked((byte)(value | 128u)));
value >>= 7;
}
this.Write(unchecked((byte)value));
}
}
}

1
src/Libraries/NRefactory/ICSharpCode.NRefactory/Utils/BitVector16.cs

@ -23,6 +23,7 @@ namespace ICSharpCode.NRefactory.Utils
/// <summary> /// <summary>
/// Holds 16 boolean values. /// Holds 16 boolean values.
/// </summary> /// </summary>
[Serializable]
public struct BitVector16 : IEquatable<BitVector16> public struct BitVector16 : IEquatable<BitVector16>
{ {
ushort data; ushort data;

1
src/Libraries/NRefactory/ICSharpCode.NRefactory/Utils/EmptyList.cs

@ -23,6 +23,7 @@ using System.Collections.ObjectModel;
namespace ICSharpCode.NRefactory namespace ICSharpCode.NRefactory
{ {
[Serializable]
sealed class EmptyList<T> : IList<T>, IEnumerator<T> sealed class EmptyList<T> : IList<T>, IEnumerator<T>
{ {
public static readonly IList<T> Instance = new EmptyList<T>(); public static readonly IList<T> Instance = new EmptyList<T>();

1316
src/Libraries/NRefactory/ICSharpCode.NRefactory/Utils/FastSerializer.cs

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save