private static async Task<bool> ExceptionDeclarationCouldBeRemoved(CodeFixContext context, SyntaxNode root, ThrowStatementSyntax originalThrowStatement) { // If "ex" from "throw ex" was the only reference to "ex", then additional modification should be made // "catch(Exception ex)" should be replaced by "catch(Exception)" var throwExIdentifier = originalThrowStatement.Expression.As(x => x as IdentifierNameSyntax); Contract.Assert(throwExIdentifier != null); var model = await context.Document.GetSemanticModelAsync(); var solution = context.Document.Project.Solution; var symbol = model.GetSymbolInfo(throwExIdentifier); Contract.Assert(symbol.Symbol != null); // Not sure this is a good idea! // TODO: talk to nikov about it! If there is an optimization for locals than everything should be fine! // Otherwise - not! // Searching within one document should be fast. Still need to check! var references = await SymbolFinder.FindReferencesAsync(symbol.Symbol, solution, ImmutableHashSet.Create(context.Document)); var locations = references.SelectMany(x => x.Locations).ToArray(); var numberOfUsages = references .SelectMany(x => x.Locations) .Select(x => root.FindToken(x.Location.SourceSpan.Start)) .Count(token => token.Parent.Parent is ThrowStatementSyntax); // TODO: code duplication with GetThrowStatementFrom! // "ex" in the "Exception ex" could be removed only if there is no any other usages. Otherwise the fix will fail. // Consider following case: // There is two usages of the "ex" in two "throw ex" statemetns. // Two different fixes would be run for both warnings. // The first fix will change the code to "catch(Exception) {throw ex; throw;}" witch is not a valid C# program return numberOfUsages == 1 && locations.Length == 1; }
private Task<Solution> RemoveRethrowAsync(Document document, SyntaxNode root, ThrowStatementSyntax throwStatement) { var newStatement = SyntaxFactory.ThrowStatement(); var newRoot = root.ReplaceNode(throwStatement, newStatement); var newDocument = document.WithSyntaxRoot(newRoot); return Task.FromResult(newDocument.Project.Solution); }
public IfThrowPrecondition(StatementSyntax ifThrowStaement, ThrowStatementSyntax throwStatement) { Contract.Requires(ifThrowStaement != null); Contract.Requires(throwStatement != null); IfThrowStaement = ifThrowStaement; ThrowStatement = throwStatement; }
public ITypeSymbol GetThrownExceptionTypeSymbol(SemanticModel semanticModel, ThrowStatementSyntax throwStatementSyntax) { SemanticModel = semanticModel; ThrowStatementSyntax = throwStatementSyntax; SyntaxNode syntaxNodeToGetTypeOf = ThrowStatementSyntax.Expression; if (syntaxNodeToGetTypeOf == null) syntaxNodeToGetTypeOf = GetCatchClaue(); if (syntaxNodeToGetTypeOf == null) return null; //Not sure this is possible.... return semanticModel.GetTypeInfo(syntaxNodeToGetTypeOf).Type; }
public static void Go(OutputWriter writer, ThrowStatementSyntax statement) { writer.WriteIndent(); writer.Write("throw "); if (statement.Expression == null) { //On just "throw" with no exception name, navigate up the stack to find the nearest catch block and insert the exception's name CatchClauseSyntax catchBlock; SyntaxNode node = statement; do catchBlock = (node = node.Parent) as CatchClauseSyntax; while (catchBlock == null); if (catchBlock == null) { throw new Exception("throw statement with no exception name, and could not locate a catch block " + Utility.Descriptor(statement)); } if (catchBlock.Declaration == null || catchBlock.Declaration.Identifier.Value == null) //Some people write code in the form catch(Exception) ...grrr writer.Write("__ex"); else { var exName = WriteIdentifierName.TransformIdentifier(catchBlock.Declaration.Identifier.Text); if (string.IsNullOrWhiteSpace(exName)) writer.Write("__ex"); else writer.Write(exName); } } else Core.Write(writer, statement.Expression); writer.Write(";\r\n"); }
/// <summary> /// Initializes a new instance of the <see cref="ThrowStatement"/> class. /// </summary> /// <param name="syntaxNode"></param> /// <param name="semanticModel"></param> public ThrowStatement(ThrowStatementSyntax syntaxNode, SemanticModel semanticModel) : base(syntaxNode, semanticModel) { }
public void Flatten(ThrowStatementSyntax node, List<FlatStatement> instructions) { if (node.Expression == null) { FlatStatement.THROW(FlatOperand.ExceptionRef()); return; } FlatOperand fop_exception = this.ResolveExpression(node.Expression, null, instructions); instructions.Add(FlatStatement.THROW(fop_exception)); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { base.VisitThrowStatement(node); this.walker.StoreVisitData(node, this.walker.ConditionalTerminates, this.walker.UnconditionalTerminates); }
private async Task <Document> RemoveThrowAsync(Document document, ThrowStatementSyntax @throw, CancellationToken ct) { return(document.WithSyntaxRoot((await document.GetSyntaxRootAsync(ct)).RemoveNode(@throw, SyntaxRemoveOptions.KeepNoTrivia))); }
public static void Analyze(SyntaxNodeAnalysisContext context, ThrowStatementSyntax throwStatement) { Analyze(context, throwStatement.Expression); }
static void ProcessThrowClause(SemanticModel semanticModel, ThrowStatementSyntax throwClause) { var thrownTypeExtractor = new ThrownTypeExtractor(); ITypeSymbol typeSymbol = thrownTypeExtractor.GetThrownExceptionTypeSymbol(semanticModel, throwClause); if (typeSymbol == null) return; if (!typeSymbol.ContainingNamespace.ToDisplayParts().Any(x => x.Kind == SymbolDisplayPartKind.NamespaceName && x.Symbol.Name.ToLowerInvariant() == "tombola")) return; var containingMethods = throwClause.AncestorsAndSelf().OfType<MethodDeclarationSyntax>(); if (containingMethods == null || containingMethods.Count() == 0) return; var containingMethod = containingMethods.Last(); if (containingMethod == null) return; if (!DoesContainingMethodDeclareExceptionType(containingMethod, typeSymbol.Name)) AddToMissingDefinitions(containingMethod, typeSymbol); }
protected override bool IsThrowStatementWithNoArgument(ThrowStatementSyntax throwNode) { Debug.Assert(throwNode != null); return(throwNode.Expression == null); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { Write("throw"); Visit(node.Expression); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { var statement = VisitSyntaxNode(node.Expression); _currentNode = new Throw(statement); }
// throw语句 public virtual void VisitThrowStatementSyntax(ThrowStatementSyntax value) { DefaultVisit(value); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { // end not connected with data curNode = builder.CreateEndNode(node); }
// // Summary: // Called when the visitor visits a ThrowStatementSyntax node. public virtual void VisitThrowStatement(ThrowStatementSyntax node);
public override void VisitThrowStatement(ThrowStatementSyntax node) { AddExpressionTerms(node.Expression, _expressions); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { base.VisitThrowStatement(node); _counter++; }
/// <inheritdoc/> public override SyntaxNode?VisitThrowStatement(ThrowStatementSyntax node) { Context.ReportDiagnostic(ThrowExpressionOrStatement, node); return(base.VisitThrowStatement(node)); }
private void BuildThrowStatement(ThrowStatementSyntax throwStatement) { BuildJumpToExitStatement(throwStatement, throwStatement.Expression); }
/// <summary> /// /// </summary> /// <param name="node"></param> /// <remarks> /// Statements will cause an AST walker to be created, thus we don't need to go further deeper in the /// tree by visiting the node. /// </remarks> public override void VisitThrowStatement(ThrowStatementSyntax node) { this.VisitStatement(node); }
private IEnumerable<ITypeSymbol> InferTypeInThrowStatement(ThrowStatementSyntax throwStatement, SyntaxToken? previousToken = null) { // If we have a position, it has to be after the 'throw' keyword. if (previousToken.HasValue && previousToken.Value != throwStatement.ThrowKeyword) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.ExceptionType()); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { }
/// <summary> /// Initializes a new instance of the <see cref="ThrowStatement"/> class. /// </summary> /// <param name="syntaxNode"></param> public ThrowStatement(ThrowStatementSyntax syntaxNode) : this(syntaxNode, null) { }
private BoundStatement BindThrow(ThrowStatementSyntax node, DiagnosticBag diagnostics) { if (node.Expression == null) { return BindThrowParts(node, diagnostics); } var binder = GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(node, binder.BindThrowParts(node, diagnostics)); }
public void Generate() { // standard using directives CompilationUnitSyntax cu = SyntaxFactory.CompilationUnit() .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System"))) .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System.Collections.Generic"))) .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System.Linq"))) .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System.Text"))) .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System.Threading.Tasks"))); NamespaceDeclarationSyntax localNamespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(directoryName)); ClassDeclarationSyntax localClass = SyntaxFactory.ClassDeclaration(Name); foreach (var member in Declarations) { switch (member.DeclarationType) { case "method": var currentMethod = member as Method; //currentMethod.Type is a string parsed from the uml diagram MethodDeclarationSyntax method = SyntaxFactory.MethodDeclaration(SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(currentMethod.Type)), currentMethod.Name); List <SyntaxToken> mods = new List <SyntaxToken>(); foreach (var modifier in currentMethod.Modifiers) { mods.Add(SyntaxFactory.ParseToken(modifier)); } method = method.AddModifiers(mods.ToArray()); SeparatedSyntaxList <ParameterSyntax> ssl = SyntaxFactory.SeparatedList <ParameterSyntax>(); foreach (var param in currentMethod.Arguments) { ParameterSyntax ps = SyntaxFactory.Parameter( new SyntaxList <AttributeListSyntax>(), new SyntaxTokenList(), SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(param.Type)), SyntaxFactory.Identifier(param.Name), null); ssl = ssl.Add(ps); } method = method.AddParameterListParameters(ssl.ToArray()); // we add an exception to the body of an otherwise empty method ThrowStatementSyntax notReady = SyntaxFactory.ThrowStatement(SyntaxFactory.ObjectCreationExpression(SyntaxFactory.IdentifierName("NotImplementedException"), SyntaxFactory.ArgumentList(), null)); method = method.AddBodyStatements(notReady); localClass = localClass.AddMembers(method); break; case "field": var currentField = member as Field; SyntaxTokenList stl = new SyntaxTokenList(); foreach (var modifier in currentField.Modifiers) { stl = stl.Add(SyntaxFactory.ParseToken(modifier)); } SeparatedSyntaxList <VariableDeclaratorSyntax> svd = SyntaxFactory.SeparatedList <VariableDeclaratorSyntax>(); svd = svd.Add(SyntaxFactory.VariableDeclarator(currentField.Name)); // currentField.Type is a string parsed from the uml diagram VariableDeclarationSyntax variable = SyntaxFactory.VariableDeclaration(SyntaxFactory.ParseTypeName(currentField.Type), svd); FieldDeclarationSyntax field = SyntaxFactory.FieldDeclaration( new SyntaxList <AttributeListSyntax>(), stl, variable ); localClass = localClass.AddMembers(field); break; } } localNamespace = localNamespace.AddMembers(localClass); cu = cu.AddMembers(localNamespace); AdhocWorkspace cw = new AdhocWorkspace(); OptionSet options = cw.Options; cw.Options.WithChangedOption(CSharpFormattingOptions.IndentBraces, true); SyntaxNode formattedNode = Formatter.Format(cu, cw, options); formattedNode.WriteTo(writer); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { if (node.Expression != null) { Visit(node.Expression, _enclosing); } }
/// <inheritdoc/> public override bool VisitThrowStatement(ThrowStatementSyntax node) { return(this.VisitStatement(node)); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { Emit <ThrowBlock, ThrowStatementSyntax>(node); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { VisitNodeToBind(node.Expression); }
internal ThrowStatementInfo(ThrowStatementSyntax node, ExpressionSyntax expression, ITypeSymbol exceptionSymbol) : base(node, expression, exceptionSymbol) { }
public override void VisitThrowStatement(ThrowStatementSyntax node) { base.VisitThrowStatement(node); this.context.ReportDiagnosticWhenActive(Diagnostic.Create(rule, node.GetLocation())); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { this.invokedThrows.Add(node); }
/// <summary> /// /// </summary> /// <param name="node"></param> public override sealed void VisitThrowStatement(ThrowStatementSyntax node) { this.OnNodeVisited(node); if (!this.traverseRootOnly) base.VisitThrowStatement(node); }
public void VisitThrowStatement(ThrowStatementSyntax node) { if (node == null) throw new ArgumentNullException("node"); node.Validate(); WriteLeadingTrivia(node); _writer.WriteIndent(); _writer.WriteKeyword(PrinterKeyword.Throw); if (node.Expression != null) { _writer.WriteSpace(); node.Expression.Accept(this); } _writer.EndStatement(); WriteTrailingTrivia(node); }
/// <inheritdoc/> public override SyntaxNode?VisitThrowStatement(ThrowStatementSyntax node) { Diagnostics.Add(ThrowExpressionOrStatement, node); return(base.VisitThrowStatement(node)); }
public ThrowStatementTranslation(ThrowStatementSyntax syntax, SyntaxTranslation parent) : base(syntax, parent) { Expression = syntax.Expression.Get<ExpressionTranslation>(this); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { currentState.Add(StateMachineThisFixer.Fix(node)); }
/// <summary> /// /// </summary> /// <param name="node"></param> public override sealed void VisitThrowStatement(ThrowStatementSyntax node) { this.OnNodeVisited(node, this.type.IsInstanceOfType(node)); base.VisitThrowStatement(node); }
public static ThrowStatementSyntax ThrowStatement(ExpressionSyntax expression = null) { var result = new ThrowStatementSyntax(); result.Expression = expression; return result; }
public ThrowStatementTranslation(ThrowStatementSyntax syntax, SyntaxTranslation parent) : base(syntax, parent) { Expression = syntax.Expression.Get <ExpressionTranslation>(this); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { base.VisitThrowStatement(node); var thrown = node.Expression; if (thrown != null) // it can be null for a rethrow (throw;) expression { bool rethrowing = IsRethrowOfCaughtException(thrown); var typeInfo = _semanticModel.GetTypeInfo(thrown); // we should never really be throwing weakly typed expressions, so if we // see such a thing, drill in to check if we can learn more if (typeInfo.Type.Name == "Exception") { // check if the expression is a call to one of our methods (throw Util.BlahBlahBlah): // if so, it will get picked up in the ObjectCreationExpression clause, so we don't // need to report the weak type if (!rethrowing && IsObtainedFromFactory(thrown)) { return; } // we can't prove a stronger type, so dump some information to help us investigate // further in case we can improve the tool var span = thrown.GetLocation().GetLineSpan(); System.Diagnostics.Debug.WriteLine($">>> {span.Path}: {span.StartLinePosition.Line}"); System.Diagnostics.Debug.WriteLine($">>> {thrown.ToString()}"); } _thrownExceptionTypeNames.Add(typeInfo.Type.Name + (rethrowing ? " - rethrown" : "")); } }
public virtual void VisitThrowStatement(ThrowStatementSyntax node) => DefaultVisit(node);
private BoundThrowStatement BindThrow(ThrowStatementSyntax node, DiagnosticBag diagnostics) { BoundExpression boundExpr = null; bool hasErrors = false; ExpressionSyntax exprSyntax = node.Expression; if (exprSyntax != null) { boundExpr = BindValue(exprSyntax, diagnostics, BindValueKind.RValue); // SPEC VIOLATION: The spec requires the thrown exception to have a type, and that the type // be System.Exception or derived from System.Exception. (Or, if a type parameter, to have // an effective base class that meets that criterion.) However, we allow the literal null // to be thrown, even though it does not meet that criterion and will at runtime always // produce a null reference exception. if (!boundExpr.IsLiteralNull()) { var type = boundExpr.Type; // If the expression is a lambda, anonymous method, or method group then it will // have no compile-time type; give the same error as if the type was wrong. if ((object)type == null || !type.IsErrorType() && !Compilation.IsExceptionType(type.EffectiveTypeNoUseSiteDiagnostics)) { diagnostics.Add(ErrorCode.ERR_BadExceptionType, exprSyntax.Location); hasErrors = true; } } } else if (!this.Flags.Includes(BinderFlags.InCatchBlock)) { diagnostics.Add(ErrorCode.ERR_BadEmptyThrow, node.ThrowKeyword.GetLocation()); hasErrors = true; } else if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { // There's a special error code for a rethrow in a finally clause in a catch clause. // Best guess interpretation: if an exception occurs within the nested try block // (i.e. the one in the catch clause, to which the finally clause is attached), // then it's not clear whether the runtime will try to rethrow the "inner" exception // or the "outer" exception. For this reason, the case is disallowed. // At this point, we know that we're within both a catch block and a finally block, // but we don't know which is nested within the other. We can't walk up the syntax // tree because we might be binding speculatively. Instead, we'll walk up the binder // chain and see which flag gets dropped first. Binder curr = this; while (curr.Flags.Includes(BinderFlags.InFinallyBlock | BinderFlags.InCatchBlock)) { curr = curr.Next; } if (curr.Flags.Includes(BinderFlags.InCatchBlock)) { // The finally block is below the catch block in the binder chain, so it // musted be nested within the catch block syntactically. diagnostics.Add(ErrorCode.ERR_BadEmptyThrowInFinally, node.ThrowKeyword.GetLocation()); hasErrors = true; } else { // Can't have added both flags in the same binder. Debug.Assert(curr.Flags.Includes(BinderFlags.InFinallyBlock)); } } return new BoundThrowStatement(node, boundExpr, hasErrors); }
public virtual void VisitThrowStatement(ThrowStatementSyntax node) { DefaultVisit(node); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { if (node.Expression != null) { var patternBinder = new PatternVariableBinder(node, _enclosing); AddToMap(node, patternBinder); Visit(node.Expression, patternBinder); } }
public override void VisitThrowStatement(ThrowStatementSyntax node) { LogicalLineCount++; base.VisitThrowStatement(node); }
private BoundThrowStatement BindThrowParts(ThrowStatementSyntax node, DiagnosticBag diagnostics) { BoundExpression boundExpr = null; bool hasErrors = false; ExpressionSyntax exprSyntax = node.Expression; if (exprSyntax != null) { boundExpr = BindThrownExpression(exprSyntax, diagnostics, ref hasErrors); } else if (!this.Flags.Includes(BinderFlags.InCatchBlock)) { diagnostics.Add(ErrorCode.ERR_BadEmptyThrow, node.ThrowKeyword.GetLocation()); hasErrors = true; } else if (this.Flags.Includes(BinderFlags.InNestedFinallyBlock)) { // There's a special error code for a rethrow in a finally clause in a catch clause. // Best guess interpretation: if an exception occurs within the nested try block // (i.e. the one in the catch clause, to which the finally clause is attached), // then it's not clear whether the runtime will try to rethrow the "inner" exception // or the "outer" exception. For this reason, the case is disallowed. diagnostics.Add(ErrorCode.ERR_BadEmptyThrowInFinally, node.ThrowKeyword.GetLocation()); hasErrors = true; } return new BoundThrowStatement(node, boundExpr, hasErrors); }
public override void VisitThrowStatement(ThrowStatementSyntax node) { currentState.Add(YieldThisFixer.Fix(node)); }
public override SyntaxNode VisitThrowStatement(ThrowStatementSyntax node) { if (node.Expression == null) { this.AppendCompileIssue(node, IssueType.Error, IssueId.ThrowNothing); } else { _output.Write(node.ThrowKeyword, "throw "); Visit(node.Expression); } return node; }
public override void VisitThrowStatement(ThrowStatementSyntax node) { base.VisitThrowStatement(node); ReportDiagnostic(AddDiagnostic, DiagnosticDescriptor, node); }
private BoundThrowStatement BindThrow(ThrowStatementSyntax node, DiagnosticBag diagnostics) { BoundExpression boundExpr = null; bool hasErrors = false; ExpressionSyntax exprSyntax = node.Expression; if (exprSyntax != null) { boundExpr = BindValue(exprSyntax, diagnostics, BindValueKind.RValue); // SPEC VIOLATION: The spec requires the thrown exception to have a type, and that the type // be System.Exception or derived from System.Exception. (Or, if a type parameter, to have // an effective base class that meets that criterion.) However, we allow the literal null // to be thrown, even though it does not meet that criterion and will at runtime always // produce a null reference exception. if (!boundExpr.IsLiteralNull()) { var type = boundExpr.Type; // If the expression is a lambda, anonymous method, or method group then it will // have no compile-time type; give the same error as if the type was wrong. HashSet<DiagnosticInfo> useSiteDiagnostics = null; if ((object)type == null || !type.IsErrorType() && !Compilation.IsExceptionType(type.EffectiveType(ref useSiteDiagnostics), ref useSiteDiagnostics)) { diagnostics.Add(ErrorCode.ERR_BadExceptionType, exprSyntax.Location); hasErrors = true; diagnostics.Add(exprSyntax, useSiteDiagnostics); } } } else if (!this.Flags.Includes(BinderFlags.InCatchBlock)) { diagnostics.Add(ErrorCode.ERR_BadEmptyThrow, node.ThrowKeyword.GetLocation()); hasErrors = true; } else if (this.Flags.Includes(BinderFlags.InNestedFinallyBlock)) { // There's a special error code for a rethrow in a finally clause in a catch clause. // Best guess interpretation: if an exception occurs within the nested try block // (i.e. the one in the catch clause, to which the finally clause is attached), // then it's not clear whether the runtime will try to rethrow the "inner" exception // or the "outer" exception. For this reason, the case is disallowed. diagnostics.Add(ErrorCode.ERR_BadEmptyThrowInFinally, node.ThrowKeyword.GetLocation()); hasErrors = true; } return new BoundThrowStatement(node, boundExpr, hasErrors); }
protected override object VisitThrowStatement(ThrowStatementSyntax node) { return(base.VisitThrowStatement(node)); }