Browse Source

Merge NRefactory commit 'd03d17bbe4f137615c230371b3301b490c466dea' into SharpDevelop newNR branch.

newNRvisualizers
Daniel Grunwald 14 years ago
parent
commit
c6662f71f6
  1. 20
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ControlFlow.cs
  2. 91
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ReachabilityAnalysis.cs
  3. 32
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNode.cs
  4. 33
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNodeCollection.cs
  5. 60
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstType.cs
  6. 17
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ComposedType.cs
  7. 15
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/Expression.cs
  8. 23
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ParenthesizedExpression.cs
  9. 24
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/MemberType.cs
  10. 56
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/PrimitiveType.cs
  11. 21
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SimpleType.cs
  12. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/AttributedNode.cs
  13. 449
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs
  14. 126
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngineBase.cs
  15. 91
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/CSharpParameterCompletionEngine.cs
  16. 1
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/ICompletionDataFactory.cs
  17. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/IParameterCompletionDataFactory.cs
  18. 14
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj
  19. 34
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CSharpOutputVisitor.cs
  20. 5
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/CodeDomConvertVisitor.cs
  21. 20
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/OutputVisitor/TextWriterOutputFormatter.cs
  22. 435
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/CSharpParser.cs
  23. 43
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/AssemblyInfo.cs
  24. 34100
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ChangeLog
  25. 126
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/Makefile
  26. 22
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolFile.cs
  27. 54
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolTable.cs
  28. 46
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolWriter.cs
  29. 38
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/NOTES
  30. 26
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/OPTIMIZE
  31. 239
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/OTODO
  32. 66
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/PLAN
  33. 72
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/README
  34. 223
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/TODO
  35. 122
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/anonymous.cs
  36. 18
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assembly.cs
  37. 15
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/assign.cs
  38. 12
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/async.cs
  39. 2026
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/class.cs
  40. 33
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/codegen.cs
  41. 116
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/compiler.doc
  42. 22
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/complete.cs
  43. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/const.cs
  44. 13
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/context.cs
  45. 55
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/convert.cs
  46. 9624
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.cs
  47. 327
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-parser.jay
  48. 332
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/cs-tokenizer.cs
  49. 135
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/decl.cs
  50. 24
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/delegate.cs
  51. 154
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dmcs.csproj
  52. 6
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dmcs.exe.config
  53. 55
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dmcs.exe.sources
  54. 20
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dmcs.sln
  55. 59
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/doc-bootstrap.cs
  56. 15
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/doc.cs
  57. 125
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/driver.cs
  58. 25
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dynamic.cs
  59. 118
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ecore.cs
  60. 29
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/enum.cs
  61. 112
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/eval.cs
  62. 57
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/expression.cs
  63. 19
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/field.cs
  64. 27
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/flowanalysis.cs
  65. 26
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/generic.cs
  66. 111
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs.csproj
  67. 14
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs.exe.config
  68. 56
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs.exe.sources
  69. 20
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs.sln
  70. 23
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs.userprefs
  71. 29
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs2.csproj
  72. 0
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/hosting.cs
  73. 95
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/iterators.cs
  74. 24
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/lambda.todo
  75. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/linq.cs
  76. 410
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/location.cs
  77. 43
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/membercache.cs
  78. 161
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/method.cs
  79. 232
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/module.cs
  80. 587
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/namespace.cs
  81. 8
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/pending.cs
  82. 62
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/property.cs
  83. 168
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/repl.txt
  84. 135
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/report.cs
  85. 170
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/settings.cs
  86. 53
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/smcs.exe.sources
  87. 384
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/smcs.exe.sources-xml
  88. 257
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/statement.cs
  89. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/support.cs
  90. 17
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/symbolwriter.cs
  91. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/typemanager.cs
  92. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/typespec.cs
  93. 68
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/visit.cs
  94. 31920
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/y.output
  95. 2
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Properties/AssemblyInfo.cs
  96. 4
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/ConvertForeachToFor.cs
  97. 10
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/InsertAnonymousMethodSignature.cs
  98. 3
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/RemoveBackingStore.cs
  99. 7
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/SplitDeclarationAndAssignment.cs
  100. 17
      src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/NodeOutputAction.cs
  101. Some files were not shown because too many files have changed in this diff Show More

20
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ControlFlow.cs

@ -21,9 +21,10 @@ using System.Collections.Generic; @@ -21,9 +21,10 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.CSharp.Analysis
@ -156,7 +157,8 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis @@ -156,7 +157,8 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
}
Statement rootStatement;
CSharpAstResolver resolver;
CSharpTypeResolveContext typeResolveContext;
Func<AstNode, CancellationToken, ResolveResult> resolver;
List<ControlFlowNode> nodes;
Dictionary<string, ControlFlowNode> labels;
List<ControlFlowNode> gotoStatements;
@ -164,6 +166,8 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis @@ -164,6 +166,8 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
public IList<ControlFlowNode> BuildControlFlowGraph(Statement statement, CancellationToken cancellationToken = default(CancellationToken))
{
if (statement == null)
throw new ArgumentNullException("statement");
CSharpResolver r = new CSharpResolver(MinimalCorlib.Instance.CreateCompilation());
return BuildControlFlowGraph(statement, new CSharpAstResolver(r, statement), cancellationToken);
}
@ -174,7 +178,11 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis @@ -174,7 +178,11 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
throw new ArgumentNullException("statement");
if (resolver == null)
throw new ArgumentNullException("resolver");
return BuildControlFlowGraph(statement, resolver.Resolve, resolver.TypeResolveContext, cancellationToken);
}
internal IList<ControlFlowNode> BuildControlFlowGraph(Statement statement, Func<AstNode, CancellationToken, ResolveResult> resolver, CSharpTypeResolveContext typeResolveContext, CancellationToken cancellationToken)
{
NodeCreationVisitor nodeCreationVisitor = new NodeCreationVisitor();
nodeCreationVisitor.builder = this;
try {
@ -183,6 +191,7 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis @@ -183,6 +191,7 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
this.gotoStatements = new List<ControlFlowNode>();
this.rootStatement = statement;
this.resolver = resolver;
this.typeResolveContext = typeResolveContext;
this.cancellationToken = cancellationToken;
ControlFlowNode entryPoint = CreateStartNode(statement);
@ -205,6 +214,7 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis @@ -205,6 +214,7 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
this.gotoStatements = null;
this.rootStatement = null;
this.resolver = null;
this.typeResolveContext = null;
this.cancellationToken = CancellationToken.None;
}
}
@ -288,7 +298,7 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis @@ -288,7 +298,7 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
if (!(expr is PrimitiveExpression || expr is NullReferenceExpression))
return null;
}
return resolver.Resolve(expr, cancellationToken);
return resolver(expr, cancellationToken);
}
/// <summary>
@ -308,7 +318,7 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis @@ -308,7 +318,7 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
{
if (c1 == null || c2 == null || !c1.IsCompileTimeConstant || !c2.IsCompileTimeConstant)
return false;
CSharpResolver r = new CSharpResolver(resolver.TypeResolveContext);
CSharpResolver r = new CSharpResolver(typeResolveContext);
ResolveResult c = r.ResolveBinaryOperator(BinaryOperatorType.Equality, c1, c2);
return c.IsCompileTimeConstant && (c.ConstantValue as bool?) == true;
}

91
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Analysis/ReachabilityAnalysis.cs

@ -0,0 +1,91 @@ @@ -0,0 +1,91 @@
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Threading;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
namespace ICSharpCode.NRefactory.CSharp.Analysis
{
/// <summary>
/// Statement reachability analysis.
/// </summary>
public sealed class ReachabilityAnalysis
{
HashSet<Statement> reachableStatements = new HashSet<Statement>();
HashSet<Statement> reachableEndPoints = new HashSet<Statement>();
HashSet<ControlFlowNode> visitedNodes = new HashSet<ControlFlowNode>();
Stack<ControlFlowNode> stack = new Stack<ControlFlowNode>();
private ReachabilityAnalysis() {}
public static ReachabilityAnalysis Create(Statement statement, CSharpAstResolver resolver = null, CancellationToken cancellationToken = default(CancellationToken))
{
var cfgBuilder = new ControlFlowGraphBuilder();
var cfg = cfgBuilder.BuildControlFlowGraph(statement, resolver, cancellationToken);
return Create(cfg, cancellationToken);
}
internal static ReachabilityAnalysis Create(Statement statement, Func<AstNode, CancellationToken, ResolveResult> resolver, CSharpTypeResolveContext typeResolveContext, CancellationToken cancellationToken)
{
var cfgBuilder = new ControlFlowGraphBuilder();
var cfg = cfgBuilder.BuildControlFlowGraph(statement, resolver, typeResolveContext, cancellationToken);
return Create(cfg, cancellationToken);
}
public static ReachabilityAnalysis Create(IList<ControlFlowNode> controlFlowGraph, CancellationToken cancellationToken = default(CancellationToken))
{
if (controlFlowGraph == null)
throw new ArgumentNullException("controlFlowGraph");
ReachabilityAnalysis ra = new ReachabilityAnalysis();
ra.stack.Push(controlFlowGraph[0]);
while (ra.stack.Count > 0) {
cancellationToken.ThrowIfCancellationRequested();
ra.MarkReachable(ra.stack.Pop());
}
ra.stack = null;
ra.visitedNodes = null;
return ra;
}
void MarkReachable(ControlFlowNode node)
{
if (node.PreviousStatement != null)
reachableEndPoints.Add(node.PreviousStatement);
if (node.NextStatement != null)
reachableStatements.Add(node.NextStatement);
foreach (var edge in node.Outgoing) {
if (visitedNodes.Add(edge.To))
stack.Push(edge.To);
}
}
public bool IsReachable(Statement statement)
{
return reachableStatements.Contains(statement);
}
public bool IsEndpointReachable(Statement statement)
{
return reachableEndPoints.Contains(statement);
}
}
}

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

@ -135,6 +135,34 @@ namespace ICSharpCode.NRefactory.CSharp @@ -135,6 +135,34 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
/// <summary>
/// Returns true, if the given coordinates are in the node.
/// </summary>
public bool IsInside (TextLocation location)
{
return StartLocation <= location && location <= EndLocation;
}
/// <summary>
/// Returns true, if the given coordinates (line, column) are in the node.
/// </summary>
public bool IsInside(int line, int column)
{
return IsInside(new TextLocation (line, column));
}
/// <summary>
/// Gets the region from StartLocation to EndLocation for this node.
/// The file name of the region is set based on the parent CompilationUnit's file name.
/// If this node is not connected to a whole compilation, the file name will be null.
/// </summary>
public ICSharpCode.NRefactory.TypeSystem.DomRegion GetRegion()
{
var cu = (this.Ancestors.LastOrDefault() ?? this) as CompilationUnit;
string fileName = (cu != null ? cu.FileName : null);
return new ICSharpCode.NRefactory.TypeSystem.DomRegion(fileName, this.StartLocation, this.EndLocation);
}
public AstNode Parent {
get { return parent; }
}
@ -537,7 +565,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -537,7 +565,7 @@ namespace ICSharpCode.NRefactory.CSharp
}
/// <summary>
/// Gets the node specified by T at location. This is useful for getting a specific node from the tree. For example searching
/// Gets the node specified by T at location. This is useful for getting a specific node from the tree. For example searching
/// the current method declaration.
/// </summary>
public T GetNodeAt<T> (TextLocation location) where T : AstNode
@ -579,7 +607,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -579,7 +607,7 @@ namespace ICSharpCode.NRefactory.CSharp
yield return node;
} else {
if (node.EndLocation <= start) {
next = node.NextSibling;
next = node.NextSibling;
} else {
next = node.FirstChild;
}

33
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstNodeCollection.cs

@ -85,12 +85,16 @@ namespace ICSharpCode.NRefactory.CSharp @@ -85,12 +85,16 @@ namespace ICSharpCode.NRefactory.CSharp
if (nodes != null)
nodes = nodes.ToList();
Clear();
foreach (T node in nodes)
Add(node);
if (nodes != null) {
foreach (T node in nodes)
Add(node);
}
}
public void MoveTo(ICollection<T> targetCollection)
{
if (targetCollection == null)
throw new ArgumentNullException("targetCollection");
foreach (T node in this) {
node.Remove();
targetCollection.Add(node);
@ -124,6 +128,31 @@ namespace ICSharpCode.NRefactory.CSharp @@ -124,6 +128,31 @@ namespace ICSharpCode.NRefactory.CSharp
item.Remove();
}
/// <summary>
/// Returns the first element for which the predicate returns true,
/// or the null node (AstNode with IsNull=true) if no such object is found.
/// </summary>
public T FirstOrNullObject(Func<T, bool> predicate = null)
{
foreach (T item in this)
if (predicate == null || predicate(item))
return item;
return role.NullObject;
}
/// <summary>
/// Returns the last element for which the predicate returns true,
/// or the null node (AstNode with IsNull=true) if no such object is found.
/// </summary>
public T LastOrNullObject(Func<T, bool> predicate = null)
{
T result = role.NullObject;
foreach (T item in this)
if (predicate == null || predicate(item))
result = item;
return result;
}
bool ICollection<T>.IsReadOnly {
get { return false; }
}

60
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/AstType.cs

@ -18,6 +18,7 @@ @@ -18,6 +18,7 @@
using System;
using System.Collections.Generic;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp
@ -47,6 +48,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -47,6 +48,11 @@ namespace ICSharpCode.NRefactory.CSharp
{
return other == null || other.IsNull;
}
public override ITypeReference ToTypeReference(SimpleNameLookupMode lookupMode)
{
return SpecialType.UnknownType;
}
}
#endregion
@ -74,6 +80,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -74,6 +80,11 @@ namespace ICSharpCode.NRefactory.CSharp
return visitor.VisitPatternPlaceholder(this, child, data);
}
public override ITypeReference ToTypeReference(SimpleNameLookupMode lookupMode)
{
throw new NotSupportedException();
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
return child.DoMatch(other, match);
@ -95,6 +106,18 @@ namespace ICSharpCode.NRefactory.CSharp @@ -95,6 +106,18 @@ namespace ICSharpCode.NRefactory.CSharp
return (AstType)base.Clone();
}
/// <summary>
/// Create an ITypeReference for this AstType.
/// </summary>
/// <remarks>
/// The resulting type reference will read the context information from the
/// <see cref="ITypeResolveContext"/>:
/// For resolving type parameters, the CurrentTypeDefinition/CurrentMember is used.
/// For resolving simple names, the current namespace and usings from the CurrentUsingScope
/// (on CSharpTypeResolveContext only) is used.
/// </remarks>
public abstract ITypeReference ToTypeReference(SimpleNameLookupMode lookupMode = SimpleNameLookupMode.Type);
/// <summary>
/// Creates a pointer type from this type by nesting it in a <see cref="ComposedType"/>.
/// If this type already is a pointer type, this method just increases the PointerRank of the existing pointer type.
@ -153,42 +176,5 @@ namespace ICSharpCode.NRefactory.CSharp @@ -153,42 +176,5 @@ namespace ICSharpCode.NRefactory.CSharp
{
return new TypeReferenceExpression { Type = this }.Invoke(methodName, typeArguments, arguments);
}
public static AstType Create(Type type)
{
switch (Type.GetTypeCode(type)) {
case TypeCode.Object:
return new PrimitiveType("object");
case TypeCode.Boolean:
return new PrimitiveType("bool");
case TypeCode.Char:
return new PrimitiveType("char");
case TypeCode.SByte:
return new PrimitiveType("sbyte");
case TypeCode.Byte:
return new PrimitiveType("byte");
case TypeCode.Int16:
return new PrimitiveType("short");
case TypeCode.UInt16:
return new PrimitiveType("ushort");
case TypeCode.Int32:
return new PrimitiveType("int");
case TypeCode.UInt32:
return new PrimitiveType("uint");
case TypeCode.Int64:
return new PrimitiveType("long");
case TypeCode.UInt64:
return new PrimitiveType("ulong");
case TypeCode.Single:
return new PrimitiveType("float");
case TypeCode.Double:
return new PrimitiveType("double");
case TypeCode.Decimal:
return new PrimitiveType("decimal");
case TypeCode.String:
return new PrimitiveType("string");
}
return new SimpleType(type.FullName); // TODO: implement this correctly
}
}
}

17
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/ComposedType.cs

@ -27,6 +27,7 @@ using System; @@ -27,6 +27,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp
{
@ -114,6 +115,22 @@ namespace ICSharpCode.NRefactory.CSharp @@ -114,6 +115,22 @@ namespace ICSharpCode.NRefactory.CSharp
InsertChildBefore(this.ArraySpecifiers.FirstOrDefault(), new ArraySpecifier(dimensions), ArraySpecifierRole);
return this;
}
public override ITypeReference ToTypeReference(SimpleNameLookupMode lookupMode = SimpleNameLookupMode.Type)
{
ITypeReference t = this.BaseType.ToTypeReference(lookupMode);
if (this.HasNullableSpecifier) {
t = NullableType.Create(t);
}
int pointerRank = this.PointerRank;
for (int i = 0; i < pointerRank; i++) {
t = new PointerTypeReference(t);
}
foreach (var a in this.ArraySpecifiers.Reverse()) {
t = new ArrayTypeReference(t, a.Dimensions);
}
return t;
}
}
/// <summary>

15
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/Expression.cs

@ -202,30 +202,15 @@ namespace ICSharpCode.NRefactory.CSharp @@ -202,30 +202,15 @@ namespace ICSharpCode.NRefactory.CSharp
return new CastExpression { Type = type, Expression = this };
}
public CastExpression CastTo(Type type)
{
return new CastExpression { Type = AstType.Create(type), Expression = this };
}
public AsExpression CastAs(AstType type)
{
return new AsExpression { Type = type, Expression = this };
}
public AsExpression CastAs(Type type)
{
return new AsExpression { Type = AstType.Create(type), Expression = this };
}
public IsExpression IsType(AstType type)
{
return new IsExpression { Type = type, Expression = this };
}
public IsExpression IsType(Type type)
{
return new IsExpression { Type = AstType.Create(type), Expression = this };
}
#endregion
}
}

23
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Expressions/ParenthesizedExpression.cs

@ -1,6 +1,6 @@ @@ -1,6 +1,6 @@
//
// ParenthesizedExpression.cs
//
//
// Author:
// Mike Krüger <mkrueger@novell.com>
//
@ -63,5 +63,26 @@ namespace ICSharpCode.NRefactory.CSharp @@ -63,5 +63,26 @@ namespace ICSharpCode.NRefactory.CSharp
ParenthesizedExpression o = other as ParenthesizedExpression;
return o != null && this.Expression.DoMatch(o.Expression, match);
}
/// <summary>
/// Gets whether the expression acts like a parenthesized expression,
/// i.e. whether information about the expected type (for lambda type inference) flows
/// into the inner expression.
/// </summary>
/// <returns>Returns true for ParenthesizedExpression, CheckedExpression or UncheckedExpression; false otherwise.</returns>
public static bool ActsAsParenthesizedExpression(AstNode expression)
{
return expression is ParenthesizedExpression || expression is CheckedExpression || expression is UncheckedExpression;
}
/// <summary>
/// Unpacks the given expression if it is a ParenthesizedExpression, CheckedExpression or UncheckedExpression.
/// </summary>
public static Expression UnpackParenthesizedExpression(Expression expr)
{
while (ActsAsParenthesizedExpression(expr))
expr = expr.GetChildByRole(ParenthesizedExpression.Roles.Expression);
return expr;
}
}
}

24
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/MemberType.cs

@ -28,6 +28,8 @@ using System; @@ -28,6 +28,8 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp
{
@ -114,6 +116,28 @@ namespace ICSharpCode.NRefactory.CSharp @@ -114,6 +116,28 @@ namespace ICSharpCode.NRefactory.CSharp
}
return b.ToString();
}
public override ITypeReference ToTypeReference(SimpleNameLookupMode lookupMode = SimpleNameLookupMode.Type)
{
TypeOrNamespaceReference t;
if (this.IsDoubleColon) {
SimpleType st = this.Target as SimpleType;
if (st != null) {
t = new AliasNamespaceReference(st.Identifier);
} else {
t = null;
}
} else {
t = this.Target.ToTypeReference(lookupMode) as TypeOrNamespaceReference;
}
if (t == null)
return SpecialType.UnknownType;
var typeArguments = new List<ITypeReference>();
foreach (var ta in this.TypeArguments) {
typeArguments.Add(ta.ToTypeReference(lookupMode));
}
return new MemberTypeOrNamespaceReference(t, this.MemberName, typeArguments);
}
}
}

56
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/PrimitiveType.cs

@ -26,6 +26,9 @@ @@ -26,6 +26,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.CSharp
{
@ -34,6 +37,10 @@ namespace ICSharpCode.NRefactory.CSharp @@ -34,6 +37,10 @@ namespace ICSharpCode.NRefactory.CSharp
public string Keyword { get; set; }
public TextLocation Location { get; set; }
public KnownTypeCode KnownTypeCode {
get { return GetTypeCodeForPrimitiveType(this.Keyword); }
}
public PrimitiveType()
{
}
@ -83,6 +90,55 @@ namespace ICSharpCode.NRefactory.CSharp @@ -83,6 +90,55 @@ namespace ICSharpCode.NRefactory.CSharp
{
return Keyword ?? base.ToString();
}
public override ITypeReference ToTypeReference(SimpleNameLookupMode lookupMode = SimpleNameLookupMode.Type)
{
KnownTypeCode typeCode = GetTypeCodeForPrimitiveType(this.Keyword);
if (typeCode == KnownTypeCode.None)
return new UnknownType(null, this.Keyword);
else
return KnownTypeReference.Get(typeCode);
}
public static KnownTypeCode GetTypeCodeForPrimitiveType(string keyword)
{
switch (keyword) {
case "string":
return KnownTypeCode.String;
case "int":
return KnownTypeCode.Int32;
case "uint":
return KnownTypeCode.UInt32;
case "object":
return KnownTypeCode.Object;
case "bool":
return KnownTypeCode.Boolean;
case "sbyte":
return KnownTypeCode.SByte;
case "byte":
return KnownTypeCode.Byte;
case "short":
return KnownTypeCode.Int16;
case "ushort":
return KnownTypeCode.UInt16;
case "long":
return KnownTypeCode.Int64;
case "ulong":
return KnownTypeCode.UInt64;
case "float":
return KnownTypeCode.Single;
case "double":
return KnownTypeCode.Double;
case "decimal":
return KnownTypeCode.Decimal;
case "char":
return KnownTypeCode.Char;
case "void":
return KnownTypeCode.Void;
default:
return KnownTypeCode.None;
}
}
}
}

21
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/SimpleType.cs

@ -28,6 +28,9 @@ using System; @@ -28,6 +28,9 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp
{
@ -53,6 +56,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -53,6 +56,11 @@ namespace ICSharpCode.NRefactory.CSharp
{
return other == null || other.IsNull;
}
public override ITypeReference ToTypeReference(SimpleNameLookupMode lookupMode)
{
return SpecialType.UnknownType;
}
}
#endregion
@ -130,6 +138,19 @@ namespace ICSharpCode.NRefactory.CSharp @@ -130,6 +138,19 @@ namespace ICSharpCode.NRefactory.CSharp
}
return b.ToString();
}
public override ITypeReference ToTypeReference(SimpleNameLookupMode lookupMode = SimpleNameLookupMode.Type)
{
var typeArguments = new List<ITypeReference>();
foreach (var ta in this.TypeArguments) {
typeArguments.Add(ta.ToTypeReference(lookupMode));
}
if (typeArguments.Count == 0 && string.IsNullOrEmpty(this.Identifier)) {
// empty SimpleType is used for typeof(List<>).
return SpecialType.UnboundTypeArgument;
}
return new SimpleTypeOrNamespaceReference(this.Identifier, typeArguments, lookupMode);
}
}
}

1
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/TypeMembers/AttributedNode.cs

@ -25,6 +25,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -25,6 +25,7 @@ namespace ICSharpCode.NRefactory.CSharp
public abstract class AttributedNode : AstNode
{
public static readonly Role<AttributeSection> AttributeRole = new Role<AttributeSection>("Attribute");
public static readonly Role<AttributeSection> UnattachedAttributeRole = new Role<AttributeSection>("UnattachedAttribute");
public static readonly Role<CSharpModifierToken> ModifierRole = new Role<CSharpModifierToken>("Modifier");
public AstNodeCollection<AttributeSection> Attributes {

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

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// CSharpCompletionEngine.cs
//
// Author:
@ -65,6 +65,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -65,6 +65,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
throw new ArgumentNullException ("factory");
this.document = document;
this.factory = factory;
// Set defaults for additional input properties
this.FormattingPolicy = new CSharpFormattingOptions();
this.EolMarker = Environment.NewLine;
this.IndentString = "\t";
}
public IEnumerable<ICompletionData> GetCompletionData (int offset, bool controlSpace)
@ -170,9 +174,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -170,9 +174,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return null;
}
var resolveResult = ResolveExpression (expr.Item1, expr.Item2, expr.Item3);
if (resolveResult == null)
return null;
if (expr.Item2 is AstType)
@ -308,12 +310,12 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -308,12 +310,12 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
case "=":
case "==":
GetPreviousToken (ref tokenIndex, false);
var expressionOrVariableDeclaration = GetExpressionAt (tokenIndex);
if (expressionOrVariableDeclaration == null)
return null;
resolveResult = ResolveExpression (expressionOrVariableDeclaration.Item1, expressionOrVariableDeclaration.Item2, expressionOrVariableDeclaration.Item3);
if (resolveResult == null)
return null;
if (resolveResult.Item1.Type.Kind == TypeKind.Enum) {
@ -409,8 +411,13 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -409,8 +411,13 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (IsInsideCommentOrString ())
return null;
if (IsInLinqContext (offset)) {
if (!controlSpace && !(char.IsLetter (completionChar) || completionChar == '_'))
return null;
tokenIndex = offset;
token = GetPreviousToken (ref tokenIndex, false); // token last typed
if (!char.IsWhiteSpace (completionChar) && !linqKeywords.Contains (token))
token = GetPreviousToken (ref tokenIndex, false); // token last typed
if (linqKeywords.Contains (token)) {
if (token == "from") // after from no auto code completion.
return null;
@ -420,7 +427,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -420,7 +427,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
AddKeywords (dataList, linqKeywords);
return dataList.Result;
}
if (currentType != null && currentType.Kind == TypeKind.Enum)
return HandleEnumContext ();
@ -436,7 +442,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -436,7 +442,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (!(char.IsLetter (completionChar) || completionChar == '_') && (!controlSpace || identifierStart == null || !(identifierStart.Item2 is ArrayInitializerExpression))) {
return controlSpace ? HandleAccessorContext () ?? DefaultControlSpaceItems (identifierStart) : null;
}
char prevCh = offset > 2 ? document.GetCharAt (offset - 2) : ';';
char nextCh = offset < document.TextLength ? document.GetCharAt (offset) : ' ';
const string allowedChars = ";,[](){}+-*/%^?:&|~!<>=";
@ -444,14 +449,15 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -444,14 +449,15 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return null;
if (!(Char.IsWhiteSpace (prevCh) || allowedChars.IndexOf (prevCh) >= 0))
return null;
// Do not pop up completion on identifier identifier (should be handled by keyword completion).
tokenIndex = offset - 1;
token = GetPreviousToken (ref tokenIndex, false);
if (token == "class" || token == "namespace") // after these always follows a name
if (token == "class" || token == "interface" || token == "struct" || token == "enum" || token == "namespace") // after these always follows a name
return null;
int prevTokenIndex = tokenIndex;
var prevToken2 = GetPreviousToken (ref prevTokenIndex, false);
if (prevToken2 == "delegate") // after these always follows a name
return null;
if (identifierStart == null && !string.IsNullOrEmpty (token) && !(IsInsideComment (tokenIndex) || IsInsideString (tokenIndex)) && (prevToken2 == ";" || prevToken2 == "{" || prevToken2 == "}")) {
char last = token [token.Length - 1];
if (char.IsLetterOrDigit (last) || last == '_' || token == ">") {
@ -464,9 +470,13 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -464,9 +470,13 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return accCtx;
return DefaultControlSpaceItems (null, controlSpace);
}
CSharpResolver csResolver;
AstNode n = identifierStart.Item2;
if (n != null && n.Parent is AnonymousTypeCreateExpression) {
AutoSelect = false;
}
// Handle foreach (type name _
if (n is IdentifierExpression) {
var prev = n.GetPrevNode () as ForeachStatement;
@ -479,14 +489,36 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -479,14 +489,36 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
}
if (n != null && n.Parent is InvocationExpression) {
var invokeResult = ResolveExpression (identifierStart.Item1, ((InvocationExpression)n.Parent).Target, identifierStart.Item3);
var invokeParent = (InvocationExpression)n.Parent;
var invokeResult = ResolveExpression (identifierStart.Item1, invokeParent.Target, identifierStart.Item3);
var mgr = invokeResult != null ? invokeResult.Item1 as MethodGroupResolveResult : null;
if (mgr != null) {
int idx = 0;
foreach (var arg in invokeParent.Arguments) {
if (arg == n)
break;
idx++;
}
foreach (var method in mgr.Methods) {
if (idx < method.Parameters.Count && method.Parameters[idx].Type.Kind == TypeKind.Delegate) {
AutoSelect = false;
AutoCompleteEmptyMatch = false;
}
foreach (var p in method.Parameters) {
contextList.AddVariable (p);
}
}
idx++;
foreach (var list in mgr.GetExtensionMethods ()) {
foreach (var method in list) {
if (idx < method.Parameters.Count && method.Parameters[idx].Type.Kind == TypeKind.Delegate) {
AutoSelect = false;
AutoCompleteEmptyMatch = false;
}
}
}
}
}
@ -503,6 +535,27 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -503,6 +535,27 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
}
if (n is IdentifierExpression) {
var bop = n.Parent as BinaryOperatorExpression;
Expression evaluationExpr = null;
if (bop != null && bop.Right == n && (bop.Operator == BinaryOperatorType.Equality || bop.Operator == BinaryOperatorType.InEquality)) {
evaluationExpr = bop.Left;
}
// check for compare to enum case
if (evaluationExpr != null) {
resolveResult = ResolveExpression (identifierStart.Item1, evaluationExpr, identifierStart.Item3);
if (resolveResult != null && resolveResult.Item1.Type.Kind == TypeKind.Enum) {
var wrapper = new CompletionDataWrapper (this);
AddContextCompletion (wrapper, resolveResult.Item2, evaluationExpr);
AddEnumMembers (wrapper, resolveResult.Item1.Type, resolveResult.Item2);
AutoCompleteEmptyMatch = false;
return wrapper.Result;
}
}
}
if (n is Identifier && n.Parent is ForeachStatement) {
if (controlSpace)
return DefaultControlSpaceItems ();
@ -544,17 +597,16 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -544,17 +597,16 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
nodes.Add (n);
if (n.Parent is ICSharpCode.NRefactory.CSharp.Attribute)
nodes.Add (n.Parent);
var navigator = new NodeListResolveVisitorNavigator (nodes);
var visitor = new ResolveVisitor (csResolver, identifierStart.Item1, navigator);
visitor.Scan (identifierStart.Item3);
var astResolver = new CSharpAstResolver (csResolver, identifierStart.Item3, identifierStart.Item1);
astResolver.ApplyNavigator (new NodeListResolveVisitorNavigator (nodes));
try {
csResolver = visitor.GetResolverStateBefore (n);
csResolver = astResolver.GetResolverStateBefore (n);
} catch (Exception) {
csResolver = GetState ();
}
// add attribute properties.
if (n.Parent is ICSharpCode.NRefactory.CSharp.Attribute) {
var resolved = visitor.GetResolveResult (n.Parent);
var resolved = astResolver.Resolve (n.Parent);
if (resolved != null && resolved.Type != null) {
foreach (var property in resolved.Type.GetProperties (p => p.Accessibility == Accessibility.Public)) {
contextList.AddMember (property);
@ -567,7 +619,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -567,7 +619,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
} else {
csResolver = GetState ();
}
// identifier has already started with the first letter
offset--;
AddContextCompletion (contextList, csResolver, identifierStart.Item2);
@ -658,7 +709,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -658,7 +709,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
while (null != (token = GetPreviousToken (ref offset, true)) && !IsInsideComment (offset) && !IsInsideString (offset)) {
if (token == "from")
return true;
if (token == ";")
if (token == ";" || token == "{")
return false;
}
return false;
@ -694,6 +745,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -694,6 +745,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
offset--;
}
location = document.GetLocation (offset);
if (xp == null)
xp = GetExpressionAtCursor ();
AstNode node;
@ -706,6 +758,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -706,6 +758,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
node = unit.GetNodeAt (location);
rr = ResolveExpression (CSharpParsedFile, node, unit);
}
if (node is Identifier && node.Parent is ForeachStatement) {
var foreachStmt = (ForeachStatement)node.Parent;
foreach (var possibleName in GenerateNameProposals (foreachStmt.VariableType)) {
@ -741,25 +794,24 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -741,25 +794,24 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return wrapper.Result;
}
}
CSharpResolver csResolver;
if (node != null) {
var nodes = new List<AstNode> ();
var n = node;
nodes.Add (n);
if (n.Parent is ICSharpCode.NRefactory.CSharp.Attribute)
nodes.Add (n.Parent);
var navigator = new NodeListResolveVisitorNavigator (nodes);
var visitor = new ResolveVisitor (GetState (), xp != null ? xp.Item1 : CSharpParsedFile, navigator);
visitor.Scan (node);
try {
csResolver = visitor.GetResolverStateBefore (node);
} catch (Exception) {
CSharpResolver csResolver = null;
if (rr != null)
csResolver = rr.Item2;
if (csResolver == null) {
if (node != null) {
csResolver = GetState ();
//var astResolver = new CSharpAstResolver (csResolver, node, xp != null ? xp.Item1 : CSharpParsedFile);
try {
//csResolver = astResolver.GetResolverStateBefore (node);
Console.WriteLine (csResolver.LocalVariables.Count ());
} catch (Exception e) {
Console.WriteLine ("E!!!" + e);
}
} else {
csResolver = GetState ();
}
} else {
csResolver = GetState ();
}
AddContextCompletion (wrapper, csResolver, node);
@ -769,13 +821,15 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -769,13 +821,15 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
void AddContextCompletion (CompletionDataWrapper wrapper, CSharpResolver state, AstNode node)
{
if (state != null) {
if (state != null && !(node is AstType)) {
foreach (var variable in state.LocalVariables) {
if (variable.Region.IsInside (location.Line, location.Column - 1))
continue;
wrapper.AddVariable (variable);
}
}
if (currentMember is IUnresolvedParameterizedMember) {
if (currentMember is IUnresolvedParameterizedMember && !(node is AstType)) {
var param = (IParameterizedMember)currentMember.CreateResolved (ctx);
foreach (var p in param.Parameters) {
wrapper.AddVariable (p);
@ -791,7 +845,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -791,7 +845,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
Predicate<IType> typePred = null;
if (node is Attribute) {
var attribute = Compilation.FindType (typeof(System.Attribute));
var attribute = Compilation.FindType (KnownTypeCode.Attribute);
typePred = t => {
return t.GetAllBaseTypeDefinitions ().Any (bt => bt.Equals (attribute));
};
@ -799,25 +853,30 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -799,25 +853,30 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
AddTypesAndNamespaces (wrapper, state, node, typePred);
wrapper.Result.Add (factory.CreateLiteralCompletionData ("global"));
if (currentMember != null) {
AddKeywords (wrapper, statementStartKeywords);
AddKeywords (wrapper, expressionLevelKeywords);
} else if (currentType != null) {
AddKeywords (wrapper, typeLevelKeywords);
} else {
AddKeywords (wrapper, globalLevelKeywords);
}
var prop = currentMember as IUnresolvedProperty;
if (prop != null && prop.Setter != null && prop.Setter.Region.IsInside (location))
wrapper.AddCustom ("value");
if (currentMember is IUnresolvedEvent)
wrapper.AddCustom ("value");
if (IsInSwitchContext (node)) {
wrapper.AddCustom ("case");
if (!(node is AstType)) {
if (currentMember != null) {
AddKeywords (wrapper, statementStartKeywords);
AddKeywords (wrapper, expressionLevelKeywords);
} else if (currentType != null) {
AddKeywords (wrapper, typeLevelKeywords);
} else {
AddKeywords (wrapper, globalLevelKeywords);
}
var prop = currentMember as IUnresolvedProperty;
if (prop != null && prop.Setter != null && prop.Setter.Region.IsInside (location))
wrapper.AddCustom ("value");
if (currentMember is IUnresolvedEvent)
wrapper.AddCustom ("value");
if (IsInSwitchContext (node)) {
wrapper.AddCustom ("case");
}
}
AddKeywords (wrapper, primitiveTypesKeywords);
if (currentMember != null)
wrapper.AddCustom ("var");
wrapper.Result.AddRange (factory.CreateCodeTemplateCompletionData ());
if (node != null && node.Role == AstNode.Roles.Argument) {
@ -854,7 +913,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -854,7 +913,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
void AddTypesAndNamespaces (CompletionDataWrapper wrapper, CSharpResolver state, AstNode node, Predicate<IType> typePred = null, Predicate<IMember> memberPred = null)
{
var currentMember = ctx.CurrentMember;
if (currentType != null) {
for (var ct = currentType; ct != null; ct = ct.DeclaringTypeDefinition) {
foreach (var nestedType in ct.NestedTypes) {
@ -866,31 +924,34 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -866,31 +924,34 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
}
}
if (this.currentMember != null) {
if (this.currentMember != null && !(node is AstType)) {
var def = ctx.CurrentTypeDefinition ?? Compilation.MainAssembly.GetTypeDefinition (currentType);
foreach (var member in def.GetMembers ()) {
if (member is IMethod && ((IMethod)member).FullName == "System.Object.Finalize")
continue;
if (member.EntityType == EntityType.Operator)
continue;
if (memberPred == null || memberPred (member))
wrapper.AddMember (member);
}
var declaring = def.DeclaringTypeDefinition;
while (declaring != null) {
foreach (var member in declaring.GetMembers (m => m.IsStatic)) {
if (def != null) {
foreach (var member in def.GetMembers ()) {
if (member is IMethod && ((IMethod)member).FullName == "System.Object.Finalize")
continue;
if (member.EntityType == EntityType.Operator)
continue;
if (memberPred == null || memberPred (member))
wrapper.AddMember (member);
}
declaring = declaring.DeclaringTypeDefinition;
var declaring = def.DeclaringTypeDefinition;
while (declaring != null) {
foreach (var member in declaring.GetMembers (m => m.IsStatic)) {
if (memberPred == null || memberPred (member))
wrapper.AddMember (member);
}
declaring = declaring.DeclaringTypeDefinition;
}
}
}
foreach (var p in currentType.TypeParameters) {
wrapper.AddTypeParameter (p);
}
}
var scope = CSharpParsedFile.GetUsingScope (location).Resolve (Compilation);
for (var n = state.CurrentUsingScope; n != null; n = n.Parent) {
for (var n = scope; n != null; n = n.Parent) {
foreach (var pair in n.UsingAliases) {
wrapper.AddNamespace (pair.Key);
}
@ -1005,7 +1066,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1005,7 +1066,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
isAsType = resolved.Item1.Type;
}
}
var isAsWrapper = new CompletionDataWrapper (this);
AddTypesAndNamespaces (isAsWrapper, GetState (), null, t => isAsType == null || t.GetDefinition ().IsDerivedFrom (isAsType.GetDefinition ()));
return isAsWrapper.Result;
@ -1074,10 +1134,9 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1074,10 +1134,9 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
if (!IsLineEmptyUpToEol ())
return null;
var overrideCls = CSharpParsedFile.GetInnermostTypeDefinition (location);
if (overrideCls != null && (overrideCls.Kind == TypeKind.Class || overrideCls.Kind == TypeKind.Struct)) {
if (currentType != null && (currentType.Kind == TypeKind.Class || currentType.Kind == TypeKind.Struct)) {
string modifiers = document.GetText (firstMod, wordStart - firstMod);
return GetOverrideCompletionData (overrideCls, modifiers);
return GetOverrideCompletionData (currentType, modifiers);
}
return null;
case "partial":
@ -1096,11 +1155,11 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1096,11 +1155,11 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
if (!IsLineEmptyUpToEol ())
return null;
var state = GetState ();
overrideCls = CSharpParsedFile.GetInnermostTypeDefinition (location);
if (overrideCls != null && (overrideCls.Kind == TypeKind.Class || overrideCls.Kind == TypeKind.Struct)) {
if (state.CurrentTypeDefinition != null && (state.CurrentTypeDefinition.Kind == TypeKind.Class || state.CurrentTypeDefinition.Kind == TypeKind.Struct)) {
string modifiers = document.GetText (firstMod, wordStart - firstMod);
return GetPartialCompletionData (overrideCls, modifiers);
return GetPartialCompletionData (state.CurrentTypeDefinition, modifiers);
}
return null;
@ -1114,7 +1173,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1114,7 +1173,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (accessorContext != null)
return accessorContext;
wrapper = new CompletionDataWrapper (this);
var state = GetState ();
state = GetState ();
AddTypesAndNamespaces (wrapper, state, null, null, m => false);
AddKeywords (wrapper, typeLevelKeywords);
AddKeywords (wrapper, primitiveTypesKeywords);
@ -1344,80 +1403,60 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1344,80 +1403,60 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return null; // don't add override completion for static members
}
}
foreach (var baseType in type.Resolve (ctx).GetAllBaseTypeDefinitions ()) {
AddVirtuals (alreadyInserted, wrapper, type.Resolve (ctx).GetDefinition (), modifiers, baseType, declarationBegin);
addedVirtuals = true;
}
if (!addedVirtuals)
AddVirtuals (alreadyInserted, wrapper, type.Resolve (ctx).GetDefinition (), modifiers, Compilation.FindType (typeof(object)).GetDefinition (), declarationBegin);
AddVirtuals (alreadyInserted, wrapper, modifiers, type.Resolve (ctx), declarationBegin);
return wrapper.Result;
}
IEnumerable<ICompletionData> GetPartialCompletionData (IUnresolvedTypeDefinition type, string modifiers)
IEnumerable<ICompletionData> GetPartialCompletionData (ITypeDefinition type, string modifiers)
{
var wrapper = new CompletionDataWrapper (this);
var partialType = type.Resolve (ctx);
if (partialType != null) {
int declarationBegin = offset;
int j = declarationBegin;
for (int i = 0; i < 3; i++) {
switch (GetPreviousToken (ref j, true)) {
case "public":
case "protected":
case "private":
case "internal":
case "sealed":
case "override":
declarationBegin = j;
break;
case "static":
return null; // don't add override completion for static members
}
}
var methods = new List<IMethod> ();
// gather all partial methods without implementation
/* TODO: foreach (var method in partialType.GetMethods ()) {
if (method.IsPartial && method.BodyRegion.IsEmpty) {
methods.Add (method);
}
int declarationBegin = offset;
int j = declarationBegin;
for (int i = 0; i < 3; i++) {
switch (GetPreviousToken (ref j, true)) {
case "public":
case "protected":
case "private":
case "internal":
case "sealed":
case "override":
declarationBegin = j;
break;
case "static":
return null; // don't add override completion for static members
}
// now filter all methods that are implemented in the compound class
foreach (var part in partialType.GetParts ()) {
if (part == type)
continue;
for (int i = 0; i < methods.Count; i++) {
var curMethod = methods [i];
var method = GetImplementation (partialType, curMethod);
if (method != null && !method.BodyRegion.IsEmpty) {
methods.RemoveAt (i);
i--;
}
var methods = new List<IUnresolvedMethod> ();
foreach (var part in type.Parts) {
foreach (var method in part.Methods) {
if (method.BodyRegion.IsEmpty) {
if (GetImplementation (type, method) != null)
continue;
}
methods.Add (method);
}
}
*/
foreach (var method in methods) {
wrapper.Add (factory.CreateNewOverrideCompletionData (declarationBegin, type, method));
}
}
}
foreach (var method in methods) {
wrapper.Add (factory.CreateNewPartialCompletionData (declarationBegin, method.DeclaringTypeDefinition, method));
}
return wrapper.Result;
}
IMethod GetImplementation (ITypeDefinition type, IMethod method)
IMethod GetImplementation (ITypeDefinition type, IUnresolvedMethod method)
{
foreach (var cur in type.Methods) {
if (cur.Name == method.Name && cur.Parameters.Count == method.Parameters.Count && !cur.BodyRegion.IsEmpty) {
bool equal = true;
for (int i = 0; i < cur.Parameters.Count; i++) {
/*for (int i = 0; i < cur.Parameters.Count; i++) {
if (!cur.Parameters [i].Type.Equals (method.Parameters [i].Type)) {
equal = false;
break;
}
}
}*/
if (equal)
return cur;
}
@ -1433,27 +1472,29 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1433,27 +1472,29 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return e.Name + "`" + e.TypeParameters.Count;
}
void AddVirtuals (Dictionary<string, bool> alreadyInserted, CompletionDataWrapper col, ITypeDefinition type, string modifiers, ITypeDefinition curType, int declarationBegin)
void AddVirtuals (Dictionary<string, bool> alreadyInserted, CompletionDataWrapper col, string modifiers, IType curType, int declarationBegin)
{
if (curType == null)
return;
foreach (var m in curType.Methods.Where (m => !m.IsConstructor && !m.IsDestructor).Cast<IMember> ().Concat (curType.Properties.Cast<IMember> ())) {
if (m.IsSynthetic || curType.Kind != TypeKind.Interface && !(m.IsVirtual || m.IsOverride || m.IsAbstract))
foreach (var m in curType.GetMethods (m => !m.IsConstructor && !m.IsDestructor).Cast<IMember> ().Concat (curType.GetProperties ().Cast<IMember> ()).Reverse ()) {
if (m.IsSynthetic || curType.Kind != TypeKind.Interface && !m.IsOverridable)
continue;
// filter out the "Finalize" methods, because finalizers should be done with destructors.
if (m is IMethod && m.Name == "Finalize")
continue;
var data = factory.CreateNewOverrideCompletionData (declarationBegin, type.Parts.First (), m);
var data = factory.CreateNewOverrideCompletionData (declarationBegin, currentType, m);
string text = GetNameWithParamCount (m);
// check if the member is already implemented
bool foundMember = type.Members.Any (cm => GetNameWithParamCount (cm) == text);
if (!foundMember && !alreadyInserted.ContainsKey (text)) {
alreadyInserted [text] = true;
data.CompletionCategory = col.GetCompletionCategory (curType);
col.Add (data);
}
bool foundMember = curType.GetMembers ().Any (cm => GetNameWithParamCount (cm) == text && cm.DeclaringTypeDefinition == curType.GetDefinition ());
if (foundMember)
continue;
if (alreadyInserted.ContainsKey (text))
continue;
alreadyInserted [text] = true;
data.CompletionCategory = col.GetCompletionCategory (curType);
col.Add (data);
}
}
@ -1682,6 +1723,17 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1682,6 +1723,17 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
string GetShortType (IType type, CSharpResolver state)
{
var builder = new TypeSystemAstBuilder (state);
var dt = state.CurrentTypeDefinition;
var declaring = type.DeclaringType != null ? type.DeclaringType.GetDefinition () : null;
if (declaring != null) {
while (dt != null) {
if (dt.Equals (declaring)) {
builder.AlwaysUseShortTypeNames = true;
break;
}
dt = dt.DeclaringTypeDefinition;
}
}
var shortType = builder.ConvertType (type);
using (var w = new System.IO.StringWriter ()) {
var visitor = new CSharpOutputVisitor (w, FormattingPolicy);
@ -1725,19 +1777,14 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1725,19 +1777,14 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
IType type = resolveResult.Type;
var typeDef = resolveResult.Type.GetDefinition ();
var lookup = new MemberLookup (ctx.CurrentTypeDefinition, Compilation.MainAssembly);
var result = new CompletionDataWrapper (this);
bool isProtectedAllowed = false;
bool includeStaticMembers = false;
if (resolveResult is LocalResolveResult) {
isProtectedAllowed = currentType != null && typeDef != null ? typeDef.GetAllBaseTypeDefinitions ().Any (bt => bt.Equals (currentType)) : false;
if (resolvedNode is IdentifierExpression) {
var mrr = (LocalResolveResult)resolveResult;
includeStaticMembers = mrr.Variable.Name == mrr.Type.Name;
}
} else {
isProtectedAllowed = currentType != null && typeDef != null ? currentType.Resolve (ctx).GetDefinition ().GetAllBaseTypeDefinitions ().Any (bt => bt.Equals (typeDef)) : false;
}
if (resolveResult is TypeResolveResult && type.Kind == TypeKind.Enum) {
foreach (var field in type.GetFields ()) {
@ -1753,28 +1800,60 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1753,28 +1800,60 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (resolveResult is MemberResolveResult && resolvedNode is IdentifierExpression) {
var mrr = (MemberResolveResult)resolveResult;
includeStaticMembers = mrr.Member.Name == mrr.Type.Name;
// ADD Aliases
var scope = CSharpParsedFile.GetUsingScope (location).Resolve (Compilation);
for (var n = scope; n != null; n = n.Parent) {
foreach (var pair in n.UsingAliases) {
if (pair.Key == mrr.Member.Name) {
foreach (var r in CreateCompletionData (location, pair.Value, resolvedNode, state)) {
if (r is IEntityCompletionData && ((IEntityCompletionData)r).Entity is IMember) {
result.AddMember ((IMember)((IEntityCompletionData)r).Entity);
} else {
result.Add (r);
}
}
}
}
}
}
if (resolveResult is TypeResolveResult && (resolvedNode is IdentifierExpression || resolvedNode is MemberReferenceExpression)) {
includeStaticMembers = true;
}
// Console.WriteLine ("type:" + type +"/"+type.GetType ());
// Console.WriteLine ("IS PROT ALLOWED:" + isProtectedAllowed);
// Console.WriteLine ("current:" + ctx.CurrentTypeDefinition);
// Console.WriteLine ("IS PROT ALLOWED:" + isProtectedAllowed + " static: "+ includeStaticMembers);
// Console.WriteLine (resolveResult);
// Console.WriteLine ("node:" + resolvedNode);
// Console.WriteLine (currentMember != null ? currentMember.IsStatic : "currentMember == null");
if (resolvedNode.Annotation<ObjectCreateExpression> () == null) { //tags the created expression as part of an object create expression.
var lookup = new MemberLookup (ctx.CurrentTypeDefinition, Compilation.MainAssembly);
bool isProtectedAllowed = resolveResult is ThisResolveResult ? true : lookup.IsProtectedAccessAllowed (type);
var filteredList = new List<IMember> ();
foreach (var member in type.GetMembers ()) {
// Console.WriteLine ("member:" + member + member.IsShadowing);
if (!lookup.IsAccessible (member, isProtectedAllowed)) {
// Console.WriteLine ("skip access: " + member.FullName);
// Console.WriteLine ("skip access: " + member.FullName);
continue;
}
if (resolvedNode is BaseReferenceExpression && member.IsAbstract)
continue;
if (!includeStaticMembers && member.IsStatic && !(resolveResult is TypeResolveResult)) {
// Console.WriteLine ("skip static member: " + member.FullName);
bool memberIsStatic = member.IsStatic;
if (!includeStaticMembers && memberIsStatic && !(resolveResult is TypeResolveResult)) {
// Console.WriteLine ("skip static member: " + member.FullName);
continue;
}
if (!member.IsStatic && (resolveResult is TypeResolveResult)) {
// Console.WriteLine ("skip non static member: " + member.FullName);
var field = member as IField;
if (field != null)
memberIsStatic |= field.IsConst;
if (!memberIsStatic && (resolveResult is TypeResolveResult)) {
continue;
}
@ -1782,7 +1861,14 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1782,7 +1861,14 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
continue;
if (member.EntityType == EntityType.Operator)
continue;
// Console.WriteLine ("add : "+ member.FullName + " --- " + member.IsStatic);
if (member.IsShadowing)
filteredList.RemoveAll (m => m.Name == member.Name);
filteredList.Add (member);
}
foreach (var member in filteredList) {
// Console.WriteLine ("add : "+ member.FullName + " --- " + member.IsStatic);
result.AddMember (member);
}
}
@ -1793,7 +1879,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1793,7 +1879,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
} else {
foreach (var meths in state.GetAllExtensionMethods (type)) {
foreach (var meths in state.GetExtensionMethods (type)) {
foreach (var m in meths) {
result.AddMember (m);
}
@ -1865,7 +1951,12 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1865,7 +1951,12 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
if (type != null) {
// insert target type into compilation unit, to respect the
if (currentType == null) {
var tsvisitor2 = new TypeSystemConvertVisitor (this.CSharpParsedFile.FileName);
baseUnit.AcceptVisitor (tsvisitor2, null);
return Tuple.Create (tsvisitor2.ParsedFile, (AstNode)type.Target, baseUnit);
}
var target = type.Target;
target.Remove ();
var node = Unit.GetNodeAt (location) ?? Unit;
@ -1876,13 +1967,19 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1876,13 +1967,19 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (currentMember == null && currentType == null)
return null;
baseUnit = ParseStub ("a()");
baseUnit = ParseStub ("a()", false);
var curNode = baseUnit.GetNodeAt (location);
// hack for local variable declaration missing ';' issue - remove that if it works.
if (curNode is AttributedNode || baseUnit.GetNodeAt<Expression> (location) == null) {
baseUnit = ParseStub ("a()");
curNode = baseUnit.GetNodeAt (location);
}
// Hack for handle object initializer continuation expressions
if (curNode is AttributedNode || baseUnit.GetNodeAt<Expression> (location) == null) {
baseUnit = ParseStub ("a()};");
}
var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
var mref = baseUnit.GetNodeAt<MemberReferenceExpression> (location);
if (mref == null) {
@ -1944,9 +2041,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1944,9 +2041,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var baseUnit = ParseStub ("");
var tmpUnit = baseUnit;
AstNode expr = baseUnit.GetNodeAt<IdentifierExpression> (location.Line, location.Column - 1);
if (expr == null)
expr = baseUnit.GetNodeAt<Attribute> (location.Line, location.Column - 1);
if (expr == null)
expr = baseUnit.GetNodeAt<AstType> (location.Line, location.Column - 1);
// try insertStatement
if (expr == null && baseUnit.GetNodeAt<EmptyStatement> (location.Line, location.Column) != null) {
@ -1993,8 +2091,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -1993,8 +2091,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
baseUnit = tmpUnit;
}
}
if (expr == null) {
expr = tmpUnit.GetNodeAt<VariableInitializer> (location.Line, location.Column - 1);
baseUnit = tmpUnit;
@ -2012,6 +2108,14 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2012,6 +2108,14 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
expr = baseUnit.GetNodeAt<TypeParameterDeclaration> (location.Line, location.Column - 1);
}
// try expression in anonymous type "new { sample = x$" case
if (expr == null) {
baseUnit = ParseStub ("a", false);
expr = baseUnit.GetNodeAt<AnonymousTypeCreateExpression> (location.Line, location.Column);
if (expr != null)
expr = baseUnit.GetNodeAt<Expression> (location.Line, location.Column) ?? expr;
}
if (expr == null)
return null;
var member = Unit.GetNodeAt<AttributedNode> (memberLocation);
@ -2228,31 +2332,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -2228,31 +2332,6 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return parentheses != 1 || bracket > 0 ? -1 : index;
}
CSharpResolver GetState ()
{
return new CSharpResolver (ctx);
/*var state = new CSharpResolver (ctx);
state.CurrentMember = currentMember;
state.CurrentTypeDefinition = currentType;
state.CurrentUsingScope = CSharpParsedFile.GetUsingScope (location);
if (state.CurrentMember != null) {
var node = Unit.GetNodeAt (location);
if (node == null)
return state;
var navigator = new NodeListResolveVisitorNavigator (new[] { node });
var visitor = new ResolveVisitor (state, CSharpParsedFile, navigator);
Unit.AcceptVisitor (visitor, null);
try {
var newState = visitor.GetResolverStateBefore (node);
if (newState != null)
state = newState;
} catch (Exception) {
}
}
return state;*/
}
#endregion
#region Preprocessor

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

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
//
//
// CSharpCompletionEngineBase.cs
//
// Author:
@ -192,55 +192,113 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -192,55 +192,113 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var expr = Unit.GetNodeAt<PrimitiveExpression> (loc.Line, loc.Column);
return expr != null && expr.Value is string;
}
#endregion
protected CSharpResolver GetState ()
{
return new CSharpResolver (ctx);
/*var state = new CSharpResolver (ctx);
state.CurrentMember = currentMember;
state.CurrentTypeDefinition = currentType;
state.CurrentUsingScope = CSharpParsedFile.GetUsingScope (location);
if (state.CurrentMember != null) {
var node = Unit.GetNodeAt (location);
if (node == null)
return state;
var navigator = new NodeListResolveVisitorNavigator (new[] { node });
var visitor = new ResolveVisitor (state, CSharpParsedFile, navigator);
Unit.AcceptVisitor (visitor, null);
try {
var newState = visitor.GetResolverStateBefore (node);
if (newState != null)
state = newState;
} catch (Exception) {
}
}
return state;*/
}
#endregion
#region Basic parsing/resolving functions
Stack<Tuple<char, int>> GetBracketStack (string memberText)
{
var bracketStack = new Stack<Tuple<char, int>> ();
bool isInString = false, isInChar = false;
bool isInLineComment = false, isInBlockComment = false;
bool inSingleComment = false, inString = false, inVerbatimString = false, inChar = false, inMultiLineComment = false;
for (int pos = 0; pos < memberText.Length; pos++) {
char ch = memberText [pos];
for (int i = 0; i < memberText.Length; i++) {
char ch = memberText [i];
char nextCh = i + 1 < memberText.Length ? memberText [i + 1] : '\0';
switch (ch) {
case '(':
case '[':
case '{':
if (!isInString && !isInChar && !isInLineComment && !isInBlockComment)
bracketStack.Push (Tuple.Create (ch, pos));
if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
break;
bracketStack.Push (Tuple.Create (ch, i));
break;
case ')':
case ']':
case '}':
if (!isInString && !isInChar && !isInLineComment && !isInBlockComment)
if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
break;
if (bracketStack.Count > 0)
bracketStack.Pop ();
break;
case '\r':
case '\n':
isInLineComment = false;
break;
case '/':
if (isInBlockComment) {
if (pos > 0 && memberText [pos - 1] == '*')
isInBlockComment = false;
} else if (!isInString && !isInChar && pos + 1 < memberText.Length) {
char nextChar = memberText [pos + 1];
if (nextChar == '/')
isInLineComment = true;
if (!isInLineComment && nextChar == '*')
isInBlockComment = true;
if (inString || inChar || inVerbatimString)
break;
if (nextCh == '/') {
i++;
inSingleComment = true;
}
if (nextCh == '*')
inMultiLineComment = true;
break;
case '*':
if (inString || inChar || inVerbatimString || inSingleComment)
break;
if (nextCh == '/') {
i++;
inMultiLineComment = false;
}
break;
case '@':
if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
break;
if (nextCh == '"') {
i++;
inVerbatimString = true;
}
break;
case '\n':
case '\r':
inSingleComment = false;
inString = false;
inChar = false;
break;
case '\\':
if (inString || inChar)
i++;
break;
case '"':
if (!(isInChar || isInLineComment || isInBlockComment))
isInString = !isInString;
if (inSingleComment || inMultiLineComment || inChar)
break;
if (inVerbatimString) {
if (nextCh == '"') {
i++;
break;
}
inVerbatimString = false;
break;
}
inString = !inString;
break;
case '\'':
if (!(isInString || isInLineComment || isInBlockComment))
isInChar = !isInChar;
if (inSingleComment || inMultiLineComment || inString || inVerbatimString)
break;
inChar = !inChar;
break;
default :
break;
@ -336,14 +394,14 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -336,14 +394,14 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
wrapper.Append ('}');
TextLocation memberLocation;
if (currentMember != null && currentType.Kind != TypeKind.Enum) {
if (currentMember != null && currentType != null && currentType.Kind != TypeKind.Enum) {
memberLocation = currentMember.Region.Begin;
} else if (currentType != null) {
memberLocation = currentType.Region.Begin;
} else {
memberLocation = new TextLocation (1, 1);
}
using (var stream = new System.IO.StringReader (wrapper.ToString ())) {
try {
var parser = new CSharpParser ();
@ -366,7 +424,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -366,7 +424,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
protected Tuple<string, bool> GetMemberTextToCaret ()
{
int startOffset;
if (currentMember != null && currentType.Kind != TypeKind.Enum) {
if (currentMember != null && currentType != null && currentType.Kind != TypeKind.Enum) {
startOffset = document.GetOffset (currentMember.Region.BeginLine, currentMember.Region.BeginColumn);
} else if (currentType != null) {
startOffset = document.GetOffset (currentType.Region.BeginLine, currentType.Region.BeginColumn);
@ -447,14 +505,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -447,14 +505,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
// var newContent = ProjectContent.UpdateProjectContent (CSharpParsedFile, file);
var csResolver = new CSharpResolver (ctx);
var navigator = new NodeListResolveVisitorNavigator (new[] { resolveNode });
var visitor = new ResolveVisitor (csResolver, CSharpParsedFile, navigator);
var csResolver = new CSharpAstResolver(new CSharpResolver (ctx), unit, CSharpParsedFile);
visitor.Scan (unit);
var state = visitor.GetResolverStateBefore (resolveNode);
var result = visitor.GetResolveResult (resolveNode);
var result = csResolver.Resolve (resolveNode);
var state = csResolver.GetResolverStateBefore (resolveNode);
return Tuple.Create (result, state);
}

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

@ -53,11 +53,12 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -53,11 +53,12 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
CompilationUnit baseUnit;
if (currentMember == null && currentType == null)
return null;
if (Unit == null)
return null;
baseUnit = ParseStub ("x] = a[1");
var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
var mref = baseUnit.GetNodeAt (location, n => n is IndexerExpression);
Print (baseUnit);
AstNode expr;
if (mref is IndexerExpression) {
expr = ((IndexerExpression)mref).Target;
@ -67,6 +68,30 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -67,6 +68,30 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var member = Unit.GetNodeAt<AttributedNode> (memberLocation);
var member2 = baseUnit.GetNodeAt<AttributedNode> (memberLocation);
if (member == null || member2 == null)
return null;
member2.Remove ();
member.ReplaceWith (member2);
var tsvisitor = new TypeSystemConvertVisitor (CSharpParsedFile.FileName);
Unit.AcceptVisitor (tsvisitor, null);
return Tuple.Create (tsvisitor.ParsedFile, (AstNode)expr, Unit);
}
public Tuple<CSharpParsedFile, AstNode, CompilationUnit> GetTypeBeforeCursor ()
{
CompilationUnit baseUnit;
if (currentMember == null && currentType == null)
return null;
if (Unit == null)
return null;
baseUnit = ParseStub ("x> a");
var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
var expr = baseUnit.GetNodeAt<AstType> (location.Line, location.Column + 1); // '>' position
var member = Unit.GetNodeAt<AttributedNode> (memberLocation);
var member2 = baseUnit.GetNodeAt<AttributedNode> (memberLocation);
if (member == null || member2 == null)
return null;
member2.Remove ();
member.ReplaceWith (member2);
var tsvisitor = new TypeSystemConvertVisitor (CSharpParsedFile.FileName);
@ -85,13 +110,13 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -85,13 +110,13 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (IsInsideCommentOrString ())
return null;
var invoke = GetInvocationBeforeCursor (true) ?? GetIndexerBeforeCursor ();
if (invoke == null)
return null;
ResolveResult resolveResult;
switch (completionChar) {
case '(':
var invoke = GetInvocationBeforeCursor (true) ?? GetIndexerBeforeCursor ();
if (invoke == null)
return null;
if (invoke.Item2 is ObjectCreateExpression) {
var createType = ResolveExpression (invoke.Item1, ((ObjectCreateExpression)invoke.Item2).Type, invoke.Item3);
return factory.CreateConstructorProvider (createType.Item1.Type);
@ -131,6 +156,18 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -131,6 +156,18 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
// }
break;
case ',':
invoke = GetInvocationBeforeCursor (true) ?? GetIndexerBeforeCursor ();
if (invoke == null) {
invoke = GetTypeBeforeCursor ();
if (invoke !=null) {
var typeExpression = ResolveExpression (invoke.Item1, invoke.Item2, invoke.Item3);
if (typeExpression == null || typeExpression.Item1 == null || typeExpression.Item1.IsError)
return null;
return factory.CreateTypeParameterDataProvider (CollectAllTypes (typeExpression.Item1.Type));
}
return null;
}
if (invoke.Item2 is ObjectCreateExpression) {
var createType = ResolveExpression (invoke.Item1, ((ObjectCreateExpression)invoke.Item2).Type, invoke.Item3);
return factory.CreateConstructorProvider (createType.Item1.Type);
@ -161,12 +198,19 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -161,12 +198,19 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (resolveResult != null)
return factory.CreateIndexerParameterDataProvider (resolveResult.Type, invoke.Item2);
break;
// case '<':
// if (string.IsNullOrEmpty (result.Expression))
// return null;
// return new NRefactoryTemplateParameterDataProvider (textEditorData, resolver, GetUsedNamespaces (), result, new TextLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
case '<':
invoke = GetTypeBeforeCursor ();
if (invoke == null)
return null;
var tExpr = ResolveExpression (invoke.Item1, invoke.Item2, invoke.Item3);
if (tExpr == null || tExpr.Item1 == null || tExpr.Item1.IsError)
return null;
return factory.CreateTypeParameterDataProvider (CollectAllTypes (tExpr.Item1.Type));
case '[':
invoke = GetIndexerBeforeCursor ();
if (invoke == null)
return null;
var indexerExpression = ResolveExpression (invoke.Item1, invoke.Item2, invoke.Item3);
if (indexerExpression == null || indexerExpression.Item1 == null || indexerExpression.Item1.IsError)
return null;
@ -175,6 +219,24 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -175,6 +219,24 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
return null;
}
IEnumerable<IType> CollectAllTypes (IType baseType)
{
var state = GetState ();
for (var n = state.CurrentUsingScope; n != null; n = n.Parent) {
foreach (var u in n.Usings) {
foreach (var type in u.Types) {
if (type.TypeParameterCount > 0 && type.Name == baseType.Name)
yield return type;
}
}
foreach (var type in n.Namespace.Types) {
if (type.TypeParameterCount > 0 && type.Name == baseType.Name)
yield return type;
}
}
}
List<string> GetUsedNamespaces ()
{
var scope = CSharpParsedFile.GetUsingScope (location);
@ -198,7 +260,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -198,7 +260,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
{
SetOffset (triggerOffset);
var text = GetMemberTextToCaret ();
if (text.Item1.EndsWith ("("))
if (text.Item1.EndsWith ("(") || text.Item1.EndsWith ("<"))
return 0;
var parameter = new Stack<int> ();
@ -220,6 +282,17 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -220,6 +282,17 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (parameter.Count > 0)
parameter.Pop ();
break;
case '<':
if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
break;
parameter.Push (0);
break;
case '>':
if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
break;
if (parameter.Count > 0)
parameter.Pop ();
break;
case ',':
if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
break;

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

@ -63,6 +63,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -63,6 +63,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
ICompletionData CreateEventCreationCompletionData (string varName, IType delegateType, IEvent evt, string parameterDefinition, IUnresolvedMember currentMember, IUnresolvedTypeDefinition currentType);
ICompletionData CreateNewOverrideCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IMember m);
ICompletionData CreateNewPartialCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IUnresolvedMember m);
IEnumerable<ICompletionData> CreateCodeTemplateCompletionData ();

3
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Completion/IParameterCompletionDataFactory.cs

@ -27,6 +27,7 @@ using System; @@ -27,6 +27,7 @@ using System;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Completion;
using ICSharpCode.NRefactory.CSharp.Resolver;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.CSharp.Completion
{
@ -41,6 +42,8 @@ namespace ICSharpCode.NRefactory.CSharp.Completion @@ -41,6 +42,8 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
IParameterDataProvider CreateDelegateDataProvider (IType type);
IParameterDataProvider CreateIndexerParameterDataProvider (IType type, AstNode resolvedNode);
IParameterDataProvider CreateTypeParameterDataProvider (IEnumerable<IType> types);
}
}

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

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup>
<ProjectGuid>{53DCA265-3C3C-42F9-B647-F72BA678122B}</ProjectGuid>
@ -45,9 +45,6 @@ @@ -45,9 +45,6 @@
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE;FULL_AST</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
@ -61,6 +58,7 @@ @@ -61,6 +58,7 @@
<ItemGroup>
<Compile Include="Analysis\ControlFlow.cs" />
<Compile Include="Analysis\DefiniteAssignmentAnalysis.cs" />
<Compile Include="Analysis\ReachabilityAnalysis.cs" />
<Compile Include="Ast\AstNode.cs" />
<Compile Include="Ast\AstNodeCollection.cs" />
<Compile Include="Ast\AstType.cs" />
@ -201,7 +199,6 @@ @@ -201,7 +199,6 @@
<Compile Include="Parser\mcs\cs-tokenizer.cs" />
<Compile Include="Parser\mcs\decl.cs" />
<Compile Include="Parser\mcs\delegate.cs" />
<Compile Include="Parser\mcs\doc-bootstrap.cs" />
<Compile Include="Parser\mcs\doc.cs" />
<Compile Include="Parser\mcs\driver.cs" />
<Compile Include="Parser\mcs\dynamic.cs" />
@ -212,7 +209,6 @@ @@ -212,7 +209,6 @@
<Compile Include="Parser\mcs\field.cs" />
<Compile Include="Parser\mcs\flowanalysis.cs" />
<Compile Include="Parser\mcs\generic.cs" />
<Compile Include="Parser\mcs\hosting.cs" />
<Compile Include="Parser\mcs\import.cs" />
<Compile Include="Parser\mcs\iterators.cs" />
<Compile Include="Parser\mcs\lambda.cs" />
@ -233,8 +229,6 @@ @@ -233,8 +229,6 @@
<Compile Include="Parser\mcs\property.cs" />
<Compile Include="Parser\mcs\reflection.cs" />
<Compile Include="Parser\mcs\report.cs" />
<Compile Include="Parser\mcs\rootcontext.cs" />
<Compile Include="Parser\mcs\roottypes.cs" />
<Compile Include="Parser\mcs\statement.cs" />
<Compile Include="Parser\mcs\support.cs" />
<Compile Include="Parser\mcs\symbolwriter.cs" />
@ -296,10 +290,10 @@ @@ -296,10 +290,10 @@
<Compile Include="Resolver\OverloadResolutionErrors.cs" />
<Compile Include="Resolver\ResolveAtLocation.cs" />
<Compile Include="Resolver\ResolveVisitor.cs" />
<Compile Include="Resolver\SimpleNameLookupMode.cs" />
<Compile Include="Resolver\TypeInference.cs" />
<Compile Include="Completion\ICompletionDataFactory.cs" />
<Compile Include="Completion\IParameterCompletionDataFactory.cs" />
<Compile Include="SimpleNameLookupMode.cs" />
<Compile Include="TypeSystem\AliasNamespaceReference.cs" />
<Compile Include="TypeSystem\AttributeTypeReference.cs" />
<Compile Include="TypeSystem\ConstantValues.cs" />
@ -322,6 +316,8 @@ @@ -322,6 +316,8 @@
<Compile Include="Completion\CSharpCompletionEngineBase.cs" />
<Compile Include="Completion\CSharpParameterCompletionEngine.cs" />
<Compile Include="Completion\IMemberProvider.cs" />
<Compile Include="Parser\mcs\module.cs" />
<Compile Include="Parser\mcs\settings.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj">

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

@ -77,38 +77,6 @@ namespace ICSharpCode.NRefactory.CSharp @@ -77,38 +77,6 @@ namespace ICSharpCode.NRefactory.CSharp
}
#region StartNode/EndNode
public event EventHandler<AstNodeEventArgs> OutputStarted;
protected virtual void OnOutputStarted (AstNodeEventArgs e)
{
EventHandler<AstNodeEventArgs> handler = this.OutputStarted;
if (handler != null)
handler (this, e);
}
public event EventHandler<AstNodeEventArgs> OutputFinished;
protected virtual void OnOutputFinished (AstNodeEventArgs e)
{
EventHandler<AstNodeEventArgs> handler = this.OutputFinished;
if (handler != null)
handler (this, e);
}
[Serializable]
public sealed class AstNodeEventArgs : EventArgs
{
public AstNode AstNode {
get;
private set;
}
public AstNodeEventArgs (AstNode node)
{
this.AstNode = node;
}
}
void StartNode (AstNode node)
{
// Ensure that nodes are visited in the proper nested order.
@ -118,7 +86,6 @@ namespace ICSharpCode.NRefactory.CSharp @@ -118,7 +86,6 @@ namespace ICSharpCode.NRefactory.CSharp
WriteSpecialsUpToNode (node);
containerStack.Push (node);
positionStack.Push (node.FirstChild);
OnOutputStarted (new AstNodeEventArgs (node));
formatter.StartNode (node);
}
@ -129,7 +96,6 @@ namespace ICSharpCode.NRefactory.CSharp @@ -129,7 +96,6 @@ namespace ICSharpCode.NRefactory.CSharp
Debug.Assert (pos == null || pos.Parent == node);
WriteSpecials (pos, null);
containerStack.Pop ();
OnOutputFinished (new AstNodeEventArgs (node));
formatter.EndNode (node);
return null;
}

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

@ -1232,13 +1232,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1232,13 +1232,12 @@ namespace ICSharpCode.NRefactory.CSharp
CodeObject IAstVisitor<object, CodeObject>.VisitPrimitiveType(PrimitiveType primitiveType, object data)
{
string keyword = primitiveType.Keyword;
KnownTypeCode typeCode = TypeSystemConvertVisitor.GetTypeCodeForPrimitiveType(keyword);
KnownTypeCode typeCode = primitiveType.KnownTypeCode;
if (typeCode != KnownTypeCode.None) {
KnownTypeReference ktr = KnownTypeReference.Get(typeCode);
return new CodeTypeReference(ktr.Namespace + "." + ktr.Name);
}
return new CodeTypeReference(keyword);
return new CodeTypeReference(primitiveType.Keyword);
}
CodeObject IAstVisitor<object, CodeObject>.VisitComment (Comment comment, object data)

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

@ -29,6 +29,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -29,6 +29,7 @@ namespace ICSharpCode.NRefactory.CSharp
readonly TextWriter textWriter;
int indentation;
bool needsIndent = true;
bool isAtStartOfLine = true;
public int Indentation {
get {
@ -53,18 +54,21 @@ namespace ICSharpCode.NRefactory.CSharp @@ -53,18 +54,21 @@ namespace ICSharpCode.NRefactory.CSharp
{
WriteIndentation();
textWriter.Write(ident);
isAtStartOfLine = false;
}
public void WriteKeyword(string keyword)
{
WriteIndentation();
textWriter.Write(keyword);
isAtStartOfLine = false;
}
public void WriteToken(string token)
{
WriteIndentation();
textWriter.Write(token);
isAtStartOfLine = false;
}
public void Space()
@ -75,7 +79,6 @@ namespace ICSharpCode.NRefactory.CSharp @@ -75,7 +79,6 @@ namespace ICSharpCode.NRefactory.CSharp
public void OpenBrace(BraceStyle style)
{
bool isAtStartOfLine = needsIndent;
switch (style) {
case BraceStyle.DoNotChange:
case BraceStyle.EndOfLine:
@ -125,16 +128,19 @@ namespace ICSharpCode.NRefactory.CSharp @@ -125,16 +128,19 @@ namespace ICSharpCode.NRefactory.CSharp
Unindent();
WriteIndentation();
textWriter.Write('}');
isAtStartOfLine = false;
break;
case BraceStyle.NextLineShifted:
WriteIndentation();
textWriter.Write('}');
isAtStartOfLine = false;
Unindent();
break;
case BraceStyle.NextLineShifted2:
Unindent();
WriteIndentation();
textWriter.Write('}');
isAtStartOfLine = false;
Unindent();
break;
default:
@ -142,7 +148,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -142,7 +148,7 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
void WriteIndentation()
protected void WriteIndentation()
{
if (needsIndent) {
needsIndent = false;
@ -156,6 +162,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -156,6 +162,7 @@ namespace ICSharpCode.NRefactory.CSharp
{
textWriter.WriteLine();
needsIndent = true;
isAtStartOfLine = true;
}
public void Indent()
@ -176,16 +183,19 @@ namespace ICSharpCode.NRefactory.CSharp @@ -176,16 +183,19 @@ namespace ICSharpCode.NRefactory.CSharp
textWriter.Write("//");
textWriter.WriteLine(content);
needsIndent = true;
isAtStartOfLine = true;
break;
case CommentType.MultiLine:
textWriter.Write("/*");
textWriter.Write(content);
textWriter.Write("*/");
isAtStartOfLine = false;
break;
case CommentType.Documentation:
textWriter.Write("///");
textWriter.WriteLine(content);
needsIndent = true;
isAtStartOfLine = true;
break;
default:
textWriter.Write(content);
@ -196,7 +206,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -196,7 +206,7 @@ namespace ICSharpCode.NRefactory.CSharp
public void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument)
{
// pre-processor directive must start on its own line
if (!needsIndent)
if (!isAtStartOfLine)
NewLine();
WriteIndentation();
textWriter.Write('#');
@ -210,6 +220,10 @@ namespace ICSharpCode.NRefactory.CSharp @@ -210,6 +220,10 @@ namespace ICSharpCode.NRefactory.CSharp
public virtual void StartNode(AstNode node)
{
// Write out the indentation, so that overrides of this method
// can rely use the current output length to identify the position of the node
// in the output.
WriteIndentation();
}
public virtual void EndNode(AstNode node)

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

@ -29,6 +29,7 @@ using System.Linq; @@ -29,6 +29,7 @@ using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Text;
using ICSharpCode.NRefactory.Editor;
using Mono.CSharp;
using ICSharpCode.NRefactory.TypeSystem;
@ -66,6 +67,60 @@ namespace ICSharpCode.NRefactory.CSharp @@ -66,6 +67,60 @@ namespace ICSharpCode.NRefactory.CSharp
return new TextLocation (loc.Row, loc.Column);
}
public override void Visit (ModuleContainer mc)
{
bool first = true;
foreach (var container in mc.Containers) {
var nspace = container as NamespaceContainer;
if (nspace == null) {
container.Accept (this);
continue;
}
NamespaceDeclaration nDecl = null;
var loc = LocationsBag.GetLocations (nspace);
if (nspace.NS != null && !string.IsNullOrEmpty (nspace.NS.Name)) {
nDecl = new NamespaceDeclaration ();
if (loc != null)
nDecl.AddChild (new CSharpTokenNode (Convert (loc[0]), "namespace".Length), NamespaceDeclaration.Roles.Keyword);
ConvertNamespaceName (nspace.RealMemberName, nDecl);
if (loc != null && loc.Count > 1)
nDecl.AddChild (new CSharpTokenNode (Convert (loc[1]), 1), NamespaceDeclaration.Roles.LBrace);
AddToNamespace (nDecl);
namespaceStack.Push (nDecl);
}
if (nspace.Usings != null) {
foreach (var us in nspace.Usings) {
us.Accept (this);
}
}
if (first) {
first = false;
AddAttributeSection (Unit, mc);
}
if (nspace.Containers != null) {
foreach (var subContainer in nspace.Containers) {
subContainer.Accept (this);
}
}
if (nDecl != null) {
AddAttributeSection (nDecl, nspace.UnattachedAttributes, AttributedNode.UnattachedAttributeRole);
if (loc != null && loc.Count > 2)
nDecl.AddChild (new CSharpTokenNode (Convert (loc[2]), 1), NamespaceDeclaration.Roles.RBrace);
if (loc != null && loc.Count > 3)
nDecl.AddChild (new CSharpTokenNode (Convert (loc[3]), 1), NamespaceDeclaration.Roles.Semicolon);
namespaceStack.Pop ();
} else {
AddAttributeSection (unit, nspace.UnattachedAttributes, AttributedNode.UnattachedAttributeRole);
}
}
AddAttributeSection (unit, mc.UnattachedAttributes, AttributedNode.UnattachedAttributeRole);
}
#region Global
Stack<NamespaceDeclaration> namespaceStack = new Stack<NamespaceDeclaration> ();
@ -197,12 +252,10 @@ namespace ICSharpCode.NRefactory.CSharp @@ -197,12 +252,10 @@ namespace ICSharpCode.NRefactory.CSharp
return new PrimitiveType ("new", Convert (sce.Location));
}
}
System.Console.WriteLine ("Error while converting :" + typeName + " - unknown type name");
System.Console.WriteLine (Environment.StackTrace);
return new SimpleType ("unknown");
}
IEnumerable<Attribute> GetAttributes (List<Mono.CSharp.Attribute> optAttributes)
IEnumerable<Attribute> GetAttributes (IEnumerable<Mono.CSharp.Attribute> optAttributes)
{
if (optAttributes == null)
yield break;
@ -225,10 +278,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -225,10 +278,12 @@ namespace ICSharpCode.NRefactory.CSharp
var argLoc = LocationsBag.GetLocations (na);
if (argLoc != null)
newArg.AddChild (new CSharpTokenNode (Convert (argLoc [0]), 1), NamedArgumentExpression.Roles.Colon);
newArg.AddChild ((Expression)na.Expr.Accept (this), NamedExpression.Roles.Expression);
if (na.Expr != null)
newArg.AddChild ((Expression)na.Expr.Accept (this), NamedExpression.Roles.Expression);
result.AddChild (newArg, Attribute.Roles.Argument);
} else {
result.AddChild ((Expression)arg.Expr.Accept (this), Attribute.Roles.Argument);
if (arg.Expr != null)
result.AddChild ((Expression)arg.Expr.Accept (this), Attribute.Roles.Argument);
}
if (loc != null && pos + 1 < loc.Count)
result.AddChild (new CSharpTokenNode (Convert (loc [pos++]), 1), AttributeSection.Roles.Comma);
@ -242,7 +297,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -242,7 +297,8 @@ namespace ICSharpCode.NRefactory.CSharp
var argLoc = LocationsBag.GetLocations (na);
if (argLoc != null)
newArg.AddChild (new CSharpTokenNode (Convert (argLoc[0]), 1), NamedExpression.Roles.Assign);
newArg.AddChild ((Expression)na.Expr.Accept (this), NamedExpression.Roles.Expression);
if (na.Expr != null)
newArg.AddChild ((Expression)na.Expr.Accept (this), NamedExpression.Roles.Expression);
result.AddChild (newArg, Attribute.Roles.Argument);
if (loc != null && pos + 1 < loc.Count)
result.AddChild (new CSharpTokenNode (Convert (loc [pos++]), 1), AttributeSection.Roles.Comma);
@ -255,7 +311,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -255,7 +311,7 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
AttributeSection ConvertAttributeSection (List<Mono.CSharp.Attribute> optAttributes)
AttributeSection ConvertAttributeSection (IEnumerable<Mono.CSharp.Attribute> optAttributes)
{
if (optAttributes == null)
return null;
@ -265,7 +321,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -265,7 +321,8 @@ namespace ICSharpCode.NRefactory.CSharp
if (loc != null)
result.AddChild (new CSharpTokenNode (Convert (loc [pos++]), 1), AttributeSection.Roles.LBracket);
string target = optAttributes.First ().ExplicitTarget;
var first = optAttributes.FirstOrDefault ();
string target = first != null ? first.ExplicitTarget : null;
if (!string.IsNullOrEmpty (target)) {
if (loc != null && pos < loc.Count - 1) {
@ -288,30 +345,54 @@ namespace ICSharpCode.NRefactory.CSharp @@ -288,30 +345,54 @@ namespace ICSharpCode.NRefactory.CSharp
return result;
}
public override void Visit (UsingsBag.Namespace nspace)
public override void Visit (NamespaceContainer nspace)
{
NamespaceDeclaration nDecl = null;
if (nspace.Name != null) {
var loc = LocationsBag.GetLocations (nspace);
if (nspace.NS != null && !string.IsNullOrEmpty (nspace.NS.Name)) {
nDecl = new NamespaceDeclaration ();
nDecl.AddChild (new CSharpTokenNode (Convert (nspace.NamespaceLocation), "namespace".Length), NamespaceDeclaration.Roles.Keyword);
ConvertNamespaceName (nspace.Name, nDecl);
nDecl.AddChild (new CSharpTokenNode (Convert (nspace.OpenBrace), 1), NamespaceDeclaration.Roles.LBrace);
if (loc != null)
nDecl.AddChild (new CSharpTokenNode (Convert (loc[0]), "namespace".Length), NamespaceDeclaration.Roles.Keyword);
ConvertNamespaceName (nspace.RealMemberName, nDecl);
if (loc != null && loc.Count > 1)
nDecl.AddChild (new CSharpTokenNode (Convert (loc[1]), 1), NamespaceDeclaration.Roles.LBrace);
AddToNamespace (nDecl);
namespaceStack.Push (nDecl);
}
VisitNamespaceUsings (nspace);
VisitNamespaceBody (nspace);
if (nspace.Usings != null) {
foreach (var us in nspace.Usings) {
us.Accept (this);
}
}
if (nspace.Containers != null) {
foreach (var container in nspace.Containers) {
container.Accept (this);
}
}
if (nDecl != null) {
nDecl.AddChild (new CSharpTokenNode (Convert (nspace.CloseBrace), 1), NamespaceDeclaration.Roles.RBrace);
if (!nspace.OptSemicolon.IsNull)
nDecl.AddChild (new CSharpTokenNode (Convert (nspace.OptSemicolon), 1), NamespaceDeclaration.Roles.Semicolon);
AddAttributeSection (nDecl, nspace.UnattachedAttributes, AttributedNode.UnattachedAttributeRole);
if (loc != null && loc.Count > 2)
nDecl.AddChild (new CSharpTokenNode (Convert (loc[2]), 1), NamespaceDeclaration.Roles.RBrace);
if (loc != null && loc.Count > 3)
nDecl.AddChild (new CSharpTokenNode (Convert (loc[3]), 1), NamespaceDeclaration.Roles.Semicolon);
namespaceStack.Pop ();
}
}
// public override void Visit (UsingsBag.Namespace nspace)
// {
//
//
// VisitNamespaceUsings (nspace);
// VisitNamespaceBody (nspace);
//
// }
//
void ConvertNamespaceName (MemberName memberName, NamespaceDeclaration namespaceDecl)
{
AstNode insertPos = null;
@ -330,35 +411,46 @@ namespace ICSharpCode.NRefactory.CSharp @@ -330,35 +411,46 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
public override void Visit (UsingsBag.Using u)
{
UsingDeclaration ud = new UsingDeclaration ();
ud.AddChild (new CSharpTokenNode (Convert (u.UsingLocation), "using".Length), UsingDeclaration.Roles.Keyword);
ud.AddChild (ConvertToType (u.NSpace), UsingDeclaration.ImportRole);
ud.AddChild (new CSharpTokenNode (Convert (u.SemicolonLocation), 1), UsingDeclaration.Roles.Semicolon);
AddToNamespace (ud);
}
public override void Visit (UsingsBag.AliasUsing u)
{
UsingAliasDeclaration ud = new UsingAliasDeclaration ();
ud.AddChild (new CSharpTokenNode (Convert (u.UsingLocation), "using".Length), UsingAliasDeclaration.Roles.Keyword);
ud.AddChild (Identifier.Create (u.Identifier.Value, Convert (u.Identifier.Location)), UsingAliasDeclaration.AliasRole);
ud.AddChild (new CSharpTokenNode (Convert (u.AssignLocation), 1), UsingAliasDeclaration.Roles.Assign);
ud.AddChild (ConvertToType (u.Nspace), UsingAliasDeclaration.ImportRole);
ud.AddChild (new CSharpTokenNode (Convert (u.SemicolonLocation), 1), UsingAliasDeclaration.Roles.Semicolon);
AddToNamespace (ud);
}
public override void Visit (UsingNamespace un)
{
var ud = new UsingDeclaration ();
var loc = LocationsBag.GetLocations (un);
ud.AddChild (new CSharpTokenNode (Convert (un.Location), "using".Length), UsingDeclaration.Roles.Keyword);
if (un.NamespaceExpression != null)
ud.AddChild (ConvertToType (un.NamespaceExpression), UsingDeclaration.ImportRole);
if (loc != null)
ud.AddChild (new CSharpTokenNode (Convert (loc[0]), 1), UsingDeclaration.Roles.Semicolon);
AddToNamespace (ud);
}
public override void Visit (UsingsBag.ExternAlias u)
{
var ud = new ExternAliasDeclaration ();
ud.AddChild (new CSharpTokenNode (Convert (u.ExternLocation), "extern".Length), ExternAliasDeclaration.Roles.Keyword);
ud.AddChild (new CSharpTokenNode (Convert (u.AliasLocation), "alias".Length), ExternAliasDeclaration.AliasRole);
ud.AddChild (Identifier.Create (u.Identifier.Value, Convert (u.Identifier.Location)), ExternAliasDeclaration.Roles.Identifier);
ud.AddChild (new CSharpTokenNode (Convert (u.SemicolonLocation), 1), UsingAliasDeclaration.Roles.Semicolon);
AddToNamespace (ud);
}
public override void Visit (UsingAliasNamespace uan)
{
var ud = new UsingAliasDeclaration ();
var loc = LocationsBag.GetLocations (uan);
ud.AddChild (new CSharpTokenNode (Convert (uan.Location), "using".Length), UsingAliasDeclaration.Roles.Keyword);
ud.AddChild (Identifier.Create (uan.Alias.Value, Convert (uan.Alias.Location)), UsingAliasDeclaration.AliasRole);
if (loc != null)
ud.AddChild (new CSharpTokenNode (Convert (loc[0]), 1), UsingAliasDeclaration.Roles.Assign);
if (uan.NamespaceExpression != null)
ud.AddChild (ConvertToType (uan.NamespaceExpression), UsingAliasDeclaration.ImportRole);
if (loc != null && loc.Count > 1)
ud.AddChild (new CSharpTokenNode (Convert (loc[1]), 1), UsingAliasDeclaration.Roles.Semicolon);
AddToNamespace (ud);
}
public override void Visit (UsingExternAlias uea)
{
var ud = new ExternAliasDeclaration ();
var loc = LocationsBag.GetLocations (uea);
ud.AddChild (new CSharpTokenNode (Convert (uea.Location), "extern".Length), ExternAliasDeclaration.Roles.Keyword);
if (loc != null)
ud.AddChild (new CSharpTokenNode (Convert (loc[0]), "alias".Length), ExternAliasDeclaration.AliasRole);
ud.AddChild (Identifier.Create (uea.Alias.Value, Convert (uea.Alias.Location)), ExternAliasDeclaration.Roles.Identifier);
if (loc != null && loc.Count > 1)
ud.AddChild (new CSharpTokenNode (Convert (loc[1]), 1), UsingAliasDeclaration.Roles.Semicolon);
AddToNamespace (ud);
}
AstType ConvertImport (MemberName memberName)
{
@ -425,11 +517,13 @@ namespace ICSharpCode.NRefactory.CSharp @@ -425,11 +517,13 @@ namespace ICSharpCode.NRefactory.CSharp
newType.AddChild (new CSharpTokenNode (Convert (location[curLoc++]), 1), AstNode.Roles.LBrace);
typeStack.Push (newType);
base.Visit (c);
AddAttributeSection (newType, c.UnattachedAttributes, AttributedNode.UnattachedAttributeRole);
if (location != null && curLoc < location.Count) {
newType.AddChild (new CSharpTokenNode (Convert (location[curLoc++]), 1), AstNode.Roles.RBrace);
if (c.HasOptionalSemicolon)
newType.AddChild (new CSharpTokenNode (Convert (c.OptionalSemicolon), 1), AstNode.Roles.Semicolon);
if (location != null && curLoc < location.Count)
newType.AddChild (new CSharpTokenNode (Convert (location[curLoc++]), 1), AstNode.Roles.Semicolon);
} else {
// parser error, set end node to max value.
@ -474,8 +568,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -474,8 +568,8 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null && location.Count > 2) {
if (location != null && curLoc < location.Count)
newType.AddChild (new CSharpTokenNode (Convert (location[curLoc++]), 1), AstNode.Roles.RBrace);
if (s.HasOptionalSemicolon)
newType.AddChild (new CSharpTokenNode (Convert (s.OptionalSemicolon), 1), AstNode.Roles.Semicolon);
if (location != null && curLoc < location.Count)
newType.AddChild (new CSharpTokenNode (Convert (location[curLoc++]), 1), AstNode.Roles.Semicolon);
} else {
// parser error, set end node to max value.
newType.AddChild (new ErrorNode (), AstNode.Roles.Error);
@ -519,8 +613,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -519,8 +613,8 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null && location.Count > 2) {
if (location != null && curLoc < location.Count)
newType.AddChild (new CSharpTokenNode (Convert (location[curLoc++]), 1), AstNode.Roles.RBrace);
if (i.HasOptionalSemicolon)
newType.AddChild (new CSharpTokenNode (Convert (i.OptionalSemicolon), 1), AstNode.Roles.Semicolon);
if (location != null && curLoc < location.Count)
newType.AddChild (new CSharpTokenNode (Convert (location[curLoc++]), 1), AstNode.Roles.Semicolon);
} else {
// parser error, set end node to max value.
newType.AddChild (new ErrorNode (), AstNode.Roles.Error);
@ -596,7 +690,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -596,7 +690,7 @@ namespace ICSharpCode.NRefactory.CSharp
newType.AddChild (new CSharpTokenNode (Convert (location[curLoc++]), 1), AstNode.Roles.LBrace);
typeStack.Push (newType);
foreach (EnumMember member in e.OrderedAllMembers) {
foreach (EnumMember member in e.Members) {
Visit (member);
if (location != null && curLoc < location.Count - 1) //last one is closing brace
newType.AddChild (new CSharpTokenNode (Convert (location[curLoc++]), 1), AstNode.Roles.Comma);
@ -605,9 +699,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -605,9 +699,8 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null && location.Count > 2) {
if (location != null && curLoc < location.Count)
newType.AddChild (new CSharpTokenNode (Convert (location[curLoc++]), 1), AstNode.Roles.RBrace);
if (e.HasOptionalSemicolon)
newType.AddChild (new CSharpTokenNode (Convert (e.OptionalSemicolon), 1), AstNode.Roles.Semicolon);
if (location != null && curLoc < location.Count)
newType.AddChild (new CSharpTokenNode (Convert (location[curLoc++]), 1), AstNode.Roles.Semicolon);
} else {
// parser error, set end node to max value.
newType.AddChild (new ErrorNode (), AstNode.Roles.Error);
@ -819,7 +912,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -819,7 +912,7 @@ namespace ICSharpCode.NRefactory.CSharp
AddAttributeSection (parent, a.OptAttributes);
}
public void AddAttributeSection (AstNode parent, Attributes attrs)
public void AddAttributeSection (AstNode parent, Attributes attrs, Role role)
{
if (attrs == null)
return;
@ -827,6 +920,10 @@ namespace ICSharpCode.NRefactory.CSharp @@ -827,6 +920,10 @@ namespace ICSharpCode.NRefactory.CSharp
parent.AddChild (ConvertAttributeSection (attr), AttributedNode.AttributeRole);
}
}
public void AddAttributeSection (AstNode parent, Attributes attrs)
{
AddAttributeSection (parent, attrs, AttributedNode.AttributeRole);
}
public override void Visit (Indexer indexer)
{
@ -969,6 +1066,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -969,6 +1066,7 @@ namespace ICSharpCode.NRefactory.CSharp
keywordTable [(int)BuiltinTypeSpec.Type.SByte] = "sbyte";
keywordTable [(int)BuiltinTypeSpec.Type.Decimal] = "decimal";
keywordTable [(int)BuiltinTypeSpec.Type.Char] = "char";
keywordTable [(int)BuiltinTypeSpec.Type.Bool] = "bool";
}
void AddModifiers (AttributedNode parent, LocationsBag.MemberLocations location)
@ -1342,7 +1440,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1342,7 +1440,8 @@ namespace ICSharpCode.NRefactory.CSharp
result.AddChild (new CSharpTokenNode (Convert (ifStatement.loc), "if".Length), IfElseStatement.IfKeywordRole);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), IfElseStatement.Roles.LPar);
result.AddChild ((Expression)ifStatement.Expr.Accept (this), IfElseStatement.Roles.Condition);
if (ifStatement.Expr != null)
result.AddChild ((Expression)ifStatement.Expr.Accept (this), IfElseStatement.Roles.Condition);
if (location != null && location.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), IfElseStatement.Roles.RPar);
@ -1363,7 +1462,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1363,7 +1462,8 @@ namespace ICSharpCode.NRefactory.CSharp
var result = new DoWhileStatement ();
var location = LocationsBag.GetLocations (doStatement);
result.AddChild (new CSharpTokenNode (Convert (doStatement.loc), "do".Length), DoWhileStatement.DoKeywordRole);
result.AddChild ((Statement)doStatement.EmbeddedStatement.Accept (this), WhileStatement.Roles.EmbeddedStatement);
if (doStatement.EmbeddedStatement != null)
result.AddChild ((Statement)doStatement.EmbeddedStatement.Accept (this), WhileStatement.Roles.EmbeddedStatement);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), "while".Length), DoWhileStatement.WhileKeywordRole);
if (location != null && location.Count > 1)
@ -1534,7 +1634,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1534,7 +1634,8 @@ namespace ICSharpCode.NRefactory.CSharp
var location = LocationsBag.GetLocations (gotoCase);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), "case".Length), GotoCaseStatement.CaseKeywordRole);
result.AddChild ((Expression)gotoCase.Expr.Accept (this), GotoCaseStatement.Roles.Expression);
if (gotoCase.Expr != null)
result.AddChild ((Expression)gotoCase.Expr.Accept (this), GotoCaseStatement.Roles.Expression);
if (location != null && location.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), GotoCaseStatement.Roles.Semicolon);
return result;
@ -1598,10 +1699,27 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1598,10 +1699,27 @@ namespace ICSharpCode.NRefactory.CSharp
if (u.Variables.Initializer != null)
initializer.Initializer = u.Variables.Initializer.Accept (this) as Expression;
var varDec = new VariableDeclarationStatement () {
Type = ConvertToType (u.Variables.TypeExpression),
Variables = { initializer }
};
if (u.Variables.Declarators != null) {
foreach (var decl in u.Variables.Declarators) {
var declLoc = LocationsBag.GetLocations (decl);
var init = new VariableInitializer ();
if (declLoc != null && declLoc.Count > 0)
varDec.AddChild (new CSharpTokenNode (Convert (declLoc [0]), 1), VariableInitializer.Roles.Comma);
init.AddChild (Identifier.Create (decl.Variable.Name, Convert (decl.Variable.Location)), VariableInitializer.Roles.Identifier);
if (decl.Initializer != null) {
if (declLoc != null && declLoc.Count > 1)
init.AddChild (new CSharpTokenNode (Convert (declLoc [1]), 1), VariableInitializer.Roles.Assign);
init.AddChild ((Expression)decl.Initializer.Accept (this), VariableInitializer.Roles.Expression);
}
varDec.AddChild (init, UsingStatement.Roles.Variable);
}
}
usingResult.AddChild (varDec, UsingStatement.ResourceAcquisitionRole);
}
cur = u.Statement;
@ -1670,7 +1788,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1670,7 +1788,8 @@ namespace ICSharpCode.NRefactory.CSharp
var newLabel = new CaseLabel ();
if (caseLabel.Label != null) {
newLabel.AddChild (new CSharpTokenNode (Convert (caseLabel.Location), "case".Length), SwitchStatement.Roles.Keyword);
newLabel.AddChild ((Expression)caseLabel.Label.Accept (this), SwitchStatement.Roles.Expression);
if (caseLabel.Label != null)
newLabel.AddChild ((Expression)caseLabel.Label.Accept (this), SwitchStatement.Roles.Expression);
var colonLocation = LocationsBag.GetLocations (caseLabel);
if (colonLocation != null)
newLabel.AddChild (new CSharpTokenNode (Convert (colonLocation [0]), 1), SwitchStatement.Roles.Colon);
@ -1713,11 +1832,13 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1713,11 +1832,13 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), LockStatement.Roles.LPar);
result.AddChild ((Expression)lockStatement.Expr.Accept (this), LockStatement.Roles.Expression);
if (lockStatement.Expr != null)
result.AddChild ((Expression)lockStatement.Expr.Accept (this), LockStatement.Roles.Expression);
if (location != null && location.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), LockStatement.Roles.RPar);
result.AddChild ((Statement)lockStatement.Statement.Accept (this), LockStatement.Roles.EmbeddedStatement);
if (lockStatement.Statement != null)
result.AddChild ((Statement)lockStatement.Statement.Accept (this), LockStatement.Roles.EmbeddedStatement);
return result;
}
@ -1726,7 +1847,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1726,7 +1847,8 @@ namespace ICSharpCode.NRefactory.CSharp
{
var result = new UncheckedStatement ();
result.AddChild (new CSharpTokenNode (Convert (uncheckedStatement.loc), "unchecked".Length), UncheckedStatement.Roles.Keyword);
result.AddChild ((BlockStatement)uncheckedStatement.Block.Accept (this), UncheckedStatement.Roles.Body);
if (uncheckedStatement.Block != null)
result.AddChild ((BlockStatement)uncheckedStatement.Block.Accept (this), UncheckedStatement.Roles.Body);
return result;
}
@ -1735,7 +1857,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1735,7 +1857,8 @@ namespace ICSharpCode.NRefactory.CSharp
{
var result = new CheckedStatement ();
result.AddChild (new CSharpTokenNode (Convert (checkedStatement.loc), "checked".Length), CheckedStatement.Roles.Keyword);
result.AddChild ((BlockStatement)checkedStatement.Block.Accept (this), CheckedStatement.Roles.Body);
if (checkedStatement.Block != null)
result.AddChild ((BlockStatement)checkedStatement.Block.Accept (this), CheckedStatement.Roles.Body);
return result;
}
@ -1743,7 +1866,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1743,7 +1866,8 @@ namespace ICSharpCode.NRefactory.CSharp
{
var result = new UnsafeStatement ();
result.AddChild (new CSharpTokenNode (Convert (unsafeStatement.loc), "unsafe".Length), UnsafeStatement.Roles.Keyword);
result.AddChild ((BlockStatement)unsafeStatement.Block.Accept (this), UnsafeStatement.Roles.Body);
if (unsafeStatement.Block != null)
result.AddChild ((BlockStatement)unsafeStatement.Block.Accept (this), UnsafeStatement.Roles.Body);
return result;
}
@ -1779,7 +1903,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1779,7 +1903,7 @@ namespace ICSharpCode.NRefactory.CSharp
init.AddChild (Identifier.Create (decl.Variable.Name, Convert (decl.Variable.Location)), VariableInitializer.Roles.Identifier);
if (decl.Initializer != null) {
if (loc != null && loc.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (loc [1]), 1), VariableInitializer.Roles.Assign);
init.AddChild (new CSharpTokenNode (Convert (loc [1]), 1), VariableInitializer.Roles.Assign);
init.AddChild ((Expression)decl.Initializer.Accept (this), VariableInitializer.Roles.Expression);
} else {
}
@ -1790,7 +1914,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1790,7 +1914,8 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null && location.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), FixedStatement.Roles.RPar);
result.AddChild ((Statement)fixedStatement.Statement.Accept (this), FixedStatement.Roles.EmbeddedStatement);
if (fixedStatement.Statement != null)
result.AddChild ((Statement)fixedStatement.Statement.Accept (this), FixedStatement.Roles.EmbeddedStatement);
return result;
}
@ -1809,7 +1934,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1809,7 +1934,8 @@ namespace ICSharpCode.NRefactory.CSharp
}
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), "finally".Length), TryCatchStatement.FinallyKeywordRole);
result.AddChild ((BlockStatement)tryFinallyStatement.Fini.Accept (this), TryCatchStatement.FinallyBlockRole);
if (tryFinallyStatement.Fini != null)
result.AddChild ((BlockStatement)tryFinallyStatement.Fini.Accept (this), TryCatchStatement.FinallyBlockRole);
return result;
}
@ -1823,7 +1949,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -1823,7 +1949,8 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), CatchClause.Roles.LPar);
result.AddChild (ConvertToType (ctch.TypeExpression), CatchClause.Roles.Type);
if (ctch.TypeExpression != null)
result.AddChild (ConvertToType (ctch.TypeExpression), CatchClause.Roles.Type);
if (ctch.Variable != null && !string.IsNullOrEmpty (ctch.Variable.Name))
result.AddChild (Identifier.Create (ctch.Variable.Name, Convert (ctch.Variable.Location)), CatchClause.Roles.Identifier);
@ -2028,7 +2155,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2028,7 +2155,8 @@ namespace ICSharpCode.NRefactory.CSharp
var location = LocationsBag.GetLocations (parenthesizedExpression);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), ParenthesizedExpression.Roles.LPar);
result.AddChild ((Expression)parenthesizedExpression.Expr.Accept (this), ParenthesizedExpression.Roles.Expression);
if (parenthesizedExpression.Expr != null)
result.AddChild ((Expression)parenthesizedExpression.Expr.Accept (this), ParenthesizedExpression.Roles.Expression);
if (location != null && location.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), ParenthesizedExpression.Roles.RPar);
return result;
@ -2055,14 +2183,16 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2055,14 +2183,16 @@ namespace ICSharpCode.NRefactory.CSharp
break;
}
result.AddChild (new CSharpTokenNode (Convert (unaryExpression.Location), 1), UnaryOperatorExpression.OperatorRole);
result.AddChild ((Expression)unaryExpression.Expr.Accept (this), UnaryOperatorExpression.Roles.Expression);
if (unaryExpression.Expr != null)
result.AddChild ((Expression)unaryExpression.Expr.Accept (this), UnaryOperatorExpression.Roles.Expression);
return result;
}
public override object Visit (UnaryMutator unaryMutatorExpression)
{
var result = new UnaryOperatorExpression ();
if (unaryMutatorExpression.Expr == null)
return result;
var expression = (Expression)unaryMutatorExpression.Expr.Accept (this);
switch (unaryMutatorExpression.UnaryMutatorMode) {
case UnaryMutator.Mode.PostDecrement:
@ -2098,25 +2228,31 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2098,25 +2228,31 @@ namespace ICSharpCode.NRefactory.CSharp
var location = LocationsBag.GetLocations (indirectionExpression);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 2), UnaryOperatorExpression.OperatorRole);
result.AddChild ((Expression)indirectionExpression.Expr.Accept (this), UnaryOperatorExpression.Roles.Expression);
if (indirectionExpression.Expr != null)
result.AddChild ((Expression)indirectionExpression.Expr.Accept (this), UnaryOperatorExpression.Roles.Expression);
return result;
}
public override object Visit (Is isExpression)
{
var result = new IsExpression ();
result.AddChild ((Expression)isExpression.Expr.Accept (this), IsExpression.Roles.Expression);
if (isExpression.Expr != null)
result.AddChild ((Expression)isExpression.Expr.Accept (this), IsExpression.Roles.Expression);
result.AddChild (new CSharpTokenNode (Convert (isExpression.Location), "is".Length), IsExpression.Roles.Keyword);
result.AddChild (ConvertToType (isExpression.ProbeType), IsExpression.Roles.Type);
if (isExpression.ProbeType != null)
result.AddChild (ConvertToType (isExpression.ProbeType), IsExpression.Roles.Type);
return result;
}
public override object Visit (As asExpression)
{
var result = new AsExpression ();
result.AddChild ((Expression)asExpression.Expr.Accept (this), AsExpression.Roles.Expression);
if (asExpression.Expr != null)
result.AddChild ((Expression)asExpression.Expr.Accept (this), AsExpression.Roles.Expression);
result.AddChild (new CSharpTokenNode (Convert (asExpression.Location), "as".Length), AsExpression.Roles.Keyword);
result.AddChild (ConvertToType (asExpression.ProbeType), AsExpression.Roles.Type);
if (asExpression.ProbeType != null)
result.AddChild (ConvertToType (asExpression.ProbeType), AsExpression.Roles.Type);
return result;
}
@ -2242,9 +2378,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2242,9 +2378,11 @@ namespace ICSharpCode.NRefactory.CSharp
break;
}
result.AddChild ((Expression)binaryExpression.Left.Accept (this), BinaryOperatorExpression.LeftRole);
if (binaryExpression.Left != null)
result.AddChild ((Expression)binaryExpression.Left.Accept (this), BinaryOperatorExpression.LeftRole);
result.AddChild (new CSharpTokenNode (Convert (binaryExpression.Location), opLength), BinaryOperatorExpression.OperatorRole);
result.AddChild ((Expression)binaryExpression.Right.Accept (this), BinaryOperatorExpression.RightRole);
if (binaryExpression.Right != null)
result.AddChild ((Expression)binaryExpression.Right.Accept (this), BinaryOperatorExpression.RightRole);
return result;
}
@ -2252,9 +2390,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2252,9 +2390,11 @@ namespace ICSharpCode.NRefactory.CSharp
{
var result = new BinaryOperatorExpression ();
result.Operator = BinaryOperatorType.NullCoalescing;
result.AddChild ((Expression)nullCoalescingOperator.LeftExpression.Accept (this), BinaryOperatorExpression.LeftRole);
if (nullCoalescingOperator.LeftExpression != null)
result.AddChild ((Expression)nullCoalescingOperator.LeftExpression.Accept (this), BinaryOperatorExpression.LeftRole);
result.AddChild (new CSharpTokenNode (Convert (nullCoalescingOperator.Location), 2), BinaryOperatorExpression.OperatorRole);
result.AddChild ((Expression)nullCoalescingOperator.RightExpression.Accept (this), BinaryOperatorExpression.RightRole);
if (nullCoalescingOperator.RightExpression != null)
result.AddChild ((Expression)nullCoalescingOperator.RightExpression.Accept (this), BinaryOperatorExpression.RightRole);
return result;
}
@ -2262,14 +2402,17 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2262,14 +2402,17 @@ namespace ICSharpCode.NRefactory.CSharp
{
var result = new ConditionalExpression ();
result.AddChild ((Expression)conditionalExpression.Expr.Accept (this), ConditionalExpression.Roles.Condition);
if (conditionalExpression.Expr != null)
result.AddChild ((Expression)conditionalExpression.Expr.Accept (this), ConditionalExpression.Roles.Condition);
var location = LocationsBag.GetLocations (conditionalExpression);
result.AddChild (new CSharpTokenNode (Convert (conditionalExpression.Location), 1), ConditionalExpression.QuestionMarkRole);
result.AddChild ((Expression)conditionalExpression.TrueExpr.Accept (this), ConditionalExpression.TrueRole);
if (conditionalExpression.TrueExpr != null)
result.AddChild ((Expression)conditionalExpression.TrueExpr.Accept (this), ConditionalExpression.TrueRole);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), ConditionalExpression.ColonRole);
result.AddChild ((Expression)conditionalExpression.FalseExpr.Accept (this), ConditionalExpression.FalseRole);
if (conditionalExpression.FalseExpr != null)
result.AddChild ((Expression)conditionalExpression.FalseExpr.Accept (this), ConditionalExpression.FalseRole);
return result;
}
@ -2542,6 +2685,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2542,6 +2685,8 @@ namespace ICSharpCode.NRefactory.CSharp
if (newAnonymousType.Parameters == null)
return result;
foreach (var par in newAnonymousType.Parameters) {
if (par == null)
continue;
var location = LocationsBag.GetLocations (par);
if (location == null) {
@ -2732,7 +2877,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2732,7 +2877,7 @@ namespace ICSharpCode.NRefactory.CSharp
#region Undocumented expressions
public override object Visit (Arglist argListExpression)
{
var result = new UndocumentedExpression () { UndocumentedExpressionType = UndocumentedExpressionType.ArgListAccess };
var result = new UndocumentedExpression () { UndocumentedExpressionType = UndocumentedExpressionType.ArgList };
result.AddChild (new CSharpTokenNode (Convert (argListExpression.Location), "__arglist".Length), UndocumentedExpression.Roles.Keyword);
var location = LocationsBag.GetLocations (argListExpression);
if (location != null)
@ -2747,7 +2892,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2747,7 +2892,7 @@ namespace ICSharpCode.NRefactory.CSharp
public override object Visit (MakeRefExpr makeRefExpr)
{
var result = new UndocumentedExpression () { UndocumentedExpressionType = UndocumentedExpressionType.RefValue };
var result = new UndocumentedExpression () { UndocumentedExpressionType = UndocumentedExpressionType.MakeRef };
result.AddChild (new CSharpTokenNode (Convert (makeRefExpr.Location), "__makeref".Length), UndocumentedExpression.Roles.Keyword);
var location = LocationsBag.GetLocations (makeRefExpr);
if (location != null)
@ -2761,7 +2906,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2761,7 +2906,7 @@ namespace ICSharpCode.NRefactory.CSharp
public override object Visit (RefTypeExpr refTypeExpr)
{
var result = new UndocumentedExpression () { UndocumentedExpressionType = UndocumentedExpressionType.RefValue };
var result = new UndocumentedExpression () { UndocumentedExpressionType = UndocumentedExpressionType.RefType };
result.AddChild (new CSharpTokenNode (Convert (refTypeExpr.Location), "__reftype".Length), UndocumentedExpression.Roles.Keyword);
var location = LocationsBag.GetLocations (refTypeExpr);
if (location != null)
@ -2803,7 +2948,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2803,7 +2948,8 @@ namespace ICSharpCode.NRefactory.CSharp
result.AddChild (new CSharpTokenNode (Convert (typeOfExpression.Location), "typeof".Length), TypeOfExpression.Roles.Keyword);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), TypeOfExpression.Roles.LPar);
result.AddChild (ConvertToType (typeOfExpression.TypeExpression), TypeOfExpression.Roles.Type);
if (typeOfExpression.TypeExpression != null)
result.AddChild (ConvertToType (typeOfExpression.TypeExpression), TypeOfExpression.Roles.Type);
if (location != null && location.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), TypeOfExpression.Roles.RPar);
return result;
@ -2816,7 +2962,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2816,7 +2962,8 @@ namespace ICSharpCode.NRefactory.CSharp
result.AddChild (new CSharpTokenNode (Convert (sizeOfExpression.Location), "sizeof".Length), TypeOfExpression.Roles.Keyword);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), TypeOfExpression.Roles.LPar);
result.AddChild (ConvertToType (sizeOfExpression.TypeExpression), TypeOfExpression.Roles.Type);
if (sizeOfExpression.TypeExpression != null)
result.AddChild (ConvertToType (sizeOfExpression.TypeExpression), TypeOfExpression.Roles.Type);
if (location != null && location.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), TypeOfExpression.Roles.RPar);
return result;
@ -2829,7 +2976,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2829,7 +2976,8 @@ namespace ICSharpCode.NRefactory.CSharp
result.AddChild (new CSharpTokenNode (Convert (checkedExpression.Location), "checked".Length), TypeOfExpression.Roles.Keyword);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), TypeOfExpression.Roles.LPar);
result.AddChild ((Expression)checkedExpression.Expr.Accept (this), TypeOfExpression.Roles.Expression);
if (checkedExpression.Expr != null)
result.AddChild ((Expression)checkedExpression.Expr.Accept (this), TypeOfExpression.Roles.Expression);
if (location != null && location.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), TypeOfExpression.Roles.RPar);
return result;
@ -2842,7 +2990,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2842,7 +2990,8 @@ namespace ICSharpCode.NRefactory.CSharp
result.AddChild (new CSharpTokenNode (Convert (uncheckedExpression.Location), "unchecked".Length), TypeOfExpression.Roles.Keyword);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), TypeOfExpression.Roles.LPar);
result.AddChild ((Expression)uncheckedExpression.Expr.Accept (this), TypeOfExpression.Roles.Expression);
if (uncheckedExpression.Expr != null)
result.AddChild ((Expression)uncheckedExpression.Expr.Accept (this), TypeOfExpression.Roles.Expression);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), TypeOfExpression.Roles.RPar);
return result;
@ -2853,7 +3002,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2853,7 +3002,8 @@ namespace ICSharpCode.NRefactory.CSharp
IndexerExpression result = new IndexerExpression ();
var location = LocationsBag.GetLocations (elementAccessExpression);
result.AddChild ((Expression)elementAccessExpression.Expr.Accept (this), IndexerExpression.Roles.TargetExpression);
if (elementAccessExpression.Expr != null)
result.AddChild ((Expression)elementAccessExpression.Expr.Accept (this), IndexerExpression.Roles.TargetExpression);
result.AddChild (new CSharpTokenNode (Convert (elementAccessExpression.Location), 1), TypeOfExpression.Roles.LBracket);
AddArguments (result, location, elementAccessExpression.Arguments);
if (location != null)
@ -2875,10 +3025,12 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2875,10 +3025,12 @@ namespace ICSharpCode.NRefactory.CSharp
var location = LocationsBag.GetLocations (stackAllocExpression);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), "stackalloc".Length), StackAllocExpression.Roles.Keyword);
result.AddChild (ConvertToType (stackAllocExpression.TypeExpression), StackAllocExpression.Roles.Type);
if (stackAllocExpression.TypeExpression != null)
result.AddChild (ConvertToType (stackAllocExpression.TypeExpression), StackAllocExpression.Roles.Type);
if (location != null && location.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), StackAllocExpression.Roles.LBracket);
result.AddChild ((Expression)stackAllocExpression.CountExpression.Accept (this), StackAllocExpression.Roles.Expression);
if (stackAllocExpression.CountExpression != null)
result.AddChild ((Expression)stackAllocExpression.CountExpression.Accept (this), StackAllocExpression.Roles.Expression);
if (location != null && location.Count > 2)
result.AddChild (new CSharpTokenNode (Convert (location[2]), 1), StackAllocExpression.Roles.RBracket);
return result;
@ -2937,9 +3089,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2937,9 +3089,11 @@ namespace ICSharpCode.NRefactory.CSharp
break;
}
result.AddChild ((Expression)compoundAssign.Target.Accept (this), AssignmentExpression.LeftRole);
if (compoundAssign.Target != null)
result.AddChild ((Expression)compoundAssign.Target.Accept (this), AssignmentExpression.LeftRole);
result.AddChild (new CSharpTokenNode (Convert (compoundAssign.Location), opLength), AssignmentExpression.OperatorRole);
result.AddChild ((Expression)compoundAssign.Source.Accept (this), AssignmentExpression.RightRole);
if (compoundAssign.Source != null)
result.AddChild ((Expression)compoundAssign.Source.Accept (this), AssignmentExpression.RightRole);
return result;
}
@ -2962,7 +3116,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -2962,7 +3116,8 @@ namespace ICSharpCode.NRefactory.CSharp
result.AddChild (new CSharpTokenNode (Convert (location[l++]), 1), AnonymousMethodExpression.Roles.RPar);
}
}
result.AddChild ((BlockStatement)anonymousMethodExpression.Block.Accept (this), AnonymousMethodExpression.Roles.Body);
if (anonymousMethodExpression.Block != null)
result.AddChild ((BlockStatement)anonymousMethodExpression.Block.Accept (this), AnonymousMethodExpression.Roles.Body);
return result;
}
@ -3073,7 +3228,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3073,7 +3228,8 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null)
fromClause.AddChild (new CSharpTokenNode (Convert (location[0]), "in".Length), QueryFromClause.InKeywordRole);
fromClause.AddChild ((Expression)queryStart.Expr.Accept (this), QueryFromClause.Roles.Expression);
if (queryStart.Expr != null)
fromClause.AddChild ((Expression)queryStart.Expr.Accept (this), QueryFromClause.Roles.Expression);
return fromClause;
}
@ -3091,7 +3247,9 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3091,7 +3247,9 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null)
fromClause.AddChild (new CSharpTokenNode (Convert (location[0]), "in".Length), QueryFromClause.InKeywordRole);
fromClause.AddChild ((Expression)queryStart.Expr.Accept (this), QueryFromClause.Roles.Expression);
if (queryStart.Expr != null)
fromClause.AddChild ((Expression)queryStart.Expr.Accept (this), QueryFromClause.Roles.Expression);
return fromClause;
}
@ -3099,7 +3257,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3099,7 +3257,8 @@ namespace ICSharpCode.NRefactory.CSharp
{
var result = new QuerySelectClause ();
result.AddChild (new CSharpTokenNode (Convert (sel.Location), "select".Length), QueryWhereClause.Roles.Keyword);
result.AddChild ((Expression)sel.Expr.Accept (this), QueryWhereClause.Roles.Expression);
if (sel.Expr != null)
result.AddChild ((Expression)sel.Expr.Accept (this), QueryWhereClause.Roles.Expression);
return result;
}
@ -3111,7 +3270,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3111,7 +3270,8 @@ namespace ICSharpCode.NRefactory.CSharp
result.AddChild ((Expression)groupBy.ElementSelector.Accept (this), QueryGroupClause.ProjectionRole);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), "by".Length), QueryGroupClause.ByKeywordRole);
result.AddChild ((Expression)groupBy.Expr.Accept (this), QueryGroupClause.KeyRole);
if (groupBy.Expr != null)
result.AddChild ((Expression)groupBy.Expr.Accept (this), QueryGroupClause.KeyRole);
return result;
}
@ -3124,7 +3284,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3124,7 +3284,8 @@ namespace ICSharpCode.NRefactory.CSharp
result.AddChild (Identifier.Create (l.IntoVariable.Name, Convert (l.IntoVariable.Location)), Identifier.Roles.Identifier);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), QueryLetClause.Roles.Assign);
result.AddChild ((Expression)l.Expr.Accept (this), QueryLetClause.Roles.Expression);
if (l.Expr != null)
result.AddChild ((Expression)l.Expr.Accept (this), QueryLetClause.Roles.Expression);
return result;
}
@ -3134,7 +3295,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3134,7 +3295,8 @@ namespace ICSharpCode.NRefactory.CSharp
var location = LocationsBag.GetLocations (w);
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), "where".Length), QueryWhereClause.Roles.Keyword);
result.AddChild ((Expression)w.Expr.Accept (this), QueryWhereClause.Roles.Condition);
if (w.Expr != null)
result.AddChild ((Expression)w.Expr.Accept (this), QueryWhereClause.Roles.Condition);
return result;
}
@ -3147,8 +3309,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3147,8 +3309,8 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null)
result.AddChild (new CSharpTokenNode (Convert (location[0]), "in".Length), QueryJoinClause.InKeywordRole);
result.AddChild ((Expression)join.Expr.Accept (this), QueryJoinClause.InExpressionRole);
if (join.Expr != null)
result.AddChild ((Expression)join.Expr.Accept (this), QueryJoinClause.InExpressionRole);
if (location != null && location.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (location[1]), "on".Length), QueryJoinClause.OnKeywordRole);
@ -3185,7 +3347,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3185,7 +3347,8 @@ namespace ICSharpCode.NRefactory.CSharp
if (location != null && location.Count > 1)
result.AddChild (new CSharpTokenNode (Convert (location[1]), "on".Length), QueryJoinClause.OnKeywordRole);
result.AddChild ((Expression)join.Expr.Accept (this), QueryJoinClause.InExpressionRole);
if (join.Expr != null)
result.AddChild ((Expression)join.Expr.Accept (this), QueryJoinClause.InExpressionRole);
if (location != null && location.Count > 2)
result.AddChild (new CSharpTokenNode (Convert (location[2]), "equals".Length), QueryJoinClause.EqualsKeywordRole);
@ -3205,8 +3368,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3205,8 +3368,8 @@ namespace ICSharpCode.NRefactory.CSharp
var result = new QueryOrderClause ();
var ordering = new QueryOrdering ();
ordering.AddChild ((Expression)orderByAscending.Expr.Accept (this), QueryWhereClause.Roles.Expression);
if (orderByAscending.Expr != null)
ordering.AddChild ((Expression)orderByAscending.Expr.Accept (this), QueryWhereClause.Roles.Expression);
var location = LocationsBag.GetLocations (orderByAscending);
if (location != null) {
ordering.Direction = QueryOrderingDirection.Ascending;
@ -3221,8 +3384,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3221,8 +3384,8 @@ namespace ICSharpCode.NRefactory.CSharp
var result = new QueryOrderClause ();
var ordering = new QueryOrdering ();
ordering.AddChild ((Expression)orderByDescending.Expr.Accept (this), QueryWhereClause.Roles.Expression);
if (orderByDescending.Expr != null)
ordering.AddChild ((Expression)orderByDescending.Expr.Accept (this), QueryWhereClause.Roles.Expression);
var location = LocationsBag.GetLocations (orderByDescending);
if (location != null) {
ordering.Direction = QueryOrderingDirection.Descending;
@ -3237,8 +3400,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3237,8 +3400,8 @@ namespace ICSharpCode.NRefactory.CSharp
var result = new QueryOrderClause ();
var ordering = new QueryOrdering ();
ordering.AddChild ((Expression)thenByAscending.Expr.Accept (this), QueryWhereClause.Roles.Expression);
if (thenByAscending.Expr != null)
ordering.AddChild ((Expression)thenByAscending.Expr.Accept (this), QueryWhereClause.Roles.Expression);
var location = LocationsBag.GetLocations (thenByAscending);
if (location != null) {
ordering.Direction = QueryOrderingDirection.Ascending;
@ -3253,8 +3416,8 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3253,8 +3416,8 @@ namespace ICSharpCode.NRefactory.CSharp
var result = new QueryOrderClause ();
var ordering = new QueryOrdering ();
ordering.AddChild ((Expression)thenByDescending.Expr.Accept (this), QueryWhereClause.Roles.Expression);
if (thenByDescending.Expr != null)
ordering.AddChild ((Expression)thenByDescending.Expr.Accept (this), QueryWhereClause.Roles.Expression);
var location = LocationsBag.GetLocations (thenByDescending);
if (location != null) {
ordering.Direction = QueryOrderingDirection.Descending;
@ -3278,12 +3441,13 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3278,12 +3441,13 @@ namespace ICSharpCode.NRefactory.CSharp
public CSharpParser ()
{
CompilerArguments = new string[] { "-v", "-unsafe"};
CompilerSettings = new CompilerSettings ();
CompilerSettings.Unsafe = true;
}
public CSharpParser (string[] args)
public CSharpParser (CompilerSettings args)
{
CompilerArguments = args;
CompilerSettings = args;
}
static AstNode GetOuterLeft (AstNode node)
@ -3416,6 +3580,11 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3416,6 +3580,11 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
public CompilationUnit Parse (ITextSource textSource, string fileName, int lineModifier = 0)
{
return Parse (textSource.CreateReader(), fileName, lineModifier);
}
public CompilationUnit Parse (TextReader reader, string fileName, int lineModifier = 0)
{
// TODO: can we optimize this to avoid the text->stream->text roundtrip?
@ -3427,6 +3596,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3427,6 +3596,7 @@ namespace ICSharpCode.NRefactory.CSharp
w.Write (buffer, 0, read);
w.Flush (); // we can't close the StreamWriter because that would also close the MemoryStream
stream.Position = 0;
return Parse (stream, fileName, lineModifier);
}
}
@ -3446,8 +3616,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3446,8 +3616,7 @@ namespace ICSharpCode.NRefactory.CSharp
if (top == null)
return null;
CSharpParser.ConversionVisitor conversionVisitor = new ConversionVisitor (GenerateTypeSystemMode, top.LocationsBag);
top.UsingsBag.Global.Accept (conversionVisitor);
conversionVisitor.AddAttributeSection (conversionVisitor.Unit, top.ModuleCompiled);
top.ModuleCompiled.Accept (conversionVisitor);
InsertComments (top, conversionVisitor);
if (CompilationUnitCallback != null)
CompilationUnitCallback (top);
@ -3459,7 +3628,7 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3459,7 +3628,7 @@ namespace ICSharpCode.NRefactory.CSharp
return conversionVisitor.Unit;
}
public string[] CompilerArguments {
public CompilerSettings CompilerSettings {
get;
private set;
}
@ -3479,13 +3648,29 @@ namespace ICSharpCode.NRefactory.CSharp @@ -3479,13 +3648,29 @@ namespace ICSharpCode.NRefactory.CSharp
return Parse (new StringReader (program), fileName);
}
internal static object parseLock = new object ();
public CompilationUnit Parse (Stream stream, string fileName, int lineModifier = 0)
{
lock (CompilerCallableEntryPoint.parseLock) {
lock (parseLock) {
errorReportPrinter = new ErrorReportPrinter ("");
CompilerCompilationUnit top = CompilerCallableEntryPoint.ParseFile (CompilerArguments, stream, fileName, errorReportPrinter);
var unit = Parse (top, fileName, lineModifier);
var ctx = new CompilerContext (CompilerSettings, errorReportPrinter);
ctx.Settings.TabSize = 1;
var reader = new SeekableStreamReader (stream, Encoding.UTF8);
var file = new SourceFile (fileName, fileName, 0);
Location.Initialize (new List<SourceFile> (new [] { file }));
var module = new ModuleContainer (ctx);
var driver = new Driver (ctx);
var parser = driver.Parse (reader, file, module);
var top = new CompilerCompilationUnit () {
ModuleCompiled = module,
LocationsBag = parser.LocationsBag,
SpecialsBag = parser.Lexer.sbag
};
var unit = Parse (top, fileName, lineModifier);
unit.Errors.AddRange (errorReportPrinter.Errors);
CompilerCallableEntryPoint.Reset ();
return unit;
}
}

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

@ -1,43 +0,0 @@ @@ -1,43 +0,0 @@
//
// AssemblyInfo.cs
//
// Author:
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle ("Mono C# Compiler")]
[assembly: AssemblyProduct ("Mono C# Compiler")]
[assembly: AssemblyCopyright ("2001 - 2009 Novell, Inc.")]
[assembly: AssemblyCompany ("Novell, Inc.")]
[assembly: AssemblyCulture ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyVersion ("1.0")]
[assembly: AssemblyFileVersion ("1.0")]
[assembly: AssemblyDescription ("Mono C# Compiler")]

34100
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ChangeLog

File diff suppressed because it is too large Load Diff

126
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/Makefile

@ -1,126 +0,0 @@ @@ -1,126 +0,0 @@
thisdir := mcs
SUBDIRS :=
include ../build/rules.make
EXTRA_DISTFILES = \
*mcs.csproj \
compiler.doc \
*mcs.sln \
*cs-parser.jay \
*.sources \
NOTES \
TODO \
*mcs.exe.config
COMPILER_NAME = gmcs
ifeq (net_2_0, $(PROFILE))
INTERNAL_GMCS = $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BOOTSTRAP_PROFILE)/gmcs.exe
endif
ifeq (moonlight_bootstrap, $(PROFILE))
INTERNAL_GMCS = $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BOOTSTRAP_PROFILE)/gmcs.exe
endif
ifeq (2.1, $(FRAMEWORK_VERSION))
LOCAL_MCS_FLAGS += -d:SMCS_SOURCE
COMPILER_NAME = smcs
endif
ifeq (4.0, $(FRAMEWORK_VERSION))
COMPILER_NAME = dmcs
endif
PROGRAM = $(topdir)/class/lib/$(PROFILE)/$(COMPILER_NAME).exe
BUILT_SOURCES = cs-parser.cs
PROGRAM_COMPILE = $(BOOT_COMPILE)
CLEAN_FILES += y.output
%-parser.cs: %-parser.jay $(topdir)/jay/skeleton.cs
$(topdir)/jay/jay -cvt < $(topdir)/jay/skeleton.cs $< > jay-tmp.out && mv jay-tmp.out $@
KEEP_OUTPUT_FILE_COPY = yes
include ../build/executable.make
csproj-local:
config_file=`basename $(PROGRAM) .exe`-$(PROFILE).input; \
echo $(thisdir):$$config_file >> $(topdir)/../mono/msvc/scripts/order; \
(echo $(is_boot); \
echo $(BOOTSTRAP_MCS); \
echo $(USE_MCS_FLAGS) $(LIBRARY_FLAGS) $(LIB_MCS_FLAGS); \
echo $(PROGRAM); \
echo $(BUILT_SOURCES); \
echo $(PROGRAM); \
echo $(response)) > $(topdir)/../mono/msvc/scripts/inputs/$$config_file
#
# Below this line we have local targets used for testing and development
#
# Testing targets
TIME = time
# This used to be called test, but that conflicts with the global
# recursive target.
btest: mcs2.exe mcs3.exe
ls -l mcs2.exe mcs3.exe
mcs2.exe: $(PROGRAM)
$(TIME) $(RUNTIME) $(RUNTIME_FLAGS) $(PROGRAM) $(USE_MCS_FLAGS) -target:exe -out:$@ $(BUILT_SOURCES) @$(response)
mcs3.exe: mcs2.exe
$(TIME) $(RUNTIME) $(RUNTIME_FLAGS) ./mcs2.exe $(USE_MCS_FLAGS) -target:exe -out:$@ $(BUILT_SOURCES) @$(response)
wc:
wc -l $(BUILT_SOURCES) `cat $(sourcefile)`
ctest:
rm -f mcs2.exe mcs3.exe
$(MAKE) USE_MCS_FLAGS="-d:NET_1_1 -d:ONLY_1_1" btest
# we need this because bash tries to use its own crappy timer
FRIENDLY_TIME = $(shell which time) -f'%U seconds'
do-time : $(PROGRAM)
@ echo -n "Run 1: "
@ rm -f mcs2.exe
@ $(MAKE) TIME="$(FRIENDLY_TIME)" mcs2.exe > /dev/null || (echo FAILED; exit 1)
@ echo -n "Run 2: "
@ rm -f mcs3.exe
@ $(MAKE) TIME="$(FRIENDLY_TIME)" mcs3.exe > /dev/null || (echo FAILED; exit 1)
@ $(MAKE) do-corlib
do-corlib:
@ echo -n "corlib: "
@ rm -f ../class/lib/mscorlib.dll
@ cd ../class/corlib ; $(MAKE) BOOTSTRAP_MCS='$(FRIENDLY_TIME) mono $$(topdir)/class/lib/$(PROFILE)/mcs.exe' > /dev/null || (echo FAILED; exit 1)
PROFILER=default
do-gettext:
xgettext --keyword='Report.Error:3' --keyword='Report.Error:2' --keyword='Report.Warning:3' --keyword='Report.Warning:2' -o mcs.po --language='C#' `cat gmcs.exe.sources | grep -v /`
profile : $(PROGRAM)
$(RUNTIME) $(RUNTIME_FLAGS) --profile=$(PROFILER) $(PROGRAM) $(USE_MCS_FLAGS) -target:exe -out:mcs2.exe $(BUILT_SOURCES) @$(response)
#
# quick hack target, to quickly develop the gmcs compiler
# Update manually.
q: cs-parser.cs qh
echo 'System.Console.WriteLine ("Hello");' | mono csharp.exe
echo -e 'using System;\nConsole.WriteLine ("hello");' | mono csharp.exe
echo -e '"foo" == "bar";' | mono csharp.exe
echo -e 'var a = 1;\na + 2;' | mono csharp.exe
echo -e 'int j;\nj = 1;' | mono csharp.exe
echo -e 'var a = new int[]{1,2,3};\nfrom x in a select x;' | mono csharp.exe
echo -e 'var a = from f in System.IO.Directory.GetFiles ("/tmp") where f == "passwd" select f;' | mono csharp.exe

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

@ -156,7 +156,6 @@ namespace Mono.CompilerServices.SymbolWriter @@ -156,7 +156,6 @@ namespace Mono.CompilerServices.SymbolWriter
List<MethodEntry> methods = new List<MethodEntry> ();
List<SourceFileEntry> sources = new List<SourceFileEntry> ();
List<CompileUnitEntry> comp_units = new List<CompileUnitEntry> ();
Dictionary<Type, int> type_hash = new Dictionary<Type, int> ();
Dictionary<int, AnonymousScopeEntry> anonymous_scopes;
OffsetTable ot;
@ -187,17 +186,6 @@ namespace Mono.CompilerServices.SymbolWriter @@ -187,17 +186,6 @@ namespace Mono.CompilerServices.SymbolWriter
return comp_units.Count;
}
internal int DefineType (Type type)
{
int index;
if (type_hash.TryGetValue (type, out index))
return index;
index = ++last_type_index;
type_hash.Add (type, index);
return index;
}
internal void AddMethod (MethodEntry entry)
{
methods.Add (entry);
@ -285,7 +273,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -285,7 +273,7 @@ namespace Mono.CompilerServices.SymbolWriter
//
methods.Sort ();
for (int i = 0; i < methods.Count; i++)
((MethodEntry) methods [i]).Index = i + 1;
methods [i].Index = i + 1;
//
// Write data sections.
@ -304,7 +292,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -304,7 +292,7 @@ namespace Mono.CompilerServices.SymbolWriter
//
ot.MethodTableOffset = (int) bw.BaseStream.Position;
for (int i = 0; i < methods.Count; i++) {
MethodEntry entry = (MethodEntry) methods [i];
MethodEntry entry = methods [i];
entry.Write (bw);
}
ot.MethodTableSize = (int) bw.BaseStream.Position - ot.MethodTableOffset;
@ -314,7 +302,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -314,7 +302,7 @@ namespace Mono.CompilerServices.SymbolWriter
//
ot.SourceTableOffset = (int) bw.BaseStream.Position;
for (int i = 0; i < sources.Count; i++) {
SourceFileEntry source = (SourceFileEntry) sources [i];
SourceFileEntry source = sources [i];
source.Write (bw);
}
ot.SourceTableSize = (int) bw.BaseStream.Position - ot.SourceTableOffset;
@ -324,7 +312,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -324,7 +312,7 @@ namespace Mono.CompilerServices.SymbolWriter
//
ot.CompileUnitTableOffset = (int) bw.BaseStream.Position;
for (int i = 0; i < comp_units.Count; i++) {
CompileUnitEntry unit = (CompileUnitEntry) comp_units [i];
CompileUnitEntry unit = comp_units [i];
unit.Write (bw);
}
ot.CompileUnitTableSize = (int) bw.BaseStream.Position - ot.CompileUnitTableOffset;
@ -633,7 +621,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -633,7 +621,7 @@ namespace Mono.CompilerServices.SymbolWriter
lock (this) {
read_methods ();
return (MethodEntry) method_list [index - 1];
return method_list [index - 1];
}
}

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

@ -185,9 +185,23 @@ namespace Mono.CompilerServices.SymbolWriter @@ -185,9 +185,23 @@ namespace Mono.CompilerServices.SymbolWriter
public readonly int Row;
public readonly int File;
public readonly int Offset;
public readonly bool IsHidden;
public readonly bool IsHidden; // Obsolete is never used
#endregion
public sealed class LocationComparer : IComparer<LineNumberEntry>
{
public static readonly LocationComparer Default = new LocationComparer ();
public int Compare (LineNumberEntry l1, LineNumberEntry l2)
{
return l1.Row == l2.Row ?
l1.Offset.CompareTo (l2.Offset) :
l1.Row.CompareTo (l2.Row);
}
}
public static readonly LineNumberEntry Null = new LineNumberEntry (0, 0, 0);
public LineNumberEntry (int file, int row, int offset)
: this (file, row, offset, false)
{ }
@ -200,37 +214,6 @@ namespace Mono.CompilerServices.SymbolWriter @@ -200,37 +214,6 @@ namespace Mono.CompilerServices.SymbolWriter
this.IsHidden = is_hidden;
}
public static LineNumberEntry Null = new LineNumberEntry (0, 0, 0);
private class OffsetComparerClass : IComparer<LineNumberEntry>
{
public int Compare (LineNumberEntry l1, LineNumberEntry l2)
{
if (l1.Offset < l2.Offset)
return -1;
else if (l1.Offset > l2.Offset)
return 1;
else
return 0;
}
}
private class RowComparerClass : IComparer<LineNumberEntry>
{
public int Compare (LineNumberEntry l1, LineNumberEntry l2)
{
if (l1.Row < l2.Row)
return -1;
else if (l1.Row > l2.Row)
return 1;
else
return 0;
}
}
public static readonly IComparer<LineNumberEntry> OffsetComparer = new OffsetComparerClass ();
public static readonly IComparer<LineNumberEntry> RowComparer = new RowComparerClass ();
public override string ToString ()
{
return String.Format ("[Line {0}:{1}:{2}]", File, Row, Offset);
@ -568,6 +551,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -568,6 +551,7 @@ namespace Mono.CompilerServices.SymbolWriter
}
}
[Obsolete]
public int DefineNamespace (string name, string[] using_clauses, int parent)
{
if (!creating)
@ -700,6 +684,12 @@ namespace Mono.CompilerServices.SymbolWriter @@ -700,6 +684,12 @@ namespace Mono.CompilerServices.SymbolWriter
this.hash = checksum;
}
public byte[] Checksum {
get {
return hash;
}
}
internal void WriteData (MyBinaryWriter bw)
{
DataOffset = (int) bw.BaseStream.Position;

46
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/MonoSymbolWriter.cs

@ -153,6 +153,7 @@ namespace Mono.CompilerServices.SymbolWriter @@ -153,6 +153,7 @@ namespace Mono.CompilerServices.SymbolWriter
return entry;
}
[Obsolete]
public int DefineNamespace (string name, CompileUnitEntry unit,
string[] using_clauses, int parent)
{
@ -250,6 +251,8 @@ namespace Mono.CompilerServices.SymbolWriter @@ -250,6 +251,8 @@ namespace Mono.CompilerServices.SymbolWriter
#else
Stack<CodeBlockEntry> _block_stack;
#endif
List<LineNumberEntry> method_lines;
string _real_name;
IMethodDef _method;
ICompileUnit _comp_unit;
@ -261,25 +264,33 @@ namespace Mono.CompilerServices.SymbolWriter @@ -261,25 +264,33 @@ namespace Mono.CompilerServices.SymbolWriter
this._comp_unit = comp_unit;
this._method = method;
this._ns_id = ns_id;
method_lines = new LineNumberEntry [32];
method_lines = new List<LineNumberEntry> ();
}
private LineNumberEntry [] method_lines;
private int method_lines_pos = 0;
public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column,
bool is_hidden)
public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column, bool is_hidden)
{
if (method_lines_pos == method_lines.Length) {
LineNumberEntry [] tmp = method_lines;
method_lines = new LineNumberEntry [method_lines.Length * 2];
Array.Copy (tmp, method_lines, method_lines_pos);
int file_idx = file != null ? file.Index : 0;
var lne = new LineNumberEntry (file_idx, line, offset, is_hidden);
if (method_lines.Count > 0) {
var prev = method_lines[method_lines.Count - 1];
//
// Same offset cannot be used for multiple lines
//
if (prev.Offset == offset) {
//
// Use the new location because debugger will adjust
// the breakpoint to next line with sequence point
//
if (LineNumberEntry.LocationComparer.Default.Compare (lne, prev) > 0)
method_lines[method_lines.Count - 1] = lne;
return;
}
}
int file_idx = file != null ? file.Index : 0;
method_lines [method_lines_pos++] = new LineNumberEntry (
file_idx, line, offset, is_hidden);
method_lines.Add (lne);
}
public void StartBlock (CodeBlockEntry.Type type, int start_offset)
@ -370,10 +381,12 @@ namespace Mono.CompilerServices.SymbolWriter @@ -370,10 +381,12 @@ namespace Mono.CompilerServices.SymbolWriter
new ScopeVariable (scope, index));
}
[Obsolete]
public string RealMethodName {
get { return _real_name; }
}
[Obsolete ("It has no meaning")]
public void SetRealMethodName (string name)
{
_real_name = name;
@ -389,12 +402,9 @@ namespace Mono.CompilerServices.SymbolWriter @@ -389,12 +402,9 @@ namespace Mono.CompilerServices.SymbolWriter
public void DefineMethod (MonoSymbolFile file)
{
LineNumberEntry[] lines = new LineNumberEntry [method_lines_pos];
Array.Copy (method_lines, lines, method_lines_pos);
MethodEntry entry = new MethodEntry (
file, _comp_unit.Entry, _method.Token, ScopeVariables,
Locals, lines, Blocks, RealMethodName, 0, //_method_flags,
Locals, method_lines.ToArray (), Blocks, _real_name, 0, //_method_flags,
_ns_id);
file.AddMethod (entry);

38
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/NOTES

@ -1,38 +0,0 @@ @@ -1,38 +0,0 @@
* Notes on improving error handling in MCS
(from Axel Schreiner <ats@cs.rit.edu>)
I included the 'recover' example with C# as well. Currently the package
is at <http://www.cs.rit.edu/~ats/projects/jay/>. I did change some
names and the embedding that the user does somewhat, i.e., it is not
directly compatible with what you did.
Here is the important part about error recovery. To make the typical
iterations bullet-proof, code them as follows:
opt : // null
| opt WORD { yyErrorFlag = 0; }
| opt error
seq : WORD
| seq WORD { yyErrorFlag = 0; }
| error
| seq error
list : WORD
| list ',' WORD { yyErrorFlag = 0; }
| error
| list error
| list error WORD { yyErrorFlag = 0; }
| list ',' error
i.e., throw in 'error' wherever a token can be. 'yyErrorFlag' need not
be set to zero, but if it is done this way, second errors are caught
earlier. This may introduce s/r conflicts, but they tend to be harmless.
In your case -- the comment concerning error recovery at the beginning
of your compiler jay file -- just adding 'error' to the different
global things won't work. Your example will already have started to
advance in one of the rules and 'error' is then not in the lookahead of
wherever the parse then is. You need to put 'error' into the iteration
above those global things.

26
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/OPTIMIZE

@ -1,26 +0,0 @@ @@ -1,26 +0,0 @@
This document describes all code optimalizations performed by Mono C# compiler
when optimalizations are enabled via /optimize+ option.
Optimalizations:
* Instance field initializer to default value
---------------------------------------------
Code to optimize:
class C
{
enum E
{
Test
}
int i = 0; // Field will not be redundantly assigned
int i2 = new int (); // This will be also completely optimized out
E e = E.Test; // Even this will go out.
}

239
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/OTODO

@ -1,239 +0,0 @@ @@ -1,239 +0,0 @@
---- This is a list of old tasks, just here for historical value ----
Open question:
Create a toplevel block for anonymous methods?
Anonymous Methods
-----------------
Plan:
* Resolve anonymous methods before.
* Each time a Local matches, if the mode is `InAnonymous', flag
the VariableInfo for `proxying'.
* During Resolve track the depth required for local variables.
* Before Emit, create proxy classes with proper depth.
* Emit.
Notes on memory allocation
--------------------------
Outdated:
A run of the AllocationProfile shows that the compiler allocates roughly
30 megabytes of strings. From those, 20 megabytes come from
LookupType.
See the notes on current_container problems below on memory usage.
LookupTypeReflection:
---------------------
With something like `System.Object', LookupTypeReflection will be called
twice: once to find out that `System' is not a type and once
for System.Object.
This is required because System.Reflection requires that the type/nested types are
not separated by a dot but by a plus sign.
A nested class would be My+Class (My being the toplevel, Class the nested one).
It is interesting to look at the most called lookups when bootstrapping MCS:
647 LTR: ArrayList
713 LTR: System.Globalization
822 LTR: System.Object+Expression
904 LTR: Mono.CSharp.ArrayList
976 LTR: System.Runtime.CompilerServices
999 LTR: Type
1118 LTR: System.Runtime
1208 LTR: Mono.CSharp.Type
1373 LTR: Mono.Languages
1599 LTR: System.Diagnostics
2036 LTR: System.Text
2302 LTR: System.Reflection.Emit
2515 LTR: System.Collections
4527 LTR: System.Reflection
22273 LTR: Mono.CSharp
24245 LTR: System
27005 LTR: Mono
Analysis:
The top 9 lookups are done for things which are not types.
Mono.CSharp.Type happens to be a common lookup: the class Type
used heavily in the compiler in the default namespace.
RED FLAG:
Then `Type' is looked up alone a lot of the time, this happens
in parameter declarations and am not entirely sure that this is
correct (FindType will pass to LookupInterfaceOrClass a the current_type.FullName,
which for some reason is null!). This seems to be a problem with a lost
piece of context during FindType.
System.Object is also used a lot as a toplevel class, and we assume it will
have children, we should just shortcut this.
A cache:
Adding a cache and adding a catch for `System.Object' to flag that it wont be the
root of a hierarchy reduced the MCS bootstrap time from 10.22 seconds to 8.90 seconds.
This cache is currently enabled with SIMPLE_SPEEDUP in typemanager.cs. Memory consumption
went down from 74 megs to 65 megs with this change.
Major tasks:
------------
Pinned and volatile require type modifiers that can not be encoded
with Reflection.Emit.
* Revisit
Primary-expression, as it has now been split into
non-array-creation-expression and array-creation-expression.
* Emit `pinned' for pinned local variables.
Both `modreq' and pinned will require special hacks in the compiler.
* Make sure that we are pinning the right variable
* local_variable_declaration
Not sure that this grammar is correct, we might have to
resolve this during semantic analysis.
* Optimizations
In Indexers and Properties, probably support an EmitWithDup
That emits the code to call Get and then leaves a this pointer
in the stack, so that later a Store can be emitted using that
this pointer (consider Property++ or Indexer++)
* Use of local temporary in UnaryMutator
We should get rid of the Localtemporary there for some cases
This turns out to be very complex, at least for the post-version,
because this case:
a = i++
To produce optimal code, it is necessary for UnaryMutator to know
that it is being assigned to a variable (the way the stack is laid
out using dup requires the store to happen inside UnaryMutator).
* Interface indexers
I have not figured out why the Microsoft version puts an
`instance' attribute, and I am not generating this `instance' attribute.
Explanation: The reason for the `instance' attribute on
indexers is that indexers only apply to instances
* Check for Final when overriding, if the parent is Final, then we cant
allow an override.
Implement base indexer access.
current_container/current_namespace and the DeclSpace
-----------------------------------------------------
We are storing fully qualified names in the DeclSpace instead of the node,
this is because `current_namespace' (Namepsace) is not a DeclSpace like
`current_container'.
The reason for storing the full names today is this:
namespace X {
class Y {
}
}
namespace A {
class Y {
}
}
The problem is that we only use the namespace stack to track the "prefix"
for typecontainers, but they are not typecontainers themselves, so we have
to use fully qualified names, because both A.X and A.Y would be entered
in the toplevel type container. If we use the short names, there would be
a name clash.
To fix this problem, we have to make namespaces DeclSpaces.
The full size, contrasted with the size that could be stored is:
corlib:
Size of strings held: 368901
Size of strings short: 147863
System:
Size of strings held: 212677
Size of strings short: 97521
System.XML:
Size of strings held: 128055
Size of strings short: 35782
System.Data:
Size of strings held: 117896
Size of strings short: 36153
System.Web:
Size of strings held: 194527
Size of strings short: 58064
System.Windows.Forms:
Size of strings held: 220495
Size of strings short: 64923
The use of DottedName
---------------------
We could probably use a different system to represent names, like this:
class Name {
string simplename;
Name parent;
}
So `System.ComponentModel' becomes:
x: (System, null)
y: (ComponentModel, x)
The problem is that we would still need to construct the name to pass to
GetType.
This has been now implemented, its called "QualifiedIdentifier"
TODO:
1. Create a "partial" emit context for each TypeContainer..
2. EmitContext should be partially constructed. No IL Generator.
interface_type review.
parameter_array, line 952: `note: must be a single dimension array type'. Validate this
Instance idea
-------------
It would be nice to have things that can be "instances" to have an
EmitInstance method (this would default to nothing).
The idea is to be able to use efficiently the instance data on stack
manipulations, as opposed to the current scheme, where we basically have
a few special cases.
* `yield' is no longer a keyword, it only has special
meaning before a return or break keywords.
* Study side effects with assign
* Study TemporaryStorage/LocalStorage -> Merge/rename

66
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/PLAN

@ -1,66 +0,0 @@ @@ -1,66 +0,0 @@
Clean Up
--------
Move MapVariable from CodeGen into Block?
Improve test:
Necesitamos que a-capture8.cs pruebe si la asignacion funciona o no.
Audit:
Al emitir instancias de variables
(EmitCaptureVariableInstance) parece ser que el loop de iteracion:
while (si.ScopeBlock.ID != li.Block.ID)
está mas actulizado que el codigo similar para parámetros, es posible
que sea bitrot de parámetros o que en los parámetros usamos otra estrategia
(lo segundo es más razonable).
Iteradores:
En algún lugar no pongo el `FieldBuilder' a un valor con los
iteradores, ver expression.cs: 3616, local_info.FieldBuilder es nulo.
Parameters:
a-parameter4.cs falla por que no se liga el método anónimo
anidado con el padre.
Cleanup:
CaptureContext cc = ContextForParameter (ec.CurrentBlock.Toplevel, name);
if (cc != this){
cc.EmitParameter (ec, name);
return;
}
That should be a static method, and call the instance method
in the right CaptureContext, instead of having the CaptureContext
compute that itself.
MakePinned is gone:
Need to audit the code now that use DeclareLocal, and that this uses
a differnent code path than the main mcs.
Need to fix the order in which types are closed: currently we are not
compatible with the MS requirement that the parent has to be created
before the children are.
Tests and pending features:
Switch statement is broken (because it uses ILGenerator during
the Resolve phase, which with the `anonymous' branch is no longer
the case: so we have to delay the creation of labels until they
are needed, during the Emit phase).
Validation:
For testing, set ec.IG == null during resolve, restore value
for emit.
Currently it is commented out: there is a bug in the
statement.cs changes (see the old-statement.cs, the compiler
fails during bootstrap)

72
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/README

@ -1,72 +0,0 @@ @@ -1,72 +0,0 @@
Completion support
==================
Supported:
a.<TAB> to complete members of type `a'
a<TAB> for types and namespaces
a.W<TAB>
a<TAB> for local variables
Unsupported:
delegate { FOO.<TAB>
using statement autocompletion
These are the sources to the Mono C# compiler
---------------------------------------------
Read the mcs/docs/compiler.txt for an overview of the compiler.
Testing the Compiler
--------------------
You might want to use the `make btest' in this directory to
have the compiler bootstrap itself, this is the basic regression
test.
Before commiting changes to MCS, make sure that all the tests
in `mcs/tests' pass, and all the tests in 'mcs/errors' have the
expected result, type:
cd mcs # The top-level 'mcs' directory
make compiler-tests
If you want to test the installed compiler, you can run:
cd mcs # The top-level 'mcs' directory
make test-installed-compiler
Full Bootstrap
==============
To finally ensure the state of the compiler, it is ideal to do
a full bootstrap, to do this, do:
cd mcs
make clean;
make
make install
That installs the compiler and assemblies compiled by the new compiler.
Then, repeat that step again:
make clean
make
If things work, the compiler has not added a new regression
while building the mscorlib and the compiler itself.
Tests
=====
When bugs are fixed, new tests must be added to the
`mcs/tests' directory to excercise the problem and to guarantee
that we keep the compiler in a good state.
When an error is reported, it should be added to mcs/errors.
We try to make the errors numbers be the same as the ones in
Microsoft C#, if this is not possible, allocate a negative error
number, and list it in mcs/errors/errors.txt

223
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/TODO

@ -1,223 +0,0 @@ @@ -1,223 +0,0 @@
===========================================
* Value Parameter
I believe that `Value Parameter' might have been introduced
after C# 1.0, also notice than in the treatment of Value Parameter
the parameters are defined in four categories:
Section 9.3 in the latest spec.
Large project:
--------------
New
---
It would be nice to optimize the case of:
Method (new ValueType ())
So that no temporary is created, and we only use a newobj call
that remains on the stack, as opposed to ldloca, initobj, ldloc
call.
NEW NOTES:
----------
ImplicitStandardConversionExists and ImplicitStandardConversion
should always be the same, but there are a few diverging lines that
must be studied:
if (expr_type == target_type && !(expr is NullLiteral))
return expr;
vs:
if (expr_type == target_type)
return true;
****************************************************************************************
*
* The information on the rest of this file is mostly outdated, and its kept here for
* historical reasons
*
****************************************************************************************
Error Reporting:
----------------
* Make yyerror show a nice syntax error, instead of the current mess.
Optimization ideas
------------------
Currently when we build a type cache, it contains private members,
internal members, and internal protected members; We should trim
these out, as it shows up on the profile.
We create too many Arraylists; When we know the size, we should create
an array;
During parsing we use arraylists to accumulate data, like this:
thing:
thing_list
: thing { $$ =new ArrayList (); $$.Add ($1); }
| thing_list thing { ArrayList a = $1; a.Add ($2); $$ = a; }
We probably could start using "Pairs" there:
thing_list
: thing { $$ = new Pair ($1, null); }
| thing_list thing { Pair p = $1; $$ = new Pair ($2, $1); }
EmitContext.ResolveTypeTree
---------------------------
We should investigate its usage. The problem is that by default
this will be set when calling FindType, that triggers a more expensive
lookup.
I believe we should pass the current EmitContext (which has this turned off
by default) to ResolveType/REsolveTypeExpr and then have the routines that
need ResolveType to pass null as the emit context.
DeclareLocal audit
------------------
DeclareLocal is used in various statements. The audit should be done
in two steps:
* Identify all the declare locals.
* Identify its uses.
* Find if we can make wrapper functions for all of them.
Then we can move DeclareLocal into a helper class.
This is required to fix foreach in iterators.
Ideas:
------
Instead of the hack that *knows* about System.Object not having any children classes,
we should just make it simple for a probe to know that there is no need for it.
Dead Code Elimination bugs:
---------------------------
I should also resolve all the children expressions in Switch, Fixed, Using.
Major tasks:
------------
Properties and 17.6.3: Finish it.
readonly variables and ref/out
BUGS
----
* Break/Continue statements
A finally block should reset the InLoop/LoopBegin/LoopEnd, as
they are logically outside the scope of the loop.
* Break/continue part 2.
They should transfer control to the finally block if inside a try/catch
block.
*
> // CSC sets beforefieldinit
> class X {
> // .cctor will be generated by compiler
> public static readonly object O = new System.Object ();
> public static void Main () {}
> }
>
PENDING TASKS
-------------
* Merge test 89 and test-34
* Code cleanup
The information when registering a method in InternalParameters
is duplicated, you can always get the types from the InternalParameters
* Emit modreq for volatiles
Handle modreq from public apis.
* Merge tree.cs, rootcontext.cs
OPTIMIZATIONS
-------------
* User Defined Conversions is doing way too many calls to do union sets that are not needed
* Add test case for destructors
* Places that use `Ldelema' are basically places where I will be
initializing a value type. I could apply an optimization to
disable the implicit local temporary from being created (by using
the method in New).
* Dropping TypeContainer as an argument to EmitContext
My theory is that I can get rid of the TypeBuilder completely from
the EmitContext, and have typecasts where it is used (from
DeclSpace to where it matters).
The only pending problem is that the code that implements Aliases
is on TypeContainer, and probably should go in DeclSpace.
* Tests
Write tests for the various reference conversions. We have
test for all the numeric conversions.
* Optimizations: variable allocation.
When local variables of a type are required, we should request
the variable and later release it when we are done, so that
the same local variable slot can be reused later on.
* Add a cache for the various GetArrayMethod operations.
* MakeUnionSet Callers
If the types are the same, there is no need to compute the unionset,
we can just use the list from one of the types.
* Factor the lookup code for class declarations an interfaces
(interface.cs:GetInterfaceByName)
RECOMMENDATIONS
---------------
* Use of lexer.Location in the parser
Currently we do:
TOKEN nt TERMINAL nt TERMINAL nt3 {
$$ = new Blah ($2, $4, $6, lexer.Location);
}
This is bad, because the lexer.Location is for the last item in `nt3'
We need to change that to use this pattern:
TOKEN { oob_stack.Push (lexer.Location) } nt TERMINAL nt TERMINAL nt3 {
$$ = new Blah ($3, $5, $7, (Location) oob_stack.Pop ());
}
Notice how numbering of the arguments changes as the
{ oob_stack.Push (lexer.Location) } takes a "slot" in the productions.

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

@ -27,7 +27,7 @@ namespace Mono.CSharp { @@ -27,7 +27,7 @@ namespace Mono.CSharp {
public abstract class CompilerGeneratedClass : Class
{
protected CompilerGeneratedClass (TypeContainer parent, MemberName name, Modifiers mod)
: base (parent.NamespaceEntry, parent, name, mod | Modifiers.COMPILER_GENERATED, null)
: base (parent, name, mod | Modifiers.COMPILER_GENERATED, null)
{
}
@ -85,7 +85,7 @@ namespace Mono.CSharp { @@ -85,7 +85,7 @@ namespace Mono.CSharp {
protected TypeParameterMutator mutator;
public HoistedStoreyClass (TypeContainer parent, MemberName name, TypeParameters tparams, Modifiers mod)
public HoistedStoreyClass (TypeDefinition parent, MemberName name, TypeParameters tparams, Modifiers mod)
: base (parent, name, mod | Modifiers.PRIVATE)
{
@ -183,7 +183,6 @@ namespace Mono.CSharp { @@ -183,7 +183,6 @@ namespace Mono.CSharp {
// Unique storey ID
public readonly int ID;
static int unique_id;
public readonly Block OriginalSourceBlock;
@ -201,12 +200,12 @@ namespace Mono.CSharp { @@ -201,12 +200,12 @@ namespace Mono.CSharp {
// Local variable which holds this storey instance
public Expression Instance;
public AnonymousMethodStorey (Block block, TypeContainer parent, MemberBase host, TypeParameters tparams, string name)
: base (parent, MakeMemberName (host, name, unique_id, tparams, block.StartLocation),
public AnonymousMethodStorey (Block block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name)
: base (parent, MakeMemberName (host, name, parent.Module.CounterAnonymousContainers, tparams, block.StartLocation),
tparams, Modifiers.SEALED)
{
OriginalSourceBlock = block;
ID = unique_id++;
ID = parent.Module.CounterAnonymousContainers++;
}
public void AddCapturedThisField (EmitContext ec)
@ -497,8 +496,10 @@ namespace Mono.CSharp { @@ -497,8 +496,10 @@ namespace Mono.CSharp {
}
}
public override void EmitType ()
public override void Emit ()
{
base.Emit ();
SymbolWriter.DefineAnonymousScope (ID);
if (hoisted_this != null)
@ -519,8 +520,6 @@ namespace Mono.CSharp { @@ -519,8 +520,6 @@ namespace Mono.CSharp {
SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
}
}
base.EmitType ();
}
//
@ -597,11 +596,6 @@ namespace Mono.CSharp { @@ -597,11 +596,6 @@ namespace Mono.CSharp {
public IList<ExplicitBlock> ReferencesFromChildrenBlock {
get { return children_references; }
}
public static void Reset ()
{
unique_id = 0;
}
}
public abstract class HoistedVariable
@ -1045,16 +1039,10 @@ namespace Mono.CSharp { @@ -1045,16 +1039,10 @@ namespace Mono.CSharp {
return false;
for (int i = 0; i < Parameters.Count; ++i) {
TypeSpec itype = d_params.Types [i];
if (!TypeManager.IsGenericParameter (itype)) {
if (!TypeManager.HasElementType (itype))
continue;
if (!TypeManager.IsGenericParameter (TypeManager.GetElementType (itype)))
continue;
}
type_inference.ExactInference (Parameters.Types [i], itype);
if (type_inference.ExactInference (Parameters.Types[i], d_params.Types[i]) == 0)
return false;
}
return true;
}
@ -1072,7 +1060,7 @@ namespace Mono.CSharp { @@ -1072,7 +1060,7 @@ namespace Mono.CSharp {
var body = CompatibleMethodBody (ec, tic, InternalType.Arglist, delegate_type);
if (body != null) {
if (Block.IsAsync) {
AsyncInitializer.Create (ec, body.Block, body.Parameters, ec.CurrentMemberDefinition.Parent, null, loc);
AsyncInitializer.Create (ec, body.Block, body.Parameters, ec.CurrentMemberDefinition.Parent.PartialContainer, null, loc);
}
am = body.Compatible (ec, body);
@ -1166,7 +1154,7 @@ namespace Mono.CSharp { @@ -1166,7 +1154,7 @@ namespace Mono.CSharp {
GetSignatureForError (), type.GetSignatureForError ());
}
AsyncInitializer.Create (ec, body.Block, body.Parameters, ec.CurrentMemberDefinition.Parent, rt, loc);
AsyncInitializer.Create (ec, body.Block, body.Parameters, ec.CurrentMemberDefinition.Parent.PartialContainer, rt, loc);
}
am = body.Compatible (ec);
@ -1324,20 +1312,18 @@ namespace Mono.CSharp { @@ -1324,20 +1312,18 @@ namespace Mono.CSharp {
{
public readonly AnonymousExpression AnonymousMethod;
public readonly AnonymousMethodStorey Storey;
readonly string RealName;
public AnonymousMethodMethod (TypeContainer parent, AnonymousExpression am, AnonymousMethodStorey storey,
public AnonymousMethodMethod (TypeDefinition parent, AnonymousExpression am, AnonymousMethodStorey storey,
TypeExpr return_type,
Modifiers mod, string real_name, MemberName name,
Modifiers mod, MemberName name,
ParametersCompiled parameters)
: base (parent, return_type, mod | Modifiers.COMPILER_GENERATED,
name, parameters, null)
{
this.AnonymousMethod = am;
this.Storey = storey;
this.RealName = real_name;
Parent.PartialContainer.AddMethod (this);
Parent.PartialContainer.Members.Add (this);
Block = new ToplevelBlock (am.block, parameters);
}
@ -1379,11 +1365,6 @@ namespace Mono.CSharp { @@ -1379,11 +1365,6 @@ namespace Mono.CSharp {
base.Emit ();
}
public override void EmitExtraSymbolInfo (SourceMethod source)
{
source.SetRealMethodName (RealName);
}
}
protected ParametersBlock block;
@ -1496,8 +1477,6 @@ namespace Mono.CSharp { @@ -1496,8 +1477,6 @@ namespace Mono.CSharp {
string block_name;
TypeInferenceContext return_inference;
static int unique_id;
public AnonymousMethodBody (ParametersCompiled parameters,
ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
Location loc)
@ -1583,11 +1562,10 @@ namespace Mono.CSharp { @@ -1583,11 +1562,10 @@ namespace Mono.CSharp {
modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
}
TypeContainer parent = storey != null ? storey : ec.CurrentTypeDefinition.Parent.PartialContainer;
var parent = storey != null ? storey : ec.CurrentTypeDefinition.Parent.PartialContainer;
MemberCore mc = ec.MemberContext as MemberCore;
string name = CompilerGeneratedClass.MakeName (parent != storey ? block_name : null,
"m", null, unique_id++);
"m", null, ec.Module.CounterAnonymousMethods++);
MemberName member_name;
if (storey == null && ec.CurrentTypeParameters != null) {
@ -1603,13 +1581,9 @@ namespace Mono.CSharp { @@ -1603,13 +1581,9 @@ namespace Mono.CSharp {
member_name = new MemberName (name, Location);
}
string real_name = String.Format (
"{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
parameters.GetSignatureForError ());
return new AnonymousMethodMethod (parent,
this, storey, new TypeExpression (ReturnType, Location), modifiers,
real_name, member_name, parameters);
member_name, parameters);
}
protected override Expression DoResolve (ResolveContext ec)
@ -1642,8 +1616,8 @@ namespace Mono.CSharp { @@ -1642,8 +1616,8 @@ namespace Mono.CSharp {
// Creates a field cache to store delegate instance if it's not generic
//
if (!method.MemberName.IsGeneric) {
TypeContainer parent = method.Parent.PartialContainer;
int id = parent.Fields == null ? 0 : parent.Fields.Count;
var parent = method.Parent.PartialContainer;
int id = parent.AnonymousMethodsCounter++;
var cache_type = storey != null && storey.Mutator != null ? storey.Mutator.Mutate (type) : type;
am_cache = new Field (parent, new TypeExpression (cache_type, loc),
@ -1752,11 +1726,6 @@ namespace Mono.CSharp { @@ -1752,11 +1726,6 @@ namespace Mono.CSharp {
{
return TypeManager.CSharpName (type);
}
public static void Reset ()
{
unique_id = 0;
}
}
//
@ -1764,21 +1733,20 @@ namespace Mono.CSharp { @@ -1764,21 +1733,20 @@ namespace Mono.CSharp {
//
public class AnonymousTypeClass : CompilerGeneratedClass
{
static int types_counter;
public const string ClassNamePrefix = "<>__AnonType";
public const string SignatureForError = "anonymous type";
readonly IList<AnonymousTypeParameter> parameters;
private AnonymousTypeClass (TypeContainer parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
: base (parent, name, (parent.Module.Evaluator != null ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
private AnonymousTypeClass (ModuleContainer parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
: base (parent, name, (parent.Evaluator != null ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
{
this.parameters = parameters;
}
public static AnonymousTypeClass Create (TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
{
string name = ClassNamePrefix + types_counter++;
string name = ClassNamePrefix + parent.Module.CounterAnonymousTypes++;
ParametersCompiled all_parameters;
TypeParameters tparams = null;
@ -1817,8 +1785,7 @@ namespace Mono.CSharp { @@ -1817,8 +1785,7 @@ namespace Mono.CSharp {
// Create generic anonymous type host with generic arguments
// named upon properties names
//
AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
new MemberName (name, tparams, loc), parameters, loc);
AnonymousTypeClass a_type = new AnonymousTypeClass (parent.Module, new MemberName (name, tparams, loc), parameters, loc);
Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
null, all_parameters, loc);
@ -1851,7 +1818,7 @@ namespace Mono.CSharp { @@ -1851,7 +1818,7 @@ namespace Mono.CSharp {
new MemberName (p.Name, p.Location), null);
prop.Get = new Property.GetMethod (prop, 0, null, p.Location);
prop.Get.Block = get_block;
a_type.AddProperty (prop);
a_type.AddMember (prop);
}
if (error)
@ -1861,30 +1828,6 @@ namespace Mono.CSharp { @@ -1861,30 +1828,6 @@ namespace Mono.CSharp {
return a_type;
}
public static void Reset ()
{
types_counter = 0;
}
protected override bool AddToContainer (MemberCore symbol, string name)
{
MemberCore mc = GetDefinition (name);
if (mc == null) {
defined_names.Add (name, symbol);
return true;
}
// A conflict between anonymous type members will be reported
if (symbol is TypeParameter) {
Report.SymbolRelatedToPreviousError (symbol);
return false;
}
// Ignore other conflicts
return true;
}
protected override bool DoDefineMembers ()
{
if (!base.DoDefineMembers ())
@ -1931,7 +1874,7 @@ namespace Mono.CSharp { @@ -1931,7 +1874,7 @@ namespace Mono.CSharp {
Expression rs_hashcode = new IntConstant (Compiler.BuiltinTypes, -2128831035, loc);
for (int i = 0; i < parameters.Count; ++i) {
var p = parameters [i];
var f = Fields [i];
var f = (Field) Members [i * 2];
MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
system_collections_generic, "EqualityComparer",
@ -2008,7 +1951,7 @@ namespace Mono.CSharp { @@ -2008,7 +1951,7 @@ namespace Mono.CSharp {
equals.Block = equals_block;
equals.Define ();
AddMethod (equals);
Members.Add (equals);
//
// GetHashCode () override
@ -2062,7 +2005,7 @@ namespace Mono.CSharp { @@ -2062,7 +2005,7 @@ namespace Mono.CSharp {
hashcode_block.AddStatement (new Return (hash_variable, loc));
hashcode.Block = hashcode_top;
hashcode.Define ();
AddMethod (hashcode);
Members.Add (hashcode);
//
// ToString () override
@ -2072,7 +2015,7 @@ namespace Mono.CSharp { @@ -2072,7 +2015,7 @@ namespace Mono.CSharp {
tostring_block.AddStatement (new Return (string_concat, loc));
tostring.Block = tostring_block;
tostring.Define ();
AddMethod (tostring);
Members.Add (tostring);
return true;
}
@ -2082,6 +2025,11 @@ namespace Mono.CSharp { @@ -2082,6 +2025,11 @@ namespace Mono.CSharp {
return SignatureForError;
}
public override CompilationSourceFile GetCompilationSourceFile ()
{
return null;
}
public IList<AnonymousTypeParameter> Parameters {
get {
return parameters;

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

@ -437,8 +437,8 @@ namespace Mono.CSharp @@ -437,8 +437,8 @@ namespace Mono.CSharp
{
if (Compiler.Settings.Target == Target.Module) {
module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
module_target_attrs.CreateType ();
module_target_attrs.DefineType ();
module_target_attrs.CreateContainer ();
module_target_attrs.DefineContainer ();
module_target_attrs.Define ();
module.AddCompilerGeneratedClass (module_target_attrs);
} else if (added_modules != null) {
@ -448,16 +448,11 @@ namespace Mono.CSharp @@ -448,16 +448,11 @@ namespace Mono.CSharp
if (Compiler.Settings.GenerateDebugInfo) {
symbol_writer = new MonoSymbolWriter (file_name);
// Register all source files with symbol writer
foreach (var source in Compiler.SourceFiles) {
source.DefineSymbolInfo (symbol_writer);
}
// TODO: global variables
SymbolWriter.symwriter = symbol_writer;
}
module.Emit ();
module.EmitContainer ();
if (module.HasExtensionMethod) {
var pa = module.PredefinedAttributes.Extension;
@ -484,12 +479,7 @@ namespace Mono.CSharp @@ -484,12 +479,7 @@ namespace Mono.CSharp
Builder.__AddDeclarativeSecurity (entry);
}
#else
var args = new PermissionSet[3];
#pragma warning disable 618
declarative_security.TryGetValue (SecurityAction.RequestMinimum, out args[0]);
declarative_security.TryGetValue (SecurityAction.RequestOptional, out args[1]);
declarative_security.TryGetValue (SecurityAction.RequestRefuse, out args[2]);
builder_extra.AddPermissionRequests (args);
throw new NotSupportedException ("Assembly-level security");
#endif
}

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

@ -357,7 +357,7 @@ namespace Mono.CSharp { @@ -357,7 +357,7 @@ namespace Mono.CSharp {
return this;
}
#if NET_4_0
#if NET_4_0 || MONODROID
public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
{
var tassign = target as IDynamicAssign;
@ -565,7 +565,18 @@ namespace Mono.CSharp { @@ -565,7 +565,18 @@ namespace Mono.CSharp {
{
if (resolved == null)
return;
//
// Emit sequence symbol info even if we are in compiler generated
// block to allow debugging filed initializers when constructor is
// compiler generated
//
if (ec.HasSet (BuilderContext.Options.OmitDebugInfo)) {
using (ec.With (BuilderContext.Options.OmitDebugInfo, false)) {
ec.Mark (loc);
}
}
if (resolved != this)
resolved.EmitStatement (ec);
else

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

@ -399,7 +399,7 @@ namespace Mono.CSharp @@ -399,7 +399,7 @@ namespace Mono.CSharp
{
TypeInferenceContext return_inference;
public AsyncInitializer (ParametersBlock block, TypeContainer host, TypeSpec returnType)
public AsyncInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
: base (block, host, returnType)
{
}
@ -432,7 +432,7 @@ namespace Mono.CSharp @@ -432,7 +432,7 @@ namespace Mono.CSharp
#endregion
public static void Create (IMemberContext context, ParametersBlock block, ParametersCompiled parameters, TypeContainer host, TypeSpec returnType, Location loc)
public static void Create (IMemberContext context, ParametersBlock block, ParametersCompiled parameters, TypeDefinition host, TypeSpec returnType, Location loc)
{
for (int i = 0; i < parameters.Count; i++) {
Parameter p = parameters[i];
@ -543,7 +543,7 @@ namespace Mono.CSharp @@ -543,7 +543,7 @@ namespace Mono.CSharp
TypeSpec action;
public AsyncTaskStorey (IMemberContext context, AsyncInitializer initializer, TypeSpec type)
: base (initializer.OriginalBlock, initializer.Host,context.CurrentMemberDefinition as MemberBase, context.CurrentTypeParameters, "async")
: base (initializer.OriginalBlock, initializer.Host, context.CurrentMemberDefinition as MemberBase, context.CurrentTypeParameters, "async")
{
return_type = type;
}
@ -675,10 +675,12 @@ namespace Mono.CSharp @@ -675,10 +675,12 @@ namespace Mono.CSharp
builder = AddCompilerGeneratedField ("$builder", new TypeExpression (bt, Location));
var ctor = DefineDefaultConstructor (false);
if (!base.DoDefineMembers ())
return false;
var block = instance_constructors[0].Block;
Block block = ctor.Block;
var mg = MethodGroupExpr.CreatePredefined (builder_factory, bt, Location);
block.AddStatement (
@ -783,7 +785,7 @@ namespace Mono.CSharp @@ -783,7 +785,7 @@ namespace Mono.CSharp
class StackField : Field
{
public StackField (TypeContainer parent, FullNamedExpression type, Modifiers mod, MemberName name)
public StackField (TypeDefinition parent, FullNamedExpression type, Modifiers mod, MemberName name)
: base (parent, type, mod, name, null)
{
}

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

File diff suppressed because it is too large Load Diff

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

@ -89,6 +89,13 @@ namespace Mono.CSharp @@ -89,6 +89,13 @@ namespace Mono.CSharp
if (rc.Module.Compiler.Settings.Checked)
flags |= Options.CheckedScope;
if (SymbolWriter.HasSymbolWriter) {
if (!rc.Module.Compiler.Settings.Optimize)
flags |= Options.AccurateDebugInfo;
} else {
flags |= Options.OmitDebugInfo;
}
#if STATIC
ig.__CleverExceptionBlockAssistance ();
#endif
@ -120,6 +127,12 @@ namespace Mono.CSharp @@ -120,6 +127,12 @@ namespace Mono.CSharp
get { return member_context.CurrentMemberDefinition; }
}
public bool EmitAccurateDebugInfo {
get {
return (flags & Options.AccurateDebugInfo) != 0;
}
}
public bool HasReturnLabel {
get {
return return_label.HasValue;
@ -188,12 +201,19 @@ namespace Mono.CSharp @@ -188,12 +201,19 @@ namespace Mono.CSharp
/// This is called immediately before emitting an IL opcode to tell the symbol
/// writer to which source line this opcode belongs.
/// </summary>
public void Mark (Location loc)
public bool Mark (Location loc)
{
if (!SymbolWriter.HasSymbolWriter || HasSet (Options.OmitDebugInfo) || loc.IsNull)
return;
if ((flags & Options.OmitDebugInfo) != 0)
return false;
if (loc.IsNull)
return false;
if (loc.SourceFile.IsHiddenLocation (loc))
return false;
SymbolWriter.MarkSequencePoint (ig, loc);
return true;
}
public void DefineLocalVariable (string name, LocalBuilder builder)
@ -241,9 +261,8 @@ namespace Mono.CSharp @@ -241,9 +261,8 @@ namespace Mono.CSharp
dynamic_site_container = new DynamicSiteClass (CurrentTypeDefinition.Parent.PartialContainer, mc, member_context.CurrentTypeParameters);
CurrentTypeDefinition.Module.AddCompilerGeneratedClass (dynamic_site_container);
dynamic_site_container.CreateType ();
dynamic_site_container.DefineType ();
dynamic_site_container.ResolveTypeParameters ();
dynamic_site_container.CreateContainer ();
dynamic_site_container.DefineContainer ();
dynamic_site_container.Define ();
var inflator = new TypeParameterInflator (Module, CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
@ -866,7 +885,7 @@ namespace Mono.CSharp @@ -866,7 +885,7 @@ namespace Mono.CSharp
public void Emit (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
{
// Speed up the check by not doing it on not allowed targets
if (method.ReturnType.Kind == MemberKind.Void && method.IsConditionallyExcluded (ec.Module.Compiler, loc))
if (method.ReturnType.Kind == MemberKind.Void && method.IsConditionallyExcluded (ec.MemberContext, loc))
return;
EmitPredefined (ec, method, Arguments);

116
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/compiler.doc

@ -1,116 +0,0 @@ @@ -1,116 +0,0 @@
Compiler operation
The compiler has a number of phases:
* Parsing.
Initially the compiler parses all the source files and keeps a
parsed representation in memory. Very syntax error checking
is performed at this point.
The compiler stores the information in classes whose names
represent the language construct, for example, the "if"
construct is stored in an `If' class. A class is stored in a
`Class'.
* The TypeManager
The TypeManager loads all the assemblies that were referenced
by the programmer. The CLR type system is used as our
repository for types defined as well.
So the same interface that is used to query the types,
properties and flags about system types is the same interface
that we use for our types.
As we work our way through the code generation and semantic
analysis, new types are entered into the Type system through
the use of System.Reflection.Emit. The TypeManager will
lookup types on both the user defined types and on the system
defined ones.
So special care has to be used. The order in which we
proceeed from here is important.
* Base class resolution and type definition.
Once the parsing has happened, the compiler resolves the
inheritance tree for interfaces. This is done recursively
and we catch recursive interface definitions here.
After this is done, we continue on with classes. Classes have
can have an optional "parent" inherit from or the implicit
System.Object class (for normal builds, builds with /nostdlib
will allow you to compile class System.Object with no parent).
At this point we do some error checking and verify that the
inherits/implements section of a class is correct (since we
have previously built the interface inheritance).
By the time we are done, all classes, structs and interfaces
have been created using System.Reflection.Emit and registered
with the Type Manager.
This allows us to define fields and resolve argument names for
methods, properties, indexers and events.
* Field generation
Fields are generated next, we go through all the type
containers (classes and structs) and enter the fields into
their types.
* Method, Properties, Indexers and events definitions
Now all the methods, constructors, properties, indexers and
events are entered. They are only `defined' using
System.Reflection.Emit. No code generation will happen until
everything has been entered into System.Reflection.Emit.
This is important because to actually generate code we need to
know everything about the environment in which the code is
being generated.
* Code Generation
At this point all the definitions have been entered into the
type manager through System.Reflection.Emit. We can now use
System.Reflection to query all the information about the
types.
Your normal semantic analysis and code generation phase lives
here.
* Statements
Most of the statements are handled in the codegen.cs file.
* Expressions
* Error reporting
Always use `Report::Error' or `Report::Warning' methods of Report
class. The actual Report instance is available via local context.
An expression error reporting has to be done during Resolve phase,
except when it's Emit specific (very rare).
Error reporting should try to use the same codes that the
Microsoft compiler uses (if only so we can track which errors
we handle and which ones we dont).
If there is an error which is specific to MSC, use negative
numbers, and register the number in mcs/errors/errors.txt
Try to write a test case for any error that you run into the
code of the compiler if there is none already.
Put your test case in a file called csNNNN.cs in the
mcs/errors directory, and have the first two lines be:
// csNNNN.cs: This is the error message
// Line: XXX
// Compiler options: an optional compiler options
Where `XXX' is the line where the error ocurrs. We will later
use this as a regression test suite for catching errors in the
compiler.

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

@ -78,11 +78,9 @@ namespace Mono.CSharp { @@ -78,11 +78,9 @@ namespace Mono.CSharp {
{
var results = new List<string> ();
AppendResults (results, Prefix, ec.Module.Evaluator.GetVarNames ());
AppendResults (results, Prefix, ec.CurrentMemberDefinition.Parent.NamespaceEntry.CompletionGetTypesStartingWith (Prefix));
AppendResults (results, Prefix, ec.Module.Evaluator.GetUsingList ());
throw new CompletionResult (Prefix, results.ToArray ());
ec.CurrentMemberDefinition.GetCompletionStartingWith (Prefix, results);
throw new CompletionResult (Prefix, results.Distinct ().Select (l => l.Substring (Prefix.Length)).ToArray ());
}
protected override void CloneTo (CloneContext clonectx, Expression t)
@ -140,17 +138,9 @@ namespace Mono.CSharp { @@ -140,17 +138,9 @@ namespace Mono.CSharp {
else
namespaced_partial = nexpr.Name + "." + partial_name;
#if false
Console.WriteLine ("Workign with: namespaced partial {0}", namespaced_partial);
foreach (var x in ec.TypeContainer.NamespaceEntry.CompletionGetTypesStartingWith (ec.TypeContainer, namespaced_partial)){
Console.WriteLine (" {0}", x);
}
#endif
CompletionSimpleName.AppendResults (
results,
partial_name,
ec.CurrentMemberDefinition.Parent.NamespaceEntry.CompletionGetTypesStartingWith (namespaced_partial));
ec.CurrentMemberDefinition.GetCompletionStartingWith (namespaced_partial, results);
if (partial_name != null)
results = results.Select (l => l.Substring (partial_name.Length)).ToList ();
} else {
var r = MemberCache.GetCompletitionMembers (ec, expr_type, partial_name).Select (l => l.Name);
AppendResults (results, partial_name, r);

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

@ -26,7 +26,7 @@ namespace Mono.CSharp { @@ -26,7 +26,7 @@ namespace Mono.CSharp {
Modifiers.INTERNAL |
Modifiers.PRIVATE;
public Const (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
public Const (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
: base (parent, type, mod_flags, AllowedModifiers, name, attrs)
{
ModFlags |= Modifiers.STATIC;
@ -63,12 +63,12 @@ namespace Mono.CSharp { @@ -63,12 +63,12 @@ namespace Mono.CSharp {
if (declarators != null) {
var t = new TypeExpression (MemberType, TypeExpression.Location);
int index = Parent.PartialContainer.Constants.IndexOf (this);
foreach (var d in declarators) {
var c = new Const (Parent, t, ModFlags & ~Modifiers.STATIC, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
c.initializer = d.Initializer;
((ConstInitializer) c.initializer).Name = d.Name.Value;
Parent.PartialContainer.Constants.Insert (++index, c);
c.Define ();
Parent.PartialContainer.Members.Add (c);
}
}

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

@ -586,10 +586,10 @@ namespace Mono.CSharp @@ -586,10 +586,10 @@ namespace Mono.CSharp
Dictionary<string, SourceFile> all_source_files;
public CompilerContext (CompilerSettings settings, Report report)
public CompilerContext (CompilerSettings settings, ReportPrinter reportPrinter)
{
this.settings = settings;
this.report = report;
this.report = new Report (this, reportPrinter);
this.builtin_types = new BuiltinTypes ();
this.TimeReporter = DisabledTimeReporter;
}
@ -620,7 +620,7 @@ namespace Mono.CSharp @@ -620,7 +620,7 @@ namespace Mono.CSharp
}
}
public List<CompilationSourceFile> SourceFiles {
public List<SourceFile> SourceFiles {
get {
return settings.SourceFiles;
}
@ -646,7 +646,7 @@ namespace Mono.CSharp @@ -646,7 +646,7 @@ namespace Mono.CSharp
string path;
if (!Path.IsPathRooted (name)) {
string root = Path.GetDirectoryName (comp_unit.FullPathName);
string root = Path.GetDirectoryName (comp_unit.SourceFile.FullPathName);
path = Path.Combine (root, name);
} else
path = name;
@ -655,7 +655,8 @@ namespace Mono.CSharp @@ -655,7 +655,8 @@ namespace Mono.CSharp
if (all_source_files.TryGetValue (path, out retval))
return retval;
retval = Location.AddFile (name, path);
retval = new SourceFile (name, path, all_source_files.Count + 1);
Location.AddFile (retval);
all_source_files.Add (path, retval);
return retval;
}
@ -681,6 +682,8 @@ namespace Mono.CSharp @@ -681,6 +682,8 @@ namespace Mono.CSharp
/// </summary>
CheckedScope = 1 << 0,
AccurateDebugInfo = 1 << 1,
OmitDebugInfo = 1 << 2,
ConstructorScope = 1 << 3,

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

@ -330,17 +330,40 @@ namespace Mono.CSharp { @@ -330,17 +330,40 @@ namespace Mono.CSharp {
return TypeSpecComparer.Variant.IsEqual (expr_type, target_type) || expr_type.ImplementsInterface (target_type, true);
return target_type.BuiltinType == BuiltinTypeSpec.Type.Object || target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
}
//
// from the null literal to any reference-type.
//
if (expr_type == InternalType.NullLiteral) {
// Exlude internal compiler types
if (target_type.Kind == MemberKind.InternalCompilerType)
return target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
case MemberKind.InternalCompilerType:
//
// from the null literal to any reference-type.
//
if (expr_type == InternalType.NullLiteral) {
// Exlude internal compiler types
if (target_type.Kind == MemberKind.InternalCompilerType)
return target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
return TypeSpec.IsReferenceType (target_type);
}
//
// Implicit dynamic conversion
//
if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
switch (target_type.Kind) {
case MemberKind.ArrayType:
case MemberKind.Class:
case MemberKind.Delegate:
case MemberKind.Interface:
case MemberKind.TypeParameter:
return true;
}
// dynamic to __arglist
if (target_type == InternalType.Arglist)
return true;
return TypeSpec.IsReferenceType (target_type);
return false;
}
break;
}
return false;
@ -773,23 +796,17 @@ namespace Mono.CSharp { @@ -773,23 +796,17 @@ namespace Mono.CSharp {
return i.IsZeroInteger;
}
// Implicit dynamic conversion
//
// Implicit dynamic conversion for remaining value types. It should probably
// go somewhere else
//
if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
switch (target_type.Kind) {
case MemberKind.ArrayType:
case MemberKind.Class:
case MemberKind.Struct:
case MemberKind.Delegate:
case MemberKind.Enum:
case MemberKind.Interface:
case MemberKind.TypeParameter:
return true;
}
// dynamic to __arglist
if (target_type == InternalType.Arglist)
return true;
return false;
}

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

File diff suppressed because it is too large Load Diff

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

@ -45,9 +45,9 @@ namespace Mono.CSharp @@ -45,9 +45,9 @@ namespace Mono.CSharp
static readonly object ModifierNone = 0;
NamespaceContainer current_namespace;
TypeContainer current_container;
TypeContainer current_class;
NamespaceContainer current_namespace;
TypeContainer current_container;
TypeDefinition current_type;
PropertyBase current_property;
EventProperty current_event;
EventField current_event_field;
@ -86,7 +86,7 @@ namespace Mono.CSharp @@ -86,7 +86,7 @@ namespace Mono.CSharp
///
/// Controls the verbosity of the errors produced by the parser
///
static public int yacc_verbose_flag;
int yacc_verbose_flag;
///
/// Used by the interactive shell, flags whether EOF was reached
@ -143,7 +143,6 @@ namespace Mono.CSharp @@ -143,7 +143,6 @@ namespace Mono.CSharp
// Full AST support members
//
LocationsBag lbag;
UsingsBag ubag;
List<Tuple<Modifiers, Location>> mod_locations;
Location parameterModifierLocation, savedLocation, savedOpenLocation, savedCloseLocation;
Location savedAttrParenOpenLocation, savedAttrParenCloseLocation, savedOperatorLocation;
@ -470,7 +469,6 @@ using_namespace @@ -470,7 +469,6 @@ using_namespace
var un = new UsingNamespace ((ATypeNameExpression) $2, GetLocation ($1));
current_namespace.AddUsing (un);
ubag.AddUsing (GetLocation ($1), (ATypeNameExpression) $2, GetLocation ($3));
lbag.AddLocation (un, GetLocation ($3));
}
| USING IDENTIFIER ASSIGN namespace_or_type_expr SEMICOLON
@ -483,8 +481,6 @@ using_namespace @@ -483,8 +481,6 @@ using_namespace
var un = new UsingAliasNamespace (new SimpleMemberName (lt.Value, lt.Location), (ATypeNameExpression) $4, GetLocation ($1));
current_namespace.AddUsing (un);
ubag.AddUsingAlias (GetLocation ($1), lt, GetLocation ($3), (ATypeNameExpression) $4, GetLocation ($5));
lbag.AddLocation (un, GetLocation ($3), GetLocation ($5));
}
| USING error
@ -506,7 +502,7 @@ namespace_declaration @@ -506,7 +502,7 @@ namespace_declaration
var name = (MemberName) $3;
if (attrs != null) {
bool valid_global_attrs = true;
if ((current_namespace.DeclarationFound || current_namespace != file.NamespaceContainer)) {
if ((current_namespace.DeclarationFound || current_namespace != file)) {
valid_global_attrs = false;
} else {
foreach (var a in attrs.Attrs) {
@ -524,29 +520,23 @@ namespace_declaration @@ -524,29 +520,23 @@ namespace_declaration
module.AddAttributes (attrs, current_namespace);
current_namespace = new NamespaceContainer (name, module, current_namespace, file);
module.AddTypesContainer (current_namespace);
current_class = current_namespace.SlaveDeclSpace;
current_container = current_class.PartialContainer;
ubag.DeclareNamespace (GetLocation ($2), name);
var ns = new NamespaceContainer (name, current_namespace);
current_namespace.AddTypeContainer (ns);
current_container = current_namespace = ns;
}
OPEN_BRACE
{
if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
ubag.OpenNamespace (GetLocation ($5));
}
opt_extern_alias_directives opt_using_directives opt_namespace_or_type_declarations CLOSE_BRACE opt_semicolon
{
current_namespace = current_namespace.Parent;
current_class = current_namespace.SlaveDeclSpace;
current_container = current_class.PartialContainer;
ubag.CloseNamespace (GetLocation ($10));
if ($11 != null)
ubag.EndNamespace (GetLocation ($11));
lbag.AddLocation (current_container, GetLocation ($2), GetLocation ($5), GetLocation ($10), GetLocation ($11));
else
ubag.EndNamespace ();
lbag.AddLocation (current_container, GetLocation ($2), GetLocation ($5), GetLocation ($10));
current_container = current_namespace = current_namespace.Parent;
}
;
@ -615,7 +605,7 @@ namespace_or_type_declaration @@ -615,7 +605,7 @@ namespace_or_type_declaration
// we parse succeeding declaration hence we parse them as normal and re-attach them
// when we know whether they are global (assembly:, module:) or local (type:).
if (ds.OptAttributes != null) {
ds.OptAttributes.ConvertGlobalAttributes (ds, current_namespace, !current_namespace.DeclarationFound && current_namespace == file.NamespaceContainer);
ds.OptAttributes.ConvertGlobalAttributes (ds, current_namespace, !current_namespace.DeclarationFound && current_namespace == file);
}
}
current_namespace.DeclarationFound = true;
@ -624,6 +614,13 @@ namespace_or_type_declaration @@ -624,6 +614,13 @@ namespace_or_type_declaration
{
current_namespace.DeclarationFound = true;
}
| attribute_sections CLOSE_BRACE {
#if FULL_AST
current_namespace.UnattachedAttributes = (Attributes) $1;
#endif
report.Error (1518, lexer.Location, "Attributes must be attached to class, delegate, enum, interface or struct");
lexer.putback ('}');
}
;
type_declaration
@ -918,6 +915,7 @@ class_member_declaration @@ -918,6 +915,7 @@ class_member_declaration
| constructor_declaration
| destructor_declaration
| type_declaration
| attributes_without_members
| error
{
report.Error (1519, lexer.Location, "Unexpected symbol `{0}' in class, struct, or interface member declaration",
@ -937,9 +935,8 @@ struct_declaration @@ -937,9 +935,8 @@ struct_declaration
}
type_declaration_name
{
MemberName name = MakeName ((MemberName) $6);
push_current_class (new Struct (current_namespace, current_class, name, (Modifiers) $2, (Attributes) $1), $3);
lbag.AddMember (current_class, GetModifierLocations (), GetLocation ($4));
push_current_container (new Struct (current_container, (MemberName) $6, (Modifiers) $2, (Attributes) $1), $3);
lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($4));
}
opt_class_base
opt_type_parameter_constraints_clauses
@ -947,10 +944,10 @@ struct_declaration @@ -947,10 +944,10 @@ struct_declaration
lexer.ConstraintsParsing = false;
if ($9 != null)
current_class.SetConstraints ((List<Constraints>) $9);
current_container.SetConstraints ((List<Constraints>) $9);
if (doc_support)
current_container.DocComment = Lexer.consume_doc_comment ();
current_container.PartialContainer.DocComment = Lexer.consume_doc_comment ();
lexer.parsing_modifiers = true;
@ -962,15 +959,17 @@ struct_declaration @@ -962,15 +959,17 @@ struct_declaration
}
opt_class_member_declarations CLOSE_BRACE
{
lbag.AppendToMember (current_class, GetLocation ($11), GetLocation ($13));
--lexer.parsing_declaration;
if (doc_support)
Lexer.doc_state = XmlCommentState.Allowed;
}
opt_semicolon
{
if ($15 != null)
current_class.OptionalSemicolon = GetLocation ($15);
if ($16 == null) {
lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($14));
} else {
lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($14), GetLocation ($16));
}
$$ = pop_current_class ();
}
| opt_attributes opt_modifiers opt_partial STRUCT error
@ -986,8 +985,8 @@ constant_declaration @@ -986,8 +985,8 @@ constant_declaration
{
var lt = (Tokenizer.LocatedToken) $5;
var mod = (Modifiers) $2;
current_field = new Const (current_class, (FullNamedExpression) $4, mod, new MemberName (lt.Value, lt.Location), (Attributes) $1);
current_container.AddConstant ((Const) current_field);
current_field = new Const (current_type, (FullNamedExpression) $4, mod, new MemberName (lt.Value, lt.Location), (Attributes) $1);
current_type.AddMember (current_field);
if ((mod & Modifiers.STATIC) != 0) {
report.Error (504, current_field.Location, "The constant `{0}' cannot be marked static", current_field.GetSignatureForError ());
@ -1068,8 +1067,8 @@ field_declaration @@ -1068,8 +1067,8 @@ field_declaration
report.Error (670, GetLocation ($3), "Fields cannot have void type");
var lt = (Tokenizer.LocatedToken) $4;
current_field = new Field (current_class, type, (Modifiers) $2, new MemberName (lt.Value, lt.Location), (Attributes) $1);
current_container.AddField (current_field);
current_field = new Field (current_type, type, (Modifiers) $2, new MemberName (lt.Value, lt.Location), (Attributes) $1);
current_type.AddField (current_field);
$$ = current_field;
}
opt_field_initializer
@ -1093,10 +1092,10 @@ field_declaration @@ -1093,10 +1092,10 @@ field_declaration
FeatureIsNotAvailable (GetLocation ($3), "fixed size buffers");
var lt = (Tokenizer.LocatedToken) $5;
current_field = new FixedField (current_class, (FullNamedExpression) $4, (Modifiers) $2,
current_field = new FixedField (current_type, (FullNamedExpression) $4, (Modifiers) $2,
new MemberName (lt.Value, lt.Location), (Attributes) $1);
current_container.AddField (current_field);
current_type.AddField (current_field);
}
fixed_field_size opt_fixed_field_declarators SEMICOLON
{
@ -1236,7 +1235,7 @@ method_declaration @@ -1236,7 +1235,7 @@ method_declaration
// Add it early in the case of body being eof for full ast
Method m = (Method) $1;
async_block = (m.ModFlags & Modifiers.ASYNC) != 0;
current_container.AddMethod (m);
current_type.AddMember (m);
}
method_body
{
@ -1285,7 +1284,7 @@ method_header @@ -1285,7 +1284,7 @@ method_header
MemberName name = (MemberName) $4;
current_local_parameters = (ParametersCompiled) $7;
var method = Method.Create (current_class, (FullNamedExpression) $3, (Modifiers) $2,
var method = Method.Create (current_type, (FullNamedExpression) $3, (Modifiers) $2,
name, current_local_parameters, (Attributes) $1, $10 != null);
if ($10 != null)
@ -1325,7 +1324,7 @@ method_header @@ -1325,7 +1324,7 @@ method_header
var modifiers = (Modifiers) $2;
modifiers |= Modifiers.PARTIAL;
var method = Method.Create (current_class, new TypeExpression (compiler.BuiltinTypes.Void, GetLocation ($4)),
var method = Method.Create (current_type, new TypeExpression (compiler.BuiltinTypes.Void, GetLocation ($4)),
modifiers, name, current_local_parameters, (Attributes) $1, $11 != null);
if ($11 != null)
@ -1347,7 +1346,7 @@ method_header @@ -1347,7 +1346,7 @@ method_header
report.Error (1585, name.Location,
"Member modifier `{0}' must precede the member type and name", ModifiersExtensions.Name ((Modifiers) $4));
var method = Method.Create (current_class, (FullNamedExpression) $3,
var method = Method.Create (current_type, (FullNamedExpression) $3,
0, name, (ParametersCompiled) $7, (Attributes) $1, false);
current_local_parameters = (ParametersCompiled) $7;
@ -1681,13 +1680,13 @@ property_declaration @@ -1681,13 +1680,13 @@ property_declaration
OPEN_BRACE
{
var type = (FullNamedExpression) $3;
current_property = new Property (current_class, type, (Modifiers) $2,
current_property = new Property (current_type, type, (Modifiers) $2,
(MemberName) $4, (Attributes) $1);
if (type.Type != null && type.Type.Kind == MemberKind.Void)
report.Error (547, GetLocation ($3), "`{0}': property or indexer cannot have void type", current_property.GetSignatureForError ());
current_container.AddProperty ((Property)current_property);
current_type.AddMember (current_property);
lbag.AddMember (current_property, GetModifierLocations (), GetLocation ($6));
lexer.PropertyParsing = true;
@ -1717,11 +1716,11 @@ indexer_declaration @@ -1717,11 +1716,11 @@ indexer_declaration
{
valid_param_mod = 0;
var type = (FullNamedExpression) $3;
Indexer indexer = new Indexer (current_class, type, (MemberName) $4, (Modifiers) $2, (ParametersCompiled) $7, (Attributes) $1);
Indexer indexer = new Indexer (current_type, type, (MemberName) $4, (Modifiers) $2, (ParametersCompiled) $7, (Attributes) $1);
current_property = indexer;
current_container.AddIndexer (indexer);
current_type.AddIndexer (indexer);
lbag.AddMember (current_property, GetModifierLocations (), GetLocation ($5), GetLocation ($8), GetLocation ($9));
if (type.Type != null && type.Type.Kind == MemberKind.Void)
@ -1893,9 +1892,8 @@ interface_declaration @@ -1893,9 +1892,8 @@ interface_declaration
}
type_declaration_name
{
MemberName name = MakeName ((MemberName) $6);
push_current_class (new Interface (current_namespace, current_class, name, (Modifiers) $2, (Attributes) $1), $3);
lbag.AddMember (current_class, GetModifierLocations (), GetLocation ($4));
push_current_container (new Interface (current_container, (MemberName) $6, (Modifiers) $2, (Attributes) $1), $3);
lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($4));
}
opt_class_base
opt_type_parameter_constraints_clauses
@ -1903,10 +1901,10 @@ interface_declaration @@ -1903,10 +1901,10 @@ interface_declaration
lexer.ConstraintsParsing = false;
if ($9 != null)
current_class.SetConstraints ((List<Constraints>) $9);
current_container.SetConstraints ((List<Constraints>) $9);
if (doc_support) {
current_container.DocComment = Lexer.consume_doc_comment ();
current_container.PartialContainer.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
@ -1920,9 +1918,11 @@ interface_declaration @@ -1920,9 +1918,11 @@ interface_declaration
}
opt_semicolon
{
if ($15 != null)
current_class.OptionalSemicolon = GetLocation ($15);
lbag.AppendToMember (current_class, GetLocation ($11), GetLocation ($13));
if ($15 == null) {
lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($13));
} else {
lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($13), GetLocation ($15));
}
$$ = pop_current_class ();
}
| opt_attributes opt_modifiers opt_partial INTERFACE error
@ -1983,7 +1983,7 @@ operator_declaration @@ -1983,7 +1983,7 @@ operator_declaration
OperatorDeclaration decl = (OperatorDeclaration) $3;
if (decl != null) {
Operator op = new Operator (
current_class, decl.optype, decl.ret_type, (Modifiers) $2,
current_type, decl.optype, decl.ret_type, (Modifiers) $2,
current_local_parameters,
(ToplevelBlock) $5, (Attributes) $1, decl.location);
@ -1996,7 +1996,7 @@ operator_declaration @@ -1996,7 +1996,7 @@ operator_declaration
}
// Note again, checking is done in semantic analysis
current_container.AddOperator (op);
current_type.AddOperator (op);
lbag.AddMember (op, GetModifierLocations (), lbag.GetLocations (decl));
if ($5 == null) { // Semicolon
@ -2186,7 +2186,7 @@ constructor_declarator @@ -2186,7 +2186,7 @@ constructor_declarator
var lt = (Tokenizer.LocatedToken) $3;
var mods = (Modifiers) $2;
var c = new Constructor (current_class, lt.Value, mods, (Attributes) $1, current_local_parameters, lt.Location);
var c = new Constructor (current_type, lt.Value, mods, (Attributes) $1, current_local_parameters, lt.Location);
if (lt.Value != current_container.MemberName.Name) {
report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
@ -2198,7 +2198,7 @@ constructor_declarator @@ -2198,7 +2198,7 @@ constructor_declarator
}
}
current_container.AddConstructor (c);
current_type.AddConstructor (c);
lbag.AddMember (c, GetModifierLocations (), GetLocation ($5), GetLocation ($7));
$$ = c;
@ -2258,8 +2258,8 @@ constructor_initializer @@ -2258,8 +2258,8 @@ constructor_initializer
}
| COLON error
{
Error_SyntaxError (yyToken);
$$ = new ConstructorThisInitializer (null, GetLocation ($1));
Error_SyntaxError (yyToken);
$$ = new ConstructorThisInitializer (null, GetLocation ($2));
lbag.AddLocation ($$, GetLocation ($1));
}
| error
@ -2288,13 +2288,13 @@ destructor_declaration @@ -2288,13 +2288,13 @@ destructor_declaration
report.Error (575, lt.Location, "Only class types can contain destructor");
}
Destructor d = new Destructor (current_class, (Modifiers) $2,
Destructor d = new Destructor (current_type, (Modifiers) $2,
ParametersCompiled.EmptyReadOnlyParameters, (Attributes) $1, lt.Location);
if (doc_support)
d.DocComment = ConsumeStoredComment ();
d.Block = (ToplevelBlock) $8;
current_container.AddMethod (d);
current_type.AddMember (d);
lbag.AddMember (d, GetModifierLocations (), GetLocation ($3), GetLocation ($6), GetLocation ($7));
current_local_parameters = null;
@ -2306,8 +2306,8 @@ event_declaration @@ -2306,8 +2306,8 @@ event_declaration
opt_modifiers
EVENT type member_declaration_name
{
current_event_field = new EventField (current_class, (FullNamedExpression) $4, (Modifiers) $2, (MemberName) $5, (Attributes) $1);
current_container.AddEvent (current_event_field);
current_event_field = new EventField (current_type, (FullNamedExpression) $4, (Modifiers) $2, (MemberName) $5, (Attributes) $1);
current_type.AddMember (current_event_field);
if (current_event_field.MemberName.ExplicitInterface != null) {
report.Error (71, current_event_field.Location, "`{0}': An explicit interface implementation of an event must use property syntax",
@ -2333,8 +2333,8 @@ event_declaration @@ -2333,8 +2333,8 @@ event_declaration
EVENT type member_declaration_name
OPEN_BRACE
{
current_event = new EventProperty (current_class, (FullNamedExpression) $4, (Modifiers) $2, (MemberName) $5, (Attributes) $1);
current_container.AddEvent (current_event);
current_event = new EventProperty (current_type, (FullNamedExpression) $4, (Modifiers) $2, (MemberName) $5, (Attributes) $1);
current_type.AddMember (current_event);
lbag.AddMember (current_event, GetModifierLocations (), GetLocation ($3), GetLocation ($6));
lexer.EventParsing = true;
@ -2511,6 +2511,16 @@ event_accessor_block @@ -2511,6 +2511,16 @@ event_accessor_block
| block;
;
attributes_without_members
: attribute_sections CLOSE_BRACE {
#if FULL_AST
current_type.UnattachedAttributes = (Attributes) $1;
#endif
report.Error (1519, GetLocation ($1), "An attribute is missing member declaration");
lexer.putback ('}');
}
;
enum_declaration
: opt_attributes
opt_modifiers
@ -2531,11 +2541,11 @@ enum_declaration @@ -2531,11 +2541,11 @@ enum_declaration
report.Error (1675, name.Location, "Enums cannot have type parameters");
}
push_current_class (new Enum (current_namespace, current_class, (TypeExpression) $5, (Modifiers) $2, MakeName (name), (Attributes) $1), null);
push_current_container (new Enum (current_container, (TypeExpression) $5, (Modifiers) $2, name, (Attributes) $1), null);
if ($5 != null) {
lbag.AddMember (current_class, GetModifierLocations (), GetLocation ($3), savedLocation, GetLocation ($7));
lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($3), savedLocation, GetLocation ($7));
} else {
lbag.AddMember (current_class, GetModifierLocations (), GetLocation ($3), GetLocation ($7));
lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($3), GetLocation ($7));
}
}
opt_enum_member_declarations
@ -2546,16 +2556,18 @@ enum_declaration @@ -2546,16 +2556,18 @@ enum_declaration
}
CLOSE_BRACE opt_semicolon
{
lbag.AppendToMember (current_class, GetLocation ($11));
lbag.AppendToMember (current_container, GetLocation ($11));
if ($12 != null) {
current_class.OptionalSemicolon = GetLocation ($12);
lbag.AppendToMember (current_class, GetLocation ($12));
lbag.AppendToMember (current_container, GetLocation ($12));
}
if (doc_support)
current_class.DocComment = enumTypeComment;
current_container.DocComment = enumTypeComment;
--lexer.parsing_declaration;
// if (doc_support)
// em.DocComment = ev.DocComment;
$$ = pop_current_class ();
}
;
@ -2585,7 +2597,7 @@ opt_enum_member_declarations @@ -2585,7 +2597,7 @@ opt_enum_member_declarations
| enum_member_declarations
| enum_member_declarations COMMA
{
lbag.AppendToMember (current_class, GetLocation ($2));
lbag.AppendToMember (current_container, GetLocation ($2));
}
;
@ -2593,7 +2605,7 @@ enum_member_declarations @@ -2593,7 +2605,7 @@ enum_member_declarations
: enum_member_declaration
| enum_member_declarations COMMA enum_member_declaration
{
lbag.AppendToMember (current_class, GetLocation ($2));
lbag.AppendToMember (current_container, GetLocation ($2));
$$ = $3;
}
;
@ -2602,8 +2614,8 @@ enum_member_declaration @@ -2602,8 +2614,8 @@ enum_member_declaration
: opt_attributes IDENTIFIER
{
var lt = (Tokenizer.LocatedToken) $2;
var em = new EnumMember ((Enum) current_class, new MemberName (lt.Value, lt.Location), (Attributes) $1);
((Enum) current_class).AddEnumMember (em);
var em = new EnumMember ((Enum) current_type, new MemberName (lt.Value, lt.Location), (Attributes) $1);
((Enum) current_type).AddEnumMember (em);
if (doc_support) {
em.DocComment = Lexer.consume_doc_comment ();
@ -2625,9 +2637,9 @@ enum_member_declaration @@ -2625,9 +2637,9 @@ enum_member_declaration
--lexer.parsing_block;
var lt = (Tokenizer.LocatedToken) $2;
var em = new EnumMember ((Enum) current_class, new MemberName (lt.Value, lt.Location), (Attributes) $1);
var em = new EnumMember ((Enum) current_type, new MemberName (lt.Value, lt.Location), (Attributes) $1);
em.Initializer = new ConstInitializer (em, (Expression) $5, GetLocation ($4));
((Enum) current_class).AddEnumMember (em);
((Enum) current_type).AddEnumMember (em);
if (doc_support)
em.DocComment = ConsumeStoredComment ();
@ -2649,17 +2661,14 @@ delegate_declaration @@ -2649,17 +2661,14 @@ delegate_declaration
{
valid_param_mod = 0;
MemberName name = MakeName ((MemberName) $5);
ParametersCompiled p = (ParametersCompiled) $8;
Delegate del = new Delegate (current_namespace, current_class, (FullNamedExpression) $4,
(Modifiers) $2, name, p, (Attributes) $1);
Delegate del = new Delegate (current_container, (FullNamedExpression) $4, (Modifiers) $2, (MemberName) $5, p, (Attributes) $1);
p.CheckParameters (del);
ubag.PushTypeDeclaration (del);
ubag.PopTypeDeclaration ();
current_container.AddTypeContainer (del);
current_container.AddDelegate (del);
current_delegate = del;
lexer.ConstraintsParsing = true;
}
@ -2805,12 +2814,12 @@ indexer_declaration_name @@ -2805,12 +2814,12 @@ indexer_declaration_name
: THIS
{
lexer.parsing_generic_declaration = false;
$$ = new MemberName (TypeContainer.DefaultIndexerName, GetLocation ($1));
$$ = new MemberName (TypeDefinition.DefaultIndexerName, GetLocation ($1));
}
| explicit_interface THIS
{
lexer.parsing_generic_declaration = false;
$$ = new MemberName (TypeContainer.DefaultIndexerName, null, (ATypeNameExpression) $1, GetLocation ($2));
$$ = new MemberName (TypeDefinition.DefaultIndexerName, null, (ATypeNameExpression) $1, GetLocation ($2));
}
;
@ -4185,11 +4194,11 @@ lambda_expression_body @@ -4185,11 +4194,11 @@ lambda_expression_body
lambda_expression_body_simple
: {
start_block (lexer.Location);
start_block (Location.Null);
}
expression_or_error // Have to close block when error occurs
{
Block b = end_block (lexer.Location);
Block b = end_block (Location.Null);
b.IsCompilerGenerated = true;
b.AddStatement (new ContextualReturn ((Expression) $2));
$$ = b;
@ -4315,13 +4324,13 @@ class_declaration @@ -4315,13 +4324,13 @@ class_declaration
}
type_declaration_name
{
MemberName name = MakeName ((MemberName) $6);
Class c = new Class (current_namespace, current_class, name, (Modifiers) $2, (Attributes) $1);
Class c = new Class (current_container, (MemberName) $6, (Modifiers) $2, (Attributes) $1);
if (((c.ModFlags & Modifiers.STATIC) != 0) && lang_version == LanguageVersion.ISO_1) {
FeatureIsNotAvailable (c.Location, "static classes");
}
push_current_class (c, $3);
push_current_container (c, $3);
lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($4));
}
opt_class_base
opt_type_parameter_constraints_clauses
@ -4329,11 +4338,10 @@ class_declaration @@ -4329,11 +4338,10 @@ class_declaration
lexer.ConstraintsParsing = false;
if ($9 != null)
current_class.SetConstraints ((List<Constraints>) $9);
lbag.AddMember (current_class, GetModifierLocations (), GetLocation ($4));
current_container.SetConstraints ((List<Constraints>) $9);
if (doc_support) {
current_container.DocComment = Lexer.consume_doc_comment ();
current_container.PartialContainer.DocComment = Lexer.consume_doc_comment ();
Lexer.doc_state = XmlCommentState.Allowed;
}
@ -4347,9 +4355,11 @@ class_declaration @@ -4347,9 +4355,11 @@ class_declaration
}
opt_semicolon
{
lbag.AppendToMember (current_class, GetLocation ($11), GetLocation ($13));
if ($15 != null)
current_class.OptionalSemicolon = GetLocation ($15);
if ($15 == null) {
lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($13));
} else {
lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($13), GetLocation ($15));
}
$$ = pop_current_class ();
}
;
@ -4400,7 +4410,7 @@ modifier @@ -4400,7 +4410,7 @@ modifier
$$ = Modifiers.NEW;
StoreModifierLocation ($$, GetLocation ($1));
if (current_container == module)
if (current_container.Kind == MemberKind.Namespace)
report.Error (1530, GetLocation ($1), "Keyword `new' is not allowed on namespace elements");
}
| PUBLIC
@ -4481,8 +4491,8 @@ opt_class_base @@ -4481,8 +4491,8 @@ opt_class_base
: /* empty */
| COLON type_list
{
lbag.AppendToMember (current_class, GetLocation ($1));
current_container.AddBasesForPart (current_class, (List<FullNamedExpression>) $2);
current_type.AddBasesForPart ((List<FullNamedExpression>) $2);
lbag.AppendToMember (current_type, GetLocation ($1));
}
;
@ -5069,6 +5079,12 @@ expression_statement @@ -5069,6 +5079,12 @@ expression_statement
lbag.AddStatement ($$, GetLocation ($2));
}
| statement_expression COMPLETE_COMPLETION { $$ = $1; }
| statement_expression CLOSE_BRACE {
$$ = $1;
lbag.AddStatement ($$, GetLocation ($2));
report.Error (1525, "Unexpected symbol '}' after statement, expecting ';'");
lexer.putback ('}');
}
;
interactive_expression_statement
@ -5563,7 +5579,7 @@ try_statement @@ -5563,7 +5579,7 @@ try_statement
}
| TRY block catch_clauses FINALLY block
{
$$ = new TryFinally (new TryCatch ((Block) $2, (List<Catch>) $3, GetLocation ($1), true), (Block) $5, GetLocation ($1));
$$ = new TryFinally (new TryCatch ((Block) $2, (List<Catch>) $3, Location.Null, true), (Block) $5, GetLocation ($1));
lbag.AddStatement ($$, GetLocation ($4));
}
| TRY block error
@ -5865,7 +5881,7 @@ from_clause @@ -5865,7 +5881,7 @@ from_clause
{
current_block = new Linq.QueryBlock (current_block, lexer.Location);
}
expression
expression_or_error
{
var lt = (Tokenizer.LocatedToken) $2;
var sn = new Linq.RangeVariable (lt.Value, lt.Location);
@ -5880,7 +5896,7 @@ from_clause @@ -5880,7 +5896,7 @@ from_clause
{
current_block = new Linq.QueryBlock (current_block, lexer.Location);
}
expression
expression_or_error
{
var lt = (Tokenizer.LocatedToken) $3;
var sn = new Linq.RangeVariable (lt.Value, lt.Location);
@ -5925,7 +5941,7 @@ select_or_group_clause @@ -5925,7 +5941,7 @@ select_or_group_clause
{
current_block = new Linq.QueryBlock (current_block, lexer.Location);
}
expression
expression_or_error
{
$$ = new Linq.Select ((Linq.QueryBlock)current_block, (Expression)$3, GetLocation ($1));
@ -5940,14 +5956,14 @@ select_or_group_clause @@ -5940,14 +5956,14 @@ select_or_group_clause
current_block = new Linq.QueryBlock (current_block, lexer.Location);
linq_clause_blocks.Push ((Linq.QueryBlock)current_block);
}
expression
expression_or_error
{
current_block.SetEndLocation (lexer.Location);
current_block = current_block.Parent;
current_block = new Linq.QueryBlock (current_block, lexer.Location);
}
BY expression
BY expression_or_error
{
$$ = new Linq.GroupBy ((Linq.QueryBlock)current_block, (Expression)$3, linq_clause_blocks.Pop (), (Expression)$6, GetLocation ($1));
lbag.AddLocation ($$, GetLocation ($5));
@ -5984,7 +6000,7 @@ let_clause @@ -5984,7 +6000,7 @@ let_clause
{
current_block = new Linq.QueryBlock (current_block, lexer.Location);
}
expression
expression_or_error
{
var lt = (Tokenizer.LocatedToken) $2;
var sn = new Linq.RangeVariable (lt.Value, lt.Location);
@ -6003,7 +6019,7 @@ where_clause @@ -6003,7 +6019,7 @@ where_clause
{
current_block = new Linq.QueryBlock (current_block, lexer.Location);
}
expression
expression_or_error
{
$$ = new Linq.Where ((Linq.QueryBlock)current_block, (Expression)$3, GetLocation ($1));
@ -6021,7 +6037,7 @@ join_clause @@ -6021,7 +6037,7 @@ join_clause
current_block = new Linq.QueryBlock (current_block, lexer.Location);
linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
}
expression ON
expression_or_error ON
{
current_block.SetEndLocation (lexer.Location);
current_block = current_block.Parent;
@ -6029,7 +6045,7 @@ join_clause @@ -6029,7 +6045,7 @@ join_clause
current_block = new Linq.QueryBlock (current_block, lexer.Location);
linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
}
expression EQUALS
expression_or_error EQUALS
{
current_block.AddStatement (new ContextualReturn ((Expression) $8));
current_block.SetEndLocation (lexer.Location);
@ -6037,7 +6053,7 @@ join_clause @@ -6037,7 +6053,7 @@ join_clause
current_block = new Linq.QueryBlock (current_block, lexer.Location);
}
expression opt_join_into
expression_or_error opt_join_into
{
current_block.AddStatement (new ContextualReturn ((Expression) $11));
current_block.SetEndLocation (lexer.Location);
@ -6083,7 +6099,7 @@ join_clause @@ -6083,7 +6099,7 @@ join_clause
current_block = new Linq.QueryBlock (current_block, lexer.Location);
linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
}
expression ON
expression_or_error ON
{
current_block.SetEndLocation (lexer.Location);
current_block = current_block.Parent;
@ -6091,7 +6107,7 @@ join_clause @@ -6091,7 +6107,7 @@ join_clause
current_block = new Linq.QueryBlock (current_block, lexer.Location);
linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
}
expression EQUALS
expression_or_error EQUALS
{
current_block.AddStatement (new ContextualReturn ((Expression) $9));
current_block.SetEndLocation (lexer.Location);
@ -6099,7 +6115,7 @@ join_clause @@ -6099,7 +6115,7 @@ join_clause
current_block = new Linq.QueryBlock (current_block, lexer.Location);
}
expression opt_join_into
expression_or_error opt_join_into
{
current_block.AddStatement (new ContextualReturn ((Expression) $12));
current_block.SetEndLocation (lexer.Location);
@ -6277,8 +6293,7 @@ interactive_parsing @@ -6277,8 +6293,7 @@ interactive_parsing
| EVAL_USING_DECLARATIONS_UNIT_PARSER using_directives opt_COMPLETE_COMPLETION
| EVAL_STATEMENT_PARSER
{
current_container = new Class (current_namespace, current_class, new MemberName ("<InteractiveExpressionClass>"), Modifiers.PUBLIC, null);
current_class = current_container;
current_container = current_type = new Class (current_container, new MemberName ("<InteractiveExpressionClass>"), Modifiers.PUBLIC, null);
// (ref object retval)
Parameter [] mpar = new Parameter [1];
@ -6291,14 +6306,14 @@ interactive_parsing @@ -6291,14 +6306,14 @@ interactive_parsing
current_local_parameters = pars;
Method method = new Method (
current_class,
current_type,
new TypeExpression (compiler.BuiltinTypes.Void, Location.Null),
mods,
new MemberName ("Host"),
pars,
null /* attributes */);
current_container.AddMethod (method);
current_type.AddMember (method);
oob_stack.Push (method);
++lexer.parsing_block;
@ -6515,51 +6530,34 @@ void Error_MissingInitializer (Location loc) @@ -6515,51 +6530,34 @@ void Error_MissingInitializer (Location loc)
report.Error (210, loc, "You must provide an initializer in a fixed or using statement declaration");
}
void push_current_class (TypeContainer tc, object partial_token)
void push_current_container (TypeDefinition tc, object partial_token)
{
if (module.Evaluator != null && current_container is ModuleContainer){
if (module.Evaluator != null){
tc.Definition.Modifiers = tc.ModFlags = (tc.ModFlags & ~Modifiers.AccessibilityMask) | Modifiers.PUBLIC;
if (undo == null)
undo = new Undo ();
undo.AddTypeContainer (current_container, tc);
}
if (partial_token != null)
current_container = current_container.AddPartial (tc);
current_container.AddPartial (tc);
else
current_container = current_container.AddTypeContainer (tc);
current_container.AddTypeContainer (tc);
++lexer.parsing_declaration;
current_class = tc;
ubag.PushTypeDeclaration (tc);
current_container = tc;
current_type = tc;
}
TypeContainer pop_current_class ()
{
var retval = current_class;
var retval = current_container;
current_class = current_class.Parent;
current_container = current_class.PartialContainer;
ubag.PopTypeDeclaration ();
return retval;
}
current_container = current_container.Parent;
current_type = current_type.Parent as TypeDefinition;
// <summary>
// Given the @class_name name, it creates a fully qualified name
// based on the containing declaration space
// </summary>
MemberName
MakeName (MemberName class_name)
{
if (current_container == module) {
if (current_namespace.MemberName != MemberName.Null)
return new MemberName (current_namespace.NS.MemberName, class_name);
else
return class_name;
} else {
return new MemberName (current_container.MemberName, class_name);
}
return retval;
}
[System.Diagnostics.Conditional ("FULL_AST")]
@ -6629,26 +6627,31 @@ static CSharpParser () @@ -6629,26 +6627,31 @@ static CSharpParser ()
}
public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file)
: this (reader, file, file.NamespaceContainer.Module.Compiler.Report)
: this (reader, file, file.Compiler.Report)
{
}
public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, Report report)
{
this.file = file;
current_namespace = file.NamespaceContainer;
current_container = current_namespace = file;
this.module = current_namespace.Module;
this.compiler = module.Compiler;
this.module = file.Module;
this.compiler = file.Compiler;
this.settings = compiler.Settings;
this.report = report;
lang_version = settings.Version;
yacc_verbose_flag = settings.VerboseParserFlag;
doc_support = settings.DocumentationFile != null;
current_class = current_namespace.SlaveDeclSpace;
current_container = current_class.PartialContainer; // == RootContest.ToplevelTypes
oob_stack.Clear ();
lexer = new Tokenizer (reader, file, compiler);
lexer = new Tokenizer (reader, file);
#if FULL_AST
lbag = new LocationsBag ();
#else
lbag = null;
#endif
use_global_stacks = true;
}
@ -6727,18 +6730,6 @@ public LocationsBag LocationsBag { @@ -6727,18 +6730,6 @@ public LocationsBag LocationsBag {
get {
return lbag;
}
set {
lbag = value;
}
}
public UsingsBag UsingsBag {
get {
return ubag;
}
set {
ubag = value;
}
}
void start_block (Location loc)

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

@ -73,7 +73,8 @@ namespace Mono.CSharp @@ -73,7 +73,8 @@ namespace Mono.CSharp
{
int row, column;
string value;
static LocatedToken[] buffer;
static LocatedToken[] buffer = new LocatedToken[0];
static int pos;
private LocatedToken ()
@ -129,8 +130,10 @@ namespace Mono.CSharp @@ -129,8 +130,10 @@ namespace Mono.CSharp
public static void Initialize ()
{
if (buffer == null)
buffer = new LocatedToken [10000];
#if !FULL_AST
if (buffer.Length == 0)
buffer = new LocatedToken [15000];
#endif
pos = 0;
}
@ -158,23 +161,24 @@ namespace Mono.CSharp @@ -158,23 +161,24 @@ namespace Mono.CSharp
Error = 9,
Warning = 10,
Pragma = 11 | CustomArgumentsParsing,
Line = 12,
Line = 12 | CustomArgumentsParsing,
CustomArgumentsParsing = 1 << 10,
RequiresArgument = 1 << 11
}
SeekableStreamReader reader;
SourceFile ref_name;
CompilationSourceFile file_name;
CompilerContext context;
bool hidden = false;
readonly SeekableStreamReader reader;
readonly CompilationSourceFile source_file;
readonly CompilerContext context;
SourceFile current_source;
Location hidden_block_start;
int ref_line = 1;
int line = 1;
int col = 0;
int previous_col;
int current_token;
int tab_size;
readonly int tab_size;
bool handle_get_set = false;
bool handle_remove_add = false;
bool handle_where = false;
@ -263,7 +267,7 @@ namespace Mono.CSharp @@ -263,7 +267,7 @@ namespace Mono.CSharp
//
static readonly KeywordEntry<int>[][] keywords;
static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
static readonly Dictionary<string, object> keyword_strings; // TODO: HashSet
static readonly HashSet<string> keyword_strings;
static readonly NumberStyles styles;
static readonly NumberFormatInfo csharp_format_info;
@ -272,6 +276,9 @@ namespace Mono.CSharp @@ -272,6 +276,9 @@ namespace Mono.CSharp
static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
static readonly char[] pragma_checksum = "checksum".ToCharArray ();
static readonly char[] line_hidden = "hidden".ToCharArray ();
static readonly char[] line_default = "default".ToCharArray ();
static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
bool startsLine = true;
internal SpecialsBag sbag;
@ -295,12 +302,7 @@ namespace Mono.CSharp @@ -295,12 +302,7 @@ namespace Mono.CSharp
get { return handle_typeof; }
set { handle_typeof = value; }
}
public int TabSize {
get { return tab_size; }
set { tab_size = value; }
}
public XmlCommentState doc_state {
get { return xml_doc_state; }
set {
@ -348,14 +350,27 @@ namespace Mono.CSharp @@ -348,14 +350,27 @@ namespace Mono.CSharp
//
Stack<int> ifstack;
static System.Text.StringBuilder string_builder;
const int max_id_size = 512;
static readonly char[] id_builder = new char [max_id_size];
public static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
const int max_number_size = 512;
static char[] number_builder = new char [max_number_size];
#if FULL_AST
readonly char [] id_builder = new char [max_id_size];
Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
char [] number_builder = new char [max_number_size];
int number_pos;
char[] value_builder = new char[256];
#else
static readonly char [] id_builder = new char [max_id_size];
static Dictionary<char[], string>[] identifiers = new Dictionary<char[], string>[max_id_size + 1];
static char [] number_builder = new char [max_number_size];
static int number_pos;
static char[] value_builder = new char[256];
#endif
public int Line {
get {
@ -377,7 +392,7 @@ namespace Mono.CSharp @@ -377,7 +392,7 @@ namespace Mono.CSharp
public int line;
public int ref_line;
public int col;
public bool hidden;
public Location hidden;
public int putback_char;
public int previous_col;
public Stack<int> ifstack;
@ -391,7 +406,7 @@ namespace Mono.CSharp @@ -391,7 +406,7 @@ namespace Mono.CSharp
line = t.line;
ref_line = t.ref_line;
col = t.col;
hidden = t.hidden;
hidden = t.hidden_block_start;
putback_char = t.putback_char;
previous_col = t.previous_col;
if (t.ifstack != null && t.ifstack.Count != 0) {
@ -407,24 +422,22 @@ namespace Mono.CSharp @@ -407,24 +422,22 @@ namespace Mono.CSharp
}
}
public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, CompilerContext ctx)
public Tokenizer (SeekableStreamReader input, CompilationSourceFile file)
{
this.ref_name = file;
this.file_name = file;
this.context = ctx;
this.source_file = file;
this.context = file.Compiler;
this.current_source = file.SourceFile;
reader = input;
putback_char = -1;
xml_comment_buffer = new StringBuilder ();
doc_processing = ctx.Settings.DocumentationFile != null;
doc_processing = context.Settings.DocumentationFile != null;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
tab_size = 4;
else
tab_size = 8;
tab_size = context.Settings.TabSize;
Mono.CSharp.Location.Push (file, file);
Mono.CSharp.Location.Push (current_source);
}
public void PushPosition ()
@ -440,7 +453,7 @@ namespace Mono.CSharp @@ -440,7 +453,7 @@ namespace Mono.CSharp
ref_line = p.ref_line;
line = p.line;
col = p.col;
hidden = p.hidden;
hidden_block_start = p.hidden;
putback_char = p.putback_char;
previous_col = p.previous_col;
ifstack = p.ifstack;
@ -457,7 +470,7 @@ namespace Mono.CSharp @@ -457,7 +470,7 @@ namespace Mono.CSharp
static void AddKeyword (string kw, int token)
{
keyword_strings.Add (kw, null);
keyword_strings.Add (kw);
AddKeyword (keywords, kw, token);
}
@ -493,7 +506,7 @@ namespace Mono.CSharp @@ -493,7 +506,7 @@ namespace Mono.CSharp
//
static Tokenizer ()
{
keyword_strings = new Dictionary<string, object> ();
keyword_strings = new HashSet<string> ();
// 11 is the length of the longest keyword for now
keywords = new KeywordEntry<int>[11][];
@ -621,8 +634,6 @@ namespace Mono.CSharp @@ -621,8 +634,6 @@ namespace Mono.CSharp
csharp_format_info = NumberFormatInfo.InvariantInfo;
styles = NumberStyles.Float;
string_builder = new System.Text.StringBuilder ();
}
int GetKeyword (char[] id, int id_len)
@ -872,7 +883,7 @@ namespace Mono.CSharp @@ -872,7 +883,7 @@ namespace Mono.CSharp
public Location Location {
get {
return new Location (ref_line, hidden ? -1 : col);
return new Location (ref_line, col);
}
}
@ -900,7 +911,7 @@ namespace Mono.CSharp @@ -900,7 +911,7 @@ namespace Mono.CSharp
public static bool IsKeyword (string s)
{
return keyword_strings.ContainsKey (s);
return keyword_strings.Contains (s);
}
//
@ -1511,6 +1522,12 @@ namespace Mono.CSharp @@ -1511,6 +1522,12 @@ namespace Mono.CSharp
#if FULL_AST
int read_start = reader.Position - 1;
if (c == '.') {
//
// Caller did peek_char
//
--read_start;
}
#endif
number_pos = 0;
var loc = Location;
@ -1596,10 +1613,10 @@ namespace Mono.CSharp @@ -1596,10 +1613,10 @@ namespace Mono.CSharp
val = res;
#if FULL_AST
var endPos = reader.Position - (type == TypeCode.Empty ? 1 : 0);
if (reader.GetChar (endPos - 1) == '\r')
endPos--;
res.ParsedValue = reader.ReadChars (hasLeadingDot ? read_start - 1 : read_start, endPos);
var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
if (chars[chars.Length - 1] == '\r')
Array.Resize (ref chars, chars.Length - 1);
res.ParsedValue = chars;
#endif
return Token.LITERAL;
@ -1774,12 +1791,12 @@ namespace Mono.CSharp @@ -1774,12 +1791,12 @@ namespace Mono.CSharp
return reader.Peek ();
}
void putback (int c)
public void putback (int c)
{
if (putback_char != -1){
Console.WriteLine ("Col: " + col);
Console.WriteLine ("Row: " + line);
Console.WriteLine ("Name: " + ref_name.Name);
Console.WriteLine ("Name: " + current_source.Name);
Console.WriteLine ("Current [{0}] putting back [{1}] ", putback_char, c);
throw new Exception ("This should not happen putback on putback");
}
@ -1940,44 +1957,120 @@ namespace Mono.CSharp @@ -1940,44 +1957,120 @@ namespace Mono.CSharp
//
// Handles the #line directive
//
bool PreProcessLine (string arg)
bool PreProcessLine ()
{
if (arg.Length == 0)
return false;
Location loc = Location;
int c;
int length = TokenizePreprocessorIdentifier (out c);
if (length == line_default.Length) {
if (!IsTokenIdentifierEqual (line_default))
return false;
current_source = source_file.SourceFile;
if (!hidden_block_start.IsNull) {
current_source.RegisterHiddenScope (hidden_block_start, loc);
hidden_block_start = Location.Null;
}
if (arg == "default"){
ref_line = line;
ref_name = file_name;
hidden = false;
Location.Push (file_name, ref_name);
Location.Push (current_source);
return true;
} else if (arg == "hidden"){
hidden = true;
}
if (length == line_hidden.Length) {
if (!IsTokenIdentifierEqual (line_hidden))
return false;
if (hidden_block_start.IsNull)
hidden_block_start = loc;
return true;
}
try {
int pos;
if ((pos = arg.IndexOf (' ')) != -1 && pos != 0){
ref_line = System.Int32.Parse (arg.Substring (0, pos));
pos++;
char [] quotes = { '\"' };
string name = arg.Substring (pos). Trim (quotes);
ref_name = context.LookupFile (file_name, name);
file_name.AddIncludeFile (ref_name);
hidden = false;
Location.Push (file_name, ref_name);
} else {
ref_line = System.Int32.Parse (arg);
hidden = false;
if (length != 0 || c < '0' || c > '9') {
//
// Eat any remaining characters to continue parsing on next line
//
while (c != -1 && c != '\n') {
c = get_char ();
}
} catch {
return false;
}
int new_line = TokenizeNumber (c);
if (new_line < 1) {
//
// Eat any remaining characters to continue parsing on next line
//
while (c != -1 && c != '\n') {
c = get_char ();
}
return new_line != 0;
}
c = get_char ();
if (c == ' ') {
// skip over white space
do {
c = get_char ();
} while (c == ' ' || c == '\t');
} else if (c == '"') {
c = 0;
}
if (c != '\n' && c != '/' && c != '"') {
//
// Eat any remaining characters to continue parsing on next line
//
while (c != -1 && c != '\n') {
c = get_char ();
}
Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
return true;
}
string new_file_name = null;
if (c == '"') {
new_file_name = TokenizeFileName (ref c);
// skip over white space
while (c == ' ' || c == '\t') {
c = get_char ();
}
}
if (c == '\n') {
} else if (c == '/') {
ReadSingleLineComment ();
} else {
//
// Eat any remaining characters to continue parsing on next line
//
while (c != -1 && c != '\n') {
c = get_char ();
}
Error_EndLineExpected ();
return true;
}
if (new_file_name != null) {
current_source = context.LookupFile (source_file, new_file_name);
source_file.AddIncludeFile (current_source);
Location.Push (current_source);
}
if (!hidden_block_start.IsNull) {
current_source.RegisterHiddenScope (hidden_block_start, loc);
hidden_block_start = Location.Null;
}
ref_line = new_line;
return true;
}
@ -2016,12 +2109,12 @@ namespace Mono.CSharp @@ -2016,12 +2109,12 @@ namespace Mono.CSharp
if (context.Settings.IsConditionalSymbolDefined (ident))
return;
file_name.AddDefine (ident);
source_file.AddDefine (ident);
} else {
//
// #undef ident
//
file_name.AddUndefine (ident);
source_file.AddUndefine (ident);
}
}
@ -2072,26 +2165,13 @@ namespace Mono.CSharp @@ -2072,26 +2165,13 @@ namespace Mono.CSharp
if (c != '"')
return false;
string_builder.Length = 0;
while (c != -1 && c != '\n') {
c = get_char ();
if (c == '"') {
c = get_char ();
break;
}
string_builder.Append ((char) c);
}
if (string_builder.Length == 0) {
Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
}
string file_name = TokenizeFileName (ref c);
// TODO: Any white-spaces count
if (c != ' ')
return false;
SourceFile file = context.LookupFile (file_name, string_builder.ToString ());
SourceFile file = context.LookupFile (source_file, file_name);
if (get_char () != '"' || get_char () != '{')
return false;
@ -2158,7 +2238,7 @@ namespace Mono.CSharp @@ -2158,7 +2238,7 @@ namespace Mono.CSharp
}
file.SetChecksum (guid_bytes, checksum_bytes.ToArray ());
ref_name.AutoGenerated = true;
current_source.AutoGenerated = true;
return true;
}
@ -2172,27 +2252,53 @@ namespace Mono.CSharp @@ -2172,27 +2252,53 @@ namespace Mono.CSharp
return true;
}
int TokenizePragmaNumber (ref int c)
int TokenizeNumber (int value)
{
number_pos = 0;
int number;
decimal_digits (value);
uint ui = (uint) (number_builder[0] - '0');
if (c >= '0' && c <= '9') {
decimal_digits (c);
uint ui = (uint) (number_builder[0] - '0');
try {
for (int i = 1; i < number_pos; i++) {
ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
}
try {
for (int i = 1; i < number_pos; i++) {
ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
}
return (int) ui;
} catch (OverflowException) {
Error_NumericConstantTooLong ();
return -1;
}
}
number = (int) ui;
} catch (OverflowException) {
Error_NumericConstantTooLong ();
number = -1;
string TokenizeFileName (ref int c)
{
var string_builder = new StringBuilder ();
while (c != -1 && c != '\n') {
c = get_char ();
if (c == '"') {
c = get_char ();
break;
}
string_builder.Append ((char) c);
}
if (string_builder.Length == 0) {
Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
}
return string_builder.ToString ();
}
int TokenizePragmaNumber (ref int c)
{
number_pos = 0;
int number;
if (c >= '0' && c <= '9') {
number = TokenizeNumber (c);
c = get_char ();
@ -2287,9 +2393,9 @@ namespace Mono.CSharp @@ -2287,9 +2393,9 @@ namespace Mono.CSharp
code = TokenizePragmaNumber (ref c);
if (code > 0) {
if (disable) {
Report.RegisterWarningRegion (loc).WarningDisable (loc, code, Report);
Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
} else {
Report.RegisterWarningRegion (loc).WarningEnable (loc, code, Report);
Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
}
}
} while (code >= 0 && c != '\n' && c != -1);
@ -2325,7 +2431,7 @@ namespace Mono.CSharp @@ -2325,7 +2431,7 @@ namespace Mono.CSharp
if (s == "false")
return false;
return file_name.IsConditionalDefined (context, s);
return source_file.IsConditionalDefined (s);
}
bool pp_primary (ref string s)
@ -2715,10 +2821,10 @@ namespace Mono.CSharp @@ -2715,10 +2821,10 @@ namespace Mono.CSharp
return true;
case PreprocessorDirective.Line:
if (!PreProcessLine (arg))
Report.Error (
1576, Location,
"The line number specified for #line directive is missing or invalid");
Location loc = Location;
if (!PreProcessLine ())
Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
return caller_is_taking;
}
@ -2897,7 +3003,7 @@ namespace Mono.CSharp @@ -2897,7 +3003,7 @@ namespace Mono.CSharp
return Token.IDENTIFIER;
}
static string InternIdentifier (char[] charBuffer, int length)
string InternIdentifier (char[] charBuffer, int length)
{
//
// Keep identifiers in an array of hashtables to avoid needless

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

@ -15,6 +15,7 @@ @@ -15,6 +15,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
#if NET_2_1
using XmlElement = System.Object;
@ -96,12 +97,6 @@ namespace Mono.CSharp { @@ -96,12 +97,6 @@ namespace Mono.CSharp {
this.Left = left;
}
// TODO: Remove
public string GetName ()
{
return GetName (false);
}
public int Arity {
get {
return TypeParameters == null ? 0 : TypeParameters.Count;
@ -110,24 +105,10 @@ namespace Mono.CSharp { @@ -110,24 +105,10 @@ namespace Mono.CSharp {
public bool IsGeneric {
get {
if (TypeParameters != null)
return true;
else if (Left != null)
return Left.IsGeneric;
else
return false;
return TypeParameters != null;
}
}
public string GetName (bool is_generic)
{
string name = is_generic ? Basename : Name;
if (Left != null)
return Left.GetName (is_generic) + "." + name;
return name;
}
public string Basename {
get {
if (TypeParameters != null)
@ -136,6 +117,31 @@ namespace Mono.CSharp { @@ -136,6 +117,31 @@ namespace Mono.CSharp {
}
}
public void CreateMetadataName (StringBuilder sb)
{
if (Left != null)
Left.CreateMetadataName (sb);
if (sb.Length != 0) {
sb.Append (".");
}
sb.Append (Basename);
}
public string GetSignatureForDocumentation ()
{
var s = Basename;
if (ExplicitInterface != null)
s = ExplicitInterface.GetSignatureForError () + "." + s;
if (Left == null)
return s;
return Left.GetSignatureForDocumentation () + "." + s;
}
public string GetSignatureForError ()
{
string s = TypeParameters == null ? null : "<" + TypeParameters.GetSignatureForError () + ">";
@ -290,7 +296,9 @@ namespace Mono.CSharp { @@ -290,7 +296,9 @@ namespace Mono.CSharp {
IsAssigned = 1 << 12, // Field is assigned
HasExplicitLayout = 1 << 13,
PartialDefinitionExists = 1 << 14, // Set when corresponding partial method definition exists
HasStructLayout = 1 << 15 // Has StructLayoutAttribute
HasStructLayout = 1 << 15, // Has StructLayoutAttribute
HasInstanceConstructor = 1 << 16,
HasUserOperators = 1 << 17
}
/// <summary>
@ -398,10 +406,11 @@ namespace Mono.CSharp { @@ -398,10 +406,11 @@ namespace Mono.CSharp {
//
public virtual string GetSignatureForError ()
{
if (Parent == null || Parent.Parent == null)
var parent = Parent.GetSignatureForError ();
if (parent == null)
return member_name.GetSignatureForError ();
return Parent.GetSignatureForError () + "." + member_name.GetSignatureForError ();
return parent + "." + member_name.GetSignatureForError ();
}
/// <summary>
@ -553,7 +562,7 @@ namespace Mono.CSharp { @@ -553,7 +562,7 @@ namespace Mono.CSharp {
case Modifiers.PROTECTED:
if (al == Modifiers.PROTECTED) {
same_access_restrictions = mc.Parent.IsBaseTypeDefinition (p_parent);
same_access_restrictions = mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent);
break;
}
@ -562,8 +571,8 @@ namespace Mono.CSharp { @@ -562,8 +571,8 @@ namespace Mono.CSharp {
// When type is private and any of its parents derives from
// protected type then the type is accessible
//
while (mc.Parent != null) {
if (mc.Parent.IsBaseTypeDefinition (p_parent))
while (mc.Parent != null && mc.Parent.PartialContainer != null) {
if (mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent))
same_access_restrictions = true;
mc = mc.Parent;
}
@ -575,7 +584,7 @@ namespace Mono.CSharp { @@ -575,7 +584,7 @@ namespace Mono.CSharp {
if (al == Modifiers.INTERNAL)
same_access_restrictions = p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
else if (al == (Modifiers.PROTECTED | Modifiers.INTERNAL))
same_access_restrictions = mc.Parent.IsBaseTypeDefinition (p_parent) && p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
same_access_restrictions = mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent) && p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
else
goto case Modifiers.PROTECTED;
@ -589,7 +598,7 @@ namespace Mono.CSharp { @@ -589,7 +598,7 @@ namespace Mono.CSharp {
var decl = mc.Parent;
do {
same_access_restrictions = decl.CurrentType == p_parent;
} while (!same_access_restrictions && !decl.IsTopLevel && (decl = decl.Parent) != null);
} while (!same_access_restrictions && !decl.PartialContainer.IsTopLevel && (decl = decl.Parent) != null);
}
break;
@ -624,7 +633,7 @@ namespace Mono.CSharp { @@ -624,7 +633,7 @@ namespace Mono.CSharp {
return true;
}
if (Parent.PartialContainer.IsClsComplianceRequired ()) {
if (Parent.IsClsComplianceRequired ()) {
caching_flags |= Flags.ClsCompliant;
return true;
}
@ -643,25 +652,40 @@ namespace Mono.CSharp { @@ -643,25 +652,40 @@ namespace Mono.CSharp {
public bool IsExposedFromAssembly ()
{
if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
return false;
return this is NamespaceContainer;
var parentContainer = Parent.PartialContainer;
while (parentContainer != null && parentContainer.ModFlags != 0) {
while (parentContainer != null) {
if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
return false;
parentContainer = parentContainer.Parent;
parentContainer = parentContainer.Parent.PartialContainer;
}
return true;
}
public virtual ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
//
// Does extension methods look up to find a method which matches name and extensionType.
// Search starts from this namespace and continues hierarchically up to top level.
//
public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
{
return Parent.LookupExtensionMethod (extensionType, name, arity);
var m = Parent;
do {
var ns = m as NamespaceContainer;
if (ns != null)
return ns.LookupExtensionMethod (this, extensionType, name, arity, ns, 0);
m = m.Parent;
} while (m != null);
return null;
}
public virtual FullNamedExpression LookupNamespaceAlias (string name)
{
return Parent.NamespaceEntry.LookupNamespaceAlias (name);
return Parent.LookupNamespaceAlias (name);
}
public virtual FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
@ -747,7 +771,7 @@ namespace Mono.CSharp { @@ -747,7 +771,7 @@ namespace Mono.CSharp {
}
if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
if (Parent.Kind == MemberKind.Interface && Parent.IsClsComplianceRequired ()) {
if (Parent is Interface && Parent.IsClsComplianceRequired ()) {
Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
} else if (Parent.Kind == MemberKind.Class && (ModFlags & Modifiers.ABSTRACT) != 0 && Parent.IsClsComplianceRequired ()) {
Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
@ -756,7 +780,7 @@ namespace Mono.CSharp { @@ -756,7 +780,7 @@ namespace Mono.CSharp {
return false;
}
if (Parent.Parent != null && !Parent.IsClsComplianceRequired ()) {
if (Parent.Kind != MemberKind.Namespace && Parent.Kind != 0 && !Parent.IsClsComplianceRequired ()) {
Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
Report.Warning (3018, 1, a.Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
GetSignatureForError (), Parent.GetSignatureForError ());
@ -766,12 +790,12 @@ namespace Mono.CSharp { @@ -766,12 +790,12 @@ namespace Mono.CSharp {
if (!IsExposedFromAssembly ())
return false;
if (!Parent.PartialContainer.IsClsComplianceRequired ())
if (!Parent.IsClsComplianceRequired ())
return false;
}
if (member_name.Name [0] == '_') {
Report.Warning (3008, 1, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
Warning_IdentifierNotCompliant ();
}
if (member_name.TypeParameters != null)
@ -780,12 +804,22 @@ namespace Mono.CSharp { @@ -780,12 +804,22 @@ namespace Mono.CSharp {
return true;
}
protected void Warning_IdentifierNotCompliant ()
{
Report.Warning (3008, 1, MemberName.Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError ());
}
//
// Returns a string that represents the signature for this
// member which should be used in XML documentation.
//
public abstract string GetSignatureForDocumentation ();
public virtual void GetCompletionStartingWith (string prefix, List<string> results)
{
Parent.GetCompletionStartingWith (prefix, results);
}
//
// Generates xml doc comments (if any), and if required,
// handle warning report.
@ -813,7 +847,9 @@ namespace Mono.CSharp { @@ -813,7 +847,9 @@ namespace Mono.CSharp {
#region IMemberContext Members
public virtual CompilerContext Compiler {
get { return Parent.Compiler; }
get {
return Module.Compiler;
}
}
public virtual TypeSpec CurrentType {
@ -1163,7 +1199,7 @@ namespace Mono.CSharp { @@ -1163,7 +1199,7 @@ namespace Mono.CSharp {
return (state & StateFlags.CLSCompliant) != 0;
}
public bool IsConditionallyExcluded (CompilerContext ctx, Location loc)
public bool IsConditionallyExcluded (IMemberContext ctx, Location loc)
{
if ((Kind & (MemberKind.Class | MemberKind.Method)) == 0)
return false;
@ -1172,9 +1208,18 @@ namespace Mono.CSharp { @@ -1172,9 +1208,18 @@ namespace Mono.CSharp {
if (conditions == null)
return false;
foreach (var condition in conditions) {
if (loc.CompilationUnit.IsConditionalDefined (ctx, condition))
return false;
var m = ctx.CurrentMemberDefinition;
CompilationSourceFile unit = null;
while (m != null && unit == null) {
unit = m as CompilationSourceFile;
m = m.Parent;
}
if (unit != null) {
foreach (var condition in conditions) {
if (unit.IsConditionalDefined (condition))
return false;
}
}
return true;

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

@ -28,7 +28,7 @@ namespace Mono.CSharp { @@ -28,7 +28,7 @@ namespace Mono.CSharp {
//
// Delegate container implementation
//
public class Delegate : TypeContainer, IParametersMember
public class Delegate : TypeDefinition, IParametersMember
{
public FullNamedExpression ReturnType;
readonly ParametersCompiled parameters;
@ -55,9 +55,9 @@ namespace Mono.CSharp { @@ -55,9 +55,9 @@ namespace Mono.CSharp {
Modifiers.UNSAFE |
Modifiers.PRIVATE;
public Delegate (NamespaceContainer ns, TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
public Delegate (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
Attributes attrs)
: base (ns, parent, name, attrs, MemberKind.Delegate)
: base (parent, name, attrs, MemberKind.Delegate)
{
this.ReturnType = type;
@ -292,15 +292,17 @@ namespace Mono.CSharp { @@ -292,15 +292,17 @@ namespace Mono.CSharp {
EndInvokeBuilder.Define ();
}
public override void DefineConstants ()
public override void PrepareEmit ()
{
if (!Parameters.IsEmpty) {
parameters.ResolveDefaultValues (this);
}
}
public override void EmitType ()
public override void Emit ()
{
base.Emit ();
if (ReturnType.Type != null) {
if (ReturnType.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
@ -327,12 +329,6 @@ namespace Mono.CSharp { @@ -327,12 +329,6 @@ namespace Mono.CSharp {
BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
}
if (OptAttributes != null) {
OptAttributes.Emit ();
}
base.Emit ();
}
protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
@ -344,9 +340,7 @@ namespace Mono.CSharp { @@ -344,9 +340,7 @@ namespace Mono.CSharp {
protected override TypeAttributes TypeAttr {
get {
return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) |
TypeAttributes.Class | TypeAttributes.Sealed |
base.TypeAttr;
return base.TypeAttr | TypeAttributes.Class | TypeAttributes.Sealed;
}
}
@ -531,7 +525,7 @@ namespace Mono.CSharp { @@ -531,7 +525,7 @@ namespace Mono.CSharp {
Error_ConversionFailed (ec, delegate_method, ret_expr);
}
if (delegate_method.IsConditionallyExcluded (ec.Module.Compiler, loc)) {
if (delegate_method.IsConditionallyExcluded (ec, loc)) {
ec.Report.SymbolRelatedToPreviousError (delegate_method);
MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
if (m != null && m.IsPartialDefinition) {

154
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dmcs.csproj

@ -1,154 +0,0 @@ @@ -1,154 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.20506</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>dmcs</RootNamespace>
<AssemblyName>dmcs</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>.\</OutputPath>
<DefineConstants>TRACE;DEBUG;NET_4_0;MS_COMPATIBLE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<UseVSHostingProcess>true</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<DefineConstants>TRACE;NET_2_0;MS_COMPATIBLE;GMCS_SOURCE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<OutputPath>.\</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\build\common\Consts.cs">
</Compile>
<Compile Include="..\class\corlib\Mono.Security.Cryptography\CryptoConvert.cs">
<Link>CryptoConvert.cs</Link>
</Compile>
<Compile Include="..\class\Mono.CompilerServices.SymbolWriter\MonoSymbolFile.cs">
<Link>MonoSymbolFile.cs</Link>
</Compile>
<Compile Include="..\class\Mono.CompilerServices.SymbolWriter\MonoSymbolTable.cs">
<Link>MonoSymbolTable.cs</Link>
</Compile>
<Compile Include="..\class\Mono.CompilerServices.SymbolWriter\MonoSymbolWriter.cs">
<Link>MonoSymbolWriter.cs</Link>
</Compile>
<Compile Include="argument.cs" />
<Compile Include="AssemblyInfo.cs">
</Compile>
<Compile Include="anonymous.cs">
</Compile>
<Compile Include="assign.cs">
</Compile>
<Compile Include="attribute.cs">
</Compile>
<Compile Include="cfold.cs">
</Compile>
<Compile Include="class.cs">
</Compile>
<Compile Include="codegen.cs">
</Compile>
<Compile Include="complete.cs" />
<Compile Include="const.cs">
</Compile>
<Compile Include="constant.cs">
</Compile>
<Compile Include="convert.cs">
</Compile>
<Compile Include="context.cs" />
<Compile Include="dynamic.cs" />
<Compile Include="eval.cs" />
<Compile Include="import.cs" />
<Compile Include="lambda.cs">
</Compile>
<Compile Include="cs-parser.cs" />
<Compile Include="cs-tokenizer.cs">
</Compile>
<Compile Include="decl.cs">
</Compile>
<Compile Include="delegate.cs">
</Compile>
<Compile Include="doc.cs">
</Compile>
<Compile Include="driver.cs">
</Compile>
<Compile Include="ecore.cs">
</Compile>
<Compile Include="enum.cs">
</Compile>
<Compile Include="expression.cs">
</Compile>
<Compile Include="flowanalysis.cs">
</Compile>
<Compile Include="generic.cs" />
<Compile Include="iterators.cs">
</Compile>
<Compile Include="literal.cs">
</Compile>
<Compile Include="location.cs">
</Compile>
<Compile Include="membercache.cs" />
<Compile Include="method.cs" />
<Compile Include="modifiers.cs">
</Compile>
<Compile Include="namespace.cs">
</Compile>
<Compile Include="nullable.cs">
</Compile>
<Compile Include="..\tools\monop\outline.cs">
<Link>outline.cs</Link>
</Compile>
<Compile Include="parameter.cs">
</Compile>
<Compile Include="pending.cs">
</Compile>
<Compile Include="property.cs" />
<Compile Include="report.cs">
</Compile>
<Compile Include="rootcontext.cs">
</Compile>
<Compile Include="roottypes.cs">
</Compile>
<Compile Include="statement.cs">
</Compile>
<Compile Include="support.cs">
</Compile>
<Compile Include="symbolwriter.cs">
</Compile>
<Compile Include="typemanager.cs">
</Compile>
<Compile Include="linq.cs" />
<Compile Include="field.cs" />
<Compile Include="typespec.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

6
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dmcs.exe.config

@ -1,6 +0,0 @@ @@ -1,6 +0,0 @@
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v4.0.30319"/>
</startup>
</configuration>

55
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dmcs.exe.sources

@ -1,55 +0,0 @@ @@ -1,55 +0,0 @@
AssemblyInfo.cs
anonymous.cs
argument.cs
assign.cs
attribute.cs
cs-tokenizer.cs
cfold.cs
class.cs
codegen.cs
complete.cs
const.cs
constant.cs
convert.cs
context.cs
decl.cs
delegate.cs
doc.cs
driver.cs
dynamic.cs
ecore.cs
enum.cs
eval.cs
expression.cs
field.cs
flowanalysis.cs
generic.cs
import.cs
iterators.cs
lambda.cs
linq.cs
literal.cs
location.cs
membercache.cs
method.cs
modifiers.cs
namespace.cs
nullable.cs
parameter.cs
pending.cs
property.cs
report.cs
rootcontext.cs
roottypes.cs
statement.cs
support.cs
typemanager.cs
typespec.cs
visit.cs
symbolwriter.cs
../class/Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs
../class/Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs
../class/Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs
../class/corlib/Mono.Security.Cryptography/CryptoConvert.cs
../build/common/Consts.cs
../tools/monop/outline.cs

20
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/dmcs.sln

@ -1,20 +0,0 @@ @@ -1,20 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dmcs", "dmcs.csproj", "{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

59
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/doc-bootstrap.cs

@ -1,59 +0,0 @@ @@ -1,59 +0,0 @@
//
// doc-bootstrap.cs: Stub support for XML documentation.
//
// Author:
// Raja R Harinath <rharinath@novell.com>
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2004 Novell, Inc.
//
//
#if BOOTSTRAP_WITH_OLDLIB || NET_2_1
using XmlElement = System.Object;
namespace Mono.CSharp {
public class DocUtil
{
internal static void GenerateTypeDocComment (TypeContainer t, DeclSpace ds, Report r)
{
}
internal static void GenerateDocComment (MemberCore mc, DeclSpace ds, Report r)
{
}
public static string GetMethodDocCommentName (MemberCore mc, ParametersCompiled p, DeclSpace ds)
{
return "";
}
internal static void OnMethodGenerateDocComment (MethodCore mc, XmlElement el, Report r)
{
}
public static void GenerateEnumDocComment (Enum e, DeclSpace ds)
{
}
}
public class Documentation
{
public Documentation (string xml_output_filename)
{
}
public bool OutputDocComment (string asmfilename, Report r)
{
return true;
}
public void GenerateDocComment ()
{
}
}
}
#endif

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

@ -32,6 +32,7 @@ namespace Mono.CSharp @@ -32,6 +32,7 @@ namespace Mono.CSharp
readonly XmlDocument XmlDocumentation;
readonly ModuleContainer module;
readonly ModuleContainer doc_module;
//
// The output for XML documentation.
@ -48,6 +49,9 @@ namespace Mono.CSharp @@ -48,6 +49,9 @@ namespace Mono.CSharp
public DocumentationBuilder (ModuleContainer module)
{
doc_module = new ModuleContainer (module.Compiler);
doc_module.DocumentationBuilder = this;
this.module = module;
XmlDocumentation = new XmlDocument ();
XmlDocumentation.PreserveWhitespace = false;
@ -322,13 +326,10 @@ namespace Mono.CSharp @@ -322,13 +326,10 @@ namespace Mono.CSharp
var s = new MemoryStream (encoding.GetBytes (cref));
SeekableStreamReader seekable = new SeekableStreamReader (s, encoding);
var source_file = new CompilationSourceFile ("{documentation}", "", 1);
var doc_module = new ModuleContainer (module.Compiler);
doc_module.DocumentationBuilder = this;
source_file.NamespaceContainer = new NamespaceContainer (null, doc_module, null, source_file);
var source_file = new CompilationSourceFile (doc_module);
var report = new Report (doc_module.Compiler, new NullReportPrinter ());
Report parse_report = new Report (new NullReportPrinter ());
var parser = new CSharpParser (seekable, source_file, parse_report);
var parser = new CSharpParser (seekable, source_file, report);
ParsedParameters = null;
ParsedName = null;
ParsedBuiltinType = null;
@ -336,7 +337,7 @@ namespace Mono.CSharp @@ -336,7 +337,7 @@ namespace Mono.CSharp
parser.Lexer.putback_char = Tokenizer.DocumentationXref;
parser.Lexer.parsing_generic_declaration_doc = true;
parser.parse ();
if (parse_report.Errors > 0) {
if (report.Errors > 0) {
Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
mc.GetSignatureForError (), cref);

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

@ -41,20 +41,22 @@ namespace Mono.CSharp @@ -41,20 +41,22 @@ namespace Mono.CSharp
}
}
void tokenize_file (CompilationSourceFile file)
void tokenize_file (SourceFile sourceFile, ModuleContainer module)
{
Stream input;
try {
input = File.OpenRead (file.Name);
input = File.OpenRead (sourceFile.Name);
} catch {
Report.Error (2001, "Source file `" + file.Name + "' could not be found");
Report.Error (2001, "Source file `" + sourceFile.Name + "' could not be found");
return;
}
using (input){
SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding);
Tokenizer lexer = new Tokenizer (reader, file, ctx);
var file = new CompilationSourceFile (module, sourceFile);
Tokenizer lexer = new Tokenizer (reader, file);
int token, tokens = 0, errors = 0;
while ((token = lexer.token ()) != Token.EOF){
@ -70,20 +72,21 @@ namespace Mono.CSharp @@ -70,20 +72,21 @@ namespace Mono.CSharp
void Parse (ModuleContainer module)
{
Location.Initialize (module.Compiler.SourceFiles);
bool tokenize_only = module.Compiler.Settings.TokenizeOnly;
var sources = module.Compiler.SourceFiles;
Location.Initialize (sources);
for (int i = 0; i < sources.Count; ++i) {
if (tokenize_only) {
tokenize_file (sources[i]);
tokenize_file (sources[i], module);
} else {
Parse (sources[i], module);
}
}
}
public void Parse (CompilationSourceFile file, ModuleContainer module)
public void Parse (SourceFile file, ModuleContainer module)
{
Stream input;
@ -96,6 +99,7 @@ namespace Mono.CSharp @@ -96,6 +99,7 @@ namespace Mono.CSharp
// Check 'MZ' header
if (input.ReadByte () == 77 && input.ReadByte () == 90) {
Report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
input.Close ();
return;
@ -107,30 +111,32 @@ namespace Mono.CSharp @@ -107,30 +111,32 @@ namespace Mono.CSharp
Parse (reader, file, module);
reader.Dispose ();
input.Close ();
}
public void Parse (SeekableStreamReader reader, CompilationSourceFile file, ModuleContainer module)
}
public CSharpParser Parse (SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module)
{
file.NamespaceContainer = new NamespaceContainer (null, module, null, file);
var file = new CompilationSourceFile (module, sourceFile);
module.AddTypeContainer (file);
CSharpParser parser = new CSharpParser (reader, file);
parser.Lexer.sbag = new SpecialsBag ();
parser.parse ();
return parser;
}
public static int Main (string[] args)
{
Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
var r = new Report (new ConsoleReportPrinter ());
CommandLineParser cmd = new CommandLineParser (r);
CommandLineParser cmd = new CommandLineParser (Console.Out);
var settings = cmd.ParseArguments (args);
if (settings == null || r.Errors > 0)
if (settings == null)
return 1;
if (cmd.HasBeenStopped)
return 0;
Driver d = new Driver (new CompilerContext (settings, r));
Driver d = new Driver (new CompilerContext (settings, new ConsoleReportPrinter ()));
if (d.Compile () && d.Report.Errors == 0) {
if (d.Report.Warnings > 0) {
@ -263,7 +269,7 @@ namespace Mono.CSharp @@ -263,7 +269,7 @@ namespace Mono.CSharp
// loaded assembly into compiled builder to be resolved
// correctly
tr.Start (TimeReporter.TimerType.CreateTypeTotal);
module.CreateType ();
module.CreateContainer ();
importer.AddCompiledAssembly (assembly);
tr.Stop (TimeReporter.TimerType.CreateTypeTotal);
@ -292,18 +298,12 @@ namespace Mono.CSharp @@ -292,18 +298,12 @@ namespace Mono.CSharp
if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Save))
return false;
module.CreateType ();
module.CreateContainer ();
loader.LoadModules (assembly, module.GlobalRootNamespace);
#endif
module.InitializePredefinedTypes ();
tr.Start (TimeReporter.TimerType.UsingResolve);
foreach (var source_file in ctx.SourceFiles) {
source_file.NamespaceContainer.Define ();
}
tr.Stop (TimeReporter.TimerType.UsingResolve);
tr.Start (TimeReporter.TimerType.ModuleDefinitionTotal);
module.Define ();
tr.Stop (TimeReporter.TimerType.ModuleDefinitionTotal);
@ -331,7 +331,7 @@ namespace Mono.CSharp @@ -331,7 +331,7 @@ namespace Mono.CSharp
}
tr.Start (TimeReporter.TimerType.CloseTypes);
module.CloseType ();
module.CloseContainer ();
tr.Stop (TimeReporter.TimerType.CloseTypes);
tr.Start (TimeReporter.TimerType.Resouces);
@ -356,26 +356,24 @@ namespace Mono.CSharp @@ -356,26 +356,24 @@ namespace Mono.CSharp
public class CompilerCompilationUnit {
public ModuleContainer ModuleCompiled { get; set; }
public LocationsBag LocationsBag { get; set; }
public UsingsBag UsingsBag { get; set; }
public SpecialsBag SpecialsBag { get; set; }
public object LastYYValue { get; set; }
}
//
// This is the only public entry point
//
public class CompilerCallableEntryPoint : MarshalByRefObject {
public class CompilerCallableEntryPoint : MarshalByRefObject
{
public static bool InvokeCompiler (string [] args, TextWriter error)
{
try {
var r = new Report (new StreamReportPrinter (error));
CommandLineParser cmd = new CommandLineParser (r, error);
CommandLineParser cmd = new CommandLineParser (error);
var setting = cmd.ParseArguments (args);
if (setting == null || r.Errors > 0)
if (setting == null)
return false;
var d = new Driver (new CompilerContext (setting, r));
var d = new Driver (new CompilerContext (setting, new StreamReportPrinter (error)));
return d.Compile ();
} finally {
Reset ();
@ -400,74 +398,15 @@ namespace Mono.CSharp @@ -400,74 +398,15 @@ namespace Mono.CSharp
public static void Reset (bool full_flag)
{
CSharpParser.yacc_verbose_flag = 0;
Location.Reset ();
if (!full_flag)
return;
AnonymousTypeClass.Reset ();
AnonymousMethodBody.Reset ();
AnonymousMethodStorey.Reset ();
SymbolWriter.Reset ();
Switch.Reset ();
Linq.QueryBlock.TransparentParameter.Reset ();
TypeInfo.Reset ();
}
public static CompilerCompilationUnit ParseFile (string[] args, Stream input, string inputFile, TextWriter reportStream)
{
return ParseFile (args, input, inputFile, new StreamReportPrinter (reportStream));
}
internal static object parseLock = new object ();
public static CompilerCompilationUnit ParseFile (string[] args, Stream input, string inputFile, ReportPrinter reportPrinter)
{
lock (parseLock) {
try {
// Driver d = Driver.Create (args, false, null, reportPrinter);
// if (d == null)
// return null;
var r = new Report (reportPrinter);
CommandLineParser cmd = new CommandLineParser (r, Console.Out);
var setting = cmd.ParseArguments (args);
if (setting == null || r.Errors > 0)
return null;
setting.Version = LanguageVersion.V_5;
CompilerContext ctx = new CompilerContext (setting, r);
var files = new List<CompilationSourceFile> ();
var unit = new CompilationSourceFile (inputFile, inputFile, 0);
var module = new ModuleContainer (ctx);
unit.NamespaceContainer = new NamespaceContainer (null, module, null, unit);
files.Add (unit);
Location.Initialize (files);
// TODO: encoding from driver
SeekableStreamReader reader = new SeekableStreamReader (input, Encoding.UTF8);
RootContext.ToplevelTypes = module;
CSharpParser parser = new CSharpParser (reader, unit);
parser.Lexer.TabSize = 1;
parser.Lexer.sbag = new SpecialsBag ();
parser.LocationsBag = new LocationsBag ();
parser.UsingsBag = new UsingsBag ();
parser.parse ();
return new CompilerCompilationUnit () {
ModuleCompiled = RootContext.ToplevelTypes,
LocationsBag = parser.LocationsBag,
UsingsBag = parser.UsingsBag,
SpecialsBag = parser.Lexer.sbag
};
} finally {
Reset ();
}
}
}
}
}

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

@ -13,7 +13,7 @@ using System; @@ -13,7 +13,7 @@ using System;
using System.Linq;
using SLE = System.Linq.Expressions;
#if NET_4_0
#if NET_4_0 || MONODROID
using System.Dynamic;
#endif
@ -63,7 +63,7 @@ namespace Mono.CSharp @@ -63,7 +63,7 @@ namespace Mono.CSharp
//
public class RuntimeValueExpression : Expression, IDynamicAssign, IMemoryLocation
{
#if !NET_4_0
#if !NET_4_0 && !MONODROID
public class DynamicMetaObject
{
public TypeSpec RuntimeType;
@ -146,7 +146,7 @@ namespace Mono.CSharp @@ -146,7 +146,7 @@ namespace Mono.CSharp
return base.MakeExpression (ctx);
#else
#if NET_4_0
#if NET_4_0 || MONODROID
if (type.IsStruct && !obj.Expression.Type.IsValueType)
return SLE.Expression.Unbox (obj.Expression, type.GetMetaInfo ());
@ -181,7 +181,7 @@ namespace Mono.CSharp @@ -181,7 +181,7 @@ namespace Mono.CSharp
return this;
}
#if NET_4_0
#if NET_4_0 || MONODROID
public override SLE.Expression MakeExpression (BuilderContext ctx)
{
#if STATIC
@ -430,7 +430,7 @@ namespace Mono.CSharp @@ -430,7 +430,7 @@ namespace Mono.CSharp
p[0] = new Parameter (targs[0], "p0", Parameter.Modifier.NONE, null, loc);
var site = ec.CreateDynamicSite ();
int index = site.Types == null ? 0 : site.Types.Count;
int index = site.Containers == null ? 0 : site.Containers.Count;
if (mutator != null)
rt = mutator.Mutate (rt);
@ -439,17 +439,16 @@ namespace Mono.CSharp @@ -439,17 +439,16 @@ namespace Mono.CSharp
p[i] = new Parameter (targs[i], "p" + i.ToString ("X"), arguments[i - 1].Modifier, null, loc);
}
d = new Delegate (site.NamespaceEntry, site, new TypeExpression (rt, loc),
d = new Delegate (site, new TypeExpression (rt, loc),
Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED,
new MemberName ("Container" + index.ToString ("X")),
new ParametersCompiled (p), null);
d.CreateType ();
d.DefineType ();
d.CreateContainer ();
d.DefineContainer ();
d.Define ();
d.Emit ();
site.AddDelegate (d);
site.AddTypeContainer (d);
del_type = new TypeExpression (d.CurrentType, loc);
if (targs_for_instance != null) {
del_type_instance_access = null;
@ -487,7 +486,7 @@ namespace Mono.CSharp @@ -487,7 +486,7 @@ namespace Mono.CSharp
// When site container already exists the inflated version has to be
// updated manually to contain newly created field
if (gt is InflatedTypeSpec && site_container.Fields.Count > 1) {
if (gt is InflatedTypeSpec && site_container.AnonymousMethodsCounter > 1) {
var tparams = gt.MemberDefinition.TypeParametersCount > 0 ? gt.MemberDefinition.TypeParameters : TypeParameterSpec.EmptyTypes;
var inflator = new TypeParameterInflator (module, gt, tparams, gt.TypeArguments);
gt.MemberCache.AddMember (field.InflateMember (inflator));
@ -957,7 +956,7 @@ namespace Mono.CSharp @@ -957,7 +956,7 @@ namespace Mono.CSharp
sealed class DynamicSiteClass : HoistedStoreyClass
{
public DynamicSiteClass (TypeContainer parent, MemberBase host, TypeParameters tparams)
public DynamicSiteClass (TypeDefinition parent, MemberBase host, TypeParameters tparams)
: base (parent, MakeMemberName (host, "DynamicSite", parent.DynamicSitesCounter, tparams, Location.Null), tparams, Modifiers.STATIC)
{
parent.DynamicSitesCounter++;
@ -965,7 +964,7 @@ namespace Mono.CSharp @@ -965,7 +964,7 @@ namespace Mono.CSharp
public FieldSpec CreateCallSiteField (FullNamedExpression type, Location loc)
{
int index = fields == null ? 0 : fields.Count;
int index = AnonymousMethodsCounter++;
Field f = new HoistedField (this, type, Modifiers.PUBLIC | Modifiers.STATIC, "Site" + index.ToString ("X"), null, loc);
f.Define ();

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

@ -831,21 +831,11 @@ namespace Mono.CSharp { @@ -831,21 +831,11 @@ namespace Mono.CSharp {
/// <summary>
/// Reports that we were expecting `expr' to be of class `expected'
/// </summary>
public void Error_UnexpectedKind (Report r, MemberCore mc, string expected, Location loc)
public void Error_UnexpectedKind (IMemberContext ctx, Expression memberExpr, string expected, string was, Location loc)
{
Error_UnexpectedKind (r, mc, expected, ExprClassName, loc);
}
var name = memberExpr.GetSignatureForError ();
public void Error_UnexpectedKind (Report r, MemberCore mc, string expected, string was, Location loc)
{
string name;
if (mc != null)
name = mc.GetSignatureForError ();
else
name = GetSignatureForError ();
r.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected",
name, was, expected);
ctx.Module.Compiler.Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected", name, was, expected);
}
public virtual void Error_UnexpectedKind (ResolveContext ec, ResolveFlags flags, Location loc)
@ -2254,12 +2244,10 @@ namespace Mono.CSharp { @@ -2254,12 +2244,10 @@ namespace Mono.CSharp {
protected virtual void Error_TypeOrNamespaceNotFound (IMemberContext ctx)
{
if (ctx.CurrentType != null) {
if (ctx.CurrentMemberDefinition != null) {
MemberCore mc = ctx.CurrentMemberDefinition.Parent.GetDefinition (Name);
if (mc != null) {
Error_UnexpectedKind (ctx.Module.Compiler.Report, mc, "type", GetMemberType (mc), loc);
return;
}
var member = MemberLookup (ctx, false, ctx.CurrentType, Name, 0, MemberLookupRestrictions.ExactArity, loc) as MemberExpr;
if (member != null) {
member.Error_UnexpectedKind (ctx, member, "type", member.KindName, loc);
return;
}
}
@ -2575,7 +2563,7 @@ namespace Mono.CSharp { @@ -2575,7 +2563,7 @@ namespace Mono.CSharp {
TypeExpr te = fne as TypeExpr;
if (te == null) {
fne.Error_UnexpectedKind (mc.Module.Compiler.Report, null, "type", loc);
fne.Error_UnexpectedKind (mc, fne, "type", fne.ExprClassName, loc);
return null;
}
@ -2592,7 +2580,7 @@ namespace Mono.CSharp { @@ -2592,7 +2580,7 @@ namespace Mono.CSharp {
// Obsolete checks cannot be done when resolving base context as they
// require type dependencies to be set but we are in process of resolving them
//
if (!(mc is TypeContainer.BaseContext)) {
if (!(mc is TypeDefinition.BaseContext) && !(mc is UsingAliasNamespace.AliasContext)) {
ObsoleteAttribute obsolete_attr = type.GetAttributeObsolete ();
if (obsolete_attr != null && !mc.IsObsolete) {
AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location, mc.Module.Compiler.Report);
@ -2705,6 +2693,10 @@ namespace Mono.CSharp { @@ -2705,6 +2693,10 @@ namespace Mono.CSharp {
get;
}
public abstract string KindName {
get;
}
protected abstract TypeSpec DeclaringType {
get;
}
@ -3035,20 +3027,17 @@ namespace Mono.CSharp { @@ -3035,20 +3027,17 @@ namespace Mono.CSharp {
public class ExtensionMethodCandidates
{
NamespaceContainer container;
Namespace ns;
IList<MethodSpec> methods;
readonly NamespaceContainer container;
readonly IList<MethodSpec> methods;
readonly int index;
readonly IMemberContext context;
public ExtensionMethodCandidates (IList<MethodSpec> methods, NamespaceContainer nsContainer)
: this (methods, nsContainer, null)
{
}
public ExtensionMethodCandidates (IList<MethodSpec> methods, NamespaceContainer nsContainer, Namespace ns)
public ExtensionMethodCandidates (IMemberContext context, IList<MethodSpec> methods, NamespaceContainer nsContainer, int lookupIndex)
{
this.context = context;
this.methods = methods;
this.container = nsContainer;
this.ns = ns;
this.index = lookupIndex;
}
public NamespaceContainer Container {
@ -3057,11 +3046,15 @@ namespace Mono.CSharp { @@ -3057,11 +3046,15 @@ namespace Mono.CSharp {
}
}
public bool HasUninspectedMembers { get; set; }
public IMemberContext Context {
get {
return context;
}
}
public Namespace Namespace {
public int LookupIndex {
get {
return ns;
return index;
}
}
@ -3104,38 +3097,7 @@ namespace Mono.CSharp { @@ -3104,38 +3097,7 @@ namespace Mono.CSharp {
int arity = type_arguments == null ? 0 : type_arguments.Count;
//
// Here we try to resume the search for extension method at the point
// where the last bunch of candidates was found. It's more tricky than
// it seems as we have to check both namespace containers and namespace
// in correct order.
//
// Consider:
//
// namespace A {
// using N1;
// namespace B.C.D {
// <our first search found candidates in A.B.C.D
// }
// }
//
// In the example above namespace A.B.C.D, A.B.C and A.B have to be
// checked before we hit A.N1 using
//
if (candidates.Namespace == null) {
Namespace scope;
var methods = candidates.Container.NS.LookupExtensionMethod (candidates.Container, ExtensionExpression.Type, Name, arity, out scope);
if (methods != null) {
candidates = new ExtensionMethodCandidates (null, candidates.Container, scope);
return methods.Cast<MemberSpec> ().ToList ();
}
}
var ns_container = candidates.HasUninspectedMembers ? candidates.Container : candidates.Container.Parent;
if (ns_container == null)
return null;
candidates = ns_container.LookupExtensionMethod (ExtensionExpression.Type, Name, arity);
candidates = candidates.Container.LookupExtensionMethod (candidates.Context, ExtensionExpression.Type, Name, arity, candidates.Container, candidates.LookupIndex);
if (candidates == null)
return null;
@ -3280,6 +3242,10 @@ namespace Mono.CSharp { @@ -3280,6 +3242,10 @@ namespace Mono.CSharp {
}
}
public override string KindName {
get { return "method"; }
}
public override string Name {
get {
if (best_candidate != null)
@ -3321,7 +3287,7 @@ namespace Mono.CSharp { @@ -3321,7 +3287,7 @@ namespace Mono.CSharp {
return null;
}
if (best_candidate.IsConditionallyExcluded (ec.Module.Compiler, loc))
if (best_candidate.IsConditionallyExcluded (ec, loc))
ec.Report.Error (765, loc,
"Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree");
@ -5039,6 +5005,10 @@ namespace Mono.CSharp { @@ -5039,6 +5005,10 @@ namespace Mono.CSharp {
get { throw new NotImplementedException (); }
}
public override string KindName {
get { return "constant"; }
}
public override bool IsInstance {
get { return !IsStatic; }
}
@ -5139,6 +5109,10 @@ namespace Mono.CSharp { @@ -5139,6 +5109,10 @@ namespace Mono.CSharp {
}
}
public override string KindName {
get { return "field"; }
}
public FieldSpec Spec {
get {
return spec;
@ -5362,7 +5336,7 @@ namespace Mono.CSharp { @@ -5362,7 +5336,7 @@ namespace Mono.CSharp {
if (ec.HasSet (ResolveContext.Options.ConstructorScope)) {
// InitOnly fields cannot be assigned-to in a different constructor from their declaring type
if (ec.CurrentMemberDefinition.Parent.Definition != spec.DeclaringType.GetDefinition ())
if (ec.CurrentMemberDefinition.Parent.PartialContainer.Definition != spec.DeclaringType.GetDefinition ())
return Report_AssignToReadonly (ec, right_side);
// static InitOnly fields cannot be assigned-to in an instance constructor
if (IsStatic && !ec.IsStatic)
@ -5645,6 +5619,10 @@ namespace Mono.CSharp { @@ -5645,6 +5619,10 @@ namespace Mono.CSharp {
}
}
public override string KindName {
get { return "property"; }
}
public PropertySpec PropertyInfo {
get {
return best_candidate;
@ -6058,6 +6036,10 @@ namespace Mono.CSharp { @@ -6058,6 +6036,10 @@ namespace Mono.CSharp {
}
}
public override string KindName {
get { return "event"; }
}
public MethodSpec Operator {
get {
return op;

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

@ -102,7 +102,7 @@ namespace Mono.CSharp { @@ -102,7 +102,7 @@ namespace Mono.CSharp {
/// <summary>
/// Enumeration container
/// </summary>
public class Enum : TypeContainer
public class Enum : TypeDefinition
{
//
// Implicit enum member initializer, used when no constant value is provided
@ -164,8 +164,8 @@ namespace Mono.CSharp { @@ -164,8 +164,8 @@ namespace Mono.CSharp {
readonly TypeExpr underlying_type_expr;
public Enum (NamespaceContainer ns, TypeContainer parent, TypeExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
: base (ns, parent, name, attrs, MemberKind.Enum)
public Enum (TypeContainer parent, TypeExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
: base (parent, name, attrs, MemberKind.Enum)
{
underlying_type_expr = type;
var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
@ -189,8 +189,7 @@ namespace Mono.CSharp { @@ -189,8 +189,7 @@ namespace Mono.CSharp {
protected override TypeAttributes TypeAttr {
get {
return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) |
TypeAttributes.Class | TypeAttributes.Sealed | base.TypeAttr;
return base.TypeAttr | TypeAttributes.Class | TypeAttributes.Sealed;
}
}
@ -215,7 +214,7 @@ namespace Mono.CSharp { @@ -215,7 +214,7 @@ namespace Mono.CSharp {
return;
}
AddConstant (em);
AddMember (em);
}
public static void Error_1008 (Location loc, Report Report)
@ -224,27 +223,25 @@ namespace Mono.CSharp { @@ -224,27 +223,25 @@ namespace Mono.CSharp {
"Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
}
protected override bool DefineNestedTypes ()
protected override void DoDefineContainer ()
{
((EnumSpec) spec).UnderlyingType = underlying_type_expr == null ? Compiler.BuiltinTypes.Int : underlying_type_expr.Type;
TypeBuilder.DefineField (UnderlyingValueField, UnderlyingType.GetMetaInfo (),
FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);
return true;
DefineBaseTypes ();
}
protected override bool DoDefineMembers ()
{
if (constants != null) {
for (int i = 0; i < constants.Count; ++i) {
EnumMember em = (EnumMember) constants [i];
if (em.Initializer == null) {
em.Initializer = new ImplicitInitializer (em, i == 0 ? null : (EnumMember) constants[i - 1]);
}
em.Define ();
for (int i = 0; i < Members.Count; ++i) {
EnumMember em = (EnumMember) Members[i];
if (em.Initializer == null) {
em.Initializer = new ImplicitInitializer (em, i == 0 ? null : (EnumMember) Members[i - 1]);
}
em.Define ();
}
return true;

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

@ -72,18 +72,17 @@ namespace Mono.CSharp @@ -72,18 +72,17 @@ namespace Mono.CSharp
readonly ReflectionImporter importer;
readonly CompilationSourceFile source_file;
public Evaluator (CompilerSettings settings, Report report)
public Evaluator (CompilerContext ctx)
{
ctx = new CompilerContext (settings, report);
this.ctx = ctx;
module = new ModuleContainer (ctx);
module.Evaluator = this;
source_file = new CompilationSourceFile ("{interactive}", "", 1);
source_file.NamespaceContainer = new NamespaceContainer (null, module, null, source_file);
source_file = new CompilationSourceFile (module);
module.AddTypeContainer (source_file);
startup_files = ctx.SourceFiles.Count;
ctx.SourceFiles.Add (source_file);
// FIXME: Importer needs this assembly for internalsvisibleto
module.SetDeclaringAssembly (new AssemblyDefinitionDynamic (module, "evaluator"));
@ -97,7 +96,6 @@ namespace Mono.CSharp @@ -97,7 +96,6 @@ namespace Mono.CSharp
{
var loader = new DynamicLoader (importer, ctx);
CompilerCallableEntryPoint.Reset ();
RootContext.ToplevelTypes = module;
//var startup_files = new List<string> ();
@ -118,15 +116,13 @@ namespace Mono.CSharp @@ -118,15 +116,13 @@ namespace Mono.CSharp
Location.Initialize (ctx.SourceFiles);
for (int i = 0; i < startup_files; ++i) {
var sf = ctx.Settings.SourceFiles [i];
var sf = ctx.SourceFiles [i];
d.Parse (sf, module);
}
}
void Reset ()
{
CompilerCallableEntryPoint.PartialReset ();
Location.Reset ();
Location.Initialize (ctx.SourceFiles);
}
@ -355,8 +351,6 @@ namespace Mono.CSharp @@ -355,8 +351,6 @@ namespace Mono.CSharp
bool partial_input;
CSharpParser parser = ParseString (ParseMode.GetCompletions, input, out partial_input);
if (parser == null){
if (CSharpParser.yacc_verbose_flag != 0)
Console.WriteLine ("DEBUG: No completions available");
return null;
}
@ -372,10 +366,9 @@ namespace Mono.CSharp @@ -372,10 +366,9 @@ namespace Mono.CSharp
module.SetDeclaringAssembly (a);
// Need to setup MemberCache
parser_result.CreateType ();
parser_result.NamespaceEntry.Define ();
parser_result.CreateContainer ();
var method = parser_result.Methods[0] as Method;
var method = parser_result.Members[0] as Method;
BlockContext bc = new BlockContext (method, method.Block, ctx.BuiltinTypes.Void);
try {
@ -449,7 +442,7 @@ namespace Mono.CSharp @@ -449,7 +442,7 @@ namespace Mono.CSharp
//
InputKind ToplevelOrStatement (SeekableStreamReader seekable)
{
Tokenizer tokenizer = new Tokenizer (seekable, source_file, ctx);
Tokenizer tokenizer = new Tokenizer (seekable, source_file);
int t = tokenizer.token ();
switch (t){
@ -555,7 +548,6 @@ namespace Mono.CSharp @@ -555,7 +548,6 @@ namespace Mono.CSharp
{
partial_input = false;
Reset ();
Tokenizer.LocatedToken.Initialize ();
var enc = ctx.Settings.Encoding;
var s = new MemoryStream (enc.GetBytes (input));
@ -578,7 +570,7 @@ namespace Mono.CSharp @@ -578,7 +570,7 @@ namespace Mono.CSharp
}
seekable.Position = 0;
source_file.NamespaceContainer.DeclarationFound = false;
source_file.DeclarationFound = false;
CSharpParser parser = new CSharpParser (seekable, source_file);
if (kind == InputKind.StatementOrExpression){
@ -593,7 +585,7 @@ namespace Mono.CSharp @@ -593,7 +585,7 @@ namespace Mono.CSharp
parser.Lexer.CompleteOnEOF = true;
ReportPrinter old_printer = null;
if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions) && CSharpParser.yacc_verbose_flag == 0)
if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions))
old_printer = ctx.Report.SetPrinter (new StreamReportPrinter (TextWriter.Null));
try {
@ -648,18 +640,19 @@ namespace Mono.CSharp @@ -648,18 +640,19 @@ namespace Mono.CSharp
new TypeExpression (base_class_imported, host.Location)
};
host.AddBasesForPart (host, baseclass_list);
host.AddBasesForPart (baseclass_list);
host.CreateType ();
host.DefineType ();
host.CreateContainer ();
host.DefineContainer ();
host.Define ();
expression_method = (Method) host.Methods[0];
expression_method = (Method) host.Members[0];
} else {
expression_method = null;
}
module.CreateType ();
module.CreateContainer ();
source_file.EnableUsingClausesRedefinition ();
module.Define ();
if (Report.Errors != 0){
@ -670,19 +663,19 @@ namespace Mono.CSharp @@ -670,19 +663,19 @@ namespace Mono.CSharp
}
if (host != null){
host.EmitType ();
host.EmitContainer ();
}
module.Emit ();
module.EmitContainer ();
if (Report.Errors != 0){
if (undo != null)
undo.ExecuteUndo ();
return null;
}
module.CloseType ();
module.CloseContainer ();
if (host != null)
host.CloseType ();
host.CloseContainer ();
if (access == AssemblyBuilderAccess.RunAndSave)
assembly.Save ();
@ -697,34 +690,36 @@ namespace Mono.CSharp @@ -697,34 +690,36 @@ namespace Mono.CSharp
var tt = assembly.Builder.GetType (host.TypeBuilder.Name);
var mi = tt.GetMethod (expression_method.MemberName.Name);
if (host.Fields != null) {
//
// We need to then go from FieldBuilder to FieldInfo
// or reflection gets confused (it basically gets confused, and variables override each
// other).
//
foreach (Field field in host.Fields) {
var fi = tt.GetField (field.Name);
Tuple<FieldSpec, FieldInfo> old;
// If a previous value was set, nullify it, so that we do
// not leak memory
if (fields.TryGetValue (field.Name, out old)) {
if (old.Item1.MemberType.IsStruct) {
//
// TODO: Clear fields for structs
//
} else {
try {
old.Item2.SetValue (null, null);
} catch {
}
//
// We need to then go from FieldBuilder to FieldInfo
// or reflection gets confused (it basically gets confused, and variables override each
// other).
//
foreach (var member in host.Members) {
var field = member as Field;
if (field == null)
continue;
var fi = tt.GetField (field.Name);
Tuple<FieldSpec, FieldInfo> old;
// If a previous value was set, nullify it, so that we do
// not leak memory
if (fields.TryGetValue (field.Name, out old)) {
if (old.Item1.MemberType.IsStruct) {
//
// TODO: Clear fields for structs
//
} else {
try {
old.Item2.SetValue (null, null);
} catch {
}
}
fields[field.Name] = Tuple.Create (field.Spec, fi);
}
fields[field.Name] = Tuple.Create (field.Spec, fi);
}
return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi);
@ -761,7 +756,7 @@ namespace Mono.CSharp @@ -761,7 +756,7 @@ namespace Mono.CSharp
//foreach (object x in ns.using_alias_list)
// sb.AppendFormat ("using {0};\n", x);
foreach (var ue in source_file.NamespaceContainer.Usings) {
foreach (var ue in source_file.Usings) {
sb.AppendFormat ("using {0};", ue.ToString ());
sb.Append (Environment.NewLine);
}
@ -773,7 +768,7 @@ namespace Mono.CSharp @@ -773,7 +768,7 @@ namespace Mono.CSharp
{
var res = new List<string> ();
foreach (var ue in source_file.NamespaceContainer.Usings) {
foreach (var ue in source_file.Usings) {
if (ue.Alias != null || ue.ResolvedExpression == null)
continue;
@ -1118,7 +1113,7 @@ namespace Mono.CSharp @@ -1118,7 +1113,7 @@ namespace Mono.CSharp
{
}
public void AddTypeContainer (TypeContainer current_container, TypeContainer tc)
public void AddTypeContainer (TypeContainer current_container, TypeDefinition tc)
{
if (current_container == tc){
Console.Error.WriteLine ("Internal error: inserting container into itself");
@ -1128,14 +1123,13 @@ namespace Mono.CSharp @@ -1128,14 +1123,13 @@ namespace Mono.CSharp
if (undo_actions == null)
undo_actions = new List<Action> ();
var existing = current_container.Types.FirstOrDefault (l => l.MemberName.Basename == tc.MemberName.Basename);
var existing = current_container.Containers.FirstOrDefault (l => l.Basename == tc.Basename);
if (existing != null) {
current_container.RemoveTypeContainer (existing);
existing.NamespaceEntry.SlaveDeclSpace.RemoveTypeContainer (existing);
current_container.RemoveContainer (existing);
undo_actions.Add (() => current_container.AddTypeContainer (existing));
}
undo_actions.Add (() => current_container.RemoveTypeContainer (tc));
undo_actions.Add (() => current_container.RemoveContainer (tc));
}
public void ExecuteUndo ()

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

@ -620,7 +620,7 @@ namespace Mono.CSharp @@ -620,7 +620,7 @@ namespace Mono.CSharp
return is_checked ? SLE.Expression.NegateChecked (expr) : SLE.Expression.Negate (expr);
case Operator.LogicalNot:
return SLE.Expression.Not (expr);
#if NET_4_0
#if NET_4_0 || MONODROID
case Operator.OnesComplement:
return SLE.Expression.OnesComplement (expr);
#endif
@ -1268,7 +1268,7 @@ namespace Mono.CSharp @@ -1268,7 +1268,7 @@ namespace Mono.CSharp
}
#if NET_4_0
#if NET_4_0 || MONODROID
public override SLE.Expression MakeExpression (BuilderContext ctx)
{
var target = ((RuntimeValueExpression) expr).MetaObject.Expression;
@ -1820,7 +1820,7 @@ namespace Mono.CSharp @@ -1820,7 +1820,7 @@ namespace Mono.CSharp
temp_storage.Release (ec);
}
#if NET_4_0 && !STATIC
#if (NET_4_0 || MONODROID) && !STATIC
public override SLE.Expression MakeExpression (BuilderContext ctx)
{
return SLE.Expression.Default (type.GetMetaInfo ());
@ -3664,7 +3664,7 @@ namespace Mono.CSharp @@ -3664,7 +3664,7 @@ namespace Mono.CSharp
//
// Merge two sets of user operators into one, they are mostly distinguish
// expect when they share base type and it contains an operator
// except when they share base type and it contains an operator
//
static IList<MemberSpec> CombineUserOperators (IList<MemberSpec> left, IList<MemberSpec> right)
{
@ -5401,7 +5401,8 @@ namespace Mono.CSharp @@ -5401,7 +5401,8 @@ namespace Mono.CSharp
// Any value type has to be pass as by-ref to get back the same
// instance on which the member was called
//
var mod = TypeSpec.IsValueType (ma.LeftExpression.Type) ? Argument.AType.Ref : Argument.AType.None;
var mod = ma.LeftExpression is IMemoryLocation && TypeSpec.IsValueType (ma.LeftExpression.Type) ?
Argument.AType.Ref : Argument.AType.None;
args.Insert (0, new Argument (ma.LeftExpression.Resolve (ec), mod));
}
} else { // is SimpleName
@ -6515,7 +6516,7 @@ namespace Mono.CSharp @@ -6515,7 +6516,7 @@ namespace Mono.CSharp
return data;
}
#if NET_4_0
#if NET_4_0 || MONODROID
public override SLE.Expression MakeExpression (BuilderContext ctx)
{
#if STATIC
@ -8208,9 +8209,9 @@ namespace Mono.CSharp @@ -8208,9 +8209,9 @@ namespace Mono.CSharp
return;
}
var any_other_member = MemberLookup (rc, true, expr_type, Name, 0, MemberLookupRestrictions.None, loc);
var any_other_member = MemberLookup (rc, false, expr_type, Name, 0, MemberLookupRestrictions.None, loc);
if (any_other_member != null) {
any_other_member.Error_UnexpectedKind (rc.Module.Compiler.Report, null, "type", loc);
any_other_member.Error_UnexpectedKind (rc, any_other_member, "type", any_other_member.ExprClassName, loc);
return;
}
@ -8746,7 +8747,7 @@ namespace Mono.CSharp @@ -8746,7 +8747,7 @@ namespace Mono.CSharp
public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
{
#if NET_4_0
#if NET_4_0 || MONODROID
return SLE.Expression.ArrayAccess (ea.Expr.MakeExpression (ctx), MakeExpressionArguments (ctx));
#else
throw new NotImplementedException ();
@ -8813,6 +8814,10 @@ namespace Mono.CSharp @@ -8813,6 +8814,10 @@ namespace Mono.CSharp
}
}
public override string KindName {
get { return "indexer"; }
}
public override string Name {
get {
return "this";
@ -8914,7 +8919,7 @@ namespace Mono.CSharp @@ -8914,7 +8919,7 @@ namespace Mono.CSharp
#else
var value = new[] { source.MakeExpression (ctx) };
var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
#if NET_4_0
#if NET_4_0 || MONODROID
return SLE.Expression.Block (
SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo (), args),
value [0]);
@ -10016,8 +10021,11 @@ namespace Mono.CSharp @@ -10016,8 +10021,11 @@ namespace Mono.CSharp
public override void EmitStatement (EmitContext ec)
{
foreach (ExpressionStatement e in initializers)
foreach (ExpressionStatement e in initializers) {
// TODO: need location region
ec.Mark (e.Location);
e.EmitStatement (ec);
}
}
}
@ -10245,9 +10253,8 @@ namespace Mono.CSharp @@ -10245,9 +10253,8 @@ namespace Mono.CSharp
return null;
int errors = ec.Report.Errors;
type.CreateType ();
type.DefineType ();
type.ResolveTypeParameters ();
type.CreateContainer ();
type.DefineContainer ();
type.Define ();
if ((ec.Report.Errors - errors) == 0) {
parent.Module.AddAnonymousType (type);
@ -10262,8 +10269,11 @@ namespace Mono.CSharp @@ -10262,8 +10269,11 @@ namespace Mono.CSharp
return base.CreateExpressionTree (ec);
var init = new ArrayInitializer (parameters.Count, loc);
foreach (Property p in anonymous_type.Properties)
init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
foreach (var m in anonymous_type.Members) {
var p = m as Property;
if (p != null)
init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
}
var ctor_args = new ArrayInitializer (arguments.Count, loc);
foreach (Argument a in arguments)
@ -10292,7 +10302,7 @@ namespace Mono.CSharp @@ -10292,7 +10302,7 @@ namespace Mono.CSharp
bool error = false;
arguments = new Arguments (parameters.Count);
TypeExpression [] t_args = new TypeExpression [parameters.Count];
var t_args = new TypeSpec [parameters.Count];
for (int i = 0; i < parameters.Count; ++i) {
Expression e = parameters [i].Resolve (ec);
if (e == null) {
@ -10301,7 +10311,7 @@ namespace Mono.CSharp @@ -10301,7 +10311,7 @@ namespace Mono.CSharp
}
arguments.Add (new Argument (e));
t_args [i] = new TypeExpression (e.Type, e.Location);
t_args [i] = e.Type;
}
if (error)
@ -10311,8 +10321,15 @@ namespace Mono.CSharp @@ -10311,8 +10321,15 @@ namespace Mono.CSharp
if (anonymous_type == null)
return null;
RequestedType = new GenericTypeExpr (anonymous_type.Definition, new TypeArguments (t_args), loc);
return base.DoResolve (ec);
type = anonymous_type.Definition.MakeGenericType (ec.Module, t_args);
method = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
eclass = ExprClass.Value;
return this;
}
public override void EmitStatement (EmitContext ec)
{
base.EmitStatement (ec);
}
public override object Accept (StructuralVisitor visitor)

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

@ -62,7 +62,7 @@ namespace Mono.CSharp @@ -62,7 +62,7 @@ namespace Mono.CSharp
static readonly string[] attribute_targets = new string [] { "field" };
protected FieldBase (TypeContainer parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
protected FieldBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
: base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE, name, attrs)
{
if ((mod & Modifiers.ABSTRACT) != 0)
@ -118,8 +118,7 @@ namespace Mono.CSharp @@ -118,8 +118,7 @@ namespace Mono.CSharp
declarators.Add (declarator);
// TODO: This will probably break
Parent.AddMember (this, declarator.Name.Value);
Parent.AddNameToContainer (this, declarator.Name.Value);
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
@ -375,7 +374,7 @@ namespace Mono.CSharp @@ -375,7 +374,7 @@ namespace Mono.CSharp
Modifiers.PRIVATE |
Modifiers.UNSAFE;
public FixedField (TypeContainer parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
public FixedField (TypeDefinition parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
: base (parent, type, mod, AllowedModifiers, name, attrs)
{
}
@ -407,12 +406,12 @@ namespace Mono.CSharp @@ -407,12 +406,12 @@ namespace Mono.CSharp
GetSignatureForError ());
} else if (declarators != null) {
var t = new TypeExpression (MemberType, TypeExpression.Location);
int index = Parent.PartialContainer.Fields.IndexOf (this);
foreach (var d in declarators) {
var f = new FixedField (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
f.initializer = d.Initializer;
((ConstInitializer) f.initializer).Name = d.Name.Value;
Parent.PartialContainer.Fields.Insert (++index, f);
f.Define ();
Parent.PartialContainer.Members.Add (f);
}
}
@ -577,7 +576,7 @@ namespace Mono.CSharp @@ -577,7 +576,7 @@ namespace Mono.CSharp
Modifiers.UNSAFE |
Modifiers.READONLY;
public Field (TypeContainer parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
public Field (TypeDefinition parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
: base (parent, type, mod, AllowedModifiers, name, attrs)
{
}
@ -639,19 +638,19 @@ namespace Mono.CSharp @@ -639,19 +638,19 @@ namespace Mono.CSharp
}
if (initializer != null) {
((TypeContainer) Parent).RegisterFieldForInitialization (this,
Parent.RegisterFieldForInitialization (this,
new FieldInitializer (spec, initializer, this));
}
if (declarators != null) {
var t = new TypeExpression (MemberType, TypeExpression.Location);
int index = Parent.PartialContainer.Fields.IndexOf (this);
foreach (var d in declarators) {
var f = new Field (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
if (d.Initializer != null)
f.initializer = d.Initializer;
Parent.PartialContainer.Fields.Insert (++index, f);
f.Define ();
Parent.PartialContainer.Members.Add (f);
}
}

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

@ -1213,7 +1213,6 @@ namespace Mono.CSharp @@ -1213,7 +1213,6 @@ namespace Mono.CSharp
class StructInfo
{
public readonly TypeSpec Type;
readonly List<FieldSpec> fields;
public readonly TypeInfo[] StructFields;
public readonly int Length;
@ -1223,14 +1222,13 @@ namespace Mono.CSharp @@ -1223,14 +1222,13 @@ namespace Mono.CSharp
private Dictionary<string, TypeInfo> struct_field_hash;
private Dictionary<string, int> field_hash;
protected bool InTransit;
bool InTransit;
// Private constructor. To save memory usage, we only need to create one instance
// of this class per struct type.
private StructInfo (TypeSpec type)
//
// We only need one instance per type
//
StructInfo (TypeSpec type)
{
this.Type = type;
field_type_hash.Add (type, this);
fields = MemberCache.GetAllFieldsForDefiniteAssignment (type);
@ -1327,7 +1325,7 @@ namespace Mono.CSharp @@ -1327,7 +1325,7 @@ namespace Mono.CSharp
// </summary>
public class VariableInfo {
readonly string Name;
public readonly TypeInfo TypeInfo;
readonly TypeInfo TypeInfo;
// <summary>
// The bit offset of this variable in the flow vector.
@ -1348,7 +1346,7 @@ namespace Mono.CSharp @@ -1348,7 +1346,7 @@ namespace Mono.CSharp
VariableInfo[] sub_info;
protected VariableInfo (string name, TypeSpec type, int offset)
VariableInfo (string name, TypeSpec type, int offset)
{
this.Name = name;
this.Offset = offset;
@ -1359,7 +1357,7 @@ namespace Mono.CSharp @@ -1359,7 +1357,7 @@ namespace Mono.CSharp
Initialize ();
}
protected VariableInfo (VariableInfo parent, TypeInfo type)
VariableInfo (VariableInfo parent, TypeInfo type)
{
this.Name = parent.Name;
this.TypeInfo = type;
@ -1451,6 +1449,11 @@ namespace Mono.CSharp @@ -1451,6 +1449,11 @@ namespace Mono.CSharp
return !ec.DoFlowAnalysis || ec.CurrentBranching.IsStructFieldAssigned (this, name);
}
public bool IsFullyInitialized (BlockContext bc, Location loc)
{
return TypeInfo.IsFullyInitialized (bc, this, loc);
}
public bool IsStructFieldAssigned (MyBitVector vector, string field_name)
{
int field_idx = TypeInfo.GetFieldIndex (field_name);
@ -1495,7 +1498,7 @@ namespace Mono.CSharp @@ -1495,7 +1498,7 @@ namespace Mono.CSharp
var complex_field = TypeInfo.GetStructField (field_name);
if (complex_field != null) {
vector.SetRange (complex_field.Offset, complex_field.TotalLength);
vector.SetRange (Offset + complex_field.Offset, complex_field.TotalLength);
} else {
vector[Offset + field_idx] = true;
}
@ -1505,7 +1508,7 @@ namespace Mono.CSharp @@ -1505,7 +1508,7 @@ namespace Mono.CSharp
//
// Each field must be assigned
//
for (int i = Offset + 1; i <= TypeInfo.TotalLength + Offset; i++) {
for (int i = Offset + 1; i < TypeInfo.TotalLength + Offset; i++) {
if (!vector[i])
return;
}

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

@ -479,7 +479,7 @@ namespace Mono.CSharp { @@ -479,7 +479,7 @@ namespace Mono.CSharp {
// already have constraints they become our constraints. If we already
// have constraints, we must check that they're the same.
//
public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
{
if (builder == null)
throw new InvalidOperationException ();
@ -1831,9 +1831,13 @@ namespace Mono.CSharp { @@ -1831,9 +1831,13 @@ namespace Mono.CSharp {
return;
}
var tc = open_type.MemberDefinition as TypeContainer;
if (tc != null && !tc.HasMembersDefined)
throw new InternalErrorException ("Inflating MemberCache with undefined members");
var tc = open_type.MemberDefinition as TypeDefinition;
if (tc != null && !tc.HasMembersDefined) {
//
// Inflating MemberCache with undefined members
//
return;
}
if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
BaseType = inflator.Inflate (open_type.BaseType);
@ -2094,6 +2098,11 @@ namespace Mono.CSharp { @@ -2094,6 +2098,11 @@ namespace Mono.CSharp {
return null;
}
public string[] GetAllNames ()
{
return names.Select (l => l.Name).ToArray ();
}
public string GetSignatureForError ()
{
StringBuilder sb = new StringBuilder ();
@ -2849,16 +2858,17 @@ namespace Mono.CSharp { @@ -2849,16 +2858,17 @@ namespace Mono.CSharp {
if (!u.IsArray)
return 0;
// TODO MemberCache: GetMetaInfo ()
if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
var ac_u = (ArrayContainer) u;
var ac_v = (ArrayContainer) v;
if (ac_u.Rank != ac_v.Rank)
return 0;
return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
return ExactInference (ac_u.Element, ac_v.Element);
}
// If V is constructed type and U is constructed type
if (TypeManager.IsGenericType (v)) {
if (!TypeManager.IsGenericType (u))
if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
return 0;
TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);

111
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs.csproj

@ -1,111 +0,0 @@ @@ -1,111 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>gmcs</RootNamespace>
<AssemblyName>gmcs</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\..\monodevelop\main\build\bin</OutputPath>
<DefineConstants>TRACE;DEBUG;NET_2_0;MS_COMPATIBLE;FULL_AST;BOOTSTRAP_BASIC</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<DefineConstants>TRACE;NET_2_0;MS_COMPATIBLE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<DefineConstants>TRACE;NET_2_0;MS_COMPATIBLE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<OutputPath>..\..\..\monodevelop\main\build\bin</OutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\class\corlib\Mono.Security.Cryptography\CryptoConvert.cs" />
<Compile Include="..\class\Mono.CompilerServices.SymbolWriter\MonoSymbolFile.cs" />
<Compile Include="..\class\Mono.CompilerServices.SymbolWriter\MonoSymbolTable.cs" />
<Compile Include="..\class\Mono.CompilerServices.SymbolWriter\MonoSymbolWriter.cs" />
<Compile Include="argument.cs" />
<Compile Include="AssemblyInfo.cs" />
<Compile Include="anonymous.cs" />
<Compile Include="assign.cs" />
<Compile Include="attribute.cs" />
<Compile Include="cfold.cs" />
<Compile Include="class.cs" />
<Compile Include="codegen.cs" />
<Compile Include="complete.cs" />
<Compile Include="const.cs" />
<Compile Include="constant.cs" />
<Compile Include="context.cs" />
<Compile Include="convert.cs" />
<Compile Include="dynamic.cs" />
<Compile Include="eval.cs" />
<Compile Include="import.cs" />
<Compile Include="lambda.cs" />
<Compile Include="cs-parser.cs" />
<Compile Include="cs-tokenizer.cs" />
<Compile Include="decl.cs" />
<Compile Include="delegate.cs" />
<Compile Include="doc.cs" />
<Compile Include="driver.cs" />
<Compile Include="ecore.cs" />
<Compile Include="enum.cs" />
<Compile Include="expression.cs" />
<Compile Include="flowanalysis.cs" />
<Compile Include="generic.cs" />
<Compile Include="iterators.cs" />
<Compile Include="literal.cs" />
<Compile Include="location.cs" />
<Compile Include="membercache.cs" />
<Compile Include="method.cs" />
<Compile Include="modifiers.cs" />
<Compile Include="namespace.cs" />
<Compile Include="nullable.cs" />
<Compile Include="..\tools\monop\outline.cs" />
<Compile Include="parameter.cs" />
<Compile Include="pending.cs" />
<Compile Include="property.cs" />
<Compile Include="report.cs" />
<Compile Include="rootcontext.cs" />
<Compile Include="roottypes.cs" />
<Compile Include="statement.cs" />
<Compile Include="support.cs" />
<Compile Include="symbolwriter.cs" />
<Compile Include="typemanager.cs" />
<Compile Include="linq.cs" />
<Compile Include="field.cs" />
<Compile Include="typespec.cs" />
<Compile Include="visit.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

14
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs.exe.config

@ -1,14 +0,0 @@ @@ -1,14 +0,0 @@
<configuration>
<startup>
<supportedRuntime version="v2.0.50727"/>
</startup>
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="compilerLogListener" type="System.Diagnostics.TextWriterTraceListener,System"
initializeData="mcs.log" />
<remove type="System.Diagnostics.DefaultTraceListener,System"/>
</listeners>
</trace>
</system.diagnostics>
</configuration>

56
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs.exe.sources

@ -1,56 +0,0 @@ @@ -1,56 +0,0 @@
AssemblyInfo.cs
anonymous.cs
argument.cs
assign.cs
attribute.cs
cs-tokenizer.cs
cfold.cs
class.cs
codegen.cs
complete.cs
const.cs
constant.cs
convert.cs
context.cs
decl.cs
delegate.cs
doc.cs
doc-bootstrap.cs
driver.cs
dynamic.cs
ecore.cs
enum.cs
eval.cs
expression.cs
field.cs
flowanalysis.cs
generic.cs
import.cs
iterators.cs
lambda.cs
linq.cs
literal.cs
location.cs
membercache.cs
method.cs
modifiers.cs
namespace.cs
nullable.cs
parameter.cs
pending.cs
property.cs
report.cs
rootcontext.cs
roottypes.cs
statement.cs
support.cs
typemanager.cs
typespec.cs
visit.cs
symbolwriter.cs
../class/Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs
../class/Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs
../class/Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs
../class/corlib/Mono.Security.Cryptography/CryptoConvert.cs
../build/common/Consts.cs
../tools/monop/outline.cs

20
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs.sln

@ -1,20 +0,0 @@ @@ -1,20 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 10.00
# Visual C# Express 2008
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "gmcs", "gmcs.csproj", "{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4A01C5B-A1B5-48F5-BB5B-D2E1BD236E56}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

23
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs.userprefs

@ -1,23 +0,0 @@ @@ -1,23 +0,0 @@
<Properties>
<MonoDevelop.Ide.Workspace ActiveConfiguration="Debug" />
<MonoDevelop.Ide.Workbench ActiveDocument="cs-parser.jay">
<Files>
<File FileName="cs-parser.jay" Line="5349" Column="43" />
</Files>
<Pads>
<Pad Id="ProjectPad">
<State expanded="True">
<Node name="gmcs" expanded="True">
<Option id="ShowVersionControlOverlays" value="True" />
<Option id="ShowAllFiles" value="True" />
<Node name="cs-parser.jay" selected="True" />
</Node>
</State>
</Pad>
</Pads>
</MonoDevelop.Ide.Workbench>
<MonoDevelop.Ide.DebuggingService.Breakpoints>
<BreakpointStore />
</MonoDevelop.Ide.DebuggingService.Breakpoints>
<MonoDevelop.Ide.DebuggingService.PinnedWatches />
</Properties>

29
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/gmcs2.csproj

@ -1,29 +0,0 @@ @@ -1,29 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AssemblyName>gmcs</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<ResponseFile>gmcs.exe.sources</ResponseFile>
<CodePage>65001</CodePage>
<OutputPath>..\class\lib\basic\</OutputPath>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'basic|AnyCPU' ">
<DefineConstants>BOOTSTRAP_BASIC,NET_1_1,NET_2_0</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_2_0|AnyCPU' ">
<DefineConstants>NET_1_1,NET_2_0</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="cs-parser.cs"/>
<Reference Include="System.dll"/>
<Reference Include="System.Core.dll"/>
<Reference Include="System.XML.dll"/>
</ItemGroup>
<Import Project="$(MSBuildProjectDirectory)\..\build\msbuild\Mono.Common.targets"/>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Target Name="BeforeBuild" DependsOnTargets="SetupProject">
<Exec Command="..\jay\jay.exe -cvt &lt; ..\jay\skeleton.cs cs-parser.jay &gt; cs-parser.cs"/>
</Target>
</Project>

0
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/hosting.cs

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

@ -160,7 +160,7 @@ namespace Mono.CSharp @@ -160,7 +160,7 @@ namespace Mono.CSharp
Field pc_field;
StateMachineMethod method;
protected StateMachine (Block block, TypeContainer parent, MemberBase host, TypeParameters tparams, string name)
protected StateMachine (Block block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name)
: base (block, parent, host, tparams, name)
{
}
@ -187,7 +187,7 @@ namespace Mono.CSharp @@ -187,7 +187,7 @@ namespace Mono.CSharp
throw new InternalErrorException ();
this.method = method;
AddMethod (method);
Members.Add (method);
}
protected override bool DoDefineMembers ()
@ -289,10 +289,23 @@ namespace Mono.CSharp @@ -289,10 +289,23 @@ namespace Mono.CSharp
}
}
public GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
: base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name)
{
Block.AddStatement (new GetEnumeratorStatement (host, this));
}
public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
{
return Create (host, returnType, name, null);
}
public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
{
var m = new GetEnumeratorMethod (host, returnType, name);
var stmt = statement ?? new GetEnumeratorStatement (host, m);
m.block.AddStatement (stmt);
m.block.IsCompilerGenerated = true;
return m;
}
}
@ -329,9 +342,10 @@ namespace Mono.CSharp @@ -329,9 +342,10 @@ namespace Mono.CSharp
: base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
new MemberName ("Dispose", host.Location))
{
host.AddMethod (this);
host.Members.Add (this);
Block.AddStatement (new DisposeMethodStatement (host.Iterator));
Block.IsCompilerGenerated = true;
}
}
@ -479,25 +493,23 @@ namespace Mono.CSharp @@ -479,25 +493,23 @@ namespace Mono.CSharp
if (Iterator.IsEnumerable) {
FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
var name = new MemberName ("GetEnumerator", null, explicit_iface, Location);
var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
if (generic_enumerator_type != null) {
Method get_enumerator = new StateMachineMethod (this, null, enumerator_type, 0, name);
explicit_iface = new GenericTypeExpr (Module.PredefinedTypes.IEnumerableGeneric.Resolve (), generic_args, Location);
name = new MemberName ("GetEnumerator", null, explicit_iface, Location);
Method gget_enumerator = new GetEnumeratorMethod (this, generic_enumerator_type, name);
var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
Method gget_enumerator = GetEnumeratorMethod.Create (this, generic_enumerator_type, gname);
//
// Just call generic GetEnumerator implementation
//
get_enumerator.Block.AddStatement (
new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location));
var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
Method get_enumerator = GetEnumeratorMethod.Create (this, enumerator_type, name, stmt);
AddMethod (get_enumerator);
AddMethod (gget_enumerator);
Members.Add (get_enumerator);
Members.Add (gget_enumerator);
} else {
AddMethod (new GetEnumeratorMethod (this, enumerator_type, name));
Members.Add (GetEnumeratorMethod.Create (this, enumerator_type, name));
}
}
@ -519,26 +531,30 @@ namespace Mono.CSharp @@ -519,26 +531,30 @@ namespace Mono.CSharp
var name = new MemberName ("Current", null, explicit_iface, Location);
ToplevelBlock get_block = new ToplevelBlock (Compiler, Location);
ToplevelBlock get_block = new ToplevelBlock (Compiler, Location) {
IsCompilerGenerated = true
};
get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN, name, null);
current.Get = new Property.GetMethod (current, 0, null, Location);
Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
current.Get.Block = get_block;
AddProperty (current);
Members.Add (current);
}
void Define_Reset ()
{
Method reset = new Method (
this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
new MemberName ("Reset", Location),
ParametersCompiled.EmptyReadOnlyParameters, null);
AddMethod (reset);
Members.Add (reset);
reset.Block = new ToplevelBlock (Compiler, Location);
reset.Block = new ToplevelBlock (Compiler, Location) {
IsCompilerGenerated = true
};
TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
if (ex_type == null)
@ -568,7 +584,7 @@ namespace Mono.CSharp @@ -568,7 +584,7 @@ namespace Mono.CSharp
name, ParametersCompiled.EmptyReadOnlyParameters, null)
{
this.expr = expr;
Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
}
public override EmitContext CreateEmitContext (ILGenerator ig)
@ -611,7 +627,7 @@ namespace Mono.CSharp @@ -611,7 +627,7 @@ namespace Mono.CSharp
}
}
public readonly TypeContainer Host;
public readonly TypeDefinition Host;
protected StateMachine storey;
//
@ -624,7 +640,7 @@ namespace Mono.CSharp @@ -624,7 +640,7 @@ namespace Mono.CSharp
protected LocalBuilder current_pc;
protected List<ResumableStatement> resume_points;
protected StateMachineInitializer (ParametersBlock block, TypeContainer host, TypeSpec returnType)
protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
: base (block, returnType, block.StartLocation)
{
this.Host = host;
@ -715,7 +731,7 @@ namespace Mono.CSharp @@ -715,7 +731,7 @@ namespace Mono.CSharp
storey.Instance.Emit (ec);
}
void EmitMoveNext_NoResumePoints (EmitContext ec, Block original_block)
void EmitMoveNext_NoResumePoints (EmitContext ec)
{
ec.EmitThis ();
ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
@ -729,9 +745,11 @@ namespace Mono.CSharp @@ -729,9 +745,11 @@ namespace Mono.CSharp
iterator_body_end = ec.DefineLabel ();
SymbolWriter.StartIteratorBody (ec);
original_block.Emit (ec);
SymbolWriter.EndIteratorBody (ec);
if (ec.EmitAccurateDebugInfo && ec.Mark (Block.Original.StartLocation)) {
ec.Emit (OpCodes.Nop);
}
block.Emit (ec);
ec.MarkLabel (iterator_body_end);
@ -751,7 +769,7 @@ namespace Mono.CSharp @@ -751,7 +769,7 @@ namespace Mono.CSharp
move_next_error = ec.DefineLabel ();
if (resume_points == null) {
EmitMoveNext_NoResumePoints (ec, block);
EmitMoveNext_NoResumePoints (ec);
return;
}
@ -785,22 +803,20 @@ namespace Mono.CSharp @@ -785,22 +803,20 @@ namespace Mono.CSharp
if (async_init != null)
ec.BeginExceptionBlock ();
SymbolWriter.StartIteratorDispatcher (ec);
ec.Emit (OpCodes.Ldloc, current_pc);
ec.Emit (OpCodes.Switch, labels);
ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
SymbolWriter.EndIteratorDispatcher (ec);
ec.MarkLabel (labels[0]);
iterator_body_end = ec.DefineLabel ();
SymbolWriter.StartIteratorBody (ec);
block.Emit (ec);
SymbolWriter.EndIteratorBody (ec);
if (ec.EmitAccurateDebugInfo && ec.Mark (Block.Original.StartLocation)) {
ec.Emit (OpCodes.Nop);
}
SymbolWriter.StartIteratorDispatcher (ec);
block.Emit (ec);
ec.MarkLabel (iterator_body_end);
@ -820,6 +836,7 @@ namespace Mono.CSharp @@ -820,6 +836,7 @@ namespace Mono.CSharp
ec.EndExceptionBlock ();
}
ec.Mark (Block.Original.EndLocation);
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
@ -839,8 +856,6 @@ namespace Mono.CSharp @@ -839,8 +856,6 @@ namespace Mono.CSharp
ec.EmitInt (1);
ec.Emit (OpCodes.Ret);
}
SymbolWriter.EndIteratorDispatcher (ec);
}
protected virtual void EmitMoveNextEpilogue (EmitContext ec)
@ -897,7 +912,7 @@ namespace Mono.CSharp @@ -897,7 +912,7 @@ namespace Mono.CSharp
public readonly bool IsEnumerable;
public readonly TypeSpec OriginalIteratorType;
public Iterator (ParametersBlock block, IMethodData method, TypeContainer host, TypeSpec iterator_type, bool is_enumerable)
public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
: base (block, host, host.Compiler.BuiltinTypes.Bool)
{
this.OriginalMethod = method;
@ -1025,7 +1040,7 @@ namespace Mono.CSharp @@ -1025,7 +1040,7 @@ namespace Mono.CSharp
return bc;
}
public static void CreateIterator (IMethodData method, TypeContainer parent, Modifiers modifiers)
public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
{
bool is_enumerable;
TypeSpec iterator_type;

24
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/lambda.todo

@ -1,24 +0,0 @@ @@ -1,24 +0,0 @@
Tasks for completing Lambda support:
* Port the grammar to mcs
* Everywhere where we use Arguments, we need to clone them.
* We need a "CloneContext" that would keep track of mappings between
the old blocks and the new blocks, so that expression that keep
pointers to blocks can get the proper block on cloning, something like:
CloneTo (CloneContext cc, Expression t)
{
MyClass target = (MyClass) t;
target.Block = cc.RemapBlock (Block);
}
* Generics section support.
* Fix the bug in the modified l1.cs that introduces two rets instead
of a single one.
* Complete CloneTo for Statements.
* Write an extensive test suite to exercise CloneTo

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

@ -850,7 +850,7 @@ namespace Mono.CSharp.Linq @@ -850,7 +850,7 @@ namespace Mono.CSharp.Linq
public void AddRangeVariable (RangeVariable variable)
{
variable.Block = this;
AddLocalName (variable.Name, variable);
TopBlock.AddLocalName (variable.Name, variable, true);
}
public override void Error_AlreadyDeclared (string name, INamedBlockVariable variable, string reason)

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

@ -17,16 +17,42 @@ using Mono.CompilerServices.SymbolWriter; @@ -17,16 +17,42 @@ using Mono.CompilerServices.SymbolWriter;
using System.Diagnostics;
using System.Linq;
namespace Mono.CSharp {
/// <summary>
/// This is one single source file.
/// </summary>
/// <remarks>
/// This is intentionally a class and not a struct since we need
/// to pass this by reference.
/// </remarks>
public class SourceFile : ISourceFile, IEquatable<SourceFile>
namespace Mono.CSharp
{
//
// This is one single source file.
//
public class SourceFile : IEquatable<SourceFile>
{
//
// Used by #line directive to track hidden sequence point
// regions
//
struct LocationRegion : IComparable<LocationRegion>
{
public readonly Location Start;
public readonly Location End;
public LocationRegion (Location start, Location end)
{
this.Start = start;
this.End = end;
}
public int CompareTo (LocationRegion other)
{
if (Start.Row == other.Start.Row)
return Start.Column.CompareTo (other.Start.Column);
return Start.Row.CompareTo (other.Start.Row);
}
public override string ToString ()
{
return Start.ToString () + " - " + End.ToString ();
}
}
public readonly string Name;
public readonly string FullPathName;
public readonly int Index;
@ -34,6 +60,7 @@ namespace Mono.CSharp { @@ -34,6 +60,7 @@ namespace Mono.CSharp {
SourceFileEntry file;
byte[] guid, checksum;
List<LocationRegion> hidden_lines;
public SourceFile (string name, string path, int index)
{
@ -43,11 +70,9 @@ namespace Mono.CSharp { @@ -43,11 +70,9 @@ namespace Mono.CSharp {
}
public SourceFileEntry SourceFileEntry {
get { return file; }
}
SourceFileEntry ISourceFile.Entry {
get { return file; }
get {
return file;
}
}
public void SetChecksum (byte[] guid, byte[] checksum)
@ -56,8 +81,11 @@ namespace Mono.CSharp { @@ -56,8 +81,11 @@ namespace Mono.CSharp {
this.checksum = checksum;
}
public virtual void DefineSymbolInfo (MonoSymbolWriter symwriter)
public SourceFileEntry CreateSymbolInfo (MonoSymbolWriter symwriter)
{
if (hidden_lines != null)
hidden_lines.Sort ();
if (guid != null)
file = symwriter.DefineDocument (FullPathName, guid, checksum);
else {
@ -65,6 +93,8 @@ namespace Mono.CSharp { @@ -65,6 +93,8 @@ namespace Mono.CSharp {
if (AutoGenerated)
file.SetAutoGenerated ();
}
return file;
}
public bool Equals (SourceFile other)
@ -72,97 +102,33 @@ namespace Mono.CSharp { @@ -72,97 +102,33 @@ namespace Mono.CSharp {
return FullPathName == other.FullPathName;
}
public override string ToString ()
public bool IsHiddenLocation (Location loc)
{
return String.Format ("SourceFile ({0}:{1}:{2}:{3})",
Name, FullPathName, Index, SourceFileEntry);
}
}
public class CompilationSourceFile : SourceFile, ICompileUnit
{
CompileUnitEntry comp_unit;
Dictionary<string, SourceFile> include_files;
Dictionary<string, bool> conditionals;
NamespaceContainer ns_container;
if (hidden_lines == null)
return false;
public CompilationSourceFile (string name, string fullPathName, int index)
: base (name, fullPathName, index)
{
}
CompileUnitEntry ICompileUnit.Entry {
get { return comp_unit; }
}
public CompileUnitEntry CompileUnitEntry {
get { return comp_unit; }
}
public NamespaceContainer NamespaceContainer {
get {
return ns_container;
int index = hidden_lines.BinarySearch (new LocationRegion (loc, loc));
index = ~index;
if (index > 0) {
var found = hidden_lines[index - 1];
if (loc.Row < found.End.Row)
return true;
}
set {
ns_container = value;
}
}
public void AddIncludeFile (SourceFile file)
{
if (file == this)
return;
if (include_files == null)
include_files = new Dictionary<string, SourceFile> ();
if (!include_files.ContainsKey (file.FullPathName))
include_files.Add (file.FullPathName, file);
return false;
}
public void AddDefine (string value)
public void RegisterHiddenScope (Location start, Location end)
{
if (conditionals == null)
conditionals = new Dictionary<string, bool> (2);
if (hidden_lines == null)
hidden_lines = new List<LocationRegion> ();
conditionals [value] = true;
hidden_lines.Add (new LocationRegion (start, end));
}
public void AddUndefine (string value)
{
if (conditionals == null)
conditionals = new Dictionary<string, bool> (2);
conditionals [value] = false;
}
public override void DefineSymbolInfo (MonoSymbolWriter symwriter)
{
base.DefineSymbolInfo (symwriter);
comp_unit = symwriter.DefineCompilationUnit (SourceFileEntry);
if (include_files != null) {
foreach (SourceFile include in include_files.Values) {
include.DefineSymbolInfo (symwriter);
comp_unit.AddFile (include.SourceFileEntry);
}
}
}
public bool IsConditionalDefined (CompilerContext ctx, string value)
public override string ToString ()
{
if (conditionals != null) {
bool res;
if (conditionals.TryGetValue (value, out res))
return res;
// When conditional was undefined
if (conditionals.ContainsKey (value))
return false;
}
return ctx.Settings.IsConditionalSymbolDefined (value);
return String.Format ("SourceFile ({0}:{1}:{2})", Name, FullPathName, Index);
}
}
@ -186,41 +152,37 @@ namespace Mono.CSharp { @@ -186,41 +152,37 @@ namespace Mono.CSharp {
{
struct Checkpoint {
public readonly int LineOffset;
public readonly int CompilationUnit;
public readonly int File;
public Checkpoint (int compile_unit, int file, int line)
public Checkpoint (int file, int line)
{
File = file;
CompilationUnit = compile_unit;
LineOffset = line - (int) (line % (1 << line_delta_bits));
}
}
#if FULL_AST
long token;
readonly long token;
const int column_bits = 24;
const int line_delta_bits = 24;
#else
int token;
readonly int token;
const int column_bits = 8;
const int line_delta_bits = 8;
#endif
const int checkpoint_bits = 16;
// -2 because the last one is used for hidden
const int max_column = (1 << column_bits) - 2;
const int column_mask = (1 << column_bits) - 1;
const int max_column = column_mask;
static List<SourceFile> source_list;
static int current_source;
static int current_compile_unit;
static Checkpoint [] checkpoints;
static int checkpoint_index;
public readonly static Location Null = new Location (-1);
public readonly static Location Null = new Location ();
public static bool InEmacs;
static Location ()
@ -232,15 +194,12 @@ namespace Mono.CSharp { @@ -232,15 +194,12 @@ namespace Mono.CSharp {
{
source_list = new List<SourceFile> ();
current_source = 0;
current_compile_unit = 0;
checkpoint_index = 0;
}
public static SourceFile AddFile (string name, string fullName)
public static void AddFile (SourceFile file)
{
var source = new SourceFile (name, fullName, source_list.Count + 1);
source_list.Add (source);
return source;
source_list.Add (file);
}
// <summary>
@ -249,31 +208,25 @@ namespace Mono.CSharp { @@ -249,31 +208,25 @@ namespace Mono.CSharp {
// source file. We reserve some extra space for files we encounter via #line
// directives while parsing.
// </summary>
static public void Initialize (List<CompilationSourceFile> files)
static public void Initialize (List<SourceFile> files)
{
#if NET_4_0
#if NET_4_0 || MONODROID
source_list.AddRange (files);
#else
source_list.AddRange (files.ToArray ());
#endif
checkpoints = new Checkpoint [source_list.Count * 2];
checkpoints = new Checkpoint [System.Math.Max (1, source_list.Count * 2)];
if (checkpoints.Length > 0)
checkpoints [0] = new Checkpoint (0, 0, 0);
checkpoints [0] = new Checkpoint (0, 0);
}
static public void Push (CompilationSourceFile compile_unit, SourceFile file)
static public void Push (SourceFile file)
{
current_source = file != null ? file.Index : -1;
current_compile_unit = compile_unit != null ? compile_unit.Index : -1;
// File is always pushed before being changed.
}
public Location (int row)
: this (row, 0)
{
}
public Location (int row, int column)
{
if (row <= 0)
@ -281,8 +234,6 @@ namespace Mono.CSharp { @@ -281,8 +234,6 @@ namespace Mono.CSharp {
else {
if (column > max_column)
column = max_column;
else if (column < 0)
column = max_column + 1;
long target = -1;
long delta = 0;
@ -301,7 +252,7 @@ namespace Mono.CSharp { @@ -301,7 +252,7 @@ namespace Mono.CSharp {
}
}
if (target == -1) {
AddCheckpoint (current_compile_unit, current_source, row);
AddCheckpoint (current_source, row);
target = checkpoint_index;
delta = row % (1 << line_delta_bits);
}
@ -322,12 +273,12 @@ namespace Mono.CSharp { @@ -322,12 +273,12 @@ namespace Mono.CSharp {
return new Location (loc.Row, loc.Column - columns);
}
static void AddCheckpoint (int compile_unit, int file, int row)
static void AddCheckpoint (int file, int row)
{
if (checkpoints.Length == ++checkpoint_index) {
Array.Resize (ref checkpoints, checkpoint_index * 2);
}
checkpoints [checkpoint_index] = new Checkpoint (compile_unit, file, row);
checkpoints [checkpoint_index] = new Checkpoint (file, row);
}
string FormatLocation (string fileName)
@ -359,10 +310,9 @@ namespace Mono.CSharp { @@ -359,10 +310,9 @@ namespace Mono.CSharp {
public string Name {
get {
int index = File;
if (token == 0 || index == 0)
return "Internal";
if (source_list == null || index - 1 >= source_list.Count)
return "unknown_file";
if (token == 0 || index <= 0)
return null;
SourceFile file = source_list [index - 1];
return file.Name;
@ -372,8 +322,8 @@ namespace Mono.CSharp { @@ -372,8 +322,8 @@ namespace Mono.CSharp {
public string NameFullPath {
get {
int index = File;
if (token == 0 || index == 0)
return "Internal";
if (token == 0 || index <= 0)
return null;
return source_list[index - 1].FullPathName;
}
@ -402,23 +352,7 @@ namespace Mono.CSharp { @@ -402,23 +352,7 @@ namespace Mono.CSharp {
get {
if (token == 0)
return 1;
int col = (int) (token & column_mask);
return col > max_column ? 1 : col;
}
}
public bool Hidden {
get {
return (int) (token & column_mask) == max_column + 1;
}
}
public int CompilationUnitIndex {
get {
if (token == 0)
return 0;
if (checkpoints.Length <= CheckpointIndex) throw new Exception (String.Format ("Should not happen. Token is {0:X04}, checkpoints are {1}, index is {2}", token, checkpoints.Length, CheckpointIndex));
return checkpoints [CheckpointIndex].CompilationUnit;
return (int) (token & column_mask);
}
}
@ -448,16 +382,7 @@ if (checkpoints.Length <= CheckpointIndex) throw new Exception (String.Format (" @@ -448,16 +382,7 @@ if (checkpoints.Length <= CheckpointIndex) throw new Exception (String.Format ("
int index = File;
if (index == 0)
return null;
return (SourceFile) source_list [index - 1];
}
}
public CompilationSourceFile CompilationUnit {
get {
int index = CompilationUnitIndex;
if (index == 0)
return null;
return (CompilationSourceFile) source_list [index - 1];
return source_list [index - 1];
}
}
@ -765,173 +690,4 @@ if (checkpoints.Length <= CheckpointIndex) throw new Exception (String.Format (" @@ -765,173 +690,4 @@ if (checkpoints.Length <= CheckpointIndex) throw new Exception (String.Format ("
return found;
}
}
public class UsingsBag
{
public class Namespace {
public Location NamespaceLocation { get; set; }
public MemberName Name { get; set; }
public Location OpenBrace { get; set; }
public Location CloseBrace { get; set; }
public Location OptSemicolon { get; set; }
public List<object> usings = new List<object> ();
public List<object> members = new List<object> ();
public Namespace ()
{
// in case of missing close brace, set it to the highest value.
CloseBrace = new Location (int.MaxValue, int.MaxValue);
}
public virtual void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
}
public class AliasUsing
{
public readonly Location UsingLocation;
public readonly Tokenizer.LocatedToken Identifier;
public readonly Location AssignLocation;
public readonly ATypeNameExpression Nspace;
public readonly Location SemicolonLocation;
public AliasUsing (Location usingLocation, Tokenizer.LocatedToken identifier, Location assignLocation, ATypeNameExpression nspace, Location semicolonLocation)
{
this.UsingLocation = usingLocation;
this.Identifier = identifier;
this.AssignLocation = assignLocation;
this.Nspace = nspace;
this.SemicolonLocation = semicolonLocation;
}
public virtual void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
}
public class Using
{
public readonly Location UsingLocation;
public readonly ATypeNameExpression NSpace;
public readonly Location SemicolonLocation;
public Using (Location usingLocation, ATypeNameExpression nSpace, Location semicolonLocation)
{
this.UsingLocation = usingLocation;
this.NSpace = nSpace;
this.SemicolonLocation = semicolonLocation;
}
public virtual void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
}
public class ExternAlias
{
public readonly Location ExternLocation;
public readonly Location AliasLocation;
public readonly Tokenizer.LocatedToken Identifier;
public readonly Location SemicolonLocation;
public ExternAlias (Location externLocation, Location aliasLocation, Tokenizer.LocatedToken identifier, Location semicolonLocation)
{
this.ExternLocation = externLocation;
this.AliasLocation = aliasLocation;
this.Identifier = identifier;
this.SemicolonLocation = semicolonLocation;
}
public virtual void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
}
public Namespace Global {
get;
set;
}
Stack<Namespace> curNamespace = new Stack<Namespace> ();
public UsingsBag ()
{
Global = new Namespace ();
Global.OpenBrace = new Location (1, 1);
Global.CloseBrace = new Location (int.MaxValue, int.MaxValue);
curNamespace.Push (Global);
}
[Conditional ("FULL_AST")]
public void AddUsingAlias (Location usingLocation, Tokenizer.LocatedToken identifier, Location assignLocation, ATypeNameExpression nspace, Location semicolonLocation)
{
curNamespace.Peek ().usings.Add (new AliasUsing (usingLocation, identifier, assignLocation, nspace, semicolonLocation));
}
[Conditional ("FULL_AST")]
public void AddUsing (Location usingLocation, ATypeNameExpression nspace, Location semicolonLocation)
{
curNamespace.Peek ().usings.Add (new Using (usingLocation, nspace, semicolonLocation));
}
[Conditional ("FULL_AST")]
public void AddExternAlias (Location externLocation, Location aliasLocation, Tokenizer.LocatedToken identifier, Location semicolonLocation)
{
curNamespace.Peek ().usings.Add (new ExternAlias (externLocation, aliasLocation, identifier, semicolonLocation));
}
[Conditional ("FULL_AST")]
public void DeclareNamespace (Location namespaceLocation, MemberName nspace)
{
var newNamespace = new Namespace () { NamespaceLocation = namespaceLocation, Name = nspace };
curNamespace.Peek ().members.Add (newNamespace);
curNamespace.Push (newNamespace);
}
int typeLevel = 0;
[Conditional ("FULL_AST")]
public void PushTypeDeclaration (object type)
{
if (typeLevel == 0)
curNamespace.Peek ().members.Add (type);
typeLevel++;
}
[Conditional ("FULL_AST")]
public void PopTypeDeclaration ()
{
typeLevel--;
}
[Conditional ("FULL_AST")]
public void EndNamespace (Location optSemicolon)
{
curNamespace.Peek ().OptSemicolon = optSemicolon;
curNamespace.Pop ();
}
[Conditional ("FULL_AST")]
public void EndNamespace ()
{
curNamespace.Pop ();
}
[Conditional ("FULL_AST")]
public void OpenNamespace (Location bracketLocation)
{
curNamespace.Peek ().OpenBrace = bracketLocation;
}
[Conditional ("FULL_AST")]
public void CloseNamespace (Location bracketLocation)
{
curNamespace.Peek ().CloseBrace = bracketLocation;
}
}
}

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

@ -41,6 +41,7 @@ namespace Mono.CSharp { @@ -41,6 +41,7 @@ namespace Mono.CSharp {
InternalCompilerType = 1 << 21,
MissingType = 1 << 22,
Void = 1 << 23,
Namespace = 1 << 24,
NestedMask = Class | Struct | Delegate | Enum | Interface,
GenericMask = Method | Class | Struct | Delegate | Interface,
@ -303,24 +304,28 @@ namespace Mono.CSharp { @@ -303,24 +304,28 @@ namespace Mono.CSharp {
{
if (member.Kind == MemberKind.Operator) {
var dt = member.DeclaringType;
switch (dt.BuiltinType) {
case BuiltinTypeSpec.Type.String:
case BuiltinTypeSpec.Type.Delegate:
case BuiltinTypeSpec.Type.MulticastDelegate:
// Some core types have user operators but they cannot be used as normal
// user operators as they are predefined and therefore having different
// rules (e.g. binary operators) by not setting the flag we hide them for
// user conversions
// TODO: Should I do this for all core types ?
break;
default:
if (name == Operator.GetMetadataName (Operator.OpType.Implicit) || name == Operator.GetMetadataName (Operator.OpType.Explicit)) {
state |= StateFlags.HasConversionOperator;
} else {
state |= StateFlags.HasUserOperator;
}
break;
//
// Some core types have user operators but they cannot be used like normal
// user operators as they are predefined and therefore having different
// rules (e.g. binary operators) by not setting the flag we hide them for
// user conversions
//
if (!BuiltinTypeSpec.IsPrimitiveType (dt)) {
switch (dt.BuiltinType) {
case BuiltinTypeSpec.Type.String:
case BuiltinTypeSpec.Type.Delegate:
case BuiltinTypeSpec.Type.MulticastDelegate:
break;
default:
if (name == Operator.GetMetadataName (Operator.OpType.Implicit) || name == Operator.GetMetadataName (Operator.OpType.Explicit)) {
state |= StateFlags.HasConversionOperator;
} else {
state |= StateFlags.HasUserOperator;
}
break;
}
}
}
@ -468,7 +473,7 @@ namespace Mono.CSharp { @@ -468,7 +473,7 @@ namespace Mono.CSharp {
// based on type definition
var tc = container.MemberDefinition as TypeContainer;
if (tc != null)
tc.DefineType ();
tc.DefineContainer ();
if (container.MemberCacheTypes.member_hash.TryGetValue (name, out applicable)) {
for (int i = applicable.Count - 1; i >= 0; i--) {
@ -889,7 +894,7 @@ namespace Mono.CSharp { @@ -889,7 +894,7 @@ namespace Mono.CSharp {
return IndexerNameAlias;
if (mc is Constructor)
return Constructor.ConstructorName;
return mc.IsStatic ? Constructor.TypeConstructorName : Constructor.ConstructorName;
return mc.MemberName.Name;
}

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

@ -47,7 +47,7 @@ namespace Mono.CSharp { @@ -47,7 +47,7 @@ namespace Mono.CSharp {
protected ToplevelBlock block;
protected MethodSpec spec;
public MethodCore (TypeContainer parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
public MethodCore (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
MemberName name, Attributes attrs, ParametersCompiled parameters)
: base (parent, type, mod, allowed_mod, name, attrs)
{
@ -517,7 +517,7 @@ namespace Mono.CSharp { @@ -517,7 +517,7 @@ namespace Mono.CSharp {
static readonly string[] attribute_targets = new string [] { "method", "return" };
protected MethodOrOperator (TypeContainer parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name,
protected MethodOrOperator (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name,
Attributes attrs, ParametersCompiled parameters)
: base (parent, type, mod, allowed_mod, name, attrs, parameters)
{
@ -774,9 +774,6 @@ namespace Mono.CSharp { @@ -774,9 +774,6 @@ namespace Mono.CSharp {
return conditions;
}
public virtual void EmitExtraSymbolInfo (SourceMethod source)
{ }
#endregion
}
@ -784,13 +781,11 @@ namespace Mono.CSharp { @@ -784,13 +781,11 @@ namespace Mono.CSharp {
public class SourceMethod : IMethodDef
{
MethodBase method;
SourceMethodBuilder builder;
protected SourceMethod (TypeContainer parent, MethodBase method, ICompileUnit file)
SourceMethod (MethodBase method, ICompileUnit file)
{
this.method = method;
builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
SymbolWriter.OpenMethod (file, this);
}
public string Name {
@ -818,28 +813,16 @@ namespace Mono.CSharp { @@ -818,28 +813,16 @@ namespace Mono.CSharp {
SymbolWriter.CloseMethod ();
}
public void SetRealMethodName (string name)
{
if (builder != null)
builder.SetRealMethodName (name);
}
public static SourceMethod Create (TypeContainer parent, MethodBase method, Block block)
public static SourceMethod Create (TypeDefinition parent, MethodBase method)
{
if (!SymbolWriter.HasSymbolWriter)
return null;
if (block == null)
return null;
Location start_loc = block.StartLocation;
if (start_loc.IsNull)
var source_file = parent.GetCompilationSourceFile ();
if (source_file == null)
return null;
ICompileUnit compile_unit = start_loc.CompilationUnit;
if (compile_unit == null)
return null;
return new SourceMethod (parent, method, compile_unit);
return new SourceMethod (method, source_file.SymbolUnitEntry);
}
}
@ -847,7 +830,7 @@ namespace Mono.CSharp { @@ -847,7 +830,7 @@ namespace Mono.CSharp {
{
Method partialMethodImplementation;
public Method (TypeContainer parent, FullNamedExpression return_type, Modifiers mod, MemberName name, ParametersCompiled parameters, Attributes attrs)
public Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, MemberName name, ParametersCompiled parameters, Attributes attrs)
: base (parent, return_type, mod,
parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct | Modifiers.ASYNC :
@ -856,7 +839,7 @@ namespace Mono.CSharp { @@ -856,7 +839,7 @@ namespace Mono.CSharp {
{
}
protected Method (TypeContainer parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
protected Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
MemberName name, ParametersCompiled parameters, Attributes attrs)
: base (parent, return_type, mod, amod, name, attrs, parameters)
{
@ -889,7 +872,7 @@ namespace Mono.CSharp { @@ -889,7 +872,7 @@ namespace Mono.CSharp {
visitor.Visit (this);
}
public static Method Create (TypeContainer parent, FullNamedExpression returnType, Modifiers mod,
public static Method Create (TypeDefinition parent, FullNamedExpression returnType, Modifiers mod,
MemberName name, ParametersCompiled parameters, Attributes attrs, bool hasConstraints)
{
var m = new Method (parent, returnType, mod, name, parameters, attrs);
@ -1357,10 +1340,6 @@ namespace Mono.CSharp { @@ -1357,10 +1340,6 @@ namespace Mono.CSharp {
public override bool EnableOverloadChecks (MemberCore overload)
{
// TODO: It can be deleted when members will be defined in correct order
if (overload is Operator)
return overload.EnableOverloadChecks (this);
if (overload is Indexer)
return false;
@ -1484,7 +1463,7 @@ namespace Mono.CSharp { @@ -1484,7 +1463,7 @@ namespace Mono.CSharp {
ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
caller_builder.GetSignatureForError ());
}
return this;
}
@ -1494,8 +1473,6 @@ namespace Mono.CSharp { @@ -1494,8 +1473,6 @@ namespace Mono.CSharp {
if (base_ctor == null)
return;
ec.Mark (loc);
var call = new CallEmitter ();
call.InstanceExpression = new CompilerGeneratedThis (type, loc);
call.EmitPredefined (ec, base_ctor, argument_list);
@ -1551,7 +1528,7 @@ namespace Mono.CSharp { @@ -1551,7 +1528,7 @@ namespace Mono.CSharp {
public static readonly string ConstructorName = ".ctor";
public static readonly string TypeConstructorName = ".cctor";
public Constructor (TypeContainer parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args, Location loc)
public Constructor (TypeDefinition parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args, Location loc)
: base (parent, null, mod, AllowedModifiers, new MemberName (name, loc), attrs, args)
{
}
@ -1615,6 +1592,9 @@ namespace Mono.CSharp { @@ -1615,6 +1592,9 @@ namespace Mono.CSharp {
return false;
}
if ((caching_flags & Flags.MethodOverloadsExist) != 0)
Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
// the rest can be ignored
return true;
}
@ -1645,14 +1625,6 @@ namespace Mono.CSharp { @@ -1645,14 +1625,6 @@ namespace Mono.CSharp {
if (ConstructorBuilder != null)
return true;
var ca = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
if ((ModFlags & Modifiers.STATIC) != 0) {
ca |= MethodAttributes.Static | MethodAttributes.Private;
} else {
ca |= ModifiersExtensions.MethodAttr (ModFlags);
}
if (!CheckAbstractAndExtern (block != null))
return false;
@ -1660,6 +1632,8 @@ namespace Mono.CSharp { @@ -1660,6 +1632,8 @@ namespace Mono.CSharp {
if (!CheckBase ())
return false;
var ca = ModifiersExtensions.MethodAttr (ModFlags) | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
ca, CallingConventions,
parameters.GetMetaInfo ());
@ -1703,50 +1677,56 @@ namespace Mono.CSharp { @@ -1703,50 +1677,56 @@ namespace Mono.CSharp {
base.Emit ();
parameters.ApplyAttributes (this, ConstructorBuilder);
//
// If we use a "this (...)" constructor initializer, then
// do not emit field initializers, they are initialized in the other constructor
//
bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
!(Initializer is ConstructorThisInitializer);
BlockContext bc = new BlockContext (this, block, Compiler.BuiltinTypes.Void);
bc.Set (ResolveContext.Options.ConstructorScope);
if (emit_field_initializers)
//
// If we use a "this (...)" constructor initializer, then
// do not emit field initializers, they are initialized in the other constructor
//
if (!(Initializer is ConstructorThisInitializer))
Parent.PartialContainer.ResolveFieldInitializers (bc);
if (block != null) {
// If this is a non-static `struct' constructor and doesn't have any
// initializer, it must initialize all of the struct's fields.
if ((Parent.PartialContainer.Kind == MemberKind.Struct) &&
((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
block.AddThisVariable (bc);
if ((ModFlags & Modifiers.STATIC) == 0){
if (Parent.PartialContainer.Kind == MemberKind.Class && Initializer == null)
Initializer = new GeneratedBaseInitializer (Location);
if (!IsStatic) {
if (Initializer == null) {
if (Parent.PartialContainer.Kind == MemberKind.Struct) {
//
// If this is a non-static `struct' constructor and doesn't have any
// initializer, it must initialize all of the struct's fields.
//
block.AddThisVariable (bc);
} else if (Parent.PartialContainer.Kind == MemberKind.Class) {
Initializer = new GeneratedBaseInitializer (Location);
}
}
if (Initializer != null) {
block.AddScopeStatement (new StatementExpression (Initializer));
//
// Use location of the constructor to emit sequence point of initializers
// at beginning of constructor name
//
// TODO: Need to extend mdb to support line regions to allow set a breakpoint at
// initializer
//
block.AddScopeStatement (new StatementExpression (Initializer, Location));
}
}
}
SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder, block);
if (block != null) {
if (block.Resolve (null, bc, this)) {
EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType);
ec.With (EmitContext.Options.ConstructorScope, true);
SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder);
block.Emit (ec);
if (source != null)
source.CloseMethod ();
}
}
if (source != null)
source.CloseMethod ();
if (declarative_security != null) {
foreach (var de in declarative_security) {
#if STATIC
@ -1825,9 +1805,6 @@ namespace Mono.CSharp { @@ -1825,9 +1805,6 @@ namespace Mono.CSharp {
return false;
}
void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
{ }
#endregion
}
@ -1848,7 +1825,6 @@ namespace Mono.CSharp { @@ -1848,7 +1825,6 @@ namespace Mono.CSharp {
ToplevelBlock Block { get; set; }
EmitContext CreateEmitContext (ILGenerator ig);
void EmitExtraSymbolInfo (SourceMethod source);
}
//
@ -1902,16 +1878,14 @@ namespace Mono.CSharp { @@ -1902,16 +1878,14 @@ namespace Mono.CSharp {
public MethodData (InterfaceMemberBase member,
Modifiers modifiers, MethodAttributes flags,
IMethodData method, MethodBuilder builder,
//GenericMethod generic,
MethodSpec parent_method)
: this (member, modifiers, flags, method)
{
this.builder = builder;
//this.GenericMethod = generic;
this.parent_method = parent_method;
}
public bool Define (TypeContainer container, string method_full_name)
public bool Define (TypeDefinition container, string method_full_name)
{
PendingImplementation pending = container.PendingImplementations;
MethodSpec ambig_iface_method;
@ -2083,7 +2057,7 @@ namespace Mono.CSharp { @@ -2083,7 +2057,7 @@ namespace Mono.CSharp {
/// <summary>
/// Create the MethodBuilder for the method
/// </summary>
void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
void DefineMethodBuilder (TypeDefinition container, string method_name, ParametersCompiled param)
{
var return_type = method.ReturnType.GetMetaInfo ();
var p_types = param.GetMetaInfo ();
@ -2119,27 +2093,25 @@ namespace Mono.CSharp { @@ -2119,27 +2093,25 @@ namespace Mono.CSharp {
//
// Emits the code
//
public void Emit (TypeContainer parent)
public void Emit (TypeDefinition parent)
{
var mc = (IMemberContext) method;
method.ParameterInfo.ApplyAttributes (mc, MethodBuilder);
SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
ToplevelBlock block = method.Block;
if (block != null) {
BlockContext bc = new BlockContext (mc, block, method.ReturnType);
if (block.Resolve (null, bc, method)) {
EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator ());
SourceMethod source = SourceMethod.Create (parent, MethodBuilder);
block.Emit (ec);
}
}
if (source != null) {
method.EmitExtraSymbolInfo (source);
source.CloseMethod ();
if (source != null)
source.CloseMethod ();
}
}
}
}
@ -2154,7 +2126,7 @@ namespace Mono.CSharp { @@ -2154,7 +2126,7 @@ namespace Mono.CSharp {
public static readonly string MetadataName = "Finalize";
public Destructor (TypeContainer parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
public Destructor (TypeDefinition parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
: base (parent, null, mod, AllowedModifiers, new MemberName (MetadataName, l), attrs, parameters)
{
ModFlags &= ~Modifiers.PRIVATE;
@ -2195,15 +2167,19 @@ namespace Mono.CSharp { @@ -2195,15 +2167,19 @@ namespace Mono.CSharp {
MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
method_expr.InstanceExpression = new BaseThis (base_type, Location);
var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation);
var finaly_block = new ExplicitBlock (block, Location, Location);
var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation) {
IsCompilerGenerated = true
};
var finaly_block = new ExplicitBlock (block, Location, Location) {
IsCompilerGenerated = true
};
//
// 0-size arguments to avoid CS0250 error
// TODO: Should use AddScopeStatement or something else which emits correct
// debugger scope
//
finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0))));
finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0)), Location.Null));
var tf = new TryFinally (try_block, finaly_block, Location);
block.WrapIntoDestructor (tf, try_block);
@ -2349,7 +2325,7 @@ namespace Mono.CSharp { @@ -2349,7 +2325,7 @@ namespace Mono.CSharp {
throw new NotSupportedException ();
}
public virtual void Emit (TypeContainer parent)
public virtual void Emit (TypeDefinition parent)
{
method_data.Emit (parent);
@ -2416,9 +2392,6 @@ namespace Mono.CSharp { @@ -2416,9 +2392,6 @@ namespace Mono.CSharp {
public override string DocCommentHeader {
get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
}
void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
{ }
}
public class Operator : MethodOrOperator {
@ -2504,8 +2477,8 @@ namespace Mono.CSharp { @@ -2504,8 +2477,8 @@ namespace Mono.CSharp {
names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
}
public Operator (TypeContainer parent, OpType type, FullNamedExpression ret_type, Modifiers mod_flags, ParametersCompiled parameters,
public Operator (TypeDefinition parent, OpType type, FullNamedExpression ret_type, Modifiers mod_flags, ParametersCompiled parameters,
ToplevelBlock block, Attributes attrs, Location loc)
: base (parent, ret_type, mod_flags, AllowedModifiers, new MemberName (GetMetadataName (type), loc), attrs, parameters)
{

232
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/roottypes.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/module.cs

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
//
// roottypes.cs: keeps a tree representation of the generated code
// module.cs: keeps a tree representation of the generated code
//
// Authors: Miguel de Icaza (miguel@gnu.org)
// Marek Safar (marek.safar@gmail.com)
@ -15,6 +15,7 @@ using System; @@ -15,6 +15,7 @@ using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Mono.CompilerServices.SymbolWriter;
using System.Linq;
#if STATIC
using IKVM.Reflection;
@ -38,7 +39,7 @@ namespace Mono.CSharp @@ -38,7 +39,7 @@ namespace Mono.CSharp
sealed class StaticDataContainer : CompilerGeneratedClass
{
readonly Dictionary<int, Struct> size_types;
new int fields;
int fields;
public StaticDataContainer (ModuleContainer module)
: base (module, new MemberName ("<PrivateImplementationDetails>" + module.builder.ModuleVersionId.ToString ("B"), Location.Null), Modifiers.STATIC)
@ -46,12 +47,12 @@ namespace Mono.CSharp @@ -46,12 +47,12 @@ namespace Mono.CSharp
size_types = new Dictionary<int, Struct> ();
}
public override void CloseType ()
public override void CloseContainer ()
{
base.CloseType ();
base.CloseContainer ();
foreach (var entry in size_types) {
entry.Value.CloseType ();
entry.Value.CloseContainer ();
}
}
@ -64,9 +65,9 @@ namespace Mono.CSharp @@ -64,9 +65,9 @@ namespace Mono.CSharp
// DefineInitializedData because it creates public type,
// and its name is not unique among modules
//
size_type = new Struct (null, this, new MemberName ("$ArrayType=" + data.Length, loc), Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED, null);
size_type.CreateType ();
size_type.DefineType ();
size_type = new Struct (this, new MemberName ("$ArrayType=" + data.Length, loc), Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED, null);
size_type.CreateContainer ();
size_type.DefineContainer ();
size_types.Add (data.Length, size_type);
@ -93,8 +94,8 @@ namespace Mono.CSharp @@ -93,8 +94,8 @@ namespace Mono.CSharp
{
if (static_data == null) {
static_data = new StaticDataContainer (this);
static_data.CreateType ();
static_data.DefineType ();
static_data.CreateContainer ();
static_data.DefineContainer ();
AddCompilerGeneratedClass (static_data);
}
@ -112,9 +113,6 @@ namespace Mono.CSharp @@ -112,9 +113,6 @@ namespace Mono.CSharp
readonly Dictionary<TypeSpec, ReferenceContainer> reference_types;
readonly Dictionary<TypeSpec, MethodSpec> attrs_cache;
// Used for unique namespaces/types during parsing
Dictionary<MemberName, ITypesContainer> defined_type_containers;
AssemblyDefinition assembly;
readonly CompilerContext context;
readonly RootNamespace global_ns;
@ -131,13 +129,13 @@ namespace Mono.CSharp @@ -131,13 +129,13 @@ namespace Mono.CSharp
static readonly string[] attribute_targets = new string[] { "assembly", "module" };
public ModuleContainer (CompilerContext context)
: base (null, null, MemberName.Null, null, 0)
: base (null, MemberName.Null, null, 0)
{
this.context = context;
caching_flags &= ~(Flags.Obsolete_Undetected | Flags.Excluded_Undetected);
types = new List<TypeContainer> ();
containers = new List<TypeContainer> ();
anonymous_types = new Dictionary<int, List<AnonymousTypeClass>> ();
global_ns = new GlobalRootNamespace ();
alias_ns = new Dictionary<string, RootNamespace> ();
@ -145,8 +143,6 @@ namespace Mono.CSharp @@ -145,8 +143,6 @@ namespace Mono.CSharp
pointer_types = new Dictionary<TypeSpec, PointerContainer> ();
reference_types = new Dictionary<TypeSpec, ReferenceContainer> ();
attrs_cache = new Dictionary<TypeSpec, MethodSpec> ();
defined_type_containers = new Dictionary<MemberName, ITypesContainer> ();
}
#region Properties
@ -184,7 +180,12 @@ namespace Mono.CSharp @@ -184,7 +180,12 @@ namespace Mono.CSharp
}
}
public override AssemblyDefinition DeclaringAssembly {
public int CounterAnonymousTypes { get; set; }
public int CounterAnonymousMethods { get; set; }
public int CounterAnonymousContainers { get; set; }
public int CounterSwitchTypes { get; set; }
public AssemblyDefinition DeclaringAssembly {
get {
return assembly;
}
@ -194,6 +195,12 @@ namespace Mono.CSharp @@ -194,6 +195,12 @@ namespace Mono.CSharp
get; set;
}
public override string DocCommentHeader {
get {
throw new NotSupportedException ();
}
}
public Evaluator Evaluator {
get; set;
}
@ -299,9 +306,9 @@ namespace Mono.CSharp @@ -299,9 +306,9 @@ namespace Mono.CSharp
attributes.AddAttribute (attr);
}
public override TypeContainer AddPartial (TypeContainer nextPart)
public override void AddTypeContainer (TypeContainer tc)
{
return AddPartial (nextPart, nextPart.MemberName.GetName (true));
containers.Add (tc);
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
@ -345,21 +352,15 @@ namespace Mono.CSharp @@ -345,21 +352,15 @@ namespace Mono.CSharp
builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
}
public override void CloseType ()
public override void CloseContainer ()
{
foreach (TypeContainer tc in types) {
tc.CloseType ();
}
if (anonymous_types != null) {
foreach (var atypes in anonymous_types)
foreach (var at in atypes.Value)
at.CloseType ();
at.CloseContainer ();
}
if (compiler_generated != null)
foreach (CompilerGeneratedClass c in compiler_generated)
c.CloseType ();
base.CloseContainer ();
}
public TypeBuilder CreateBuilder (string name, TypeAttributes attr, int typeSize)
@ -392,43 +393,25 @@ namespace Mono.CSharp @@ -392,43 +393,25 @@ namespace Mono.CSharp
builder = moduleBuilder;
}
public new void CreateType ()
public override bool Define ()
{
// Release cache used by parser only
if (Evaluator == null)
defined_type_containers = null;
else
defined_type_containers.Clear ();
DefineContainer ();
foreach (TypeContainer tc in types)
tc.CreateType ();
}
base.Define ();
public new void Define ()
{
foreach (TypeContainer tc in types) {
try {
tc.DefineType ();
} catch (Exception e) {
throw new InternalErrorException (tc, e);
}
}
HasTypesFullyDefined = true;
foreach (TypeContainer tc in types)
tc.ResolveTypeParameters ();
return true;
}
foreach (TypeContainer tc in types) {
try {
tc.Define ();
} catch (Exception e) {
throw new InternalErrorException (tc, e);
}
}
public override bool DefineContainer ()
{
DefineNamespace ();
HasTypesFullyDefined = true;
return base.DefineContainer ();
}
public override void Emit ()
public override void EmitContainer ()
{
if (OptAttributes != null)
OptAttributes.Emit ();
@ -439,32 +422,25 @@ namespace Mono.CSharp @@ -439,32 +422,25 @@ namespace Mono.CSharp
pa.EmitAttribute (builder);
}
foreach (var tc in types)
tc.DefineConstants ();
foreach (TypeContainer tc in types)
tc.EmitType ();
foreach (var tc in containers) {
tc.PrepareEmit ();
}
if (Compiler.Report.Errors > 0)
return;
base.EmitContainer ();
foreach (TypeContainer tc in types)
tc.VerifyMembers ();
if (Compiler.Report.Errors == 0)
VerifyMembers ();
if (anonymous_types != null) {
foreach (var atypes in anonymous_types)
foreach (var at in atypes.Value)
at.EmitType ();
at.EmitContainer ();
}
if (compiler_generated != null)
foreach (var c in compiler_generated)
c.EmitType ();
}
internal override void GenerateDocComment (DocumentationBuilder builder)
{
foreach (var tc in types)
foreach (var tc in containers)
tc.GenerateDocComment (builder);
}
@ -488,6 +464,12 @@ namespace Mono.CSharp @@ -488,6 +464,12 @@ namespace Mono.CSharp
return null;
}
public override void GetCompletionStartingWith (string prefix, List<string> results)
{
var names = Evaluator.GetVarNames ();
results.AddRange (names.Where (l => l.StartsWith (prefix)));
}
public RootNamespace GetRootNamespace (string name)
{
RootNamespace rn;
@ -512,62 +494,6 @@ namespace Mono.CSharp @@ -512,62 +494,6 @@ namespace Mono.CSharp
return DeclaringAssembly.IsCLSCompliant;
}
protected override bool AddMemberType (TypeContainer tc)
{
if (AddTypesContainer (tc)) {
if ((tc.ModFlags & Modifiers.PARTIAL) != 0)
defined_names.Add (tc.MemberName.GetName (true), tc);
tc.NamespaceEntry.NS.AddType (this, tc.Definition);
return true;
}
return false;
}
public bool AddTypesContainer (ITypesContainer container)
{
var mn = container.MemberName;
ITypesContainer found;
if (!defined_type_containers.TryGetValue (mn, out found)) {
defined_type_containers.Add (mn, container);
return true;
}
if (container is NamespaceContainer && found is NamespaceContainer)
return true;
var container_tc = container as TypeContainer;
var found_tc = found as TypeContainer;
if (container_tc != null && found_tc != null && container_tc.Kind == found_tc.Kind) {
if ((found_tc.ModFlags & container_tc.ModFlags & Modifiers.PARTIAL) != 0) {
return false;
}
if (((found_tc.ModFlags | container_tc.ModFlags) & Modifiers.PARTIAL) != 0) {
Report.SymbolRelatedToPreviousError (found_tc);
Error_MissingPartialModifier (container_tc);
return false;
}
}
string ns = mn.Left != null ? mn.Left.GetSignatureForError () : Module.GlobalRootNamespace.GetSignatureForError ();
mn = new MemberName (mn.Name, mn.TypeParameters, mn.Location);
Report.SymbolRelatedToPreviousError (found.Location, "");
Report.Error (101, container.Location,
"The namespace `{0}' already contains a definition for `{1}'",
ns, mn.GetSignatureForError ());
return false;
}
protected override void RemoveMemberType (TypeContainer ds)
{
defined_type_containers.Remove (ds.MemberName);
ds.NamespaceEntry.NS.RemoveDeclSpace (ds.Basename);
base.RemoveMemberType (ds);
}
public Attribute ResolveAssemblyAttribute (PredefinedAttribute a_type)
{
Attribute a = OptAttributes.Search ("assembly", a_type);
@ -583,52 +509,4 @@ namespace Mono.CSharp @@ -583,52 +509,4 @@ namespace Mono.CSharp
this.assembly = assembly;
}
}
sealed class RootDeclSpace : TypeContainer {
public RootDeclSpace (ModuleContainer module, NamespaceContainer ns)
: base (ns, null, MemberName.Null, null, 0)
{
PartialContainer = module;
}
public override AttributeTargets AttributeTargets {
get { throw new InternalErrorException ("should not be called"); }
}
public override CompilerContext Compiler {
get {
return PartialContainer.Compiler;
}
}
public override string DocCommentHeader {
get { throw new InternalErrorException ("should not be called"); }
}
public override ModuleContainer Module {
get {
return PartialContainer.Module;
}
}
public override void Accept (StructuralVisitor visitor)
{
throw new InternalErrorException ("should not be called");
}
public override bool IsClsComplianceRequired ()
{
return PartialContainer.IsClsComplianceRequired ();
}
public override ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
{
return null;
}
public override FullNamedExpression LookupNamespaceAlias (string name)
{
return NamespaceEntry.LookupNamespaceAlias (name);
}
}
}

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

@ -12,6 +12,7 @@ @@ -12,6 +12,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Mono.CompilerServices.SymbolWriter;
namespace Mono.CSharp {
@ -83,6 +84,7 @@ namespace Mono.CSharp { @@ -83,6 +84,7 @@ namespace Mono.CSharp {
string fullname;
protected Dictionary<string, Namespace> namespaces;
protected Dictionary<string, IList<TypeSpec>> types;
List<TypeSpec> extension_method_types;
Dictionary<string, TypeExpr> cached_types;
RootNamespace root;
bool cls_checked;
@ -194,7 +196,29 @@ namespace Mono.CSharp { @@ -194,7 +196,29 @@ namespace Mono.CSharp {
{
return fullname;
}
public Namespace AddNamespace (MemberName name)
{
Namespace ns_parent;
if (name.Left != null) {
if (parent != null)
ns_parent = parent.AddNamespace (name.Left);
else
ns_parent = AddNamespace (name.Left);
} else {
ns_parent = this;
}
Namespace ns;
if (!ns_parent.namespaces.TryGetValue (name.Basename, out ns)) {
ns = new Namespace (ns_parent, name.Basename);
ns_parent.namespaces.Add (name.Basename, ns);
}
return ns;
}
// TODO: Replace with CreateNamespace where MemberName is created for the method call
public Namespace GetNamespace (string name, bool create)
{
int pos = name.IndexOf ('.');
@ -381,59 +405,55 @@ namespace Mono.CSharp { @@ -381,59 +405,55 @@ namespace Mono.CSharp {
//
public List<MethodSpec> LookupExtensionMethod (IMemberContext invocationContext, TypeSpec extensionType, string name, int arity)
{
if (types == null)
if (extension_method_types == null)
return null;
List<MethodSpec> found = null;
for (int i = 0; i < extension_method_types.Count; ++i) {
var ts = extension_method_types[i];
// TODO: Add per namespace flag when at least 1 type has extension
//
// When the list was built we didn't know what members the type
// contains
//
if ((ts.Modifiers & Modifiers.METHOD_EXTENSION) == 0) {
if (extension_method_types.Count == 1) {
extension_method_types = null;
return found;
}
foreach (var tgroup in types.Values) {
foreach (var ts in tgroup) {
if ((ts.Modifiers & Modifiers.METHOD_EXTENSION) == 0)
continue;
extension_method_types.RemoveAt (i--);
continue;
}
var res = ts.MemberCache.FindExtensionMethods (invocationContext, extensionType, name, arity);
if (res == null)
continue;
var res = ts.MemberCache.FindExtensionMethods (invocationContext, extensionType, name, arity);
if (res == null)
continue;
if (found == null) {
found = res;
} else {
found.AddRange (res);
}
if (found == null) {
found = res;
} else {
found.AddRange (res);
}
}
return found;
}
//
// Extension methods look up for dotted namespace names
//
public IList<MethodSpec> LookupExtensionMethod (IMemberContext invocationContext, TypeSpec extensionType, string name, int arity, out Namespace scope)
{
//
// Inspect parent namespaces in namespace expression
//
scope = this;
do {
var candidates = scope.LookupExtensionMethod (invocationContext, extensionType, name, arity);
if (candidates != null)
return candidates;
scope = scope.Parent;
} while (scope != null);
return null;
}
public void AddType (ModuleContainer module, TypeSpec ts)
{
if (types == null) {
types = new Dictionary<string, IList<TypeSpec>> (64);
}
if (ts.IsStatic && ts.Arity == 0 &&
(ts.MemberDefinition.DeclaringAssembly == null || ts.MemberDefinition.DeclaringAssembly.HasExtensionMethod)) {
if (extension_method_types == null)
extension_method_types = new List<TypeSpec> ();
extension_method_types.Add (ts);
}
var name = ts.Name;
IList<TypeSpec> existing;
if (types.TryGetValue (name, out existing)) {
@ -499,10 +519,10 @@ namespace Mono.CSharp { @@ -499,10 +519,10 @@ namespace Mono.CSharp {
return null;
}
public void RemoveDeclSpace (string name)
public void RemoveContainer (TypeContainer tc)
{
types.Remove (name);
cached_types.Remove (name);
types.Remove (tc.Basename);
cached_types.Remove (tc.Basename);
}
public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc)
@ -578,63 +598,161 @@ namespace Mono.CSharp { @@ -578,63 +598,161 @@ namespace Mono.CSharp {
}
}
public class CompilationSourceFile : NamespaceContainer
{
readonly SourceFile file;
CompileUnitEntry comp_unit;
Dictionary<string, SourceFile> include_files;
Dictionary<string, bool> conditionals;
public CompilationSourceFile (ModuleContainer parent, SourceFile sourceFile)
: this (parent)
{
this.file = sourceFile;
}
public CompilationSourceFile (ModuleContainer parent)
: base (parent)
{
}
public CompileUnitEntry SymbolUnitEntry {
get {
return comp_unit;
}
}
public string FileName {
get {
return file.Name;
}
}
public SourceFile SourceFile {
get {
return file;
}
}
public void AddIncludeFile (SourceFile file)
{
if (file == this.file)
return;
if (include_files == null)
include_files = new Dictionary<string, SourceFile> ();
if (!include_files.ContainsKey (file.FullPathName))
include_files.Add (file.FullPathName, file);
}
public void AddDefine (string value)
{
if (conditionals == null)
conditionals = new Dictionary<string, bool> (2);
conditionals[value] = true;
}
public void AddUndefine (string value)
{
if (conditionals == null)
conditionals = new Dictionary<string, bool> (2);
conditionals[value] = false;
}
public override void PrepareEmit ()
{
// Compiler.SymbolWriter
if (SymbolWriter.symwriter != null) {
CreateUnitSymbolInfo (SymbolWriter.symwriter);
}
base.PrepareEmit ();
}
//
// Creates symbol file index in debug symbol file
//
void CreateUnitSymbolInfo (MonoSymbolWriter symwriter)
{
var si = file.CreateSymbolInfo (symwriter);
comp_unit = symwriter.DefineCompilationUnit (si);
if (include_files != null) {
foreach (SourceFile include in include_files.Values) {
si = include.CreateSymbolInfo (symwriter);
comp_unit.AddFile (si);
}
}
}
public bool IsConditionalDefined (string value)
{
if (conditionals != null) {
bool res;
if (conditionals.TryGetValue (value, out res))
return res;
// When conditional was undefined
if (conditionals.ContainsKey (value))
return false;
}
return Compiler.Settings.IsConditionalSymbolDefined (value);
}
}
//
// Namespace block as created by the parser
//
public class NamespaceContainer : IMemberContext, ITypesContainer
public class NamespaceContainer : TypeContainer, IMemberContext
{
static readonly Namespace[] empty_namespaces = new Namespace[0];
static readonly string[] empty_using_list = new string[0];
Namespace ns;
readonly ModuleContainer module;
readonly NamespaceContainer parent;
readonly CompilationSourceFile file;
readonly MemberName name;
readonly Namespace ns;
int symfile_id;
public new readonly NamespaceContainer Parent;
List<UsingNamespace> clauses;
// Used by parsed to check for parser errors
public bool DeclarationFound;
bool resolved;
public readonly TypeContainer SlaveDeclSpace;
Namespace[] namespace_using_table;
Dictionary<string, UsingAliasNamespace> aliases;
public readonly MemberName RealMemberName;
public NamespaceContainer (MemberName name, ModuleContainer module, NamespaceContainer parent, CompilationSourceFile sourceFile)
public NamespaceContainer (MemberName name, NamespaceContainer parent)
: base (parent, name, null, MemberKind.Namespace)
{
this.module = module;
this.parent = parent;
this.file = sourceFile;
this.name = name ?? MemberName.Null;
this.RealMemberName = name;
this.Parent = parent;
this.ns = parent.NS.AddNamespace (name);
if (parent != null)
ns = parent.NS.GetNamespace (name.GetName (), true);
else if (name != null)
ns = module.GlobalRootNamespace.GetNamespace (name.GetName (), true);
else
ns = module.GlobalRootNamespace;
containers = new List<TypeContainer> ();
}
SlaveDeclSpace = new RootDeclSpace (module, this);
protected NamespaceContainer (ModuleContainer parent)
: base (parent, null, null, MemberKind.Namespace)
{
ns = parent.GlobalRootNamespace;
containers = new List<TypeContainer> (2);
}
#region Properties
public Location Location {
public override AttributeTargets AttributeTargets {
get {
return name.Location;
throw new NotSupportedException ();
}
}
public MemberName MemberName {
public override string DocCommentHeader {
get {
return name;
throw new NotSupportedException ();
}
}
@ -644,21 +762,15 @@ namespace Mono.CSharp { @@ -644,21 +762,15 @@ namespace Mono.CSharp {
}
}
public NamespaceContainer Parent {
get {
return parent;
}
}
public CompilationSourceFile SourceFile {
public List<UsingNamespace> Usings {
get {
return file;
return clauses;
}
}
public List<UsingNamespace> Usings {
public override string[] ValidAttributeTargets {
get {
return clauses;
throw new NotSupportedException ();
}
}
@ -674,8 +786,6 @@ namespace Mono.CSharp { @@ -674,8 +786,6 @@ namespace Mono.CSharp {
clauses = new List<UsingNamespace> ();
clauses.Add (un);
resolved = false;
}
public void AddUsing (UsingAliasNamespace un)
@ -703,54 +813,157 @@ namespace Mono.CSharp { @@ -703,54 +813,157 @@ namespace Mono.CSharp {
}
clauses.Add (un);
}
resolved = false;
public override void AddPartial (TypeDefinition next_part)
{
var existing = ns.LookupType (this, next_part.MemberName.Name, next_part.MemberName.Arity, LookupMode.Probing, Location.Null);
var td = existing != null ? existing.Type.MemberDefinition as TypeDefinition : null;
AddPartial (next_part, td);
}
//
// Does extension methods look up to find a method which matches name and extensionType.
// Search starts from this namespace and continues hierarchically up to top level.
//
public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
public override void AddTypeContainer (TypeContainer tc)
{
List<MethodSpec> candidates = null;
foreach (Namespace n in namespace_using_table) {
var a = n.LookupExtensionMethod (this, extensionType, name, arity);
if (a == null)
continue;
string name = tc.Basename;
if (candidates == null)
candidates = a;
else
candidates.AddRange (a);
var mn = tc.MemberName;
while (mn.Left != null) {
mn = mn.Left;
name = mn.Name;
}
if (candidates != null)
return new ExtensionMethodCandidates (candidates, this);
MemberCore mc;
if (defined_names.TryGetValue (name, out mc)) {
if (tc is NamespaceContainer && mc is NamespaceContainer) {
containers.Add (tc);
return;
}
if (parent == null)
return null;
Report.SymbolRelatedToPreviousError (mc);
if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (tc is ClassOrStruct || tc is Interface)) {
Error_MissingPartialModifier (tc);
} else {
Report.Error (101, tc.Location, "The namespace `{0}' already contains a definition for `{1}'",
GetSignatureForError (), mn.GetSignatureForError ());
}
} else {
defined_names.Add (name, tc);
}
base.AddTypeContainer (tc);
var tdef = tc.PartialContainer;
if (tdef != null)
ns.AddType (Module, tdef.Definition);
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
throw new NotSupportedException ();
}
Namespace ns_scope;
var ns_candidates = ns.Parent.LookupExtensionMethod (this, extensionType, name, arity, out ns_scope);
if (ns_candidates != null)
return new ExtensionMethodCandidates (ns_candidates, this, ns_scope);
public override void EmitContainer ()
{
VerifyClsCompliance ();
base.EmitContainer ();
}
public ExtensionMethodCandidates LookupExtensionMethod (IMemberContext invocationContext, TypeSpec extensionType, string name, int arity, NamespaceContainer container, int position)
{
//
// Continue in parent container
// Here we try to resume the search for extension method at the point
// where the last bunch of candidates was found. It's more tricky than
// it seems as we have to check both namespace containers and namespace
// in correct order.
//
return parent.LookupExtensionMethod (extensionType, name, arity);
// Consider:
//
// namespace A {
// using N1;
// namespace B.C.D {
// <our first search found candidates in A.B.C.D
// }
// }
//
// In the example above namespace A.B.C.D, A.B.C and A.B have to be
// checked before we hit A.N1 using
//
ExtensionMethodCandidates candidates;
for (; container != null; container = container.Parent) {
candidates = container.LookupExtensionMethodCandidates (invocationContext, extensionType, name, arity, ref position);
if (candidates != null || container.MemberName == null)
return candidates;
var container_ns = container.ns.Parent;
var mn = container.MemberName.Left;
int already_checked = position - 2;
while (already_checked-- > 0) {
mn = mn.Left;
container_ns = container_ns.Parent;
}
while (mn != null) {
++position;
var methods = container_ns.LookupExtensionMethod (invocationContext, extensionType, name, arity);
if (methods != null) {
return new ExtensionMethodCandidates (invocationContext, methods, container, position);
}
mn = mn.Left;
container_ns = container_ns.Parent;
}
position = 0;
}
return null;
}
ExtensionMethodCandidates LookupExtensionMethodCandidates (IMemberContext invocationContext, TypeSpec extensionType, string name, int arity, ref int position)
{
List<MethodSpec> candidates = null;
if (position == 0) {
++position;
candidates = ns.LookupExtensionMethod (invocationContext, extensionType, name, arity);
if (candidates != null) {
return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
}
}
if (position == 1) {
++position;
foreach (Namespace n in namespace_using_table) {
var a = n.LookupExtensionMethod (invocationContext, extensionType, name, arity);
if (a == null)
continue;
if (candidates == null)
candidates = a;
else
candidates.AddRange (a);
}
if (candidates != null)
return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
}
return null;
}
public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
{
//
// Only simple names (no dots) will be looked up with this function
//
FullNamedExpression resolved;
for (NamespaceContainer container = this; container != null; container = container.parent) {
for (NamespaceContainer container = this; container != null; container = container.Parent) {
resolved = container.Lookup (name, arity, mode, loc);
if (resolved != null)
if (resolved != null || container.MemberName == null)
return resolved;
var container_ns = container.ns.Parent;
@ -768,25 +981,35 @@ namespace Mono.CSharp { @@ -768,25 +981,35 @@ namespace Mono.CSharp {
return null;
}
public IList<string> CompletionGetTypesStartingWith (string prefix)
public override void GetCompletionStartingWith (string prefix, List<string> results)
{
foreach (var un in Usings) {
if (un.Alias != null)
continue;
var name = un.NamespaceExpression.Name;
if (name.StartsWith (prefix))
results.Add (name);
}
IEnumerable<string> all = Enumerable.Empty<string> ();
for (NamespaceContainer curr_ns = this; curr_ns != null; curr_ns = curr_ns.parent){
foreach (Namespace using_ns in namespace_using_table){
if (prefix.StartsWith (using_ns.Name)){
int ld = prefix.LastIndexOf ('.');
if (ld != -1){
string rest = prefix.Substring (ld+1);
all = all.Concat (using_ns.CompletionGetTypesStartingWith (rest));
}
foreach (Namespace using_ns in namespace_using_table) {
if (prefix.StartsWith (using_ns.Name)) {
int ld = prefix.LastIndexOf ('.');
if (ld != -1) {
string rest = prefix.Substring (ld + 1);
all = all.Concat (using_ns.CompletionGetTypesStartingWith (rest));
}
all = all.Concat (using_ns.CompletionGetTypesStartingWith (prefix));
}
all = all.Concat (using_ns.CompletionGetTypesStartingWith (prefix));
}
return all.Distinct ().ToList ();
results.AddRange (all);
base.GetCompletionStartingWith (prefix, results);
}
@ -808,9 +1031,9 @@ namespace Mono.CSharp { @@ -808,9 +1031,9 @@ namespace Mono.CSharp {
//
// Looks-up a alias named @name in this and surrounding namespace declarations
//
public FullNamedExpression LookupNamespaceAlias (string name)
public override FullNamedExpression LookupNamespaceAlias (string name)
{
for (NamespaceContainer n = this; n != null; n = n.parent) {
for (NamespaceContainer n = this; n != null; n = n.Parent) {
if (n.aliases == null)
continue;
@ -851,6 +1074,13 @@ namespace Mono.CSharp { @@ -851,6 +1074,13 @@ namespace Mono.CSharp {
if (fne != null)
return fne;
//
// Lookup can be called before the namespace is defined from different namespace using alias clause
//
if (namespace_using_table == null) {
DoDefineNamespace ();
}
//
// Check using entries.
//
@ -880,7 +1110,7 @@ namespace Mono.CSharp { @@ -880,7 +1110,7 @@ namespace Mono.CSharp {
}
// It can be top level accessibility only
var better = Namespace.IsImportedTypeOverride (module, texpr_match.Type, texpr_fne.Type);
var better = Namespace.IsImportedTypeOverride (Module, texpr_match.Type, texpr_fne.Type);
if (better == null) {
if (mode == LookupMode.Normal) {
Compiler.Report.SymbolRelatedToPreviousError (texpr_match.Type);
@ -899,28 +1129,6 @@ namespace Mono.CSharp { @@ -899,28 +1129,6 @@ namespace Mono.CSharp {
return match;
}
public int SymbolFileID {
get {
if (symfile_id == 0 && file.SourceFileEntry != null) {
int parent_id = parent == null ? 0 : parent.SymbolFileID;
string [] using_list = empty_using_list;
if (clauses != null) {
// TODO: Why is it needed, what to do with aliases
var ul = new List<string> ();
foreach (var c in clauses) {
ul.Add (c.ResolvedExpression.GetSignatureForError ());
}
using_list = ul.ToArray ();
}
symfile_id = SymbolWriter.DefineNamespace (ns.Name, file.CompileUnitEntry, using_list, parent_id);
}
return symfile_id;
}
}
static void MsgtryRef (string s)
{
Console.WriteLine (" Try using -r:" + s);
@ -959,17 +1167,17 @@ namespace Mono.CSharp { @@ -959,17 +1167,17 @@ namespace Mono.CSharp {
}
}
public void Define ()
protected override void DefineNamespace ()
{
if (resolved)
return;
if (namespace_using_table == null)
DoDefineNamespace ();
// FIXME: Because we call Define from bottom not top
if (parent != null)
parent.Define ();
base.DefineNamespace ();
}
void DoDefineNamespace ()
{
namespace_using_table = empty_namespaces;
resolved = true;
if (clauses != null) {
var list = new List<Namespace> (clauses.Count);
@ -1031,46 +1239,48 @@ namespace Mono.CSharp { @@ -1031,46 +1239,48 @@ namespace Mono.CSharp {
}
}
public string GetSignatureForError ()
public void EnableUsingClausesRedefinition ()
{
return ns.GetSignatureForError ();
}
#region IMemberContext Members
CompilerContext Compiler {
get { return module.Compiler; }
namespace_using_table = null;
}
public TypeSpec CurrentType {
get { return SlaveDeclSpace.CurrentType; }
internal override void GenerateDocComment (DocumentationBuilder builder)
{
if (containers != null) {
foreach (var tc in containers)
tc.GenerateDocComment (builder);
}
}
public MemberCore CurrentMemberDefinition {
get { return SlaveDeclSpace.CurrentMemberDefinition; }
public override string GetSignatureForError ()
{
return MemberName == null ? "global::" : base.GetSignatureForError ();
}
public TypeParameters CurrentTypeParameters {
get { return SlaveDeclSpace.CurrentTypeParameters; }
public override void RemoveContainer (TypeContainer cont)
{
base.RemoveContainer (cont);
NS.RemoveContainer (cont);
}
public bool IsObsolete {
get { return false; }
}
protected override bool VerifyClsCompliance ()
{
if (Module.IsClsComplianceRequired ()) {
if (MemberName != null && MemberName.Name[0] == '_') {
Warning_IdentifierNotCompliant ();
}
public bool IsUnsafe {
get { return SlaveDeclSpace.IsUnsafe; }
}
ns.VerifyClsCompliance ();
return true;
}
public bool IsStatic {
get { return SlaveDeclSpace.IsStatic; }
return false;
}
public ModuleContainer Module {
get { return module; }
public override void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
#endregion
}
public class UsingNamespace
@ -1131,6 +1341,11 @@ namespace Mono.CSharp { @@ -1131,6 +1341,11 @@ namespace Mono.CSharp {
}
}
}
public virtual void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
}
public class UsingExternAlias : UsingAliasNamespace
@ -1149,13 +1364,18 @@ namespace Mono.CSharp { @@ -1149,13 +1364,18 @@ namespace Mono.CSharp {
Alias.Value);
}
}
public override void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
}
public class UsingAliasNamespace : UsingNamespace
{
readonly SimpleMemberName alias;
struct AliasContext : IMemberContext
public struct AliasContext : IMemberContext
{
readonly NamespaceContainer ns;
@ -1226,7 +1446,7 @@ namespace Mono.CSharp { @@ -1226,7 +1446,7 @@ namespace Mono.CSharp {
// Only extern aliases are allowed in this context
//
fne = ns.LookupExternAlias (name);
if (fne != null)
if (fne != null || ns.MemberName == null)
return fne;
var container_ns = ns.NS.Parent;
@ -1278,5 +1498,10 @@ namespace Mono.CSharp { @@ -1278,5 +1498,10 @@ namespace Mono.CSharp {
//
resolved = NamespaceExpression.ResolveAsTypeOrNamespace (new AliasContext (ctx));
}
public override void Accept (StructuralVisitor visitor)
{
visitor.Visit (this);
}
}
}

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

@ -129,7 +129,7 @@ namespace Mono.CSharp { @@ -129,7 +129,7 @@ namespace Mono.CSharp {
/// <summary>
/// The container for this PendingImplementation
/// </summary>
readonly TypeContainer container;
readonly TypeDefinition container;
/// <summary>
/// This is the array of TypeAndMethods that describes the pending implementations
@ -137,7 +137,7 @@ namespace Mono.CSharp { @@ -137,7 +137,7 @@ namespace Mono.CSharp {
/// </summary>
TypeAndMethods [] pending_implementations;
PendingImplementation (TypeContainer container, MissingInterfacesInfo[] missing_ifaces, MethodSpec[] abstract_methods, int total)
PendingImplementation (TypeDefinition container, MissingInterfacesInfo[] missing_ifaces, MethodSpec[] abstract_methods, int total)
{
var type_builder = container.Definition;
@ -189,7 +189,7 @@ namespace Mono.CSharp { @@ -189,7 +189,7 @@ namespace Mono.CSharp {
static readonly MissingInterfacesInfo [] EmptyMissingInterfacesInfo = new MissingInterfacesInfo [0];
static MissingInterfacesInfo [] GetMissingInterfaces (TypeContainer container)
static MissingInterfacesInfo [] GetMissingInterfaces (TypeDefinition container)
{
//
// Notice that Interfaces will only return the interfaces that the Type
@ -233,7 +233,7 @@ namespace Mono.CSharp { @@ -233,7 +233,7 @@ namespace Mono.CSharp {
// Register method implementations are either abstract methods
// flagged as such on the base class or interface methods
//
static public PendingImplementation GetPendingImplementations (TypeContainer container)
static public PendingImplementation GetPendingImplementations (TypeDefinition container)
{
TypeSpec b = container.BaseType;

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

@ -34,7 +34,7 @@ namespace Mono.CSharp @@ -34,7 +34,7 @@ namespace Mono.CSharp
// This includes properties, indexers, and events
public abstract class PropertyBasedMember : InterfaceMemberBase
{
public PropertyBasedMember (TypeContainer parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
public PropertyBasedMember (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
: base (parent, type, mod, allowed_mod, name, attrs)
{
}
@ -335,7 +335,7 @@ namespace Mono.CSharp @@ -335,7 +335,7 @@ namespace Mono.CSharp
public virtual MethodBuilder Define (TypeContainer parent)
{
TypeContainer container = parent.PartialContainer;
var container = parent.PartialContainer;
//
// Check for custom access modifier
@ -402,7 +402,7 @@ namespace Mono.CSharp @@ -402,7 +402,7 @@ namespace Mono.CSharp
PropertyMethod get, set, first;
PropertyBuilder PropertyBuilder;
public PropertyBase (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, Modifiers allowed_mod, MemberName name, Attributes attrs)
public PropertyBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, Modifiers allowed_mod, MemberName name, Attributes attrs)
: base (parent, type, mod_flags, allowed_mod, name, attrs)
{
}
@ -445,7 +445,7 @@ namespace Mono.CSharp @@ -445,7 +445,7 @@ namespace Mono.CSharp
if (first == null)
first = value;
Parent.AddMember (get);
Parent.AddNameToContainer (get, get.MemberName.Basename);
}
}
@ -458,7 +458,7 @@ namespace Mono.CSharp @@ -458,7 +458,7 @@ namespace Mono.CSharp
if (first == null)
first = value;
Parent.AddMember (set);
Parent.AddNameToContainer (set, set.MemberName.Basename);
}
}
@ -720,7 +720,7 @@ namespace Mono.CSharp @@ -720,7 +720,7 @@ namespace Mono.CSharp
}
}
public Property (TypeContainer parent, FullNamedExpression type, Modifiers mod,
public Property (TypeDefinition parent, FullNamedExpression type, Modifiers mod,
MemberName name, Attributes attrs)
: base (parent, type, mod,
parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
@ -743,21 +743,25 @@ namespace Mono.CSharp @@ -743,21 +743,25 @@ namespace Mono.CSharp
if (!field.Define ())
return;
Parent.PartialContainer.AddField (field);
Parent.PartialContainer.Members.Add (field);
FieldExpr fe = new FieldExpr (field, Location);
if ((field.ModFlags & Modifiers.STATIC) == 0)
fe.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
// Create get block
Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
Return r = new Return (fe, Location);
//
// Create get block but we careful with location to
// emit only single sequence point per accessor. This allow
// to set a breakpoint on it even with no user code
//
Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
Return r = new Return (fe, Get.Location);
Get.Block.AddStatement (r);
// Create set block
Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location);
Assign a = new SimpleAssign (fe, new SimpleName ("value", Location));
Set.Block.AddStatement (new StatementExpression (a));
Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
Set.Block.AddStatement (new StatementExpression (a, Set.Location));
}
public override bool Define ()
@ -787,7 +791,7 @@ namespace Mono.CSharp @@ -787,7 +791,7 @@ namespace Mono.CSharp
else
pm = new GetMethod (this, 0, null, Location);
Parent.AddMember (pm);
Parent.AddNameToContainer (pm, pm.MemberName.Basename);
}
if (!CheckBase ())
@ -850,7 +854,7 @@ namespace Mono.CSharp @@ -850,7 +854,7 @@ namespace Mono.CSharp
static readonly string[] attribute_targets = new string [] { "event" };
public EventProperty (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
: base (parent, type, mod_flags, name, attrs)
{
}
@ -890,10 +894,12 @@ namespace Mono.CSharp @@ -890,10 +894,12 @@ namespace Mono.CSharp
protected abstract MethodSpec GetOperation (Location loc);
public override void Emit (TypeContainer parent)
public override void Emit (TypeDefinition parent)
{
if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0) {
block = new ToplevelBlock (Compiler, ParameterInfo, Location);
block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
IsCompilerGenerated = true
};
FabricateBodyStatement ();
}
@ -989,7 +995,7 @@ namespace Mono.CSharp @@ -989,7 +995,7 @@ namespace Mono.CSharp
Field backing_field;
List<FieldDeclarator> declarators;
public EventField (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
: base (parent, type, mod_flags, name, attrs)
{
Add = new AddDelegateMethod (this);
@ -1040,8 +1046,7 @@ namespace Mono.CSharp @@ -1040,8 +1046,7 @@ namespace Mono.CSharp
declarators.Add (declarator);
// TODO: This will probably break
Parent.AddMember (this, declarator.Name.Value);
Parent.AddNameToContainer (this, declarator.Name.Value);
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
@ -1074,14 +1079,14 @@ namespace Mono.CSharp @@ -1074,14 +1079,14 @@ namespace Mono.CSharp
mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFER);
var t = new TypeExpression (MemberType, TypeExpression.Location);
int index = Parent.PartialContainer.Events.IndexOf (this);
foreach (var d in declarators) {
var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
if (d.Initializer != null)
ef.initializer = d.Initializer;
Parent.PartialContainer.Events.Insert (++index, ef);
ef.Define ();
Parent.PartialContainer.Members.Add (ef);
}
}
@ -1098,7 +1103,7 @@ namespace Mono.CSharp @@ -1098,7 +1103,7 @@ namespace Mono.CSharp
Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
MemberName, null);
Parent.PartialContainer.AddField (backing_field);
Parent.PartialContainer.Members.Add (backing_field);
backing_field.Initializer = Initializer;
backing_field.ModFlags &= ~Modifiers.COMPILER_GENERATED;
@ -1215,7 +1220,7 @@ namespace Mono.CSharp @@ -1215,7 +1220,7 @@ namespace Mono.CSharp
EventBuilder EventBuilder;
protected EventSpec spec;
protected Event (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
: base (parent, type, mod_flags,
parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
@ -1238,7 +1243,7 @@ namespace Mono.CSharp @@ -1238,7 +1243,7 @@ namespace Mono.CSharp
}
set {
add = value;
Parent.AddMember (value);
Parent.AddNameToContainer (value, value.MemberName.Basename);
}
}
@ -1254,7 +1259,7 @@ namespace Mono.CSharp @@ -1254,7 +1259,7 @@ namespace Mono.CSharp
}
set {
remove = value;
Parent.AddMember (value);
Parent.AddNameToContainer (value, value.MemberName.Basename);
}
}
#endregion
@ -1488,7 +1493,7 @@ namespace Mono.CSharp @@ -1488,7 +1493,7 @@ namespace Mono.CSharp
readonly ParametersCompiled parameters;
public Indexer (TypeContainer parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
: base (parent, type, mod,
parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
name, attrs)
@ -1572,8 +1577,7 @@ namespace Mono.CSharp @@ -1572,8 +1577,7 @@ namespace Mono.CSharp
}
}
if (!Parent.PartialContainer.AddMember (this))
return false;
Parent.AddNameToContainer (this, MemberName.Basename);
flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;

168
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/repl.txt

@ -1,168 +0,0 @@ @@ -1,168 +0,0 @@
Things to do for the REPL support in MCS:
Documentation for the REPL mode for MCS can be found here:
http://mono-project.com/CsharpRepl
* Embedding API
* Booting the compiler without Main ()
* Expose LoadAssembly/LoadPackage
* Register fields?
* Register a lookup function for fields?
* Register classes to expose to REPL
* Embedded Library
* Run a REPL on a socket (from Joe Shaw)
* Host a REPL on XSP (from Nat).
* TODO
Clear struct fields inside the clearing code.
* Other ideas:
MD addin for "csharp"
* Supporting class-level declarations
Currently the evaluator has this feature disabled, to enable
it edit the eval.cs file and make this be the default:
- parser.Lexer.putback_char = Tokenizer.EvalUsingDeclarationsParserCharacter;
- //parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
+ //parser.Lexer.putback_char = Tokenizer.EvalUsingDeclarationsParserCharacter;
+ parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
It currently has a few problems:
* Support for overwritting existing defined
classes is not supported.
* The usability is not as useful, since the defaults
for C# are still to make members private, we should
change this default to be public in those cases.
* The error lookup system lacks information from types, for
example this causes an unsupported call into a TypeBuilder:
csharp>class D { void DD () {} }
csharp>var d = new D ();
csharp>d.DD ();
Internal compiler error at Internal(1,1):: exception caught while emitting MethodBuilder [Class0::Host]
System.NotSupportedException: The invoked member is not supported in a dynamic module.
at System.Reflection.Emit.AssemblyBuilder.get_Location () [0x00000] in <filename unknown>:0
at Mono.CSharp.Report.SymbolRelatedToPreviousError (System.Reflection.MemberInfo mi) [0x00000] in
at Mono.CSharp.MethodGroupExpr.NoExactMatch (Mono.CSharp.ResolveContext ec,
Mono.CSharp.Arguments& Arguments, IDictionary`2 c
The above is caused by TypeManager.LookupDeclSpace (dt)
failing to return a value (it returns null) so our code
assumes we have an Assembly instead of an assemblybuilder.
* Declaring a class twice produces an internal parse error:
class X {}
class X {}
The second declaration will no longer be parsed, so it could even
contain junk, and wont be flagged. We probably need to allow for
type redefinition in REPL modes, the exception from the second is:
csharp -v -v
> class X {}
> class X {}
System.ArgumentException: An element with the same key already exists in the dictionary.
at System.Collections.Generic.Dictionary`2[System.String,Mono.CSharp.DeclSpace].Add (System.String key, Mono.CSharp.DeclSpace value) [0x00000] in <filename unknown>:0
at Mono.CSharp.Namespace.AddDeclSpace (System.String name, Mono.CSharp.DeclSpace ds) [0x00000] in <filename unknown>:0
at Mono.CSharp.ModuleCompiled.AddMemberType (Mono.CSharp.DeclSpace ds) [0x00000] in <filename unknown>:0
at Mono.CSharp.TypeContainer.AddTypeContainer (Mono.CSharp.TypeContainer tc) [0x00000] in <filename unknown>:0
at Mono.CSharp.CSharpParser.push_current_class (Mono.CSharp.TypeContainer tc, System.Object partial_token) [0x00000] in <filename unknown>:0
at Mono.CSharp.CSharpParser.yyparse (yyInput yyLex) [0x00000] in <filename unknown>:0
at Mono.CSharp.CSharpParser.yyparse (yyInput yyLex, System.Object yyd) [0x00000] in <filename unknown>:0
at Mono.CSharp.CSharpParser.parse () [0x00000] in <filename unknown>:0
* Mix statements with other top-level declarations.
csharp> class Y {static void Main () {Console.WriteLine ("Foo"); }}
csharp> typeof (Y);
Y
csharp> Y.Main ();
Exception caught by the compiler while compiling:
Block that caused the problem begin at: Internal(1,1):
Block being compiled: [<interactive>(1,2):,<interactive>(1,11):]
System.NotSupportedException: The invoked member is not supported in a dynamic module.
Internal compiler error at Internal(1,1):: exception caught while emitting MethodBuilder [Class2::Host]
System.NotSupportedException: The invoked member is not supported in a dynamic module.
at System.Reflection.Emit.AssemblyBuilder.get_Location () [0x00000] in /second/home/cvs/mcs/class/corlib/System.Reflection.Emit/AssemblyBuilder.cs:214
at Mono.CSharp.Report.SymbolRelatedToPreviousError (System.Reflection.MemberInfo mi) [0x00036] in /second/home/cvs/mcs/mcs/report.cs:664
at Mono.CSharp.Expression.Error_MemberLookupFailed (System.Type container_type, System.Type qualifier_type, System.Type queried_type, System.String name, System.String class_name, MemberTypes mt, BindingFlags bf) [0x00121] in /second/home/cvs/mcs/mcs/ecore.cs:857
at Mono.CSharp.MemberAccess.DoResolve (Mono.CSharp.EmitContext ec, Mono.CSharp.Expression right_side) [0x00230] in /second/home/cvs/mcs/mcs/expression.cs:7426
at Mono.CSharp.MemberAccess.DoResolve (Mono.CSharp.EmitContext ec) [0x00000] in /second/home/cvs/mcs/mcs/expression.cs:7494
at Mono.CSharp.Expression.Resolve (Mono.CSharp.EmitContext ec, ResolveFlags flags) [0x00075] in /second/home/cvs/mcs/mcs/ecore.cs:479
at Mono.CSharp.Invocation.DoResolve (Mono.CSharp.EmitContext ec) [0x0000d] in /second/home/cvs/mcs/mcs/expression.cs:4725
at Mono.CSharp.Expression.Resolve (Mono.CSharp.EmitContext ec, ResolveFlags flags) [0x00075] in /second/home/cvs/mcs/mcs/ecore.cs:479
at Mono.CSharp.Expression.Resolve (Mono.CSharp.EmitContext ec) [0x00000] in /second/home/cvs/mcs/mcs/ecore.cs:506
at Mono.CSharp.OptionalAssign.DoResolve (Mono.CSharp.EmitContext ec) [0x00013] in /second/home/cvs/mcs/mcs/repl.cs:681
at Mono.CSharp.Expression.Resolve (Mono.CSharp.EmitContext ec, ResolveFlags flags) [0x00075] in /second/home/cvs/mcs/mcs/ecore.cs:479
at Mono.CSharp.Expression.Resolve (Mono.CSharp.EmitContext ec) [0x00000] in /second/home/cvs/mcs/mcs/ecore.cs:506
at Mono.CSharp.ExpressionStatement.ResolveStatement (Mono.CSharp.EmitContext ec) [0x00000] in /second/home/cvs/mcs/mcs/ecore.cs:1307
at Mono.CSharp.StatementExpression.Resolve (Mono.CSharp.EmitContext ec) [0x0000b] in /second/home/cvs/mcs/mcs/statement.cs:743
at Mono.CSharp.Block.Resolve (Mono.CSharp.EmitContext ec) [0x000f0] in /second/home/cvs/mcs/mcs/statement.cs:2254
at Mono.CSharp.ExplicitBlock.Resolve (Mono.CSharp.EmitContext ec) [0x00000] in /second/home/cvs/mcs/mcs/statement.cs:2550
at Mono.CSharp.EmitContext.ResolveTopBlock (Mono.CSharp.EmitContext anonymous_method_host, Mono.CSharp.ToplevelBlock block, Mono.CSharp.Parameters ip, IMethodData md, System.Boolean& unreachable) [0x00087] in /second/home/cvs/mcs/mcs/codegen.cs:796
csharp>
* Another one:
csharp> class X { X (){ Console.WriteLine ("Called"); } }
csharp> new X ();
Exception caught by the compiler while compiling:
Block that caused the problem begin at: Internal(1,1):
Block being compiled: [<interactive>(1,2):,<interactive>(1,10):]
System.NotSupportedException: The invoked member is not supported in a dynamic module.
Internal compiler error at Internal(1,1):: exception caught while emitting MethodBuilder [Class0::Host]
System.NotSupportedException: The invoked member is not supported in a dynamic module.
at System.Reflection.Emit.AssemblyBuilder.get_Location () [0x00000] in /second/home/cvs/mcs/class/corlib/System.Reflection.Emit/AssemblyBuilder.cs:214
at Mono.CSharp.Report.SymbolRelatedToPreviousError (System.Reflection.MemberInfo mi) [0x00036] in /second/home/cvs/mcs/mcs/report.cs:664
at Mono.CSharp.Expression.Error_MemberLookupFailed (System.Type container_type, System.Type qualifier_type, System.Type queried_type, System.String name, System.String class_name, MemberTypes mt, BindingFlags bf) [0x00121] in /second/home/cvs/mcs/mcs/ecore.cs:857
at Mono.CSharp.Expression.MemberLookupFinal (Mono.CSharp.EmitContext ec, System.Type qualifier_type, System.Type queried_type, System.String name, MemberTypes mt, BindingFlags bf, Location loc) [0x0002f] in /second/home/cvs/mcs/mcs/ecore.cs:804
at Mono.CSharp.New.DoResolve (Mono.CSharp.EmitContext ec) [0x002ad] in /second/home/cvs/mcs/mcs/expression.cs:5486
at Mono.CSharp.Expression.Resolve (Mono.CSharp.EmitContext ec, ResolveFlags flags) [0x00075] in /second/home/cvs/mcs/mcs/ecore.cs:479
at Mono.CSharp.Expression.Resolve (Mono.CSharp.EmitContext ec) [0x00000] in /second/home/cvs/mcs/mcs/ecore.cs:506
at Mono.CSharp.OptionalAssign.DoResolve (Mono.CSharp.EmitContext ec) [0x00013] in /second/home/cvs/mcs/mcs/repl.cs:687
at Mono.CSharp.Expression.Resolve (Mono.CSharp.EmitContext ec, ResolveFlags flags) [0x00075] in /second/home/cvs/mcs/mcs/ecore.cs:479
at Mono.CSharp.Expression.Resolve (Mono.CSharp.EmitContext ec) [0x00000] in /second/home/cvs/mcs/mcs/ecore.cs:506
at Mono.CSharp.ExpressionStatement.ResolveStatement (Mono.CSharp.EmitContext ec) [0x00000] in /second/home/cvs/mcs/mcs/ecore.cs:1307
at Mono.CSharp.StatementExpression.Resolve (Mono.CSharp.EmitContext ec) [0x0000b] in /second/home/cvs/mcs/mcs/statement.cs:743
at Mono.CSharp.Block.Resolve (Mono.CSharp.EmitContext ec) [0x000f0] in /second/home/cvs/mcs/mcs/statement.cs:2254
at Mono.CSharp.ExplicitBlock.Resolve (Mono.CSharp.EmitContext ec) [0x00000] in /second/home/cvs/mcs/mcs/statement.cs:2550
at Mono.CSharp.EmitContext.ResolveTopBlock (Mono.CSharp.EmitContext anonymous_method_host, Mono.CSharp.ToplevelBlock block, Mono.CSharp.Parameters ip, IMethodData md, System.Boolean& unreachable) [0x00087] in /second/home/cvs/mcs/mcs/codegen.cs:796
csharp>
* Important: we need to replace TypeBuidlers with Types after things
have been emitted, or stuff like this happens:
csharp> public class y {}
csharp> typeof (y);
Class1
* Clearing data
TODO: when clearing data for variables that have been overwritten
we need to check for structs and clear all the fields that contain
reference types.
* DEBATABLE: Implement auto-insert-semicolon
This is easy to implement, just retry the parse with a
semicolon, the question is whether this is a good idea to do
in the first place or not.

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

@ -21,27 +21,15 @@ namespace Mono.CSharp { @@ -21,27 +21,15 @@ namespace Mono.CSharp {
//
public class Report
{
/// <summary>
/// Whether warnings should be considered errors
/// </summary>
public bool WarningsAreErrors;
List<int> warnings_as_error;
List<int> warnings_only;
public const int RuntimeErrorId = 10000;
//
// Keeps track of the warnings that we are ignoring
//
HashSet<int> warning_ignore_table;
Dictionary<int, WarningRegions> warning_regions_table;
int warning_level;
ReportPrinter printer;
int reporting_disabled;
readonly CompilerSettings settings;
/// <summary>
/// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
@ -72,13 +60,15 @@ namespace Mono.CSharp { @@ -72,13 +60,15 @@ namespace Mono.CSharp {
static HashSet<int> AllWarningsHashSet;
public Report (ReportPrinter printer)
public Report (CompilerContext context, ReportPrinter printer)
{
if (context == null)
throw new ArgumentNullException ("settings");
if (printer == null)
throw new ArgumentNullException ("printer");
this.settings = context.Settings;
this.printer = printer;
warning_level = 4;
}
public void DisableReporting ()
@ -125,44 +115,6 @@ namespace Mono.CSharp { @@ -125,44 +115,6 @@ namespace Mono.CSharp {
"Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
feature);
}
bool IsWarningEnabled (int code, int level, Location loc)
{
if (WarningLevel < level)
return false;
if (IsWarningDisabledGlobally (code))
return false;
if (warning_regions_table == null || loc.IsNull)
return true;
WarningRegions regions;
if (!warning_regions_table.TryGetValue (loc.File, out regions))
return true;
return regions.IsWarningEnabled (code, loc.Row);
}
public bool IsWarningDisabledGlobally (int code)
{
return warning_ignore_table != null && warning_ignore_table.Contains (code);
}
bool IsWarningAsError (int code)
{
bool is_error = WarningsAreErrors;
// Check specific list
if (warnings_as_error != null)
is_error |= warnings_as_error.Contains (code);
// Ignore excluded warnings
if (warnings_only != null && warnings_only.Contains (code))
is_error = false;
return is_error;
}
public void RuntimeMissingSupport (Location loc, string feature)
{
@ -217,44 +169,6 @@ namespace Mono.CSharp { @@ -217,44 +169,6 @@ namespace Mono.CSharp {
extra_information.Add (msg);
}
public void AddWarningAsError (string warningId)
{
int id;
try {
id = int.Parse (warningId);
} catch {
CheckWarningCode (warningId, Location.Null);
return;
}
if (!CheckWarningCode (id, Location.Null))
return;
if (warnings_as_error == null)
warnings_as_error = new List<int> ();
warnings_as_error.Add (id);
}
public void RemoveWarningAsError (string warningId)
{
int id;
try {
id = int.Parse (warningId);
} catch {
CheckWarningCode (warningId, Location.Null);
return;
}
if (!CheckWarningCode (id, Location.Null))
return;
if (warnings_only == null)
warnings_only = new List<int> ();
warnings_only.Add (id);
}
public bool CheckWarningCode (string code, Location loc)
{
Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
@ -300,11 +214,17 @@ namespace Mono.CSharp { @@ -300,11 +214,17 @@ namespace Mono.CSharp {
if (reporting_disabled > 0)
return;
if (!IsWarningEnabled (code, level, loc))
if (!settings.IsWarningEnabled (code, level))
return;
if (warning_regions_table != null && !loc.IsNull) {
WarningRegions regions;
if (warning_regions_table.TryGetValue (loc.File, out regions) && !regions.IsWarningEnabled (code, loc.Row))
return;
}
AbstractMessage msg;
if (IsWarningAsError (code)) {
if (settings.IsWarningAsError (code)) {
message = "Warning as Error: " + message;
msg = new ErrorMessage (code, loc, message, extra_information);
} else {
@ -420,14 +340,6 @@ namespace Mono.CSharp { @@ -420,14 +340,6 @@ namespace Mono.CSharp {
get { return printer; }
}
public void SetIgnoreWarning (int code)
{
if (warning_ignore_table == null)
warning_ignore_table = new HashSet<int> ();
warning_ignore_table.Add (code);
}
public ReportPrinter SetPrinter (ReportPrinter printer)
{
ReportPrinter old = this.printer;
@ -435,15 +347,6 @@ namespace Mono.CSharp { @@ -435,15 +347,6 @@ namespace Mono.CSharp {
return old;
}
public int WarningLevel {
get {
return warning_level;
}
set {
warning_level = value;
}
}
[Conditional ("MCS_DEBUG")]
static public void Debug (string message, params object[] args)
{
@ -999,7 +902,6 @@ namespace Mono.CSharp { @@ -999,7 +902,6 @@ namespace Mono.CSharp {
ReferencesImporting,
PredefinedTypesInit,
ModuleDefinitionTotal,
UsingResolve,
EmitTotal,
CloseTypes,
Resouces,
@ -1058,7 +960,6 @@ namespace Mono.CSharp { @@ -1058,7 +960,6 @@ namespace Mono.CSharp {
{ TimerType.ReferencesImporting, "Referenced assemblies importing" },
{ TimerType.PredefinedTypesInit, "Predefined types initialization" },
{ TimerType.ModuleDefinitionTotal, "Module definition" },
{ TimerType.UsingResolve, "Top-level usings resolve" },
{ TimerType.EmitTotal, "Resolving and emitting members blocks" },
{ TimerType.CloseTypes, "Module types closed" },
{ TimerType.Resouces, "Embedding resources" },
@ -1202,13 +1103,13 @@ namespace Mono.CSharp { @@ -1202,13 +1103,13 @@ namespace Mono.CSharp {
regions.Add (new EnableAll (line));
}
public void WarningEnable (Location location, int code, Report Report)
public void WarningEnable (Location location, int code, CompilerContext context)
{
if (!Report.CheckWarningCode (code, location))
if (!context.Report.CheckWarningCode (code, location))
return;
if (Report.IsWarningDisabledGlobally (code))
Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
if (context.Settings.IsWarningDisabledGlobally (code))
context.Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
regions.Add (new Enable (location.Row, code));
}

170
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/rootcontext.cs → src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/settings.cs

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
//
// rootcontext.cs: keeps track of our tree representation, and assemblies loaded.
// settings.cs: All compiler settings
//
// Author: Miguel de Icaza (miguel@ximian.com)
// Ravi Pratap (ravi@ximian.com)
@ -66,6 +66,11 @@ namespace Mono.CSharp { @@ -66,6 +66,11 @@ namespace Mono.CSharp {
public string StrongNameKeyContainer;
public bool StrongNameDelaySign;
public int TabSize;
public bool WarningsAreErrors;
public int WarningLevel;
//
// Assemblies references to be loaded
//
@ -133,6 +138,7 @@ namespace Mono.CSharp { @@ -133,6 +138,7 @@ namespace Mono.CSharp {
// Compiler debug flags only
public bool ParseOnly, TokenizeOnly, Timestamps;
public int DebugFlags;
public int VerboseParserFlag;
//
// Whether we are being linked against the standard libraries.
@ -145,7 +151,11 @@ namespace Mono.CSharp { @@ -145,7 +151,11 @@ namespace Mono.CSharp {
readonly List<string> conditional_symbols;
readonly List<CompilationSourceFile> source_files;
readonly List<SourceFile> source_files;
List<int> warnings_as_error;
List<int> warnings_only;
HashSet<int> warning_ignore_table;
public CompilerSettings ()
{
@ -155,10 +165,15 @@ namespace Mono.CSharp { @@ -155,10 +165,15 @@ namespace Mono.CSharp {
Platform = Platform.AnyCPU;
Version = LanguageVersion.Default;
VerifyClsCompliance = true;
Optimize = true;
Encoding = Encoding.UTF8;
LoadDefaultReferences = true;
StdLibRuntimeVersion = RuntimeVersion.v4;
WarningLevel = 4;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
TabSize = 4;
else
TabSize = 8;
AssemblyReferences = new List<string> ();
AssemblyReferencesAliases = new List<Tuple<string, string>> ();
@ -171,12 +186,12 @@ namespace Mono.CSharp { @@ -171,12 +186,12 @@ namespace Mono.CSharp {
//
conditional_symbols.Add ("__MonoCS__");
source_files = new List<CompilationSourceFile> ();
source_files = new List<SourceFile> ();
}
#region Properties
public CompilationSourceFile FirstSourceFile {
public SourceFile FirstSourceFile {
get {
return source_files.Count > 0 ? source_files [0] : null;
}
@ -194,7 +209,7 @@ namespace Mono.CSharp { @@ -194,7 +209,7 @@ namespace Mono.CSharp {
}
}
public List<CompilationSourceFile> SourceFiles {
public List<SourceFile> SourceFiles {
get {
return source_files;
}
@ -208,10 +223,62 @@ namespace Mono.CSharp { @@ -208,10 +223,62 @@ namespace Mono.CSharp {
conditional_symbols.Add (symbol);
}
public void AddWarningAsError (int id)
{
if (warnings_as_error == null)
warnings_as_error = new List<int> ();
warnings_as_error.Add (id);
}
public void AddWarningOnly (int id)
{
if (warnings_only == null)
warnings_only = new List<int> ();
warnings_only.Add (id);
}
public bool IsConditionalSymbolDefined (string symbol)
{
return conditional_symbols.Contains (symbol);
}
public bool IsWarningAsError (int code)
{
bool is_error = WarningsAreErrors;
// Check specific list
if (warnings_as_error != null)
is_error |= warnings_as_error.Contains (code);
// Ignore excluded warnings
if (warnings_only != null && warnings_only.Contains (code))
is_error = false;
return is_error;
}
public bool IsWarningEnabled (int code, int level)
{
if (WarningLevel < level)
return false;
return !IsWarningDisabledGlobally (code);
}
public bool IsWarningDisabledGlobally (int code)
{
return warning_ignore_table != null && warning_ignore_table.Contains (code);
}
public void SetIgnoreWarning (int code)
{
if (warning_ignore_table == null)
warning_ignore_table = new HashSet<int> ();
warning_ignore_table.Add (code);
}
}
public class CommandLineParser
@ -227,22 +294,27 @@ namespace Mono.CSharp { @@ -227,22 +294,27 @@ namespace Mono.CSharp {
static readonly char[] argument_value_separator = new char[] { ';', ',' };
static readonly char[] numeric_value_separator = new char[] { ';', ',', ' ' };
readonly Report report;
readonly TextWriter output;
readonly Report report;
bool stop_argument;
Dictionary<string, int> source_file_index;
public event Func<string[], int, int> UnknownOptionHandler;
public CommandLineParser (Report report)
: this (report, Console.Out)
CompilerSettings parser_settings;
public CommandLineParser (TextWriter errorOutput)
: this (errorOutput, Console.Out)
{
}
public CommandLineParser (Report report, TextWriter messagesOutput)
public CommandLineParser (TextWriter errorOutput, TextWriter messagesOutput)
{
this.report = report;
var rp = new StreamReportPrinter (errorOutput);
parser_settings = new CompilerSettings ();
report = new Report (new CompilerContext (parser_settings, rp), rp);
this.output = messagesOutput;
}
@ -363,10 +435,13 @@ namespace Mono.CSharp { @@ -363,10 +435,13 @@ namespace Mono.CSharp {
ProcessSourceFiles (arg, false, settings.SourceFiles);
}
if (report.Errors > 0)
return null;
return settings;
}
void ProcessSourceFiles (string spec, bool recurse, List<CompilationSourceFile> sourceFiles)
void ProcessSourceFiles (string spec, bool recurse, List<SourceFile> sourceFiles)
{
string path, pattern;
@ -460,7 +535,7 @@ namespace Mono.CSharp { @@ -460,7 +535,7 @@ namespace Mono.CSharp {
settings.Resources.Add (res);
}
void AddSourceFile (string fileName, List<CompilationSourceFile> sourceFiles)
void AddSourceFile (string fileName, List<SourceFile> sourceFiles)
{
string path = Path.GetFullPath (fileName);
@ -475,11 +550,43 @@ namespace Mono.CSharp { @@ -475,11 +550,43 @@ namespace Mono.CSharp {
return;
}
var unit = new CompilationSourceFile (fileName, path, sourceFiles.Count + 1);
var unit = new SourceFile (fileName, path, sourceFiles.Count + 1);
sourceFiles.Add (unit);
source_file_index.Add (path, unit.Index);
}
void AddWarningAsError (string warningId, CompilerSettings settings)
{
int id;
try {
id = int.Parse (warningId);
} catch {
report.CheckWarningCode (warningId, Location.Null);
return;
}
if (!report.CheckWarningCode (id, Location.Null))
return;
settings.AddWarningAsError (id);
}
void RemoveWarningAsError (string warningId, CompilerSettings settings)
{
int id;
try {
id = int.Parse (warningId);
} catch {
report.CheckWarningCode (warningId, Location.Null);
return;
}
if (!report.CheckWarningCode (id, Location.Null))
return;
settings.AddWarningOnly (id);
}
void Error_RequiresArgument (string option)
{
report.Error (2006, "Missing argument for `{0}' option", option);
@ -830,10 +937,18 @@ namespace Mono.CSharp { @@ -830,10 +937,18 @@ namespace Mono.CSharp {
return ParseResult.Success;
case "/debug":
if (value == "full" || value == "")
if (value == "full" || value == "pdbonly" || idx < 0) {
settings.GenerateDebugInfo = true;
return ParseResult.Success;
}
return ParseResult.Success;
if (value.Length > 0) {
report.Error (1902, "Invalid debug option `{0}'. Valid options are `full' or `pdbonly'", value);
} else {
Error_RequiresArgument (option);
}
return ParseResult.Error;
case "/debug+":
settings.GenerateDebugInfo = true;
@ -869,19 +984,20 @@ namespace Mono.CSharp { @@ -869,19 +984,20 @@ namespace Mono.CSharp {
case "/warnaserror":
case "/warnaserror+":
if (value.Length == 0) {
report.WarningsAreErrors = true;
settings.WarningsAreErrors = true;
parser_settings.WarningsAreErrors = true;
} else {
foreach (string wid in value.Split (numeric_value_separator))
report.AddWarningAsError (wid);
AddWarningAsError (wid, settings);
}
return ParseResult.Success;
case "/warnaserror-":
if (value.Length == 0) {
report.WarningsAreErrors = false;
settings.WarningsAreErrors = false;
} else {
foreach (string wid in value.Split (numeric_value_separator))
report.RemoveWarningAsError (wid);
RemoveWarningAsError (wid, settings);
}
return ParseResult.Success;
@ -891,7 +1007,7 @@ namespace Mono.CSharp { @@ -891,7 +1007,7 @@ namespace Mono.CSharp {
return ParseResult.Error;
}
SetWarningLevel (value);
SetWarningLevel (value, settings);
return ParseResult.Success;
case "/nowarn":
@ -910,7 +1026,7 @@ namespace Mono.CSharp { @@ -910,7 +1026,7 @@ namespace Mono.CSharp {
if (warn < 1) {
throw new ArgumentOutOfRangeException ("warn");
}
report.SetIgnoreWarning (warn);
settings.SetIgnoreWarning (warn);
} catch {
report.Error (1904, "`{0}' is not a valid warning number", wc);
return ParseResult.Error;
@ -1095,7 +1211,7 @@ namespace Mono.CSharp { @@ -1095,7 +1211,7 @@ namespace Mono.CSharp {
{
switch (arg){
case "-v":
CSharpParser.yacc_verbose_flag++;
settings.VerboseParserFlag++;
return ParseResult.Success;
case "--version":
@ -1263,7 +1379,7 @@ namespace Mono.CSharp { @@ -1263,7 +1379,7 @@ namespace Mono.CSharp {
Usage ();
Environment.Exit (1);
}
report.SetIgnoreWarning (warn);
settings.SetIgnoreWarning (warn);
return ParseResult.Success;
case "--wlevel":
@ -1273,7 +1389,7 @@ namespace Mono.CSharp { @@ -1273,7 +1389,7 @@ namespace Mono.CSharp {
return ParseResult.Error;
}
SetWarningLevel (args [++i]);
SetWarningLevel (args [++i], settings);
return ParseResult.Success;
case "--mcs-debug":
@ -1351,7 +1467,7 @@ namespace Mono.CSharp { @@ -1351,7 +1467,7 @@ namespace Mono.CSharp {
}
}
void SetWarningLevel (string s)
void SetWarningLevel (string s, CompilerSettings settings)
{
int level = -1;
@ -1363,7 +1479,7 @@ namespace Mono.CSharp { @@ -1363,7 +1479,7 @@ namespace Mono.CSharp {
report.Error (1900, "Warning level must be in the range 0-4");
return;
}
report.WarningLevel = level;
settings.WarningLevel = level;
}
//

53
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/smcs.exe.sources

@ -1,53 +0,0 @@ @@ -1,53 +0,0 @@
AssemblyInfo.cs
anonymous.cs
argument.cs
assign.cs
attribute.cs
driver.cs
cs-tokenizer.cs
cfold.cs
class.cs
codegen.cs
complete.cs
const.cs
constant.cs
convert.cs
context.cs
decl.cs
delegate.cs
doc-bootstrap.cs
dynamic.cs
enum.cs
ecore.cs
eval.cs
expression.cs
field.cs
flowanalysis.cs
generic.cs
import.cs
iterators.cs
lambda.cs
linq.cs
literal.cs
location.cs
membercache.cs
method.cs
modifiers.cs
namespace.cs
nullable.cs
parameter.cs
pending.cs
property.cs
report.cs
rootcontext.cs
roottypes.cs
statement.cs
support.cs
typemanager.cs
typespec.cs
symbolwriter.cs
../class/Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs
../class/Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs
../class/Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs
../class/corlib/Mono.Security.Cryptography/CryptoConvert.cs
../build/common/Consts.cs

384
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/smcs.exe.sources-xml

@ -1,384 +0,0 @@ @@ -1,384 +0,0 @@
../build/common/MonoTODOAttribute.cs
../build/common/Locale.cs
../class/System.XML/Mono.Xml.Schema/XmlSchemaValidatingReader.cs
../class/System.XML/Mono.Xml.Schema/XsdIdentityPath.cs
../class/System.XML/Mono.Xml.Schema/XsdIdentityState.cs
../class/System.XML/Mono.Xml.Schema/XsdKeyTable.cs
../class/System.XML/Mono.Xml.Schema/XsdParticleValidationState.cs
../class/System.XML/Mono.Xml.Schema/XsdValidatingReader.cs
../class/System.XML/Mono.Xml.Schema/XsdWildcard.cs
../class/System.XML/Mono.Xml.XPath/DTMXPathDocument.cs
../class/System.XML/Mono.Xml.XPath/DTMXPathDocumentBuilder.cs
../class/System.XML/Mono.Xml.XPath/DTMXPathDocumentWriter.cs
../class/System.XML/Mono.Xml.XPath/DTMXPathNavigator.cs
../class/System.XML/Mono.Xml.XPath/DTMXPathNode.cs
../class/System.XML/Mono.Xml.XPath/DTMXPathDocument2.cs
../class/System.XML/Mono.Xml.XPath/DTMXPathDocumentBuilder2.cs
../class/System.XML/Mono.Xml.XPath/DTMXPathDocumentWriter2.cs
../class/System.XML/Mono.Xml.XPath/DTMXPathNavigator2.cs
../class/System.XML/Mono.Xml.XPath/DTMXPathNode2.cs
../class/System.XML/Mono.Xml.XPath/IdPattern.cs
../class/System.XML/Mono.Xml.XPath/KeyPattern.cs
../class/System.XML/Mono.Xml.XPath/LocationPathPattern.cs
../class/System.XML/Mono.Xml.XPath/Pattern.cs
../class/System.XML/Mono.Xml.XPath/UnionPattern.cs
../class/System.XML/Mono.Xml.XPath/XPathEditableDocument.cs
../class/System.XML/Mono.Xml.XPath/XPathNavigatorReader.cs
../class/System.XML/Mono.Xml/IHasXmlParserContext.cs
../class/System.XML/Mono.Xml/IHasXmlSchemaInfo.cs
../class/System.XML/Mono.Xml/SubtreeXmlReader.cs
../class/System.XML/Mono.Xml/XmlFilterReader.cs
../class/System.XML/Mono.Xml/XmlNodeWriter.cs
../class/System.XML/System.Xml/ConformanceLevel.cs
../class/System.XML/System.Xml/DTDAutomata.cs
../class/System.XML/System.Xml/DTDObjectModel.cs
../class/System.XML/System.Xml/DTDReader.cs
../class/System.XML/System.Xml/DTDValidatingReader2.cs
../class/System.XML/System.Xml/EntityResolvingXmlReader.cs
../class/System.XML/System.Xml/EntityHandling.cs
../class/System.XML/System.Xml/Formatting.cs
../class/System.XML/System.Xml/IHasXmlNode.cs
../class/System.XML/System.Xml/IXmlLineInfo.cs
../class/System.XML/System.Xml/IHasXmlChildNode.cs
../class/System.XML/System.Xml/IXmlNamespaceResolver.cs
../class/System.XML/System.Xml/MonoFIXAttribute.cs
../class/System.XML/System.Xml/NameTable.cs
../class/System.XML/System.Xml/NewLineHandling.cs
../class/System.XML/System.Xml/ReadState.cs
../class/System.XML/System.Xml/ValidationType.cs
../class/System.XML/System.Xml/WhitespaceHandling.cs
../class/System.XML/System.Xml/WriteState.cs
../class/System.XML/System.Xml/XmlEntity.cs
../class/System.XML/System.Xml/XmlAttribute.cs
../class/System.XML/System.Xml/XmlAttributeCollection.cs
../class/System.XML/System.Xml/XmlCDataSection.cs
../class/System.XML/System.Xml/XmlConstructs.cs
../class/System.XML/System.Xml/XmlChar.cs
../class/System.XML/System.Xml/XmlCharacterData.cs
../class/System.XML/System.Xml/XmlComment.cs
../class/System.XML/System.Xml/XmlNotation.cs
../class/System.XML/System.Xml/XmlDeclaration.cs
../class/System.XML/System.Xml/XmlDocument.cs
../class/System.XML/System.Xml/XmlDocumentFragment.cs
../class/System.XML/System.Xml/XmlDocumentNavigator.cs
../class/System.XML/System.Xml/XmlDocumentType.cs
../class/System.XML/System.Xml/XmlElement.cs
../class/System.XML/System.Xml/XmlEntityReference.cs
../class/System.XML/System.Xml/XmlException.cs
../class/System.XML/System.Xml/XmlImplementation.cs
../class/System.XML/System.Xml/XmlConvert.cs
../class/System.XML/System.Xml/XmlDateTimeSerializationMode.cs
../class/System.XML/System.Xml/XmlLinkedNode.cs
../class/System.XML/System.Xml/XmlNameEntry.cs
../class/System.XML/System.Xml/XmlNameEntryCache.cs
../class/System.XML/System.Xml/XmlNameTable.cs
../class/System.XML/System.Xml/XmlNamedNodeMap.cs
../class/System.XML/System.Xml/XmlNamespaceScope.cs
../class/System.XML/System.Xml/XmlNamespaceManager.cs
../class/System.XML/System.Xml/XmlNode.cs
../class/System.XML/System.Xml/XmlNodeChangedAction.cs
../class/System.XML/System.Xml/XmlNodeChangedEventArgs.cs
../class/System.XML/System.Xml/XmlNodeChangedEventHandler.cs
../class/System.XML/System.Xml/XmlNodeList.cs
../class/System.XML/System.Xml/XmlNodeListChildren.cs
../class/System.XML/System.Xml/XmlNodeArrayList.cs
../class/System.XML/System.Xml/XmlIteratorNodeList.cs
../class/System.XML/System.Xml/XmlNodeOrder.cs
../class/System.XML/System.Xml/XmlNodeReader2.cs
../class/System.XML/System.Xml/XmlNodeReaderImpl.cs
../class/System.XML/System.Xml/XmlNodeType.cs
../class/System.XML/System.Xml/XmlOutputMethod.cs
../class/System.XML/System.Xml/XmlParserContext.cs
../class/System.XML/System.Xml/XmlProcessingInstruction.cs
../class/System.XML/System.Xml/XmlQualifiedName.cs
../class/System.XML/System.Xml/XmlReader.cs
../class/System.XML/System.Xml/XmlReaderBinarySupport.cs
../class/System.XML/System.Xml/XmlReaderSettings.cs
../class/System.XML/System.Xml/XmlResolver.cs
../class/System.XML/System.Xml/XmlSecureResolver.cs
../class/System.XML/System.Xml/XmlSignificantWhitespace.cs
../class/System.XML/System.Xml/XmlSpace.cs
../class/System.XML/System.Xml/XmlText.cs
../class/System.XML/System.Xml/XmlTextReader.cs
../class/System.XML/System.Xml/XmlTextReader2.cs
../class/System.XML/System.Xml/XmlTokenizedType.cs
../class/System.XML/System.Xml/XmlUrlResolver.cs
../class/System.XML/System.Xml/XmlValidatingReader.cs
../class/System.XML/System.Xml/XmlWhitespace.cs
../class/System.XML/System.Xml/XmlWriter.cs
../class/System.XML/System.Xml/XmlWriterSettings.cs
../class/System.XML/System.Xml/XmlTextWriter2.cs
../class/System.XML/System.Xml/XmlInputStream.cs
../class/System.XML/System.Xml/XmlParserInput.cs
../class/System.XML/System.Xml.XPath/IXPathNavigable.cs
../class/System.XML/System.Xml.XPath/XPathNavigator.cs
../class/System.XML/System.Xml.XPath/XPathExpression.cs
../class/System.XML/System.Xml.XPath/XPathItem.cs
../class/System.XML/System.Xml.XPath/XPathNamespaceScope.cs
../class/System.XML/System.Xml.XPath/XPathNodeIterator.cs
../class/System.XML/System.Xml.XPath/XPathResultType.cs
../class/System.XML/System.Xml.XPath/XPathNodeType.cs
../class/System.XML/System.Xml.XPath/XmlDataType.cs
../class/System.XML/System.Xml.XPath/XmlSortOrder.cs
../class/System.XML/System.Xml.XPath/XmlCaseOrder.cs
../class/System.XML/System.Xml.XPath/XPathDocument.cs
../class/System.XML/System.Xml.XPath/XPathException.cs
../class/System.XML/System.Xml.XPath/XPathComparer.cs
../class/System.XML/System.Xml.XPath/DefaultContext.cs
../class/System.XML/System.Xml.XPath/Expression.cs
../class/System.XML/System.Xml.XPath/Iterator.cs
../class/System.XML/System.Xml.XPath/Tokenizer.cs
../class/System.XML/System.Xml.XPath/Parser.cs
../class/System.XML/System.Xml.Schema/BuiltInDatatype.cs
../class/System.XML/System.Xml.Schema/IXmlSchemaInfo.cs
../class/System.XML/System.Xml.Schema/SchemaDataValueType.cs
../class/System.XML/System.Xml.Schema/ValidationEventArgs.cs
../class/System.XML/System.Xml.Schema/XmlAtomicValue.cs
../class/System.XML/System.Xml.Schema/XmlSchema.cs
../class/System.XML/System.Xml.Schema/XmlSchemaAll.cs
../class/System.XML/System.Xml.Schema/XmlSchemaAnnotated.cs
../class/System.XML/System.Xml.Schema/XmlSchemaAnnotation.cs
../class/System.XML/System.Xml.Schema/XmlSchemaAny.cs
../class/System.XML/System.Xml.Schema/XmlSchemaAnyAttribute.cs
../class/System.XML/System.Xml.Schema/XmlSchemaAppInfo.cs
../class/System.XML/System.Xml.Schema/XmlSchemaAttribute.cs
../class/System.XML/System.Xml.Schema/XmlSchemaAttributeGroup.cs
../class/System.XML/System.Xml.Schema/XmlSchemaAttributeGroupRef.cs
../class/System.XML/System.Xml.Schema/XmlSchemaChoice.cs
../class/System.XML/System.Xml.Schema/XmlSchemaCollection.cs
../class/System.XML/System.Xml.Schema/XmlSchemaCollectionEnumerator.cs
../class/System.XML/System.Xml.Schema/XmlSchemaCompilationSettings.cs
../class/System.XML/System.Xml.Schema/XmlSchemaComplexContent.cs
../class/System.XML/System.Xml.Schema/XmlSchemaComplexContentExtension.cs
../class/System.XML/System.Xml.Schema/XmlSchemaComplexContentRestriction.cs
../class/System.XML/System.Xml.Schema/XmlSchemaComplexType.cs
../class/System.XML/System.Xml.Schema/XmlSchemaContent.cs
../class/System.XML/System.Xml.Schema/XmlSchemaContentModel.cs
../class/System.XML/System.Xml.Schema/XmlSchemaContentProcessing.cs
../class/System.XML/System.Xml.Schema/XmlSchemaContentType.cs
../class/System.XML/System.Xml.Schema/XmlSchemaDatatype.cs
../class/System.XML/System.Xml.Schema/XmlSchemaDatatypeVariety.cs
../class/System.XML/System.Xml.Schema/XmlSchemaDerivationMethod.cs
../class/System.XML/System.Xml.Schema/XmlSchemaDocumentation.cs
../class/System.XML/System.Xml.Schema/XmlSchemaElement.cs
../class/System.XML/System.Xml.Schema/XmlSchemaEnumerationFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaException.cs
../class/System.XML/System.Xml.Schema/XmlSchemaExternal.cs
../class/System.XML/System.Xml.Schema/XmlSchemaFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaForm.cs
../class/System.XML/System.Xml.Schema/XmlSchemaFractionDigitsFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaGroup.cs
../class/System.XML/System.Xml.Schema/XmlSchemaGroupBase.cs
../class/System.XML/System.Xml.Schema/XmlSchemaGroupRef.cs
../class/System.XML/System.Xml.Schema/XmlSchemaIdentityConstraint.cs
../class/System.XML/System.Xml.Schema/XmlSchemaImport.cs
../class/System.XML/System.Xml.Schema/XmlSchemaInclude.cs
../class/System.XML/System.Xml.Schema/XmlSchemaInference.cs
../class/System.XML/System.Xml.Schema/XmlSchemaInferenceException.cs
../class/System.XML/System.Xml.Schema/XmlSchemaInfo.cs
../class/System.XML/System.Xml.Schema/XmlSchemaKey.cs
../class/System.XML/System.Xml.Schema/XmlSchemaKeyref.cs
../class/System.XML/System.Xml.Schema/XmlSchemaLengthFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaMaxExclusiveFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaMaxInclusiveFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaMaxLengthFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaMinExclusiveFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaMinInclusiveFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaMinLengthFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaNotation.cs
../class/System.XML/System.Xml.Schema/XmlSchemaNumericFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaObject.cs
../class/System.XML/System.Xml.Schema/XmlSchemaObjectCollection.cs
../class/System.XML/System.Xml.Schema/XmlSchemaObjectEnumerator.cs
../class/System.XML/System.Xml.Schema/XmlSchemaObjectTable.cs
../class/System.XML/System.Xml.Schema/XmlSchemaParticle.cs
../class/System.XML/System.Xml.Schema/XmlSchemaPatternFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaRedefine.cs
../class/System.XML/System.Xml.Schema/XmlSchemaSet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaSequence.cs
../class/System.XML/System.Xml.Schema/XmlSchemaSerializer.cs
../class/System.XML/System.Xml.Schema/XmlSchemaSimpleContent.cs
../class/System.XML/System.Xml.Schema/XmlSchemaSimpleContentExtension.cs
../class/System.XML/System.Xml.Schema/XmlSchemaSimpleContentRestriction.cs
../class/System.XML/System.Xml.Schema/XmlSchemaSimpleType.cs
../class/System.XML/System.Xml.Schema/XmlSchemaSimpleTypeContent.cs
../class/System.XML/System.Xml.Schema/XmlSchemaSimpleTypeList.cs
../class/System.XML/System.Xml.Schema/XmlSchemaSimpleTypeRestriction.cs
../class/System.XML/System.Xml.Schema/XmlSchemaSimpleTypeUnion.cs
../class/System.XML/System.Xml.Schema/XmlSchemaTotalDigitsFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaType.cs
../class/System.XML/System.Xml.Schema/XmlSchemaUnique.cs
../class/System.XML/System.Xml.Schema/XmlSchemaUse.cs
../class/System.XML/System.Xml.Schema/XmlSchemaValidator.cs
../class/System.XML/System.Xml.Schema/XmlSchemaValidity.cs
../class/System.XML/System.Xml.Schema/XmlSchemaValidationException.cs
../class/System.XML/System.Xml.Schema/XmlSchemaWhiteSpaceFacet.cs
../class/System.XML/System.Xml.Schema/XmlSchemaXPath.cs
../class/System.XML/System.Xml.Schema/XmlSeverityType.cs
../class/System.XML/System.Xml.Schema/ValidationHandler.cs
../class/System.XML/System.Xml.Schema/XmlSchemaUtil.cs
../class/System.XML/System.Xml.Schema/XmlSchemaReader.cs
../class/System.XML/System.Xml.Schema/XmlSchemaValidationFlags.cs
../class/System.XML/System.Xml.Schema/XmlTypeCode.cs
../class/System.XML/System.Xml.Schema/XmlValueGetter.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslApplyImports.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslApplyTemplates.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslAttribute.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslAvt.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslCallTemplate.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslChoose.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslComment.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslCompiledElement.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslCopy.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslCopyOf.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslElement.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslFallback.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslForEach.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslIf.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslLiteralElement.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslMessage.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslNotSupportedOperation.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslNumber.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslOperation.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslProcessingInstruction.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslTemplateContent.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslText.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslValueOf.cs
../class/System.XML/Mono.Xml.Xsl.Operations/XslVariable.cs
../class/System.XML/Mono.Xml.Xsl/Attribute.cs
../class/System.XML/Mono.Xml.Xsl/Compiler.cs
../class/System.XML/Mono.Xml.Xsl/Debug.cs
../class/System.XML/Mono.Xml.Xsl/Emitter.cs
../class/System.XML/Mono.Xml.Xsl/GenericOutputter.cs
../class/System.XML/Mono.Xml.Xsl/HtmlEmitter.cs
../class/System.XML/Mono.Xml.Xsl/MSXslScriptManager.cs
../class/System.XML/Mono.Xml.Xsl/Outputter.cs
../class/System.XML/Mono.Xml.Xsl/ScriptCompilerInfo.cs
../class/System.XML/Mono.Xml.Xsl/TextEmitter.cs
../class/System.XML/Mono.Xml.Xsl/TextOutputter.cs
../class/System.XML/Mono.Xml.Xsl/PatternParser.cs
../class/System.XML/Mono.Xml.Xsl/PatternTokenizer.cs
../class/System.XML/Mono.Xml.Xsl/XmlWriterEmitter.cs
../class/System.XML/Mono.Xml.Xsl/XslAttributeSet.cs
../class/System.XML/Mono.Xml.Xsl/XslDecimalFormat.cs
../class/System.XML/Mono.Xml.Xsl/XslKey.cs
../class/System.XML/Mono.Xml.Xsl/XslOutput.cs
../class/System.XML/Mono.Xml.Xsl/XslSortEvaluator.cs
../class/System.XML/Mono.Xml.Xsl/XslStylesheet.cs
../class/System.XML/Mono.Xml.Xsl/XslTemplate.cs
../class/System.XML/Mono.Xml.Xsl/XslTransformProcessor.cs
../class/System.XML/Mono.Xml.Xsl/XsltCompiledContext.cs
../class/System.XML/Mono.Xml.Xsl/XsltDebuggerWrapper.cs
../class/System.XML/Mono.Xml.Xsl/XslFunctions.cs
../class/System.XML/System.Xml.Xsl/IXsltContextFunction.cs
../class/System.XML/System.Xml.Xsl/IXsltContextVariable.cs
../class/System.XML/System.Xml.Xsl/XslCompiledTransform.cs
../class/System.XML/System.Xml.Xsl/XslTransform.cs
../class/System.XML/System.Xml.Xsl/XsltArgumentList.cs
../class/System.XML/System.Xml.Xsl/XsltCompileException.cs
../class/System.XML/System.Xml.Xsl/XsltContext.cs
../class/System.XML/System.Xml.Xsl/XsltException.cs
../class/System.XML/System.Xml.Xsl/XsltMessageEncounteredEventArgs.cs
../class/System.XML/System.Xml.Xsl/XsltMessageEncounteredEventHandler.cs
../class/System.XML/System.Xml.Xsl/XsltSettings.cs
../class/System.XML/System.Xml/XQueryConvert.cs
../class/System.XML/System.Xml.Serialization/IXmlTextParser.cs
../class/System.XML/System.Xml.Serialization/CodeExporter.cs
../class/System.XML/System.Xml.Serialization/CodeGenerationOptions.cs
../class/System.XML/System.Xml.Serialization/CodeIdentifier.cs
../class/System.XML/System.Xml.Serialization/CodeIdentifiers.cs
../class/System.XML/System.Xml.Serialization/IXmlSerializable.cs
../class/System.XML/System.Xml.Serialization/ImportContext.cs
../class/System.XML/System.Xml.Serialization/MapCodeGenerator.cs
../class/System.XML/System.Xml.Serialization/ReflectionHelper.cs
../class/System.XML/System.Xml.Serialization/SchemaImporter.cs
../class/System.XML/System.Xml.Serialization/SchemaTypes.cs
../class/System.XML/System.Xml.Serialization/SerializationCodeGenerator.cs
../class/System.XML/System.Xml.Serialization/SerializationCodeGeneratorConfiguration.cs
../class/System.XML/System.Xml.Serialization/SerializationSource.cs
../class/System.XML/System.Xml.Serialization/SoapAttributeAttribute.cs
../class/System.XML/System.Xml.Serialization/SoapAttributeOverrides.cs
../class/System.XML/System.Xml.Serialization/SoapAttributes.cs
../class/System.XML/System.Xml.Serialization/SoapCodeExporter.cs
../class/System.XML/System.Xml.Serialization/SoapElementAttribute.cs
../class/System.XML/System.Xml.Serialization/SoapEnumAttribute.cs
../class/System.XML/System.Xml.Serialization/SoapIgnoreAttribute.cs
../class/System.XML/System.Xml.Serialization/SoapIncludeAttribute.cs
../class/System.XML/System.Xml.Serialization/SoapSchemaImporter.cs
../class/System.XML/System.Xml.Serialization/SoapSchemaExporter.cs
../class/System.XML/System.Xml.Serialization/SoapSchemaMember.cs
../class/System.XML/System.Xml.Serialization/SoapReflectionImporter.cs
../class/System.XML/System.Xml.Serialization/SoapTypeAttribute.cs
../class/System.XML/System.Xml.Serialization/TypeData.cs
../class/System.XML/System.Xml.Serialization/TypeMember.cs
../class/System.XML/System.Xml.Serialization/TypeTranslator.cs
../class/System.XML/System.Xml.Serialization/UnreferencedObjectEventArgs.cs
../class/System.XML/System.Xml.Serialization/UnreferencedObjectEventHandler.cs
../class/System.XML/System.Xml.Serialization/XmlAnyAttributeAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlAnyElementAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlAnyElementAttributes.cs
../class/System.XML/System.Xml.Serialization/XmlArrayAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlArrayItemAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlArrayItemAttributes.cs
../class/System.XML/System.Xml.Serialization/XmlAttributeAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlAttributeEventArgs.cs
../class/System.XML/System.Xml.Serialization/XmlAttributeEventHandler.cs
../class/System.XML/System.Xml.Serialization/XmlAttributeOverrides.cs
../class/System.XML/System.Xml.Serialization/XmlAttributes.cs
../class/System.XML/System.Xml.Serialization/XmlCodeExporter.cs
../class/System.XML/System.Xml.Serialization/XmlChoiceIdentifierAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlCustomFormatter.cs
../class/System.XML/System.Xml.Serialization/XmlDeserializationEvents.cs
../class/System.XML/System.Xml.Serialization/XmlElementAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlElementAttributes.cs
../class/System.XML/System.Xml.Serialization/XmlElementEventArgs.cs
../class/System.XML/System.Xml.Serialization/XmlEnumAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlIgnoreAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlIncludeAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlMemberMapping.cs
../class/System.XML/System.Xml.Serialization/XmlMembersMapping.cs
../class/System.XML/System.Xml.Serialization/XmlMapping.cs
../class/System.XML/System.Xml.Serialization/XmlMappingAccess.cs
../class/System.XML/System.Xml.Serialization/XmlNamespaceDeclarationsAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlNodeEventArgs.cs
../class/System.XML/System.Xml.Serialization/XmlReflectionImporter.cs
../class/System.XML/System.Xml.Serialization/XmlReflectionMember.cs
../class/System.XML/System.Xml.Serialization/XmlRootAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlSchemaEnumerator.cs
../class/System.XML/System.Xml.Serialization/XmlSchemaExporter.cs
../class/System.XML/System.Xml.Serialization/XmlSchemaImporter.cs
../class/System.XML/System.Xml.Serialization/XmlSchemaProviderAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlSchemas.cs
../class/System.XML/System.Xml.Serialization/XmlSerializationCollectionFixupCallback.cs
../class/System.XML/System.Xml.Serialization/XmlSerializationFixupCallback.cs
../class/System.XML/System.Xml.Serialization/XmlSerializationGeneratedCode.cs
../class/System.XML/System.Xml.Serialization/XmlSerializationReadCallback.cs
../class/System.XML/System.Xml.Serialization/XmlSerializationReader.cs
../class/System.XML/System.Xml.Serialization/XmlSerializationReaderInterpreter.cs
../class/System.XML/System.Xml.Serialization/XmlSerializationWriteCallback.cs
../class/System.XML/System.Xml.Serialization/XmlSerializationWriter.cs
../class/System.XML/System.Xml.Serialization/XmlSerializationWriterInterpreter.cs
../class/System.XML/System.Xml.Serialization/XmlSerializer.cs
../class/System.XML/System.Xml.Serialization/XmlSerializerAssemblyAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlSerializerFactory.cs
../class/System.XML/System.Xml.Serialization/XmlSerializerImplementation.cs
../class/System.XML/System.Xml.Serialization/XmlSerializerNamespaces.cs
../class/System.XML/System.Xml.Serialization/XmlSerializerVersionAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlTextAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlTypeAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlTypeMapElementInfo.cs
../class/System.XML/System.Xml.Serialization/XmlTypeMapMember.cs
../class/System.XML/System.Xml.Serialization/XmlTypeMapMemberAttribute.cs
../class/System.XML/System.Xml.Serialization/XmlTypeMapMemberElement.cs
../class/System.XML/System.Xml.Serialization/XmlTypeMapMemberNamespaces.cs
../class/System.XML/System.Xml.Serialization/XmlTypeMapping.cs
../class/System.XML/System.Xml.Serialization/XmlElementEventHandler.cs
../class/System.XML/System.Xml.Serialization/XmlNodeEventHandler.cs
../class/System.XML/System.Xml.Serialization.Advanced/SchemaImporterExtension.cs
../class/System.XML/System.Xml.Serialization.Advanced/SchemaImporterExtensionCollection.cs
../class/System.XML/System.Xml.Serialization.Configuration/DateTimeSerializationSection.cs
../class/System.XML/System.Xml.Serialization.Configuration/SchemaImporterExtensionElement.cs
../class/System.XML/System.Xml.Serialization.Configuration/SchemaImporterExtensionElementCollection.cs
../class/System.XML/System.Xml.Serialization.Configuration/SchemaImporterExtensionsSection.cs
../class/System.XML/System.Xml.Serialization.Configuration/SerializationSectionGroup.cs
../class/System.XML/System.Xml.Serialization.Configuration/XmlSerializerSection.cs

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

@ -327,17 +327,21 @@ namespace Mono.CSharp { @@ -327,17 +327,21 @@ namespace Mono.CSharp {
EmbeddedStatement.Emit (ec);
ec.MarkLabel (ec.LoopBegin);
// Mark start of while condition
ec.Mark (expr.Location);
//
// Dead code elimination
//
if (expr is Constant){
if (expr is Constant) {
bool res = !((Constant) expr).IsDefaultValue;
expr.EmitSideEffect (ec);
if (res)
ec.Emit (OpCodes.Br, loop);
} else
ec.Emit (OpCodes.Br, loop);
} else {
expr.EmitBranchable (ec, loop, true);
}
ec.MarkLabel (ec.LoopEnd);
@ -427,9 +431,13 @@ namespace Mono.CSharp { @@ -427,9 +431,13 @@ namespace Mono.CSharp {
//
// Inform whether we are infinite or not
//
if (expr is Constant){
if (expr is Constant) {
// expr is 'true', since the 'empty' case above handles the 'false' case
ec.MarkLabel (ec.LoopBegin);
if (ec.EmitAccurateDebugInfo)
ec.Emit (OpCodes.Nop);
expr.EmitSideEffect (ec);
Statement.Emit (ec);
ec.Emit (OpCodes.Br, ec.LoopBegin);
@ -448,8 +456,8 @@ namespace Mono.CSharp { @@ -448,8 +456,8 @@ namespace Mono.CSharp {
Statement.Emit (ec);
ec.MarkLabel (ec.LoopBegin);
ec.Mark (loc);
ec.Mark (expr.Location);
expr.EmitBranchable (ec, while_loop, true);
ec.MarkLabel (ec.LoopEnd);
@ -459,11 +467,6 @@ namespace Mono.CSharp { @@ -459,11 +467,6 @@ namespace Mono.CSharp {
ec.LoopEnd = old_end;
}
public override void Emit (EmitContext ec)
{
DoEmit (ec);
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
While target = (While) t;
@ -592,7 +595,9 @@ namespace Mono.CSharp { @@ -592,7 +595,9 @@ namespace Mono.CSharp {
// If test is null, there is no test, and we are just
// an infinite loop
//
if (Condition != null){
if (Condition != null) {
ec.Mark (Condition.Location);
//
// The Resolve code already catches the case for
// Test == Constant (false) so we know that
@ -642,6 +647,12 @@ namespace Mono.CSharp { @@ -642,6 +647,12 @@ namespace Mono.CSharp {
loc = expr.Location;
}
public StatementExpression (ExpressionStatement expr, Location loc)
{
this.expr = expr;
this.loc = loc;
}
public ExpressionStatement Expr {
get {
return this.expr;
@ -925,14 +936,17 @@ namespace Mono.CSharp { @@ -925,14 +936,17 @@ namespace Mono.CSharp {
return;
}
if (unwind_protect)
if (unwind_protect || ec.EmitAccurateDebugInfo)
ec.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
}
if (unwind_protect)
if (unwind_protect) {
ec.Emit (OpCodes.Leave, ec.CreateReturnLabel ());
else
} else if (ec.EmitAccurateDebugInfo) {
ec.Emit (OpCodes.Br, ec.CreateReturnLabel ());
} else {
ec.Emit (OpCodes.Ret);
}
}
void Error_ReturnFromIterator (ResolveContext rc)
@ -1456,7 +1470,7 @@ namespace Mono.CSharp { @@ -1456,7 +1470,7 @@ namespace Mono.CSharp {
if (bc.Report.Errors != 0)
return;
var container = bc.CurrentMemberDefinition.Parent;
var container = bc.CurrentMemberDefinition.Parent.PartialContainer;
Field f = new Field (container, new TypeExpression (li.Type, li.Location), Modifiers.PUBLIC | Modifiers.STATIC,
new MemberName (li.Name, li.Location), null);
@ -1576,9 +1590,6 @@ namespace Mono.CSharp { @@ -1576,9 +1590,6 @@ namespace Mono.CSharp {
protected override void DoEmit (EmitContext ec)
{
if (li.IsConstant)
return;
li.CreateBuilder (ec);
if (Initializer != null)
@ -1623,6 +1634,11 @@ namespace Mono.CSharp { @@ -1623,6 +1634,11 @@ namespace Mono.CSharp {
{
}
public override void Emit (EmitContext ec)
{
// Nothing to emit, not even sequence point
}
protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
{
initializer = initializer.Resolve (bc);
@ -1842,7 +1858,7 @@ namespace Mono.CSharp { @@ -1842,7 +1858,7 @@ namespace Mono.CSharp {
// All fixed variabled are pinned, a slot has to be alocated
//
builder = ec.DeclareLocal (Type, IsFixed);
if (SymbolWriter.HasSymbolWriter)
if (!ec.HasSet (BuilderContext.Options.OmitDebugInfo) && (flags & Flags.CompilerGenerated) == 0)
ec.DefineLocalVariable (name, builder);
}
@ -1912,7 +1928,7 @@ namespace Mono.CSharp { @@ -1912,7 +1928,7 @@ namespace Mono.CSharp {
if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
return true;
return VariableInfo.TypeInfo.IsFullyInitialized (ec, VariableInfo, block.StartLocation);
return VariableInfo.IsFullyInitialized (ec, block.StartLocation);
}
public bool IsAssigned (BlockContext ec)
@ -2042,8 +2058,13 @@ namespace Mono.CSharp { @@ -2042,8 +2058,13 @@ namespace Mono.CSharp {
#region Properties
public bool HasRet {
get { return (flags & Flags.HasRet) != 0; }
public bool HasUnreachableClosingBrace {
get {
return (flags & Flags.HasRet) != 0;
}
set {
flags = value ? flags | Flags.HasRet : flags & ~Flags.HasRet;
}
}
public Block Original {
@ -2099,9 +2120,9 @@ namespace Mono.CSharp { @@ -2099,9 +2120,9 @@ namespace Mono.CSharp {
AddLocalName (li.Name, li);
}
public virtual void AddLocalName (string name, INamedBlockVariable li)
public void AddLocalName (string name, INamedBlockVariable li)
{
ParametersBlock.TopBlock.AddLocalName (name, li);
ParametersBlock.TopBlock.AddLocalName (name, li, false);
}
public virtual void Error_AlreadyDeclared (string name, INamedBlockVariable variable, string reason)
@ -2296,7 +2317,6 @@ namespace Mono.CSharp { @@ -2296,7 +2317,6 @@ namespace Mono.CSharp {
if (scope_initializers != null)
EmitScopeInitializers (ec);
ec.Mark (StartLocation);
DoEmit (ec);
if (SymbolWriter.HasSymbolWriter)
@ -2305,14 +2325,8 @@ namespace Mono.CSharp { @@ -2305,14 +2325,8 @@ namespace Mono.CSharp {
protected void EmitScopeInitializers (EmitContext ec)
{
SymbolWriter.OpenCompilerGeneratedBlock (ec);
using (ec.With (EmitContext.Options.OmitDebugInfo, true)) {
foreach (Statement s in scope_initializers)
s.Emit (ec);
}
SymbolWriter.CloseCompilerGeneratedBlock (ec);
foreach (Statement s in scope_initializers)
s.Emit (ec);
}
protected virtual void EmitSymbolInfo (EmitContext ec)
@ -2444,14 +2458,28 @@ namespace Mono.CSharp { @@ -2444,14 +2458,28 @@ namespace Mono.CSharp {
am_storey.EmitStoreyInstantiation (ec, this);
}
if (scope_initializers != null)
EmitScopeInitializers (ec);
if (ec.EmitAccurateDebugInfo && !IsCompilerGenerated && ec.Mark (StartLocation)) {
ec.Emit (OpCodes.Nop);
}
bool emit_debug_info = SymbolWriter.HasSymbolWriter && Parent != null && !(am_storey is IteratorStorey);
if (emit_debug_info)
ec.BeginScope ();
base.Emit (ec);
DoEmit (ec);
if (SymbolWriter.HasSymbolWriter)
EmitSymbolInfo (ec);
if (emit_debug_info)
ec.EndScope ();
if (ec.EmitAccurateDebugInfo && !HasUnreachableClosingBrace && !IsCompilerGenerated && ec.Mark (EndLocation)) {
ec.Emit (OpCodes.Nop);
}
}
void DefineAnonymousStorey (EmitContext ec)
@ -2481,9 +2509,8 @@ namespace Mono.CSharp { @@ -2481,9 +2509,8 @@ namespace Mono.CSharp {
am_storey.Mutator = ec.CurrentAnonymousMethod.Storey.Mutator;
}
am_storey.CreateType ();
am_storey.DefineType ();
am_storey.ResolveTypeParameters ();
am_storey.CreateContainer ();
am_storey.DefineContainer ();
var ref_blocks = am_storey.ReferencesFromChildrenBlock;
if (ref_blocks != null) {
@ -2921,10 +2948,9 @@ namespace Mono.CSharp { @@ -2921,10 +2948,9 @@ namespace Mono.CSharp {
}
}
public void WrapIntoIterator (IMethodData method, TypeContainer host, TypeSpec iterator_type, bool is_enumerable)
public void WrapIntoIterator (IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
{
ParametersBlock pb = new ParametersBlock (this, ParametersCompiled.EmptyReadOnlyParameters, StartLocation);
pb.EndLocation = EndLocation;
ParametersBlock pb = new ParametersBlock (this, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
pb.statements = statements;
pb.Original = this;
@ -2934,9 +2960,10 @@ namespace Mono.CSharp { @@ -2934,9 +2960,10 @@ namespace Mono.CSharp {
statements = new List<Statement> (1);
AddStatement (new Return (iterator, iterator.Location));
flags &= ~Flags.YieldBlock;
IsCompilerGenerated = true;
}
public void WrapIntoAsyncTask (IMemberContext context, TypeContainer host, TypeSpec returnType)
public void WrapIntoAsyncTask (IMemberContext context, TypeDefinition host, TypeSpec returnType)
{
ParametersBlock pb = new ParametersBlock (this, ParametersCompiled.EmptyReadOnlyParameters, StartLocation);
pb.EndLocation = EndLocation;
@ -2981,6 +3008,7 @@ namespace Mono.CSharp { @@ -2981,6 +3008,7 @@ namespace Mono.CSharp {
{
this.compiler = ctx;
top_block = this;
flags |= Flags.HasRet;
ProcessParameters ();
}
@ -2996,6 +3024,7 @@ namespace Mono.CSharp { @@ -2996,6 +3024,7 @@ namespace Mono.CSharp {
{
this.compiler = source.TopBlock.compiler;
top_block = this;
flags |= Flags.HasRet;
}
public bool IsIterator {
@ -3004,7 +3033,7 @@ namespace Mono.CSharp { @@ -3004,7 +3033,7 @@ namespace Mono.CSharp {
}
}
public override void AddLocalName (string name, INamedBlockVariable li)
public void AddLocalName (string name, INamedBlockVariable li, bool ignoreChildrenBlocks)
{
if (names == null)
names = new Dictionary<string, object> ();
@ -3030,31 +3059,32 @@ namespace Mono.CSharp { @@ -3030,31 +3059,32 @@ namespace Mono.CSharp {
//
for (int i = 0; i < existing_list.Count; ++i) {
existing = existing_list[i];
Block b = existing.Block;
Block b = existing.Block.Explicit;
// Collision at same level
if (li.Block == b) {
if (li.Block.Explicit == b) {
li.Block.Error_AlreadyDeclared (name, li);
break;
}
// Collision with parent
b = li.Block;
while ((b = b.Parent) != null) {
if (existing.Block == b) {
Block parent = li.Block.Explicit;
while ((parent = parent.Parent) != null) {
if (parent == b) {
li.Block.Error_AlreadyDeclared (name, li, "parent or current");
i = existing_list.Count;
break;
}
}
// Collision with with children
b = existing.Block;
while ((b = b.Parent) != null) {
if (li.Block == b) {
li.Block.Error_AlreadyDeclared (name, li, "child");
i = existing_list.Count;
break;
if (!ignoreChildrenBlocks) {
// Collision with children
while ((b = b.Parent) != null) {
if (li.Block.Explicit == b) {
li.Block.Error_AlreadyDeclared (name, li, "child");
i = existing_list.Count;
break;
}
}
}
}
@ -3271,36 +3301,37 @@ namespace Mono.CSharp { @@ -3271,36 +3301,37 @@ namespace Mono.CSharp {
#if PRODUCTION
try {
#endif
if (IsCompilerGenerated) {
using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
base.Emit (ec);
}
} else {
base.Emit (ec);
}
base.Emit (ec);
//
// If `HasReturnLabel' is set, then we already emitted a
// jump to the end of the method, so we must emit a `ret'
// there.
//
// Unfortunately, System.Reflection.Emit automatically emits
// a leave to the end of a finally block. This is a problem
// if no code is following the try/finally block since we may
// jump to a point after the end of the method.
// As a workaround, we're always creating a return label in
// this case.
//
if (ec.HasReturnLabel || !unreachable) {
if (ec.HasReturnLabel)
ec.MarkLabel (ec.ReturnLabel);
ec.Mark (EndLocation);
if (ec.EmitAccurateDebugInfo && !IsCompilerGenerated)
ec.Mark (EndLocation);
if (ec.HasReturnLabel)
ec.MarkLabel (ec.ReturnLabel);
if (ec.ReturnType.Kind != MemberKind.Void)
ec.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
if (ec.return_value != null) {
ec.Emit (OpCodes.Ldloc, ec.return_value);
ec.Emit (OpCodes.Ret);
} else {
//
// If `HasReturnLabel' is set, then we already emitted a
// jump to the end of the method, so we must emit a `ret'
// there.
//
// Unfortunately, System.Reflection.Emit automatically emits
// a leave to the end of a finally block. This is a problem
// if no code is following the try/finally block since we may
// jump to a point after the end of the method.
// As a workaround, we're always creating a return label in
// this case.
//
if (ec.HasReturnLabel || !unreachable) {
if (ec.ReturnType.Kind != MemberKind.Void)
ec.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
ec.Emit (OpCodes.Ret);
}
}
#if PRODUCTION
@ -3552,7 +3583,6 @@ namespace Mono.CSharp { @@ -3552,7 +3583,6 @@ namespace Mono.CSharp {
VariableReference value;
ExpressionStatement string_dictionary;
FieldExpr switch_cache_field;
static int unique_counter;
ExplicitBlock block;
//
@ -3913,11 +3943,6 @@ namespace Mono.CSharp { @@ -3913,11 +3943,6 @@ namespace Mono.CSharp {
return null;
}
public static void Reset ()
{
unique_counter = 0;
}
public override bool Resolve (BlockContext ec)
{
Expr = Expr.Resolve (ec);
@ -4061,7 +4086,10 @@ namespace Mono.CSharp { @@ -4061,7 +4086,10 @@ namespace Mono.CSharp {
}
}
simple_stmt = new If (cond, s.Block, simple_stmt, loc);
//
// Compiler generated, hide from symbol file
//
simple_stmt = new If (cond, s.Block, simple_stmt, Location.Null);
}
// It's null for empty switch
@ -4090,7 +4118,7 @@ namespace Mono.CSharp { @@ -4090,7 +4118,7 @@ namespace Mono.CSharp {
var ctype = ec.CurrentMemberDefinition.Parent.PartialContainer;
Field field = new Field (ctype, string_dictionary_type,
Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
new MemberName (CompilerGeneratedClass.MakeName (null, "f", "switch$map", unique_counter++), loc), null);
new MemberName (CompilerGeneratedClass.MakeName (null, "f", "switch$map", ec.Module.CounterSwitchTypes++), loc), null);
if (!field.Define ())
return;
ctype.AddField (field);
@ -4149,7 +4177,9 @@ namespace Mono.CSharp { @@ -4149,7 +4177,9 @@ namespace Mono.CSharp {
// Check if string dictionary is initialized and initialize
//
switch_cache_field.EmitBranchable (ec, l_initialized, true);
string_dictionary.EmitStatement (ec);
using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
string_dictionary.EmitStatement (ec);
}
ec.MarkLabel (l_initialized);
LocalTemporary string_switch_variable = new LocalTemporary (ec.BuiltinTypes.Int);
@ -4193,6 +4223,9 @@ namespace Mono.CSharp { @@ -4193,6 +4223,9 @@ namespace Mono.CSharp {
protected override void DoEmit (EmitContext ec)
{
// Workaround broken flow-analysis
block.HasUnreachableClosingBrace = true;
//
// Needed to emit anonymous storey initialization
// Otherwise it does not contain any statements for now
@ -5100,17 +5133,13 @@ namespace Mono.CSharp { @@ -5100,17 +5133,13 @@ namespace Mono.CSharp {
//
if (li.HoistedVariant != null) {
LocalTemporary lt = new LocalTemporary (li.Type);
SymbolWriter.OpenCompilerGeneratedBlock (ec);
lt.Store (ec);
SymbolWriter.CloseCompilerGeneratedBlock (ec);
// switch to assigning from the temporary variable and not from top of the stack
assign.UpdateSource (lt);
}
} else {
SymbolWriter.OpenCompilerGeneratedBlock (ec);
ec.Emit (OpCodes.Pop);
SymbolWriter.CloseCompilerGeneratedBlock (ec);
}
Block.Emit (ec);
@ -5135,8 +5164,11 @@ namespace Mono.CSharp { @@ -5135,8 +5164,11 @@ namespace Mono.CSharp {
if (li.Type.IsGenericParameter)
source = new UnboxCast (source, li.Type);
assign = new CompilerAssign (new LocalVariableReference (li, loc), source, loc);
Block.AddScopeStatement (new StatementExpression (assign));
//
// Uses Location.Null to hide from symbol file
//
assign = new CompilerAssign (new LocalVariableReference (li, Location.Null), source, Location.Null);
Block.AddScopeStatement (new StatementExpression (assign, Location.Null));
}
}
@ -5462,7 +5494,10 @@ namespace Mono.CSharp { @@ -5462,7 +5494,10 @@ namespace Mono.CSharp {
new Cast (new TypeExpression (idt, loc), lvr, loc).Resolve (bc) :
lvr;
Statement dispose = new StatementExpression (new Invocation (dispose_mg, null));
//
// Hide it from symbol file via null location
//
Statement dispose = new StatementExpression (new Invocation (dispose_mg, null), Location.Null);
// Add conditional call when disposing possible null variable
if (!type.IsStruct || type.IsNullableType)
@ -5529,6 +5564,14 @@ namespace Mono.CSharp { @@ -5529,6 +5564,14 @@ namespace Mono.CSharp {
#endregion
public override void Emit (EmitContext ec)
{
//
// Don't emit sequence point it will be set on variable declaration
//
DoEmit (ec);
}
protected override void EmitTryBodyPrepare (EmitContext ec)
{
decl.Emit (ec);
@ -5952,9 +5995,11 @@ namespace Mono.CSharp { @@ -5952,9 +5995,11 @@ namespace Mono.CSharp {
} while (t != null);
if (iface_candidate == null) {
rc.Report.Error (1579, loc,
"foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `{1}' or is inaccessible",
expr.Type.GetSignatureForError (), "GetEnumerator");
if (expr.Type != InternalType.ErrorType) {
rc.Report.Error (1579, loc,
"foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `{1}' or is inaccessible",
expr.Type.GetSignatureForError (), "GetEnumerator");
}
return null;
}
@ -5979,7 +6024,7 @@ namespace Mono.CSharp { @@ -5979,7 +6024,7 @@ namespace Mono.CSharp {
return null;
}
return MethodGroupExpr.CreatePredefined (ms, enumerator.ReturnType, loc);
return MethodGroupExpr.CreatePredefined (ms, enumerator.ReturnType, expr.Location);
}
PropertySpec ResolveCurrent (ResolveContext rc, MethodSpec enumerator)
@ -6058,7 +6103,7 @@ namespace Mono.CSharp { @@ -6058,7 +6103,7 @@ namespace Mono.CSharp {
var init = new Invocation (get_enumerator_mg, null);
statement = new While (new BooleanExpression (new Invocation (move_next_mg, null)),
new Body (variable.Type, variable, current_pe, statement, loc), loc);
new Body (variable.Type, variable, current_pe, statement, variable.Location), Location.Null);
var enum_type = enumerator_variable.Type;
@ -6070,23 +6115,23 @@ namespace Mono.CSharp { @@ -6070,23 +6115,23 @@ namespace Mono.CSharp {
//
// Runtime Dispose check
//
var vd = new RuntimeDispose (enumerator_variable.LocalInfo, loc);
var vd = new RuntimeDispose (enumerator_variable.LocalInfo, Location.Null);
vd.Initializer = init;
statement = new Using (vd, statement, loc);
statement = new Using (vd, statement, Location.Null);
} else {
//
// No Dispose call needed
//
this.init = new SimpleAssign (enumerator_variable, init);
this.init = new SimpleAssign (enumerator_variable, init, Location.Null);
this.init.Resolve (ec);
}
} else {
//
// Static Dispose check
//
var vd = new Using.VariableDeclaration (enumerator_variable.LocalInfo, loc);
var vd = new Using.VariableDeclaration (enumerator_variable.LocalInfo, Location.Null);
vd.Initializer = init;
statement = new Using (vd, statement, loc);
statement = new Using (vd, statement, Location.Null);
}
return statement.Resolve (ec);
@ -6107,7 +6152,7 @@ namespace Mono.CSharp { @@ -6107,7 +6152,7 @@ namespace Mono.CSharp {
bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
{
ec.Report.SymbolRelatedToPreviousError (best);
ec.Report.Warning (278, 2, loc,
ec.Report.Warning (278, 2, expr.Location,
"`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
expr.Type.GetSignatureForError (), "enumerable",
best.GetSignatureForError (), ambiguous.GetSignatureForError ());

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

@ -37,7 +37,7 @@ namespace Mono.CSharp { @@ -37,7 +37,7 @@ namespace Mono.CSharp {
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode (obj);
}
}
#if !NET_4_0
#if !NET_4_0 && !MONODROID
public class Tuple<T1, T2> : IEquatable<Tuple<T1, T2>>
{
public Tuple (T1 item1, T2 item2)

17
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/symbolwriter.cs

@ -92,11 +92,10 @@ namespace Mono.CSharp @@ -92,11 +92,10 @@ namespace Mono.CSharp
}
}
public static SourceMethodBuilder OpenMethod (ICompileUnit file, int ns_id,
IMethodDef method)
public static SourceMethodBuilder OpenMethod (ICompileUnit file, IMethodDef method)
{
if (symwriter != null)
return symwriter.OpenMethod (file, ns_id, method);
return symwriter.OpenMethod (file, -1 /* Not used */, method);
else
return null;
}
@ -125,15 +124,6 @@ namespace Mono.CSharp @@ -125,15 +124,6 @@ namespace Mono.CSharp
}
}
public static int DefineNamespace (string name, CompileUnitEntry source,
string[] using_clauses, int parent)
{
if (symwriter != null)
return symwriter.DefineNamespace (name, source, using_clauses, parent);
else
return -1;
}
public static void DefineAnonymousScope (int id)
{
if (symwriter != null)
@ -232,8 +222,7 @@ namespace Mono.CSharp @@ -232,8 +222,7 @@ namespace Mono.CSharp
if (symwriter != null) {
SourceFileEntry file = loc.SourceFile.SourceFileEntry;
int offset = GetILOffset (ig);
symwriter.MarkSequencePoint (
offset, file, loc.Row, loc.Column, loc.Hidden);
symwriter.MarkSequencePoint (offset, file, loc.Row, loc.Column, false);
}
}

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

@ -148,7 +148,7 @@ namespace Mono.CSharp @@ -148,7 +148,7 @@ namespace Mono.CSharp
if (found == null || found == p)
continue;
var tc = found.MemberDefinition as TypeContainer;
var tc = found.MemberDefinition as TypeDefinition;
if (tc != null) {
var ns = module.GlobalRootNamespace.GetNamespace (p.Namespace, false);
ns.SetBuiltinType (p);

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

@ -292,7 +292,7 @@ namespace Mono.CSharp @@ -292,7 +292,7 @@ namespace Mono.CSharp
if (IsPointer)
return ((ElementTypeSpec) this).Element.IsUnmanaged;
var ds = MemberDefinition as TypeContainer;
var ds = MemberDefinition as TypeDefinition;
if (ds != null)
return ds.IsUnmanagedType ();

68
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/visit.cs

@ -22,80 +22,50 @@ namespace Mono.CSharp @@ -22,80 +22,50 @@ namespace Mono.CSharp
}
public virtual void Visit (ModuleContainer mc)
{/*
if (mc.Delegates != null) {
foreach (TypeContainer tc in mc.Delegates) {
tc.Accept (this);
}
}*/
if (mc.Types != null) {
foreach (TypeContainer tc in mc.Types) {
tc.Accept (this);
}
{
foreach (var container in mc.Containers) {
container.Accept (this);
}
}
void VisitTypeContainer (TypeContainer tc)
void VisitTypeDefinition (TypeDefinition tc)
{
foreach (MemberCore member in tc.OrderedAllMembers) {
member.Accept (this);
}
}
protected void VisitNamespaceUsings (UsingsBag.Namespace nspace)
{
foreach (object u in nspace.usings) {
if (u is UsingsBag.Using) {
((UsingsBag.Using)u).Accept (this);
} else {
((UsingsBag.AliasUsing)u).Accept (this);
}
foreach (var container in tc.Members) {
container.Accept (this);
}
}
protected void VisitNamespaceBody (UsingsBag.Namespace nspace)
{
foreach (object member in nspace.members) {
if (member is MemberCore) {
((MemberCore)member).Accept (this);
} else {
((UsingsBag.Namespace)member).Accept (this);
}
}
}
public virtual void Visit (UsingsBag.Namespace nspace)
public virtual void Visit (NamespaceContainer ns)
{
VisitNamespaceUsings (nspace);
VisitNamespaceBody (nspace);
}
public virtual void Visit (UsingsBag.Using u)
public virtual void Visit (UsingNamespace un)
{
}
public virtual void Visit (UsingsBag.AliasUsing aliasUsing)
public virtual void Visit (UsingAliasNamespace uan)
{
}
public virtual void Visit (UsingsBag.ExternAlias externAlias)
public virtual void Visit (UsingExternAlias uea)
{
}
public virtual void Visit (Class c)
{
VisitTypeContainer (c);
VisitTypeDefinition (c);
}
public virtual void Visit (Struct s)
{
VisitTypeContainer (s);
VisitTypeDefinition (s);
}
public virtual void Visit (Interface i)
{
VisitTypeContainer (i);
VisitTypeDefinition (i);
}
public virtual void Visit (Delegate d)
@ -104,7 +74,7 @@ namespace Mono.CSharp @@ -104,7 +74,7 @@ namespace Mono.CSharp
public virtual void Visit (Enum e)
{
VisitTypeContainer (e);
VisitTypeDefinition (e);
}
public virtual void Visit (FixedField f)

31920
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/y.output

File diff suppressed because it is too large Load Diff

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

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

4
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/ConvertForeachToFor.cs

@ -41,8 +41,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -41,8 +41,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
static string GetCountProperty (IType type)
{
// if (!type.)
// return "Length";
if (type.Kind == TypeKind.Array)
return "Length";
return "Count";
}

10
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/InsertAnonymousMethodSignature.cs

@ -52,7 +52,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -52,7 +52,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
var paramType = delegateMethod.Parameters [k].Type;
sb.Append (paramType.ToString ());
sb.Append (context.CreateShortType (paramType));
sb.Append (" ");
sb.Append (delegateMethod.Parameters [k].Name);
}
@ -68,19 +68,19 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -68,19 +68,19 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
delegateType = null;
var anonymousMethodExpression = context.GetNode<AnonymousMethodExpression> ();
if (anonymousMethodExpression == null || !anonymousMethodExpression.DelegateToken.Contains (context.Location.Line, context.Location.Column) || anonymousMethodExpression.HasParameterList)
if (anonymousMethodExpression == null || !anonymousMethodExpression.DelegateToken.Contains (context.Location) || anonymousMethodExpression.HasParameterList)
return null;
IType resolvedType = null;
var parent = anonymousMethodExpression.Parent;
if (parent is AssignmentExpression) {
resolvedType = context.Resolve (((AssignmentExpression)parent).Left).Type;
} else if (parent is VariableDeclarationStatement) {
resolvedType = context.Resolve (((VariableDeclarationStatement)parent).Type).Type;
} else if (parent is VariableInitializer) {
resolvedType = context.Resolve (((VariableDeclarationStatement)parent.Parent).Type).Type;
} else if (parent is InvocationExpression) {
// TODO: handle invocations
}
if (resolvedType == null)
return null;
delegateType = resolvedType;

3
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/RemoveBackingStore.cs

@ -99,7 +99,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -99,7 +99,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
if (propertyDeclaration.Getter.Body.Statements.Count != 1)
return null;
var returnStatement = propertyDeclaration.Getter.Body.Statements.First () as ReturnStatement;
if (returnStatement == null)
return null;
var result = context.Resolve (returnStatement.Expression);
if (result == null || !(result is MemberResolveResult))
return null;

7
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/ContextAction/SplitDeclarationAndAssignment.cs

@ -61,9 +61,10 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -61,9 +61,10 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
var result = context.GetNode<VariableDeclarationStatement> ();
if (result != null && result.Variables.Count == 1 && !result.Variables.First ().Initializer.IsNull && result.Variables.First ().NameToken.Contains (context.Location.Line, context.Location.Column)) {
resolvedType = context.Resolve (result.Variables.First ().Initializer).Type.ConvertToAstType ();
if (resolvedType == null)
return null;
resolvedType = result.Type.Clone ();
// resolvedType = context.Resolve (result.Variables.First ().Initializer).Type.ConvertToAstType ();
// if (resolvedType == null)
// return null;
return result;
}
resolvedType = null;

17
src/Libraries/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/NodeOutputAction.cs

@ -62,24 +62,29 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring @@ -62,24 +62,29 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
public int Offset {
get;
set;
internal set;
}
public int Length {
get {
return EndOffset - Offset;
}
get;
internal set;
}
public int EndOffset {
get;
set;
get {
return Offset + Length;
}
}
public Segment (int offset)
{
this.Offset = offset;
}
public override string ToString ()
{
return string.Format ("[NodeOutput.Segment: Offset={0}, Length={1}, EndOffset={2}]", Offset, Length, EndOffset);
}
}
}

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

Loading…
Cancel
Save