/// <summary> /// This method provides a <see cref="IDaemonStageProcess"/> instance which is assigned to highlighting a single document. /// </summary> protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { if (process == null) throw new ArgumentNullException("process"); return new CloneDetectionDaemonStageProcess(process); }
/// <summary> /// Initializes a new instance of the <see cref="FileHeader"/> class. /// </summary> /// <param name="file"> /// The file to load the header for. /// </param> public FileHeader(ICSharpFile file) { try { this.File = file; string headerText = Utils.GetFileHeader(file); if (string.IsNullOrEmpty(headerText)) { // no header provided so we'll load the default one headerText = StandardHeader; } this.LoadFileHeader(headerText); } catch (XmlException) { this.ResetToStandardHeader(); } catch (ArgumentException) { this.headerXml = null; } this.InsertSummary = true; }
private IEnumerable<IClassDeclaration> GetClassDeclarations(ICSharpFile csharpFile) { var namespaceDeclarations = csharpFile.NamespaceDeclarations.SelectMany(x => x.DescendantsAndSelf(y => y.NamespaceDeclarations)); var classDeclarations = namespaceDeclarations.Cast<ITypeDeclarationHolder>().SelectMany(x => x.TypeDeclarations) .SelectMany(x => x.DescendantsAndSelf(y => y.TypeDeclarations)).OfType<IClassDeclaration>(); return classDeclarations; }
public DaemonStageProcess(IDaemonProcess process, SearchDomainFactory searchDomainFactory, ICSharpFile csFile) { this.searchDomainFactory = searchDomainFactory; this.csFile = csFile; DaemonProcess = process; usages = process.GetStageProcess<CollectUsagesStageProcess>(); Assertion.Assert(usages != null, "usages != null"); }
protected ContextActionExecutorBase(ICSharpStatement statement) { Contract.Requires(statement != null); _psiModule = statement.GetPsiModule(); _psiServices = statement.GetPsiServices(); _factory = CSharpElementFactory.GetInstance(statement); _currentFile = (ICSharpFile)statement.GetContainingFile(); }
/// <summary> /// Executes the specified options. /// </summary> /// <param name="options">The options.</param> /// <param name="file">The file.</param> public void Execute(ValueAnalysisOptions options, ICSharpFile file) { foreach (var namespaceDeclaration in file.NamespaceDeclarations) { this.ProcessCSharpTypeDeclarations(options, namespaceDeclaration.TypeDeclarations); } this.ProcessCSharpTypeDeclarations(options, file.TypeDeclarations); }
protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { if (processKind == DaemonProcessKind.VISIBLE_DOCUMENT && settings.GetValue(HighlightingSettingsAccessor.ColorUsageHighlightingEnabled)) { return new UnityColorHighlighterProcess(process, settings, file); } return null; }
public ExceptionalDaemonStageProcess(ICSharpFile file, IContextBoundSettingsStore settings) : base(ServiceLocator.Process, file) { _settings = settings; #if R2016_1 || R2016_2 _consumer = new FilteringHighlightingConsumer(this, _settings, file); #else _consumer = new DefaultHighlightingConsumer(this, _settings); #endif }
protected override IDaemonStageProcess CreateProcess( IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { var testFile = file.ToTestFile(); if (testFile == null) return null; return new TestFileDaemonStageProcess(process, testFile, _testFileAnalyzers); }
/// <summary> /// Initializes a new instance of the StyleCopStageProcess class, using the specified <see cref="IDaemonProcess"/> . /// </summary> /// <param name="lifetime"> /// The <see cref="Lifetime"/> of the owning <see cref="IDaemonProcess"/> /// </param> /// <param name="apiPool"> /// A reference to the StyleCop runner. /// </param> /// <param name="daemon"> /// A reference to the <see cref="IDaemon"/> manager. /// </param> /// <param name="daemonProcess"> /// <see cref="IDaemonProcess"/> to execute within. /// </param> /// <param name="threading"> /// A reference to the <see cref="IThreading"/> instance for timed actions. /// </param> /// <param name="file"> /// The file to analyze. /// </param> public StyleCopStageProcess(Lifetime lifetime, StyleCopApiPool apiPool, IDaemon daemon, IDaemonProcess daemonProcess, IThreading threading, ICSharpFile file) { StyleCopTrace.In(daemonProcess, file); this.lifetime = lifetime; this.apiPool = apiPool; this.daemon = daemon; this.daemonProcess = daemonProcess; this.threading = threading; this.file = file; StyleCopTrace.Out(); }
public CleanCodeDaemonStageProcess(IDaemonProcess daemonProcess, ICSharpFile file, IContextBoundSettingsStore settingsStore) : base(daemonProcess, file) { this.settingsStore = settingsStore; // Simple checks. methodTooLongCheck = new MethodTooLongCheck(settingsStore); classTooBigCheck = new ClassTooBigCheck(settingsStore); tooManyArgumentsCheck = new TooManyMethodArgumentsCheck(settingsStore); excessiveIndentationCheck = new ExcessiveIndentationCheck(settingsStore); tooManyDependenciesCheck = new TooManyDependenciesCheck(settingsStore); methodNamesNotMeaningfulCheck = new MethodNamesNotMeaningfulCheck(settingsStore); tooManyChainedReferencesCheck = new TooManyChainedReferencesCheck(settingsStore); }
public ITestFile GetTestFile(ICSharpFile csharpFile) { var assemblyIdentity = new Identity(_project.GetOutputFilePath().FullPath); var classTests = TreeNodeEnumerable.Create( () => { return GetClassDeclarations(csharpFile) .TakeWhile(_notInterrupted) .Select(x => GetClassTest(x, assemblyIdentity)) .WhereNotNull(); }); return new TestFile(classTests, csharpFile); }
protected ContextActionExecutorBase(ICSharpContextActionDataProvider provider) { Contract.Requires(provider != null); _factory = provider.ElementFactory; Contract.Assert(provider.SelectedElement != null, "Can't create executor if SelectedElement is null"); _currentFile = (ICSharpFile)provider.SelectedElement.GetContainingFile(); _psiServices = provider.PsiServices; _psiModule = provider.PsiModule; }
/// <summary> /// Invoked by ReSharper each time it wants us to perform some background processing /// of a file. /// </summary> /// <param name="process">Provides information about and services relating to the /// work we are being asked to do.</param> /// <param name="settings">Settings information.</param> /// <param name="processKind">The kind of processing we're being asked to do.</param> /// <param name="file">The file to be processed.</param> /// <returns>A process object representing the work, or null if no work will be done.</returns> protected override IDaemonStageProcess CreateProcess( IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { if (process == null) { throw new ArgumentNullException("process"); } // StyleCop's daemon stage looks for a processKind of DaemonProcessKind.OTHER // and does nothing (returns null) if it sees it. This turns out to prevent // highlights from showing up when you ask ReSharper to inspect code issues // across the whole solution. I'm not sure why StyleCop deliberately opts out // of it. Perhaps something goes horribly wrong, but I've not seen any sign // of that yet, and we really do want solution-wide inspection to work. try { // I guess the base class checks that this is actually a C# file? if (!IsSupported(process.SourceFile)) { return null; } // StyleCop checks to see if there are already any errors in the file, and if // there are, it decides to do nothing. // TODO: Do we need to do that? // TODO: We should probably check for exemptions, e.g. generated source files. } catch (ProcessCancelledException) { return null; } // TODO: should we get an injected ISettingsOptimization? var orderUsingSettings = settings.GetKey<OrderUsingsSettings>(SettingsOptimization.DoMeSlowly); OrderUsingsConfiguration config = null; if (!string.IsNullOrWhiteSpace(orderUsingSettings.OrderSpecificationXml)) { config = ConfigurationSerializer.FromXml(new StringReader(orderUsingSettings.OrderSpecificationXml)); } return new OrderUsingsDaemonStageProcess(process, file, config); }
public AddContractClassExecutor(ICSharpContextActionDataProvider provider, AddContractClassAvailability addContractForAvailability, ICSharpFunctionDeclaration requiredFunction = null) { Contract.Requires(provider != null); Contract.Requires(addContractForAvailability != null); Contract.Requires(addContractForAvailability.IsAvailable); _addContractForAvailability = addContractForAvailability; _provider = provider; _requiredFunction = requiredFunction; _factory = _provider.ElementFactory; // TODO: look at this class CSharpStatementNavigator Contract.Assert(provider.SelectedElement != null); _currentFile = (ICSharpFile)provider.SelectedElement.GetContainingFile(); }
public AddContractForExecutor(AddContractForAvailability addContractForAvailability, ICSharpContextActionDataProvider provider) { Contract.Requires(addContractForAvailability != null); Contract.Requires(addContractForAvailability.IsAvailable); Contract.Requires(provider != null); _addContractForAvailability = addContractForAvailability; _provider = provider; _factory = CSharpElementFactory.GetInstance(provider.PsiModule); // TODO: look at this class CSharpStatementNavigator _classDeclaration = provider.GetSelectedElement<IClassLikeDeclaration>(true, true); Contract.Assert(provider.SelectedElement != null); _currentFile = (ICSharpFile)provider.SelectedElement.GetContainingFile(); }
private static void EnsureNamespaceExists(ICSharpFile file, CSharpElementFactory factory) { var namespaceExists = file.NamespaceDeclarationNodes.Any( n => n.Imports.Any(d => d.ImportedSymbolName.QualifiedName == AsObservableNamespace)); if (!namespaceExists) { var directive = factory.CreateUsingDirective(AsObservableNamespace); var namespaceNode = file.NamespaceDeclarationNodes.FirstOrDefault(); if (namespaceNode != null) { UsingUtil.AddImportTo(namespaceNode, directive); } else { UsingUtil.AddImportTo(file, directive); } } }
public TestFileAnalysisDaemonStageProcess(IDaemonProcess daemonProcess, IContextBoundSettingsStore settings, ICSharpFile file) : base(daemonProcess, file) { _myDaemonProcess = daemonProcess; _settings = settings; }
protected FileBase(ICSharpFile file) : base(file) { _file = file; }
/// <summary> /// Checks declaration comment blocks. /// </summary> /// <param name="file"> /// The <see cref="ICSharpFile"/> to use. /// </param> /// <param name="declaration"> /// The <see cref="IDeclaration"/> to check. /// </param> /// <param name="options"> /// <see cref="OrderingOptions"/>Current options that we can reference. /// </param> public void CheckDeclarationDocumentation(ICSharpFile file, IDeclaration declaration, DocumentationOptions options) { Param.RequireNotNull(file, "file"); Param.RequireNotNull(declaration, "declaration"); Param.Ignore(options); bool insertMissingElementDocOption = true; bool documentationTextMustBeginWithACapitalLetter = true; bool documentationTextMustEndWithAPeriod = true; bool elementDocumentationMustHaveSummary = true; bool constructorSummaryDocBeginsWithStandardText = true; bool destructorSummaryDocBeginsWithStandardText = true; bool propertyDocumentationMustHaveValueDocumented = true; bool insertMissingParamTagOption = true; bool genericTypeParametersMustBeDocumented = true; if (options != null) { insertMissingElementDocOption = options.SA1600ElementsMustBeDocumented; documentationTextMustBeginWithACapitalLetter = options.SA1628DocumentationTextMustBeginWithACapitalLetter; documentationTextMustEndWithAPeriod = options.SA1629DocumentationTextMustEndWithAPeriod; elementDocumentationMustHaveSummary = options.SA1604ElementDocumentationMustHaveSummary; constructorSummaryDocBeginsWithStandardText = options.SA1642ConstructorSummaryDocumentationMustBeginWithStandardText; destructorSummaryDocBeginsWithStandardText = options.SA1643DestructorSummaryDocumentationMustBeginWithStandardText; propertyDocumentationMustHaveValueDocumented = options.SA1609PropertyDocumentationMustHaveValue; insertMissingParamTagOption = options.SA1611ElementParametersMustBeDocumented; genericTypeParametersMustBeDocumented = options.SA1618GenericTypeParametersMustBeDocumented; } DeclarationHeader declarationHeader = new DeclarationHeader(declaration); bool formatSummary = false; if (insertMissingElementDocOption && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1600) && declarationHeader.IsMissing) { formatSummary = this.InsertMissingDeclarationHeader(file, declaration); } if (elementDocumentationMustHaveSummary && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1604) && !declarationHeader.HasSummary) { formatSummary = formatSummary | this.InsertMissingSummaryElement(declaration); } if (formatSummary) { this.FormatSummaryElement(declaration); } if (declaration is IConstructorDeclaration) { if (insertMissingParamTagOption && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1611)) { IConstructorDeclaration constructorDeclaration = declaration as IConstructorDeclaration; if (constructorDeclaration.ParameterDeclarations.Count > 0) { this.InsertMissingParamElement(constructorDeclaration); } } if (constructorSummaryDocBeginsWithStandardText && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1642)) { this.EnsureConstructorSummaryDocBeginsWithStandardText(declaration as IConstructorDeclaration); } } DocumentationRulesConfiguration docConfig = this.GetDocumentationRulesConfig(file); // However it can be on/off depending on the file so we'd have to cache it per file bool ruleIsEnabled = docConfig.GetStyleCopRuleEnabled("DocumentationTextMustBeginWithACapitalLetter"); if (documentationTextMustBeginWithACapitalLetter && ruleIsEnabled && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1628)) { this.EnsureDocumentationTextIsUppercase(declaration); } ruleIsEnabled = docConfig.GetStyleCopRuleEnabled("DocumentationTextMustEndWithAPeriod"); if (documentationTextMustEndWithAPeriod && ruleIsEnabled && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1629)) { this.EnsureDocumentationTextEndsWithAPeriod(declaration); } if (declaration is IDestructorDeclaration) { if (destructorSummaryDocBeginsWithStandardText && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1643)) { this.EnsureDestructorSummaryDocBeginsWithStandardText(declaration as IDestructorDeclaration); } } if (declaration is IMethodDeclaration || declaration is IIndexerDeclaration) { this.CheckMethodAndIndexerDeclarationDocumentation(declaration as IParametersOwnerDeclaration, options); } if (declaration is IPropertyDeclaration) { ruleIsEnabled = docConfig.GetStyleCopRuleEnabled("PropertyDocumentationMustHaveValue"); if (propertyDocumentationMustHaveValueDocumented && ruleIsEnabled && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1609)) { this.InsertValueElement(declaration as IPropertyDeclaration); } } if (declaration is ITypeParametersOwner && (genericTypeParametersMustBeDocumented && !Utils.IsRuleSuppressed(declaration, StyleCopRules.SA1618))) { this.InsertMissingTypeParamElement(declaration); } }
private bool IsAnalysisEnabled(IContextBoundSettingsStore settingsStore, ICSharpFile file) { var enabled = settingsStore.GetValue <StyleCopOptionsSettingsKey, bool>(key => key.AnalysisEnabled); return(enabled && !this.referencedAnalyzersCache.IsAnalyzerReferenced(file.GetProject(), "stylecop.analyzers")); }
/// <summary> /// Updates the existing header or inserts one if missing. /// </summary> /// <param name="file"> /// THe file to check the header on. /// </param> public void InsertFileHeader(ICSharpFile file) { FileHeader fileHeader = new FileHeader(file); DocumentationRulesConfiguration docConfig = this.GetDocumentationRulesConfig(file); fileHeader.FileName = file.GetSourceFile().ToProjectFile().Location.Name; fileHeader.CompanyName = docConfig.CompanyName; fileHeader.CopyrightText = docConfig.Copyright; fileHeader.Summary = Utils.GetSummaryText(file); fileHeader.Update(); }
/// <summary> /// Inserts the file name into the file. /// </summary> /// <param name="file"> /// The file to insert into. /// </param> public void InsertFileName(ICSharpFile file) { string fileName = file.GetSourceFile().ToProjectFile().Location.Name; FileHeader fileHeader = new FileHeader(file) { FileName = fileName }; fileHeader.Update(); }
public T4CSharpErrorProcess(IDaemonProcess process, IContextBoundSettingsStore settingsStore, ICSharpFile file) : base(process, settingsStore, file) { }
/// <summary> /// Daemon stage for analysis. This class is automatically loaded by ReSharper daemon /// because it's marked with the attribute. /// </summary> protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { if (process == null) { throw new ArgumentNullException("process"); } return(new ProjectAnalysisDaemonStageProcess(process, settings, file)); }
protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { if (!file.GetProject().IsUnityProject()) { return(null); } return(new UnityHighlightingProcess(process, file, HiglightingProviders, API, UnityHighlightingContributor, processKind)); }
/// <summary> /// Initializes a new instance of the StyleCopStageProcess class, using the specified <see cref="IDaemonProcess"/> . /// </summary> /// <param name="lifetime"> /// The <see cref="Lifetime"/> of the owning <see cref="IDaemonProcess"/> /// </param> /// <param name="apiPool"> /// A reference to the StyleCop runner. /// </param> /// <param name="daemon"> /// A reference to the <see cref="IDaemon"/> manager. /// </param> /// <param name="daemonProcess"> /// <see cref="IDaemonProcess"/> to execute within. /// </param> /// <param name="threading"> /// A reference to the <see cref="IThreading"/> instance for timed actions. /// </param> /// <param name="settings"> /// The current settings. /// </param> /// <param name="file"> /// The file to analyze. /// </param> public StyleCopStageProcess(Lifetime lifetime, StyleCopApiPool apiPool, IDaemon daemon, IDaemonProcess daemonProcess, IThreading threading, IContextBoundSettingsStore settings, ICSharpFile file) { StyleCopTrace.In(daemonProcess, file); this.lifetime = lifetime; this.apiPool = apiPool; this.daemon = daemon; this.daemonProcess = daemonProcess; this.threading = threading; this.settings = settings; this.file = file; StyleCopTrace.Out(); }
public TestFile(IEnumerable <ITestDeclaration> testDeclarations, ICSharpFile file) : base(file) { TestDeclarations = testDeclarations; }
private static void SwapFileHeaderNode(ICSharpFile file, string newHeader) { ITreeRange existingHeaderRange = Utils.GetFileHeaderTreeRange(file); using (WriteLockCookie.Create(file.IsPhysical())) { ICommentNode newCommentNode; if (existingHeaderRange.IsEmpty) { // existing header missing so add on a new line for our new header newHeader += Environment.NewLine; IWhitespaceNode node = file.ToTreeNode().FirstChild as IWhitespaceNode; bool insertNewLine = true; while (node != null) { if (node.IsNewLine) { insertNewLine = false; break; } node = node.NextSibling as IWhitespaceNode; } if (insertNewLine) { newHeader += Environment.NewLine; } newCommentNode = (ICommentNode) CSharpTokenType.END_OF_LINE_COMMENT.Create(new JB::JetBrains.Text.StringBuffer(newHeader), new TreeOffset(0), new TreeOffset(newHeader.Length)); LowLevelModificationUtil.AddChildBefore(file.ToTreeNode().FirstChild, new ITreeNode[] { newCommentNode }); } else { ITokenNode lastToken = (ITokenNode)existingHeaderRange.Last; ITokenNode nextToken = lastToken.GetNextToken(); if (nextToken != null) { ITokenNode nextNextToken = nextToken.GetNextToken(); if (nextNextToken != null) { ITokenNode nextNextNextToken = nextNextToken.GetNextToken(); if (!nextToken.IsNewLine() || !nextNextToken.IsNewLine()) { newHeader += Environment.NewLine; } if (nextNextNextToken.GetTokenType() == CSharpTokenType.PP_SHARP && nextToken.IsNewLine() && nextNextToken.IsNewLine()) { newHeader += Environment.NewLine; } newCommentNode = (ICommentNode) CSharpTokenType.END_OF_LINE_COMMENT.Create( new JB::JetBrains.Text.StringBuffer(newHeader), new TreeOffset(0), new TreeOffset(newHeader.Length)); LowLevelModificationUtil.ReplaceChildRange(existingHeaderRange.First, existingHeaderRange.Last, new ITreeNode[] { newCommentNode }); } } } } }
/// <summary> /// This method provides a <see cref="IDaemonStageProcess"/> instance which is assigned to highlighting a single document. /// </summary> /// <param name="process"> /// Current Daemon Process. /// </param> /// <param name="settingsStore"> /// The settingsStore store to use. /// </param> /// <param name="processKind"> /// The process kind. /// </param> /// <param name="file"> /// The file to analyze. /// </param> /// /// /// <returns> /// The current <see cref="IDaemonStageProcess"/>. /// </returns> protected override IDaemonStageProcess CreateProcess( IDaemonProcess process, IContextBoundSettingsStore settingsStore, DaemonProcessKind processKind, ICSharpFile file) { StyleCopTrace.In(process, settingsStore, processKind, file); if (process == null) { throw new ArgumentNullException("process"); } try { if (processKind == DaemonProcessKind.OTHER) { StyleCopTrace.Info("ProcessKind Other."); StyleCopTrace.Out(); return(null); } if (!this.IsAnalysisEnabled(settingsStore, file)) { StyleCopTrace.Info("Analysis disabled."); StyleCopTrace.Out(); return(null); } if (!this.IsSupported(process.SourceFile)) { StyleCopTrace.Info("File type not supported."); StyleCopTrace.Out(); return(null); } if (!this.FileIsValid(file)) { StyleCopTrace.Info("Source file not valid."); StyleCopTrace.Out(); return(null); } if (!settingsStore.GetValue <StyleCopOptionsSettingsKey, bool>(key => key.AnalyzeReadOnlyFiles)) { if (process.SourceFile.Properties.IsNonUserFile) { StyleCopTrace.Info("Not analysing non user files."); StyleCopTrace.Out(); return(null); } } IDaemon daemon = file.GetSolution().GetComponent <IDaemon>(); return (StyleCopTrace.Out( new StyleCopStageProcess( this.lifetime, this.apiPool, daemon, process, this.threading, settingsStore, file))); } catch (JetBrains.Application.Progress.ProcessCancelledException) { return(null); } }
public PerformanceCriticalCodeAnalysisProcess([NotNull] IDaemonProcess process, [NotNull] ICSharpFile file, CallGraphSwaExtensionProvider callGraphSwaExtensionProvider, [NotNull] SolutionAnalysisService swa, CallGraphActivityTracker tracker, [NotNull] PerformanceCriticalCodeCallGraphAnalyzer performanceAnalyzer, [NotNull] ExpensiveCodeCallGraphAnalyzer expensiveCodeCallGraphAnalyzer) : base(process, file) { myCallGraphSwaExtensionProvider = callGraphSwaExtensionProvider; mySwa = swa; myTracker = tracker; myPerformanceAnalyzerId = performanceAnalyzer.Id; myExpensiveAnalyzerId = expensiveCodeCallGraphAnalyzer.Id; myLineMarkerEnabled = DaemonProcess.ContextBoundSettingsStore.GetValue((UnitySettings key) => key.PerformanceHighlightingMode) == PerformanceHighlightingMode.Always; }
protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { if (!file.GetProject().IsUnityProject()) { return(null); } var enabled = settings.GetValue((UnitySettings s) => s.EnablePerformanceCriticalCodeHighlighting); if (!enabled) { return(null); } return(GetProcess(process, settings, processKind, file)); }
/// <summary> /// Inserts copyright text into the file's header. /// </summary> /// <param name="file"> /// The file to insert the company name into. /// </param> public void InsertCopyrightText(ICSharpFile file) { DocumentationRulesConfiguration docConfig = this.GetDocumentationRulesConfig(file); FileHeader fileHeader = new FileHeader(file) { CopyrightText = docConfig.Copyright }; fileHeader.Update(); }
/// <summary> /// The execute transaction inner. /// </summary> /// <param name="solution"> /// The solution. /// </param> /// <param name="textControl"> /// The text control. /// </param> public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl) { ICSharpFile file = Utils.GetCSharpFile(solution, textControl); new DocumentationRules().InsertFileName(file); }
/// <summary> /// Inserts a summary into the file's header. /// </summary> /// <param name="file"> /// The file to insert into. /// </param> public void InsertFileHeaderSummary(ICSharpFile file) { FileHeader fileHeader = new FileHeader(file) { Summary = Utils.GetSummaryText(file) }; fileHeader.Update(); }
/// <summary> /// Executes the cleanup rules. /// </summary> /// <param name="options"> /// The options. /// </param> /// <param name="file"> /// The file to process. /// </param> public void Execute(ReadabilityOptions options, ICSharpFile file) { StyleCopTrace.In(options, file); bool dontPrefixCallsWithBaseUnlessLocalImplementationExists = options.SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists; bool codeMustNotContainEmptyStatements = options.SA1106CodeMustNotContainEmptyStatements; bool blockStatementsMustNotContainEmbeddedComments = options.SA1108BlockStatementsMustNotContainEmbeddedComments; bool blockStatementsMustNotContainEmbeddedRegions = options.SA1109BlockStatementsMustNotContainEmbeddedRegions; bool commentsMustContainText = options.SA1120CommentsMustContainText; bool useBuiltInTypeAlias = options.SA1121UseBuiltInTypeAlias; bool useStringEmptyForEmptyStrings = options.SA1122UseStringEmptyForEmptyStrings; bool dontPlaceRegionsWithinElements = options.SA1123DoNotPlaceRegionsWithinElements; bool codeMustNotContainEmptyRegions = options.SA1124CodeMustNotContainEmptyRegions; if (dontPlaceRegionsWithinElements) { this.DoNotPlaceRegionsWithinElements(file.FirstChild); } if (blockStatementsMustNotContainEmbeddedComments) { this.BlockStatementsMustNotContainEmbeddedComments(file.FirstChild); } if (blockStatementsMustNotContainEmbeddedRegions) { this.BlockStatementsMustNotContainEmbeddedRegions(file.FirstChild); } if (codeMustNotContainEmptyStatements) { this.CodeMustNotContainEmptyStatements(file.FirstChild); } if (codeMustNotContainEmptyRegions) { this.CodeMustNotContainEmptyRegions(file.FirstChild); } if (useStringEmptyForEmptyStrings) { ReplaceEmptyStringsWithStringDotEmpty(file.FirstChild); } if (useBuiltInTypeAlias) { SwapToBuiltInTypeAlias(file.FirstChild); } if (commentsMustContainText) { RemoveEmptyComments(file.FirstChild); } if (dontPrefixCallsWithBaseUnlessLocalImplementationExists) { this.DoNotPrefixCallsWithBaseUnlessLocalImplementationExists(file.FirstChild); } StyleCopTrace.Out(); }
/// <summary> /// Insert a summary element if missing. /// </summary> /// <param name="file"> /// The <see cref="ICSharpFile"/> to use. /// </param> /// <param name="declaration"> /// The <see cref="ITypeDeclaration"/> to check and fix. /// </param> /// <returns> /// True if it inserted a missing header. /// </returns> public bool InsertMissingDeclarationHeader(ICSharpFile file, IDeclaration declaration) { StyleCopTrace.In(file, declaration); Param.RequireNotNull(file, "file"); Param.RequireNotNull(declaration, "declaration"); Debug.Assert(declaration.DeclaredElement != null, "declaration.DeclaredElement != null"); bool returnValue = false; DocumentationRulesConfiguration docConfig = this.GetDocumentationRulesConfig(file); bool isIFieldDeclaration = declaration is IFieldDeclaration; AccessRights accessRights = ((IModifiersOwnerDeclaration)declaration).GetAccessRights(); DeclaredElementType elementType = declaration.DeclaredElement.GetElementType(); if ((!isIFieldDeclaration || docConfig.RequireFields) && (accessRights != AccessRights.PRIVATE || !docConfig.IgnorePrivates) && (accessRights != AccessRights.INTERNAL || !docConfig.IgnoreInternals)) { DeclarationHeader.CreateNewHeader(declaration, docConfig); returnValue = true; } return StyleCopTrace.Out(returnValue); }
protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { var enabled = processKind == DaemonProcessKind.VISIBLE_DOCUMENT && settings.GetValue((UnitySettings s) => s.EnablePerformanceCriticalCodeHighlighting); if (!enabled) { return(null); } return(new PerformanceCriticalCodeAnalysisProcess(process, file)); }
public T4CSharpErrorProcess(IDaemonProcess process, IContextBoundSettingsStore settingsStore, ICSharpFile file) : base(process, settingsStore, file) { }
public ExceptionalDaemonStageProcess(ICSharpFile file, IPsiSourceFile psiSourceFile, IContextBoundSettingsStore settings) : base(ServiceLocator.Process, file) { _consumer = new FilteringHighlightingConsumer(psiSourceFile, file, settings); }
private HashSet <IDeclaration> FindHotRootMethods([NotNull] ICSharpFile file, [NotNull] IPsiSourceFile sourceFile) { var api = file.GetSolution().GetComponent <UnityApi>(); var result = new HashSet <IDeclaration>(); var descendantsEnumerator = file.Descendants(); while (descendantsEnumerator.MoveNext()) { switch (descendantsEnumerator.Current) { case IClassLikeDeclaration classLikeDeclaration: var declaredSymbol = classLikeDeclaration.DeclaredElement; if (declaredSymbol == null || !declaredSymbol.GetAllSuperTypes().Any(t => t.GetClrName().Equals(KnownTypes.MonoBehaviour))) { descendantsEnumerator.SkipThisNode(); } break; case IMethodDeclaration methodDeclaration: // check that method is hot and add it to container var declaredElement = methodDeclaration.DeclaredElement; if (declaredElement == null) { break; } var name = declaredElement.ShortName; if (ourKnownHotMonoBehaviourMethods.Contains(name) && api.IsEventFunction(declaredElement)) { result.Add(methodDeclaration); } break; case IInvocationExpression invocationExpression: // we should find 'StartCoroutine' method, because passed symbol will be hot too var reference = (invocationExpression.InvokedExpression as IReferenceExpression)?.Reference; if (reference == null) { break; } var info = reference.Resolve(); if (info.ResolveErrorType != ResolveErrorType.OK) { break; } declaredElement = info.DeclaredElement as IMethod; if (declaredElement == null) { break; } var containingType = declaredElement.GetContainingType(); if (containingType == null || containingType.GetClrName().Equals(KnownTypes.MonoBehaviour) && declaredElement.ShortName.Equals("StartCoroutine")) { var arguments = invocationExpression.Arguments; if (arguments.Count == 0 || arguments.Count > 2) { break; } var firstArgument = arguments[0].Value; if (firstArgument == null) { break; } var coroutineMethodDeclaration = ExtractMethodDeclarationFromStartCoroutine(firstArgument); if (coroutineMethodDeclaration == null) { break; } var declarations = coroutineMethodDeclaration.GetDeclarationsIn(sourceFile).Where(t => t.GetSourceFile() == sourceFile); foreach (var declaration in declarations) { result.Add(declaration); } } break; } } return(result); }
public bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate) { // Better to check everything now and then work with valid data. ITextControl textControl = context.GetData(TextControlDataConstants.TEXT_CONTROL); if (textControl == null) { return(false); } if (textControl.IsReadOnly) { return(false); } if (textControl.Selection.IsDisjoint()) { return(false); } IEquatableList <TextControlPosRange> equatableList = textControl.Selection.Ranges.Value; if (equatableList.Count > 1) { return(false); } ISolution solution = context.GetData(ProjectModelDataConstants.SOLUTION); if (solution == null) { return(false); } IPsiSourceFile psiSourceFile = textControl.Document.GetPsiSourceFile(solution); if (psiSourceFile == null) { return(false); } if (!psiSourceFile.IsValid()) { return(false); } TextRange textRange = equatableList.Count == 1 ? equatableList[0].ToDocRangeNormalized() : new TextRange(textControl.Caret.Offset()); DocumentRange range = new DocumentRange(textControl.Document, textRange); ICSharpFile psiFile = psiSourceFile.GetPsiFile <CSharpLanguage>(range) as ICSharpFile; if (psiFile == null) { return(false); } if (!psiFile.IsValid()) { return(false); } if (context.GetData(UIDataConstants.PopupWindowContextSource) == null) { return(false); } return(true); }
public PerformanceCriticalCodeAnalysisProcess([NotNull] IDaemonProcess process, [NotNull] ICSharpFile file) : base(process, file) { myCheckForInterrupt = InterruptableActivityCookie.GetCheck().NotNull(); }
/// <summary> /// Checks the given file is valid to check. /// </summary> /// <param name="sourceFile"> /// THe file to check. /// </param> /// <returns> /// True if its valid. /// </returns> private bool FileIsValid(ICSharpFile sourceFile) { if (sourceFile == null) { return false; } bool hasErrorElements = new RecursiveElementCollector<IErrorElement>(null).ProcessElement(sourceFile).GetResults().Any(); return !hasErrorElements; }
public ProjectAnalysisDaemonStageProcess(IDaemonProcess daemonProcess, IContextBoundSettingsStore settings, ICSharpFile csharpFile) : base(daemonProcess, csharpFile) { _myDaemonProcess = daemonProcess; _settings = settings; }
protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { return(new InterproceduralDaemonStageProcess(process, file)); }
/// <summary> /// Implement the Execute method. /// </summary> /// <param name="options"> /// The options. /// </param> /// <param name="file"> /// The file to use. /// </param> public void Execute(SpacingOptions options, ICSharpFile file) { StyleCopTrace.In(options, file); Param.RequireNotNull(options, "options"); Param.RequireNotNull(file, "file"); bool commasMustBeSpacedCorrectly = options.SA1001CommasMustBeSpacedCorrectly; bool singleLineCommentsMustBeginWithSingleSpace = options.SA1005SingleLineCommentsMustBeginWithSingleSpace; bool preprocessorKeywordsMustNotBePrecededBySpace = options.SA1006PreprocessorKeywordsMustNotBePrecededBySpace; bool negativeSignsMustBeSpacedCorrectly = options.SA1021NegativeSignsMustBeSpacedCorrectly; bool positiveSignsMustBeSpacedCorrectly = options.SA1022PositiveSignsMustBeSpacedCorrectly; bool codeMustNotContainMultipleWhitespaceInARow = options.SA1025CodeMustNotContainMultipleWhitespaceInARow; if (codeMustNotContainMultipleWhitespaceInARow) { this.CodeMustNotContainMultipleWhitespaceInARow(file.FirstChild); } if (commasMustBeSpacedCorrectly) { this.CommasMustBeSpacedCorrectly(file.FirstChild); } if (singleLineCommentsMustBeginWithSingleSpace) { this.SingleLineCommentsMustBeginWithSingleSpace(file.FirstChild); } if (preprocessorKeywordsMustNotBePrecededBySpace) { this.PreprocessorKeywordsMustNotBePrecededBySpace(file.FirstChild); } if (negativeSignsMustBeSpacedCorrectly) { this.NegativeAndPositiveSignsMustBeSpacedCorrectly(file.FirstChild, CSharpTokenType.MINUS); } if (positiveSignsMustBeSpacedCorrectly) { this.NegativeAndPositiveSignsMustBeSpacedCorrectly(file.FirstChild, CSharpTokenType.PLUS); } StyleCopTrace.Out(); }
/// <summary> /// Inserts the company name into the file's header. /// </summary> /// <param name="file"> /// The file to insert the company name into. /// </param> public void InsertCompanyName(ICSharpFile file) { DocumentationRulesConfiguration docConfig = this.GetDocumentationRulesConfig(file); FileHeader fileHeader = new FileHeader(file) { CompanyName = docConfig.CompanyName }; fileHeader.Update(); }
private void OrderPropertyIndexerAndEventDeclarations(OrderingOptions options, ICSharpFile file) { foreach (ICSharpNamespaceDeclaration namespaceDeclaration in file.NamespaceDeclarations) { this.ProcessTypeDeclarations(options, namespaceDeclaration.TypeDeclarations); } this.ProcessTypeDeclarations(options, file.TypeDeclarations); }
protected virtual IDaemonStageProcess GetProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { return(new PerformanceCriticalCodeAnalysisProcess(process, file, CallGraphSwaExtension, Swa, Tracker, PerformanceAnalyzer, ExpensiveAnalyzer)); }
protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { // TODO: Load configuration var configuration = new SyntaxRuleConfiguration(new SyntaxRule[0]); return(new SourcePathDaemonProcess(process, file, configuration, _queryExecutor)); }
protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { if (processKind == DaemonProcessKind.VISIBLE_DOCUMENT && settings.GetValue(HighlightingSettingsAccessor.ColorUsageHighlightingEnabled)) { return(new UnityColorHighlighterProcess(process, settings, file)); } return(null); }
protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { return(new CleanCodeDaemonStageProcess(process, file, settings)); }
public UnityColorHighlighterProcess(IDaemonProcess process, IContextBoundSettingsStore settingsStore, ICSharpFile file) : base(process, settingsStore, file) { }
protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { var sourceFile = file.GetSourceFile(); if (!file.GetProject().IsUnityProject() || !mySwaExtensionProvider.IsApplicable(sourceFile)) { return(null); } return(new CallGraphProcess(process, processKind, file, myLogger, myContextProviders, myProblemAnalyzers)); }
protected override IDaemonStageProcess GetProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, ICSharpFile file) { return(new VSPerformanceCriticalCodeAnalysisProcess(process, file, Swa, Tracker, PerformanceAnalyzer, ExpensiveAnalyzer)); }
/// <summary> /// This method provides a <see cref="IDaemonStageProcess"/> instance which is assigned to highlighting a single document. /// </summary> /// <param name="process"> /// Current Daemon Process. /// </param> /// <param name="settingsStore"> /// The settingsStore store to use. /// </param> /// <param name="processKind"> /// The process kind. /// </param> /// <param name="file"> /// The file to analyze. /// </param> /// /// /// <returns> /// The current <see cref="IDaemonStageProcess"/>. /// </returns> protected override IDaemonStageProcess CreateProcess( IDaemonProcess process, IContextBoundSettingsStore settingsStore, DaemonProcessKind processKind, ICSharpFile file) { StyleCopTrace.In(process, settingsStore, processKind, file); if (process == null) { throw new ArgumentNullException("process"); } try { if (processKind == DaemonProcessKind.OTHER) { StyleCopTrace.Info("ProcessKind Other."); StyleCopTrace.Out(); return null; } if (!settingsStore.GetValue<StyleCopOptionsSettingsKey, bool>(key => key.AnalysisEnabled)) { StyleCopTrace.Info("Analysis disabled."); StyleCopTrace.Out(); return null; } if (!this.IsSupported(process.SourceFile)) { StyleCopTrace.Info("File type not supported."); StyleCopTrace.Out(); return null; } if (!this.FileIsValid(file)) { StyleCopTrace.Info("Source file not valid."); StyleCopTrace.Out(); return null; } if (!settingsStore.GetValue<StyleCopOptionsSettingsKey, bool>(key => key.AnalyzeReadOnlyFiles)) { if (process.SourceFile.Properties.IsNonUserFile) { StyleCopTrace.Info("Not analysing non user files."); StyleCopTrace.Out(); return null; } } return StyleCopTrace.Out(new StyleCopStageProcess(process, settingsStore, file)); } catch (JetBrains.Application.Progress.ProcessCancelledException) { return null; } }
public VSPerformanceCriticalCodeAnalysisProcess([NotNull] IDaemonProcess process, [NotNull] ICSharpFile file, [NotNull] SolutionAnalysisService swa, [NotNull] CallGraphActivityTracker tracker, [NotNull] PerformanceCriticalCodeCallGraphAnalyzer performanceAnalyzer, ExpensiveCodeCallGraphAnalyzer expensiveAnalyzer) : base(process, file, swa, tracker, performanceAnalyzer, expensiveAnalyzer) { }
private static void SwapFileHeaderNode(ICSharpFile file, string newHeader) { ITreeRange existingHeaderRange = Utils.GetFileHeaderTreeRange(file); using (WriteLockCookie.Create(file.IsPhysical())) { ICommentNode newCommentNode; if (existingHeaderRange.IsEmpty) { // existing header missing so add on a new line for our new header newHeader += Environment.NewLine; IWhitespaceNode node = file.FirstChild as IWhitespaceNode; bool insertNewLine = true; while (node != null) { if (node.IsNewLine) { insertNewLine = false; break; } node = node.NextSibling as IWhitespaceNode; } if (insertNewLine) { newHeader += Environment.NewLine; } newCommentNode = (ICommentNode) CSharpTokenType.END_OF_LINE_COMMENT.Create(new JB::JetBrains.Text.StringBuffer(newHeader), new TreeOffset(0), new TreeOffset(newHeader.Length)); LowLevelModificationUtil.AddChildBefore(file.FirstChild, new ITreeNode[] { newCommentNode }); } else { ITokenNode lastToken = (ITokenNode)existingHeaderRange.Last; ITokenNode nextToken = lastToken.GetNextToken(); if (nextToken != null) { ITokenNode nextNextToken = nextToken.GetNextToken(); if (nextNextToken != null) { ITokenNode nextNextNextToken = nextNextToken.GetNextToken(); if (!nextToken.IsNewLine() || !nextNextToken.IsNewLine()) { newHeader += Environment.NewLine; } if (nextNextNextToken.GetTokenType() == CSharpTokenType.PP_SHARP && nextToken.IsNewLine() && nextNextToken.IsNewLine()) { newHeader += Environment.NewLine; } newCommentNode = (ICommentNode) CSharpTokenType.END_OF_LINE_COMMENT.Create( new JB::JetBrains.Text.StringBuffer(newHeader), new TreeOffset(0), new TreeOffset(newHeader.Length)); LowLevelModificationUtil.ReplaceChildRange(existingHeaderRange.First, existingHeaderRange.Last, new ITreeNode[] { newCommentNode }); } } } } }
protected override IDaemonStageProcess CreateProcess([NotNull] IDaemonProcess process, [NotNull] IContextBoundSettingsStore settings, DaemonProcessKind processKind, [NotNull] ICSharpFile file) { DaemonProcess = process; SettingsStore = settings; CurrentCSharpFile = file; return(this); }