public ExpressionKind Eat(ISnapshot snapshot, ICSharpExpression expression) { if (expression == null) throw new ArgumentNullException("expression"); return GetEater(expression).Eat(snapshot, expression); }
protected override IForStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { var hasLength = (LengthName != null); var template = hasLength ? "for(var x=$0;x>=0;x--)" : "for(var x=$0;x>0;x--)"; var forStatement = (IForStatement) factory.CreateStatement( template + EmbeddedStatementBracesTemplate, expression); var variable = (ILocalVariableDeclaration) forStatement.Initializer.Declaration.Declarators[0]; var initializer = (IExpressionInitializer) variable.Initial; if (!hasLength) { var value = initializer.Value.ReplaceBy(expression); value.ReplaceBy(value); } else { var lengthAccess = factory.CreateReferenceExpression("expr.$0", LengthName); lengthAccess = initializer.Value.ReplaceBy(lengthAccess); lengthAccess.QualifierExpression.NotNull().ReplaceBy(expression); lengthAccess.ReplaceBy(factory.CreateExpression("$0 - 1", lengthAccess)); } return forStatement; }
protected override void AcceptExpression( ITextControl textControl, ISolution solution, TextRange resultRange, ICSharpExpression expression) { // set selection for introduce field textControl.Selection.SetRanges(new[] {TextControlPosRange.FromDocRange(textControl, resultRange)}); const string name = "IntroFieldAction"; var rules = DataRules .AddRule(name, ProjectModel.DataContext.DataConstants.SOLUTION, solution) .AddRule(name, DataConstants.DOCUMENT, textControl.Document) .AddRule(name, TextControl.DataContext.DataConstants.TEXT_CONTROL, textControl) .AddRule(name, Psi.Services.DataConstants.SELECTED_EXPRESSION, expression); Lifetimes.Using(lifetime => WorkflowExecuter.ExecuteBatch( Shell.Instance.GetComponent<DataContexts>().CreateWithDataRules(lifetime, rules), new IntroFieldWorkflow(solution, null))); // todo: rename hotspots var ranges = textControl.Selection.Ranges.Value; if (ranges.Count == 1) // reset selection { var endPos = ranges[0].End; textControl.Selection.SetRanges(new[] {new TextControlPosRange(endPos, endPos)}); } }
public void EatStubOptions(ISnapshot snapshot, ICSharpExpression options) { if (options is IConditionalAndExpression) { EatStubOptions(snapshot, (options as IConditionalAndExpression).LeftOperand); EatStubOptions(snapshot, (options as IConditionalAndExpression).RightOperand); return; } if (options is IEqualityExpression) { EatStubOptions(snapshot, (options as IEqualityExpression).LeftOperand); var kind = _eater.Eat(snapshot, (options as IEqualityExpression).RightOperand); EatOptionValue(snapshot, kind, (options as IEqualityExpression).RightOperand); return; } if (options is IInvocationExpression) { var optType = _moqStubOptionTargetEater.EatOption(snapshot, options as IInvocationExpression); snapshot.Add(optType, options); return; } if (options is IReferenceExpression) { var optType = _moqStubOptionTargetEater.EatOption(snapshot, options as IReferenceExpression); snapshot.Add(optType, options); return; } throw new MoqStubOptionWrongTypeException(this, options); }
private void EatOptionValue(ISnapshot snapshot, ExpressionKind kind, ICSharpExpression optionValue) { var addableKinds = new[] { ExpressionKind.Target, ExpressionKind.Stub, ExpressionKind.Mock }; if (addableKinds.Contains(kind)) { snapshot.Add(kind, optionValue); } }
protected PostfixTemplateContext([NotNull] ITreeNode reference, [NotNull] ICSharpExpression expression, [NotNull] PostfixExecutionContext executionContext) { myInnerExpression = expression; Reference = reference; PsiModule = reference.GetPsiModule(); ExecutionContext = executionContext; }
public static IPropertyAssignment CreatePropertyAssignment( this CSharpElementFactory factory, string name, ICSharpExpression arg) { return factory.CreateTypeMemberDeclaration("[A($0=$1)] class A {}", (object)name, (object)arg).Attributes[0] .PropertyAssignments[0]; }
public static void MoveToMethodWithFieldIntroduction([NotNull] IClassDeclaration classDeclaration, [NotNull] ICSharpExpression expression, [NotNull] string methodName, string fieldName = null) { classDeclaration.GetPsiServices().Locks.AssertReadAccessAllowed(); var methodDeclaration = GetOrCreateMethod(classDeclaration, methodName); MoveToMethodWithFieldIntroduction(classDeclaration, methodDeclaration, expression, fieldName); }
CSharpControlFlowNullReferenceState GetExpressionNullReferenceState( [CanBeNull] CSharpCompilerNullableInspector nullabilityInspector, [CanBeNull] CSharpControlFlowGraphInspector inspector, [CanBeNull][ItemNotNull] HashSet <IAsExpression> alwaysSuccessTryCastExpressions, [NotNull] ICSharpExpression expression) { if (nullabilityInspector != null) { return(GetExpressionNullReferenceStateByNullableContext(nullabilityInspector, expression)); } Debug.Assert(inspector != null); Debug.Assert(alwaysSuccessTryCastExpressions != null); while (true) { switch (expression) { case IReferenceExpression referenceExpression: if (referenceExpression is IConditionalAccessExpression conditionalAccessExpression && conditionalAccessExpression.HasConditionalAccessSign) { var referenceState = GetExpressionNullReferenceStateByAnnotations(referenceExpression); if (referenceState == CSharpControlFlowNullReferenceState.NOT_NULL) { expression = conditionalAccessExpression.ConditionalQualifier; continue; } } var nullReferenceState = inspector.GetExpressionNullReferenceState(referenceExpression, true); if (nullReferenceState == CSharpControlFlowNullReferenceState.UNKNOWN) { nullReferenceState = GetExpressionNullReferenceStateByAnnotations(referenceExpression); } return(nullReferenceState); case IAsExpression asExpression when alwaysSuccessTryCastExpressions.Contains(asExpression): return(CSharpControlFlowNullReferenceState.NOT_NULL); case IObjectCreationExpression _: return(CSharpControlFlowNullReferenceState.NOT_NULL); case IInvocationExpression invocationExpression: if (invocationExpression.InvokedExpression is IReferenceExpression invokedExpression) { return(GetExpressionNullReferenceStateByAnnotations(invokedExpression)); } goto default; default: return(CSharpControlFlowNullReferenceState.UNKNOWN); } } }
/// <summary> /// If current expression is used as initializer for local variable, declared element for this variable will be returned /// </summary> public static IDeclaredElement GetDeclaredElementFromParentDeclaration([NotNull] ICSharpExpression expression) { expression.GetPsiServices().Locks.AssertReadAccessAllowed(); var localVariableDeclaration = LocalVariableDeclarationNavigator.GetByInitial( ExpressionInitializerNavigator.GetByValue(expression.GetContainingParenthesizedExpression())); return(localVariableDeclaration?.DeclaredElement); }
public override void VisitReturnStatement(IReturnStatement returnStatementParam) { ICSharpExpression csharpExpression = returnStatementParam.Value; expressionTypes.Add(csharpExpression != null ? csharpExpression.GetExpressionType(resolveContext) : returnStatementParam.GetPsiModule().GetPredefinedType().Void); base.VisitReturnStatement(returnStatementParam); }
public override ICSharpExpression GetOuterExpression(ICSharpExpression expression) { var reference = ReferenceExpressionNavigator.GetByQualifierExpression(expression); if (reference != null && reference == Reference) { return reference; } return base.GetOuterExpression(expression); }
private static IType IsBrokenByAwaitCase([NotNull] ICSharpExpression expression, [NotNull] ITreeNode reference) { var awaitExpression = expression as IAwaitExpression; if (awaitExpression == null) { return(null); } var taskExpression = awaitExpression.Task as IReferenceExpression; if (taskExpression == null || taskExpression != reference) { return(null); } var taskQualifier = taskExpression.QualifierExpression; if (taskQualifier == null) { return(null); } var expressionType = taskQualifier.Type(); if (expressionType.IsTask() || expressionType.IsConfigurableAwaitable()) { return(taskExpression.GetPredefinedType().Void); } if (expressionType.IsGenericTask() || expressionType.IsGenericConfigurableAwaitable()) { var declaredType = expressionType as IDeclaredType; if (declaredType == null) { return(null); } var typeElement = declaredType.GetTypeElement(); if (typeElement == null) { return(null); } var typeParameters = typeElement.TypeParameters; if (typeParameters.Count != 1) { return(null); } return(declaredType.GetSubstitution().Apply(typeParameters[0])); } return(null); }
public override ICSharpExpression GetOuterExpression(ICSharpExpression expression) { var reference = ReferenceExpressionNavigator.GetByQualifierExpression(expression); if (reference != null && reference == Reference) { return(reference); } return(base.GetOuterExpression(expression)); }
private static void ExecuteRefactoring( [NotNull] ITextControl textControl, [NotNull] ICSharpExpression expression, [CanBeNull] Action executeAfter = null) { const string actionId = IntroVariableAction.ACTION_ID; var solution = expression.GetSolution(); var document = textControl.Document; var expressionRange = expression.GetDocumentRange() .TextRange; textControl.Selection.SetRange(expressionRange); var rules = DataRules .AddRule(actionId, ProjectModelDataConstants.SOLUTION, solution) .AddRule(actionId, DocumentModelDataConstants.DOCUMENT, document) .AddRule(actionId, TextControlDataConstants.TEXT_CONTROL, textControl); var settingsStore = expression.GetSettingsStoreWithEditorConfig(); var multipleOccurrences = settingsStore.GetValue(PostfixTemplatesSettingsAccessor.SearchVarOccurrences); // note: uber ugly code down here using (var definition = Lifetime.Define(Lifetime.Eternal, actionId)) { var dataContexts = solution.GetComponent <DataContexts>(); var dataContext = dataContexts.CreateWithDataRules(definition.Lifetime, rules); var workflow = new IntroduceVariableWorkflow(solution, actionId); RefactoringActionUtil.ExecuteRefactoring(dataContext, workflow); var finishedAction = executeAfter; if (finishedAction != null) { var currentSession = HotspotSessionExecutor.Instance.CurrentSession; if (currentSession != null) // ugly hack { currentSession.HotspotSession.Closed.Advise(Lifetime.Eternal, (e) => { if (e.TerminationType == TerminationType.Finished) { finishedAction(); } }); } else { finishedAction(); } } } }
internal InvalidValueRangeBoundaryWarning( [NotNull] ICSharpExpression positionParameter, ValueRangeBoundary boundary, [NotNull] IType type, bool typeIsSigned, [NotNull] string message) : base(message) { PositionParameter = positionParameter; Boundary = boundary; Type = type; TypeIsSigned = typeIsSigned; }
protected override bool AnalyzeNode(IAssignmentExpression navigated, ICSharpExpression from) { var lhs = navigated.Dest; var rhs = navigated.Source; if (BurstCodeAnalysisUtil.IsFixedString(lhs.Type()) && rhs.Type().IsString()) { return(false); } return(true); }
public IAssignableReference ToAssignableRef(ICSharpExpression csExpr, IList <IStatement> body) { if (csExpr == null) { return(new UnknownReference()); } var reference = ToReference(csExpr, body); var assignableRef = reference as IAssignableReference ?? new UnknownReference(); return(assignableRef); }
internal IntentionalBlockingAttemptWarning( [NotNull] string message, [NotNull] ICSharpExpression expression, [NotNull] ICSharpExpression valueTaskExpression, [NotNull] IReferenceExpression getAwaiterReferenceExpression, [NotNull] IReferenceExpression getResultReferenceExpression) : base(message) { this.getAwaiterReferenceExpression = getAwaiterReferenceExpression; this.getResultReferenceExpression = getResultReferenceExpression; ValueTaskExpression = valueTaskExpression; Expression = expression; }
public IAssignableExpression ToAssignableExpr(ICSharpExpression csExpr, IList <IStatement> body) { IAssignableExpression result = new UnknownExpression(); Execute.AndSupressExceptions( () => { result = csExpr == null ? new UnknownExpression() : csExpr.Accept(this, body) ?? new UnknownExpression(); }); return(result); }
public IExpressionEater GetEater(ICSharpExpression expression) { var eater = _container.GetInstance<IEnumerable<IExpressionEater>>() .SingleOrDefault(t => t.ExpressionType.IsInstanceOfType(expression)); if (eater == null) { return new StubExpressionEater(); } return eater; }
public IExpressionEater GetEater(ICSharpExpression expression) { var eater = _container.GetInstance <IEnumerable <IExpressionEater> >() .SingleOrDefault(t => t.ExpressionType.IsInstanceOfType(expression)); if (eater == null) { return(new StubExpressionEater()); } return(eater); }
public static INamespace GetNamespaceDeclaration(ICSharpExpression expression) { CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(expression.GetPsiModule()); if (expression.ConstantValue.IsString()) { string namespaceName = Convert.ToString(expression.ConstantValue.Value); return(elementFactory.CreateNamespaceDeclaration(namespaceName).DeclaredElement); } return(null); }
public static INamespace GetNamespaceDeclaration(ICSharpExpression expression) { CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(expression.GetPsiModule()); if (expression.ConstantValue != null && expression.ConstantValue.IsString()) { string namespaceName = Convert.ToString(expression.ConstantValue.Value); return elementFactory.CreateNamespaceDeclaration(namespaceName).DeclaredElement; } return null; }
public static DocumentRange GetExpressionRange([NotNull] this ICSharpExpression expression) { switch (expression) { case IReferenceExpression referenceExpression: return(referenceExpression.NameIdentifier.GetDocumentRange()); case IParenthesizedExpression parenthesizedExpression: return(parenthesizedExpression.Expression.GetExpressionRange()); default: return(expression.GetDocumentRange()); } }
public static DocumentRange GetExpressionRange([NotNull] this ICSharpExpression expression) { switch (expression) { case IReferenceExpression referenceExpression: return(referenceExpression.NameIdentifier.GetDocumentRange()); case IInvocationExpression { InvokedExpression: IReferenceExpression { QualifierExpression : { } } invokedExpression } : // todo: too short? return(invokedExpression.NameIdentifier.GetDocumentRange());
internal RedundantAwaitSuggestion( [NotNull] string message, [NotNull] Action removeAsync, [NotNull] IAwaitExpression awaitExpression, [CanBeNull] IExpressionStatement statementToBeReplacedWithReturnStatement, [NotNull] ICSharpExpression expressionToReturn, [CanBeNull] IAttributesOwnerDeclaration attributesOwnerDeclaration) : base(message) { RemoveAsync = removeAsync; AwaitExpression = awaitExpression; StatementToBeReplacedWithReturnStatement = statementToBeReplacedWithReturnStatement; ExpressionToReturn = expressionToReturn; AttributesOwnerDeclaration = attributesOwnerDeclaration; }
public ParameterizedTestMissingParameterHighlighting( IMethodDeclaration methodDeclaration, IAttribute attribute, bool isFirstMissingParameter, ICSharpExpression argumentExpression, [CanBeNull] ICSharpArgument argument) : base(argumentExpression, string.Format(Message)) { MethodDeclaration = methodDeclaration; Attribute = attribute; IsFirstMissingParameter = isFirstMissingParameter; ArgumentExpression = argumentExpression; Argument = argument; }
/// <summary> /// Remove parenthesis from node. /// </summary> /// <param name="node"> /// The node. /// </param> public static void RemoveParenthesisFromNode(ITreeNode node) { IParenthesizedExpression parenthesizedExpressionNode = node as IParenthesizedExpression; if (parenthesizedExpressionNode != null) { using (WriteLockCookie.Create(true)) { ICSharpExpression innerExpression = parenthesizedExpressionNode.Expression; if (innerExpression != null && node.Parent != null) { NodeType innerExpressionNodeType = (innerExpression as TreeElement).NodeType; if (innerExpressionNodeType != ElementType.ADDITIVE_EXPRESSION && innerExpressionNodeType != ElementType.MULTIPLICATIVE_EXPRESSION && innerExpressionNodeType != ElementType.SHIFT_EXPRESSION && innerExpressionNodeType != ElementType.AS_EXPRESSION && innerExpressionNodeType != ElementType.ASSIGNMENT_EXPRESSION && innerExpressionNodeType != ElementType.CAST_EXPRESSION && innerExpressionNodeType != ElementType.CONDITIONAL_AND_EXPRESSION && innerExpressionNodeType != ElementType.CONDITIONAL_OR_EXPRESSION && innerExpressionNodeType != ElementType.CONDITIONAL_TERNARY_EXPRESSION && innerExpressionNodeType != ElementType.POSTFIX_OPERATOR_EXPRESSION && innerExpressionNodeType != ElementType.PREFIX_OPERATOR_EXPRESSION && innerExpressionNodeType != ElementType.IS_EXPRESSION && innerExpressionNodeType != ElementType.LAMBDA_EXPRESSION && innerExpressionNodeType != ElementType.BITWISE_AND_EXPRESSION && innerExpressionNodeType != ElementType.BITWISE_INCLUSIVE_OR_EXPRESSION && innerExpressionNodeType != ElementType.BITWISE_EXCLUSIVE_OR_EXPRESSION && innerExpressionNodeType != ElementType.OBJECT_CREATION_EXPRESSION && innerExpressionNodeType != ElementType.ARRAY_CREATION_EXPRESSION && innerExpressionNodeType != ElementType.NULL_COALESCING_EXPRESSION && innerExpressionNodeType != ElementType.QUERY_EXPRESSION && innerExpressionNodeType != ElementType.RELATIONAL_EXPRESSION && innerExpressionNodeType != ElementType.UNARY_OPERATOR_EXPRESSION && innerExpressionNodeType != ElementType.EQUALITY_EXPRESSION && innerExpressionNodeType != ElementType.AWAIT_EXPRESSION) { LowLevelModificationUtil.ReplaceChildRange(node, node, new ITreeNode[] { innerExpression }); return; } if ((!(node.Parent is IExpression)) || node.Parent is IVariableDeclaration) { LowLevelModificationUtil.ReplaceChildRange(node, node, new ITreeNode[] { innerExpression }); return; } IAssignmentExpression parent = node.Parent as IAssignmentExpression; if (parent != null && parent.Source == node) { LowLevelModificationUtil.ReplaceChildRange(node, node, new ITreeNode[] { innerExpression }); return; } } } } }
public SuitableStaticMethodsFilter( [NotNull] IExpressionType expressionType, [NotNull] ICSharpExpression expression, int argumentsCount) { myExpressionType = expressionType; myExistingArgumentsCount = argumentsCount; myConversionRule = expression.GetTypeConversionRule(); var reference = expression as IReferenceExpression; if (reference != null && reference.QualifierExpression == null) { var element = reference.Reference.Resolve().DeclaredElement; myAllowRefParameters = (element is ILocalVariable || element is IParameter); } }
protected override void PlaceExpression( IForStatement forStatement, ICSharpExpression expression, CSharpElementFactory factory) { var condition = (IRelationalExpression) forStatement.Condition; if (LengthPropertyName == null) { condition.RightOperand.ReplaceBy(expression); } else { var lengthAccess = factory.CreateReferenceExpression("expr.$0", LengthPropertyName); lengthAccess = condition.RightOperand.ReplaceBy(lengthAccess); lengthAccess.QualifierExpression.NotNull().ReplaceBy(expression); } }
// todo: [C#6] what about conditional access? public static bool IsReferenceExpressionsChain([CanBeNull] ICSharpExpression expression) { do { var referenceExpression = expression as IReferenceExpression; if (referenceExpression == null) { return(false); } expression = referenceExpression.QualifierExpression; }while (expression != null); return(true); }
public bool TryAnalyze(ICSharpExpression nodeToAnalyze, out bool result) { result = false; var navigatedNode = Navigate(nodeToAnalyze); if (navigatedNode == null) { return(false); } result = AnalyzeNode(navigatedNode, nodeToAnalyze); return(true); }
static CSharpControlFlowNullReferenceState GetExpressionNullReferenceState( [NotNull] NullnessProvider nullnessProvider, [NotNull] CSharpControlFlowGraphInspector inspector, [NotNull] HashSet <IAsExpression> alwaysSuccessTryCastExpressions, ICSharpExpression expression) { while (true) { switch (expression) { case IReferenceExpression referenceExpression: if (referenceExpression is IConditionalAccessExpression conditionalAccessExpression && conditionalAccessExpression.HasConditionalAccessSign) { var referenceState = GetExpressionNullReferenceStateByAnnotations(nullnessProvider, referenceExpression); if (referenceState == CSharpControlFlowNullReferenceState.NOT_NULL) { expression = conditionalAccessExpression.ConditionalQualifier; continue; } } var nullReferenceState = inspector.GetExpressionNullReferenceState(referenceExpression, true); if (nullReferenceState == CSharpControlFlowNullReferenceState.UNKNOWN) { return(GetExpressionNullReferenceStateByAnnotations(nullnessProvider, referenceExpression)); } return(nullReferenceState); case IAsExpression asExpression when alwaysSuccessTryCastExpressions.Contains(asExpression): return(CSharpControlFlowNullReferenceState.NOT_NULL); case IObjectCreationExpression _: return(CSharpControlFlowNullReferenceState.NOT_NULL); case IInvocationExpression invocationExpression: if (invocationExpression.InvokedExpression is IReferenceExpression invokedExpression) { return(GetExpressionNullReferenceStateByAnnotations(nullnessProvider, invokedExpression)); } goto default; default: return(CSharpControlFlowNullReferenceState.UNKNOWN); } } }
public static void MoveToMethodWithFieldIntroduction([NotNull] IClassDeclaration classDeclaration, [NotNull] IMethodDeclaration methodDeclaration, [NotNull] ICSharpExpression expression, string fieldName = null) { classDeclaration.GetPsiServices().Locks.AssertReadAccessAllowed(); var result = GetDeclaredElementFromParentDeclaration(expression); var factory = CSharpElementFactory.GetInstance(classDeclaration); var type = expression.Type(new ResolveContext(classDeclaration.GetPsiModule())); if (type.IsUnknown) { type = TypeFactory.CreateTypeByCLRName("System.Object", classDeclaration.GetPsiModule()); } var isVoid = type.IsVoid(); if (!isVoid) { var baseName = fieldName ?? CreateBaseName(expression, result); var name = NamingUtil.GetUniqueName(expression, baseName, NamedElementKinds.PrivateInstanceFields, baseName == null ? collection => { collection.Add(expression.Type(), new EntryOptions()); } : (Action <INamesCollection>)null, de => !de.Equals(result)); var field = factory.CreateFieldDeclaration(type, name); field.SetAccessRights(AccessRights.PRIVATE); classDeclaration.AddClassMemberDeclaration(field); var initialization = factory.CreateStatement("$0 = $1;", name, expression.CopyWithResolve()); var body = methodDeclaration.EnsureStatementMemberBody(); body.AddStatementAfter(initialization, null); RenameOldUsages(expression, result, name, factory); } else { var initialization = factory.CreateStatement("$0;", expression.CopyWithResolve()); var body = methodDeclaration.EnsureStatementMemberBody(); body.AddStatementAfter(initialization, null); ExpressionStatementNavigator.GetByExpression(expression).NotNull("statement != null").RemoveOrReplaceByEmptyStatement(); } }
private static bool IsConstructorInvocation([NotNull] ICSharpExpression expression) { var invocationExpression = expression as IInvocationExpression; if (invocationExpression != null) // StringBuilder().new { var reference = invocationExpression.InvokedExpression as IReferenceExpression; if (reference != null && CommonUtils.IsReferenceExpressionsChain(reference)) { var resolveResult = reference.Reference.Resolve().Result; return(resolveResult.DeclaredElement is ITypeElement); } } return(false); }
private ExpressionKind EatResults(ISnapshot snapshot, ICSharpExpression initialExpression) { ExpressionKind expressionKind = _eater.Eat(snapshot, initialExpression); if (expressionKind == ExpressionKind.StubCandidate) { return(ExpressionKind.Stub); } if (expressionKind == ExpressionKind.TargetCall) { return(ExpressionKind.Result); } return(expressionKind); }
private ExpressionKind EatResults(ISnapshot snapshot, ICSharpExpression initialExpression) { ExpressionKind expressionKind = _eater.Eat(snapshot, initialExpression); if (expressionKind == ExpressionKind.StubCandidate) { return ExpressionKind.Stub; } if (expressionKind == ExpressionKind.TargetCall) { return ExpressionKind.Result; } return expressionKind; }
/// <summary> /// Gets the return value of an expression. /// </summary> /// <param name="writer">The stream on which to write.</param> /// <param name="expression">The expression.</param> public static string SingleResultExpressionText(ICSharpWriter writer, ICSharpExpression expression) { ICSharpExpressionContext SourceExpressionContext = new CSharpExpressionContext(); expression.WriteCSharp(writer, SourceExpressionContext, -1); Debug.Assert(SourceExpressionContext.ReturnValue != null); string Result = SourceExpressionContext.ReturnValue; if (expression.IsComplex) { Result = $"({Result})"; } return(Result); }
protected static PredicateArgument ExtractArgument(ICSharpExpression expression) { if (expression == null) { return(null); } var contractResultArgument = TryCreateContractResultArgument(expression); if (contractResultArgument != null) { return(contractResultArgument); } return(TryCreateReferenceArgument(expression)); }
private void CreateStatement(CSharpElementFactory factory, ICSharpExpression expression, IPsiSourceFile sourceFile, AccessRights accessRights) { var statement = (IExpressionStatement)factory.CreateStatement("'__' = expression;"); var propertyDeclaration = factory.CreatePropertyDeclaration(Context.Type, Context.SuggestedPropertyName, IsReadOnly, accessRights); var assignment = (IAssignmentExpression)statement.Expression; assignment.SetSource(expression); var psiServices = expression.GetPsiServices(); var suggestionManager = psiServices.Naming.Suggestion; var classDeclaration = Context.ParameterDeclaration.GetContainingNode <IClassDeclaration>().NotNull(); var suggestion = suggestionManager.CreateEmptyCollection( PluralityKinds.Unknown, expression.Language, true, sourceFile); suggestion.Add(expression, new EntryOptions { SubrootPolicy = SubrootPolicy.Decompose, PredefinedPrefixPolicy = PredefinedPrefixPolicy.Remove }); suggestion.Prepare(propertyDeclaration.DeclaredElement, new SuggestionOptions { UniqueNameContext = (ITreeNode)classDeclaration.Body ?? classDeclaration }); propertyDeclaration.SetName(suggestion.FirstName()); var memberAnchor = GetAnchorMember(classDeclaration.MemberDeclarations.ToList()); classDeclaration.AddClassMemberDeclarationAfter(propertyDeclaration, (IClassMemberDeclaration)memberAnchor); var languageHelper = LanguageManager.Instance.TryGetService <IIntroducePropertyFromParameterLanguageHelper>( Context.Parameter.PresentationLanguage); if (languageHelper == null) { return; } var anchorInitializationAnchorMember = GetAnchorInitializationAnchorMember(Context.ConstructorDeclaration); languageHelper.AddAssignmentToBody(Context.ConstructorDeclaration, anchorInitializationAnchorMember, false, Context.Parameter, propertyDeclaration.DeclaredElement); }
static string TryGetHighlightingMessage([NotNull] ICSharpExpression monitor) { Debug.Assert(CSharpLanguage.Instance != null); var monitorType = monitor.GetExpressionType().ToIType(); if (monitorType.IsString()) { return("Do not lock on strings."); } if (monitorType is IArrayType arrayType && arrayType.ElementType.IsValueType()) { return("Do not lock on arrays of value types."); } var monitorTypeElement = monitorType.GetTypeElement(); if (monitorTypeElement != null) { var psiModule = monitor.GetPsiModule(); foreach (var type in GetClassTypes()) { var objectType = (IClass)TypeElementUtil.GetTypeElementByClrName(type, psiModule).AssertNotNull(); if (monitorTypeElement.IsDescendantOf(objectType)) { var typeName = objectType.WithIdSubstitution().AssertNotNull().GetPresentableName(CSharpLanguage.Instance); if (objectType.IsAbstract) { return($"Do not lock on objects derived from the '{typeName}' class."); } if (objectType.IsSealed) { return($"Do not lock on '{typeName}' objects."); } return($"Do not lock on '{typeName}' objects or objects derived from the '{typeName}' class."); } } } return(null); }
private INamespace GetNamespaceDeclaration(ICSharpExpression expression) { var typeofExpression = expression as ITypeofExpression; if (typeofExpression != null) { var declaredType = typeofExpression.ArgumentType as IDeclaredType; if (declaredType != null) { ITypeElement typeElement = declaredType.GetTypeElement(); if (typeElement != null) { return typeElement.GetContainingNamespace(); } } } return null; }
protected override void AcceptExpression( ITextControl textControl, ISolution solution, TextRange resultRange, ICSharpExpression expression) { // set selection for introduce viriable textControl.Selection.SetRanges(new[] { TextControlPosRange.FromDocRange(textControl, resultRange) }); const string name = "IntroVariableAction"; var rules = DataRules .AddRule(name, ProjectModel.DataContext.DataConstants.SOLUTION, solution) .AddRule(name, DataConstants.DOCUMENT, textControl.Document) .AddRule(name, TextControl.DataContext.DataConstants.TEXT_CONTROL, textControl) .AddRule(name, Psi.Services.DataConstants.SELECTED_EXPRESSION, expression); Lifetimes.Using(lifetime => WorkflowExecuter.ExecuteBatch( Shell.Instance.GetComponent<DataContexts>().CreateWithDataRules(lifetime, rules), new IntroduceVariableWorkflow(solution, null))); }
protected override void PlaceExpression( IForStatement forStatement, ICSharpExpression expression, CSharpElementFactory factory) { var variable = (ILocalVariableDeclaration)forStatement.Initializer.Declaration.Declarators[0]; var initializer = (IExpressionInitializer)variable.Initial; if (LengthPropertyName == null) { var value = initializer.Value.ReplaceBy(expression); value.ReplaceBy(factory.CreateExpression("$0 - 1", value)); } else { var lengthAccess = factory.CreateReferenceExpression("expr.$0", LengthPropertyName); lengthAccess = initializer.Value.ReplaceBy(lengthAccess); lengthAccess.QualifierExpression.NotNull().ReplaceBy(expression); lengthAccess.ReplaceBy(factory.CreateExpression("$0 - 1", lengthAccess)); } }
private static IEnumerable<ITypeElement> GetRegisteredTypes(IStructuralMatchResult match, ICSharpExpression expression) { // match typeof() expressions var typeOfExpression = expression as ITypeofExpression; if (typeOfExpression != null) { var typeElement = (IDeclaredType)typeOfExpression.ArgumentType; yield return typeElement.GetTypeElement(); } // match new[] or new Type[] expressions var arrayExpression = expression as IArrayCreationExpression; if (arrayExpression != null) { foreach (var initializer in arrayExpression.ArrayInitializer.ElementInitializers.OfType<IExpressionInitializer>()) { foreach (ITypeElement type in GetRegisteredTypes(match, initializer.Value)) { yield return type; } } } // match new List<Type> expressions var objectCreationExpression = expression as IObjectCreationExpression; if (objectCreationExpression != null) { foreach (var initializer in objectCreationExpression.Initializer.InitializerElements.OfType<ICollectionElementInitializer>()) { // todo fixme find out if THERE CAN BE ONLY ONE!!!1 if (initializer.Arguments.Count != 1) { continue; } foreach (ITypeElement type in GetRegisteredTypes(match, initializer.Arguments[0].Value)) { yield return type; } } } }
protected override IForStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { var template = "for(var x=0;x<$0;x++)" + EmbeddedStatementBracesTemplate; var forStatement = (IForStatement) factory.CreateStatement(template, expression); var condition = (IRelationalExpression) forStatement.Condition; if (LengthName == null) { condition.RightOperand.ReplaceBy(expression); } else { var lengthAccess = factory.CreateReferenceExpression("expr.$0", LengthName); lengthAccess = condition.RightOperand.ReplaceBy(lengthAccess); lengthAccess.QualifierExpression.NotNull().ReplaceBy(expression); } return forStatement; }
private void CreateStatement(CSharpElementFactory factory, ICSharpExpression expression, IPsiSourceFile sourceFile) { var statement = (IExpressionStatement) factory.CreateStatement("'__' = expression;"); var propertyDeclaration = factory.CreatePrivatePropertyDeclaration(Context.Type, Context.SuggestedPropertyName); var assignment = (IAssignmentExpression) statement.Expression; assignment.SetSource(expression); var psiServices = expression.GetPsiServices(); var suggestionManager = psiServices.Naming.Suggestion; var classDeclaration = Context.ParameterDeclaration.GetContainingNode<IClassDeclaration>().NotNull(); var suggestion = suggestionManager.CreateEmptyCollection( PluralityKinds.Unknown, expression.Language, true, sourceFile); suggestion.Add(expression, new EntryOptions { SubrootPolicy = SubrootPolicy.Decompose, PredefinedPrefixPolicy = PredefinedPrefixPolicy.Remove }); suggestion.Prepare(propertyDeclaration.DeclaredElement, new SuggestionOptions { UniqueNameContext = (ITreeNode) classDeclaration.Body ?? classDeclaration }); propertyDeclaration.SetName(suggestion.FirstName()); var memberAnchor = GetAnchorMember(classDeclaration.MemberDeclarations.ToList()); classDeclaration.AddClassMemberDeclarationAfter(propertyDeclaration, (IClassMemberDeclaration) memberAnchor); var languageHelper = LanguageManager.Instance.TryGetService<IIntroducePrivatePropertyFromParameterLanguageHelper>( Context.Parameter.PresentationLanguage); if (languageHelper == null) return; var anchorInitializationAnchorMember = GetAnchorInitializationAnchorMember(Context.ConstructorDeclaration); languageHelper.AddAssignmentToBody(Context.ConstructorDeclaration, anchorInitializationAnchorMember, false, Context.Parameter, propertyDeclaration.DeclaredElement); }
public UnexpectedAssignDestinationException(ICSharpExpression destination, AssignmentExpressionEater eater, ICSharpTreeNode node) : base(string.Format("Unexpected assign destination. Expected IReferenceExpression, but was [{0}]", destination.GetType()), eater, node) { Destination = destination; }
// I don't have any better ideas at the moment... private bool IsResolvedToObject(ICSharpExpression expression) { var invocationExpression = expression as IInvocationExpression; if (invocationExpression != null) { if (invocationExpression.Reference != null) { var result = invocationExpression.Reference.Resolve().Result.DeclaredElement as IParametersOwner; if (result != null) { return result.ReturnType.IsObject(); } } } var castExpression = expression as ICastExpression; if (castExpression != null) { var typeUsage = castExpression.TargetType as IPredefinedTypeUsage; if (typeUsage != null) { return IsReferenceToSystemObject(typeUsage.ScalarPredefinedTypeName); } } var asExpression = expression as IAsExpression; if (asExpression != null) { var typeUsage = asExpression.TypeOperand as IPredefinedTypeUsage; if (typeUsage != null) { return IsReferenceToSystemObject(typeUsage.ScalarPredefinedTypeName); } } var objectCreationExpression = expression as IObjectCreationExpression; if (objectCreationExpression != null) { return IsReferenceToSystemObject(objectCreationExpression.TypeReference as IPredefinedTypeReference); } return false; }
/// <summary> /// Determines whether [is not expression] [the specified value]. /// </summary> /// <param name="value"> /// The value. /// </param> /// <returns> /// <c>true</c> if [is not expression] [the specified value]; otherwise, <c>false</c>. /// </returns> private static bool IsNotExpression(ICSharpExpression value) { var unaryOperatorExpression = value as IUnaryOperatorExpression; if (unaryOperatorExpression == null) { return false; } var sign = unaryOperatorExpression.OperatorSign; if (sign == null) { return false; } var operatorSign = sign.GetText(); return operatorSign == "!"; }
public ExpressionKind Eat(ISnapshot snapshot, ICSharpExpression statement) { return ExpressionKind.None; }
/// <summary> /// Adds to expression. /// </summary> /// <param name="factory"> /// The factory. /// </param> /// <param name="expression"> /// To. /// </param> /// <param name="sign"> /// The sign. /// </param> /// <returns> /// </returns> private static ICSharpExpression AddToExpression(CSharpElementFactory factory, ICSharpExpression expression, char sign) { var sign2 = sign == '-' ? '+' : '-'; var text = expression.GetText(); if (text.StartsWith("(") && text.EndsWith(")")) { text = text.Substring(1, text.Length - 2); } var match = Regex.Match(text, "\\" + sign2 + "\\s*1\\s*$"); if (match.Success) { text = text.Substring(0, text.Length - match.Value.Length).Trim(); if (text.StartsWith("(") && text.EndsWith(")")) { text = text.Substring(1, text.Length - 2); } } else { if (expression is IBinaryExpression) { text = "(" + text + ") " + sign + " 1"; } else { text += sign + " 1"; } } text = text.Trim(); var result = factory.CreateExpression(text); if (result.IsConstantValue()) { result = factory.CreateExpressionByValue(result.ConstantValue); } return result; }
public PostfixTemplateAcceptanceContext([NotNull] ITreeNode reference, [NotNull] ICSharpExpression expression, DocumentRange replaceRange, bool forceMode, [NotNull] PostfixExecutionContext context) { myReparsedContext = context.ReparsedContext; myMostInnerExpression = expression; PostfixReferenceNode = reference; ForceMode = forceMode; PsiModule = context.PsiModule; LookupItemsOwner = context.LookupItemsOwner; MostInnerReplaceRange = replaceRange; if (!replaceRange.IsValid()) { var referenceExpression = reference as IReferenceExpression; if (referenceExpression != null) { MostInnerReplaceRange = ToDocumentRange(referenceExpression.QualifierExpression.NotNull()).SetEndTo( ToDocumentRange(referenceExpression.Delimiter.NotNull()).TextRange.EndOffset); } var referenceName = reference as IReferenceName; if (referenceName != null) { MostInnerReplaceRange = ToDocumentRange(referenceName.Qualifier).SetEndTo( ToDocumentRange(referenceName.Delimiter).TextRange.EndOffset); } } // build expression contexts var expressionContexts = new List<PrefixExpressionContext>(); var endOffset = Math.Max( MostInnerReplaceRange.TextRange.EndOffset, ToDocumentRange(reference).TextRange.EndOffset); for (ITreeNode node = expression; node != null; node = node.Parent) { if (node is ICSharpStatement) break; var expr = node as ICSharpExpression; if (expr == null || expr == reference) continue; var exprRange = myReparsedContext.ToDocumentRange(expr); if (!exprRange.IsValid()) break; // stop when out of generated if (exprRange.TextRange.EndOffset > endOffset) break; // stop when 'a.var + b' // skip relational expressions like this: 'List<int.{here}>' if (CommonUtils.IsRelationalExpressionWithTypeOperand(expr)) continue; var expressionContext = new PrefixExpressionContext(this, expr); if (expressionContext.ReferencedElement is ITypeElement) { // skip types that are parts of 'List<T.>'-like expressions if (!CommonUtils.CanTypeBecameExpression(expression)) continue; } expressionContexts.Add(expressionContext); if (expressionContext.CanBeStatement) break; } Expressions = (expressionContexts.Count == 0) ? EmptyList<PrefixExpressionContext>.InstanceList : expressionContexts.AsReadOnly(); }
private static bool IsInvocationExpression(ICSharpExpression expression) { return InvocationExpressionNavigator.GetByInvokedExpression(expression) != null; }
private IEnumerable<IComponentRegistration> GetRegistrationsFromExpression(ITreeNode registrationRootElement, ICSharpExpression expression) { var castExpression = expression as ICastExpression; if (castExpression != null) { var predefinedTypeUsage = castExpression.TargetType as IUserTypeUsage; if (predefinedTypeUsage != null && predefinedTypeUsage.ScalarTypeName != null) { IResolveResult resolveResult = predefinedTypeUsage.ScalarTypeName.Reference.Resolve().Result; var typeElement = resolveResult.DeclaredElement as ITypeElement; if (typeElement != null) { yield return new ServiceRegistration(registrationRootElement, typeElement); } } } var asExpression = expression as IAsExpression; if (asExpression != null) { var typeUsage = asExpression.TypeOperand as IUserTypeUsage; if (typeUsage != null && typeUsage.ScalarTypeName != null) { IResolveResult resolveResult = typeUsage.ScalarTypeName.Reference.Resolve().Result; var typeElement = resolveResult.DeclaredElement as ITypeElement; if (typeElement != null) { yield return new ServiceRegistration(registrationRootElement, typeElement); } } } var objectCreationExpression = expression as IObjectCreationExpression; if (objectCreationExpression != null && objectCreationExpression.TypeReference != null) { IResolveResult resolveResult = objectCreationExpression.TypeReference.Resolve().Result; var @class = resolveResult.DeclaredElement as IClass; if (@class != null) { yield return new ComponentRegistration(registrationRootElement, @class, @class); } } var invocationExpression = expression as IInvocationExpression; if (invocationExpression != null) { if (invocationExpression.Reference != null) { var result = invocationExpression.Reference.Resolve().Result.DeclaredElement as IParametersOwner; if (result != null) { var type = result.ReturnType as IDeclaredType; if (type != null) { var @class = type.GetTypeElement(); if (@class != null) { yield return new ComponentRegistration(registrationRootElement, @class, @class); } } } } } }
internal UnthrowableExceptionHighlighting([NotNull] string message, [NotNull] ICSharpExpression thrownStatementExpression) : base(message) { this.thrownStatementExpression = thrownStatementExpression; }
/// <summary> /// Negates the expression. /// </summary> /// <param name="factory"> /// The factory. /// </param> /// <param name="condition"> /// The condition. /// </param> private static void NegateExpression(CSharpElementFactory factory, ICSharpExpression condition) { var expression = factory.CreateExpression("!(" + condition.GetText() + ")"); condition.ReplaceBy(expression); }
private ConstantValue2 GetCSharpConstantValueHack(ICSharpExpression expression, IType type) { if (expression == null) return ConstantValue2.NOT_COMPILE_TIME_CONSTANT; IArrayCreationExpression arrayExpression = expression as IArrayCreationExpression; if (arrayExpression != null) { int[] dimensions = arrayExpression.Dimensions; int rank = dimensions.Length; for (int i = 0; i < rank; i++) if (dimensions[i] != 1) return ConstantValue2.NOT_COMPILE_TIME_CONSTANT; IArrayType arrayType = arrayExpression.Type() as IArrayType; if (arrayType == null) return ConstantValue2.NOT_COMPILE_TIME_CONSTANT; IArrayInitializer arrayInitializer = arrayExpression.Initializer; if (arrayInitializer == null) return ConstantValue2.NOT_COMPILE_TIME_CONSTANT; IType elementType = arrayType.ElementType; Type resolvedScalarType = MakeType(arrayType.GetScalarType()).Resolve(true); if (resolvedScalarType == typeof(Type)) resolvedScalarType = typeof(IType); Type resolvedElementType = rank == 1 ? resolvedScalarType : rank == 2 ? resolvedScalarType.MakeArrayType() : resolvedScalarType.MakeArrayType(rank - 1); IList<IVariableInitializer> elementInitializers = arrayInitializer.ElementInitializers; int length = elementInitializers.Count; Array array = Array.CreateInstance(resolvedElementType, length); for (int i = 0; i < length; i++) { IExpressionInitializer initializer = elementInitializers[i] as IExpressionInitializer; if (initializer == null) return ConstantValue2.NOT_COMPILE_TIME_CONSTANT; ConstantValue2 elementValue = GetCSharpConstantValueHack(initializer.Value, elementType); if (elementValue.IsBadValue()) return ConstantValue2.NOT_COMPILE_TIME_CONSTANT; array.SetValue(elementValue.Value, i); } return new ConstantValue2(array, arrayType, type.GetManager().Solution); } ITypeofExpression typeExpression = expression as ITypeofExpression; if (typeExpression != null) { return new ConstantValue2(typeExpression.ArgumentType, type, type.GetManager().Solution); } return expression.ConstantCalculator.ToTypeImplicit(expression.CompileTimeConstantValue(), type); }
/// <summary> /// Gets the condition. /// </summary> /// <param name="factory"> /// The factory. /// </param> /// <param name="leftOperand"> /// The left operand. /// </param> /// <param name="operatorSign"> /// The operator sign. /// </param> /// <param name="rightOperand"> /// The right operand. /// </param> /// <returns> /// </returns> private static ICSharpExpression GetCondition(CSharpElementFactory factory, ICSharpExpression leftOperand, string operatorSign, ICSharpExpression rightOperand) { switch (operatorSign) { case "<": operatorSign = ">="; break; case ">": operatorSign = "<="; break; case "<=": operatorSign = ">"; break; case ">=": operatorSign = "<"; break; } return factory.CreateExpression(string.Format("{0} {1} {2}", leftOperand.GetText(), operatorSign, rightOperand.GetText())); }