Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpAstResolver.cs @ 11807

Last change on this file since 11807 was 11700, checked in by jkarder, 10 years ago

#2077: created branch and added first version

File size: 10.7 KB
Line 
1// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy of this
4// software and associated documentation files (the "Software"), to deal in the Software
5// without restriction, including without limitation the rights to use, copy, modify, merge,
6// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
7// to whom the Software is furnished to do so, subject to the following conditions:
8//
9// The above copyright notice and this permission notice shall be included in all copies or
10// substantial portions of the Software.
11//
12// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
13// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
15// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
17// DEALINGS IN THE SOFTWARE.
18
19using System;
20using System.Diagnostics;
21using System.Threading;
22using ICSharpCode.NRefactory.CSharp.TypeSystem;
23using ICSharpCode.NRefactory.Semantics;
24using ICSharpCode.NRefactory.TypeSystem;
25
26namespace ICSharpCode.NRefactory.CSharp.Resolver
27{
28  /// <summary>
29  /// Resolves C# AST nodes.
30  /// </summary>
31  /// <remarks>This class is thread-safe.</remarks>
32  public class CSharpAstResolver
33  {
34    readonly CSharpResolver initialResolverState;
35    readonly AstNode rootNode;
36    readonly CSharpUnresolvedFile unresolvedFile;
37    readonly ResolveVisitor resolveVisitor;
38    bool resolverInitialized;
39   
40    /// <summary>
41    /// Creates a new C# AST resolver.
42    /// Use this overload if you are resolving within a complete C# file.
43    /// </summary>
44    /// <param name="compilation">The current compilation.</param>
45    /// <param name="syntaxTree">The syntax tree to be resolved.</param>
46    /// <param name="unresolvedFile">
47    /// Optional: Result of <see cref="SyntaxTree.ToTypeSystem()"/> for the file being resolved.
48    /// <para>
49    /// This is used for setting up the context on the resolver. The unresolved file must be registered in the compilation.
50    /// </para>
51    /// <para>
52    /// When a unresolvedFile is specified, the resolver will use the member's StartLocation/EndLocation to identify
53    /// member declarations in the AST with members in the type system.
54    /// When no unresolvedFile is specified (<c>null</c> value for this parameter), the resolver will instead compare the
55    /// member's signature in the AST with the signature in the type system.
56    /// </para>
57    /// </param>
58    public CSharpAstResolver(ICompilation compilation, SyntaxTree syntaxTree, CSharpUnresolvedFile unresolvedFile = null)
59    {
60      if (compilation == null)
61        throw new ArgumentNullException("compilation");
62      if (syntaxTree == null)
63        throw new ArgumentNullException("syntaxTree");
64      this.initialResolverState = new CSharpResolver(compilation);
65      this.rootNode = syntaxTree;
66      this.unresolvedFile = unresolvedFile;
67      this.resolveVisitor = new ResolveVisitor(initialResolverState, unresolvedFile);
68    }
69   
70    /// <summary>
71    /// Creates a new C# AST resolver.
72    /// Use this overload if you are resolving code snippets (not necessarily complete files).
73    /// </summary>
74    /// <param name="resolver">The resolver state at the root node (to be more precise: just outside the root node).</param>
75    /// <param name="rootNode">The root node of the tree to be resolved.</param>
76    /// <param name="unresolvedFile">
77    /// Optional: Result of <see cref="SyntaxTree.ToTypeSystem()"/> for the file being resolved.
78    /// <para>
79    /// This is used for setting up the context on the resolver. The unresolved file must be registered in the compilation.
80    /// </para>
81    /// <para>
82    /// When a unresolvedFile is specified, the resolver will use the member's StartLocation/EndLocation to identify
83    /// member declarations in the AST with members in the type system.
84    /// When no unresolvedFile is specified (<c>null</c> value for this parameter), the resolver will instead compare the
85    /// member's signature in the AST with the signature in the type system.
86    /// </para>
87    /// </param>
88    public CSharpAstResolver(CSharpResolver resolver, AstNode rootNode, CSharpUnresolvedFile unresolvedFile = null)
89    {
90      if (resolver == null)
91        throw new ArgumentNullException("resolver");
92      if (rootNode == null)
93        throw new ArgumentNullException("rootNode");
94      this.initialResolverState = resolver;
95      this.rootNode = rootNode;
96      this.unresolvedFile = unresolvedFile;
97      this.resolveVisitor = new ResolveVisitor(initialResolverState, unresolvedFile);
98    }
99   
100    /// <summary>
101    /// Gets the type resolve context for the root resolver.
102    /// </summary>
103    public CSharpTypeResolveContext TypeResolveContext {
104      get { return initialResolverState.CurrentTypeResolveContext; }
105    }
106   
107    /// <summary>
108    /// Gets the compilation for this resolver.
109    /// </summary>
110    public ICompilation Compilation {
111      get { return initialResolverState.Compilation; }
112    }
113   
114    /// <summary>
115    /// Gets the root node for which this CSharpAstResolver was created.
116    /// </summary>
117    public AstNode RootNode {
118      get { return rootNode; }
119    }
120   
121    /// <summary>
122    /// Gets the unresolved file used by this CSharpAstResolver.
123    /// Can return null.
124    /// </summary>
125    public CSharpUnresolvedFile UnresolvedFile {
126      get { return unresolvedFile; }
127    }
128   
129    /// <summary>
130    /// Applies a resolver navigator. This will resolve the nodes requested by the navigator, and will inform the
131    /// navigator of the results.
132    /// This method must be called as the first operation on the CSharpAstResolver, it is invalid to apply a navigator
133    /// after a portion of the file was already resolved.
134    /// </summary>
135    public void ApplyNavigator(IResolveVisitorNavigator navigator, CancellationToken cancellationToken = default(CancellationToken))
136    {
137      if (navigator == null)
138        throw new ArgumentNullException("navigator");
139     
140      lock (resolveVisitor) {
141        if (resolverInitialized)
142          throw new InvalidOperationException("Applying a navigator is only valid as the first operation on the CSharpAstResolver.");
143       
144        resolverInitialized = true;
145        resolveVisitor.cancellationToken = cancellationToken;
146        resolveVisitor.SetNavigator(navigator);
147        try {
148          resolveVisitor.Scan(rootNode);
149        } finally {
150          resolveVisitor.SetNavigator(null);
151          resolveVisitor.cancellationToken = CancellationToken.None;
152        }
153      }
154    }
155   
156    /// <summary>
157    /// Resolves the specified node.
158    /// </summary>
159    public ResolveResult Resolve(AstNode node, CancellationToken cancellationToken = default(CancellationToken))
160    {
161      if (node == null || node.IsNull || IsUnresolvableNode(node))
162        return ErrorResolveResult.UnknownError;
163      lock (resolveVisitor) {
164        InitResolver();
165        resolveVisitor.cancellationToken = cancellationToken;
166        try {
167          ResolveResult rr = resolveVisitor.GetResolveResult(node);
168          if (rr == null)
169            Debug.Fail (node.GetType () + " resolved to null.", node.StartLocation + ":'" + node.ToString () + "'");
170          return rr;
171        } finally {
172          resolveVisitor.cancellationToken = CancellationToken.None;
173        }
174      }
175    }
176   
177    void InitResolver()
178    {
179      if (!resolverInitialized) {
180        resolverInitialized = true;
181        resolveVisitor.Scan(rootNode);
182      }
183    }
184   
185    /// <summary>
186    /// Gets the resolver state immediately before the specified node.
187    /// That is, if the node is a variable declaration, the returned state will not contain the newly declared variable.
188    /// </summary>
189    public CSharpResolver GetResolverStateBefore(AstNode node, CancellationToken cancellationToken = default(CancellationToken))
190    {
191      if (node == null || node.IsNull)
192        throw new ArgumentNullException("node");
193      lock (resolveVisitor) {
194        InitResolver();
195        resolveVisitor.cancellationToken = cancellationToken;
196        try {
197          CSharpResolver resolver = resolveVisitor.GetResolverStateBefore(node);
198          Debug.Assert(resolver != null);
199          return resolver;
200        } finally {
201          resolveVisitor.cancellationToken = CancellationToken.None;
202        }
203      }
204    }
205   
206    /// <summary>
207    /// Gets the resolver state immediately after the specified node.
208    /// That is, if the node is a variable declaration, the returned state will include the newly declared variable.
209    /// </summary>
210    public CSharpResolver GetResolverStateAfter(AstNode node, CancellationToken cancellationToken = default(CancellationToken))
211    {
212      if (node == null || node.IsNull)
213        throw new ArgumentNullException("node");
214      while (node != null && IsUnresolvableNode(node))
215        node = node.Parent;
216      if (node == null)
217        return initialResolverState;
218      lock (resolveVisitor) {
219        InitResolver();
220        resolveVisitor.cancellationToken = cancellationToken;
221        try {
222          CSharpResolver resolver = resolveVisitor.GetResolverStateAfter(node);
223          Debug.Assert(resolver != null);
224          return resolver;
225        } finally {
226          resolveVisitor.cancellationToken = CancellationToken.None;
227        }
228      }
229    }
230   
231    ResolveVisitor.ConversionWithTargetType GetConversionWithTargetType(Expression expr, CancellationToken cancellationToken)
232    {
233      if (expr == null || expr.IsNull)
234        return new ResolveVisitor.ConversionWithTargetType(Conversion.None, SpecialType.UnknownType);
235      lock (resolveVisitor) {
236        InitResolver();
237        resolveVisitor.cancellationToken = cancellationToken;
238        try {
239          return resolveVisitor.GetConversionWithTargetType(expr);
240        } finally {
241          resolveVisitor.cancellationToken = CancellationToken.None;
242        }
243      }
244    }
245   
246    /// <summary>
247    /// Gets the expected type for the specified node. This is the type that a node is being converted to.
248    /// </summary>
249    public IType GetExpectedType(Expression expr, CancellationToken cancellationToken = default(CancellationToken))
250    {
251      return GetConversionWithTargetType(expr, cancellationToken).TargetType;
252    }
253   
254    /// <summary>
255    /// Gets the conversion that is being applied to the specified expression.
256    /// </summary>
257    public Conversion GetConversion(Expression expr, CancellationToken cancellationToken = default(CancellationToken))
258    {
259      return GetConversionWithTargetType(expr, cancellationToken).Conversion;
260    }
261   
262    /// <summary>
263    /// Gets whether the specified node is unresolvable.
264    /// </summary>
265    public static bool IsUnresolvableNode(AstNode node)
266    {
267      if (node == null)
268        throw new ArgumentNullException("node");
269      if (node.NodeType == NodeType.Token) {
270        // Most tokens cannot be resolved, but there are a couple of special cases:
271        if (node.Parent is QueryClause && node is Identifier) {
272          return false;
273        } else if (node.Role == Roles.Identifier) {
274          return !(node.Parent is ForeachStatement || node.Parent is CatchClause);
275        }
276        return true;
277      }
278      return (node.NodeType == NodeType.Whitespace || node is ArraySpecifier);
279    }
280  }
281}
Note: See TracBrowser for help on using the repository browser.