Browse Source

Update to NRefactory commit '2a46efacdad982a6fcf07303f57a917585356462'

2a46efa CSharpResolver: return ErrorResolveResult instead of crashing when given an invalid operator type.
2371920 Merge pull request icsharpcode/NRefactory#388 from mono-soc-2013/MateY-IndentEngine
dec33c5 Fixed Bug 18463
9719b41 Added failing unit test.
9d2209e Updated mcs
98f042d Fix icsharpcode/SharpDevelop#404: Crash in CSharpCompletionEngine.GetLineIndent() when line has no indentation.
39e17c9 Documentation for IAmbience
01bf167 Fix icsharpcode/NRefactory#386: A using statement referring to a missing nested type causes infinite recursion in resolver
2cd1a17 Re-enable NameLookupTests.NamespaceDefinitionOverwritesTypeName
0c4a81e Fixed bug in using declaration namespace name.
09531ca Fixed bug in in IndentBlocksInsideExpressions option.
484160b Added 'IndentBlocksInsideExpressions' formatting option.
a35eafb Improved event method naming.
fd9e073 Removed duplicate event creation data.
81436d0 Added new 'bold' display flag for code completion.
pull/419/head
Daniel Grunwald 11 years ago
parent
commit
129bf84e8e
  1. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/NamespaceDeclaration.cs
  2. 25
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/UsingDeclaration.cs
  3. 88
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs
  4. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CompletionDataWrapper.cs
  5. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionDataFactory.cs
  6. 5
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/CSharpFormattingOptions.cs
  7. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingOptionsFactory.cs
  8. 12
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Expressions.cs
  9. 9
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/IndentEngine/IndentState.cs
  10. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpAmbience.cs
  11. 29
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/async.cs
  12. 92
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cfold.cs
  13. 12
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/class.cs
  14. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/codegen.cs
  15. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/complete.cs
  16. 48
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/constant.cs
  17. 33
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/convert.cs
  18. 15
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.cs
  19. 15
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.jay
  20. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/delegate.cs
  21. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/doc.cs
  22. 270
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ecore.cs
  23. 43
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/expression.cs
  24. 13
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/import.cs
  25. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/modifiers.cs
  26. 185
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/namespace.cs
  27. 22
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/nullable.cs
  28. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/parameter.cs
  29. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/property.cs
  30. 19
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/settings.cs
  31. 27
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/statement.cs
  32. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/typespec.cs
  33. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Resolver/CSharpResolver.cs
  34. 19
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/DelegateContextTests.cs
  35. 27
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/RedundantUsingDirectiveIssueTests.cs
  36. 12
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Resolver/NameLookupTests.cs
  37. 56
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/FormattingTests/TestBraceStlye.cs
  38. 68
      src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/IndentationTests/BlockTest.cs
  39. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory/Completion/DisplayFlags.cs
  40. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/IAmbience.cs

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

@ -55,7 +55,7 @@ namespace ICSharpCode.NRefactory.CSharp
public string Name { public string Name {
get { get {
return NamespaceName.ToString(); return UsingDeclaration.ConstructNamespace(NamespaceName);
} }
set { set {
var arr = value.Split('.'); var arr = value.Split('.');

25
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/GeneralScope/UsingDeclaration.cs

@ -27,6 +27,7 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp namespace ICSharpCode.NRefactory.CSharp
{ {
@ -54,7 +55,29 @@ namespace ICSharpCode.NRefactory.CSharp
} }
public string Namespace { public string Namespace {
get { return this.Import.ToString(); } get { return ConstructNamespace (Import); }
}
internal static string ConstructNamespace (AstType type)
{
var stack = new Stack<string>();
while (type is MemberType) {
var mt = (MemberType)type;
stack.Push(mt.MemberName);
type = mt.Target;
if (mt.IsDoubleColon) {
stack.Push("::");
} else {
stack.Push(".");
}
}
if (type is SimpleType)
stack.Push(((SimpleType)type).Identifier);
var result = new StringBuilder();
while (stack.Count > 0)
result.Append(stack.Pop());
return result.ToString();
} }
public CSharpTokenNode SemicolonToken { public CSharpTokenNode SemicolonToken {

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

@ -350,8 +350,8 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
} }
var lookup = new MemberLookup(ctx.CurrentTypeDefinition, Compilation.MainAssembly); var lookup = new MemberLookup(ctx.CurrentTypeDefinition, Compilation.MainAssembly);
bool isProtectedAllowed = ctx.CurrentTypeDefinition != null && initializerType.GetDefinition() != null ? bool isProtectedAllowed = ctx.CurrentTypeDefinition != null && initializerType.GetDefinition() != null ?
ctx.CurrentTypeDefinition.IsDerivedFrom(initializerType.GetDefinition()) : ctx.CurrentTypeDefinition.IsDerivedFrom(initializerType.GetDefinition()) :
false; false;
foreach (var m in initializerType.GetMembers (m => m.SymbolKind == SymbolKind.Field)) { foreach (var m in initializerType.GetMembers (m => m.SymbolKind == SymbolKind.Field)) {
var f = m as IField; var f = m as IField;
if (f != null && (f.IsReadOnly || f.IsConst)) if (f != null && (f.IsReadOnly || f.IsConst))
@ -844,6 +844,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return null; return null;
case "+=": case "+=":
case "-=": case "-=":
var curTokenIndex = tokenIndex;
GetPreviousToken(ref tokenIndex, false); GetPreviousToken(ref tokenIndex, false);
expressionOrVariableDeclaration = GetExpressionAt(tokenIndex); expressionOrVariableDeclaration = GetExpressionAt(tokenIndex);
@ -881,17 +882,8 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (token == "+=") { if (token == "+=") {
string parameterDefinition = AddDelegateHandlers( string parameterDefinition = AddDelegateHandlers(
wrapper, wrapper,
delegateType delegateType,
); optDelegateName: GuessEventHandlerMethodName(curTokenIndex)
string varName = GetPreviousMemberReferenceExpression(tokenIndex);
wrapper.Result.Add(
factory.CreateEventCreationCompletionData(
varName,
delegateType,
evt,
parameterDefinition,
currentMember,
currentType)
); );
} }
@ -2316,7 +2308,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
for (int j = line.Offset; j < line.EndOffset; j++) { for (int j = line.Offset; j < line.EndOffset; j++) {
char ch = document.GetCharAt(j); char ch = document.GetCharAt(j);
if (!char.IsWhiteSpace(ch)) { if (!char.IsWhiteSpace(ch)) {
return document.GetText(line.Offset, j - line.Offset - 1); return document.GetText(line.Offset, j - line.Offset);
} }
} }
return ""; return "";
@ -2364,7 +2356,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
// check for valid constructors // check for valid constructors
if (t.GetConstructors().Count() > 0) { if (t.GetConstructors().Count() > 0) {
bool isProtectedAllowed = currentType != null ? bool isProtectedAllowed = currentType != null ?
currentType.Resolve(ctx).GetDefinition().IsDerivedFrom(t.GetDefinition()) : false; currentType.Resolve(ctx).GetDefinition().IsDerivedFrom(t.GetDefinition()) : false;
if (!t.GetConstructors().Any(m => lookup.IsAccessible(m, isProtectedAllowed))) { if (!t.GetConstructors().Any(m => lookup.IsAccessible(m, isProtectedAllowed))) {
return null; return null;
} }
@ -2589,36 +2581,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
} }
} }
public string GetPreviousMemberReferenceExpression(int tokenIndex) public string GuessEventHandlerMethodName(int tokenIndex)
{ {
string result = GetPreviousToken(ref tokenIndex, false); string result = GetPreviousToken(ref tokenIndex, false);
result = GetPreviousToken(ref tokenIndex, false); return "Handle" + result;
if (result != ".") {
result = null;
} else {
var names = new List<string>();
while (result == ".") {
result = GetPreviousToken(ref tokenIndex, false);
if (result == "this") {
names.Add("handle");
} else if (result != null) {
string trimmedName = result.Trim();
if (trimmedName.Length == 0) {
break;
}
names.Insert(0, trimmedName);
}
result = GetPreviousToken(ref tokenIndex, false);
}
result = String.Join("", names.ToArray());
foreach (char ch in result) {
if (!char.IsLetterOrDigit(ch) && ch != '_') {
result = "";
break;
}
}
}
return result;
} }
bool MatchDelegate(IType delegateType, IMethod method) bool MatchDelegate(IType delegateType, IMethod method)
@ -2654,13 +2620,13 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
"delegate", "delegate",
"Creates anonymous delegate.", "Creates anonymous delegate.",
"delegate {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString "delegate {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
); ).DisplayFlags |= DisplayFlags.MarkedBold;
if (LanguageVersion.Major >= 5) { if (LanguageVersion.Major >= 5) {
completionList.AddCustom( completionList.AddCustom(
"async delegate", "async delegate",
"Creates anonymous async delegate.", "Creates anonymous async delegate.",
"async delegate {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString "async delegate {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
); ).DisplayFlags |= DisplayFlags.MarkedBold;
} }
} }
var sb = new StringBuilder("("); var sb = new StringBuilder("(");
@ -2691,26 +2657,26 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
"delegate" + signature, "delegate" + signature,
"Creates anonymous delegate.", "Creates anonymous delegate.",
"delegate" + signature + " {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString "delegate" + signature + " {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
); ).DisplayFlags |= DisplayFlags.MarkedBold;
if (LanguageVersion.Major >= 5) { if (LanguageVersion.Major >= 5) {
completionList.AddCustom( completionList.AddCustom(
"async delegate" + signature, "async delegate" + signature,
"Creates anonymous async delegate.", "Creates anonymous async delegate.",
"async delegate" + signature + " {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString "async delegate" + signature + " {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
); ).DisplayFlags |= DisplayFlags.MarkedBold;
} }
if (!completionList.Result.Any(data => data.DisplayText == sb.ToString())) { if (!completionList.Result.Any(data => data.DisplayText == sb.ToString())) {
completionList.AddCustom( completionList.AddCustom(
signature, signature,
"Creates typed lambda expression.", "Creates typed lambda expression.",
signature + " => |" + (addSemicolon ? ";" : "") signature + " => |" + (addSemicolon ? ";" : "")
); ).DisplayFlags |= DisplayFlags.MarkedBold;
if (LanguageVersion.Major >= 5) { if (LanguageVersion.Major >= 5) {
completionList.AddCustom( completionList.AddCustom(
"async " + signature, "async " + signature,
"Creates typed async lambda expression.", "Creates typed async lambda expression.",
"async " + signature + " => |" + (addSemicolon ? ";" : "") "async " + signature + " => |" + (addSemicolon ? ";" : "")
); ).DisplayFlags |= DisplayFlags.MarkedBold;
} }
if (!delegateMethod.Parameters.Any(p => p.IsOut || p.IsRef) && !completionList.Result.Any(data => data.DisplayText == sbWithoutTypes.ToString())) { if (!delegateMethod.Parameters.Any(p => p.IsOut || p.IsRef) && !completionList.Result.Any(data => data.DisplayText == sbWithoutTypes.ToString())) {
@ -2718,33 +2684,25 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
sbWithoutTypes.ToString(), sbWithoutTypes.ToString(),
"Creates lambda expression.", "Creates lambda expression.",
sbWithoutTypes + " => |" + (addSemicolon ? ";" : "") sbWithoutTypes + " => |" + (addSemicolon ? ";" : "")
); ).DisplayFlags |= DisplayFlags.MarkedBold;
if (LanguageVersion.Major >= 5) { if (LanguageVersion.Major >= 5) {
completionList.AddCustom( completionList.AddCustom(
"async " + sbWithoutTypes, "async " + sbWithoutTypes,
"Creates async lambda expression.", "Creates async lambda expression.",
"async " + sbWithoutTypes + " => |" + (addSemicolon ? ";" : "") "async " + sbWithoutTypes + " => |" + (addSemicolon ? ";" : "")
); ).DisplayFlags |= DisplayFlags.MarkedBold;
} }
} }
} }
} }
string varName = "Handle" + delegateType.Name + optDelegateName; string varName = optDelegateName ?? "Handle" + delegateType.Name;
completionList.Add(factory.CreateEventCreationCompletionData(varName, delegateType, null, signature, currentMember, currentType));
var ecd = factory.CreateEventCreationCompletionData(varName, delegateType, null, signature, currentMember, currentType);
ecd.DisplayFlags |= DisplayFlags.MarkedBold;
completionList.Add(ecd);
/* TODO:Make factory method out of it.
// It's needed to temporarly disable inserting auto matching bracket because the anonymous delegates are selectable with '('
// otherwise we would end up with () => )
if (!containsDelegateData) {
var savedValue = MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket;
MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket = false;
completionList.Result.CompletionListClosed += delegate {
MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket = savedValue;
};
}*/
return sb.ToString(); return sb.ToString();
} }
@ -2835,7 +2793,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var astResolver = unit != null ? CompletionContextProvider.GetResolver(state, unit) : null; var astResolver = unit != null ? CompletionContextProvider.GetResolver(state, unit) : null;
IType hintType = exprParent != null && astResolver != null ? IType hintType = exprParent != null && astResolver != null ?
TypeGuessing.GetValidTypes(astResolver, exprParent).FirstOrDefault() : TypeGuessing.GetValidTypes(astResolver, exprParent).FirstOrDefault() :
null; null;
var result = new CompletionDataWrapper(this); var result = new CompletionDataWrapper(this);
var lookup = new MemberLookup( var lookup = new MemberLookup(
ctx.CurrentTypeDefinition, ctx.CurrentTypeDefinition,
@ -2900,7 +2858,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (resolvedType.Kind == TypeKind.Delegate) { if (resolvedType.Kind == TypeKind.Delegate) {
if (addedDelegates.Contains(resolvedType.ReflectionName)) if (addedDelegates.Contains(resolvedType.ReflectionName))
return; return;
AddDelegateHandlers(result, resolvedType, false, true, method.Parameters [parameter].Name); AddDelegateHandlers(result, resolvedType, false, true, "Handle" + method.Parameters [parameter].Type.Name + method.Parameters [parameter].Name);
} }
} }

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

