private bool CheckNamingOfFileAgainstTypeAndCreateWarningIfNot(ICSharpTypeDeclaration declaration) { var declaredClassName = declaration.DeclaredName; if (declaredClassName.StartsWith(Enumerable.ToArray(BDDPrefixes))) { return(false); } var currentFileName = CurrentSourceFile.GetLocation().NameWithoutExtension; if (declaration.IsPartial && currentFileName.Contains(".")) { currentFileName = currentFileName.Substring(0, currentFileName.LastIndexOf('.')); } var testClassNameFromFileName = currentFileName.Replace(".", ""); if (testClassNameFromFileName != declaredClassName) { var testingWarning = new TestClassNameDoesNotMatchFileNameWarning(declaredClassName, testClassNameFromFileName, declaration); AddHighlighting(declaration.GetNameDocumentRange(), testingWarning); return(false); } return(true); }
private void ProcessTypeDeclaration(ICSharpTypeDeclaration declaration) { if (declaration.GetContainingNode <ICSharpTypeDeclaration>() != null) { return;//Dont instpect types already within a type } var testingAttributes = FindTestingAttributes(declaration, TestAttributes); if (testingAttributes.Count == 0) { /* type is missing attributes - lets check the body */ if (!CheckMethodsForTestingAttributes(declaration, TestAttributes)) { return; } } //We have a testing attribute so now check some conformance. CheckElementIsPublicAndCreateWarningIfNot(declaration, testingAttributes); if (CheckNamingOfTypeEndsWithTestSuffix(declaration)) { if (CheckNamingOfFileAgainstTypeAndCreateWarningIfNot(declaration)) { CheckClassnameInFileNameActuallyExistsAndCreateWarningIfNot(declaration); } } }
private static bool isTypeParameter(ICSharpTypeMemberDeclaration declaration, string word) { IMethodDeclaration method = declaration as IMethodDeclaration; if (method != null) { foreach (ITypeParameterOfMethodDeclaration decl in method.TypeParameterDeclarations) { if (decl.DeclaredName == word) { return true; } } } ICSharpTypeDeclaration containingType = declaration.GetContainingTypeDeclaration(); if (containingType != null) { IClassLikeDeclaration classDecl = containingType as IClassLikeDeclaration; if (classDecl != null) { foreach (ITypeParameterOfTypeDeclaration decl in classDecl.TypeParameters) { if (decl.DeclaredName == word) { return true; } } } } return false; }
protected CodeElementModel CreateNamespaceModel([NotNull] ICSharpTypeDeclaration declaration) { var ns = declaration.OwnerNamespaceDeclaration; int id = AstManager.GetOrCreateId(ns); int typeId = PsiElementRegistrar.GetTypeId(ns); return(new CodeElementModel(typeId, id)); }
/// <summary> /// Swap base to this unless local implementation. /// </summary> /// <param name="invocationExpression"> /// The invocation expression. /// </param> public static void SwapBaseToThisUnlessLocalImplementation(IInvocationExpression invocationExpression) { bool isOverride = false; bool isNew = false; IPrimaryExpression invokedExpression = invocationExpression.InvokedExpression; if (invokedExpression != null) { IReferenceExpression referenceExpressionNode = invokedExpression as IReferenceExpression; if (referenceExpressionNode != null) { IReferenceExpression referenceExpression = invokedExpression as IReferenceExpression; if (referenceExpression != null) { ICSharpExpression qualifierExpression = referenceExpression.QualifierExpression; if (qualifierExpression is IBaseExpression) { string methodName = referenceExpressionNode.NameIdentifier.Name; ICSharpTypeDeclaration typeDeclaration = invocationExpression.GetContainingNode <ICSharpTypeDeclaration>(true); if (typeDeclaration != null) { foreach (ICSharpTypeMemberDeclaration memberDeclaration in typeDeclaration.MemberDeclarations) { if (memberDeclaration.DeclaredName == methodName) { IMethodDeclaration methodDeclaration = memberDeclaration as IMethodDeclaration; if (methodDeclaration != null) { isOverride = methodDeclaration.IsOverride; isNew = methodDeclaration.IsNew(); break; } } } if (isOverride || isNew) { return; } using (WriteLockCookie.Create(true)) { // swap the base to this ICSharpExpression expression = CSharpElementFactory.GetInstance(invocationExpression.GetPsiModule()).CreateExpression("this"); referenceExpression.SetQualifierExpression(expression); } } } } } } }
public MoveClassBulbItem([NotNull] ICSharpTypeDeclaration sourceTypeDeclaration, IProject destinationProject) { if (sourceTypeDeclaration == null) { throw new ArgumentNullException("typeDeclaration"); } _sourceTypeDeclaration = sourceTypeDeclaration; _destinationProject = destinationProject; }
static bool IsPublicSurfaceArea([NotNull] ICSharpTypeDeclaration typeDeclaration) { switch (typeDeclaration.GetAccessRights()) { case AccessRights.PUBLIC: case AccessRights.PROTECTED: case AccessRights.PROTECTED_OR_INTERNAL: return(true); default: return(false); } }
public static ICSharpTypeDeclaration FindFirstCharpTypeDeclarationInDocument(ISolution solution, IDocument document) { for (int i = document.DocumentRange.StartOffset; i < document.DocumentRange.EndOffset; i++) { ICSharpTypeDeclaration declaration = TextControlToPsi .GetElements <ICSharpTypeDeclaration>(solution, new DocumentOffset(document, i)).FirstOrDefault(); if (declaration != null) { return(declaration); } } return(null); }
private static bool isClassMemberDeclaration(ICSharpTypeMemberDeclaration declaration, string word) { ICSharpTypeDeclaration containingType = declaration.GetContainingTypeDeclaration(); if (containingType != null) { string withDot = "." + word; foreach (ICSharpTypeMemberDeclaration decl in containingType.MemberDeclarations) { if (decl.DeclaredName == word || decl.DeclaredName.EndsWith(withDot)) { return true; } } } return false; }
private static bool CheckMethodsForTestingAttributes(ICSharpTypeDeclaration declaration, IList <string> testAttributes) { var sourceFile = declaration.GetSourceFile(); if (declaration.DeclaredElement == null) { return(false); } foreach (var m in declaration.DeclaredElement.Methods.SelectMany(m => m.GetDeclarationsIn(sourceFile)).OfType <IAttributesOwnerDeclaration>()) { if (Enumerable.Any(FindTestingAttributes(m, testAttributes))) { return(true); } } return(false); }
private void AnalyzeType(ICSharpTypeDeclaration aType, IPsiSourceFile psiSourceFile) { _logger.Info("Analyzing type '{0}'...", aType.CLRName); try { var ctx = ContextAnalysis.Analyze(aType, psiSourceFile, _logger).Context; _cbContext(ctx); } catch (Exception e) { _logger.Error(e); } foreach (var innerType in aType.TypeDeclarations.OfType <ICSharpTypeDeclaration>()) { AnalyzeType(innerType, psiSourceFile); } }
private bool CheckNamingOfTypeEndsWithTestSuffix(ICSharpTypeDeclaration declaration) { if (declaration.IsAbstract) { return(true); } var declaredClassName = declaration.DeclaredName; if (!declaredClassName.StartsWith(Enumerable.ToArray(BDDPrefixes))) { if (!declaredClassName.EndsWith(Settings.TestClassSuffixes())) { var testingWarning = new TestClassNameSuffixWarning(Settings.TestClassSuffix, declaration); AddHighlighting(declaration.GetNameDocumentRange(), testingWarning); return(false); } } return(true); }
/// <summary> /// Returns an xml string of the documentation for an element. /// </summary> /// <param name="owner"> /// The owner of the doc comment block. /// </param> /// <param name="docConfig"> /// The config for the current ProjectFile. /// </param> /// <returns> /// A string of the declarations summary text. /// </returns> private static string CreateDocumentationForElement(IDocCommentBlockOwnerNode owner, DocumentationRulesConfiguration docConfig) { ITreeNode element = owner; IDeclaredElement declaredElement = (element is IDeclaration) ? ((IDeclaration)element).DeclaredElement : null; StringBuilder text = new StringBuilder(); text.AppendLine("<summary>"); string summaryText = string.Empty; if (element is IConstructorDeclaration) { summaryText = Utils.CreateSummaryForConstructorDeclaration((IConstructorDeclaration)element); } if (element is IDestructorDeclaration) { summaryText = Utils.CreateSummaryForDestructorDeclaration((IDestructorDeclaration)element); } if (element is IPropertyDeclaration) { summaryText = Utils.CreateSummaryDocumentationForProperty((IPropertyDeclaration)element); } text.AppendLine(summaryText); text.AppendLine("</summary>"); ICSharpParametersOwnerDeclaration declarationWithParameters = element as ICSharpParametersOwnerDeclaration; if (declarationWithParameters != null) { foreach (IRegularParameterDeclaration parameterDeclaration in declarationWithParameters.ParameterDeclarations) { text.AppendLine(Utils.CreateDocumentationForParameter(parameterDeclaration)); } } ICSharpTypeDeclaration typeDeclaration = element as ICSharpTypeDeclaration; if (typeDeclaration != null && (typeDeclaration.TypeParameters.Count > 0)) { foreach (ITypeParameterOfTypeDeclaration typeParameter in typeDeclaration.TypeParameters) { text.AppendLine(Utils.CreateDocumentationForParameter(typeParameter)); } } ITypeParametersOwner typeParametersOwner = element as ITypeParametersOwner; if (typeParametersOwner != null && (typeParametersOwner.TypeParameters.Count > 0)) { foreach (ITypeParameter typeParameter in typeParametersOwner.TypeParameters) { text.AppendLine(Utils.CreateDocumentationForTypeParameterDeclaration((ITypeParameterDeclaration)typeParameter)); } } IMethodDeclaration methodDeclaration = element as IMethodDeclaration; if (methodDeclaration != null && (methodDeclaration.TypeParameterDeclarations.Count > 0)) { foreach (ITypeParameterOfMethodDeclaration typeParameter in methodDeclaration.TypeParameterDeclarations) { text.AppendLine(Utils.CreateDocumentationForParameter(typeParameter)); } } IParametersOwner parametersOwner = declaredElement as IParametersOwner; if ((parametersOwner != null && ((parametersOwner is IMethod) || (parametersOwner is IOperator))) && !parametersOwner.ReturnType.Equals(parametersOwner.Module.GetPredefinedType().Void)) { text.AppendLine("<returns></returns>"); } bool ruleIsEnabled = docConfig.GetStyleCopRuleEnabled("PropertyDocumentationMustHaveValue"); if (element is IPropertyDeclaration && ruleIsEnabled) { text.AppendLine(Utils.CreateValueDocumentationForProperty((IPropertyDeclaration)element)); } List <IType> exceptions = new List <IType>(); ICSharpFunctionDeclaration functionDeclaration = element as ICSharpFunctionDeclaration; if (functionDeclaration != null && functionDeclaration.Body != null) { CollectExceptions(functionDeclaration.Body, exceptions); } IPropertyDeclaration propertyDeclaration = element as IPropertyDeclaration; if (propertyDeclaration != null) { CollectExceptions(propertyDeclaration.AccessorDeclarations, exceptions); } IIndexerDeclaration indexerDeclaration = element as IIndexerDeclaration; if (indexerDeclaration != null) { CollectExceptions(indexerDeclaration.AccessorDeclarations, exceptions); } IEventDeclaration eventDeclaration = element as IEventDeclaration; if (eventDeclaration != null) { CollectExceptions(eventDeclaration.AccessorDeclarations, exceptions); } foreach (IType exception in exceptions) { string presentableName = exception.GetPresentableName(CSharpLanguage.Instance); string a = Utils.StripClassName(presentableName); string b = exception.ToString(); text.AppendLine("<exception cref=\"" + Utils.SwapGenericTypeToDocumentation(a) + "\"></exception>"); } return(text.ToString()); }
public void RemoveTypeDeclaration(ICSharpTypeDeclaration param) { _file.RemoveTypeDeclaration(param); }
private void CheckClassNamespaceOfTestMatchesClassUnderTest(ICSharpTypeDeclaration thisDeclaration, List <IClrDeclaredElement> declaredElements) { var thisProject = thisDeclaration.GetProject(); if (thisProject == null) { return; } var associatedProject = thisProject.GetAssociatedProjects(CurrentSourceFile.ToProjectFile()).FirstOrDefault(); if (associatedProject == null) { return; } ResharperHelper.RemoveElementsNotInProjects(declaredElements, new [] { associatedProject.Project }); var thisProjectsDefaultNamespace = thisProject.GetDefaultNamespace(); if (string.IsNullOrEmpty(thisProjectsDefaultNamespace)) { return; } var associatedProjectsDefaultNameSpace = associatedProject.Project.GetDefaultNamespace(); if (string.IsNullOrEmpty(associatedProjectsDefaultNameSpace)) { return; } //var nsToBeFoundShouldBe = associatedProject.Project.GetDefaultNamespace()+associatedProject.SubNamespace; var nsToBeFoundShouldBe = associatedProject.FullNamespace(); //Lookup the namespaces of the declaredElements we've found that possibly match this test IList <string> foundNameSpaces = new List <string>(); foreach (var declaredTestElement in declaredElements) { var cls = declaredTestElement as TypeElement; if (cls == null) { continue; } var ns = cls.OwnerNamespaceDeclaration(); if (nsToBeFoundShouldBe == ns) { return;//found a match ! } foundNameSpaces.Add(ns); } foreach (var ns in foundNameSpaces) { if (ns.StartsWith(associatedProjectsDefaultNameSpace)) { //TODO: Review this can be probably be replaced with associatedProject method calls var targetsubNameSpace = ns.Substring(associatedProjectsDefaultNameSpace.Length).TrimStart(new[] { '.' }); string suggestedNameSpace = thisProjectsDefaultNamespace.AppendIfNotNull(".", targetsubNameSpace); var targetFolder = thisProject.Location.Combine(targetsubNameSpace.Replace(".", @"\")); var highlight = new TestFileNameSpaceWarning(CurrentSourceFile.ToProjectFile(), thisDeclaration, suggestedNameSpace , thisProject, targetFolder); AddHighlighting(thisDeclaration.GetNameDocumentRange(), highlight); } } }
private void CheckClassnameInFileNameActuallyExistsAndCreateWarningIfNot(ICSharpTypeDeclaration thisDeclaration) { if (thisDeclaration.IsAbstract) { return; } var currentFileName = CurrentSourceFile.GetLocation().NameWithoutExtension; var appropriateTestClassSuffixes = TestCopSettingsManager.Instance.Settings.GetAppropriateTestClassSuffixes(currentFileName); foreach (var testClassSuffix in appropriateTestClassSuffixes) { var className = currentFileName.Split(new[] { '.' }, 2)[0].RemoveTrailing(testClassSuffix); var declaredElements = ResharperHelper.FindClass(Solution, className); var currentProject = thisDeclaration.GetProject(); var currentDeclarationNamespace = thisDeclaration.OwnerNamespaceDeclaration != null ? thisDeclaration.OwnerNamespaceDeclaration.DeclaredName : ""; var associatedProjects = currentProject.GetAssociatedProjects(CurrentSourceFile.ToProjectFile()); if (associatedProjects == null || associatedProjects.Count == 0) { var highlight = new TestFileNameWarning( "Project for this test assembly was not found - check namespace of projects", thisDeclaration); AddHighlighting(thisDeclaration.GetNameDocumentRange(), highlight); return; } var filteredDeclaredElements = new List <IClrDeclaredElement>(declaredElements); ResharperHelper.RemoveElementsNotInProjects(filteredDeclaredElements, associatedProjects.Select(p => p.Project).ToList()); if (filteredDeclaredElements.Count == 0) { string message = string.Format( "The file name begins with {0} but no matching class exists in associated project", className); foreach (var declaredElement in declaredElements) { var cls = declaredElement as TypeElement; if (cls != null) { message += string.Format("\nHas it moved to {0}.{1} ?", cls.OwnerNamespaceDeclaration(), cls.GetClrName()); } } var highlight = new TestFileNameWarning(message, thisDeclaration); AddHighlighting(thisDeclaration.GetNameDocumentRange(), highlight); return; } if (Settings.CheckTestNamespaces) { CheckClassNamespaceOfTestMatchesClassUnderTest(thisDeclaration, declaredElements); } } }
public MoveClass([NotNull] ICSharpTypeDeclaration sourceTypeDeclaration, IProject destinationProject) : base(sourceTypeDeclaration, destinationProject) { CopiedFileToNewProject = false; }
void IExecutableAction.Execute(IDataContext context, DelegateExecute nextExecute) { ITextControl textControl = context.GetData(TextControlDataConstants.TEXT_CONTROL); if (textControl == null) { MessageBox.ShowError("Text control unavailable."); return; } ISolution solution = context.GetData(ProjectModelDataConstants.SOLUTION); if (solution == null) { return; } IClrTypeName clrTypeClassName = ResharperHelper.GetClassNameAppropriateToLocation(solution, textControl); if (clrTypeClassName == null) { return; } ICSharpTypeDeclaration typeDeclaration = ResharperHelper.FindFirstCharpTypeDeclarationInDocument(solution, textControl.Document); if (typeDeclaration == null) { return; } IProject currentProject = context.GetData(ProjectModelDataConstants.PROJECT); if (currentProject == null) { ResharperHelper.AppendLineToOutputWindow(solution.Locks, "Internal Error: No current project"); return; } IList <TestCopProjectItem> targetProjects = currentProject.GetAssociatedProjects(textControl.ToProjectFile(solution)); if (targetProjects.IsEmpty()) { ResharperHelper.AppendLineToOutputWindow(solution.Locks, "Unable to locate associated assembly - check project namespaces and testcop Regex"); //ProjectMappingHelper.GetProjectMappingHeper().DumpDebug(solution); return; } TestFileAnalysisSettings settings = solution.GetPsiServices().SettingsStore .BindToContextTransient(ContextRange.Smart(textControl.ToDataContext())) .GetKey <TestFileAnalysisSettings>(SettingsOptimization.OptimizeDefault); string baseFileName = ResharperHelper.GetBaseFileName(context, solution); bool isTestFile = baseFileName.EndsWith(settings.TestClassSuffixes()); if (isTestFile != currentProject.IsTestProject()) { ResharperHelper.AppendLineToOutputWindow(solution.Locks, string.Format( "Don't know how to navigate with '{0}' within project '{1}'. It is a {2} file within a {3} project" , baseFileName, currentProject.Name, isTestFile ? "test" : "code", currentProject.IsTestProject() ? "test" : "code")); return; } List <IClrDeclaredElement> elementsFoundInTarget = new List <IClrDeclaredElement>(); List <IClrDeclaredElement> elementsFoundInSolution = new List <IClrDeclaredElement>(); foreach (TestCopProjectItem singleTargetProject in targetProjects) { foreach (TestCopProjectItem.FilePatternMatcher patternMatcher in singleTargetProject.FilePattern) { // FindByClassName elementsFoundInSolution.AddRangeIfMissing( ResharperHelper.FindClass(solution, patternMatcher.RegEx.ToString()), this._declElementMatcher); elementsFoundInTarget.AddRangeIfMissing( ResharperHelper.FindClass(solution, patternMatcher.RegEx.ToString(), new List <IProject> { singleTargetProject.Project }), this._declElementMatcher); if (!isTestFile) { //Find via filename (for when we switch to test files) IEnumerable <ITypeElement> otherMatches = ResharperHelper.FindFirstTypeWithinCodeFiles(solution, patternMatcher.RegEx, singleTargetProject.Project); elementsFoundInTarget.AddRangeIfMissing(otherMatches, this._declElementMatcher); } } } if (!isTestFile) { IEnumerable <IClrDeclaredElement> references = this.FindReferencesWithinAssociatedAssembly(context, solution, textControl, clrTypeClassName, targetProjects); elementsFoundInTarget.AddRangeIfMissing(references, this._declElementMatcher); } JumpToTestMenuHelper.PromptToOpenOrCreateClassFiles(this._menuDisplayer, textControl.Lifetime, context, solution , currentProject, clrTypeClassName, targetProjects , elementsFoundInTarget, elementsFoundInSolution); }
/// <summary> /// Swap base to this unless local implementation. /// </summary> /// <param name="invocationExpression"> /// The invocation expression. /// </param> public static void SwapBaseToThisUnlessLocalImplementation(IInvocationExpression invocationExpression) { bool isOverride = false; bool isNew = false; IPrimaryExpression invokedExpression = invocationExpression.InvokedExpression; if (invokedExpression == null) { return; } IReferenceExpression referenceExpression = invokedExpression as IReferenceExpression; if (referenceExpression == null) { return; } ICSharpExpression qualifierExpression = referenceExpression.QualifierExpression; if (!(qualifierExpression is IBaseExpression)) { return; } ICSharpTypeDeclaration typeDeclaration = invocationExpression.GetContainingNode <ICSharpTypeDeclaration>(true); if (typeDeclaration == null) { return; } ITypeElement typeDeclaredElement = typeDeclaration.DeclaredElement; if (typeDeclaredElement == null) { return; } IDeclaredElement referenceDeclaredElement = referenceExpression.Reference.Resolve().DeclaredElement; if (referenceDeclaredElement == null) { return; } foreach (var member in typeDeclaredElement.GetAllClassMembers(referenceDeclaredElement.ShortName)) { if (!member.Equals(referenceDeclaredElement)) { continue; } using (WriteLockCookie.Create(true)) { // swap the base to this ICSharpExpression expression = CSharpElementFactory.GetInstance(invocationExpression.GetPsiModule()).CreateExpression("this"); referenceExpression.SetQualifierExpression(expression); } } }
public MakeSerializable(ICSharpTypeDeclaration typeDeclaration) { myTypeDeclaration = typeDeclaration; }
public ICSharpTypeDeclaration AddTypeDeclarationAfter(ICSharpTypeDeclaration param, ICSharpTypeDeclaration anchor) { return(_file.AddTypeDeclarationAfter(param, anchor)); }
public ICSharpTypeDeclaration AddTypeDeclarationBefore(ICSharpTypeDeclaration param, ICSharpTypeDeclaration anchor) { return _file.AddTypeDeclarationBefore(param, anchor); }