private static DiagnosticAnalyzerService CreateDiagnosticAnalyzerService( Dictionary<string, DiagnosticAnalyzer[]> analyzerMap, IAsynchronousOperationListener listener) { return analyzerMap == null || analyzerMap.Count == 0 ? new MyDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap(), listener: listener) : new MyDiagnosticAnalyzerService(analyzerMap.ToImmutableDictionary(kvp => kvp.Key, kvp => kvp.Value.ToImmutableArray()), listener: listener); }
/// <summary> /// Given an analyzer and a collection of documents to apply it to, run the analyzer and gather an array of /// diagnostics found. The returned diagnostics are then ordered by location in the source documents. /// </summary> /// <param name="analyzers">The analyzer to run on the documents.</param> /// <param name="documents">The <see cref="Document"/>s that the analyzer will be run on.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param> /// <returns>A collection of <see cref="Diagnostic"/>s that surfaced in the source code, sorted by /// <see cref="Diagnostic.Location"/>.</returns> protected static async Task<ImmutableArray<Diagnostic>> GetSortedDiagnosticsFromDocumentsAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, Document[] documents, CancellationToken cancellationToken) { var projects = new HashSet<Project>(); foreach (var document in documents) { projects.Add(document.Project); } var supportedDiagnosticsSpecificOptions = new Dictionary<string, ReportDiagnostic>(); foreach (var analyzer in analyzers) { foreach (var diagnostic in analyzer.SupportedDiagnostics) { // make sure the analyzers we are testing are enabled supportedDiagnosticsSpecificOptions[diagnostic.Id] = ReportDiagnostic.Default; } } // Report exceptions during the analysis process as errors supportedDiagnosticsSpecificOptions.Add("AD0001", ReportDiagnostic.Error); var diagnostics = ImmutableArray.CreateBuilder<Diagnostic>(); foreach (var project in projects) { // update the project compilation options var modifiedSpecificDiagnosticOptions = supportedDiagnosticsSpecificOptions.ToImmutableDictionary().SetItems(project.CompilationOptions.SpecificDiagnosticOptions); var modifiedCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(modifiedSpecificDiagnosticOptions); var processedProject = project.WithCompilationOptions(modifiedCompilationOptions); var compilation = await processedProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var compilationWithAnalyzers = compilation.WithAnalyzers(analyzers, processedProject.AnalyzerOptions, cancellationToken); var compilerDiagnostics = compilation.GetDiagnostics(cancellationToken); var compilerErrors = compilerDiagnostics.Where(i => i.Severity == DiagnosticSeverity.Error); var diags = await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().ConfigureAwait(false); var allDiagnostics = await compilationWithAnalyzers.GetAllDiagnosticsAsync().ConfigureAwait(false); var failureDiagnostics = allDiagnostics.Where(diagnostic => diagnostic.Id == "AD0001"); foreach (var diag in diags.Concat(compilerErrors).Concat(failureDiagnostics)) { if (diag.Location == Location.None || diag.Location.IsInMetadata) { diagnostics.Add(diag); } else { for (int i = 0; i < documents.Length; i++) { var document = documents[i]; var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (tree == diag.Location.SourceTree) { diagnostics.Add(diag); } } } } } var results = SortDistinctDiagnostics(diagnostics); return results.ToImmutableArray(); }
public void Setup() { _dictionary = Enumerable.Range(1, Size).ToDictionary(_ => "test " + _, _ => _); _readonlyDictionary = new ReadonlyDictionary<string, int>(_dictionary); _concurrentDictionary = new ConcurrentDictionary<string, int>(_dictionary); _immutableDictionary = _dictionary.ToImmutableDictionary(); }
public HtmlFile ReadFile(HtmlFile file) { CommonMarkSettings.Default.OutputDelegate = (document, output, settings) => new CustomHtmlFormatter(output, settings, file).WriteDocument(document); var doc = CommonMarkConverter.Parse(file.Source); var properties = new Dictionary<string, string>(); foreach(var node in doc.AsEnumerable()) { if(node.Block?.Tag == BlockTag.FencedCode) { if(node.Block.StringContent.TakeFromStart(PropertiesString.Length) == PropertiesString) { string kvString = node.Block.StringContent.ToString().Substring(PropertiesString.Length); var propDict = ReadKV(kvString); propDict.ToList().ForEach(x => properties.Add(x.Key, x.Value)); } } } StringBuilder sb = new StringBuilder(); CommonMarkConverter.ProcessStage3(doc, new StringWriter(sb)); return file.WithContent(sb.ToString()).WithProperties(properties.ToImmutableDictionary()); }
private static ImmutableDictionary<ErrorCode, string> CreateCategoriesMap() { var map = new Dictionary<ErrorCode, string>() { // { ERROR_CODE, CATEGORY } }; return map.ToImmutableDictionary(); }
private static ImmutableDictionary<ErrorCode, string> CreateHelpLinks() { var map = new Dictionary<ErrorCode, string>() { // { ERROR_CODE, HELP_LINK } }; return map.ToImmutableDictionary(); }
public void Build(FileModel model, IHostService host) { model.File = Path.ChangeExtension(model.File, ".json"); var toc = (TocViewModel)model.Content; HashSet<string> links = new HashSet<string>(); Dictionary<string, HashSet<string>> tocMap = new Dictionary<string, HashSet<string>>(); UpdateRelativePathAndAddTocMap(toc, model, links, tocMap, host); model.Properties.LinkToFiles = links.ToImmutableArray(); model.Properties.TocMap = tocMap.ToImmutableDictionary(); // todo : metadata. }
private static void GetTagSource(TestWorkspace workspace, DiagnosticServiceWaiter diagnosticWaiter, ErrorSquiggleWaiter squiggleWaiter, out Analyzer analyzer, out DiagnosticAnalyzerService analyzerService, out DiagnosticsSquiggleTaggerProvider.TagSource taggerSource) { analyzer = new Analyzer(); var analyzerMap = new Dictionary<string, ImmutableArray<DiagnosticAnalyzer>>() { { LanguageNames.CSharp, ImmutableArray.Create<DiagnosticAnalyzer>(analyzer) } }; analyzerService = new DiagnosticAnalyzerService(analyzerMap.ToImmutableDictionary()); var diagnosticListeners = SpecializedCollections.SingletonEnumerable(new Lazy<IAsynchronousOperationListener, FeatureMetadata>( () => diagnosticWaiter, new FeatureMetadata(new Dictionary<string, object>() { { "FeatureName", FeatureAttribute.DiagnosticService } }))); var diagnosticService = new DiagnosticService(SpecializedCollections.SingletonEnumerable<IDiagnosticUpdateSource>(analyzerService), diagnosticListeners); var document = workspace.Documents.First(); var buffer = document.GetTextBuffer(); var foregroundService = new TestForegroundNotificationService(); var optionsService = workspace.Services.GetService<IOptionService>(); taggerSource = new DiagnosticsSquiggleTaggerProvider.TagSource(buffer, foregroundService, diagnosticService, optionsService, squiggleWaiter); }
/// <summary> /// The settings provider used to bridge Service Fabric configuration information and DotNetty /// </summary> /// <param name="traceId">The unique identifier used to correlate debugging and diagnostics messages</param> /// <param name="componentName">The component name used for debug and diagnostics messages</param> /// <param name="logger">The service fabric logger to be used when writing debug and diagnostics information</param> /// <param name="gatewayConfiguration">The gateway configuration used to get current configuration information for DotNetty</param> /// <param name="iotHubConfiguration">The IotHub Client configuration used to get current configuration information for DotNetty</param> /// <param name="mqttConfiguration">The MQTT configuration used to get current configuration information for DotNetty</param> public ServiceFabricConfigurationProvider(Guid traceId, string componentName, IServiceLogger logger, GatewayConfiguration gatewayConfiguration, IoTHubConfiguration iotHubConfiguration, MqttServiceConfiguration mqttConfiguration) { this.componentName = componentName; this.logger = logger; this.logger.Verbose(traceId, this.componentName, "Initializing configuration provider."); var baseProperties = new Dictionary<string, string>(); foreach (PropertyInfo element in typeof(GatewayConfiguration).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (!element.PropertyType.IsArray) { object value = element.GetValue(gatewayConfiguration, null); baseProperties.Add(element.Name, element.PropertyType == typeof(string) ? value as string : value.ToString()); } } foreach (PropertyInfo element in typeof(MqttServiceConfiguration).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (!element.PropertyType.IsArray) { object value = element.GetValue(mqttConfiguration, null); baseProperties.Add(element.Name, element.PropertyType == typeof(string) ? value as string : value.ToString()); } } foreach (PropertyInfo element in typeof(IoTHubConfiguration).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (!element.PropertyType.IsArray) { object value = element.GetValue(iotHubConfiguration, null); baseProperties.Add($"IotHubClient.{element.Name}", value?.ToString()); } } this.configurationValues = baseProperties.ToImmutableDictionary(); this.logger.Informational(traceId, this.componentName, "Initializing configuration provider complete."); }
public static void IndexSolutions(IEnumerable<string> solutionFilePaths, Dictionary<string, string> properties) { var assemblyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var path in solutionFilePaths) { using (Disposable.Timing("Reading assembly names from " + path)) { foreach (var assemblyName in AssemblyNameExtractor.GetAssemblyNames(path)) { assemblyNames.Add(assemblyName); } } } var federation = new Federation(); foreach (var path in solutionFilePaths) { using (Disposable.Timing("Generating " + path)) { using (var solutionGenerator = new SolutionGenerator( path, Paths.SolutionDestinationFolder, properties: properties.ToImmutableDictionary(), federation: federation)) { solutionGenerator.GlobalAssemblyList = assemblyNames; solutionGenerator.Generate(solutionExplorerRoot: mergedSolutionExplorerRoot); if (Configuration.ProcessReferencies) Extend.ExtendGenerator.TopReferencedAssemblies(solutionGenerator, federation, mergedSolutionExplorerRoot); } } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } }
private void BuildDocument(FileCollection files, Dictionary <string, object> metadata = null, ApplyTemplateSettings applyTemplateSettings = null, string templateFolder = null) { using (var builder = new DocumentBuilder(LoadAssemblies(), ImmutableArray <string> .Empty, null)) { if (applyTemplateSettings == null) { applyTemplateSettings = new ApplyTemplateSettings(_inputFolder, _outputFolder); applyTemplateSettings.RawModelExportSettings.Export = true; } var parameters = new DocumentBuildParameters { Files = files, OutputBaseDir = Path.Combine(Directory.GetCurrentDirectory(), _outputFolder), ApplyTemplateSettings = applyTemplateSettings, Metadata = metadata?.ToImmutableDictionary(), TemplateManager = new TemplateManager(null, null, new List <string> { _templateFolder }, null, null), TemplateDir = templateFolder, }; builder.Build(parameters); } }
/// <summary> /// Initializes a new instance of the <see cref="CompilerSettings"/> class. /// </summary> /// <param name="valueGetters">The value getters</param> /// <param name="truthyChecks">The truthy checks</param> /// <param name="enumerationConverters">The enumeration converters</param> /// <param name="rendererPipeline">The renderer pipeline to use</param> /// <param name="templateLoader">The template loader</param> /// <param name="partialLoader">The partial loader</param> /// <param name="maxRecursionDepth">The max recursion depth</param> /// <param name="ignoreCaseOnLookup">Should case be ignored on lookup</param> /// <param name="parser">The mustache parser to use</param> /// <param name="defaultTags">The default tags to use during parsing</param> /// <param name="parserPipeline">The parser pipeline to use during parsing</param> /// <param name="compilationSettings">The default compilation settings for each render</param> /// <param name="sectionBlacklistTypes">The blacklisted section types</param> /// <param name="encodingFunction">The encoding function for escaping strings</param> public CompilerSettings( Dictionary <Type, DefaultSettings.ValueGetterDelegate> valueGetters, Dictionary <Type, List <LambdaExpression> > truthyChecks, Dictionary <Type, EnumerationConverter> enumerationConverters, TokenRendererPipeline <CompilerContext> rendererPipeline, IStubbleLoader templateLoader, IStubbleLoader partialLoader, uint maxRecursionDepth, bool ignoreCaseOnLookup, IMustacheParser parser, Tags defaultTags, ParserPipeline parserPipeline, CompilationSettings compilationSettings, HashSet <Type> sectionBlacklistTypes, Expression <Func <string, string> > encodingFunction) : base(templateLoader, partialLoader, maxRecursionDepth, ignoreCaseOnLookup, parser, defaultTags, parserPipeline, sectionBlacklistTypes) { ValueGetters = valueGetters.ToImmutableDictionary(); TruthyChecks = truthyChecks.ToImmutableDictionary(k => k.Key, v => v.Value.ToImmutableList()); EnumerationConverters = enumerationConverters.ToImmutableDictionary(); RendererPipeline = rendererPipeline; CompilationSettings = compilationSettings; EncodingFuction = encodingFunction; }
} = Constants.SYS_NUM_DOUBLE; // "Double"; public DoubleExtractor(string placeholder = NumbersDefinitions.PlaceHolderDefault) { var regexes = new Dictionary <Regex, TypeTag> { { new Regex(NumbersDefinitions.DoubleDecimalPointRegex(placeholder), RegexOptions.IgnoreCase | RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.DOUBLE_PREFIX, Constants.NUMBER_SUFFIX) }, { new Regex(NumbersDefinitions.DoubleWithoutIntegralRegex(placeholder), RegexOptions.IgnoreCase | RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.DOUBLE_PREFIX, Constants.NUMBER_SUFFIX) }, { new Regex(NumbersDefinitions.DoubleWithMultiplierRegex, RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.DOUBLE_PREFIX, Constants.NUMBER_SUFFIX) }, { new Regex(NumbersDefinitions.DoubleWithRoundNumber, RegexOptions.IgnoreCase | RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.DOUBLE_PREFIX, Constants.NUMBER_SUFFIX) }, { new Regex(NumbersDefinitions.DoubleAllFloatRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.DOUBLE_PREFIX, Constants.PORTUGUESE) }, { new Regex(NumbersDefinitions.DoubleExponentialNotationRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.DOUBLE_PREFIX, Constants.POWER_SUFFIX) }, { new Regex(NumbersDefinitions.DoubleCaretExponentialNotationRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.DOUBLE_PREFIX, Constants.POWER_SUFFIX) }, { GenerateLongFormatNumberRegexes(LongFormatType.DoubleNumDotComma, placeholder), RegexTagGenerator.GenerateRegexTag(Constants.DOUBLE_PREFIX, Constants.NUMBER_SUFFIX) }, { GenerateLongFormatNumberRegexes(LongFormatType.DoubleNumNoBreakSpaceComma, placeholder), RegexTagGenerator.GenerateRegexTag(Constants.DOUBLE_PREFIX, Constants.NUMBER_SUFFIX) } }; Regexes = regexes.ToImmutableDictionary(); }
public IModelBinder GetBinder(ModelBinderProviderContext context) { var modelType = context.Metadata.ModelType; var constructorInfos = modelType.GetConstructors(BindingFlags.Public | BindingFlags.Instance); if (constructorInfos.Length != 1) { return(null !); } if (constructorInfos[0].GetParameters().Length == 0) { return(null !); } var propertyBinders = new Dictionary <ModelMetadata, IModelBinder>(); foreach (var property in context.Metadata.Properties) { propertyBinders.Add(property, context.CreateBinder(property)); } return(new ImmutableModelBinder(propertyBinders.ToImmutableDictionary())); }
public BaseURLExtractor() { var regexes = new Dictionary <Regex, string> { { new Regex(BaseURL.IpUrlRegex, RegexOptions.Compiled), Constants.URL_REGEX }, { new Regex(BaseURL.UrlRegex, RegexOptions.Compiled), Constants.URL_REGEX }, { new Regex(BaseURL.UrlRegex2, RegexOptions.Compiled), Constants.URL_REGEX }, }; Regexes = regexes.ToImmutableDictionary(); AmbiguousTimeTerm = new Regex(BaseURL.AmbiguousTimeTerm, RegexOptions.Compiled); TldMatcher = new StringMatcher(); TldMatcher.Init(BaseURL.TldList); }
private static ImmutableDictionary <string, double> ResolveDurationTimex(string timexStr) { var ret = new Dictionary <string, double>(); // resolve duration timex, such as P21DT2H(21 days 2 hours) var durationStr = timexStr.Replace("P", ""); var numberStart = 0; var isTime = false; for (var idx = 0; idx < durationStr.Length; idx++) { if (char.IsLetter(durationStr[idx])) { if (durationStr[idx] == 'T') { isTime = true; } else { var numStr = durationStr.Substring(numberStart, idx - numberStart); double number = 0; if (!double.TryParse(numStr, out number)) { return((new Dictionary <string, double>()).ToImmutableDictionary()); } var srcTimexUnit = durationStr.Substring(idx, 1); if (!isTime && srcTimexUnit == "M") { srcTimexUnit = "MON"; } ret.Add(srcTimexUnit, number); } numberStart = idx + 1; } } return(ret.ToImmutableDictionary()); }
/// <summary> /// Parses the manifest file /// </summary> /// <param name="json">Contents of the file</param> /// <returns>Parsed Webpack assets</returns> public WebpackAssets ParseManifest(string json) { var manifest = JsonSerializer.Deserialize <IDictionary <string, IDictionary <string, object> > >(json); var output = new Dictionary <string, WebpackAssets.EntryPoint>(); foreach (var(entryPoint, filesByExtension) in manifest) { var outputFiles = new Dictionary <string, ImmutableArray <string> >(); foreach (var(extension, files) in filesByExtension) { if (files is JsonElement filesElement) { // This can be either an array (for multiple files), or a string (for one file) switch (filesElement.ValueKind) { case JsonValueKind.Array: outputFiles[extension] = JsonSerializer.Deserialize <List <string> >(filesElement.GetRawText()) .Select(x => FormatPath(x.ToString())).ToImmutableArray(); break; case JsonValueKind.String: outputFiles[extension] = ImmutableArray.Create(FormatPath(filesElement.GetString())); break; default: throw new ArgumentException("Unrecognised webpack-assets format"); } } } output[entryPoint] = new WebpackAssets.EntryPoint(outputFiles.ToImmutableDictionary()); } return(new WebpackAssets(output.ToImmutableDictionary())); }
private static ImmutableDictionary <string, ChangeKindWithDependency> GetIntersectChanges(FileCollection files, ChangeList changeList) { if (changeList == null) { return(null); } var dict = new Dictionary <string, ChangeKindWithDependency>(); foreach (var file in files.EnumerateFiles()) { string fileKey = ((RelativePath)file.File).GetPathFromWorkingFolder().ToString(); dict[fileKey] = ChangeKindWithDependency.None; } foreach (ChangeItem change in changeList) { string fileKey = ((RelativePath)change.FilePath).GetPathFromWorkingFolder().ToString(); // always put the change into dict because docfx could access files outside its own scope, like tokens. dict[fileKey] = change.Kind; } return(dict.ToImmutableDictionary()); }
public void FullDidDocumentTest() { var originalJson = TestDidDocument1; var typeMap = new Dictionary <string, Type>(ServiceConverterFactory.DefaultTypeMap); typeMap.Add("OpenIdConnectVersion1.0Service", typeof(OpenIdConnectVersion1)); typeMap.Add("CredentialRepositoryService", typeof(Service)); typeMap.Add("XdiService", typeof(Service)); typeMap.Add("AgentService", typeof(Service)); typeMap.Add("IdentityHub", typeof(Service)); typeMap.Add("MessagingService", typeof(Service)); typeMap.Add("SocialWebInboxService", typeof(SocialWebInboxService)); typeMap.Add("DidAuthPushModeVersion1", typeof(Service)); var options = new JsonSerializerOptions { IgnoreNullValues = true, Converters = { new VerificationRelationshipConverterFactory(), new VerificationMethodConverter(), new ServiceConverterFactory(typeMap.ToImmutableDictionary()), new JsonLdContextConverter() } }; var didObject = JsonSerializer.Deserialize <DidDocument>(originalJson, options); var roundTrippedJson = JsonSerializer.Serialize(didObject, options); var comparer = new JsonElementComparer(); using var doc1 = JsonDocument.Parse(originalJson); using var doc2 = JsonDocument.Parse(roundTrippedJson); Assert.True(comparer.Equals(doc1.RootElement, doc2.RootElement)); }
public TimeExtractorChs() { var _regexes = new Dictionary <Regex, TimeType> { { new Regex( $@"{ApproximateDescPreffixRegex}?{DayDescRegex}?{ChineseTimeRegex}{ApproximateDescSuffixRegex}?", RegexOptions.IgnoreCase | RegexOptions.Singleline), TimeType.ChineseTime }, { new Regex( $@"{ApproximateDescPreffixRegex}?{DayDescRegex}?{DigitTimeRegex}{ApproximateDescSuffixRegex}?", RegexOptions.IgnoreCase | RegexOptions.Singleline), TimeType.DigitTime }, { new Regex($@"差{MinuteRegex}{ChineseTimeRegex}", RegexOptions.IgnoreCase | RegexOptions.Singleline), TimeType.LessTime } }; Regexes = _regexes.ToImmutableDictionary(); }
public bool Execute(CancellationToken ct) { var newOption = new Dictionary <string, string>(); if (Options != null) { foreach (var key in DefaultOptions.Keys) { if (Options.ContainsKey(key)) { newOption[key] = Options[key]; } else { newOption[key] = DefaultOptions[key]; } } return(execute(ct, newOption.ToImmutableDictionary())); } else { return(execute(ct, DefaultOptions)); } }
protected EnumToStringUsingTranslationMappingSerializer(Dictionary <T, string> translation) { _translation = translation.ToImmutableDictionary(); foreach (T enumValue in Enum.GetValues(typeof(T)).OfType <T>()) { if (!_translation.ContainsKey(enumValue)) { throw new ArgumentException( $"enum translation must be exhaustive, but '{enumValue}' is missing."); } } var translationBack = new Dictionary <string, T>(); foreach ((T key, string value) in _translation) { if (translationBack.ContainsKey(value)) { throw new ArgumentException( $"enum translation values must be unique, but '{value}' was used multiple times"); } translationBack[value] = key; } _translationBack = translationBack.ToImmutableDictionary(); }
static DefinedPermissionsProvider() { var result = new Dictionary <string, PermissionDescriptor>(); var permissionClasses = typeof(DefinedPermissions).GetNestedTypes().Concat(new[] { typeof(DefinedPermissions) }); foreach (var permissionClass in permissionClasses) { foreach (var fieldInfo in permissionClass.GetFields(BindingFlags.Static | BindingFlags.Public)) { if (typeof(PermissionDescriptor).IsAssignableFrom(fieldInfo.FieldType)) { var descriptor = (PermissionDescriptor?)fieldInfo.GetValue(null); if (descriptor != null) { result.Add(descriptor.Key, descriptor); } } } } All = result.ToImmutableDictionary(); }
} = Constants.SYS_NUM_DOUBLE; // "Double"; public DoubleExtractor(string placeholder = NumbersDefinitions.PlaceHolderDefault) { var regexes = new Dictionary <Regex, string> { { new Regex(NumbersDefinitions.DoubleDecimalPointRegex(placeholder), RegexOptions.IgnoreCase | RegexOptions.Singleline), "DoubleNum" }, { new Regex(NumbersDefinitions.DoubleWithoutIntegralRegex(placeholder), RegexOptions.IgnoreCase | RegexOptions.Singleline), "DoubleNum" }, { new Regex(NumbersDefinitions.DoubleWithMultiplierRegex, RegexOptions.Singleline), "DoubleNum" }, { new Regex(NumbersDefinitions.DoubleWithRoundNumber, RegexOptions.IgnoreCase | RegexOptions.Singleline), "DoubleNum" }, { new Regex(NumbersDefinitions.DoubleAllFloatRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline), "DoublePor" }, { new Regex(NumbersDefinitions.DoubleExponentialNotationRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline), "DoublePow" }, { new Regex(NumbersDefinitions.DoubleCaretExponentialNotationRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline), "DoublePow" }, { GenerateLongFormatNumberRegexes(LongFormatType.DoubleNumDotComma, placeholder), "DoubleNum" }, { GenerateLongFormatNumberRegexes(LongFormatType.DoubleNumNoBreakSpaceComma, placeholder), "DoubleNum" } }; Regexes = regexes.ToImmutableDictionary(); }
private void EnsureDiagnosticOptionsRead() { if (!_optionsRead) { _optionsRead = true; var specificDiagnosticOptions = new Dictionary <string, ReportDiagnostic>(); try { var effectiveRuleset = RuleSet.LoadEffectiveRuleSetFromFile(_filePath); _generalDiagnosticOption = effectiveRuleset.GeneralDiagnosticOption; foreach (var rule in effectiveRuleset.SpecificDiagnosticOptions) { specificDiagnosticOptions.Add(rule.Key, rule.Value); } _specificDiagnosticOptions = specificDiagnosticOptions.ToImmutableDictionary(); } catch (Exception e) { _exception = e; } } }
public ModeBase(ILoggerFactory loggerFactory, BaseConfig baseConfig, StopToken stopToken) { PokedexData pokedexData = PokedexData.Load(); Setups.Databases repos = Setups.SetUpRepositories(baseConfig); ArgsParser argsParser = Setups.SetUpArgsParser(repos.UserRepo, pokedexData); var chats = new Dictionary <string, IChat>(); var chatFactory = new ChatFactory(loggerFactory, SystemClock.Instance, repos.UserRepo); foreach (ConnectionConfig connectorConfig in baseConfig.Chat.Connections) { IChat chat = chatFactory.Create(connectorConfig); if (chats.ContainsKey(chat.Name)) { throw new ArgumentException($"chat name '{chat.Name}' was used multiple times. It must be unique."); } chats[chat.Name] = chat; } _chats = chats.ToImmutableDictionary(); foreach (IChat chat in _chats.Values) { chat.IncomingMessage += MessageReceived; } _commandResponders = _chats.Values.ToImmutableDictionary( c => c.Name, c => (ICommandResponder) new CommandResponder(c)); _commandProcessors = _chats.Values.ToImmutableDictionary( c => c.Name, c => Setups.SetUpCommandProcessor(loggerFactory, argsParser, repos, stopToken, baseConfig.Chat, c, c, pokedexData.KnownSpecies)); _messagequeueRepo = repos.MessagequeueRepo; _messagelogRepo = repos.MessagelogRepo; _forwardUnprocessedMessages = baseConfig.Chat.ForwardUnprocessedMessages; _clock = SystemClock.Instance; }
private static void IndexSolutions(IEnumerable<string> solutionFilePaths, Dictionary<string, string> properties, Federation federation, Dictionary<string, string> serverPathMappings) { var assemblyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var path in solutionFilePaths) { using (Disposable.Timing("Reading assembly names from " + path)) { foreach (var assemblyName in AssemblyNameExtractor.GetAssemblyNames(path)) { assemblyNames.Add(assemblyName); } } } foreach (var path in solutionFilePaths) { using (Disposable.Timing("Generating " + path)) { using (var solutionGenerator = new SolutionGenerator( path, Paths.SolutionDestinationFolder, properties: properties.ToImmutableDictionary(), federation: federation, serverPathMappings: serverPathMappings)) { solutionGenerator.GlobalAssemblyList = assemblyNames; solutionGenerator.Generate(solutionExplorerRoot: mergedSolutionExplorerRoot); } } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } }
private OrdinalExtractor() { var regexes = new Dictionary <Regex, TypeTag> { { new Regex(NumbersDefinitions.OrdinalSuffixRegex, RegexFlags), RegexTagGenerator.GenerateRegexTag(Constants.ORDINAL_PREFIX, Constants.NUMBER_SUFFIX) }, { new Regex(NumbersDefinitions.OrdinalNumericRegex, RegexFlags), RegexTagGenerator.GenerateRegexTag(Constants.ORDINAL_PREFIX, Constants.NUMBER_SUFFIX) }, { new Regex(NumbersDefinitions.OrdinalGermanRegex, RegexFlags), RegexTagGenerator.GenerateRegexTag(Constants.ORDINAL_PREFIX, Constants.GERMAN) }, { new Regex(NumbersDefinitions.OrdinalRoundNumberRegex, RegexFlags), RegexTagGenerator.GenerateRegexTag(Constants.ORDINAL_PREFIX, Constants.GERMAN) }, }; Regexes = regexes.ToImmutableDictionary(); }
public static ImmutableDictionary <string, string> ParseCompilationOptions( BlobReader blobReader ) { // Compiler flag bytes are UTF-8 null-terminated key-value pairs string key = null; Dictionary <string, string> kvp = new Dictionary <string, string>(); for (; ;) { var nullIndex = blobReader.IndexOf(0); if (nullIndex == -1) { break; } var value = blobReader.ReadUTF8(nullIndex); // Skip the null terminator blobReader.ReadByte(); if (key is null) { key = value; } else { kvp[key] = value; key = null; } } Assert.Null(key); Assert.Equal(0, blobReader.RemainingBytes); return(kvp.ToImmutableDictionary()); }
private static void IndexSolutions(IEnumerable <string> solutionFilePaths, Dictionary <string, string> properties, Federation federation, Dictionary <string, string> serverPathMappings) { var assemblyNames = new HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (var path in solutionFilePaths) { using (Disposable.Timing("Reading assembly names from " + path)) { foreach (var assemblyName in AssemblyNameExtractor.GetAssemblyNames(path)) { assemblyNames.Add(assemblyName); } } } foreach (var path in solutionFilePaths) { using (Disposable.Timing("Generating " + path)) { using (var solutionGenerator = new SolutionGenerator( path, Paths.SolutionDestinationFolder, properties: properties.ToImmutableDictionary(), federation: federation, serverPathMappings: serverPathMappings)) { solutionGenerator.GlobalAssemblyList = assemblyNames; solutionGenerator.Generate(solutionExplorerRoot: mergedSolutionExplorerRoot); } } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } }
public void FromChanges_Empty_ProjectPathAndActiveTargetChange() { const string previousProjectPath = @"c:\somefolder\someproject\a.csproj"; const string newProjectPath = @"c:\somefolder\someproject\b.csproj"; var catalogs = IProjectCatalogSnapshotFactory.Create(); var previousActiveTarget = new TargetFramework("tfm1"); var newActiveTarget = new TargetFramework("tfm2"); var previousSnapshot = new DependenciesSnapshot( previousProjectPath, previousActiveTarget, ImmutableDictionary <ITargetFramework, ITargetedDependenciesSnapshot> .Empty); var targetChanges = new DependenciesChangesBuilder(); var changes = new Dictionary <ITargetFramework, IDependenciesChanges> { [previousActiveTarget] = targetChanges.Build(), [newActiveTarget] = targetChanges.Build() }; var snapshot = DependenciesSnapshot.FromChanges( newProjectPath, previousSnapshot, changes.ToImmutableDictionary(), catalogs, newActiveTarget, ImmutableArray <IDependenciesSnapshotFilter> .Empty, new Dictionary <string, IProjectDependenciesSubTreeProvider>(), null); Assert.NotSame(previousSnapshot, snapshot); Assert.Same(newProjectPath, snapshot.ProjectPath); Assert.Same(newActiveTarget, snapshot.ActiveTarget); Assert.Same(previousSnapshot.Targets, snapshot.Targets); }
public OrdinalExtractor() { var _regexes = new Dictionary <Regex, string> { { new Regex( @"(?<=\b)((\d*(1[er][re]|2e|3e|4e|5e|6e|7e|8e|9e|0th))|(11e|12e))(?=\b)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline) , "OrdinalNum" }, { new Regex( @"", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline) , "OrdinalNum" }, { new Regex($@"(?<=\b){AllOrdinalRegex}(?=\b)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline) , "OrdFr" } }; Regexes = _regexes.ToImmutableDictionary(); }
private OrdinalExtractor() { var regexes = new Dictionary <Regex, TypeTag> { { new Regex(NumbersDefinitions.OrdinalSuffixRegex, RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.ORDINAL_PREFIX, Constants.NUMBER_SUFFIX) }, { new Regex(NumbersDefinitions.OrdinalNumericRegex, RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.ORDINAL_PREFIX, Constants.NUMBER_SUFFIX) }, { new Regex(NumbersDefinitions.OrdinalDutchRegex, RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.ORDINAL_PREFIX, Constants.DUTCH) }, { new Regex(NumbersDefinitions.OrdinalRoundNumberRegex, RegexOptions.Singleline), RegexTagGenerator.GenerateRegexTag(Constants.ORDINAL_PREFIX, Constants.DUTCH) } }; Regexes = regexes.ToImmutableDictionary(); }
public static async Task <ImmutableArray <Diagnostic> > GetProjectAnalyzerDiagnosticsAsync(Project project, ImmutableArray <DiagnosticAnalyzer> analzyers) { var cancel = new CancellationTokenSource(); var supportedDiagnosticsSpecificOptions = new Dictionary <string, ReportDiagnostic>(); analzyers.Select(x => x.SupportedDiagnostics).SelectMany(x => x).ToList().ForEach(x => { supportedDiagnosticsSpecificOptions[x.Id] = ReportDiagnostic.Default; }); supportedDiagnosticsSpecificOptions.Add("AD001", ReportDiagnostic.Error); var modifiedSpecificDiagnosticOptions = supportedDiagnosticsSpecificOptions.ToImmutableDictionary().SetItems(project.CompilationOptions.SpecificDiagnosticOptions); var modifiedCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(modifiedSpecificDiagnosticOptions); var compilation = await project.GetCompilationAsync(cancel.Token).ConfigureAwait(false); var compalationWithAnalyzers = compilation.WithAnalyzers(analzyers, cancellationToken: cancel.Token); var diagnostics = await compalationWithAnalyzers.GetAllDiagnosticsAsync(); var result = compalationWithAnalyzers.GetAnalysisResultAsync(cancel.Token); Logger.Information("get diagnostics - {0}", project.FilePath); Logger.Information("count - {0}", diagnostics.Count()); return(diagnostics); }
/// <summary> /// Creates run results for two genomes and two test instances. /// </summary> /// <returns>The created run results.</returns> private static ImmutableDictionary <ImmutableGenome, ImmutableDictionary <TestInstance, TestResult> > CreateRunResultsForTest() { // Create results for two genomes and two test instances: var runResults = new Dictionary <ImmutableGenome, ImmutableDictionary <TestInstance, TestResult> >(); // (a) Create instances. var instance1 = new TestInstance("1"); var instance2 = new TestInstance("2"); // (b) Create results for two genomes. var results1 = new Dictionary <TestInstance, TestResult>(); var results2 = new Dictionary <TestInstance, TestResult>(); results1.Add(instance1, new TestResult(TimeSpan.FromMilliseconds(1))); results1.Add(instance2, new TestResult(TimeSpan.FromMilliseconds(2))); results2.Add(instance1, new TestResult(TimeSpan.FromMilliseconds(3))); results2.Add(instance2, new TestResult(TimeSpan.FromMilliseconds(4))); // (c) Add them to dictionary using two different genomes as keys. runResults.Add(new ImmutableGenome(new Genome()), results1.ToImmutableDictionary()); runResults.Add(new ImmutableGenome(new Genome()), results2.ToImmutableDictionary()); return(runResults.ToImmutableDictionary()); }
private OrdinalExtractor() { var regexes = new Dictionary <Regex, string> { { new Regex(NumbersDefinitions.OrdinalSuffixRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline), "OrdinalNum" }, { new Regex(NumbersDefinitions.OrdinalNumericRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline), "OrdinalNum" }, { new Regex(NumbersDefinitions.AllOrdinalRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline), "OrdThai" }, { new Regex(NumbersDefinitions.RoundNumberOrdinalRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline), "OrdThai" } }; Regexes = regexes.ToImmutableDictionary(); }
private ImmutableDictionary<string, ImmutableList<LinkSourceInfo>> GetFileLinkSource(FileAndType ft, HtmlDocument doc) { var fileLinkSources = new Dictionary<string, List<LinkSourceInfo>>(); foreach (var pair in (from n in doc.DocumentNode.Descendants() where !string.Equals(n.Name, "xref", StringComparison.OrdinalIgnoreCase) from attr in n.Attributes where string.Equals(attr.Name, "src", StringComparison.OrdinalIgnoreCase) || string.Equals(attr.Name, "href", StringComparison.OrdinalIgnoreCase) where !string.IsNullOrWhiteSpace(attr.Value) select new { Node = n, Attr = attr }).ToList()) { string anchor = null; var link = pair.Attr; string linkFile = link.Value; var index = linkFile.IndexOfAny(UriFragmentOrQueryString); if (index != -1) { anchor = linkFile.Substring(index); linkFile = linkFile.Remove(index); } if (TypeForwardedToRelativePath.IsRelativePath(linkFile)) { var path = (TypeForwardedToRelativePath)ft.File + (TypeForwardedToRelativePath)linkFile; string file = path.GetPathFromWorkingFolder().UrlDecode(); if (SourceFiles.ContainsKey(file)) { link.Value = file; if (!string.IsNullOrEmpty(anchor) && string.Equals(link.Name, "href", StringComparison.OrdinalIgnoreCase)) { pair.Node.SetAttributeValue("anchor", anchor); } } List<LinkSourceInfo> sources; if (!fileLinkSources.TryGetValue(file, out sources)) { sources = new List<LinkSourceInfo>(); fileLinkSources[file] = sources; } sources.Add(new LinkSourceInfo { Target = file, Anchor = anchor, SourceFile = pair.Node.GetAttributeValue("sourceFile", null), LineNumber = pair.Node.GetAttributeValue("sourceStartLineNumber", 0), }); } } return fileLinkSources.ToImmutableDictionary(x => x.Key, x => x.Value.ToImmutableList()); }
private static void CheckIfCommasAreAtTheSameLineAsThePreviousParameter(SyntaxNodeAnalysisContext context, SyntaxNodeOrTokenList nodeOrTokenList) { SyntaxNode previousNode = null; // If index is even we expecting parameter syntax node, otherwise we expecting comma token. for (int index = 0, count = nodeOrTokenList.Count; index < count; ++index) { SyntaxNodeOrToken nodeOrToken = nodeOrTokenList[index]; if (index % 2 == 0) { // We expecting node here if (nodeOrToken.IsToken) { return; } previousNode = nodeOrToken.AsNode(); } else { // We expecting token here if (nodeOrToken.IsNode) { return; } if (previousNode.GetEndLine() < nodeOrToken.GetLineSpan().StartLinePosition.Line) { var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove, [OpenCloseSpacingCodeFixProvider.LayoutKey] = OpenCloseSpacingCodeFixProvider.LayoutPreserve }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, nodeOrToken.GetLocation(), properties.ToImmutableDictionary())); } } } }
private static void CheckIfLocationOfPreviousTokenAndOpenTokenAreTheSame(SyntaxNodeAnalysisContext context, SyntaxToken openToken, bool preserveLayout) { var previousToken = openToken.GetPreviousToken(); if (previousToken.IsMissing) { return; } var prevTokenLine = previousToken.GetLineSpan(); var openParenLine = openToken.GetLineSpan(); if (prevTokenLine.IsValid && openParenLine.IsValid && openParenLine.StartLinePosition.Line != prevTokenLine.StartLinePosition.Line) { var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove, [OpenCloseSpacingCodeFixProvider.LayoutKey] = preserveLayout ? OpenCloseSpacingCodeFixProvider.LayoutPreserve : OpenCloseSpacingCodeFixProvider.LayoutPack }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, openToken.GetLocation(), properties.ToImmutableDictionary())); } }
private static ImmutableDictionary<string, ImmutableList<CodeFixProvider>> GetAllCodeFixers() { Assembly assembly = typeof(StyleCop.Analyzers.SpacingRules.SA1027CodeFixProvider).Assembly; var codeFixProviderType = typeof(CodeFixProvider); Dictionary<string, ImmutableList<CodeFixProvider>> providers = new Dictionary<string, ImmutableList<CodeFixProvider>>(); foreach (var type in assembly.GetTypes()) { if (type.IsSubclassOf(codeFixProviderType) && !type.IsAbstract) { var codeFixProvider = (CodeFixProvider)Activator.CreateInstance(type); foreach (var diagnosticId in codeFixProvider.FixableDiagnosticIds) { providers.AddToInnerList(diagnosticId, codeFixProvider); } } } return providers.ToImmutableDictionary(); }
public NumberRangeExtractor() : base(NumberExtractor.GetInstance(), OrdinalExtractor.GetInstance(), new BaseNumberParser(new DutchNumberParserConfiguration())) { var regexes = new Dictionary <Regex, string>() { { // between...and... new Regex(NumbersDefinitions.TwoNumberRangeRegex1, RegexOptions.IgnoreCase | RegexOptions.Singleline) , NumberRangeConstants.TWONUMBETWEEN }, { // more than ... less than ... new Regex(NumbersDefinitions.TwoNumberRangeRegex2, RegexOptions.IgnoreCase | RegexOptions.Singleline) , NumberRangeConstants.TWONUM }, { // less than ... more than ... new Regex(NumbersDefinitions.TwoNumberRangeRegex3, RegexOptions.IgnoreCase | RegexOptions.Singleline) , NumberRangeConstants.TWONUM }, { // from ... to/~/- ... new Regex(NumbersDefinitions.TwoNumberRangeRegex4, RegexOptions.IgnoreCase | RegexOptions.Singleline) , NumberRangeConstants.TWONUMTILL }, { // more/greater/higher than ... new Regex(NumbersDefinitions.OneNumberRangeMoreRegex1, RegexOptions.IgnoreCase | RegexOptions.Singleline) , NumberRangeConstants.MORE }, { // 30 and/or greater/higher new Regex(NumbersDefinitions.OneNumberRangeMoreRegex2, RegexOptions.IgnoreCase | RegexOptions.Singleline) , NumberRangeConstants.MORE }, { // less/smaller/lower than ... new Regex(NumbersDefinitions.OneNumberRangeLessRegex1, RegexOptions.IgnoreCase | RegexOptions.Singleline) , NumberRangeConstants.LESS }, { // 30 and/or less/smaller/lower new Regex(NumbersDefinitions.OneNumberRangeLessRegex2, RegexOptions.IgnoreCase | RegexOptions.Singleline) , NumberRangeConstants.LESS }, { // equal to ... new Regex(NumbersDefinitions.OneNumberRangeEqualRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline) , NumberRangeConstants.EQUAL }, { // equal to 30 or more than, larger than 30 or equal to ... new Regex(NumbersDefinitions.OneNumberRangeMoreSeparateRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline) , NumberRangeConstants.MORE }, { // equal to 30 or less, smaller than 30 or equal ... new Regex(NumbersDefinitions.OneNumberRangeLessSeparateRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline) , NumberRangeConstants.LESS } }; Regexes = regexes.ToImmutableDictionary(); AmbiguousFractionConnectorsRegex = new Regex(NumbersDefinitions.AmbiguousFractionConnectorsRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline); }
private static void HandleGreaterThanToken(SyntaxTreeAnalysisContext context, SyntaxToken token) { if (token.IsMissing) { return; } switch (token.Parent.Kind()) { case SyntaxKind.TypeArgumentList: case SyntaxKind.TypeParameterList: break; default: // not a generic bracket return; } bool firstInLine = token.IsFirstInLine(); bool lastInLine = token.IsLastInLine(); bool precededBySpace = firstInLine || token.IsPrecededByWhitespace(); bool followedBySpace = token.IsFollowedByWhitespace(); bool allowTrailingNoSpace; bool allowTrailingSpace; if (!lastInLine) { SyntaxToken nextToken = token.GetNextToken(); switch (nextToken.Kind()) { case SyntaxKind.OpenParenToken: // DotToken isn't listed above, but it's required for reasonable member access formatting case SyntaxKind.DotToken: // CommaToken isn't listed above, but it's required for reasonable nested generic type arguments formatting case SyntaxKind.CommaToken: // OpenBracketToken isn't listed above, but it's required for reasonable array type formatting case SyntaxKind.OpenBracketToken: // SemicolonToken isn't listed above, but it's required for reasonable using alias declaration formatting case SyntaxKind.SemicolonToken: allowTrailingNoSpace = true; allowTrailingSpace = false; break; case SyntaxKind.CloseParenToken: case SyntaxKind.GreaterThanToken: allowTrailingNoSpace = true; allowTrailingSpace = true; break; case SyntaxKind.QuestionToken: allowTrailingNoSpace = nextToken.Parent.IsKind(SyntaxKind.NullableType); allowTrailingSpace = true; break; default: allowTrailingNoSpace = false; allowTrailingSpace = true; break; } } else { allowTrailingNoSpace = true; allowTrailingSpace = true; } if (!firstInLine && precededBySpace) { // Closing generic bracket must{ not} be {preceded} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "preceded")); } if (!lastInLine) { if (!allowTrailingNoSpace && !followedBySpace) { // Closing generic bracket must{} be {followed} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "followed")); } else if (!allowTrailingSpace && followedBySpace) { // Closing generic bracket must{ not} be {followed} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "followed")); } } }
private static void HandleCloseParenToken(SyntaxTreeAnalysisContext context, SyntaxToken token) { if (token.IsMissing) { return; } bool precededBySpace = token.IsFirstInLine() || token.IsPrecededByWhitespace(); bool followedBySpace = token.IsFollowedByWhitespace(); bool lastInLine = token.IsLastInLine(); bool precedesStickyCharacter; bool allowEndOfLine = false; bool suppressFollowingSpaceError = false; SyntaxToken nextToken = token.GetNextToken(); switch (nextToken.Kind()) { case SyntaxKind.OpenParenToken: case SyntaxKind.CloseParenToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.CloseBracketToken: case SyntaxKind.SemicolonToken: case SyntaxKind.CommaToken: precedesStickyCharacter = true; break; case SyntaxKind.QuestionToken: if (nextToken.Parent.IsKind(SyntaxKind.ConditionalAccessExpression)) { // allow a space for this case, but only if the ')' character is the last on the line allowEndOfLine = true; precedesStickyCharacter = true; } else { precedesStickyCharacter = false; } break; case SyntaxKind.PlusToken: precedesStickyCharacter = nextToken.Parent.IsKind(SyntaxKind.UnaryPlusExpression); // this will be reported as SA1022 suppressFollowingSpaceError = true; break; case SyntaxKind.MinusToken: precedesStickyCharacter = nextToken.Parent.IsKind(SyntaxKind.UnaryMinusExpression); // this will be reported as SA1021 suppressFollowingSpaceError = true; break; case SyntaxKind.DotToken: // allow a space for this case, but only if the ')' character is the last on the line allowEndOfLine = true; precedesStickyCharacter = true; break; case SyntaxKind.ColonToken: bool requireSpace = nextToken.Parent.IsKind(SyntaxKind.ConditionalExpression) || nextToken.Parent.IsKind(SyntaxKind.BaseConstructorInitializer) || nextToken.Parent.IsKind(SyntaxKind.ThisConstructorInitializer); precedesStickyCharacter = !requireSpace; break; case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: precedesStickyCharacter = true; suppressFollowingSpaceError = false; break; case SyntaxKind.CloseBraceToken: precedesStickyCharacter = nextToken.Parent is InterpolationSyntax; break; default: precedesStickyCharacter = false; break; } switch (token.Parent.Kind()) { case SyntaxKind.CastExpression: precedesStickyCharacter = true; break; default: break; } if (precededBySpace) { // Closing parenthesis must{ not} be {preceded} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "preceded")); } if (!suppressFollowingSpaceError) { if (!precedesStickyCharacter && !followedBySpace && !lastInLine) { // Closing parenthesis must{} be {followed} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "followed")); } else if (precedesStickyCharacter && followedBySpace && (!lastInLine || !allowEndOfLine)) { // Closing parenthesis must{ not} be {followed} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "followed")); } } }
private static DiagnosticAnalyzerService CreateDiagnosticAnalyzerService(Dictionary<string, DiagnosticAnalyzer[]> analyzerMap) { return analyzerMap == null || analyzerMap.Count == 0 ? new TestDiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap()) : new TestDiagnosticAnalyzerService(analyzerMap.ToImmutableDictionary(kvp => kvp.Key, kvp => kvp.Value.ToImmutableArray())); }
internal static async Task<ImmutableArray<CodeFixEquivalenceGroup>> CreateAsync(CodeFixProvider codeFixProvider, ImmutableDictionary<ProjectId, ImmutableArray<Diagnostic>> allDiagnostics, Solution solution, CancellationToken cancellationToken) { var fixAllProvider = codeFixProvider.GetFixAllProvider(); if (fixAllProvider == null) { return ImmutableArray.Create<CodeFixEquivalenceGroup>(); } Dictionary<ProjectId, Dictionary<string, List<Diagnostic>>> relevantDocumentDiagnostics = new Dictionary<ProjectId, Dictionary<string, List<Diagnostic>>>(); Dictionary<ProjectId, List<Diagnostic>> relevantProjectDiagnostics = new Dictionary<ProjectId, List<Diagnostic>>(); foreach (var projectDiagnostics in allDiagnostics) { foreach (var diagnostic in projectDiagnostics.Value) { if (!codeFixProvider.FixableDiagnosticIds.Contains(diagnostic.Id)) { continue; } if (diagnostic.Location.IsInSource) { string sourcePath = diagnostic.Location.GetLineSpan().Path; Dictionary<string, List<Diagnostic>> projectDocumentDiagnostics; if (!relevantDocumentDiagnostics.TryGetValue(projectDiagnostics.Key, out projectDocumentDiagnostics)) { projectDocumentDiagnostics = new Dictionary<string, List<Diagnostic>>(); relevantDocumentDiagnostics.Add(projectDiagnostics.Key, projectDocumentDiagnostics); } List<Diagnostic> diagnosticsInFile; if (!projectDocumentDiagnostics.TryGetValue(sourcePath, out diagnosticsInFile)) { diagnosticsInFile = new List<Diagnostic>(); projectDocumentDiagnostics.Add(sourcePath, diagnosticsInFile); } diagnosticsInFile.Add(diagnostic); } else { List<Diagnostic> diagnosticsInProject; if (!relevantProjectDiagnostics.TryGetValue(projectDiagnostics.Key, out diagnosticsInProject)) { diagnosticsInProject = new List<Diagnostic>(); relevantProjectDiagnostics.Add(projectDiagnostics.Key, diagnosticsInProject); } diagnosticsInProject.Add(diagnostic); } } } ImmutableDictionary<ProjectId, ImmutableDictionary<string, ImmutableArray<Diagnostic>>> documentDiagnosticsToFix = relevantDocumentDiagnostics.ToImmutableDictionary(i => i.Key, i => i.Value.ToImmutableDictionary(j => j.Key, j => j.Value.ToImmutableArray(), StringComparer.OrdinalIgnoreCase)); ImmutableDictionary<ProjectId, ImmutableArray<Diagnostic>> projectDiagnosticsToFix = relevantProjectDiagnostics.ToImmutableDictionary(i => i.Key, i => i.Value.ToImmutableArray()); HashSet<string> equivalenceKeys = new HashSet<string>(); foreach (var diagnostic in relevantDocumentDiagnostics.Values.SelectMany(i => i.Values).SelectMany(i => i).Concat(relevantProjectDiagnostics.Values.SelectMany(i => i))) { foreach (var codeAction in await GetFixesAsync(solution, codeFixProvider, diagnostic, cancellationToken).ConfigureAwait(false)) { equivalenceKeys.Add(codeAction.EquivalenceKey); } } List<CodeFixEquivalenceGroup> groups = new List<CodeFixEquivalenceGroup>(); foreach (var equivalenceKey in equivalenceKeys) { groups.Add(new CodeFixEquivalenceGroup(equivalenceKey, solution, fixAllProvider, codeFixProvider, documentDiagnosticsToFix, projectDiagnosticsToFix)); } return groups.ToImmutableArray(); }
private static void InitializeWellKnownSystemNamespaceTable() { if (s_wellKnownSystemNamespaceTable == null) { lock (s_lock) { if (s_wellKnownSystemNamespaceTable == null) { #region List of Well known System Namespaces var wellKnownSystemNamespaces = new List<string> { "Microsoft.CSharp", "Microsoft.SqlServer.Server", "Microsoft.VisualBasic", "Microsoft.Win32", "Microsoft.Win32.SafeHandles", "System", "System.CodeDom", "System.CodeDom.Compiler", "System.Collections", "System.Collections.Generic", "System.Collections.ObjectModel", "System.Collections.Specialized", "System.ComponentModel", "System.ComponentModel.Design", "System.ComponentModel.Design.Serialization", "System.Configuration", "System.Configuration.Assemblies", "System.Data", "System.Data.Common", "System.Data.Odbc", "System.Data.OleDb", "System.Data.Sql", "System.Data.SqlClient", "System.Data.SqlTypes", "System.Deployment.Internal", "System.Diagnostics", "System.Diagnostics.CodeAnalysis", "System.Diagnostics.SymbolStore", "System.Drawing", "System.Drawing.Design", "System.Drawing.Drawing2D", "System.Drawing.Imaging", "System.Drawing.Printing", "System.Drawing.Text", "System.Globalization", "System.IO", "System.IO.Compression", "System.IO.IsolatedStorage", "System.IO.Ports", "System.Media", "System.Net", "System.Net.Cache", "System.Net.Configuration", "System.Net.Mail", "System.Net.Mime", "System.Net.NetworkInformation", "System.Net.Security", "System.Net.Sockets", "System.Reflection", "System.Reflection.Emit", "System.Resources", "System.Runtime", "System.Runtime.CompilerServices", "System.Runtime.ConstrainedExecution", "System.Runtime.Hosting", "System.Runtime.InteropServices", "System.Runtime.InteropServices.ComTypes", "System.Runtime.InteropServices.Expando", "System.Runtime.Remoting", "System.Runtime.Remoting.Activation", "System.Runtime.Remoting.Channels", "System.Runtime.Remoting.Contexts", "System.Runtime.Remoting.Lifetime", "System.Runtime.Remoting.Messaging", "System.Runtime.Remoting.Metadata", "System.Runtime.Remoting.Metadata.W3cXsd2001", "System.Runtime.Remoting.Proxies", "System.Runtime.Remoting.Services", "System.Runtime.Serialization", "System.Runtime.Serialization.Formatters", "System.Runtime.Serialization.Formatters.Binary", "System.Runtime.Versioning", "System.Security", "System.Security.AccessControl", "System.Security.Authentication", "System.Security.Cryptography", "System.Security.Cryptography.X509Certificates", "System.Security.Permissions", "System.Security.Policy", "System.Security.Principal", "System.Text", "System.Text.RegularExpressions", "System.Threading", "System.Timers", "System.Web", "System.Web.Caching", "System.Web.Compilation", "System.Web.Configuration", "System.Web.Configuration.Internal", "System.Web.Handlers", "System.Web.Hosting", "System.Web.Mail", "System.Web.Management", "System.Web.Profile", "System.Web.Security", "System.Web.SessionState", "System.Web.UI", "System.Web.UI.Adapters", "System.Web.UI.HtmlControls", "System.Web.UI.WebControls", "System.Web.UI.WebControls.Adapters", "System.Web.UI.WebControls.WebParts", "System.Web.Util", "System.Windows.Forms", "System.Windows.Forms.ComponentModel.Com2Interop", "System.Windows.Forms.Design", "System.Windows.Forms.Layout", "System.Windows.Forms.PropertyGridInternal", "System.Windows.Forms.VisualStyles", "System.Xml", "System.Xml.Schema", "System.Xml.Serialization", "System.Xml.Serialization.Advanced", "System.Xml.Serialization.Configuration", "System.Xml.XPath", "System.Xml.Xsl" }; #endregion var wellKnownSystemNamespaceTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); UpdateNamespaceTable(wellKnownSystemNamespaceTable, wellKnownSystemNamespaces); s_wellKnownSystemNamespaceTable = wellKnownSystemNamespaceTable.ToImmutableDictionary(); } } } }
public AuthorizationManager(IAuthorizationConfiguration authorizationConfiguration) { defaultAuthorizer = authorizationConfiguration.DefaultAuthorizer; if (defaultAuthorizer == null) { throw new InitialisationException("Default Authorizer cannot be null"); } var isVisibleDict = new Dictionary<Type, Func<object, IPrincipal, object, string, bool>>() { {defaultAuthorizer, DelegateUtils.CreateTypeAuthorizerDelegate(defaultAuthorizer.GetMethod("IsVisible"))} }; var isEditableDict = new Dictionary<Type, Func<object, IPrincipal, object, string, bool>>() { {defaultAuthorizer, DelegateUtils.CreateTypeAuthorizerDelegate(defaultAuthorizer.GetMethod("IsEditable"))} }; if (authorizationConfiguration.NamespaceAuthorizers.Any()) { namespaceAuthorizers = authorizationConfiguration.NamespaceAuthorizers.OrderByDescending(x => x.Key.Length).ToImmutableDictionary(); } if (authorizationConfiguration.TypeAuthorizers.Any()) { if (authorizationConfiguration.TypeAuthorizers.Values.Any(t => typeof(ITypeAuthorizer<object>).IsAssignableFrom(t))) { throw new InitialisationException("Only Default Authorizer can be ITypeAuthorizer<object>"); } typeAuthorizers = authorizationConfiguration.TypeAuthorizers.ToImmutableDictionary(); isVisibleDelegates = isVisibleDict.Union(authorizationConfiguration.TypeAuthorizers.Values.ToDictionary(type => type, type => DelegateUtils.CreateTypeAuthorizerDelegate(type.GetMethod("IsVisible")))).ToImmutableDictionary(); isEditableDelegates = isEditableDict.Union(authorizationConfiguration.TypeAuthorizers.Values.ToDictionary(type => type, type => DelegateUtils.CreateTypeAuthorizerDelegate(type.GetMethod("IsEditable")))).ToImmutableDictionary(); } else { // default authorizer must be the only TypeAuthorizer isVisibleDelegates = isVisibleDict.ToImmutableDictionary(); isEditableDelegates = isEditableDict.ToImmutableDictionary(); } }
private static void HandleCloseBraceToken(SyntaxTreeAnalysisContext context, SyntaxToken token) { if (token.IsMissing) { return; } bool precededBySpace = token.IsFirstInLine() || token.IsPrecededByWhitespace(); if (token.Parent is InterpolationSyntax) { if (precededBySpace) { // Closing curly bracket must{ not} be {preceded} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "preceded")); } return; } bool followedBySpace = token.IsFollowedByWhitespace(); bool lastInLine = token.IsLastInLine(); bool precedesSpecialCharacter; if (!followedBySpace && !lastInLine) { SyntaxToken nextToken = token.GetNextToken(); precedesSpecialCharacter = nextToken.IsKind(SyntaxKind.CloseParenToken) || nextToken.IsKind(SyntaxKind.CommaToken) || nextToken.IsKind(SyntaxKind.SemicolonToken) || nextToken.IsKind(SyntaxKind.DotToken) || (nextToken.IsKind(SyntaxKind.QuestionToken) && nextToken.GetNextToken(includeZeroWidth: true).IsKind(SyntaxKind.DotToken)) || nextToken.IsKind(SyntaxKind.CloseBracketToken); } else { precedesSpecialCharacter = false; } if (!precededBySpace) { // Closing curly bracket must{} be {preceded} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "preceded")); } if (!lastInLine && !precedesSpecialCharacter && !followedBySpace) { // Closing curly bracket must{} be {followed} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "followed")); } }
private ImmutableDictionary<string, FileAndType> GetAllSourceFiles(IEnumerable<FileAndType> allSourceFiles) { var dict = new Dictionary<string, FileAndType>(TypeForwardedToFilePathComparer.OSPlatformSensitiveStringComparer); foreach (var item in allSourceFiles) { var path = (string)((TypeForwardedToRelativePath)item.File).GetPathFromWorkingFolder(); FileAndType ft; if (dict.TryGetValue(path, out ft)) { if (TypeForwardedToFilePathComparer.OSPlatformSensitiveStringComparer.Equals(ft.BaseDir, item.BaseDir) && TypeForwardedToFilePathComparer.OSPlatformSensitiveStringComparer.Equals(ft.File, item.File)) { if (ft.Type >= item.Type) { Logger.LogWarning($"Ignored duplicate file {Path.Combine(item.BaseDir, item.File)}."); continue; } else { Logger.LogWarning($"Ignored duplicate file {Path.Combine(ft.BaseDir, ft.File)}."); } } else { if (ft.Type >= item.Type) { Logger.LogWarning($"Ignored conflict file {Path.Combine(item.BaseDir, item.File)} for {path} by {Path.Combine(ft.BaseDir, ft.File)}."); continue; } else { Logger.LogWarning($"Ignored conflict file {Path.Combine(ft.BaseDir, ft.File)} for {path} by {Path.Combine(item.BaseDir, item.File)}."); } } } dict[path] = item; } return dict.ToImmutableDictionary(TypeForwardedToFilePathComparer.OSPlatformSensitiveStringComparer); }
private static void HandleAsteriskToken(SyntaxTreeAnalysisContext context, SyntaxToken token) { if (token.IsMissing) { return; } bool allowAtLineStart; bool allowAtLineEnd; bool allowPrecedingSpace; bool allowTrailingSpace; switch (token.Parent.Kind()) { case SyntaxKind.PointerType: allowAtLineStart = false; allowAtLineEnd = true; allowPrecedingSpace = false; var nextToken = token.GetNextToken(); switch (nextToken.Kind()) { case SyntaxKind.OpenBracketToken: case SyntaxKind.OpenParenToken: allowTrailingSpace = false; break; default: allowTrailingSpace = true; break; } break; case SyntaxKind.PointerIndirectionExpression: allowAtLineStart = true; allowAtLineEnd = false; allowTrailingSpace = false; var prevToken = token.GetPreviousToken(); switch (prevToken.Kind()) { case SyntaxKind.OpenBracketToken: case SyntaxKind.OpenParenToken: case SyntaxKind.CloseParenToken: allowPrecedingSpace = false; break; default: allowPrecedingSpace = true; break; } break; default: return; } bool firstInLine = token.IsFirstInLine(); bool precededBySpace = firstInLine || token.IsPrecededByWhitespace(); bool followedBySpace = token.IsFollowedByWhitespace(); bool lastInLine = token.IsLastInLine(); if (!allowAtLineStart && firstInLine) { // Dereference symbol '*' must {not appear at the beginning of a line}. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), "not appear at the beginning of a line")); } else if (!allowPrecedingSpace && precededBySpace) { // Dereference symbol '*' must {not be preceded by a space}. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), "not be preceded by a space")); } if (!allowAtLineEnd && lastInLine) { // Dereference symbol '*' must {not appear at the end of a line}. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), "not appear at the end of a line")); } else if (!allowTrailingSpace && followedBySpace) { // Dereference symbol '*' must {not be followed by a space}. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), "not be followed by a space")); } if (!followedBySpace && allowTrailingSpace) { // Dereference symbol '*' must {be followed by a space}. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), "be followed by a space")); } }
private static void HandleOpenBraceToken(SyntaxTreeAnalysisContext context, SyntaxToken token) { if (token.IsMissing) { return; } bool followedBySpace = token.IsFollowedByWhitespace(); if (token.Parent is InterpolationSyntax) { if (followedBySpace) { // Opening curly bracket must{} be {followed} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "followed")); } return; } bool precededBySpace = token.IsFirstInLine() || token.IsPrecededByWhitespace(); if (!precededBySpace) { // Opening curly bracket must{} be {preceded} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "preceded")); } if (!token.IsLastInLine() && !followedBySpace) { // Opening curly bracket must{} be {followed} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "followed")); } }
/// <summary> /// Returns a list of all analyzer diagnostics inside the specific project. This is an asynchronous operation. /// </summary> /// <param name="analyzers">The list of analyzers that should be used</param> /// <param name="project">The project that should be analyzed</param> /// <param name="force"><see langword="true"/> to force the analyzers to be enabled; otherwise, /// <see langword="false"/> to use the behavior configured for the specified <paramref name="project"/>.</param> /// <param name="cancellationToken">The cancellation token that the task will observe.</param> /// <returns>A list of diagnostics inside the project</returns> private static async Task<ImmutableArray<Diagnostic>> GetProjectAnalyzerDiagnosticsAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, Project project, bool force, CancellationToken cancellationToken) { var supportedDiagnosticsSpecificOptions = new Dictionary<string, ReportDiagnostic>(); if (force) { foreach (var analyzer in analyzers) { foreach (var diagnostic in analyzer.SupportedDiagnostics) { // make sure the analyzers we are testing are enabled supportedDiagnosticsSpecificOptions[diagnostic.Id] = ReportDiagnostic.Default; } } } // Report exceptions during the analysis process as errors supportedDiagnosticsSpecificOptions.Add("AD0001", ReportDiagnostic.Error); // update the project compilation options var modifiedSpecificDiagnosticOptions = supportedDiagnosticsSpecificOptions.ToImmutableDictionary().SetItems(project.CompilationOptions.SpecificDiagnosticOptions); var modifiedCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(modifiedSpecificDiagnosticOptions); var processedProject = project.WithCompilationOptions(modifiedCompilationOptions); Compilation compilation = await processedProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); CompilationWithAnalyzers compilationWithAnalyzers = compilation.WithAnalyzers(analyzers, cancellationToken: cancellationToken); var diagnostics = await FixAllContextHelper.GetAllDiagnosticsAsync(compilation, compilationWithAnalyzers, analyzers, project.Documents, true, cancellationToken).ConfigureAwait(false); return diagnostics; }
internal override CommandLineArguments CommonParse(IEnumerable <string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories) { List <Diagnostic> diagnostics = new List <Diagnostic>(); List <string> flattenedArgs = new List <string>(); List <string> scriptArgs = IsScriptRunner ? new List <string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory); var sourceFiles = new List <CommandLineSourceFile>(); var metadataReferences = new List <CommandLineReference>(); var analyzers = new List <CommandLineAnalyzerReference>(); var additionalFiles = new List <CommandLineSourceFile>(); var managedResources = new List <ResourceDescription>(); var defines = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); string outputDirectory = baseDirectory; string outputFileName = null; string documentationPath = null; string moduleName = null; string runtimeMetadataVersion = null; // will be read from cor library if not specified in cmd string compilationName = null; string versionString = null; bool optimize = false; bool concurrentBuild = true; var diagnosticOptions = new Dictionary <string, ReportDiagnostic>(); PhpDocTypes phpdocTypes = PhpDocTypes.None; OutputKind outputKind = OutputKind.ConsoleApplication; bool optionsEnded = false; bool displayHelp = false, displayLogo = true; bool emitPdb = true, debugPlus = false; string mainTypeName = null, pdbPath = null; Version languageVersion = null; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; bool publicSign = false; bool shortOpenTags = false; bool resourcesOrModulesSpecified = false; DebugInformationFormat debugInformationFormat = DebugInformationFormat.Pdb; List <string> referencePaths = new List <string>(); List <string> keyFileSearchPaths = new List <string>(); if (sdkDirectoryOpt != null) { referencePaths.Add(sdkDirectoryOpt); } if (!string.IsNullOrEmpty(additionalReferenceDirectories)) { referencePaths.AddRange(additionalReferenceDirectories.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)); } foreach (string arg in flattenedArgs) { Debug.Assert(optionsEnded || !arg.StartsWith("@", StringComparison.Ordinal)); string name, value; if (optionsEnded || !TryParseOption2(arg, out name, out value)) { sourceFiles.AddRange(ExpandFileArgument(arg, baseDirectory, diagnostics)); continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "d": case "define": ParseDefine(value, defines); continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "debug": emitPdb = true; // unused, parsed for backward compat only if (!string.IsNullOrEmpty(value)) { switch (value.ToLower()) { case "full": case "pdbonly": debugInformationFormat = DebugInformationFormat.Pdb; break; case "portable": debugInformationFormat = DebugInformationFormat.PortablePdb; break; case "embedded": debugInformationFormat = DebugInformationFormat.Embedded; break; default: //AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); break; } } continue; case "debug+": //guard against "debug+:xx" if (value != null) { break; } emitPdb = true; debugPlus = true; continue; case "debug-": if (value != null) { break; } emitPdb = false; debugPlus = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) { break; } optimize = true; continue; case "o-": case "optimize-": if (value != null) { break; } optimize = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) { break; } concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) { break; } concurrentBuild = false; continue; case "nowarn": if (string.IsNullOrEmpty(value)) { diagnostics.Add(Errors.MessageProvider.Instance.CreateDiagnostic(Errors.ErrorCode.ERR_SwitchNeedsValue, Location.None, name)); } else { foreach (var warn in value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries)) { diagnosticOptions[warn] = ReportDiagnostic.Suppress; } } continue; case "langversion": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { diagnostics.Add(Errors.MessageProvider.Instance.CreateDiagnostic(Errors.ErrorCode.ERR_SwitchNeedsValue, Location.None, name)); } else if (string.Equals(value, "default", StringComparison.OrdinalIgnoreCase) || string.Equals(value, "latest", StringComparison.OrdinalIgnoreCase)) { languageVersion = null; // latest } else if (!Version.TryParse(value, out languageVersion)) { throw new ArgumentException("langversion"); //AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "publicsign": case "publicsign+": if (value != null) { break; } publicSign = true; continue; case "publicsign-": if (value != null) { break; } publicSign = false; continue; case "keyfile": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { diagnostics.Add(Errors.MessageProvider.Instance.CreateDiagnostic(Errors.ErrorCode.ERR_SwitchNeedsValue, Location.None, name)); // TODO: AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = value; } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { diagnostics.Add(Errors.MessageProvider.Instance.CreateDiagnostic(Errors.ErrorCode.ERR_SwitchNeedsValue, Location.None, name)); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "shortopentag": shortOpenTags = string.IsNullOrEmpty(value) || (RemoveQuotesAndSlashes(value).ToLowerInvariant() == "true"); continue; case "shortopentag+": shortOpenTags = true; continue; case "shortopentag-": shortOpenTags = false; continue; case "nologo": displayLogo = false; continue; case "m": case "main": // Remove any quotes for consistent behavior as MSBuild can return quoted or // unquoted main. var unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { diagnostics.Add(Errors.MessageProvider.Instance.CreateDiagnostic(Errors.ErrorCode.ERR_SwitchNeedsValue, Location.None, name)); } else { mainTypeName = unquoted; } continue; case "pdb": if (string.IsNullOrEmpty(value)) { diagnostics.Add(Errors.MessageProvider.Instance.CreateDiagnostic(Errors.ErrorCode.ERR_SwitchNeedsValue, Location.None, name)); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "out": if (string.IsNullOrWhiteSpace(value)) { diagnostics.Add(Errors.MessageProvider.Instance.CreateDiagnostic(Errors.ErrorCode.ERR_SwitchNeedsValue, Location.None, name)); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { diagnostics.Add(Errors.MessageProvider.Instance.CreateDiagnostic(Errors.ErrorCode.ERR_SwitchNeedsValue, Location.None, name)); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "xmldoc": case "doc": documentationPath = value ?? string.Empty; break; case "phpdoctypes+": phpdocTypes = PhpDocTypes.All; break; case "phpdoctypes-": phpdocTypes = PhpDocTypes.None; break; case "phpdoctypes": if (value == null) { phpdocTypes = PhpDocTypes.All; } else { phpdocTypes = (PhpDocTypes)Enum.Parse(typeof(PhpDocTypes), value); } break; case "modulename": var unquotedModuleName = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { diagnostics.Add(Errors.MessageProvider.Instance.CreateDiagnostic(Errors.ErrorCode.ERR_SwitchNeedsValue, Location.None, name)); } else { moduleName = unquotedModuleName; } continue; case "version": case "v": versionString = RemoveQuotesAndSlashes(value); continue; case "runtimemetadataversion": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { diagnostics.Add(Errors.MessageProvider.Instance.CreateDiagnostic(Errors.ErrorCode.ERR_SwitchNeedsValue, Location.None, name)); } else { runtimeMetadataVersion = unquoted; } continue; case "res": case "resource": if (value == null) { break; // Dev11 reports unrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports unrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; default: break; } } GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFiles.Count != 0, /*moduleAssemblyName*/ null, ref outputFileName, ref moduleName, out compilationName); // if (sourceFiles.Count == 0 && !IsScriptRunner && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { // warning: no source files specified diagnostics.Add(Errors.MessageProvider.Instance.CreateDiagnostic(Errors.ErrorCode.WRN_NoSourceFiles, Location.None)); } // XML Documentation path if (documentationPath != null) { if (documentationPath.Length == 0) { // default xmldoc file name documentationPath = compilationName + ".xml"; } // resolve path documentationPath = PathUtilities.CombinePossiblyRelativeAndRelativePaths(outputDirectory, documentationPath); } // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } // Public sign doesn't use the legacy search path settings if (publicSign && !string.IsNullOrWhiteSpace(keyFileSetting)) { keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory); } var parseOptions = new PhpParseOptions ( documentationMode: DocumentationMode.Diagnose, // always diagnose kind: SourceCodeKind.Regular, languageVersion: languageVersion, shortOpenTags: shortOpenTags, features: ImmutableDictionary <string, string> .Empty, // features: parsedFeatures defines: defines.ToImmutableDictionary() ); var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); //// We want to report diagnostics with source suppression in the error log file. //// However, these diagnostics won't be reported on the command line. //var reportSuppressedDiagnostics = errorLogPath != null; var options = new PhpCompilationOptions ( outputKind: outputKind, baseDirectory: baseDirectory, sdkDirectory: sdkDirectoryOpt, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, versionString: versionString, phpdocTypes: phpdocTypes, parseOptions: parseOptions, diagnostics: diagnostics.AsImmutable(), specificDiagnosticOptions: diagnosticOptions, //usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: false, // checkOverflow, //deterministic: deterministic, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: Platform.AnyCpu, //generalDiagnosticOption: generalDiagnosticOption, //warningLevel: warningLevel, //specificDiagnosticOptions: diagnosticOptions, //reportSuppressedDiagnostics: reportSuppressedDiagnostics, publicSign: publicSign ); if (debugPlus) { options = options.WithDebugPlusMode(debugPlus); } var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: debugInformationFormat, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later //baseAddress: baseAddress, //highEntropyVirtualAddressSpace: highEntropyVA, //fileAlignment: fileAlignment, //subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion ); return(new PhpCommandLineArguments() { // TODO: parsed arguments IsScriptRunner = IsScriptRunner, //InteractiveMode = interactiveMode || IsScriptRunner && sourceFiles.Count == 0, BaseDirectory = baseDirectory, //PathMap = pathMap, Errors = ImmutableArray <Diagnostic> .Empty, Utf8Output = true, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, //ErrorLogPath = errorLogPath, //AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = Encoding.UTF8, ChecksumAlgorithm = SourceHashAlgorithm.Sha1, // checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths.AsImmutable(), SourcePaths = ImmutableArray <string> .Empty, //sourcePaths.AsImmutable(), KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), //Win32ResourceFile = win32ResourceFile, //Win32Icon = win32IconFile, //Win32Manifest = win32ManifestFile, //NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = IsScriptRunner ? scriptParseOptions : parseOptions, EmitOptions = emitOptions, //ScriptArguments = scriptArgs.AsImmutableOrEmpty(), //TouchedFilesPath = touchedFilesPath, //PrintFullPaths = printFullPaths, //ShouldIncludeErrorEndLocation = errorEndLocation, //PreferredUILang = preferredUILang, //SqmSessionGuid = sqmSessionGuid, //ReportAnalyzer = reportAnalyzer }); }
public async Task <ActionResult <GenericResponse> > GitHubWikiHistoryGet(string page) { if (string.IsNullOrEmpty(page)) { throw new ArgumentNullException(nameof(page)); } Dictionary <string, DateTime>?revisions = await GitHub.GetWikiHistory(page).ConfigureAwait(false); return(revisions != null ? revisions.Count > 0 ? Ok(new GenericResponse <ImmutableDictionary <string, DateTime> >(revisions.ToImmutableDictionary())) : BadRequest(new GenericResponse(false, string.Format(CultureInfo.CurrentCulture, Strings.ErrorIsInvalid, nameof(page)))) : StatusCode((int)HttpStatusCode.ServiceUnavailable, new GenericResponse(false, string.Format(CultureInfo.CurrentCulture, Strings.ErrorRequestFailedTooManyTimes, WebBrowser.MaxTries)))); }
private static ImmutableDictionary<FixAllProvider, ImmutableHashSet<string>> GetAllFixAllProviders(IEnumerable<CodeFixProvider> providers) { Dictionary<FixAllProvider, ImmutableHashSet<string>> fixAllProviders = new Dictionary<FixAllProvider, ImmutableHashSet<string>>(); foreach (var provider in providers) { var fixAllProvider = provider.GetFixAllProvider(); var supportedDiagnosticIds = fixAllProvider.GetSupportedFixAllDiagnosticIds(provider); foreach (var id in supportedDiagnosticIds) { fixAllProviders.AddToInnerSet(fixAllProvider, id); } } return fixAllProviders.ToImmutableDictionary(); }
private static void HandleIncrementDecrementToken(SyntaxTreeAnalysisContext context, SyntaxToken token) { if (token.IsMissing) { return; } switch (token.Parent.Kind()) { case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: if (token.HasTrailingTrivia) { string symbolName; if (token.IsKind(SyntaxKind.MinusMinusToken)) { symbolName = "Decrement"; } else { symbolName = "Increment"; } // {Increment|Decrement} symbol '{++|--}' must not be {followed} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove, }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), symbolName, token.Text, "followed")); } break; case SyntaxKind.PostIncrementExpression: case SyntaxKind.PostDecrementExpression: SyntaxToken previousToken = token.GetPreviousToken(); if (!previousToken.IsMissing && previousToken.HasTrailingTrivia) { string symbolName; if (token.IsKind(SyntaxKind.MinusMinusToken)) { symbolName = "Decrement"; } else { symbolName = "Increment"; } // {Increment|Decrement} symbol '{++|--}' must not be {preceded} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove, }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), symbolName, token.Text, "preceded")); } break; default: return; } }
internal static async Task <ImmutableArray <CodeFixEquivalenceGroup> > CreateAsync(CodeFixProvider codeFixProvider, ImmutableDictionary <ProjectId, ImmutableArray <Diagnostic> > allDiagnostics, Solution solution, CancellationToken cancellationToken) { var fixAllProvider = codeFixProvider.GetFixAllProvider(); if (fixAllProvider == null) { return(ImmutableArray.Create <CodeFixEquivalenceGroup>()); } Dictionary <ProjectId, Dictionary <string, List <Diagnostic> > > relevantDocumentDiagnostics = new Dictionary <ProjectId, Dictionary <string, List <Diagnostic> > >(); Dictionary <ProjectId, List <Diagnostic> > relevantProjectDiagnostics = new Dictionary <ProjectId, List <Diagnostic> >(); foreach (var projectDiagnostics in allDiagnostics) { foreach (var diagnostic in projectDiagnostics.Value) { if (!codeFixProvider.FixableDiagnosticIds.Contains(diagnostic.Id)) { continue; } if (diagnostic.Location.IsInSource) { string sourcePath = diagnostic.Location.GetLineSpan().Path; Dictionary <string, List <Diagnostic> > projectDocumentDiagnostics; if (!relevantDocumentDiagnostics.TryGetValue(projectDiagnostics.Key, out projectDocumentDiagnostics)) { projectDocumentDiagnostics = new Dictionary <string, List <Diagnostic> >(); relevantDocumentDiagnostics.Add(projectDiagnostics.Key, projectDocumentDiagnostics); } List <Diagnostic> diagnosticsInFile; if (!projectDocumentDiagnostics.TryGetValue(sourcePath, out diagnosticsInFile)) { diagnosticsInFile = new List <Diagnostic>(); projectDocumentDiagnostics.Add(sourcePath, diagnosticsInFile); } diagnosticsInFile.Add(diagnostic); } else { List <Diagnostic> diagnosticsInProject; if (!relevantProjectDiagnostics.TryGetValue(projectDiagnostics.Key, out diagnosticsInProject)) { diagnosticsInProject = new List <Diagnostic>(); relevantProjectDiagnostics.Add(projectDiagnostics.Key, diagnosticsInProject); } diagnosticsInProject.Add(diagnostic); } } } ImmutableDictionary <ProjectId, ImmutableDictionary <string, ImmutableArray <Diagnostic> > > documentDiagnosticsToFix = relevantDocumentDiagnostics.ToImmutableDictionary(i => i.Key, i => i.Value.ToImmutableDictionary(j => j.Key, j => j.Value.ToImmutableArray(), StringComparer.OrdinalIgnoreCase)); ImmutableDictionary <ProjectId, ImmutableArray <Diagnostic> > projectDiagnosticsToFix = relevantProjectDiagnostics.ToImmutableDictionary(i => i.Key, i => i.Value.ToImmutableArray()); HashSet <string> equivalenceKeys = new HashSet <string>(); foreach (var diagnostic in relevantDocumentDiagnostics.Values.SelectMany(i => i.Values).SelectMany(i => i).Concat(relevantProjectDiagnostics.Values.SelectMany(i => i))) { foreach (var codeAction in await GetFixesAsync(solution, codeFixProvider, diagnostic, cancellationToken).ConfigureAwait(false)) { equivalenceKeys.Add(codeAction.EquivalenceKey); } } List <CodeFixEquivalenceGroup> groups = new List <CodeFixEquivalenceGroup>(); foreach (var equivalenceKey in equivalenceKeys) { groups.Add(new CodeFixEquivalenceGroup(equivalenceKey, solution, fixAllProvider, codeFixProvider, documentDiagnosticsToFix, projectDiagnosticsToFix)); } return(groups.ToImmutableArray()); }
private static void HandleCloseBracketToken(SyntaxTreeAnalysisContext context, SyntaxToken token) { if (token.IsMissing) { return; } // attribute brackets are handled separately if (token.Parent.IsKind(SyntaxKind.AttributeList)) { return; } bool firstInLine = token.IsFirstInLine(); bool precededBySpace = firstInLine || token.IsPrecededByWhitespace(); bool followedBySpace = token.IsFollowedByWhitespace(); bool lastInLine = token.IsLastInLine(); bool precedesSpecialCharacter; // Tests for this rule have a lot of exclusions which are supposed to be caught by other rules bool suppressFollowingSpaceError = true; if (!lastInLine) { SyntaxToken nextToken = token.GetNextToken(); switch (nextToken.Kind()) { case SyntaxKind.CloseBracketToken: case SyntaxKind.OpenParenToken: case SyntaxKind.CommaToken: case SyntaxKind.SemicolonToken: // TODO: "certain types of operator symbols" case SyntaxKind.DotToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.CloseParenToken: precedesSpecialCharacter = true; break; case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: precedesSpecialCharacter = true; suppressFollowingSpaceError = false; break; case SyntaxKind.GreaterThanToken: precedesSpecialCharacter = nextToken.Parent.IsKind(SyntaxKind.TypeArgumentList); break; case SyntaxKind.QuestionToken: precedesSpecialCharacter = nextToken.Parent.IsKind(SyntaxKind.ConditionalAccessExpression); break; case SyntaxKind.CloseBraceToken: precedesSpecialCharacter = nextToken.Parent is InterpolationSyntax; break; default: precedesSpecialCharacter = false; break; } } else { precedesSpecialCharacter = false; } if (!firstInLine && precededBySpace) { // Closing square bracket must{ not} be {preceded} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationPreceding, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "preceded")); } if (!lastInLine) { if (!precedesSpecialCharacter && !followedBySpace) { // Closing square bracket must{} be {followed} by a space. var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionInsert }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), string.Empty, "followed")); } else if (precedesSpecialCharacter && followedBySpace && !suppressFollowingSpaceError) { // Closing square brackets must {not} be {followed} by a space var properties = new Dictionary<string, string> { [OpenCloseSpacingCodeFixProvider.LocationKey] = OpenCloseSpacingCodeFixProvider.LocationFollowing, [OpenCloseSpacingCodeFixProvider.ActionKey] = OpenCloseSpacingCodeFixProvider.ActionRemove }; context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties.ToImmutableDictionary(), " not", "followed")); } } }
public NumberRangeExtractor(NumberOptions options = NumberOptions.None) : base(NumberExtractor.GetInstance(), OrdinalExtractor.GetInstance(), new BaseNumberParser(new SpanishNumberParserConfiguration()), options) { var regexes = new Dictionary <Regex, string>() { { // entre ...y ... new Regex(NumbersDefinitions.TwoNumberRangeRegex1, RegexOptions.Singleline), NumberRangeConstants.TWONUMBETWEEN }, { // más que ... monos que ... new Regex(NumbersDefinitions.TwoNumberRangeRegex2, RegexOptions.Singleline), NumberRangeConstants.TWONUM }, { // monos que ... más que ... new Regex(NumbersDefinitions.TwoNumberRangeRegex3, RegexOptions.Singleline), NumberRangeConstants.TWONUM }, { // de ... a ... new Regex(NumbersDefinitions.TwoNumberRangeRegex4, RegexOptions.Singleline), NumberRangeConstants.TWONUMTILL }, { // más/mayor que ... new Regex(NumbersDefinitions.OneNumberRangeMoreRegex1, RegexOptions.Singleline), NumberRangeConstants.MORE }, { // 30 and/or greater/higher new Regex(NumbersDefinitions.OneNumberRangeMoreRegex2, RegexOptions.Singleline), NumberRangeConstants.MORE }, { // less/smaller/lower than ... new Regex(NumbersDefinitions.OneNumberRangeLessRegex1, RegexOptions.Singleline), NumberRangeConstants.LESS }, { // 30 y/o mas/más/mayor/mayores new Regex(NumbersDefinitions.OneNumberRangeLessRegex2, RegexOptions.Singleline), NumberRangeConstants.LESS }, { // igual a ... new Regex(NumbersDefinitions.OneNumberRangeEqualRegex, RegexOptions.Singleline), NumberRangeConstants.EQUAL }, { // igual a 30 o más, más que 30 o igual ... new Regex(NumbersDefinitions.OneNumberRangeMoreSeparateRegex, RegexOptions.Singleline), NumberRangeConstants.MORE }, { // igual a 30 o menos, menos que 30 o igual ... new Regex(NumbersDefinitions.OneNumberRangeLessSeparateRegex, RegexOptions.Singleline), NumberRangeConstants.LESS }, }; Regexes = regexes.ToImmutableDictionary(); AmbiguousFractionConnectorsRegex = new Regex(NumbersDefinitions.AmbiguousFractionConnectorsRegex, RegexOptions.Singleline); }
internal void CreateSourceAssemblyForCompilation(PhpCompilation compilation) { if (compilation._lazyAssemblySymbol != null) return; // TODO: lock Debug.Assert(_lazyExplicitReferences.IsDefault); Debug.Assert(_lazyCorLibrary == null); Debug.Assert(_lazyPhpCorLibrary == null); // var externalRefs = CorLibReferences.SelectMany(reference => compilation.Options.MetadataReferenceResolver.ResolveReference(reference, null, new MetadataReferenceProperties())) .Concat(compilation.ExternalReferences).AsImmutable(); var assemblies = new List<AssemblySymbol>(externalRefs.Length); var referencesMap = new Dictionary<MetadataReference, IAssemblySymbol>(); var metadataMap = new Dictionary<IAssemblySymbol, MetadataReference>(); var assembliesMap = new Dictionary<AssemblyIdentity, PEAssemblySymbol>(); var refmodules = new List<PEModuleSymbol>(); foreach (PortableExecutableReference pe in externalRefs) { var symbol = PEAssemblySymbol.Create(pe); if (symbol != null) { assemblies.Add(symbol); referencesMap[pe] = symbol; metadataMap[symbol] = pe; if (_lazyCorLibrary == null && symbol.IsCorLibrary) _lazyCorLibrary = symbol; if (_lazyPhpCorLibrary == null && symbol.IsPchpCorLibrary) _lazyPhpCorLibrary = symbol; // cache bound assembly symbol _assembliesMap.Add(symbol.Identity, symbol); // list of modules to initialize later refmodules.AddRange(symbol.Modules.Cast<PEModuleSymbol>()); } else { throw new Exception($"symbol '{pe.FilePath}' could not be created!"); } } // _lazyExplicitReferences = externalRefs; _lazyImplicitReferences = ImmutableArray<MetadataReference>.Empty; _metadataMap = metadataMap.ToImmutableDictionary(); _referencesMap = referencesMap.ToImmutableDictionary(); // var assembly = new SourceAssemblySymbol(compilation, compilation.Options.ModuleName, compilation.Options.ModuleName); assembly.SetCorLibrary(_lazyCorLibrary); compilation._lazyAssemblySymbol = assembly; assembly.SourceModule.SetReferences(new ModuleReferences<AssemblySymbol>( assemblies.Select(x => x.Identity).AsImmutable(), assemblies.AsImmutable(), ImmutableArray<UnifiedAssembly<AssemblySymbol>>.Empty), assembly); assemblies.ForEach(ass => ass.SetCorLibrary(_lazyCorLibrary)); // recursively initialize references of referenced modules SetReferencesOfReferencedModules(compilation.Options.MetadataReferenceResolver, refmodules); // set cor types for this compilation if (_lazyPhpCorLibrary == null) throw new DllNotFoundException("Peachpie.Runtime not found"); if (_lazyCorLibrary == null) throw new DllNotFoundException("A corlib not found"); compilation.CoreTypes.Update(_lazyPhpCorLibrary); compilation.CoreTypes.Update(_lazyCorLibrary); }