/// <summary> /// Called to test a C# codefix when applied on the inputted string as a source /// </summary> /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="newSource">A class in the form of a string after the CodeFix was applied to it</param> /// <param name="codeFixIndex">Index determining which codefix to apply if there are multiple</param> /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied</param> /// <param name="formatBeforeCompare">Format the code before comparing, bot the old source and the new.</param> /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param> /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param> protected async Task VerifyCSharpFixAsync(string oldSource, string newSource, int? codeFixIndex = null, bool allowNewCompilerDiagnostics = false, bool formatBeforeCompare = true, CodeFixProvider codeFixProvider = null, LanguageVersion languageVersionCSharp = LanguageVersion.CSharp6) { if (formatBeforeCompare) { oldSource = await FormatSourceAsync(LanguageNames.CSharp, oldSource, languageVersionCSharp).ConfigureAwait(true); newSource = await FormatSourceAsync(LanguageNames.CSharp, newSource, languageVersionCSharp).ConfigureAwait(true); } codeFixProvider = codeFixProvider ?? GetCodeFixProvider(); var diagnosticAnalyzer = GetDiagnosticAnalyzer(); if (diagnosticAnalyzer != null) await VerifyFixAsync(LanguageNames.CSharp, diagnosticAnalyzer, codeFixProvider, oldSource, newSource, codeFixIndex, allowNewCompilerDiagnostics, languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14).ConfigureAwait(true); else await VerifyFixAsync(LanguageNames.CSharp, codeFixProvider.FixableDiagnosticIds, codeFixProvider, oldSource, newSource, codeFixIndex, allowNewCompilerDiagnostics, languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14).ConfigureAwait(true); }
public CSharpProject(string projectFile) { if (!File.Exists(projectFile)) throw new Exception(string.Format("project file not found \"{0}\"", projectFile)); WriteLine(1, "compile project \"{0}\"", projectFile); _projectFile = projectFile; _projectDirectory = Path.GetDirectoryName(projectFile); _projectDocument = XDocument.Load(projectFile); _frameworkDirectory = GetValue("FrameworkDirectory"); WriteLine(2, " framework directory : \"{0}\"", _frameworkDirectory); _assemblyName = GetValue("AssemblyName"); WriteLine(2, " assembly name : \"{0}\"", _assemblyName); string outputDirectory = PathCombine(_projectDirectory, GetValue("OutputDirectory")); WriteLine(2, " output directory : \"{0}\"", outputDirectory); _languageVersion = GetLanguageVersion(GetValue("LanguageVersion")); WriteLine(2, " language version : \"{0}\"", _languageVersion); _outputKind = GetOutputKind(GetValue("OutputKind")); WriteLine(2, " output kind : \"{0}\"", _outputKind); _optimizationLevel = GetOptimizationLevel(GetValue("OptimizationLevel")); WriteLine(2, " optimization level : \"{0}\"", _optimizationLevel); _platform = GetPlatform(GetValue("Platform")); WriteLine(2, " platform : \"{0}\"", _platform); _generalDiagnosticOption = ReportDiagnostic.Default; WriteLine(2, " general diagnostic option : \"{0}\"", _generalDiagnosticOption); _warningLevel = 4; WriteLine(2, " warning level : \"{0}\"", _warningLevel); _outputPath = PathCombine(outputDirectory, GetValue("OutputPath")); WriteLine(2, " output path : \"{0}\"", _outputPath); _pdbPath = PathCombine(outputDirectory, GetValue("PdbPath")); WriteLine(2, " pdb path : \"{0}\"", _pdbPath); _win32ResourceFile = PathCombine(_projectDirectory, GetValue("Win32ResourceFile")); WriteLine(2, " win32 resource file : \"{0}\"", _win32ResourceFile); _preprocessorSymbols = GetPreprocessorSymbols(); _sourceFiles = GetSources(); _resourceFiles = GetResourceFiles(); _assembliesFiles = GetAssembliesFiles(); }
public ParseOptions Copy( CompatibilityMode? compatibility = null, LanguageVersion? languageVersion = null, IEnumerable<string> preprocessorSymbols = null, bool? suppressDocumentationCommentParse = null, SourceCodeKind? kind = SourceCodeKind.Regular) { return new ParseOptions( compatibility ?? this.Compatibility, languageVersion ?? this.LanguageVersion, preprocessorSymbols ?? this.PreprocessorSymbols.AsEnumerable(), suppressDocumentationCommentParse ?? this.SuppressDocumentationCommentParse, kind ?? this.Kind ); }
public static void Reset(bool full) { impl_details_class = null; helper_classes = null; if (!full) return; EntryPoint = null; Checked = false; Unsafe = false; StdLib = true; StrongNameKeyFile = null; StrongNameKeyContainer = null; StrongNameDelaySign = false; MainClass = null; Target = Target.Exe; TargetExt = ".exe"; Platform = Platform.AnyCPU; Version = LanguageVersion.Default; Documentation = null; impl_details_class = null; helper_classes = null; #if NET_4_0 MetadataCompatibilityVersion = MetadataVersion.v4; #else MetadataCompatibilityVersion = MetadataVersion.v2; #endif // // Setup default defines // AllDefines = new List<string> (); AddConditional ("__MonoCS__"); }
/// <summary> /// Given classes in the form of strings, their language, and an IDiagnosticAnlayzer to apply to it, return the diagnostics found in the string after converting it to a document. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the soruce classes are in</param> /// <param name="analyzer">The analyzer to be run on the sources</param> /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param> /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param> /// <returns>An IEnumerable of Diagnostics that surfaced in teh source code, sorted by Location</returns> private static async Task<Diagnostic[]> GetSortedDiagnosticsAsync(string[] sources, string language, DiagnosticAnalyzer analyzer, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB) => await GetSortedDiagnosticsFromDocumentsAsync(analyzer, GetDocuments(sources, language, languageVersionCSharp, languageVersionVB)).ConfigureAwait(true);
/// <summary> /// Given an array of strings as soruces and a language, turn them into a project and return the documents and spans of it. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param> /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param> /// <returns>A Tuple containing the Documents produced from the sources and thier TextSpans if relevant</returns> public static Document[] GetDocuments(string[] sources, string language, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB) { if (language != LanguageNames.CSharp && language != LanguageNames.VisualBasic) throw new ArgumentException("Unsupported Language"); for (int i = 0; i < sources.Length; i++) { var fileName = language == LanguageNames.CSharp ? nameof(Test) + i + ".cs" : nameof(Test) + i + ".vb"; } var project = CreateProject(sources, language, languageVersionCSharp, languageVersionVB); var documents = project.Documents.ToArray(); if (sources.Length != documents.Length) { throw new SystemException("Amount of sources did not match amount of Documents created"); } return documents; }
private async static Task VerifyFixAllAsync(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string oldSource, string newSource, bool allowNewCompilerDiagnostics, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB, string equivalenceKey = null) { var document = CreateDocument(oldSource, language, languageVersionCSharp, languageVersionVB); var compilerDiagnostics = await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true); var getDocumentDiagnosticsAsync = analyzer != null ? (Func<Document, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>>)(async (doc, ids, ct) => await GetSortedDiagnosticsFromDocumentsAsync(analyzer, new[] { doc }).ConfigureAwait(true)) : (async (doc, ids, ct) => { var compilerDiags = await GetCompilerDiagnosticsAsync(doc).ConfigureAwait(true); return compilerDiags.Where(d => codeFixProvider.FixableDiagnosticIds.Contains(d.Id)); }); Func<Project, bool, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getProjectDiagnosticsAsync = async (proj, b, ids, ct) => { var theDocs = proj.Documents; var diags = await Task.WhenAll(theDocs.Select(d => getDocumentDiagnosticsAsync?.Invoke(d, ids, ct))).ConfigureAwait(true); return diags.SelectMany(d => d); }; var fixAllProvider = codeFixProvider.GetFixAllProvider(); var fixAllDiagnosticProvider = new FixAllDiagnosticProvider(codeFixProvider.FixableDiagnosticIds.ToImmutableHashSet(), getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync); if (equivalenceKey == null) equivalenceKey = codeFixProvider.GetType().Name; var fixAllContext = new FixAllContext(document, codeFixProvider, FixAllScope.Document, equivalenceKey, codeFixProvider.FixableDiagnosticIds, fixAllDiagnosticProvider, CancellationToken.None); var action = await fixAllProvider.GetFixAsync(fixAllContext).ConfigureAwait(true); if (action == null) throw new Exception("No action supplied for the code fix."); document = await ApplyFixAsync(document, action).ConfigureAwait(true); //check if applying the code fix introduced any new compiler diagnostics var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true)); if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = document.WithSyntaxRoot(Formatter.Format(await document.GetSyntaxRootAsync().ConfigureAwait(true), Formatter.Annotation, document.Project.Solution.Workspace)); newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true)); Assert.True(false, $"Fix introduced new compiler diagnostics:\r\n{string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString()))}\r\n\r\nNew document:\r\n{(await document.GetSyntaxRootAsync().ConfigureAwait(true)).ToFullString()}\r\n"); } var actual = await GetStringFromDocumentAsync(document).ConfigureAwait(true); Assert.Equal(newSource, actual); }
public static void Reset (bool full) { if (full) root = null; type_container_resolve_order = new ArrayList (); EntryPoint = null; Checked = false; Unsafe = false; StdLib = true; StrongNameKeyFile = null; StrongNameKeyContainer = null; StrongNameDelaySign = false; MainClass = null; Target = Target.Exe; TargetExt = ".exe"; #if GMCS_SOURCE Platform = Platform.AnyCPU; #endif Version = LanguageVersion.Default; Documentation = null; impl_details_class = null; helper_classes = null; #if GMCS_SOURCE MetadataCompatibilityVersion = MetadataVersion.v2; #else MetadataCompatibilityVersion = MetadataVersion.v1; #endif // // Setup default defines // AllDefines = new ArrayList (); AddConditional ("__MonoCS__"); }
// // This parses the -arg and /arg options to the compiler, even if the strings // in the following text use "/arg" on the strings. // bool CSCParseOption(string option, ref string [] args) { int idx = option.IndexOf(':'); string arg, value; if (idx == -1) { arg = option; value = ""; } else { arg = option.Substring(0, idx); value = option.Substring(idx + 1); } switch (arg.ToLower(CultureInfo.InvariantCulture)) { case "/nologo": return(true); case "/t": case "/target": switch (value) { case "exe": Target = Target.Exe; break; case "winexe": Target = Target.WinExe; break; case "library": Target = Target.Library; TargetExt = ".dll"; break; case "module": Target = Target.Module; TargetExt = ".netmodule"; break; default: return(false); } return(true); case "/out": if (value.Length == 0) { Usage(); Environment.Exit(1); } OutputFile = value; return(true); case "/o": case "/o+": case "/optimize": case "/optimize+": Optimize = true; return(true); case "/o-": case "/optimize-": Optimize = false; return(true); case "/incremental": case "/incremental+": case "/incremental-": // nothing. return(true); case "/d": case "/define": { if (value.Length == 0) { Usage(); Environment.Exit(1); } foreach (string d in value.Split(argument_value_separator)) { if (defines.Length != 0) { defines.Append(";"); } defines.Append(d); } return(true); } case "/bugreport": // // We should collect data, runtime, etc and store in the file specified // return(true); case "/linkres": case "/linkresource": case "/res": case "/resource": bool embeded = arg [1] == 'r' || arg [1] == 'R'; string [] s = value.Split(argument_value_separator); switch (s.Length) { case 1: if (s [0].Length == 0) { goto default; } embedded_resources [s [0]] = Path.GetFileName(s [0]); break; case 2: embedded_resources [s [0]] = s [1]; break; case 3: Console.WriteLine("Does not support this method yet: {0}", arg); Environment.Exit(1); break; default: Console.WriteLine("Wrong number of arguments for option `{0}'", option); Environment.Exit(1); break; } return(true); case "/recurse": Console.WriteLine("/recurse not supported"); Environment.Exit(1); return(true); case "/r": case "/reference": { if (value.Length == 0) { Console.WriteLine("-reference requires an argument"); Environment.Exit(1); } string [] refs = value.Split(argument_value_separator); foreach (string r in refs) { string val = r; int index = val.IndexOf('='); if (index > -1) { reference_aliases.Add(r); continue; } if (val.Length != 0) { references.Add(val); } } return(true); } case "/main": case "/m": case "/addmodule": case "/win32res": case "/doc": if (showWarnings) { Console.WriteLine("{0} = not supported", arg); } return(true); case "/lib": { libs.Add(value); return(true); } case "/win32icon": { win32IconFile = value; return(true); } case "/debug-": want_debugging_support = false; return(true); case "/debug": case "/debug+": want_debugging_support = true; return(true); case "/checked": case "/checked+": Checked = true; return(true); case "/checked-": Checked = false; return(true); case "/clscheck": case "/clscheck+": return(true); case "/clscheck-": VerifyClsCompliance = false; return(true); case "/unsafe": case "/unsafe+": Unsafe = true; return(true); case "/unsafe-": Unsafe = false; return(true); case "/warnaserror": case "/warnaserror+": if (value.Length == 0) { WarningsAreErrors = true; } else { foreach (string wid in value.Split(argument_value_separator)) { warning_as_error.Add(wid); } } return(true); case "/-runtime": // Console.WriteLine ("Warning ignoring /runtime:v4"); return(true); case "/warnaserror-": if (value.Length == 0) { WarningsAreErrors = false; } else { foreach (string wid in value.Split(argument_value_separator)) { warning_as_error.Remove(wid); } } return(true); case "/warn": WarningLevel = Int32.Parse(value); return(true); case "/nowarn": { string [] warns; if (value.Length == 0) { Console.WriteLine("/nowarn requires an argument"); Environment.Exit(1); } warns = value.Split(argument_value_separator); foreach (string wc in warns) { try { if (wc.Trim().Length == 0) { continue; } int warn = Int32.Parse(wc); if (warn < 1) { throw new ArgumentOutOfRangeException("warn"); } ignore_warning.Add(warn); } catch { Console.WriteLine(String.Format("`{0}' is not a valid warning number", wc)); Environment.Exit(1); } } return(true); } case "/noconfig": load_default_config = false; return(true); case "/nostdlib": case "/nostdlib+": StdLib = false; return(true); case "/nostdlib-": StdLib = true; return(true); case "/fullpaths": return(true); case "/keyfile": if (value == String.Empty) { Console.WriteLine("{0} requires an argument", arg); Environment.Exit(1); } StrongNameKeyFile = value; return(true); case "/keycontainer": if (value == String.Empty) { Console.WriteLine("{0} requires an argument", arg); Environment.Exit(1); } StrongNameKeyContainer = value; return(true); case "/delaysign+": case "/delaysign": StrongNameDelaySign = true; return(true); case "/delaysign-": StrongNameDelaySign = false; return(true); case "/langversion": switch (value.ToLower(CultureInfo.InvariantCulture)) { case "iso-1": Version = LanguageVersion.ISO_1; return(true); case "default": Version = LanguageVersion.Default; return(true); case "iso-2": Version = LanguageVersion.ISO_2; return(true); case "future": Version = LanguageVersion.Future; return(true); } Console.WriteLine("Invalid option `{0}' for /langversion. It must be either `ISO-1', `ISO-2' or `Default'", value); Environment.Exit(1); return(true); case "/codepage": CodePage = value; return(true); } Console.WriteLine("Failing with : {0}", arg); return(false); }
/// <summary> /// Given classes in the form of strings, their language, and an IDiagnosticAnlayzer to apply to it, return the diagnostics found in the string after converting it to a document. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the soruce classes are in</param> /// <param name="analyzer">The analyzer to be run on the sources</param> /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param> /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param> /// <returns>An IEnumerable of Diagnostics that surfaced in teh source code, sorted by Location</returns> private static async Task <Diagnostic[]> GetSortedDiagnosticsAsync(string[] sources, string language, DiagnosticAnalyzer analyzer, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB) => await GetSortedDiagnosticsFromDocumentsAsync(analyzer, GetDocuments(sources, language, languageVersionCSharp, languageVersionVB)).ConfigureAwait(true);
public static async Task <string> FormatSourceAsync(string language, string source, LanguageVersion languageVersionCSharp = LanguageVersion.CSharp6, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14) { var document = CreateDocument(source, language, languageVersionCSharp, languageVersionVB); var newDoc = await Formatter.FormatAsync(document).ConfigureAwait(true); return((await newDoc.GetSyntaxRootAsync().ConfigureAwait(true)).ToFullString()); }
/// <summary> /// Create a Document from a string through creating a project that contains it. /// </summary> /// <param name="source">Classes in the form of a string</param> /// <param name="language">The language the source code is in</param> /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param> /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param> /// <returns>A Document created from the source string</returns> public static Document CreateDocument(string source, string language, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB) => CreateProject(new[] { source }, language, languageVersionCSharp, languageVersionVB).Documents.First();
public CompilerSettings () { StdLib = true; Target = Target.Exe; TargetExt = ".exe"; Platform = Platform.AnyCPU; Version = LanguageVersion.Default; VerifyClsCompliance = true; Optimize = true; Encoding = Encoding.Default; LoadDefaultReferences = true; StdLibRuntimeVersion = RuntimeVersion.v4; AssemblyReferences = new List<string> (); AssemblyReferencesAliases = new List<Tuple<string, string>> (); Modules = new List<string> (); ReferencesLookupPaths = new List<string> (); }
//warnaserror[+|-] //warnaserror[+|-]:<warn list> //unsafe[+|-] //warn:<n> //nowarn:<warn list> public ParseOptions( CompatibilityMode compatibility = CompatibilityMode.None, LanguageVersion languageVersion = CSharp.LanguageVersion.CSharp4, IEnumerable<string> preprocessorSymbols = null, bool suppressDocumentationCommentParse = false, SourceCodeKind kind = SourceCodeKind.Regular) { if (!compatibility.IsValid()) { throw new ArgumentOutOfRangeException("compatibility"); } if (!languageVersion.IsValid()) { throw new ArgumentOutOfRangeException("languageVersion"); } if (!kind.IsValid()) { throw new ArgumentOutOfRangeException("kind"); } this.Compatibility = compatibility; this.LanguageVersion = languageVersion; this.PreprocessorSymbols = preprocessorSymbols.AsReadOnlyOrEmpty(); this.SuppressDocumentationCommentParse = suppressDocumentationCommentParse; this.Kind = kind; }
internal CSharpRequiredLanguageVersion(LanguageVersion version) { Version = (version == LanguageVersion.Preview.MapSpecifiedToEffectiveVersion()) ? LanguageVersion.Preview : version; }
public static void Reset (bool full) { if (!full) return; Checked = false; Unsafe = false; StdLib = true; StrongNameKeyFile = null; StrongNameKeyContainer = null; StrongNameDelaySign = false; MainClass = null; OutputFile = null; Target = Target.Exe; SdkVersion = SdkVersion.v2; TargetExt = ".exe"; Platform = Platform.AnyCPU; Version = LanguageVersion.Default; VerifyClsCompliance = true; Optimize = true; Encoding = Encoding.Default; Documentation = null; GenerateDebugInfo = false; ParseOnly = false; TokenizeOnly = false; Win32IconFile = null; Win32ResourceFile = null; Resources = null; LoadDefaultReferences = true; AssemblyReferences = new List<string> (); AssemblyReferencesAliases = new List<Tuple<string, string>> (); Modules = new List<string> (); ReferencesLookupPaths = new List<string> (); StdLibRuntimeVersion = RuntimeVersion.v2; // // Setup default defines // AllDefines = new List<string> (); AddConditional ("__MonoCS__"); }
internal static bool DisallowInferredTupleElementNames(this LanguageVersion self) { return(self < MessageID.IDS_FeatureInferredTupleNames.RequiredVersion()); }
private static void TupleContextNoSystemRuntime( string source, string methodName, string expression, string expectedIL, LanguageVersion languageVersion = LanguageVersion.CSharp7 ) { var comp = CreateCompilationWithMscorlib40( source, parseOptions: TestOptions.Regular.WithLanguageVersion(languageVersion), references: new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll ); using (var systemRuntime = SystemRuntimeFacadeRef.ToModuleInstance()) { WithRuntimeInstance( comp, new[] { MscorlibRef, ValueTupleRef }, runtime => { ImmutableArray <MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState( runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken ); string errorMessage; CompilationTestData testData; int retryCount = 0; var compileResult = ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.Select(m => m.MetadataBlock).ToImmutableArray(), expression, ImmutableArray <Alias> .Empty, (b, u) => EvaluationContext.CreateMethodContext( b.ToCompilation( default(Guid), MakeAssemblyReferencesKind.AllAssemblies ), symReader, moduleVersionId, methodToken, methodVersion: 1, ilOffset: 0, localSignatureToken: localSignatureToken ), (AssemblyIdentity assemblyIdentity, out uint uSize) => { retryCount++; Assert.Equal("System.Runtime", assemblyIdentity.Name); var block = systemRuntime.MetadataBlock; uSize = (uint)block.Size; return(block.Pointer); }, errorMessage: out errorMessage, testData: out testData ); Assert.Equal(1, retryCount); testData.GetMethodData("<>x.<>m0").VerifyIL(expectedIL); } ); } }
public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file) { this.file = file; current_namespace = file.NamespaceContainer; this.module = current_namespace.Module; this.compiler = module.Compiler; this.settings = compiler.Settings; lang_version = settings.Version; doc_support = settings.Documentation != null; current_class = current_namespace.SlaveDeclSpace; current_container = current_class.PartialContainer; // == RootContest.ToplevelTypes oob_stack.Clear (); lexer = new Tokenizer (reader, file, compiler); use_global_stacks = true; }
private static CSDiagnosticInfo GetDisabledFeatureDiagnosticInfo(MessageID feature, LanguageVersion availableVersion) { string?requiredFeature = feature.RequiredFeature(); if (requiredFeature != null) { return(new CSDiagnosticInfo(ErrorCode.ERR_FeatureIsExperimental, feature.Localize(), requiredFeature)); } LanguageVersion requiredVersion = feature.RequiredVersion(); return(requiredVersion == LanguageVersion.Preview.MapSpecifiedToEffectiveVersion() ? new CSDiagnosticInfo(ErrorCode.ERR_FeatureInPreview, feature.Localize()) : new CSDiagnosticInfo(availableVersion.GetErrorCode(), feature.Localize(), new CSharpRequiredLanguageVersion(requiredVersion))); }
/// <summary> /// Called to test a C# codefix when it should not had been registered /// </summary> /// <param name="source">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param> /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param> protected async Task VerifyCSharpHasNoFixAsync(string source, CodeFixProvider codeFixProvider = null, LanguageVersion languageVersionCSharp = LanguageVersion.CSharp6) => await VerifyHasNoFixAsync(LanguageNames.CSharp, GetDiagnosticAnalyzer(), codeFixProvider ?? GetCodeFixProvider(), source, languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14).ConfigureAwait(true);
public void When_MapPropertyWithImplicitConversionFound_Should_UseItToMapToSourceProperty(string source, string expectedResult, LanguageVersion languageVersion) { // Arrange source = source.Trim(); // Act var(compilation, diagnostics) = CSharpGenerator.GetOutputCompilation(source, analyzerConfigOptions: DefaultAnalyzerOptions, languageVersion: languageVersion); // Assert diagnostics.ShouldBeSuccessful(); compilation.SyntaxTrees.Last().ShouldContainPartialSource(expectedResult); }
private async Task VerifyAsync(string codeWithMarker, string expectedResult, LanguageVersion langVersion = LanguageVersion.VisualBasic14) { var textSpans = (IList<TextSpan>)new List<TextSpan>(); MarkupTestFile.GetSpans(codeWithMarker, out var codeWithoutMarker, out textSpans); var document = CreateDocument(codeWithoutMarker, LanguageNames.VisualBasic, langVersion); var codeCleanups = CodeCleaner.GetDefaultProviders(document).Where(p => p.Name == PredefinedCodeCleanupProviderNames.RemoveUnnecessaryLineContinuation || p.Name == PredefinedCodeCleanupProviderNames.Format); var cleanDocument = await CodeCleaner.CleanupAsync(document, textSpans[0], codeCleanups); Assert.Equal(expectedResult, (await cleanDocument.GetSyntaxRootAsync()).ToFullString()); }
/// <summary> /// Check that the pattern type is valid for the operand. Return true if an error was reported. /// </summary> private bool CheckValidPatternType( CSharpSyntaxNode typeSyntax, TypeSymbol operandType, TypeSymbol patternType, bool patternTypeWasInSource, bool isVar, DiagnosticBag diagnostics) { Debug.Assert((object)operandType != null); Debug.Assert((object)patternType != null); if (operandType.IsErrorType() || patternType.IsErrorType()) { return(false); } else if (patternType.IsNullableType() && !isVar && patternTypeWasInSource) { // It is an error to use pattern-matching with a nullable type, because you'll never get null. Use the underlying type. Error(diagnostics, ErrorCode.ERR_PatternNullableType, typeSyntax, patternType, patternType.GetNullableUnderlyingType()); return(true); } else if (patternType.IsStatic) { Error(diagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, patternType); return(true); } else if (!isVar) { if (patternType.IsDynamic()) { Error(diagnostics, ErrorCode.ERR_PatternDynamicType, typeSyntax); return(true); } HashSet <DiagnosticInfo> useSiteDiagnostics = null; var matchPossible = ExpressionOfTypeMatchesPatternType(Conversions, operandType, patternType, ref useSiteDiagnostics, out Conversion conversion, operandConstantValue: null, operandCouldBeNull: true); diagnostics.Add(typeSyntax, useSiteDiagnostics); if (matchPossible != false) { if (!conversion.Exists && (operandType.ContainsTypeParameter() || patternType.ContainsTypeParameter())) { // permit pattern-matching when one of the types is an open type in C# 7.1. LanguageVersion requiredVersion = MessageID.IDS_FeatureGenericPatternMatching.RequiredVersion(); if (requiredVersion > Compilation.LanguageVersion) { Error(diagnostics, ErrorCode.ERR_PatternWrongGenericTypeInVersion, typeSyntax, operandType, patternType, Compilation.LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); return(true); } } } else { Error(diagnostics, ErrorCode.ERR_PatternWrongType, typeSyntax, operandType, patternType); return(true); } } return(false); }
/// <summary> /// Create a project using the inputted strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param> /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param> /// <returns>A Project created out of the Douments created from the source strings</returns> public static Project CreateProject(string[] sources, string language, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB) { var fileNamePrefix = DefaultFilePathPrefix; string fileExt; ParseOptions parseOptions; if (language == LanguageNames.CSharp) { fileExt = CSharpDefaultFileExt; parseOptions = new CSharpParseOptions(languageVersionCSharp); } else { fileExt = VisualBasicDefaultExt; parseOptions = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions(languageVersionVB); } var projectId = ProjectId.CreateNewId(debugName: TestProjectName); #pragma warning disable CC0022 var workspace = new AdhocWorkspace(); #pragma warning restore CC0022 var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), TestProjectName, TestProjectName, language, parseOptions: parseOptions, metadataReferences: ImmutableList.Create( CorlibReference, SystemCoreReference, RegexReference, CSharpSymbolsReference, CodeAnalysisReference, JsonNetReference)); workspace.AddProject(projectInfo); var count = 0; foreach (var source in sources) { var newFileName = fileNamePrefix + count + "." + fileExt; workspace.AddDocument(projectId, newFileName, SourceText.From(source)); count++; } var project = workspace.CurrentSolution.GetProject(projectId); var newCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(diagOptions); var newSolution = workspace.CurrentSolution.WithProjectCompilationOptions(projectId, newCompilationOptions); var newProject = newSolution.GetProject(projectId); return newProject; }
public MySyntaxFactory(LanguageVersion languageVersion) { LanguageVersion = languageVersion; }
public static void Reset (bool full) { if (!full) return; Checked = false; Unsafe = false; StdLib = true; StrongNameKeyFile = null; StrongNameKeyContainer = null; StrongNameDelaySign = false; MainClass = null; Target = Target.Exe; TargetExt = ".exe"; Platform = Platform.AnyCPU; Version = LanguageVersion.Default; VerifyClsCompliance = true; Optimize = true; Documentation = null; GenerateDebugInfo = false; Win32IconFile = null; Win32ResourceFile = null; Resources = null; LoadDefaultReferences = true; AssemblyReferences = new List<string> (); AssemblyReferencesAliases = new List<Tuple<string, string>> (); Modules = new List<string> (); ReferencesLookupPaths = new List<string> (); #if NET_4_0 MetadataCompatibilityVersion = MetadataVersion.v4; #else MetadataCompatibilityVersion = MetadataVersion.v2; #endif // // Setup default defines // AllDefines = new List<string> (); AddConditional ("__MonoCS__"); }
private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, ExpressionBodyPreference.WhenPossible } } }.RunAsync(); }
public CompilerSettings () { StdLib = true; Target = Target.Exe; TargetExt = ".exe"; Platform = Platform.AnyCPU; Version = LanguageVersion.Default; VerifyClsCompliance = true; Encoding = Encoding.UTF8; LoadDefaultReferences = true; StdLibRuntimeVersion = RuntimeVersion.v4; WarningLevel = 4; // Default to 1 or mdb files would be platform speficic TabSize = 1; AssemblyReferences = new List<string> (); AssemblyReferencesAliases = new List<Tuple<string, string>> (); Modules = new List<string> (); ReferencesLookupPaths = new List<string> (); conditional_symbols = new List<string> (); // // Add default mcs define // conditional_symbols.Add ("__MonoCS__"); source_files = new List<SourceFile> (); }
public ResultParserDeserializeMethodGenerator(LanguageVersion languageVersion) { _languageVersion = languageVersion; }
public static Script <TScript> WithLanguageVersion <TScript>(this Script <TScript> script, LanguageVersion version) { var desiredValue = new object[] { version }; var compilerField = _compilerField = _compilerField ?? typeof(Script <>).GetField("Compiler", BindingFlags.NonPublic | BindingFlags.Instance); var compiler = compilerField.GetValue(script); var optionsField = _optionsField = _optionsField ?? compiler.GetType().GetField("DefaultParseOptions", BindingFlags.NonPublic | BindingFlags.Static); var options = optionsField.GetValue(compiler); var langVersionSetter = _langVersionSetter = _langVersionSetter ?? typeof(CSharpParseOptions).GetMethod($"set_{ nameof(CSharpParseOptions.LanguageVersion)}", BindingFlags.NonPublic | BindingFlags.Instance); langVersionSetter.Invoke(options, desiredValue); var specifiedLangVerisonSetter = _specificLangVersionSetter = _specificLangVersionSetter ?? typeof(CSharpParseOptions).GetMethod($"set_{nameof(CSharpParseOptions.SpecifiedLanguageVersion)}", BindingFlags.NonPublic | BindingFlags.Instance); specifiedLangVerisonSetter.Invoke(options, desiredValue); return(script); }
private async Task VerifyAbsenceAsync(string code, LanguageVersion languageVersion = LanguageVersion.Default) { await VerifyItemIsAbsentAsync(GetMarkup(code, languageVersion), CompletionDisplayTextAwait); await VerifyItemIsAbsentAsync(GetMarkup(code, languageVersion), CompletionDisplayTextAwaitAndConfigureAwait); }
public static bool TryParse(string?version, out LanguageVersion result) { if (version == null) { result = LanguageVersion.Default; return(true); } switch (CaseInsensitiveComparison.ToLower(version)) { case "default": result = LanguageVersion.Default; return(true); case "latest": result = LanguageVersion.Latest; return(true); case "latestmajor": result = LanguageVersion.LatestMajor; return(true); case "preview": result = LanguageVersion.Preview; return(true); case "1": case "1.0": case "iso-1": result = LanguageVersion.CSharp1; return(true); case "2": case "2.0": case "iso-2": result = LanguageVersion.CSharp2; return(true); case "3": case "3.0": result = LanguageVersion.CSharp3; return(true); case "4": case "4.0": result = LanguageVersion.CSharp4; return(true); case "5": case "5.0": result = LanguageVersion.CSharp5; return(true); case "6": case "6.0": result = LanguageVersion.CSharp6; return(true); case "7": case "7.0": result = LanguageVersion.CSharp7; return(true); case "7.1": result = LanguageVersion.CSharp7_1; return(true); case "7.2": result = LanguageVersion.CSharp7_2; return(true); case "7.3": result = LanguageVersion.CSharp7_3; return(true); case "8": case "8.0": result = LanguageVersion.CSharp8; return(true); case "9": case "9.0": result = LanguageVersion.CSharp9; return(true); default: result = LanguageVersion.Default; return(false); } }
public static void RegisterCompilationStartAction(this AnalysisContext context, LanguageVersion greaterOrEqualThanLanguageVersion, Action <CompilationStartAnalysisContext> registrationAction) => context.RegisterCompilationStartAction(compilationContext => compilationContext.RunIfCSharpVersionOrGreater(greaterOrEqualThanLanguageVersion, () => registrationAction?.Invoke(compilationContext)));
internal static bool AllowNonTrailingNamedArguments(this LanguageVersion self) { return(self >= MessageID.IDS_FeatureNonTrailingNamedArguments.RequiredVersion()); }
public static void RegisterSymbolAction(this AnalysisContext context, LanguageVersion greaterOrEqualThanLanguageVersion, Action <SymbolAnalysisContext> registrationAction, params SymbolKind[] symbolKinds) => context.RegisterSymbolAction(compilationContext => compilationContext.RunIfCSharpVersionOrGreater(greaterOrEqualThanLanguageVersion, () => registrationAction?.Invoke(compilationContext)), symbolKinds);
public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, Report report) { this.file = file; current_container = current_namespace = file; this.module = file.Module; this.compiler = file.Compiler; this.settings = compiler.Settings; this.report = report; lang_version = settings.Version; yacc_verbose_flag = settings.VerboseParserFlag; doc_support = settings.DocumentationFile != null; oob_stack.Clear (); lexer = new Tokenizer (reader, file); #if FULL_AST lbag = new LocationsBag (); #else lbag = null; #endif use_global_stacks = true; }
#pragma warning restore RS1012 private static void RunIfCSharpVersionOrGreater(this Compilation compilation, Action action, LanguageVersion greaterOrEqualThanLanguageVersion) => (compilation as CSharpCompilation)?.LanguageVersion.RunIfCSharpVersionGreater(action, greaterOrEqualThanLanguageVersion);
protected async Task VerifyCSharpFixAllAsync(string oldSource, string newSource, bool allowNewCompilerDiagnostics = false, bool formatBeforeCompare = true, CodeFixProvider codeFixProvider = null, LanguageVersion languageVersionCSharp = LanguageVersion.CSharp6, string equivalenceKey = null) { if (formatBeforeCompare) { oldSource = await FormatSourceAsync(LanguageNames.CSharp, oldSource, languageVersionCSharp).ConfigureAwait(true); newSource = await FormatSourceAsync(LanguageNames.CSharp, newSource, languageVersionCSharp).ConfigureAwait(true); } codeFixProvider = codeFixProvider ?? GetCodeFixProvider(); await VerifyFixAllAsync(LanguageNames.CSharp, GetDiagnosticAnalyzer(), codeFixProvider, oldSource, newSource, allowNewCompilerDiagnostics, languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14, equivalenceKey).ConfigureAwait(true); }
private static void RunIfCSharpVersionOrGreater(this SymbolAnalysisContext context, LanguageVersion greaterOrEqualThanLanguageVersion, Action action) => context.Compilation.RunIfCSharpVersionOrGreater(action, greaterOrEqualThanLanguageVersion);
private async static Task VerifyFixAllAsync(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string[] oldSources, string[] newSources, bool allowNewCompilerDiagnostics, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB, string equivalenceKey = null) { var project = CreateProject(oldSources, language, languageVersionCSharp, languageVersionVB); var compilerDiagnostics = (await Task.WhenAll(project.Documents.Select(d => GetCompilerDiagnosticsAsync(d))).ConfigureAwait(true)).SelectMany(d => d); var fixAllProvider = codeFixProvider.GetFixAllProvider(); if (equivalenceKey == null) equivalenceKey = codeFixProvider.GetType().Name; FixAllContext fixAllContext; if (analyzer != null) { var analyzerDiagnostics = await GetSortedDiagnosticsFromDocumentsAsync(analyzer, project.Documents.ToArray()).ConfigureAwait(true); Func<Document, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getDocumentDiagnosticsAsync = (doc, ids, ct) => Task.FromResult(analyzerDiagnostics.Where(d => d.Location.SourceTree.FilePath == doc.Name)); Func<Project, bool, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getProjectDiagnosticsAsync = (proj, b, ids, ct) => Task.FromResult((IEnumerable<Diagnostic>)analyzerDiagnostics); //todo: verify, probably wrong var fixAllDiagnosticProvider = new FixAllDiagnosticProvider(codeFixProvider.FixableDiagnosticIds.ToImmutableHashSet(), getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync); fixAllContext = new FixAllContext(project.Documents.First(), codeFixProvider, FixAllScope.Solution, equivalenceKey, codeFixProvider.FixableDiagnosticIds, fixAllDiagnosticProvider, CancellationToken.None); } else { Func<Document, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getDocumentDiagnosticsAsync = async (doc, ids, ct) => { var compilerDiags = await GetCompilerDiagnosticsAsync(doc).ConfigureAwait(true); return compilerDiags.Where(d => codeFixProvider.FixableDiagnosticIds.Contains(d.Id)); }; Func<Project, bool, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getProjectDiagnosticsAsync = async (proj, b, ids, ct) => { var theDocs = proj.Documents; var diags = await Task.WhenAll(theDocs.Select(d => getDocumentDiagnosticsAsync(d, ids, ct))).ConfigureAwait(true); return diags.SelectMany(d => d); }; var fixAllDiagnosticProvider = new FixAllDiagnosticProvider(codeFixProvider.FixableDiagnosticIds.ToImmutableHashSet(), getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync); fixAllContext = new FixAllContext(project.Documents.First(), codeFixProvider, FixAllScope.Solution, equivalenceKey, codeFixProvider.FixableDiagnosticIds, fixAllDiagnosticProvider, CancellationToken.None); } var action = await fixAllProvider.GetFixAsync(fixAllContext).ConfigureAwait(true); if (action == null) throw new Exception("No action supplied for the code fix."); project = await ApplyFixAsync(project, action).ConfigureAwait(true); //check if applying the code fix introduced any new compiler diagnostics var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, (await Task.WhenAll(project.Documents.Select(d => GetCompilerDiagnosticsAsync(d))).ConfigureAwait(true)).SelectMany(d => d)); if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) Assert.True(false, $"Fix introduced new compiler diagnostics:\r\n{string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString()))}\r\n"); var docs = project.Documents.ToArray(); for (int i = 0; i < docs.Length; i++) { var document = docs[i]; var actual = await GetStringFromDocumentAsync(document).ConfigureAwait(true); newSources[i].Should().Be(actual); } }
private static void RunIfCSharpVersionGreater(this LanguageVersion languageVersion, Action action, LanguageVersion greaterOrEqualThanLanguageVersion) { if (languageVersion >= greaterOrEqualThanLanguageVersion) { action?.Invoke(); } }
/// <summary> /// General verifier for a diagnostics that should not have fix registred. /// Creates a Document from the source string, then gets diagnostics on it and verify if it has no fix registred. /// It will fail the test if it has any fix registred to it /// </summary> /// <param name="language">The language the source code is in</param> /// <param name="analyzer">The analyzer to be applied to the source code</param> /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param> /// <param name="source">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param> /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param> private async static Task VerifyHasNoFixAsync(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string source, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB) { var document = CreateDocument(source, language, languageVersionCSharp, languageVersionVB); var analyzerDiagnostics = await GetSortedDiagnosticsFromDocumentsAsync(analyzer, new[] { document }).ConfigureAwait(true); foreach (var analyzerDiagnostic in analyzerDiagnostics) { var actions = new List<CodeAction>(); var context = new CodeFixContext(document, analyzerDiagnostic, (a, d) => actions.Add(a), CancellationToken.None); await codeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(true); Assert.False(actions.Any(), $"Should not have a code fix registered for diagnostic '{analyzerDiagnostic.Id}'"); } }
public static void RegisterSyntaxNodeActionForVersionLower <TLanguageKindEnum>(this AnalysisContext context, LanguageVersion lowerThanLanguageVersion, Action <SyntaxNodeAnalysisContext> action, params TLanguageKindEnum[] syntaxKinds) where TLanguageKindEnum : struct => context.RegisterCompilationStartActionForVersionLower(lowerThanLanguageVersion, compilationContext => compilationContext.RegisterSyntaxNodeAction(action, syntaxKinds));
/// <summary> /// General verifier for codefixes. /// Creates a Document from the source string, then gets diagnostics on it and applies the relevant codefixes. /// Then gets the string after the codefix is applied and compares it with the expected result. /// Note: If any codefix causes new diagnostics to show up, the test fails unless allowNewCompilerDiagnostics is set to true. /// </summary> /// <param name="language">The language the source code is in</param> /// <param name="analyzer">The analyzer to be applied to the source code</param> /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param> /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="newSource">A class in the form of a string after the CodeFix was applied to it</param> /// <param name="codeFixIndex">Index determining which codefix to apply if there are multiple</param> /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied</param> /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param> /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param> private async static Task VerifyFixAsync(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string oldSource, string newSource, int? codeFixIndex, bool allowNewCompilerDiagnostics, LanguageVersion languageVersionCSharp, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB) { var supportedDiagnostics = analyzer.SupportedDiagnostics.Select(d => d.Id); var codeFixFixableDiagnostics = codeFixProvider.FixableDiagnosticIds; Assert.True(codeFixFixableDiagnostics.Any(d => supportedDiagnostics.Contains(d)), "Code fix provider does not fix the diagnostic provided by the analyzer."); var document = CreateDocument(oldSource, language, languageVersionCSharp, languageVersionVB); var analyzerDiagnostics = await GetSortedDiagnosticsFromDocumentsAsync(analyzer, new[] { document }).ConfigureAwait(true); var compilerDiagnostics = await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true); var attempts = analyzerDiagnostics.Length; for (int i = 0; i < attempts; ++i) { var actions = new List<CodeAction>(); var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None); await codeFixProvider.RegisterCodeFixesAsync(context).ConfigureAwait(true); if (!actions.Any()) break; if (codeFixIndex != null) document = await ApplyFixAsync(document, actions.ElementAt((int)codeFixIndex)).ConfigureAwait(true); else document = await ApplyFixAsync(document, actions.ElementAt(0)).ConfigureAwait(true); analyzerDiagnostics = await GetSortedDiagnosticsFromDocumentsAsync(analyzer, new[] { document }).ConfigureAwait(true); var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true)); //check if applying the code fix introduced any new compiler diagnostics if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = document.WithSyntaxRoot(Formatter.Format(await document.GetSyntaxRootAsync().ConfigureAwait(true), Formatter.Annotation, document.Project.Solution.Workspace)); newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnosticsAsync(document).ConfigureAwait(true)); Assert.True(false, $"Fix introduced new compiler diagnostics:\r\n{string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString()))}\r\n\r\nNew document:\r\n{(await document.GetSyntaxRootAsync().ConfigureAwait(true)).ToFullString()}\r\n"); } //check if there are analyzer diagnostics left after the code fix if (!analyzerDiagnostics.Any()) break; } //after applying all of the code fixes, compare the resulting string to the inputted one var actual = await GetStringFromDocumentAsync(document).ConfigureAwait(true); Assert.Equal(newSource, actual); }
public static void RegisterCompilationStartActionForVersionLower(this AnalysisContext context, LanguageVersion lowerThanLanguageVersion, Action <CompilationStartAnalysisContext> registrationAction) => context.RegisterCompilationStartAction(compilationContext => compilationContext.RunIfCSharpVersionLower(lowerThanLanguageVersion, () => registrationAction?.Invoke(compilationContext)));
private static Document CreateDocument(string code, string language, LanguageVersion langVersion) { var solution = new AdhocWorkspace().CurrentSolution; var projectId = ProjectId.CreateNewId(); var project = solution .AddProject(projectId, "Project", "Project.dll", language) .GetProject(projectId); var parseOptions = (VisualBasicParseOptions)project.ParseOptions; parseOptions = parseOptions.WithLanguageVersion(langVersion); project = project.WithParseOptions(parseOptions); return project.AddDocument("Document", SourceText.From(code)); }
#pragma warning disable RS1012 private static void RunIfCSharpVersionLower(this CompilationStartAnalysisContext context, LanguageVersion lowerThanLanguageVersion, Action action) => context.Compilation.RunIfCSharpVersionLower(action, lowerThanLanguageVersion);
#pragma warning restore RS1012 private static void RunIfCSharpVersionLower(this Compilation compilation, Action action, LanguageVersion lowerThanLanguageVersion) => (compilation as CSharpCompilation)?.LanguageVersion.RunIfCSharpVersionLower(action, lowerThanLanguageVersion);
public static async Task<string> FormatSourceAsync(string language, string source, LanguageVersion languageVersionCSharp = LanguageVersion.CSharp6, Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic14) { var document = CreateDocument(source, language, languageVersionCSharp, languageVersionVB); var newDoc = await Formatter.FormatAsync(document).ConfigureAwait(true); return (await newDoc.GetSyntaxRootAsync().ConfigureAwait(true)).ToFullString(); }
private static void RunIfCSharpVersionLower(this LanguageVersion languageVersion, Action action, LanguageVersion lowerThanLanguageVersion) { if (languageVersion < lowerThanLanguageVersion) { action?.Invoke(); } }
// // This parses the -arg and /arg options to the compiler, even if the strings // in the following text use "/arg" on the strings. // bool CSCParseOption (string option, ref string [] args) { int idx = option.IndexOf (':'); string arg, value; if (idx == -1) { arg = option; value = ""; } else { arg = option.Substring (0, idx); value = option.Substring (idx + 1); } switch (arg.ToLower (CultureInfo.InvariantCulture)) { case "/nologo": return true; case "/t": case "/target": switch (value) { case "exe": Target = Target.Exe; break; case "winexe": Target = Target.WinExe; break; case "library": Target = Target.Library; TargetExt = ".dll"; break; case "module": Target = Target.Module; TargetExt = ".netmodule"; break; default: return false; } return true; case "/out": if (value.Length == 0) { Usage (); Environment.Exit (1); } OutputFile = value; return true; case "/o": case "/o+": case "/optimize": case "/optimize+": Optimize = true; return true; case "/o-": case "/optimize-": Optimize = false; return true; case "/incremental": case "/incremental+": case "/incremental-": // nothing. return true; case "/d": case "/define": { if (value.Length == 0) { Usage (); Environment.Exit (1); } foreach (string d in value.Split (argument_value_separator)) { if (defines.Length != 0) defines.Append (";"); defines.Append (d); } return true; } case "/bugreport": // // We should collect data, runtime, etc and store in the file specified // return true; case "/linkres": case "/linkresource": case "/res": case "/resource": bool embeded = arg [1] == 'r' || arg [1] == 'R'; string [] s = value.Split (argument_value_separator); switch (s.Length) { case 1: if (s [0].Length == 0) goto default; embedded_resources [s [0]] = Path.GetFileName (s [0]); break; case 2: embedded_resources [s [0]] = s [1]; break; case 3: Console.WriteLine ("Does not support this method yet: {0}", arg); Environment.Exit (1); break; default: Console.WriteLine ("Wrong number of arguments for option `{0}'", option); Environment.Exit (1); break; } return true; case "/recurse": Console.WriteLine ("/recurse not supported"); Environment.Exit (1); return true; case "/r": case "/reference": { if (value.Length == 0) { Console.WriteLine ("-reference requires an argument"); Environment.Exit (1); } string [] refs = value.Split (argument_value_separator); foreach (string r in refs) { string val = r; int index = val.IndexOf ('='); if (index > -1) { reference_aliases.Add (r); continue; } if (val.Length != 0) references.Add (val); } return true; } case "/main": case "/m": case "/addmodule": case "/win32res": case "/doc": if (showWarnings) Console.WriteLine ("{0} = not supported", arg); return true; case "/lib": { libs.Add (value); return true; } case "/win32icon": { win32IconFile = value; return true; } case "/debug-": want_debugging_support = false; return true; case "/debug": case "/debug+": want_debugging_support = true; return true; case "/checked": case "/checked+": Checked = true; return true; case "/checked-": Checked = false; return true; case "/clscheck": case "/clscheck+": return true; case "/clscheck-": VerifyClsCompliance = false; return true; case "/unsafe": case "/unsafe+": Unsafe = true; return true; case "/unsafe-": Unsafe = false; return true; case "/warnaserror": case "/warnaserror+": if (value.Length == 0) { WarningsAreErrors = true; } else { foreach (string wid in value.Split (argument_value_separator)) warning_as_error.Add (wid); } return true; case "/-runtime": // Console.WriteLine ("Warning ignoring /runtime:v4"); return true; case "/warnaserror-": if (value.Length == 0) { WarningsAreErrors = false; } else { foreach (string wid in value.Split (argument_value_separator)) warning_as_error.Remove (wid); } return true; case "/warn": WarningLevel = Int32.Parse (value); return true; case "/nowarn": { string [] warns; if (value.Length == 0) { Console.WriteLine ("/nowarn requires an argument"); Environment.Exit (1); } warns = value.Split (argument_value_separator); foreach (string wc in warns) { try { if (wc.Trim ().Length == 0) continue; int warn = Int32.Parse (wc); if (warn < 1) { throw new ArgumentOutOfRangeException ("warn"); } ignore_warning.Add (warn); } catch { Console.WriteLine (String.Format ("`{0}' is not a valid warning number", wc)); Environment.Exit (1); } } return true; } case "/noconfig": load_default_config = false; return true; case "/nostdlib": case "/nostdlib+": StdLib = false; return true; case "/nostdlib-": StdLib = true; return true; case "/fullpaths": return true; case "/keyfile": if (value == String.Empty) { Console.WriteLine ("{0} requires an argument", arg); Environment.Exit (1); } StrongNameKeyFile = value; return true; case "/keycontainer": if (value == String.Empty) { Console.WriteLine ("{0} requires an argument", arg); Environment.Exit (1); } StrongNameKeyContainer = value; return true; case "/delaysign+": case "/delaysign": StrongNameDelaySign = true; return true; case "/delaysign-": StrongNameDelaySign = false; return true; case "/langversion": switch (value.ToLower (CultureInfo.InvariantCulture)) { case "iso-1": Version = LanguageVersion.ISO_1; return true; case "default": Version = LanguageVersion.Default; return true; case "iso-2": Version = LanguageVersion.ISO_2; return true; case "future": Version = LanguageVersion.Future; return true; } Console.WriteLine ("Invalid option `{0}' for /langversion. It must be either `ISO-1', `ISO-2' or `Default'", value); Environment.Exit (1); return true; case "/codepage": CodePage = value; return true; } Console.WriteLine ("Failing with : {0}", arg); return false; }
internal static bool SupportsLanguageVersion(this Document document, LanguageVersion languageVersion) { return(((CSharpParseOptions)document.Project.ParseOptions).LanguageVersion >= languageVersion); }
private static bool TryParseLanguageVersion(string str, out LanguageVersion version) { if (str == null) { version = LanguageVersion.Default; return true; } switch (str.ToLowerInvariant()) { case "iso-1": version = LanguageVersion.CSharp1; return true; case "iso-2": version = LanguageVersion.CSharp2; return true; case "7": version = LanguageVersion.CSharp7; return true; case "default": version = LanguageVersion.Default; return true; case "latest": version = LanguageVersion.Latest; return true; default: // We are likely to introduce minor version numbers after C# 7, thus breaking the // one-to-one correspondence between the integers and the corresponding // LanguageVersion enum values. But for compatibility we continue to accept any // integral value parsed by int.TryParse for its corresponding LanguageVersion enum // value for language version C# 6 and earlier (e.g. leading zeros are allowed) int versionNumber; if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && versionNumber <= 6 && ((LanguageVersion)versionNumber).IsValid()) { version = (LanguageVersion)versionNumber; return true; } version = LanguageVersion.Default; return false; } }
private async Task VerifyAbsenceAsync(string code, LanguageVersion languageVersion) { await VerifyItemIsAbsentAsync(GetMarkup(code, languageVersion), "await"); }
public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, Report report, ParserSession session) { this.file = file; current_container = current_namespace = file; this.module = file.Module; this.compiler = file.Compiler; this.settings = compiler.Settings; this.report = report; lang_version = settings.Version; yacc_verbose_flag = settings.VerboseParserFlag; doc_support = settings.DocumentationFile != null; lexer = new Tokenizer (reader, file, session); oob_stack = new Stack<object> (); lbag = session.LocationsBag; use_global_stacks = session.UseJayGlobalArrays; parameters_bucket = session.ParametersStack; }
private async Task VerifyKeywordAsync(string code, LanguageVersion languageVersion, string?inlineDescription = null) { await VerifyItemExistsAsync(GetMarkup(code, languageVersion), "await", glyph : (int)Glyph.Keyword, inlineDescription : inlineDescription); }
private static bool TryParseLanguageVersion(string str, LanguageVersion defaultVersion, out LanguageVersion version) { if (str == null) { version = defaultVersion; return true; } switch (str.ToLowerInvariant()) { case "iso-1": version = LanguageVersion.CSharp1; return true; case "iso-2": version = LanguageVersion.CSharp2; return true; case "default": version = defaultVersion; return true; default: int versionNumber; if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && ((LanguageVersion)versionNumber).IsValid()) { version = (LanguageVersion)versionNumber; return true; } version = defaultVersion; return false; } }
public CompilerSettings () { StdLib = true; Target = Target.Exe; TargetExt = ".exe"; Platform = Platform.AnyCPU; Version = LanguageVersion.Default; VerifyClsCompliance = true; Optimize = true; Encoding = Encoding.UTF8; LoadDefaultReferences = true; StdLibRuntimeVersion = RuntimeVersion.v4; AssemblyReferences = new List<string> (); AssemblyReferencesAliases = new List<Tuple<string, string>> (); Modules = new List<string> (); ReferencesLookupPaths = new List<string> (); conditional_symbols = new List<string> (); // // Add default mcs define // conditional_symbols.Add ("__MonoCS__"); source_files = new List<CompilationSourceFile> (); LaunchDebugger = false; }