@ -65,9 +65,11 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
} }
public void AddCustom (string displayText, string description = null, string completionText = null) public ICompletionData AddCustom (string displayText, string description = null, string completionText = null)
{ {
result.Add (Factory.CreateLiteralCompletionData (displayText, description, completionText)); var literalCompletionData = Factory.CreateLiteralCompletionData(displayText, description, completionText);
result.Add(literalCompletionData);
return literalCompletionData;
} }
HashSet<string> usedNamespaces = new HashSet<string> (); HashSet<string> usedNamespaces = new HashSet<string> ();

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

@ -64,7 +64,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
ICompletionData CreateVariableCompletionData (ITypeParameter parameter); ICompletionData CreateVariableCompletionData (ITypeParameter parameter);
ICompletionData CreateEventCreationCompletionData (string varName, IType delegateType, IEvent evt, string parameterDefinition, IUnresolvedMember currentMember, IUnresolvedTypeDefinition currentType); ICompletionData CreateEventCreationCompletionData (string delegateMethodName, IType delegateType, IEvent evt, string parameterDefinition, IUnresolvedMember currentMember, IUnresolvedTypeDefinition currentType);
ICompletionData CreateNewOverrideCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IMember m); ICompletionData CreateNewOverrideCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IMember m);
ICompletionData CreateNewPartialCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IUnresolvedMember m); ICompletionData CreateNewPartialCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IUnresolvedMember m);

5
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/CSharpFormattingOptions.cs

@ -186,6 +186,11 @@ namespace ICSharpCode.NRefactory.CSharp
get; get;
set; set;
} }
public bool IndentBlocksInsideExpressions {
get;
set;
}
#endregion #endregion
#region Braces #region Braces

3
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingOptionsFactory.cs

@ -59,6 +59,7 @@ namespace ICSharpCode.NRefactory.CSharp
IndentCaseBody = true, IndentCaseBody = true,
IndentBreakStatements = true, IndentBreakStatements = true,
IndentPreprocessorDirectives = true, IndentPreprocessorDirectives = true,
IndentBlocksInsideExpressions = false,
NamespaceBraceStyle = BraceStyle.NextLine, NamespaceBraceStyle = BraceStyle.NextLine,
ClassBraceStyle = BraceStyle.NextLine, ClassBraceStyle = BraceStyle.NextLine,
InterfaceBraceStyle = BraceStyle.NextLine, InterfaceBraceStyle = BraceStyle.NextLine,
@ -390,6 +391,7 @@ namespace ICSharpCode.NRefactory.CSharp
baseOptions.FinallyNewLinePlacement = NewLinePlacement.NewLine; baseOptions.FinallyNewLinePlacement = NewLinePlacement.NewLine;
baseOptions.WhileNewLinePlacement = NewLinePlacement.DoNotCare; baseOptions.WhileNewLinePlacement = NewLinePlacement.DoNotCare;
baseOptions.ArrayInitializerWrapping = Wrapping.DoNotChange; baseOptions.ArrayInitializerWrapping = Wrapping.DoNotChange;
baseOptions.IndentBlocksInsideExpressions = true;
return baseOptions; return baseOptions;
} }
@ -418,6 +420,7 @@ namespace ICSharpCode.NRefactory.CSharp
baseOptions.EventAddBraceStyle = BraceStyle.NextLineShifted; baseOptions.EventAddBraceStyle = BraceStyle.NextLineShifted;
baseOptions.EventRemoveBraceStyle = BraceStyle.NextLineShifted; baseOptions.EventRemoveBraceStyle = BraceStyle.NextLineShifted;
baseOptions.StatementBraceStyle = BraceStyle.NextLineShifted; baseOptions.StatementBraceStyle = BraceStyle.NextLineShifted;
baseOptions.IndentBlocksInsideExpressions = true;
return baseOptions; return baseOptions;
} }

12
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Formatter/FormattingVisitor_Expressions.cs

