private void Remove([NotNull] IIfStatement ifStatementToRemove, [NotNull] IDictionary <Location, IIfStatement> ifStatements) { Location location = ifStatementToRemove.GetLocationForKeyword(); ifStatements.Remove(location); }
private ElseClauseSyntax BuildElseSyntax(IIfStatement itemAsT) { // Because we reversed the list, inner is first, inner to outer required for this approach var elses = itemAsT.Elses.Reverse(); var lastItem = itemAsT; ElseClauseSyntax elseClause = null; foreach (var nestedElse in elses) { var statement = GetStatement(nestedElse); var elseIf = nestedElse as IElseIfStatement; if (elseIf != null) { // build if statement and put in else clause statement = SyntaxFactory.IfStatement(GetCondition(elseIf), statement) .WithElse(elseClause); statement = BuildSyntaxHelpers.AttachWhitespace(statement, nestedElse.Whitespace2Set, WhitespaceLookup); } var newElseClause = SyntaxFactory.ElseClause(statement); newElseClause = BuildSyntaxHelpers.AttachWhitespace(newElseClause, nestedElse.Whitespace2Set, WhitespaceLookup); elseClause = newElseClause; lastItem = itemAsT; } return(elseClause); }
private bool TryDecomposeIfCondition( IIfStatement ifStatement, out ISymbol localOrParameter) { localOrParameter = null; var condition = ifStatement.Condition; var binaryOperator = condition as IBinaryOperatorExpression; if (binaryOperator == null) { return(false); } if (binaryOperator.GetSimpleBinaryOperationKind() != SimpleBinaryOperationKind.Equals) { return(false); } if (IsNull(binaryOperator.LeftOperand)) { return(TryGetLocalOrParameterSymbol( binaryOperator.RightOperand, out localOrParameter)); } if (IsNull(binaryOperator.RightOperand)) { return(TryGetLocalOrParameterSymbol( binaryOperator.LeftOperand, out localOrParameter)); } return(false); }
private IAccessor CreateSetter(IConstructLanguage language, string propertyName, IFieldDeclaration field) { string propertyChangedName = language.Name == LanguageNames.CSharp ? "OnPropertyChanged" : "RaisePropertyChangedEvent"; IMethodInvocation onPropertyChanged = language.MethodInvocation(language.None <IExpression>(), language.Identifier(propertyChangedName), language.None <ITypeArguments>(), language.Arguments( language.Argument(language.StringLiteral(propertyName)))); IMemberAccess fieldUsage = language.MemberAccess(language.None <IExpression>(), field.Identifier); IExpression valueUsage = language.Expression("value"); IStatement assignment = language.AssignmentStatement(fieldUsage, valueUsage); IIfStatement ifStatement = language.IfStatement( language.BinaryExpression(fieldUsage, Operator.NotEqual, valueUsage), language.Block(assignment, language.ExpressionStatement(onPropertyChanged))); IAccessor setter = language.Setter(language.Block(ifStatement)); return(setter); }
public override void VisitIfStatement(IIfStatement stmt, IList <IStatement> body) { if (IsTargetMatch(stmt, CompletionCase.EmptyCompletionBefore)) { body.Add(EmptyCompletionExpression); } var ifElseBlock = new IfElseBlock { Condition = _exprVisitor.ToSimpleExpression(stmt.Condition, body) ?? new UnknownExpression() }; if (IsTargetMatch(stmt, CompletionCase.InBody)) { ifElseBlock.Then.Add(EmptyCompletionExpression); } if (IsTargetMatch(stmt, CompletionCase.InElse)) { ifElseBlock.Else.Add(EmptyCompletionExpression); } if (stmt.Then != null) { stmt.Then.Accept(this, ifElseBlock.Then); } if (stmt.Else != null) { stmt.Else.Accept(this, ifElseBlock.Else); } body.Add(ifElseBlock); if (IsTargetMatch(stmt, CompletionCase.EmptyCompletionAfter)) { body.Add(EmptyCompletionExpression); } }
private bool TryDecomposeIfCondition( IIfStatement ifStatement, out ISymbol localOrParameter) { localOrParameter = null; var condition = ifStatement.Condition; if (!(condition is IBinaryOperatorExpression binaryOperator)) { return(false); } if (binaryOperator.OperatorKind != BinaryOperatorKind.Equals) { return(false); } if (IsNull(binaryOperator.LeftOperand)) { return(TryGetLocalOrParameterSymbol( binaryOperator.RightOperand, out localOrParameter)); } if (IsNull(binaryOperator.RightOperand)) { return(TryGetLocalOrParameterSymbol( binaryOperator.LeftOperand, out localOrParameter)); } return(false); }
private static bool ValueIsAccessed(SemanticModel semanticModel, IIfStatement ifOperation, IBlockStatement containingBlock, ISymbol localOrParameter, IExpressionStatement expressionStatement, IAssignmentExpression assignmentExpression) { var statements = containingBlock.Statements; var ifOperationIndex = statements.IndexOf(ifOperation); var expressionStatementIndex = statements.IndexOf(expressionStatement); if (expressionStatementIndex > ifOperationIndex + 1) { // There are intermediary statements between the check and the assignment. // Make sure they don't try to access the local. var dataFlow = semanticModel.AnalyzeDataFlow( statements[ifOperationIndex + 1].Syntax, statements[expressionStatementIndex - 1].Syntax); if (dataFlow.ReadInside.Contains(localOrParameter) || dataFlow.WrittenInside.Contains(localOrParameter)) { return(true); } } // Also, have to make sure there is no read/write of the local/parameter on the left // of the assignment. For example: map[val.Id] = val; var exprDataFlow = semanticModel.AnalyzeDataFlow(assignmentExpression.Target.Syntax); return(exprDataFlow.ReadInside.Contains(localOrParameter) || exprDataFlow.WrittenInside.Contains(localOrParameter)); }
public override void VisitIfStatement <TExpression, TStatement>(IIfStatement <TExpression, TStatement> ifStatement) { Value = new Statement() { IfStatement = new IfStatementFactory(ifStatement).Value }; }
public IfElseIfConstructAnalyzer([NotNull] IfStatementAnalyzer owner, [NotNull] IIfStatement topIfStatement) { this.owner = owner; topIfKeywordLocation = topIfStatement.GetLocationForKeyword(); ifStatement = topIfStatement; }
public override void VisitIfStatement([NotNull] IIfStatement operation) { Location location = operation.GetLocationForKeyword(); CollectedStatements.Add(location, operation); base.VisitIfStatement(operation); }
private void AnalyzeTopIfStatement() { IIfStatement ifStatement = ConsumeNextIfStatement(); if (IsIfElseIfConstruct(ifStatement)) { AnalyzeIfElseIfConstruct(ifStatement); } }
public static void VisitIfStatementChildren <TExpression, TStatement>( IIfStatement <TExpression, TStatement> ifStatement, IGenericStatementVisitor visitor) where TExpression : IExpression where TStatement : IStatement { VisitIfNotNull(ifStatement.ThenStatement, visitor); VisitIfNotNull(ifStatement.ElseStatement, visitor); }
public override void VisitIfStatement(IIfStatement operation) { LogString(nameof(IIfStatement)); LogCommonPropertiesAndNewLine(operation); Visit(operation.Condition, "Condition"); Visit(operation.IfTrueStatement); Visit(operation.IfFalseStatement); }
private IfThrowPrecondition(IIfStatement ifStatement, PredicateExpression predicateExpression, Message message, IClrTypeName exceptionTypeName) : base(ifStatement, predicateExpression, message) { Contract.Requires(ifStatement != null); Contract.Requires(exceptionTypeName != null); _ifStatement = ifStatement; _exceptionTypeName = exceptionTypeName; }
private void AnalyzeTopIfStatement() { IIfStatement ifStatement = ConsumeNextIfStatement(); if (IsIfElseIfConstruct(ifStatement)) { var analyzer = new IfElseIfConstructAnalyzer(this, ifStatement); analyzer.Analyze(); } }
private static IThrowStatement ParseThrowStatement(IIfStatement ifStatement) { if (ifStatement.Then is IThrowStatement) return ifStatement.Then as IThrowStatement; return ifStatement.Then .With(x => x as IBlock) .With(x => x.Statements.FirstOrDefault(s => s is IThrowStatement)) .Return(x => x as IThrowStatement); }
private IfThrowPrecondition(IIfStatement ifStatement, PredicateExpression predicateExpression, Message message, IClrTypeName exceptionTypeName) : base(ifStatement, predicateExpression, message) { Contract.Requires(ifStatement != null); Contract.Requires(exceptionTypeName != null); _ifStatement = ifStatement; _exceptionTypeName = exceptionTypeName; }
public void Generate(IIfStatement statement) { Spit("if("); Generate(statement.condition); Spit("){"); foreach (var st in statement.statements.EmptyIfNull()) { Generate(st); } Spit("}"); }
private static IThrowStatement ParseThrowStatement(IIfStatement ifStatement) { if (ifStatement.Then is IThrowStatement) { return(ifStatement.Then as IThrowStatement); } return(ifStatement.Then .With(x => x as IBlock) .With(x => x.Statements.FirstOrDefault(s => s is IThrowStatement)) .Return(x => x as IThrowStatement)); }
/// <inheritdoc /> public override Expression VisitIfStatement(IIfStatement operation, LocalBinder argument) { if (operation.IfFalseStatement != null) { return(Expression.IfThenElse( operation.Condition.Accept(this, argument), operation.IfTrueStatement.Accept(this, argument), operation.IfFalseStatement.Accept(this, argument) )); } return(Expression.IfThen( operation.Condition.Accept(this, argument), operation.IfTrueStatement.Accept(this, argument) )); }
public static IList<IFieldElement> GetDisposableFieldsThatHaveNotBeenDisposed(ScopeResolveResult resolveResult, ISourceFile scope, IClassElement iClassElement, out IIfStatement parentIfDisposing) { parentIfDisposing = null; IList<IFieldElement> disposableFields = new List<IFieldElement>(); foreach (IElement child in iClassElement.AllChildren) { if (child.FirstFile == null) continue; // fix for partial classes if (child.FirstFile.Name != scope.Name) continue; IFieldElement iBaseVariable = child as IFieldElement; if (iBaseVariable != null) { if (CanAnalyseAsDisposable(iBaseVariable) && iBaseVariable.Is("System.IDisposable") && !IsDisposed(resolveResult, iClassElement, iBaseVariable)) disposableFields.Add(iBaseVariable); } else if (parentIfDisposing == null) { IMethodElement iMethodElement = child as IMethodElement; if (iMethodElement != null && iMethodElement.Name == STR_Dispose && iMethodElement.Parameters.Count == 1) { string paramName = iMethodElement.Parameters[0].Name; foreach (IElement potentialStatement in iMethodElement.AllChildren) { IIfStatement iIfStatement = potentialStatement as IIfStatement; if (iIfStatement != null) { IExpression condition = iIfStatement.Condition; if (condition != null && (condition.Name == paramName || (condition is ILogicalOperationExpression && (condition as ILogicalOperationExpression).LeftSide.Name == paramName))) { // We have found the "if (disposing)" block of code! parentIfDisposing = iIfStatement; break; } } } } } } return disposableFields; }
private static IMethodDeclaration CreateCSInvocator(IEventDeclaration eventDeclaration, IModifiers modifiers, IList <IArgument> arguments, IList <IParameter> parameters, IConstructLanguage language) { IVariableDeclaration variable = language.Variable( eventDeclaration.TypeName, language.VariableAccess(eventDeclaration.Identifier)); NamingPolicy variablesNamingPolicy = variable.PrimaryNamingPolicy(eventDeclaration.FileModel.UserSettings); string variableName = variablesNamingPolicy.ChangeNameAccordingToPolicy("on" + eventDeclaration.Identifier.Name, eventDeclaration.SolutionModel); variable.Identifier = language.Identifier(variableName); IIfStatement ifStatement = language.IfStatement( language.BinaryExpression( language.VariableAccess(variable.Identifier), Operator.NotEqual, language.New <INull>()), language.Block( language.ExpressionStatement( language.DelegateInvocation( language.VariableAccess(variable.Identifier), language.Arguments(arguments))))); IMethodDeclaration method = language.Method( language.None <IDocComment>(), language.None <IAttributes>(), modifiers, language.TypeName(eventDeclaration.VoidTypeAtThisLocation()), language.None <IMethodTypeParameters>(), language.Parameters(parameters), language.Block( variable, ifStatement)); NamingPolicy methodsNamingPolicy = method.PrimaryNamingPolicy(eventDeclaration.FileModel.UserSettings); string methodName = methodsNamingPolicy.ChangeNameAccordingToPolicy("on" + eventDeclaration.Identifier.ToUpperFirstLetter().Name, eventDeclaration.SolutionModel); method.Identifier = language.Identifier(methodName); return(method); }
public override void Execute(SolutionModel solutionModel, SelectionContext context) { FileModel fileModel; CodeSpan selection; if (!solutionModel.IsEditorSelection(context, out fileModel, out selection)) { return; } IPropertyDeclaration propertyDeclaration = fileModel.InnerMost <IPropertyDeclaration>(selection); if (IsFieldBackedPropertyWithSetterInsideClass(propertyDeclaration) && EnclosingClassImplementsINotifyPropertyChanged(propertyDeclaration)) { IConstructLanguage language = propertyDeclaration.Language; string methodInvocationName = language.Name == LanguageNames.CSharp ? "OnPropertyChanged" : "RaisePropertyChangedEvent"; IMethodInvocation methodInvocation = language.MethodInvocation( language.None <IExpression>(), language.Identifier(methodInvocationName), language.None <ITypeArguments>(), language.Arguments( language.Argument(language.StringLiteral(propertyDeclaration.Identifier.Name)))); IAccessor setter = propertyDeclaration.Setter(); List <IStatement> ifBlockStatements = new List <IStatement>(setter.Block.ChildStatements); ifBlockStatements.Add(language.ExpressionStatement(methodInvocation)); IIfStatement ifStatement = language.IfStatement( language.BinaryExpression( language.MemberAccess(language.None <IExpression>(), propertyDeclaration.BackingField().Identifier), Operator.NotEqual, language.Expression("value")), language.Block(ifBlockStatements)); IBlock newBlock = language.Block(ifStatement); setter.Block = newBlock; } }
private bool TryFindAssignmentExpression( IBlockStatement containingBlock, IIfStatement ifOperation, ISymbol localOrParameter, out IExpressionStatement expressionStatement, out IAssignmentExpression assignmentExpression) { var ifOperationIndex = containingBlock.Statements.IndexOf(ifOperation); // walk forward until we find an assignment of this local/parameter into // something else. for (var i = ifOperationIndex + 1; i < containingBlock.Statements.Length; i++) { expressionStatement = containingBlock.Statements[i] as IExpressionStatement; if (expressionStatement == null) { continue; } assignmentExpression = expressionStatement.Expression as IAssignmentExpression; if (assignmentExpression == null) { continue; } ISymbol assignmentValue; if (!TryGetLocalOrParameterSymbol(assignmentExpression.Value, out assignmentValue)) { continue; } if (!Equals(localOrParameter, assignmentValue)) { continue; } return(true); } expressionStatement = null; assignmentExpression = null; return(false); }
protected CognitiveComplexityHintBase(ITreeNode node, DocumentOffset offset, int value) { _node = node; _offset = offset; Value = value; Description = node switch { IWhileStatement _ => "While-Statement (increases nesting)", ISwitchStatement _ => "Switch-Statement (increases nesting)", IDoStatement _ => "Do-While-Statement (increases nesting)", IIfStatement _ => "If-Statement (increases nesting)", IForStatement _ => "For-Statement (increases nesting)", IForeachStatement _ => "Foreach-Statement (increases nesting)", ICatchClause _ => "Catch-Clause (increases nesting)", IGotoStatement _ => "Goto-Statement", IBreakStatement _ => "Break-Statement", IConditionalOrExpression _ => "First/alternating conditional Expression", IConditionalAndExpression _ => "First/alternating conditional Expression", ICSharpStatement _ => "If-Statement (increases nesting)", ICSharpExpression _ => "Recursive Call", _ => throw new NotSupportedException(node.GetType().FullName) }; }
public override void VisitIfStatement <TExpression, TStatement>(IIfStatement <TExpression, TStatement> ifStatement) { Steps.Add(new WriteIfKeyword()); Steps.Add(new WriteWhitespace()); Steps.Add(new WriteStartParenthesis()); Steps.Add(new WriteExpression <TExpression>(ifStatement.Condition)); Steps.Add(new WriteEndParenthesis()); Steps.AddIndentedStatementSteps(ifStatement.ThenStatement); if (ifStatement.ElseStatement != null) { Steps.Add(new WriteIndentedNewLine()); Steps.Add(new WriteElseKeyword()); if (ifStatement.ElseStatement is IIfStatement) { Steps.Add(new WriteWhitespace()); Steps.Add(new WriteStatement <TStatement>(ifStatement.ElseStatement)); } else { Steps.AddIndentedStatementSteps(ifStatement.ElseStatement); } } }
private void AnalyzeIfElseIfConstruct([NotNull] IIfStatement topIfStatement) { Location topIfKeywordLocation = topIfStatement.GetLocationForKeyword(); IIfStatement ifStatement = topIfStatement; while (true) { context.CancellationToken.ThrowIfCancellationRequested(); IOperation falseBlock = ifStatement.IfFalseStatement; if (falseBlock == null) { // no else clause context.ReportDiagnostic(Diagnostic.Create(Rule, topIfKeywordLocation)); Remove(ifStatement, ifStatementsLeftToAnalyze); break; } var ifElseStatement = falseBlock as IIfStatement; if (ifElseStatement != null) { // else-if Remove(ifElseStatement, ifStatementsLeftToAnalyze); ifStatement = ifElseStatement; } else { // unconditional else break; } } }
public IfStatementCompiler(IIfStatement ifStatement, AbstractILCompilerParams @params) : base(@params) { myIfStatement = ifStatement; }
public virtual void VisitIfStatement <TExpression, TStatement>(IIfStatement <TExpression, TStatement> ifStatement) where TExpression : IExpression where TStatement : IStatement { Visit(ifStatement); }
public virtual void VisitIfStatement(IIfStatement s) { }
private void InsertWrappedProperties(IClassDeclaration viewModel, List <IPropertyDeclaration> confirmedPropertiesForWrapping, IFieldDeclaration wrappedClassField, IIdentifier onPropertyChangedIdentifier) { IConstructLanguage language = viewModel.Language; foreach (IPropertyDeclaration property in confirmedPropertiesForWrapping) { IMemberAccess propertyMemberAccess = language.MemberAccess( language.MemberAccess(language.None <IExpression>(), wrappedClassField.Identifier), property.Identifier); IAccessor getterOfWrapper = language.None <IAccessor>(); IAccessor propertyGetter = property.Getter(); if (propertyGetter.Exists && IsAccessorVisibleOutsideClass(propertyGetter.Modifiers)) { getterOfWrapper = language.Getter( language.Modifiers(propertyGetter.Modifiers.Modifiers), language.Block( language.ReturnStatement(propertyMemberAccess))); } IAccessor setterOfWrapper = language.None <IAccessor>(); IAccessor propertySetter = property.Setter(); if (propertySetter.Exists && IsAccessorVisibleOutsideClass(propertySetter.Modifiers)) { IStatement assignment = language.AssignmentStatement(propertyMemberAccess, language.Expression("value")); IMethodInvocation onPropertyChangedInvocation = language.MethodInvocation( language.None <IExpression>(), onPropertyChangedIdentifier, language.None <ITypeArguments>(), language.Arguments( language.Argument(language.StringLiteral(property.Identifier.Name)))); IIfStatement ifStatement = language.IfStatement( language.BinaryExpression(propertyMemberAccess, Operator.NotEqual, language.Expression("value")), language.Block(assignment, language.ExpressionStatement(onPropertyChangedInvocation))); setterOfWrapper = language.Setter( language.Modifiers(propertyGetter.Modifiers.Modifiers), language.Block(ifStatement)); } if (getterOfWrapper.Exists || setterOfWrapper.Exists) { IPropertyDeclaration wrapperProperty = language.Property( language.None <IDocComment>(), language.None <IAttributes>(), property.Modifiers, property.TypeName, property.Identifier, getterOfWrapper, setterOfWrapper); viewModel.Insert(wrapperProperty); } } }
private bool TryDecomposeIfCondition( IIfStatement ifStatement, out ISymbol localOrParameter) { localOrParameter = null; var condition = ifStatement.Condition; var binaryOperator = condition as IBinaryOperatorExpression; if (binaryOperator == null) { return false; } if (binaryOperator.GetSimpleBinaryOperationKind() != SimpleBinaryOperationKind.Equals) { return false; } if (IsNull(binaryOperator.LeftOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.RightOperand, out localOrParameter); } if (IsNull(binaryOperator.RightOperand)) { return TryGetLocalOrParameterSymbol( binaryOperator.LeftOperand, out localOrParameter); } return false; }
private bool TryFindAssignmentExpression( IBlockStatement containingBlock, IIfStatement ifOperation, ISymbol localOrParameter, out IExpressionStatement expressionStatement, out IAssignmentExpression assignmentExpression) { var ifOperationIndex = containingBlock.Statements.IndexOf(ifOperation); // walk forward until we find an assignment of this local/parameter into // something else. for (var i = ifOperationIndex + 1; i < containingBlock.Statements.Length; i++) { expressionStatement = containingBlock.Statements[i] as IExpressionStatement; if (expressionStatement == null) { continue; } assignmentExpression = expressionStatement.Expression as IAssignmentExpression; if (assignmentExpression == null) { continue; } if (!TryGetLocalOrParameterSymbol(assignmentExpression.Value, out var assignmentValue)) { continue; } if (!Equals(localOrParameter, assignmentValue)) { continue; } return true; } expressionStatement = null; assignmentExpression = null; return false; }
public virtual void VisitIfStatement(IIfStatement operation) { DefaultVisit(operation); }
public virtual void VisitIfStatement(IIfStatement operation) { DefaultVisit(operation); }
public override void VisitIfStatement(IIfStatement operation) { Visit(operation.Condition); Visit(operation.IfTrueStatement); Visit(operation.IfFalseStatement); }