@ -389,13 +389,21 @@ namespace ICSharpCode.NRefactory.CSharp
} else { } else {
foreach (var arg in arguments.Take (argumentStart)) { foreach (var arg in arguments.Take (argumentStart)) {
if (policy.IndentBlocksInsideExpressions)
curIndent.Push(IndentType.Continuation);
arg.AcceptVisitor(this); arg.AcceptVisitor(this);
if (policy.IndentBlocksInsideExpressions)
curIndent.Pop();
} }
foreach (var arg in arguments.Skip(argumentStart)) { foreach (var arg in arguments.Skip(argumentStart)) {
if (arg.GetPrevSibling(NoWhitespacePredicate) != null) { if (arg.GetPrevSibling(NoWhitespacePredicate) != null) {
if (methodCallArgumentWrapping == Wrapping.DoNotWrap) { if (methodCallArgumentWrapping == Wrapping.DoNotWrap) {
ForceSpacesBeforeRemoveNewLines(arg, spaceAfterMethodCallParameterComma && arg.GetPrevSibling(NoWhitespacePredicate).Role == Roles.Comma); ForceSpacesBeforeRemoveNewLines(arg, spaceAfterMethodCallParameterComma && arg.GetPrevSibling(NoWhitespacePredicate).Role == Roles.Comma);
if (policy.IndentBlocksInsideExpressions)
curIndent.Push(IndentType.Continuation);
arg.AcceptVisitor(this); arg.AcceptVisitor(this);
if (policy.IndentBlocksInsideExpressions)
curIndent.Pop();
} else { } else {
if (!doAlignToFirstArgument && arg.PrevSibling.Role == Roles.NewLine) { if (!doAlignToFirstArgument && arg.PrevSibling.Role == Roles.NewLine) {
curIndent.Push(IndentType.Continuation); curIndent.Push(IndentType.Continuation);
@ -405,7 +413,11 @@ namespace ICSharpCode.NRefactory.CSharp
} else { } else {
if (arg.PrevSibling.StartLocation.Line == arg.StartLocation.Line) { if (arg.PrevSibling.StartLocation.Line == arg.StartLocation.Line) {
ForceSpacesBefore(arg, spaceAfterMethodCallParameterComma && arg.GetPrevSibling(NoWhitespacePredicate).Role == Roles.Comma); ForceSpacesBefore(arg, spaceAfterMethodCallParameterComma && arg.GetPrevSibling(NoWhitespacePredicate).Role == Roles.Comma);
if (policy.IndentBlocksInsideExpressions)
curIndent.Push(IndentType.Continuation);
arg.AcceptVisitor(this); arg.AcceptVisitor(this);
if (policy.IndentBlocksInsideExpressions)
curIndent.Pop();
} else { } else {
int extraSpaces = Math.Max(0, arguments.First().StartLocation.Column - 1 - curIndent.IndentString.Length); int extraSpaces = Math.Max(0, arguments.First().StartLocation.Column - 1 - curIndent.IndentString.Length);
curIndent.ExtraSpaces += extraSpaces; curIndent.ExtraSpaces += extraSpaces;

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

@ -485,7 +485,6 @@ namespace ICSharpCode.NRefactory.CSharp
ThisLineIndent.RemoveAlignment(); ThisLineIndent.RemoveAlignment();
while (ThisLineIndent.CurIndent > PreviousLineIndent && while (ThisLineIndent.CurIndent > PreviousLineIndent &&
ThisLineIndent.PopIf(IndentType.Continuation)) ; ThisLineIndent.PopIf(IndentType.Continuation)) ;
ThisLineIndent.Push(IndentType.Continuation); ThisLineIndent.Push(IndentType.Continuation);
NextLineIndent = ThisLineIndent.Clone(); NextLineIndent = ThisLineIndent.Clone();
} }
@ -517,8 +516,10 @@ namespace ICSharpCode.NRefactory.CSharp
var parent = Parent as BracesBodyState; var parent = Parent as BracesBodyState;
if (parent == null || parent.LastBlockIndent == null || !Engine.EnableCustomIndentLevels) if (parent == null || parent.LastBlockIndent == null || !Engine.EnableCustomIndentLevels)
{ {
NextLineIndent.RemoveAlignment(); if (!Engine.formattingOptions.IndentBlocksInsideExpressions) {
NextLineIndent.PopIf(IndentType.Continuation); NextLineIndent.RemoveAlignment();
NextLineIndent.PopIf(IndentType.Continuation);
}
} }
else else
{ {
@ -1032,7 +1033,7 @@ namespace ICSharpCode.NRefactory.CSharp
public override void OnExit() public override void OnExit()
{ {
// override the base.OnExit() logic Parent.OnExit();
} }
public override IndentState Clone(CSharpIndentEngine engine) public override IndentState Clone(CSharpIndentEngine engine)

2
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpAmbience.cs

@ -24,7 +24,7 @@ using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp namespace ICSharpCode.NRefactory.CSharp
{ {
/// <summary> /// <summary>
/// C# ambience. /// C# ambience. Used to convert type system symbols to text (usually for displaying the symbol to the user; e.g. in editor tooltips)
/// </summary> /// </summary>
public class CSharpAmbience : IAmbience public class CSharpAmbience : IAmbience
{ {

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

@ -936,20 +936,30 @@ namespace Mono.CSharp
} }
} }
class StackFieldExpr : FieldExpr, IExpressionCleanup public class StackFieldExpr : FieldExpr, IExpressionCleanup
{ {
public StackFieldExpr (Field field) public StackFieldExpr (Field field)
: base (field, Location.Null) : base (field, Location.Null)
{ {
} }
public bool IsAvailableForReuse {
get {
var field = (Field) spec.MemberDefinition;
return field.IsAvailableForReuse;
}
set {
var field = (Field) spec.MemberDefinition;
field.IsAvailableForReuse = value;
}
}
public override void AddressOf (EmitContext ec, AddressOp mode) public override void AddressOf (EmitContext ec, AddressOp mode)
{ {
base.AddressOf (ec, mode); base.AddressOf (ec, mode);
if (mode == AddressOp.Load) { if (mode == AddressOp.Load) {
var field = (Field) spec.MemberDefinition; IsAvailableForReuse = true;
field.IsAvailableForReuse = true;
} }
} }
@ -957,8 +967,17 @@ namespace Mono.CSharp
{ {
base.Emit (ec); base.Emit (ec);
var field = (Field) spec.MemberDefinition; PrepareCleanup (ec);
field.IsAvailableForReuse = true; }
public void EmitLoad (EmitContext ec)
{
base.Emit (ec);
}
public void PrepareCleanup (EmitContext ec)
{
IsAvailableForReuse = true;
// //
// Release any captured reference type stack variables // Release any captured reference type stack variables

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

@ -390,14 +390,14 @@ namespace Mono.CSharp {
return new DoubleConstant (ec.BuiltinTypes, res, left.Location); return new DoubleConstant (ec.BuiltinTypes, res, left.Location);
} }
if (left is FloatConstant){ if (left is FloatConstant){
float res; double a, b, res;
a = ((FloatConstant) left).DoubleValue;
b = ((FloatConstant) right).DoubleValue;
if (ec.ConstantCheckState) if (ec.ConstantCheckState)
res = checked (((FloatConstant) left).Value + res = checked (a + b);
((FloatConstant) right).Value);
else else
res = unchecked (((FloatConstant) left).Value + res = unchecked (a + b);
((FloatConstant) right).Value);
result = new FloatConstant (ec.BuiltinTypes, res, left.Location); result = new FloatConstant (ec.BuiltinTypes, res, left.Location);
} else if (left is ULongConstant){ } else if (left is ULongConstant){
@ -514,14 +514,14 @@ namespace Mono.CSharp {
result = new DoubleConstant (ec.BuiltinTypes, res, left.Location); result = new DoubleConstant (ec.BuiltinTypes, res, left.Location);
} else if (left is FloatConstant){ } else if (left is FloatConstant){
float res; double a, b, res;
a = ((FloatConstant) left).DoubleValue;
b = ((FloatConstant) right).DoubleValue;
if (ec.ConstantCheckState) if (ec.ConstantCheckState)
res = checked (((FloatConstant) left).Value - res = checked (a - b);
((FloatConstant) right).Value);
else else
res = unchecked (((FloatConstant) left).Value - res = unchecked (a - b);
((FloatConstant) right).Value);
result = new FloatConstant (ec.BuiltinTypes, res, left.Location); result = new FloatConstant (ec.BuiltinTypes, res, left.Location);
} else if (left is ULongConstant){ } else if (left is ULongConstant){
@ -611,14 +611,14 @@ namespace Mono.CSharp {
return new DoubleConstant (ec.BuiltinTypes, res, left.Location); return new DoubleConstant (ec.BuiltinTypes, res, left.Location);
} else if (left is FloatConstant){ } else if (left is FloatConstant){
float res; double a, b, res;
a = ((FloatConstant) left).DoubleValue;
b = ((FloatConstant) right).DoubleValue;
if (ec.ConstantCheckState) if (ec.ConstantCheckState)
res = checked (((FloatConstant) left).Value * res = checked (a * b);
((FloatConstant) right).Value);
else else
res = unchecked (((FloatConstant) left).Value * res = unchecked (a * b);
((FloatConstant) right).Value);
return new FloatConstant (ec.BuiltinTypes, res, left.Location); return new FloatConstant (ec.BuiltinTypes, res, left.Location);
} else if (left is ULongConstant){ } else if (left is ULongConstant){
@ -707,14 +707,14 @@ namespace Mono.CSharp {
return new DoubleConstant (ec.BuiltinTypes, res, left.Location); return new DoubleConstant (ec.BuiltinTypes, res, left.Location);
} else if (left is FloatConstant){ } else if (left is FloatConstant){
float res; double a, b, res;
a = ((FloatConstant) left).DoubleValue;
b = ((FloatConstant) right).DoubleValue;
if (ec.ConstantCheckState) if (ec.ConstantCheckState)
res = checked (((FloatConstant) left).Value / res = checked (a / b);
((FloatConstant) right).Value);
else else
res = unchecked (((FloatConstant) left).Value / res = unchecked (a / b);
((FloatConstant) right).Value);
return new FloatConstant (ec.BuiltinTypes, res, left.Location); return new FloatConstant (ec.BuiltinTypes, res, left.Location);
} else if (left is ULongConstant){ } else if (left is ULongConstant){
@ -807,14 +807,14 @@ namespace Mono.CSharp {
return new DoubleConstant (ec.BuiltinTypes, res, left.Location); return new DoubleConstant (ec.BuiltinTypes, res, left.Location);
} else if (left is FloatConstant){ } else if (left is FloatConstant){
float res; double a, b, res;
a = ((FloatConstant) left).DoubleValue;
b = ((FloatConstant) right).DoubleValue;
if (ec.ConstantCheckState) if (ec.ConstantCheckState)
res = checked (((FloatConstant) left).Value % res = checked (a % b);
((FloatConstant) right).Value);
else else
res = unchecked (((FloatConstant) left).Value % res = unchecked (a % b);
((FloatConstant) right).Value);
return new FloatConstant (ec.BuiltinTypes, res, left.Location); return new FloatConstant (ec.BuiltinTypes, res, left.Location);
} else if (left is ULongConstant){ } else if (left is ULongConstant){
@ -883,7 +883,6 @@ namespace Mono.CSharp {
IntConstant ic = right.ConvertImplicitly (ec.BuiltinTypes.Int) as IntConstant; IntConstant ic = right.ConvertImplicitly (ec.BuiltinTypes.Int) as IntConstant;
if (ic == null){ if (ic == null){
Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc);
return null; return null;
} }
@ -905,8 +904,7 @@ namespace Mono.CSharp {
if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Int) if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Int)
return new IntConstant (ec.BuiltinTypes, ((IntConstant) left).Value << lshift_val, left.Location); return new IntConstant (ec.BuiltinTypes, ((IntConstant) left).Value << lshift_val, left.Location);
Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc); return null;
break;
// //
// There is no overflow checking on right shift // There is no overflow checking on right shift
@ -920,7 +918,6 @@ namespace Mono.CSharp {
IntConstant sic = right.ConvertImplicitly (ec.BuiltinTypes.Int) as IntConstant; IntConstant sic = right.ConvertImplicitly (ec.BuiltinTypes.Int) as IntConstant;
if (sic == null){ if (sic == null){
Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc);
return null; return null;
} }
int rshift_val = sic.Value; int rshift_val = sic.Value;
@ -941,8 +938,7 @@ namespace Mono.CSharp {
if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Int) if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Int)
return new IntConstant (ec.BuiltinTypes, ((IntConstant) left).Value >> rshift_val, left.Location); return new IntConstant (ec.BuiltinTypes, ((IntConstant) left).Value >> rshift_val, left.Location);
Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc); return null;
break;
case Binary.Operator.Equality: case Binary.Operator.Equality:
if (TypeSpec.IsReferenceType (lt) && TypeSpec.IsReferenceType (rt) || if (TypeSpec.IsReferenceType (lt) && TypeSpec.IsReferenceType (rt) ||
@ -969,8 +965,8 @@ namespace Mono.CSharp {
bool_res = ((DoubleConstant) left).Value == bool_res = ((DoubleConstant) left).Value ==
((DoubleConstant) right).Value; ((DoubleConstant) right).Value;
else if (left is FloatConstant) else if (left is FloatConstant)
bool_res = ((FloatConstant) left).Value == bool_res = ((FloatConstant) left).DoubleValue ==
((FloatConstant) right).Value; ((FloatConstant) right).DoubleValue;
else if (left is ULongConstant) else if (left is ULongConstant)
bool_res = ((ULongConstant) left).Value == bool_res = ((ULongConstant) left).Value ==
((ULongConstant) right).Value; ((ULongConstant) right).Value;
@ -1013,8 +1009,8 @@ namespace Mono.CSharp {
bool_res = ((DoubleConstant) left).Value != bool_res = ((DoubleConstant) left).Value !=
((DoubleConstant) right).Value; ((DoubleConstant) right).Value;
else if (left is FloatConstant) else if (left is FloatConstant)
bool_res = ((FloatConstant) left).Value != bool_res = ((FloatConstant) left).DoubleValue !=
((FloatConstant) right).Value; ((FloatConstant) right).DoubleValue;
else if (left is ULongConstant) else if (left is ULongConstant)
bool_res = ((ULongConstant) left).Value != bool_res = ((ULongConstant) left).Value !=
((ULongConstant) right).Value; ((ULongConstant) right).Value;
@ -1049,8 +1045,8 @@ namespace Mono.CSharp {
bool_res = ((DoubleConstant) left).Value < bool_res = ((DoubleConstant) left).Value <
((DoubleConstant) right).Value; ((DoubleConstant) right).Value;
else if (left is FloatConstant) else if (left is FloatConstant)
bool_res = ((FloatConstant) left).Value < bool_res = ((FloatConstant) left).DoubleValue <
((FloatConstant) right).Value; ((FloatConstant) right).DoubleValue;
else if (left is ULongConstant) else if (left is ULongConstant)
bool_res = ((ULongConstant) left).Value < bool_res = ((ULongConstant) left).Value <
((ULongConstant) right).Value; ((ULongConstant) right).Value;
@ -1085,8 +1081,8 @@ namespace Mono.CSharp {
bool_res = ((DoubleConstant) left).Value > bool_res = ((DoubleConstant) left).Value >
((DoubleConstant) right).Value; ((DoubleConstant) right).Value;
else if (left is FloatConstant) else if (left is FloatConstant)
bool_res = ((FloatConstant) left).Value > bool_res = ((FloatConstant) left).DoubleValue >
((FloatConstant) right).Value; ((FloatConstant) right).DoubleValue;
else if (left is ULongConstant) else if (left is ULongConstant)
bool_res = ((ULongConstant) left).Value > bool_res = ((ULongConstant) left).Value >
((ULongConstant) right).Value; ((ULongConstant) right).Value;
@ -1121,8 +1117,8 @@ namespace Mono.CSharp {
bool_res = ((DoubleConstant) left).Value >= bool_res = ((DoubleConstant) left).Value >=
((DoubleConstant) right).Value; ((DoubleConstant) right).Value;
else if (left is FloatConstant) else if (left is FloatConstant)
bool_res = ((FloatConstant) left).Value >= bool_res = ((FloatConstant) left).DoubleValue >=
((FloatConstant) right).Value; ((FloatConstant) right).DoubleValue;
else if (left is ULongConstant) else if (left is ULongConstant)
bool_res = ((ULongConstant) left).Value >= bool_res = ((ULongConstant) left).Value >=
((ULongConstant) right).Value; ((ULongConstant) right).Value;
@ -1157,8 +1153,8 @@ namespace Mono.CSharp {
bool_res = ((DoubleConstant) left).Value <= bool_res = ((DoubleConstant) left).Value <=
((DoubleConstant) right).Value; ((DoubleConstant) right).Value;
else if (left is FloatConstant) else if (left is FloatConstant)
bool_res = ((FloatConstant) left).Value <= bool_res = ((FloatConstant) left).DoubleValue <=
((FloatConstant) right).Value; ((FloatConstant) right).DoubleValue;
else if (left is ULongConstant) else if (left is ULongConstant)
bool_res = ((ULongConstant) left).Value <= bool_res = ((ULongConstant) left).Value <=
((ULongConstant) right).Value; ((ULongConstant) right).Value;
@ -1176,7 +1172,7 @@ namespace Mono.CSharp {
return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location); return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location);
} }
return null; return null;
} }
} }

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

@ -144,8 +144,8 @@ namespace Mono.CSharp
} }
if ((existing.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) && if ((existing.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 && ((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) == 0 &&
(next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) { (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) == 0)) {
Report.SymbolRelatedToPreviousError (existing); Report.SymbolRelatedToPreviousError (existing);
Report.Error (262, next_part.Location, Report.Error (262, next_part.Location,
"Partial declarations of `{0}' have conflicting accessibility modifiers", "Partial declarations of `{0}' have conflicting accessibility modifiers",
@ -172,10 +172,10 @@ namespace Mono.CSharp
} }
} }
if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) { if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0) {
existing.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask); existing.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFIER | Modifiers.AccessibilityMask);
} else if ((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) { } else if ((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0) {
existing.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask); existing.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFIER | Modifiers.AccessibilityMask);
existing.ModFlags |= next_part.ModFlags; existing.ModFlags |= next_part.ModFlags;
} else { } else {
existing.ModFlags |= next_part.ModFlags; existing.ModFlags |= next_part.ModFlags;

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

@ -370,7 +370,7 @@ namespace Mono.CSharp
// //
// Creates temporary field in current async storey // Creates temporary field in current async storey
// //
public FieldExpr GetTemporaryField (TypeSpec type) public StackFieldExpr GetTemporaryField (TypeSpec type)
{ {
var f = AsyncTaskStorey.AddCapturedLocalVariable (type); var f = AsyncTaskStorey.AddCapturedLocalVariable (type);
var fexpr = new StackFieldExpr (f); var fexpr = new StackFieldExpr (f);

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

@ -147,14 +147,14 @@ namespace Mono.CSharp {
} }
var results = new List<string> (); var results = new List<string> ();
if (expr is Namespace) { var nexpr = expr as NamespaceExpression;
Namespace nexpr = expr as Namespace; if (nexpr != null) {
string namespaced_partial; string namespaced_partial;
if (partial_name == null) if (partial_name == null)
namespaced_partial = nexpr.Name; namespaced_partial = nexpr.Namespace.Name;
else else
namespaced_partial = nexpr.Name + "." + partial_name; namespaced_partial = nexpr.Namespace.Name + "." + partial_name;
rc.CurrentMemberDefinition.GetCompletionStartingWith (namespaced_partial, results); rc.CurrentMemberDefinition.GetCompletionStartingWith (namespaced_partial, results);
if (partial_name != null) if (partial_name != null)

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

@ -1652,20 +1652,32 @@ namespace Mono.CSharp {
} }
public class FloatConstant : Constant { public class FloatConstant : Constant {
public readonly float Value; //
// Store constant value as double because float constant operations
// need to work on double value to match JIT
//
public readonly double DoubleValue;
public FloatConstant (BuiltinTypes types, float v, Location loc) public FloatConstant (BuiltinTypes types, double v, Location loc)
: this (types.Float, v, loc) : this (types.Float, v, loc)
{ {
} }
public FloatConstant (TypeSpec type, float v, Location loc) public FloatConstant (TypeSpec type, double v, Location loc)
: base (loc) : base (loc)
{ {
this.type = type; this.type = type;
eclass = ExprClass.Value; eclass = ExprClass.Value;
Value = v; DoubleValue = v;
}
public override Constant ConvertImplicitly (TypeSpec type)
{
if (type.BuiltinType == BuiltinTypeSpec.Type.Double)
return new DoubleConstant (type, DoubleValue, loc);
return base.ConvertImplicitly (type);
} }
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType) public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
@ -1678,6 +1690,12 @@ namespace Mono.CSharp {
ec.Emit (OpCodes.Ldc_R4, Value); ec.Emit (OpCodes.Ldc_R4, Value);
} }
public float Value {
get {
return (float) DoubleValue;
}
}
public override object GetValue () public override object GetValue ()
{ {
return Value; return Value;
@ -1713,59 +1731,59 @@ namespace Mono.CSharp {
if (Value < byte.MinValue || Value > byte.MaxValue || float.IsNaN (Value)) if (Value < byte.MinValue || Value > byte.MaxValue || float.IsNaN (Value))
throw new OverflowException (); throw new OverflowException ();
} }
return new ByteConstant (target_type, (byte) Value, Location); return new ByteConstant (target_type, (byte) DoubleValue, Location);
case BuiltinTypeSpec.Type.SByte: case BuiltinTypeSpec.Type.SByte:
if (in_checked_context) { if (in_checked_context) {
if (Value < sbyte.MinValue || Value > sbyte.MaxValue || float.IsNaN (Value)) if (Value < sbyte.MinValue || Value > sbyte.MaxValue || float.IsNaN (Value))
throw new OverflowException (); throw new OverflowException ();
} }
return new SByteConstant (target_type, (sbyte) Value, Location); return new SByteConstant (target_type, (sbyte) DoubleValue, Location);
case BuiltinTypeSpec.Type.Short: case BuiltinTypeSpec.Type.Short:
if (in_checked_context) { if (in_checked_context) {
if (Value < short.MinValue || Value > short.MaxValue || float.IsNaN (Value)) if (Value < short.MinValue || Value > short.MaxValue || float.IsNaN (Value))
throw new OverflowException (); throw new OverflowException ();
} }
return new ShortConstant (target_type, (short) Value, Location); return new ShortConstant (target_type, (short) DoubleValue, Location);
case BuiltinTypeSpec.Type.UShort: case BuiltinTypeSpec.Type.UShort:
if (in_checked_context) { if (in_checked_context) {
if (Value < ushort.MinValue || Value > ushort.MaxValue || float.IsNaN (Value)) if (Value < ushort.MinValue || Value > ushort.MaxValue || float.IsNaN (Value))
throw new OverflowException (); throw new OverflowException ();
} }
return new UShortConstant (target_type, (ushort) Value, Location); return new UShortConstant (target_type, (ushort) DoubleValue, Location);
case BuiltinTypeSpec.Type.Int: case BuiltinTypeSpec.Type.Int:
if (in_checked_context) { if (in_checked_context) {
if (Value < int.MinValue || Value > int.MaxValue || float.IsNaN (Value)) if (Value < int.MinValue || Value > int.MaxValue || float.IsNaN (Value))
throw new OverflowException (); throw new OverflowException ();
} }
return new IntConstant (target_type, (int) Value, Location); return new IntConstant (target_type, (int) DoubleValue, Location);
case BuiltinTypeSpec.Type.UInt: case BuiltinTypeSpec.Type.UInt:
if (in_checked_context) { if (in_checked_context) {
if (Value < uint.MinValue || Value > uint.MaxValue || float.IsNaN (Value)) if (Value < uint.MinValue || Value > uint.MaxValue || float.IsNaN (Value))
throw new OverflowException (); throw new OverflowException ();
} }
return new UIntConstant (target_type, (uint) Value, Location); return new UIntConstant (target_type, (uint) DoubleValue, Location);
case BuiltinTypeSpec.Type.Long: case BuiltinTypeSpec.Type.Long:
if (in_checked_context) { if (in_checked_context) {
if (Value < long.MinValue || Value > long.MaxValue || float.IsNaN (Value)) if (Value < long.MinValue || Value > long.MaxValue || float.IsNaN (Value))
throw new OverflowException (); throw new OverflowException ();
} }
return new LongConstant (target_type, (long) Value, Location); return new LongConstant (target_type, (long) DoubleValue, Location);
case BuiltinTypeSpec.Type.ULong: case BuiltinTypeSpec.Type.ULong:
if (in_checked_context) { if (in_checked_context) {
if (Value < ulong.MinValue || Value > ulong.MaxValue || float.IsNaN (Value)) if (Value < ulong.MinValue || Value > ulong.MaxValue || float.IsNaN (Value))
throw new OverflowException (); throw new OverflowException ();
} }
return new ULongConstant (target_type, (ulong) Value, Location); return new ULongConstant (target_type, (ulong) DoubleValue, Location);
case BuiltinTypeSpec.Type.Double: case BuiltinTypeSpec.Type.Double:
return new DoubleConstant (target_type, (double) Value, Location); return new DoubleConstant (target_type, DoubleValue, Location);
case BuiltinTypeSpec.Type.Char: case BuiltinTypeSpec.Type.Char:
if (in_checked_context) { if (in_checked_context) {
if (Value < (float) char.MinValue || Value > (float) char.MaxValue || float.IsNaN (Value)) if (Value < (float) char.MinValue || Value > (float) char.MaxValue || float.IsNaN (Value))
throw new OverflowException (); throw new OverflowException ();
} }
return new CharConstant (target_type, (char) Value, Location); return new CharConstant (target_type, (char) DoubleValue, Location);
case BuiltinTypeSpec.Type.Decimal: case BuiltinTypeSpec.Type.Decimal:
return new DecimalConstant (target_type, (decimal) Value, Location); return new DecimalConstant (target_type, (decimal) DoubleValue, Location);
} }
return null; return null;

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

@ -1235,7 +1235,7 @@ namespace Mono.CSharp {
// //
// User operator is of T? // User operator is of T?
// //
if (t_x.IsNullableType && target.IsNullableType) { if (t_x.IsNullableType && (target.IsNullableType || !implicitOnly)) {
// //
// User operator return type does not match target type we need // User operator return type does not match target type we need
// yet another conversion. This should happen for promoted numeric // yet another conversion. This should happen for promoted numeric
@ -1251,7 +1251,8 @@ namespace Mono.CSharp {
if (source == null) if (source == null)
return null; return null;
source = new Nullable.LiftedConversion (source, unwrap, target).Resolve (ec); if (target.IsNullableType)
source = new Nullable.LiftedConversion (source, unwrap, target).Resolve (ec);
} }
} else { } else {
source = implicitOnly ? source = implicitOnly ?
@ -1412,25 +1413,23 @@ namespace Mono.CSharp {
} }
} }
if (ec.IsUnsafe) { var target_pc = target_type as PointerContainer;
var target_pc = target_type as PointerContainer; if (target_pc != null) {
if (target_pc != null) { if (expr_type.IsPointer) {
if (expr_type.IsPointer) { //
// // Pointer types are same when they have same element types
// Pointer types are same when they have same element types //
// if (expr_type == target_pc)
if (expr_type == target_pc) return expr;
return expr;
if (target_pc.Element.Kind == MemberKind.Void) if (target_pc.Element.Kind == MemberKind.Void)
return EmptyCast.Create (expr, target_type); return EmptyCast.Create (expr, target_type);
//return null; //return null;
}
if (expr_type == InternalType.NullLiteral)
return new NullPointer (target_type, loc);
} }
if (expr_type == InternalType.NullLiteral)
return new NullPointer (target_type, loc);
} }
if (expr_type == InternalType.AnonymousMethod){ if (expr_type == InternalType.AnonymousMethod){

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

@ -4586,7 +4586,7 @@ void case_60()
void case_61() void case_61()
#line 748 "cs-parser.jay" #line 748 "cs-parser.jay"
{ {
CheckAttributeTarget (GetTokenName (yyToken), GetLocation (yyVals[0+yyTop])); CheckAttributeTarget (yyToken, GetTokenName (yyToken), GetLocation (yyVals[0+yyTop]));
yyVal = null; yyVal = null;
} }
@ -4594,7 +4594,7 @@ void case_62()
#line 756 "cs-parser.jay" #line 756 "cs-parser.jay"
{ {
var lt = (LocatedToken) yyVals[0+yyTop]; var lt = (LocatedToken) yyVals[0+yyTop];
yyVal = CheckAttributeTarget (lt.Value, lt.Location); yyVal = CheckAttributeTarget (yyToken, lt.Value, lt.Location);
PushLocation (GetLocation (yyVals[0+yyTop])); PushLocation (GetLocation (yyVals[0+yyTop]));
} }
@ -14499,15 +14499,20 @@ Location PopLocation ()
return location_stack.Pop (); return location_stack.Pop ();
} }
string CheckAttributeTarget (string a, Location l) string CheckAttributeTarget (int token, string a, Location l)
{ {
switch (a) { switch (a) {
case "assembly" : case "module" : case "field" : case "method" : case "param" : case "property" : case "type" : case "assembly" : case "module" : case "field" : case "method" : case "param" : case "property" : case "type" :
return a; return a;
} }
report.Warning (658, 1, l, if (!Tokenizer.IsValidIdentifier (a)) {
"`{0}' is invalid attribute target. All attributes in this attribute section will be ignored", a); Error_SyntaxError (token);
} else {
report.Warning (658, 1, l,
"`{0}' is invalid attribute target. All attributes in this attribute section will be ignored", a);
}
return string.Empty; return string.Empty;
} }

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

@ -746,7 +746,7 @@ attribute_section_cont
} }
| error | error
{ {
CheckAttributeTarget (GetTokenName (yyToken), GetLocation ($1)); CheckAttributeTarget (yyToken, GetTokenName (yyToken), GetLocation ($1));
$$ = null; $$ = null;
} }
; ;
@ -755,7 +755,7 @@ attribute_target
: IDENTIFIER : IDENTIFIER
{ {
var lt = (LocatedToken) $1; var lt = (LocatedToken) $1;
$$ = CheckAttributeTarget (lt.Value, lt.Location); $$ = CheckAttributeTarget (yyToken, lt.Value, lt.Location);
PushLocation (GetLocation ($1)); PushLocation (GetLocation ($1));
} }
| EVENT { $$ = "event"; PushLocation (GetLocation ($1)); } | EVENT { $$ = "event"; PushLocation (GetLocation ($1)); }
@ -7174,15 +7174,20 @@ Location PopLocation ()
return location_stack.Pop (); return location_stack.Pop ();
} }
string CheckAttributeTarget (string a, Location l) string CheckAttributeTarget (int token, string a, Location l)
{ {
switch (a) { switch (a) {
case "assembly" : case "module" : case "field" : case "method" : case "param" : case "property" : case "type" : case "assembly" : case "module" : case "field" : case "method" : case "param" : case "property" : case "type" :
return a; return a;
} }
report.Warning (658, 1, l, if (!Tokenizer.IsValidIdentifier (a)) {
"`{0}' is invalid attribute target. All attributes in this attribute section will be ignored", a); Error_SyntaxError (token);
} else {
report.Warning (658, 1, l,
"`{0}' is invalid attribute target. All attributes in this attribute section will be ignored", a);
}
return string.Empty; return string.Empty;
} }

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

@ -679,6 +679,9 @@ namespace Mono.CSharp {
} }
} }
if (type.IsNested)
return ContainsMethodTypeParameter (type.DeclaringType);
return false; return false;
} }

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

@ -297,7 +297,7 @@ namespace Mono.CSharp
return context.LookupNamespaceOrType (mn.Name, mn.Arity, LookupMode.Probing, Location.Null); return context.LookupNamespaceOrType (mn.Name, mn.Arity, LookupMode.Probing, Location.Null);
var left = ResolveMemberName (context, mn.Left); var left = ResolveMemberName (context, mn.Left);
var ns = left as Namespace; var ns = left as NamespaceExpression;
if (ns != null) if (ns != null)
return ns.LookupTypeOrNamespace (context, mn.Name, mn.Arity, LookupMode.Probing, Location.Null); return ns.LookupTypeOrNamespace (context, mn.Name, mn.Arity, LookupMode.Probing, Location.Null);
@ -383,7 +383,7 @@ namespace Mono.CSharp
} else if (ParsedName.Left != null) { } else if (ParsedName.Left != null) {
fne = ResolveMemberName (mc, ParsedName.Left); fne = ResolveMemberName (mc, ParsedName.Left);
if (fne != null) { if (fne != null) {
var ns = fne as Namespace; var ns = fne as NamespaceExpression;
if (ns != null) { if (ns != null) {
fne = ns.LookupTypeOrNamespace (mc, ParsedName.Name, ParsedName.Arity, LookupMode.Probing, Location.Null); fne = ns.LookupTypeOrNamespace (mc, ParsedName.Name, ParsedName.Arity, LookupMode.Probing, Location.Null);
if (fne != null) { if (fne != null) {

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

@ -466,7 +466,7 @@ namespace Mono.CSharp {
return e; return e;
} catch (Exception ex) { } catch (Exception ex) {
if (loc.IsNull || ec.Module.Compiler.Settings.DebugFlags > 0 || ex is CompletionResult || ec.Report.IsDisabled || ex is FatalException || if (loc.IsNull || ec.Module.Compiler.Settings.BreakOnInternalError || ex is CompletionResult || ec.Report.IsDisabled || ex is FatalException ||
ec.Report.Printer is NullReportPrinter) ec.Report.Printer is NullReportPrinter)
throw; throw;
@ -2313,11 +2313,11 @@ namespace Mono.CSharp {
protected override Expression DoResolve (ResolveContext rc) protected override Expression DoResolve (ResolveContext rc)
{ {
expr = expr.Resolve (rc); expr = expr.Resolve (rc);
if (expr != null) { if (expr == null)
type = expr.Type; return null;
eclass = expr.eclass;
}
type = expr.Type;
eclass = expr.eclass;
return this; return this;
} }
@ -2606,7 +2606,7 @@ namespace Mono.CSharp {
// //
// dynamic namespace is ignored when dynamic is allowed (does not apply to types) // dynamic namespace is ignored when dynamic is allowed (does not apply to types)
// //
if (!(fne is Namespace)) if (!(fne is NamespaceExpression))
return fne; return fne;
} }
@ -2989,6 +2989,114 @@ namespace Mono.CSharp {
} }
} }
public class NamespaceExpression : FullNamedExpression
{
readonly Namespace ns;
public NamespaceExpression (Namespace ns, Location loc)
{
this.ns = ns;
this.Type = InternalType.Namespace;
this.eclass = ExprClass.Namespace;
this.loc = loc;
}
public Namespace Namespace {
get {
return ns;
}
}
protected override Expression DoResolve (ResolveContext rc)
{
throw new NotImplementedException ();
}
public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc)
{
return this;
}
public void Error_NamespaceDoesNotExist (IMemberContext ctx, string name, int arity)
{
var retval = Namespace.LookupType (ctx, name, arity, LookupMode.IgnoreAccessibility, loc);
if (retval != null) {
// ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (retval.MemberDefinition);
ErrorIsInaccesible (ctx, retval.GetSignatureForError (), loc);
return;
}
retval = Namespace.LookupType (ctx, name, -System.Math.Max (1, arity), LookupMode.Probing, loc);
if (retval != null) {
Error_TypeArgumentsCannotBeUsed (ctx, retval, loc);
return;
}
Namespace ns;
if (arity > 0 && Namespace.TryGetNamespace (name, out ns)) {
Error_TypeArgumentsCannotBeUsed (ctx, ExprClassName, ns.GetSignatureForError (), loc);
return;
}
string assembly = null;
string possible_name = Namespace.GetSignatureForError () + "." + name;
// Only assembly unique name should be added
switch (possible_name) {
case "System.Drawing":
case "System.Web.Services":
case "System.Web":
case "System.Data":
case "System.Configuration":
case "System.Data.Services":
case "System.DirectoryServices":
case "System.Json":
case "System.Net.Http":
case "System.Numerics":
case "System.Runtime.Caching":
case "System.ServiceModel":
case "System.Transactions":
case "System.Web.Routing":
case "System.Xml.Linq":
case "System.Xml":
assembly = possible_name;
break;
case "System.Linq":
case "System.Linq.Expressions":
assembly = "System.Core";
break;
case "System.Windows.Forms":
case "System.Windows.Forms.Layout":
assembly = "System.Windows.Forms";
break;
}
assembly = assembly == null ? "an" : "`" + assembly + "'";
if (Namespace is GlobalRootNamespace) {
ctx.Module.Compiler.Report.Error (400, loc,
"The type or namespace name `{0}' could not be found in the global namespace. Are you missing {1} assembly reference?",
name, assembly);
} else {
ctx.Module.Compiler.Report.Error (234, loc,
"The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing {2} assembly reference?",
name, GetSignatureForError (), assembly);
}
}
public override string GetSignatureForError ()
{
return ns.GetSignatureForError ();
}
public FullNamedExpression LookupTypeOrNamespace (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
{
return ns.LookupTypeOrNamespace (ctx, name, arity, mode, loc);
}
}
/// <summary> /// <summary>
/// This class denotes an expression which evaluates to a member /// This class denotes an expression which evaluates to a member
/// of a struct or a class. /// of a struct or a class.
@ -4274,7 +4382,7 @@ namespace Mono.CSharp {
AParametersCollection best_pd = ((IParametersMember) best).Parameters; AParametersCollection best_pd = ((IParametersMember) best).Parameters;
bool better_at_least_one = false; bool better_at_least_one = false;
bool same = true; bool are_equivalent = true;
int args_count = args == null ? 0 : args.Count; int args_count = args == null ? 0 : args.Count;
int j = 0; int j = 0;
Argument a = null; Argument a = null;
@ -4319,7 +4427,7 @@ namespace Mono.CSharp {
if (TypeSpecComparer.IsEqual (ct, bt)) if (TypeSpecComparer.IsEqual (ct, bt))
continue; continue;
same = false; are_equivalent = false;
int result = BetterExpressionConversion (ec, a, ct, bt); int result = BetterExpressionConversion (ec, a, ct, bt);
// for each argument, the conversion to 'ct' should be no worse than // for each argument, the conversion to 'ct' should be no worse than
@ -4337,68 +4445,56 @@ namespace Mono.CSharp {
return true; return true;
// //
// This handles the case // Tie-breaking rules are applied only for equivalent parameter types
//
// Add (float f1, float f2, float f3);
// Add (params decimal [] foo);
// //
// The call Add (3, 4, 5) should be ambiguous. Without this check, the if (!are_equivalent)
// first candidate would've chosen as better.
//
if (!same && !a.IsDefaultArgument)
return false; return false;
// //
// The two methods have equal non-optional parameter types, apply tie-breaking rules // If candidate is applicable in its normal form and best has a params array and is applicable
// only in its expanded form, then candidate is better
// //
if (candidate_params != best_params)
return !candidate_params;
// //
// This handles the following cases: // We have not reached end of parameters list due to params or used default parameters
//
// Foo (int i) is better than Foo (int i, long l = 0)
// Foo (params int[] args) is better than Foo (int i = 0, params int[] args)
// Foo (string s, params string[] args) is better than Foo (params string[] args)
//
// Prefer non-optional version
//
// LAMESPEC: Specification claims this should be done at last but the opposite is true
// //
if (candidate_params == best_params && candidate_pd.Count != best_pd.Count) { if (j < candidate_pd.Count && j < best_pd.Count) {
if (j < candidate_pd.Count && candidate_pd.FixedParameters[j].HasDefaultValue) var cand_param = candidate_pd.FixedParameters [j];
return false; var best_param = best_pd.FixedParameters [j];
if (j < best_pd.Count && best_pd.FixedParameters[j].HasDefaultValue)
return true;
return candidate_pd.Count >= best_pd.Count; if (candidate_pd.Count == best_pd.Count) {
//
// LAMESPEC:
//
// void Foo (params int[]) is better than void Foo (int i = 0) for Foo ()
// void Foo (string[] s, string value = null) is better than Foo (string s, params string[]) for Foo (null)
//
if (cand_param.HasDefaultValue != best_param.HasDefaultValue)
return !candidate_params;
} else {
//
// Neither is better when not all arguments are provided
//
// void Foo (string s, int i = 0) <-> Foo (string s, int i = 0, int i2 = 0)
// void Foo (string s, int i = 0) <-> Foo (string s, byte i = 0)
// void Foo (string s, params int[]) <-> Foo (string s, params byte[])
//
if (cand_param.HasDefaultValue && best_param.HasDefaultValue)
return false;
}
} }
if (candidate_pd.Count != best_pd.Count)
return candidate_pd.Count < best_pd.Count;
// //
// One is a non-generic method and second is a generic method, then non-generic is better // One is a non-generic method and second is a generic method, then non-generic is better
// //
if (best.IsGeneric != candidate.IsGeneric) if (best.IsGeneric != candidate.IsGeneric)
return best.IsGeneric; return best.IsGeneric;
//
// This handles the following cases:
//
// Trim () is better than Trim (params char[] chars)
// Concat (string s1, string s2, string s3) is better than
// Concat (string s1, params string [] srest)
// Foo (int, params int [] rest) is better than Foo (params int [] rest)
//
// Prefer non-expanded version
//
if (candidate_params != best_params)
return best_params;
int candidate_param_count = candidate_pd.Count;
int best_param_count = best_pd.Count;
if (candidate_param_count != best_param_count)
// can only happen if (candidate_params && best_params)
return candidate_param_count > best_param_count && best_pd.HasParams;
// //
// Both methods have the same number of parameters, and the parameters have equal types // Both methods have the same number of parameters, and the parameters have equal types
// Pick the "more specific" signature using rules over original (non-inflated) types // Pick the "more specific" signature using rules over original (non-inflated) types
@ -4626,7 +4722,8 @@ namespace Mono.CSharp {
if (g_args_count != type_arguments.Count) if (g_args_count != type_arguments.Count)
return int.MaxValue - 20000 + System.Math.Abs (type_arguments.Count - g_args_count); return int.MaxValue - 20000 + System.Math.Abs (type_arguments.Count - g_args_count);
ms = ms.MakeGenericMethod (ec, type_arguments.Arguments); if (type_arguments.Arguments != null)
ms = ms.MakeGenericMethod (ec, type_arguments.Arguments);
} else { } else {
// //
// Deploy custom error reporting for infered anonymous expression or lambda methods. When // Deploy custom error reporting for infered anonymous expression or lambda methods. When
@ -4808,12 +4905,6 @@ namespace Mono.CSharp {
} }
} }
//
// When params parameter has no argument it will be provided later if the method is the best candidate
//
if (arg_count + 1 == pd.Count && (cpd.FixedParameters [arg_count].ModFlags & Parameter.Modifier.PARAMS) != 0)
params_expanded_form = true;
// //
// Restore original arguments for dynamic binder to keep the intention of original source code // Restore original arguments for dynamic binder to keep the intention of original source code
// //
@ -5819,48 +5910,39 @@ namespace Mono.CSharp {
} }
var fe = InstanceExpression as FieldExpr; var fe = InstanceExpression as FieldExpr;
if (fe != null || lvalue_instance) { if (fe != null) {
if (fe == null) Expression instance;
return;
/* do {
while (fe.InstanceExpression is FieldExpr) { instance = fe.InstanceExpression;
fe = (FieldExpr) fe.InstanceExpression; var fe_instance = instance as FieldExpr;
if (!fe.Spec.DeclaringType.IsStruct) if ((fe_instance != null && !fe_instance.IsStatic) || instance is LocalVariableReference) {
continue; if (TypeSpec.IsReferenceType (fe.Type) && instance.Type.IsStruct) {
var var = InstanceExpression as IVariableReference;
if (var != null && var.VariableInfo == null) {
var var_inst = instance as IVariableReference;
if (var_inst == null || (var_inst.VariableInfo != null && !fc.IsDefinitelyAssigned (var_inst.VariableInfo)))
fc.Report.Warning (1060, 1, fe.loc, "Use of possibly unassigned field `{0}'", fe.Name);
}
}
if (fe.VariableInfo != null && fc.IsStructFieldDefinitelyAssigned (fe.VariableInfo, fe.Name)) { if (fe_instance != null) {
fc.Report.Warning (1060, 1, fe.loc, "Use of possibly unassigned field `{0}'", fe.Name); fe = fe_instance;
continue;
}
} }
}
fe.InstanceExpression.FlowAnalysis (fc); break;
*/ } while (true);
if (instance != null && TypeSpec.IsReferenceType (instance.Type))
instance.FlowAnalysis (fc);
} else { } else {
InstanceExpression.FlowAnalysis (fc); if (TypeSpec.IsReferenceType (InstanceExpression.Type))
InstanceExpression.FlowAnalysis (fc);
} }
} }
public void VerifyAssignedStructField (FlowAnalysisContext fc)
{
var fe = this;
do {
var var = fe.InstanceExpression as IVariableReference;
if (var != null) {
var vi = var.VariableInfo;
if (vi != null && !fc.IsStructFieldDefinitelyAssigned (vi, fe.Name) && !fe.type.IsStruct) {
fc.Report.Warning (1060, 1, fe.loc, "Use of possibly unassigned field `{0}'", fe.Name);
}
}
fe = fe.InstanceExpression as FieldExpr;
} while (fe != null);
}
Expression Error_AssignToReadonly (ResolveContext rc, Expression right_side) Expression Error_AssignToReadonly (ResolveContext rc, Expression right_side)
{ {
// The return value is always null. Returning a value simplifies calling code. // The return value is always null. Returning a value simplifies calling code.

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

@ -5031,7 +5031,7 @@ namespace Mono.CSharp
AParametersCollection pd = oper.Parameters; AParametersCollection pd = oper.Parameters;
if (!TypeSpecComparer.IsEqual (type, pd.Types[0]) || !TypeSpecComparer.IsEqual (type, pd.Types[1])) { if (!TypeSpecComparer.IsEqual (type, pd.Types[0]) || !TypeSpecComparer.IsEqual (type, pd.Types[1])) {
ec.Report.Error (217, loc, ec.Report.Error (217, loc,
"A user-defined operator `{0}' must have parameters and return values of the same type in order to be applicable as a short circuit operator", "A user-defined operator `{0}' must have each parameter type and return type of the same type in order to be applicable as a short circuit operator",
oper.GetSignatureForError ()); oper.GetSignatureForError ());
return null; return null;
} }
@ -7495,7 +7495,7 @@ namespace Mono.CSharp
// //
// This always expect the top value on the stack to be the array // This always expect the top value on the stack to be the array
// //
void EmitDynamicInitializers (EmitContext ec, bool emitConstants, FieldExpr stackArray) void EmitDynamicInitializers (EmitContext ec, bool emitConstants, StackFieldExpr stackArray)
{ {
int dims = bounds.Count; int dims = bounds.Count;
var current_pos = new int [dims]; var current_pos = new int [dims];
@ -7515,7 +7515,7 @@ namespace Mono.CSharp
e = e.EmitToField (ec); e = e.EmitToField (ec);
} }
stackArray.Emit (ec); stackArray.EmitLoad (ec);
} else { } else {
ec.Emit (OpCodes.Dup); ec.Emit (OpCodes.Dup);
} }
@ -7527,26 +7527,8 @@ namespace Mono.CSharp
// If we are dealing with a struct, get the // If we are dealing with a struct, get the
// address of it, so we can store it. // address of it, so we can store it.
// //
if (dims == 1 && etype.IsStruct) { if (dims == 1 && etype.IsStruct && !BuiltinTypeSpec.IsPrimitiveType (etype))
switch (etype.BuiltinType) { ec.Emit (OpCodes.Ldelema, etype);
case BuiltinTypeSpec.Type.Byte:
case BuiltinTypeSpec.Type.SByte:
case BuiltinTypeSpec.Type.Bool:
case BuiltinTypeSpec.Type.Short:
case BuiltinTypeSpec.Type.UShort:
case BuiltinTypeSpec.Type.Char:
case BuiltinTypeSpec.Type.Int:
case BuiltinTypeSpec.Type.UInt:
case BuiltinTypeSpec.Type.Long:
case BuiltinTypeSpec.Type.ULong:
case BuiltinTypeSpec.Type.Float:
case BuiltinTypeSpec.Type.Double:
break;
default:
ec.Emit (OpCodes.Ldelema, etype);
break;
}
}
e.Emit (ec); e.Emit (ec);
@ -7563,6 +7545,9 @@ namespace Mono.CSharp
current_pos [j] = 0; current_pos [j] = 0;
} }
} }
if (stackArray != null)
stackArray.PrepareCleanup (ec);
} }
public override void Emit (EmitContext ec) public override void Emit (EmitContext ec)
@ -7577,7 +7562,7 @@ namespace Mono.CSharp
first_emit_temp.Store (ec); first_emit_temp.Store (ec);
} }
FieldExpr await_stack_field; StackFieldExpr await_stack_field;
if (ec.HasSet (BuilderContext.Options.AsyncBody) && InitializersContainAwait ()) { if (ec.HasSet (BuilderContext.Options.AsyncBody) && InitializersContainAwait ()) {
await_stack_field = ec.GetTemporaryField (type); await_stack_field = ec.GetTemporaryField (type);
ec.EmitThis (); ec.EmitThis ();
@ -8669,7 +8654,7 @@ namespace Mono.CSharp
public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec) public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
{ {
if (alias == GlobalAlias) { if (alias == GlobalAlias) {
expr = ec.Module.GlobalRootNamespace; expr = new NamespaceExpression (ec.Module.GlobalRootNamespace, loc);
return base.ResolveAsTypeOrNamespace (ec); return base.ResolveAsTypeOrNamespace (ec);
} }
@ -8832,12 +8817,12 @@ namespace Mono.CSharp
if (expr == null) if (expr == null)
return null; return null;
Namespace ns = expr as Namespace; var ns = expr as NamespaceExpression;
if (ns != null) { if (ns != null) {
var retval = ns.LookupTypeOrNamespace (rc, Name, Arity, LookupMode.Normal, loc); var retval = ns.LookupTypeOrNamespace (rc, Name, Arity, LookupMode.Normal, loc);
if (retval == null) { if (retval == null) {
ns.Error_NamespaceDoesNotExist (rc, Name, Arity, loc); ns.Error_NamespaceDoesNotExist (rc, Name, Arity);
return null; return null;
} }
@ -8972,12 +8957,12 @@ namespace Mono.CSharp
if (expr_resolved == null) if (expr_resolved == null)
return null; return null;
Namespace ns = expr_resolved as Namespace; var ns = expr_resolved as NamespaceExpression;
if (ns != null) { if (ns != null) {
FullNamedExpression retval = ns.LookupTypeOrNamespace (rc, Name, Arity, LookupMode.Normal, loc); FullNamedExpression retval = ns.LookupTypeOrNamespace (rc, Name, Arity, LookupMode.Normal, loc);
if (retval == null) { if (retval == null) {
ns.Error_NamespaceDoesNotExist (rc, Name, Arity, loc); ns.Error_NamespaceDoesNotExist (rc, Name, Arity);
} else if (HasTypeArguments) { } else if (HasTypeArguments) {
retval = new GenericTypeExpr (retval.Type, targs, loc); retval = new GenericTypeExpr (retval.Type, targs, loc);
if (retval.ResolveAsType (rc) == null) if (retval.ResolveAsType (rc) == null)

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

@ -190,6 +190,12 @@ namespace Mono.CSharp
try { try {
field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi)); field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
//
// Private field has private type which is not fixed buffer
//
if (field_type == null)
return null;
} catch (Exception e) { } catch (Exception e) {
// TODO: I should construct fake TypeSpec based on TypeRef signature // TODO: I should construct fake TypeSpec based on TypeRef signature
// but there is no way to do it with System.Reflection // but there is no way to do it with System.Reflection
@ -340,6 +346,9 @@ namespace Mono.CSharp
} }
} }
if (spec == null)
return null;
++dtype.Position; ++dtype.Position;
tspec[index] = spec; tspec[index] = spec;
} }
@ -376,7 +385,7 @@ namespace Mono.CSharp
kind = MemberKind.Method; kind = MemberKind.Method;
if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) { if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) { if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') { if (name[2] == '_' && name[1] == 'p' && name[0] == 'o' && (mb.Attributes & MethodAttributes.SpecialName) != 0) {
var op_type = Operator.GetType (name); var op_type = Operator.GetType (name);
if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) { if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
kind = MemberKind.Operator; kind = MemberKind.Operator;
@ -756,6 +765,8 @@ namespace Mono.CSharp
return spec; return spec;
var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype); var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
if (targs == null)
return null;
if (declaringType == null) { if (declaringType == null) {
// Simple case, no nesting // Simple case, no nesting
spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType); spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);

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

@ -46,7 +46,7 @@ namespace Mono.CSharp
PROPERTY_CUSTOM = 0x10000, PROPERTY_CUSTOM = 0x10000,
PARTIAL = 0x20000, PARTIAL = 0x20000,
DEFAULT_ACCESS_MODIFER = 0x40000, DEFAULT_ACCESS_MODIFIER = 0x40000,
METHOD_EXTENSION = 0x80000, METHOD_EXTENSION = 0x80000,
COMPILER_GENERATED = 0x100000, COMPILER_GENERATED = 0x100000,
BACKING_FIELD = 0x200000, BACKING_FIELD = 0x200000,
@ -256,7 +256,7 @@ namespace Mono.CSharp
if ((mod & Modifiers.AccessibilityMask) == 0) { if ((mod & Modifiers.AccessibilityMask) == 0) {
mod |= def_access; mod |= def_access;
if (def_access != 0) if (def_access != 0)
mod |= Modifiers.DEFAULT_ACCESS_MODIFER; mod |= Modifiers.DEFAULT_ACCESS_MODIFIER;
return mod; return mod;
} }

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

@ -22,9 +22,10 @@ namespace Mono.CSharp {
readonly Dictionary<string, Namespace> all_namespaces; readonly Dictionary<string, Namespace> all_namespaces;
public RootNamespace (string alias_name) public RootNamespace (string alias_name)
: base (null, String.Empty) : base ()
{ {
this.alias_name = alias_name; this.alias_name = alias_name;
RegisterNamespace (this);
all_namespaces = new Dictionary<string, Namespace> (); all_namespaces = new Dictionary<string, Namespace> ();
all_namespaces.Add ("", this); all_namespaces.Add ("", this);
@ -87,24 +88,13 @@ namespace Mono.CSharp {
all_namespaces.Add (child.Name, child); all_namespaces.Add (child.Name, child);
} }
public bool IsNamespace (string name)
{
return all_namespaces.ContainsKey (name);
}
protected void RegisterNamespace (string dotted_name)
{
if (dotted_name != null && dotted_name.Length != 0 && ! IsNamespace (dotted_name))
GetNamespace (dotted_name, true);
}
public override string GetSignatureForError () public override string GetSignatureForError ()
{ {
return alias_name + "::"; return alias_name + "::";
} }
} }
public class GlobalRootNamespace : RootNamespace public sealed class GlobalRootNamespace : RootNamespace
{ {
public GlobalRootNamespace () public GlobalRootNamespace ()
: base ("global") : base ("global")
@ -115,65 +105,50 @@ namespace Mono.CSharp {
// //
// Namespace cache for imported and compiled namespaces // Namespace cache for imported and compiled namespaces
// //
// This is an Expression to allow it to be referenced in the public class Namespace
// compiler parse/intermediate tree during name resolution.
//
public class Namespace : FullNamedExpression
{ {
Namespace parent; readonly Namespace parent;
string fullname; string fullname;
protected Dictionary<string, Namespace> namespaces; protected Dictionary<string, Namespace> namespaces;
protected Dictionary<string, IList<TypeSpec>> types; protected Dictionary<string, IList<TypeSpec>> types;
List<TypeSpec> extension_method_types; List<TypeSpec> extension_method_types;
Dictionary<string, TypeSpec> cached_types; Dictionary<string, TypeSpec> cached_types;
RootNamespace root;
bool cls_checked; bool cls_checked;
public readonly MemberName MemberName;
/// <summary> /// <summary>
/// Constructor Takes the current namespace and the /// Constructor Takes the current namespace and the
/// name. This is bootstrapped with parent == null /// name. This is bootstrapped with parent == null
/// and name = "" /// and name = ""
/// </summary> /// </summary>
public Namespace (Namespace parent, string name) public Namespace (Namespace parent, string name)
: this ()
{ {
// Expression members. if (name == null)
this.eclass = ExprClass.Namespace; throw new ArgumentNullException ("name");
this.Type = InternalType.Namespace;
this.loc = Location.Null;
this.parent = parent; this.parent = parent;
if (parent != null) string pname = parent != null ? parent.fullname : null;
this.root = parent.root;
else
this.root = this as RootNamespace;
if (this.root == null)
throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
string pname = parent != null ? parent.fullname : "";
if (pname == "") if (pname == null)
fullname = name; fullname = name;
else else
fullname = parent.fullname + "." + name; fullname = pname + "." + name;
if (fullname == null) while (parent.parent != null)
throw new InternalErrorException ("Namespace has a null fullname"); parent = parent.parent;
if (parent != null && parent.MemberName != MemberName.Null) var root = parent as RootNamespace;
MemberName = new MemberName (parent.MemberName, name, Location.Null); if (root == null)
else if (name.Length == 0) throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
MemberName = MemberName.Null;
else root.RegisterNamespace (this);
MemberName = new MemberName (name, Location.Null); }
protected Namespace ()
{
namespaces = new Dictionary<string, Namespace> (); namespaces = new Dictionary<string, Namespace> ();
cached_types = new Dictionary<string, TypeSpec> (); cached_types = new Dictionary<string, TypeSpec> ();
root.RegisterNamespace (this);
} }
#region Properties #region Properties
@ -195,85 +170,6 @@ namespace Mono.CSharp {
#endregion #endregion
protected override Expression DoResolve (ResolveContext ec)
{
return this;
}
public void Error_NamespaceDoesNotExist (IMemberContext ctx, string name, int arity, Location loc)
{
var retval = LookupType (ctx, name, arity, LookupMode.IgnoreAccessibility, loc);
if (retval != null) {
// ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (retval.MemberDefinition);
ErrorIsInaccesible (ctx, retval.GetSignatureForError (), loc);
return;
}
retval = LookupType (ctx, name, -System.Math.Max (1, arity), LookupMode.Probing, loc);
if (retval != null) {
Error_TypeArgumentsCannotBeUsed (ctx, retval, loc);
return;
}
Namespace ns;
if (arity > 0 && namespaces.TryGetValue (name, out ns)) {
ns.Error_TypeArgumentsCannotBeUsed (ctx, null, loc);
return;
}
string assembly = null;
string possible_name = fullname + "." + name;
// Only assembly unique name should be added
switch (possible_name) {
case "System.Drawing":
case "System.Web.Services":
case "System.Web":
case "System.Data":
case "System.Configuration":
case "System.Data.Services":
case "System.DirectoryServices":
case "System.Json":
case "System.Net.Http":
case "System.Numerics":
case "System.Runtime.Caching":
case "System.ServiceModel":
case "System.Transactions":
case "System.Web.Routing":
case "System.Xml.Linq":
case "System.Xml":
assembly = possible_name;
break;
case "System.Linq":
case "System.Linq.Expressions":
assembly = "System.Core";
break;
case "System.Windows.Forms":
case "System.Windows.Forms.Layout":
assembly = "System.Windows.Forms";
break;
}
assembly = assembly == null ? "an" : "`" + assembly + "'";
if (this is GlobalRootNamespace) {
ctx.Module.Compiler.Report.Error (400, loc,
"The type or namespace name `{0}' could not be found in the global namespace. Are you missing {1} assembly reference?",
name, assembly);
} else {
ctx.Module.Compiler.Report.Error (234, loc,
"The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing {2} assembly reference?",
name, GetSignatureForError (), assembly);
}
}
public override string GetSignatureForError ()
{
return fullname;
}
public Namespace AddNamespace (MemberName name) public Namespace AddNamespace (MemberName name)
{ {
var ns_parent = name.Left == null ? this : AddNamespace (name.Left); var ns_parent = name.Left == null ? this : AddNamespace (name.Left);
@ -292,6 +188,11 @@ namespace Mono.CSharp {
return ns; return ns;
} }
public bool TryGetNamespace (string name, out Namespace ns)
{
return namespaces.TryGetValue (name, out ns);
}
// TODO: Replace with CreateNamespace where MemberName is created for the method call // TODO: Replace with CreateNamespace where MemberName is created for the method call
public Namespace GetNamespace (string name, bool create) public Namespace GetNamespace (string name, bool create)
{ {
@ -327,6 +228,11 @@ namespace Mono.CSharp {
return found; return found;
} }
public virtual string GetSignatureForError ()
{
return fullname;
}
public TypeSpec LookupType (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc) public TypeSpec LookupType (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
{ {
if (types == null) if (types == null)
@ -415,7 +321,7 @@ namespace Mono.CSharp {
Namespace ns; Namespace ns;
if (arity == 0 && namespaces.TryGetValue (name, out ns)) { if (arity == 0 && namespaces.TryGetValue (name, out ns)) {
if (texpr == null) if (texpr == null)
return ns; return new NamespaceExpression (ns, loc);
if (mode != LookupMode.Probing) { if (mode != LookupMode.Probing) {
//ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (texpr.Type); //ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (texpr.Type);
@ -426,7 +332,7 @@ namespace Mono.CSharp {
} }
if (texpr.MemberDefinition.IsImported) if (texpr.MemberDefinition.IsImported)
return ns; return new NamespaceExpression (ns, loc);
} }
if (texpr == null) if (texpr == null)
@ -580,11 +486,6 @@ namespace Mono.CSharp {
cached_types.Remove (tc.Basename); cached_types.Remove (tc.Basename);
} }
public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc)
{
return this;
}
public void SetBuiltinType (BuiltinTypeSpec pts) public void SetBuiltinType (BuiltinTypeSpec pts)
{ {
var found = types[pts.Name]; var found = types[pts.Name];
@ -651,11 +552,6 @@ namespace Mono.CSharp {
"Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ()); "Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ());
} }
} }
public override string ToString ()
{
return Name;
}
} }
public class CompilationSourceFile : NamespaceContainer public class CompilationSourceFile : NamespaceContainer
@ -1279,18 +1175,18 @@ namespace Mono.CSharp {
continue; continue;
} }
Namespace using_ns = entry.ResolvedExpression as Namespace; var using_ns = entry.ResolvedExpression as NamespaceExpression;
if (using_ns == null) if (using_ns == null)
continue; continue;
if (list.Contains (using_ns)) { if (list.Contains (using_ns.Namespace)) {
// Ensure we don't report the warning multiple times in repl // Ensure we don't report the warning multiple times in repl
clauses.RemoveAt (i--); clauses.RemoveAt (i--);
Compiler.Report.Warning (105, 3, entry.Location, Compiler.Report.Warning (105, 3, entry.Location,
"The using directive for `{0}' appeared previously in this namespace", using_ns.GetSignatureForError ()); "The using directive for `{0}' appeared previously in this namespace", using_ns.GetSignatureForError ());
} else { } else {
list.Add (using_ns); list.Add (using_ns.Namespace);
} }
} }
@ -1405,7 +1301,7 @@ namespace Mono.CSharp {
public virtual void Define (NamespaceContainer ctx) public virtual void Define (NamespaceContainer ctx)
{ {
resolved = expr.ResolveAsTypeOrNamespace (ctx); resolved = expr.ResolveAsTypeOrNamespace (ctx);
var ns = resolved as Namespace; var ns = resolved as NamespaceExpression;
if (ns == null) { if (ns == null) {
if (resolved != null) { if (resolved != null) {
ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (resolved.Type); ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (resolved.Type);
@ -1436,12 +1332,15 @@ namespace Mono.CSharp {
public override void Define (NamespaceContainer ctx) public override void Define (NamespaceContainer ctx)
{ {
resolved = ctx.Module.GetRootNamespace (Alias.Value); var ns = ctx.Module.GetRootNamespace (Alias.Value);
if (resolved == null) { if (ns == null) {
ctx.Module.Compiler.Report.Error (430, Location, ctx.Module.Compiler.Report.Error (430, Location,
"The extern alias `{0}' was not specified in -reference option", "The extern alias `{0}' was not specified in -reference option",
Alias.Value); Alias.Value);
return;
} }
resolved = new NamespaceExpression (ns, Location);
} }
public override void Accept (StructuralVisitor visitor) public override void Accept (StructuralVisitor visitor)

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

@ -659,10 +659,10 @@ namespace Mono.CSharp.Nullable
{ {
if (rc.IsRuntimeBinder) { if (rc.IsRuntimeBinder) {
if (UnwrapLeft == null && !Left.Type.IsNullableType) if (UnwrapLeft == null && !Left.Type.IsNullableType)
Left = Wrap.Create (Left, rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { Left.Type })); Left = LiftOperand (rc, Left);
if (UnwrapRight == null && !Right.Type.IsNullableType) if (UnwrapRight == null && !Right.Type.IsNullableType)
Right = Wrap.Create (Right, rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { Right.Type })); Right = LiftOperand (rc, Right);
} else { } else {
if (UnwrapLeft == null && Left != null && Left.Type.IsNullableType) { if (UnwrapLeft == null && Left != null && Left.Type.IsNullableType) {
Left = Unwrap.CreateUnwrapped (Left); Left = Unwrap.CreateUnwrapped (Left);
@ -681,6 +681,21 @@ namespace Mono.CSharp.Nullable
return this; return this;
} }
Expression LiftOperand (ResolveContext rc, Expression expr)
{
TypeSpec type;
if (expr.IsNull) {
type = Left.IsNull ? Right.Type : Left.Type;
} else {
type = expr.Type;
}
if (!type.IsNullableType)
type = rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { type });
return Wrap.Create (expr, type);
}
public override void Emit (EmitContext ec) public override void Emit (EmitContext ec)
{ {
if (IsBitwiseBoolean && UserOperator == null) { if (IsBitwiseBoolean && UserOperator == null) {
@ -762,6 +777,9 @@ namespace Mono.CSharp.Nullable
if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) { if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
Left = Left.EmitToField (ec); Left = Left.EmitToField (ec);
Right = Right.EmitToField (ec); Right = Right.EmitToField (ec);
} else {
UnwrapLeft.Store (ec);
UnwrapRight.Store (ec);
} }
Left.Emit (ec); Left.Emit (ec);

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

@ -635,7 +635,7 @@ namespace Mono.CSharp {
if (OptAttributes != null) if (OptAttributes != null)
OptAttributes.Emit (); OptAttributes.Emit ();
if (HasDefaultValue) { if (HasDefaultValue && default_expr.Type != null) {
// //
// Emit constant values for true constants only, the other // Emit constant values for true constants only, the other
// constant-like expressions will rely on default value expression // constant-like expressions will rely on default value expression
@ -1336,8 +1336,10 @@ namespace Mono.CSharp {
public void Resolve (ResolveContext rc, Parameter p) public void Resolve (ResolveContext rc, Parameter p)
{ {
var expr = Resolve (rc); var expr = Resolve (rc);
if (expr == null) if (expr == null) {
this.expr = ErrorExpression.Instance;
return; return;
}
expr = Child; expr = Child;

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

@ -1109,8 +1109,8 @@ namespace Mono.CSharp
return false; return false;
if (declarators != null) { if (declarators != null) {
if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0)
mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFER); mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFIER);
var t = new TypeExpression (MemberType, TypeExpression.Location); var t = new TypeExpression (MemberType, TypeExpression.Location);
foreach (var d in declarators) { foreach (var d in declarators) {

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

@ -146,6 +146,7 @@ namespace Mono.CSharp {
public int VerboseParserFlag; public int VerboseParserFlag;
public int FatalCounter; public int FatalCounter;
public bool Stacktrace; public bool Stacktrace;
public bool BreakOnInternalError;
#endregion #endregion
public bool ShowFullPaths; public bool ShowFullPaths;
@ -159,6 +160,8 @@ namespace Mono.CSharp {
public RuntimeVersion StdLibRuntimeVersion; public RuntimeVersion StdLibRuntimeVersion;
public string RuntimeMetadataVersion;
public bool WriteMetadataOnly; public bool WriteMetadataOnly;
readonly List<string> conditional_symbols; readonly List<string> conditional_symbols;
@ -669,7 +672,8 @@ namespace Mono.CSharp {
" --stacktrace Shows stack trace at error location\n" + " --stacktrace Shows stack trace at error location\n" +
" --timestamp Displays time stamps of various compiler events\n" + " --timestamp Displays time stamps of various compiler events\n" +
" -v Verbose parsing (for debugging the parser)\n" + " -v Verbose parsing (for debugging the parser)\n" +
" --mcs-debug X Sets MCS debugging level to X\n"); " --mcs-debug X Sets MCS debugging level to X\n" +
" --break-on-ice Breaks compilation on internal compiler error");
} }
// //
@ -1180,6 +1184,15 @@ namespace Mono.CSharp {
} }
return ParseResult.Success; return ParseResult.Success;
case "runtimemetadataversion":
if (value.Length == 0) {
Error_RequiresArgument (option);
return ParseResult.Error;
}
settings.RuntimeMetadataVersion = value;
return ParseResult.Success;
default: default:
return ParseResult.UnknownOption; return ParseResult.UnknownOption;
} }
@ -1421,6 +1434,10 @@ namespace Mono.CSharp {
settings.WriteMetadataOnly = true; settings.WriteMetadataOnly = true;
return ParseResult.Success; return ParseResult.Success;
case "--break-on-ice":
settings.BreakOnInternalError = true;
return ParseResult.Success;
default: default:
if (arg.StartsWith ("--fatal", StringComparison.Ordinal)){ if (arg.StartsWith ("--fatal", StringComparison.Ordinal)){
int fatal = 1; int fatal = 1;

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

@ -2817,12 +2817,7 @@ namespace Mono.CSharp {
if (rc.IsUnreachable) if (rc.IsUnreachable)
return rc; return rc;
base.MarkReachable (rc); MarkReachableScope (rc);
if (scope_initializers != null) {
foreach (var si in scope_initializers)
si.MarkReachable (rc);
}
foreach (var s in statements) { foreach (var s in statements) {
rc = s.MarkReachable (rc); rc = s.MarkReachable (rc);
@ -2839,6 +2834,16 @@ namespace Mono.CSharp {
return rc; return rc;
} }
public void MarkReachableScope (Reachability rc)
{
base.MarkReachable (rc);
if (scope_initializers != null) {
foreach (var si in scope_initializers)
si.MarkReachable (rc);
}
}
public override bool Resolve (BlockContext bc) public override bool Resolve (BlockContext bc)
{ {
if ((flags & Flags.Resolved) != 0) if ((flags & Flags.Resolved) != 0)
@ -3798,7 +3803,7 @@ namespace Mono.CSharp {
return false; return false;
} catch (Exception e) { } catch (Exception e) {
if (e is CompletionResult || bc.Report.IsDisabled || e is FatalException || bc.Report.Printer is NullReportPrinter) if (e is CompletionResult || bc.Report.IsDisabled || e is FatalException || bc.Report.Printer is NullReportPrinter || bc.Module.Compiler.Settings.BreakOnInternalError)
throw; throw;
if (bc.CurrentBlock != null) { if (bc.CurrentBlock != null) {
@ -3806,9 +3811,6 @@ namespace Mono.CSharp {
} else { } else {
bc.Report.Error (587, "Internal compiler error: {0}", e.Message); bc.Report.Error (587, "Internal compiler error: {0}", e.Message);
} }
if (bc.Module.Compiler.Settings.DebugFlags > 0)
throw;
} }
// //
@ -5031,6 +5033,8 @@ namespace Mono.CSharp {
base.MarkReachable (rc); base.MarkReachable (rc);
block.MarkReachableScope (rc);
if (block.Statements.Count == 0) if (block.Statements.Count == 0)
return rc; return rc;
@ -6552,6 +6556,9 @@ namespace Mono.CSharp {
ok &= c.Resolve (bc); ok &= c.Resolve (bc);
TypeSpec resolved_type = c.CatchType; TypeSpec resolved_type = c.CatchType;
if (resolved_type == null)
continue;
for (int ii = 0; ii < clauses.Count; ++ii) { for (int ii = 0; ii < clauses.Count; ++ii) {
if (ii == i) if (ii == i)
continue; continue;

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

@ -1253,6 +1253,9 @@ namespace Mono.CSharp
return false; return false;
} }
if (a.IsNested && b.IsNested)
return IsEqual (a.DeclaringType, b.DeclaringType);
return true; return true;
} }

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

@ -432,7 +432,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} }
default: default:
throw new ArgumentException("Invalid value for UnaryOperatorType", "op"); return ErrorResolveResult.UnknownError;
} }
} }
// If the type is nullable, get the underlying type: // If the type is nullable, get the underlying type:
@ -611,7 +611,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// null coalescing operator is not overloadable and needs to be handled separately // null coalescing operator is not overloadable and needs to be handled separately
return ResolveNullCoalescingOperator(lhs, rhs); return ResolveNullCoalescingOperator(lhs, rhs);
} else { } else {
throw new ArgumentException("Invalid value for BinaryOperatorType", "op"); return ErrorResolveResult.UnknownError;
} }
} }
@ -1694,6 +1694,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
case NameLookupMode.Type: case NameLookupMode.Type:
case NameLookupMode.TypeInUsingDeclaration: case NameLookupMode.TypeInUsingDeclaration:
case NameLookupMode.BaseTypeReference: case NameLookupMode.BaseTypeReference:
// Don't do the UnknownMemberResolveResult/MethodGroupResolveResult processing,
// it's only relevant for expressions.
return lookup.LookupType(target.Type, identifier, typeArguments, parameterizeResultType); return lookup.LookupType(target.Type, identifier, typeArguments, parameterizeResultType);
default: default:
throw new NotSupportedException("Invalid value for NameLookupMode"); throw new NotSupportedException("Invalid value for NameLookupMode");

19
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/DelegateContextTests.cs

@ -148,6 +148,25 @@ public class Test
"); ");
Assert.IsNull(provider.Find(".ctor")); Assert.IsNull(provider.Find(".ctor"));
} }
[Test]
public void TestCrashOnEventHandlerCCWithoutIndentation()
{
// An off-by-one error in GetLineIndent() was causing an ArgumentOutOfRangeException
CodeCompletionBugTests.CombinedProviderTest(
@"using System;
public class Test
{
void TestFoo()
{
$Action act = a$
}
}
", provider => {
Assert.IsFalse(provider.AutoSelect);
});
}
} }
} }

27
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/RedundantUsingDirectiveIssueTests.cs

@ -269,6 +269,33 @@ class Foo
} }
[Test]
public void TestKeywordsInNamespace ()
{
TestWrongContext<RedundantUsingDirectiveIssue>(@"
namespace org.eclipse.jgit.@internal.storage.file
{
public class File {}
}
namespace Foo
{
using org.eclipse.jgit.@internal.storage.file;
class Bar
{
public static void Main (string[] args)
{
File file;
}
}
}
");
}
} }
} }

12
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Resolver/NameLookupTests.cs

@ -400,7 +400,6 @@ class Activator {
Assert.AreEqual("Testnamespace.Activator", result.Type.FullName); Assert.AreEqual("Testnamespace.Activator", result.Type.FullName);
} }
[Ignore("Fixme")]
[Test] [Test]
public void NamespaceDefinitionOverwritesTypeName () public void NamespaceDefinitionOverwritesTypeName ()
{ {
@ -1135,5 +1134,16 @@ namespace Test
Assert.IsFalse(rr.IsError); Assert.IsFalse(rr.IsError);
Assert.AreEqual("ConcreteTable+Record.Value", rr.Member.ReflectionName); Assert.AreEqual("ConcreteTable+Record.Value", rr.Member.ReflectionName);
} }
[Test]
public void UsingStatementReferringToMissingNestedType()
{
string program = @"using System;
using $A.B$;
class A { }";
var rr = Resolve<UnknownMemberResolveResult>(program);
}
} }
} }

56
src/Libraries/NRefactory/ICSharpCode.NRefactory.Tests/FormattingTests/TestBraceStlye.cs

@ -482,5 +482,61 @@ namespace B {
}"); }");
} }
[Test]
public void TestIndentBlocksInsideExpressions ()
{
var policy = FormattingOptionsFactory.CreateAllman ();
Test (policy,
@"class Test
{
void Foo()
{
FooBar(delegate{Foo();});
}
}",
@"class Test
{
void Foo()
{
FooBar(delegate
{
Foo();
});
}
}");
}
/// <summary>
/// Bug 18254 - Allow customization of indentation for anonymous methods
/// </summary>
[Test]
public void TestBug18254 ()
{
var policy = FormattingOptionsFactory.CreateAllman ();
Test (policy,
@"class Test
{
void Foo()
{
UIView.Animate(duration, () =>
{
view.Alpha = 0;
}, null);
}
}",
@"class Test
{
void Foo()
{
UIView.Animate(duration, () =>
{
view.Alpha = 0;
}, null);
}
}");
}
} }
} }

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

@ -862,6 +862,7 @@ class Foo
public void TestBrackets_AnonymousMethodOpenBracketAlignment() public void TestBrackets_AnonymousMethodOpenBracketAlignment()
{ {
var policy = FormattingOptionsFactory.CreateAllman(); var policy = FormattingOptionsFactory.CreateAllman();
policy.IndentBlocksInsideExpressions = false;
var indent = Helper.CreateEngine(@" var indent = Helper.CreateEngine(@"
class Foo class Foo
{ {
@ -878,6 +879,7 @@ class Foo
public void TestBrackets_AnonymousMethodCloseingBracketAlignment() public void TestBrackets_AnonymousMethodCloseingBracketAlignment()
{ {
var policy = FormattingOptionsFactory.CreateAllman(); var policy = FormattingOptionsFactory.CreateAllman();
policy.IndentBlocksInsideExpressions = false;
var indent = Helper.CreateEngine(@" var indent = Helper.CreateEngine(@"
class Foo class Foo
{ {
@ -1166,5 +1168,71 @@ class X
Assert.AreEqual("\t\t\t", indent.ThisLineIndent); Assert.AreEqual("\t\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t", indent.NextLineIndent); Assert.AreEqual("\t\t\t", indent.NextLineIndent);
} }
[Test]
public void TestBrackets_IndentBlocksInsideExpressionsOpenBrace()
{
var policy = FormattingOptionsFactory.CreateAllman();
var indent = Helper.CreateEngine(@"
class Foo
{
void Test()
{
Foo (new MyOBject
{$
", policy);
Assert.AreEqual("\t\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t\t", indent.NextLineIndent);
}
[Test]
public void TestBrackets_IndentBlocksInsideExpressions()
{
var policy = FormattingOptionsFactory.CreateAllman();
var indent = Helper.CreateEngine(@"
class Foo
{
void Test()
{
Foo (new MyOBject
{
$
", policy);
Assert.AreEqual("\t\t\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t\t", indent.NextLineIndent);
}
/// <summary>
/// Bug 18463 - Indentation does not work when typed statement does not require semicolon
/// </summary>
[Test]
public void TestBug18463()
{
var policy = FormattingOptionsFactory.CreateMono();
var indent = Helper.CreateEngine(@"
namespace FooBar
{
public class TestProject
{
public static int Main ()
{
switch (current_token) {
case Token.CLOSE_PARENS:
case Token.TRUE:
case Token.FALSE:
case Token.NULL:
case Token.LITERAL:
return Token.INTERR;
}
if (true) {
$
", policy);
Assert.AreEqual("\t\t\t\t", indent.ThisLineIndent);
Assert.AreEqual("\t\t\t\t", indent.NextLineIndent);
}
} }
} }

3
src/Libraries/NRefactory/ICSharpCode.NRefactory/Completion/DisplayFlags.cs

@ -35,7 +35,8 @@ namespace ICSharpCode.NRefactory.Completion
Obsolete = 2, Obsolete = 2,
DescriptionHasMarkup = 4, DescriptionHasMarkup = 4,
NamedArgument = 8, NamedArgument = 8,
IsImportCompletion = 16 IsImportCompletion = 16,
MarkedBold = 32
} }
} }

3
src/Libraries/NRefactory/ICSharpCode.NRefactory/TypeSystem/IAmbience.cs

@ -87,6 +87,9 @@ namespace ICSharpCode.NRefactory.TypeSystem
All = 0x7ff, All = 0x7ff,
} }
/// <summary>
/// Ambiences are used to convert type system symbols to text (usually for displaying the symbol to the user; e.g. in editor tooltips).
/// </summary>
public interface IAmbience public interface IAmbience
{ {
ConversionFlags ConversionFlags { get; set; } ConversionFlags ConversionFlags { get; set; }

Loading…
Cancel
Save