private void VerifyFix(Document document, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string newSource, int?codeFixIndex, bool useCompilerAnalyzerDriver, bool allowNewCompilerDiagnostics)
        {
            Diagnostic[] analyzerDiagnostics = GetSortedDiagnostics(analyzer, document, useCompilerAnalyzerDriver: useCompilerAnalyzerDriver);
            System.Collections.Immutable.ImmutableArray <Diagnostic> compilerDiagnostics = document.GetSemanticModelAsync().Result.GetDiagnostics();

            // TODO(mavasani): Delete the below if statement once FxCop Analyzers have been ported to new IDiagnosticAnalyzer API.
            if (!useCompilerAnalyzerDriver)
            {
                Assert.True(analyzerDiagnostics.IsEmpty());
                return;
            }

            int 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);
                codeFixProvider.RegisterCodeFixesAsync(context).Wait();
                if (!actions.Any())
                {
                    break;
                }

                if (codeFixIndex != null)
                {
                    document = document.Apply(actions.ElementAt((int)codeFixIndex));
                    break;
                }

                document = document.Apply(actions.ElementAt(0));

                analyzerDiagnostics = GetSortedDiagnostics(analyzer, document, useCompilerAnalyzerDriver: useCompilerAnalyzerDriver);
                IEnumerable <Diagnostic> newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, document.GetSemanticModelAsync().Result.GetDiagnostics());
                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(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace));
                    newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, document.GetSemanticModelAsync().Result.GetDiagnostics());

                    Assert.True(false,
                                string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n",
                                              newCompilerDiagnostics.Select(d => d.ToString()).Join("\r\n"),
                                              document.GetSyntaxRootAsync().Result.ToFullString()));
                }

                if (analyzerDiagnostics.IsEmpty())
                {
                    break;
                }
            }

            Document   newDocument = Simplifier.ReduceAsync(document, Simplifier.Annotation).Result;
            SyntaxNode root        = newDocument.GetSyntaxRootAsync().Result;

            root = Formatter.Format(root, Formatter.Annotation, newDocument.Project.Solution.Workspace);
            string actual = root.GetText().ToString();

            Assert.Equal(newSource, actual);
        }
        private void BinarySearchPartialSortedListHelper(System.Collections.Immutable.ImmutableArray <int> inputData, int sortedIndex, int sortedLength)
        {
            if (sortedIndex < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(sortedIndex));
            }
            if (sortedLength < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(sortedLength));
            }

            inputData = inputData.Sort(sortedIndex, sortedLength, Comparer <int> .Default);
            int min = inputData[sortedIndex];
            int max = inputData[sortedIndex + sortedLength - 1];

            var basis = new List <int>(inputData);
            var query = inputData.ToImmutableSegmentedList();

            for (int value = min - 1; value <= max + 1; value++)
            {
                for (int index = sortedIndex; index < sortedIndex + sortedLength; index++) // make sure the index we pass in is always within the sorted range in the list.
                {
                    for (int count = 0; count <= sortedLength - index; count++)
                    {
                        int expected = basis.BinarySearch(index, count, value, null);
                        int actual   = BinarySearchImpl(query, index, count, value, null);
                        if (expected != actual)
                        {
                            Debugger.Break();
                        }
                        Assert.Equal(expected, actual);
                    }
                }
            }
        }
示例#3
0
        private List <string> GetCategories(IMethodSymbol methodSymbol)
        {
            List <string> categories = null;

            System.Collections.Immutable.ImmutableArray <AttributeData> attributes = methodSymbol.GetAttributes();
            if (attributes != null && attributes.Length > 0)
            {
                foreach (var attribute in attributes)
                {
                    if (attribute.AttributeClass.Name != "BenchmarkCategoryAttribute")
                    {
                        continue;
                    }

                    if (attribute.ConstructorArguments.Length == 0)
                    {
                        continue;
                    }

                    foreach (var argument in attribute.ConstructorArguments)
                    {
                        if (argument.Kind == TypedConstantKind.Array)
                        {
                            categories = ProcessArrayCategoryArgument(categories, argument);
                        }
                        else
                        {
                            categories = ProcessConstantCategoryArgument(categories, argument);
                        }
                    }
                }
            }

            return(categories);
        }
        internal static Document Apply(this Document document, CodeAction action)
        {
            System.Collections.Immutable.ImmutableArray <CodeActionOperation> operations = action.GetOperationsAsync(CancellationToken.None).Result;
            Solution solution = operations.OfType <ApplyChangesOperation>().Single().ChangedSolution;

            return(solution.GetDocument(document.Id));
        }
        private static string GetGeneratedOutput(string source)
        {
            var syntaxTree = CSharpSyntaxTree.ParseText(source);

            var references = new List <MetadataReference>();

            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (var assembly in assemblies)
            {
                if (!assembly.IsDynamic)
                {
                    references.Add(MetadataReference.CreateFromFile(assembly.Location));
                }
            }

            var compilation = CSharpCompilation.Create("foo", new SyntaxTree[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            System.Collections.Immutable.ImmutableArray <Diagnostic> diagnostics = compilation.GetDiagnostics();
            Assert.False(diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error), "Failed: " + diagnostics.FirstOrDefault()?.GetMessage());

            var generator = new Generator();

            var output = generator.GetGeneratedSource(compilation);

            return(output);
        }
        private static IMethodSymbol FindSetPropertyMethod(this INamedTypeSymbol classSymbol, Compilation compilation)
        {
            // Find SetProperty<T>(ref T, T, string) method.
            IMethodSymbol setPropertyMethod = classSymbol
                                              .GetMembers("SetProperty")
                                              .OfType <IMethodSymbol>()
                                              .FirstOrDefault(m => m.Parameters.Length == 3 && m.TypeParameters.Length == 1);

            if (setPropertyMethod != null)
            {
                System.Collections.Immutable.ImmutableArray <IParameterSymbol> parameters = setPropertyMethod.Parameters;
                ITypeParameterSymbol typeParameter = setPropertyMethod.TypeParameters[0];
                INamedTypeSymbol     stringType    = compilation.GetSpecialType(SpecialType.System_String);

                if (setPropertyMethod.ReturnsVoid &&
                    parameters[0].RefKind == RefKind.Ref &&
                    parameters[0].Type.Equals(typeParameter) &&
                    parameters[1].Type.Equals(typeParameter) &&
                    parameters[2].Type.Equals(stringType))
                {
                    return(setPropertyMethod);
                }
            }

            return(null);
        }
示例#7
0
        public void OriginUsed()
        {
            // Y axis is inverted as it expects to be drawing for bottom left
            GlyphBuilder   fullBuilder = new GlyphBuilder(new System.Numerics.Vector2(10, 99));
            IGlyphRenderer builder     = fullBuilder;

            builder.BeginGlyph(Vector2.Zero);
            builder.BeginFigure();
            builder.MoveTo(new Vector2(0, 0));
            builder.LineTo(new Vector2(0, 10)); // becomes 0, -10

            builder.CubicBezierTo(
                new Vector2(15, 15),  // control point -  will not be in the final point collection
                new Vector2(15, 10),  // control point -  will not be in the final point collection
                new Vector2(10, 10)); // becomes 10, -10

            builder.QuadraticBezierTo(
                new Vector2(10, 5), // control point -  will not be in the final point collection
                new Vector2(10, 0));

            builder.EndFigure();
            builder.EndGlyph();

            System.Collections.Immutable.ImmutableArray <Vector2> points = fullBuilder.Paths.Single().Flatten().Single().Points;

            Assert.Contains(new Vector2(10, 99), points);
            Assert.Contains(new Vector2(10, 109), points);
            Assert.Contains(new Vector2(20, 99), points);
            Assert.Contains(new Vector2(20, 109), points);
        }
        /// <summary>
        /// Apply the inputted CodeAction to the inputted document.
        /// Meant to be used to apply codefixes.
        /// </summary>
        /// <param name="document">The Document to apply the fix on</param>
        /// <param name="codeAction">A CodeAction that will be applied to the Document.</param>
        /// <returns>A Document with the changes from the CodeAction</returns>
        private static async Task <Document> ApplyFix(Document document, CodeAction codeAction)
        {
            System.Collections.Immutable.ImmutableArray <CodeActionOperation> operations = await codeAction.GetOperationsAsync(CancellationToken.None);

            Solution solution = operations.OfType <ApplyChangesOperation>().Single().ChangedSolution;

            return(solution.GetDocument(document.Id));
        }
 private static void CreateAnnotationForDiagnostics(System.Collections.Immutable.ImmutableArray <Diagnostic> diagnostics,
                                                    string annotationKind,
                                                    BidirectionalDictionary <Diagnostic, SyntaxAnnotation> diagnosticAnnotationPairs)
 {
     foreach (var diagnostic in diagnostics)
     {
         diagnosticAnnotationPairs.Add(diagnostic, new SyntaxAnnotation(annotationKind));
     }
 }
示例#10
0
        public int GetHashCode(SourceText obj)
        {
            System.Collections.Immutable.ImmutableArray <byte> checksum = obj.GetChecksum();
            int contentsHash = !checksum.IsDefault ? Hash.CombineValues(checksum) : 0;
            int encodingHash = obj.Encoding != null?obj.Encoding.GetHashCode() : 0;

            return(Hash.Combine(obj.Length,
                                Hash.Combine(contentsHash,
                                             Hash.Combine(encodingHash, obj.ChecksumAlgorithm.GetHashCode()))));
        }
 public static Location GuessCorrectLocation(CodeRefactoringContext context, System.Collections.Immutable.ImmutableArray <Location> locations)
 {
     foreach (var loc in locations)
     {
         if (context.Document.FilePath == loc.SourceTree.FilePath)
         {
             return(loc);
         }
     }
     return(locations[0]);
 }
        public override void Analyze(BinaryAnalyzerContext context)
        {
            PEBinary target = context.PEBinary();

            System.Collections.Immutable.ImmutableArray <SectionHeader> sectionHeaders = target.PE.PEHeaders.SectionHeaders;

            var badSections = new List <string>();

            if (sectionHeaders != null)
            {
                foreach (SectionHeader sectionHeader in sectionHeaders)
                {
                    SectionCharacteristics wsFlags = SectionCharacteristics.MemWrite | SectionCharacteristics.MemShared;

                    if ((sectionHeader.SectionCharacteristics & wsFlags) == wsFlags) // IMAGE_SCN_MEM_WRITE & IMAGE_SCN_MEM_SHARED
                    {
                        badSections.Add(sectionHeader.Name);
                    }
                }
            }

            if (badSections.Count == 0)
            {
                // Image '{0}' contains no data or code sections marked as both shared and writable.
                context.Logger.Log(this,
                                   RuleUtilities.BuildResult(ResultKind.Pass, context, null,
                                                             nameof(RuleResources.BA2019_Pass),
                                                             context.TargetUri.GetFileName()));
                return;
            }

            string badSectionsText = string.Join(";", badSections);

            // '{0}' contains PE section(s) ({1}) that are both writable and executable.
            // Writable and executable memory segments make it easier for an attacker
            // to exploit memory corruption vulnerabilities, because it may provide an
            // attacker executable location(s) to inject shellcode. To resolve this
            // issue, configure your tools to not emit memory sections that are writable
            // and executable. For example, look for uses of /SECTION on the linker
            // command line for C and C++ programs, or #pragma section in C and C++
            // source code, which mark a section with both attributes. Enabling
            // incremental linking via the /INCREMENTAL argument (the default for
            // Microsoft Visual Studio debug build) can also result in a writable and
            // executable section named 'textbss'. For this case, disable incremental
            // linking (or analyze an alternate build configuration that disables this
            // feature) to resolve the problem.
            context.Logger.Log(this,
                               RuleUtilities.BuildResult(FailureLevel.Error, context, null,
                                                         nameof(RuleResources.BA2019_Error),
                                                         context.TargetUri.GetFileName(),
                                                         badSectionsText));
        }
示例#13
0
        /// <summary>
        /// Initialize a ResourceData instance from a PE file
        /// </summary>
        /// <param name="ecmaModule"></param>
        public ResourceData(EcmaModule ecmaModule, Func <object, object, ushort, bool> resourceFilter = null)
        {
            System.Collections.Immutable.ImmutableArray <byte> ecmaData = ecmaModule.PEReader.GetEntireImage().GetContent();
            PEReader peFile = ecmaModule.PEReader;

            DirectoryEntry resourceDirectory = peFile.PEHeaders.PEHeader.ResourceTableDirectory;

            if (resourceDirectory.Size != 0)
            {
                BlobReader resourceDataBlob = ecmaModule.PEReader.GetSectionData(resourceDirectory.RelativeVirtualAddress).GetReader(0, resourceDirectory.Size);
                ReadResourceData(resourceDataBlob, peFile, resourceFilter);
            }
        }
        /// <summary>
        /// Helper method to format a Diagnostic into an easily readable string
        /// </summary>
        /// <param name="analyzer">The analyzer that this verifier tests</param>
        /// <param name="diagnostics">The Diagnostics to be formatted</param>
        /// <returns>The Diagnostics formatted as a string</returns>
        private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diagnostic[] diagnostics)
        {
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < diagnostics.Length; ++i)
            {
                builder.AppendLine("// " + diagnostics[i].ToString());

                System.Type analyzerType = analyzer.GetType();
                System.Collections.Immutable.ImmutableArray <DiagnosticDescriptor> rules = analyzer.SupportedDiagnostics;

                foreach (DiagnosticDescriptor rule in rules)
                {
                    if (rule != null && rule.Id == diagnostics[i].Id)
                    {
                        Location location = diagnostics[i].Location;
                        if (location == Location.None)
                        {
                            builder.AppendFormat("GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id);
                        }
                        else
                        {
                            Assert.True(
                                location.IsInSource,
                                $"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n");

                            string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt";
                            Microsoft.CodeAnalysis.Text.LinePosition linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition;

                            builder.AppendFormat(
                                "{0}({1}, {2}, {3}.{4})",
                                resultMethodName,
                                linePosition.Line + 1,
                                linePosition.Character + 1,
                                analyzerType.Name,
                                rule.Id);
                        }

                        if (i != diagnostics.Length - 1)
                        {
                            builder.Append(',');
                        }

                        builder.AppendLine();
                        break;
                    }
                }
            }

            return(builder.ToString());
        }
        /// <summary>
        /// Initializes a <see cref="DataModelMetadata"/> instance from the given grammar.
        /// </summary>
        /// <exception cref="ArgumentException">
        /// Thrown when the supplied <see cref="GrammarSymbol"/> is not a valid grammar.
        /// </exception>
        /// <param name="grammar">
        /// The grammar from which the <see cref="DataModelMetadata"/> shall be generated.
        /// </param>
        /// <returns>
        /// A <see cref="DataModelMetadata"/> containing data from the grammar <paramref name="grammar"/>.
        /// </returns>
        public static DataModelMetadata FromGrammar(GrammarSymbol grammar)
        {
            if (grammar.Kind != SymbolKind.Grammar)
            {
                throw new ArgumentException("FromGrammar requires a grammar.");
            }

            GrammarSymbol decl        = grammar.Children[0];
            GrammarSymbol grammarId   = decl.Children[0];
            string        grammarName = grammarId.GetLogicalText();

            System.Collections.Immutable.ImmutableArray <Annotation> annotations = grammarId.Annotations;
            string nameSpace = annotations.GetAnnotationValue("namespace") ?? grammarName;

            return(new DataModelMetadata(grammarName, nameSpace, annotations.HasAnnotation("generateLocations"), !annotations.HasAnnotation("noGenerateEquals")));
        }
示例#16
0
 private static void SerializeTupleElementNames(ArrayBuilder <LocalAndScope> locals, BlobBuilder cmw)
 {
     cmw.WriteInt32(locals.Count);
     foreach (LocalAndScope localAndScope in locals)
     {
         ILocalDefinition local = localAndScope.Local;
         LocalScope       scope = localAndScope.Scope;
         System.Collections.Immutable.ImmutableArray <TypedConstant> tupleElementNames = local.TupleElementNames;
         cmw.WriteInt32(tupleElementNames.Length);
         foreach (TypedConstant tupleElementName in tupleElementNames)
         {
             WriteUtf8String(cmw, (string)tupleElementName.Value ?? string.Empty);
         }
         cmw.WriteInt32(local.SlotIndex);
         cmw.WriteInt32(scope.StartOffset);
         cmw.WriteInt32(scope.EndOffset);
         WriteUtf8String(cmw, local.Name);
     }
 }
 bool IsInactiveConditional(System.Collections.Immutable.ImmutableArray <AttributeData> attributes)
 {
     foreach (var attr in attributes)
     {
         if (attr.AttributeClass.Name == "ConditionalAttribute" && attr.AttributeClass.ContainingNamespace.ToString() == "System.Diagnostics" && attr.ConstructorArguments.Length == 1)
         {
             string symbol = attr.ConstructorArguments[0].Value as string;
             if (symbol != null)
             {
                 var options = (CSharpParseOptions)semanticModel.SyntaxTree.Options;
                 if (!options.PreprocessorSymbolNames.Contains(symbol))
                 {
                     return(true);
                 }
             }
         }
     }
     return(false);
 }
示例#18
0
        public void FailedOverloadResolution()
        {
            TestCode   testCode     = new TestCode(@"
class Program
{
    static void Main(string[] args)
    {
        int i = 8;
        int j = i + q;
        X$.f(""hello"");
    }
}

class X
{
    public static void f() { }
    public static void f(int i) { }
}
");
            TypeInfo   typeInfo     = testCode.SemanticModel.GetTypeInfo((ExpressionSyntax)testCode.SyntaxNode);
            SymbolInfo semanticInfo = testCode.SemanticModel.GetSymbolInfo((ExpressionSyntax)testCode.SyntaxNode);

            Assert.Null(typeInfo.Type);
            Assert.Null(typeInfo.ConvertedType);

            Assert.Null(semanticInfo.Symbol);
            Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason);
            Assert.Equal(2, semanticInfo.CandidateSymbols.Length);
            ISymbol[] sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(s => s.ToDisplayString()).ToArray();
            Assert.Equal("X.f()", sortedCandidates[0].ToDisplayString());
            Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind);
            Assert.Equal("X.f(int)", sortedCandidates[1].ToDisplayString());
            Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind);

            System.Collections.Immutable.ImmutableArray <ISymbol> memberGroup = testCode.SemanticModel.GetMemberGroup((ExpressionSyntax)testCode.SyntaxNode);

            Assert.Equal(2, memberGroup.Length);
            ISymbol[] sortedMemberGroup = memberGroup.AsEnumerable().OrderBy(s => s.ToDisplayString()).ToArray();
            Assert.Equal("X.f()", sortedMemberGroup[0].ToDisplayString());
            Assert.Equal("X.f(int)", sortedMemberGroup[1].ToDisplayString());
        }
示例#19
0
        private void Generate()
        {
            System.Collections.Immutable.ImmutableArray <ToStringEntry> entries = _writtenType.ToStringEntries;
            if (entries.Length == 0)
            {
                return;
            }

            _codeWriter.WriteLine();
            _codeWriter.WriteLine("/// <summary>Converts this instance into a debugging string.</summary>");
            _codeWriter.WriteLine("/// <returns>A string containing the data stored in this instance.</summary>");
            _codeWriter.OpenBrace("public override string ToString()");
            _codeWriter.WriteLine("var sb = new StringBuilder();");

            foreach (ToStringEntry toStringEntry in entries)
            {
                this.WriteToStringEntry(toStringEntry);
            }

            _codeWriter.WriteLine("return sb.ToString();");
            _codeWriter.CloseBrace(); // ToString()
        }
        public void Test_InterfaceExtensionsGenerator()
        {
            // Create the 'input' compilation that the generator will act on
            Compilation inputCompilation = CreateCompilation(@"
using System;

namespace MyCode {

    [UltimateOrb.CodeAnalysis.SourceGenerators.GeneratExtensions]
    interface IInterfaceA<T> {

        bool Property1 {

            get;
        }

        internal bool Property2 {

            set;
        }

        public bool Property3 {

            get;
            protected set;
        }

        static int Method4() {
            return 123;
        }

        public long Method5() {
            return 123;
        }

        void Method6(ref long arg1, in uint? arg2 , in string? arg3, Guid arg4) {
            return;
        }

        protected void Method7(ref ulong arg1, in uint? arg2, in string? arg3, Guid arg4);

        void Method8(ref nint arg1, in UIntPtr? arg2, in string? arg3, Guid arg4);

    }
}
");

            // directly create an instance of the generator
            // (Note: in the compiler this is loaded from an assembly, and created via reflection at runtime)
            var generator = new InterfaceExtensionsGenerator();

            // Create the driver that will control the generation, passing in our generator
            GeneratorDriver driver = CSharpGeneratorDriver.Create(generator);

            // Run the generation pass
            // (Note: the generator driver itself is immutable, and all calls return an updated version of the driver that you should use for subsequent calls)
            driver = driver.RunGeneratorsAndUpdateCompilation(inputCompilation, out var outputCompilation, out var diagnostics);

            // We can now assert things about the resulting compilation:
            Debug.Assert(diagnostics.IsEmpty);                        // there were no diagnostics created by the generators
            Debug.Assert(outputCompilation.SyntaxTrees.Count() == 2); // we have two syntax trees, the original 'user' provided one, and the one added by the generator
            System.Collections.Immutable.ImmutableArray <Diagnostic> diagnostics1 = outputCompilation.GetDiagnostics();
            Debug.Assert(diagnostics1.IsEmpty);                       // verify the compilation with the added source has no diagnostics

            // Or we can look at the results directly:
            GeneratorDriverRunResult runResult = driver.GetRunResult();

            // The runResult contains the combined results of all generators passed to the driver
            Debug.Assert(runResult.GeneratedTrees.Length == 1);
            Debug.Assert(runResult.Diagnostics.IsEmpty);

            // Or you can access the individual results on a by-generator basis
            GeneratorRunResult generatorResult = runResult.Results[0];

            Debug.Assert(generatorResult.Generator == generator);
            Debug.Assert(generatorResult.Diagnostics.IsEmpty);
            Debug.Assert(generatorResult.GeneratedSources.Length == 1);
            Debug.Assert(generatorResult.Exception is null);
        }
 internal static Solution Apply(CodeAction action)
 {
     System.Collections.Immutable.ImmutableArray <CodeActionOperation> operations = action.GetOperationsAsync(CancellationToken.None).Result;
     return(operations.OfType <ApplyChangesOperation>().Single().ChangedSolution);
 }
        //private static IDisposable sw;

        /// <summary>Main entry-point for this application.</summary>
        /// <param name="args">Array of command-line argument strings.</param>
        /// <returns>Exit-code for the process - 0 for success, else an error code.</returns>
        public static int Main(string[] args)
        {
            using (var config = new DataModelGeneratorConfiguration())
            {
                if (!config.ParseArgs(args))
                {
                    return(1);
                }

                string inputText;
                using (var sr = new StreamReader(config.InputStream))
                {
                    inputText = sr.ReadToEnd();
                }

                GrammarSymbol grammar;
                try
                {
                    var factory = new TokenTextIndex(inputText);
                    System.Collections.Immutable.ImmutableArray <Token> tokens = Lexer.Lex(factory);
                    var parser = new Parser(tokens);
                    grammar = parser.ParseGrammar();
                }
                catch (G4ParseFailureException ex)
                {
                    Console.Error.WriteLine(ex.Message);
                    return(1);
                }

                var builder = new DataModelBuilder();
                for (int idx = 1; idx < grammar.Children.Length; ++idx)
                {
                    try
                    {
                        GrammarSymbol prod = grammar.Children[idx];
                        builder.CompileProduction(prod);
                    }
                    catch (G4ParseFailureException ex)
                    {
                        Console.WriteLine(Strings.FailedToCompileProduction + ex.Message);
                    }
                }

                string generatedCSharp;
                string generatedJsonSchema;
                try
                {
                    DataModel model = builder.Link(config.InputFilePath, DataModelMetadata.FromGrammar(grammar));
                    model = MemberHoister.HoistTypes(model);
                    var cr = new CodeWriter();
                    CodeGenerator.WriteDataModel(cr, model);
                    generatedCSharp = cr.ToString();

                    cr = new CodeWriter(2, ' ');
                    JsonSchemaGenerator.WriteSchema(cr, model);
                    generatedJsonSchema = cr.ToString();
                }
                catch (G4ParseFailureException ex)
                {
                    Console.Error.WriteLine(ex.Message);
                    return(1);
                }

                if (config.ToConsole)
                {
                    Console.WriteLine(generatedCSharp);
                }

                using (var sw = new StreamWriter(config.OutputStream))
                {
                    sw.Write(generatedCSharp);
                }

                string jsonSchemaPath = Path.GetFileNameWithoutExtension(config.OutputFilePath);
                jsonSchemaPath = Path.Combine(Path.GetDirectoryName(config.OutputFilePath), jsonSchemaPath + ".schema.json");

                File.WriteAllText(jsonSchemaPath, generatedJsonSchema);

                return(0);
            }
        }
 public Report Invoke(System.Collections.Immutable.ImmutableArray <City> input)
 {
     return(ReportingModuleFunctions.GenerateReport(generateCityReport, input));
 }
示例#24
0
        private static void SerializeStateMachineLocalScopes(IMethodBody methodBody, ArrayBuilder <PooledBlobBuilder> customDebugInfo)
        {
            System.Collections.Immutable.ImmutableArray <StateMachineHoistedLocalScope> scopes = methodBody.StateMachineHoistedLocalScopes;
            if (scopes.IsDefaultOrEmpty)
            {
                return;
            }

            uint numberOfScopes   = (uint)scopes.Length;
            PooledBlobBuilder cmw = PooledBlobBuilder.GetInstance();

            cmw.WriteByte(CustomDebugInfoConstants.Version);
            cmw.WriteByte((byte)CustomDebugInfoKind.StateMachineHoistedLocalScopes);
            cmw.Align(4);
            cmw.WriteUInt32(12 + numberOfScopes * 8);
            cmw.WriteUInt32(numberOfScopes);
            foreach (StateMachineHoistedLocalScope scope in scopes)
            {
                if (scope.IsDefault)
                {
                    cmw.WriteUInt32(0);
                    cmw.WriteUInt32(0);
                }
                else
                {
                    // Dev12 C# emits end-inclusive range
                    cmw.WriteUInt32((uint)scope.StartOffset);
                    cmw.WriteUInt32((uint)scope.EndOffset - 1);
                }
            }

            customDebugInfo.Add(cmw);
        }
示例#25
0
        public static IEnumerable <IEnumerable <ISymbol> > GetLocalSymbolSets(INamespaceOrTypeSymbol containerSymbol, Compilation compilation, System.Collections.Immutable.ImmutableArray <ISymbol> members)
        {
            if (!(containerSymbol is ITypeSymbol))
            {
                return(Enumerable.Empty <IEnumerable <ISymbol> >());
            }

            var semanticModels = containerSymbol.Locations.Select(loc => loc.SourceTree).Distinct().Select(sourceTree => compilation.GetSemanticModel(sourceTree, true));

            return(semanticModels.SelectMany(semanticModel => members.SelectMany(m => semanticModel.GetCsSymbolsPerScope(m))));
        }
示例#26
0
        private static GpxTrack GetGpxTrack(MotionPathData motionPathData)
        {
            var attributes = motionPathData.attribute.Split(";");
            int i          = 0;

            Point p = null;
            List <GpxWaypoint> waypoints = new List <GpxWaypoint> ();

            while (i < attributes.Length)
            {
                i++;
                var a    = attributes[i];
                var pair = a.Split("=");
                if (pair.Length != 2)
                {
                    break;
                }
                switch (pair[0])
                {
                case "k":
                {
                    AddWaypoint(p, waypoints);
                    p = new Point();

                    break;
                }

                case "lat":
                {
                    if (p != null)
                    {
                        double d = double.Parse(pair[1]);
                        p.Lat = d;
                    }

                    break;
                }

                case "lon":
                {
                    if (p != null)
                    {
                        double d = double.Parse(pair[1]);
                        p.Long = d;
                    }
                    break;
                }

                case "alt":
                {
                    if (p != null)
                    {
                        double d = double.Parse(pair[1]);
                        p.Elev = d;
                    }
                    break;
                }

                case "t":
                {
                    if (p != null)
                    {
                        var d = double.Parse(pair[1]);
                        var l = Convert.ToInt64(d);
                        if (l > 10000000000)
                        {
                            l *= 10000;         // convert to ticks
                        }
                        else
                        {
                            l *= 10000000;
                        }

                        l += offset;         // 1970-01-01
                        DateTime t = new DateTime(l);
                        p.T = t;
                    }
                    break;
                }
                }
                AddWaypoint(p, waypoints);
            }
            System.Collections.Immutable.ImmutableArray <GpxTrackSegment> segments = System.Collections.Immutable.ImmutableArray <GpxTrackSegment> .Empty;
            segments = segments.Add(new GpxTrackSegment(new ImmutableGpxWaypointTable(waypoints), null));

            var gpxTrack = new GpxTrack(GetName(motionPathData),
                                        "Steps: " + motionPathData.totalSteps,
                                        "Cals: " + motionPathData.totalCalories,
                                        "",
                                        System.Collections.Immutable.ImmutableArray <GpxWebLink> .Empty,
                                        null,
                                        null,
                                        motionPathData.sportType,
                                        segments
                                        );

            return(gpxTrack);
        }
示例#27
0
        public async Task EvaluateAsync(CommandContext ctx,
                                        [RemainingText, Description("Code to evaluate.")] string code)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                throw new InvalidCommandUsageException("Code missing.");
            }

            int cs1 = code.IndexOf("```") + 3;
            int cs2 = code.LastIndexOf("```");

            if (cs1 == -1 || cs2 == -1)
            {
                throw new InvalidCommandUsageException("You need to wrap the code into a code block.");
            }
            code = code.Substring(cs1, cs2 - cs1);

            var emb = new DiscordEmbedBuilder {
                Title = "Evaluating...",
                Color = this.ModuleColor
            };

            DiscordMessage msg = await ctx.RespondAsync(embed : emb.Build());

            var           globals = new EvaluationEnvironment(ctx);
            ScriptOptions sopts   = ScriptOptions.Default
                                    .WithImports("System", "System.Collections.Generic", "System.Linq", "System.Net.Http",
                                                 "System.Net.Http.Headers", "System.Reflection", "System.Text", "System.Text.RegularExpressions",
                                                 "System.Threading.Tasks", "DSharpPlus", "DSharpPlus.CommandsNext", "DSharpPlus.Entities",
                                                 "DSharpPlus.Interactivity")
                                    .WithReferences(AppDomain.CurrentDomain.GetAssemblies().Where(xa => !xa.IsDynamic && !string.IsNullOrWhiteSpace(xa.Location)));

            var             sw1     = Stopwatch.StartNew();
            Script <object> snippet = CSharpScript.Create(code, sopts, typeof(EvaluationEnvironment));

            System.Collections.Immutable.ImmutableArray <Diagnostic> diag = snippet.Compile();
            sw1.Stop();

            if (diag.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                emb = new DiscordEmbedBuilder {
                    Title       = "Compilation failed",
                    Description = $"Compilation failed after {sw1.ElapsedMilliseconds.ToString("#,##0")}ms with {diag.Length} errors.",
                    Color       = DiscordColor.Red
                };

                foreach (Diagnostic d in diag.Take(3))
                {
                    FileLinePositionSpan ls = d.Location.GetLineSpan();
                    emb.AddField($"Error at line: {ls.StartLinePosition.Line}, {ls.StartLinePosition.Character}", Formatter.InlineCode(d.GetMessage()));
                }

                if (diag.Length > 3)
                {
                    emb.AddField("Some errors were omitted", $"{diag.Length - 3} errors not displayed");
                }

                if (!(msg is null))
                {
                    msg = await msg.ModifyAsync(embed : emb.Build());
                }
                return;
            }

            Exception            exc = null;
            ScriptState <object> css = null;
            var sw2 = Stopwatch.StartNew();

            try {
                css = await snippet.RunAsync(globals);

                exc = css.Exception;
            } catch (Exception e) {
                exc = e;
            }
            sw2.Stop();

            if (!(exc is null))
            {
                emb = new DiscordEmbedBuilder {
                    Title       = "Execution failed",
                    Description = $"Execution failed after {sw2.ElapsedMilliseconds.ToString("#,##0")}ms with {Formatter.InlineCode($"{exc.GetType()} : {exc.Message}")}.",
                    Color       = this.ModuleColor
                };

                if (!(msg is null))
                {
                    msg = await msg.ModifyAsync(embed : emb.Build());
                }
                return;
            }

            emb = new DiscordEmbedBuilder {
                Title = "Evaluation successful",
                Color = DiscordColor.Aquamarine
            };

            emb.AddField("Result", css.ReturnValue is null ? "No value returned" : css.ReturnValue.ToString(), false);
            emb.AddField("Compilation time", string.Concat(sw1.ElapsedMilliseconds.ToString("#,##0"), "ms"), true);
            emb.AddField("Execution time", string.Concat(sw2.ElapsedMilliseconds.ToString("#,##0"), "ms"), true);

            if (!(css.ReturnValue is null))
            {
                emb.AddField("Return type", css.ReturnValue.GetType().ToString(), true);
            }

            if (!(msg is null))
            {
                await msg.ModifyAsync(embed : emb.Build());
            }
示例#28
0
        private static void SerializeDynamicLocalInfo(IMethodBody methodBody, ArrayBuilder <PooledBlobBuilder> customDebugInfo)
        {
            if (!methodBody.HasDynamicLocalVariables)
            {
                return; //There are no dynamic locals
            }

            const int dynamicAttributeSize = 64;
            const int identifierSize       = 64;

            ArrayBuilder <ILocalDefinition> dynamicLocals = GetLocalInfoToSerialize(
                methodBody,
                local =>
            {
                System.Collections.Immutable.ImmutableArray <TypedConstant> dynamicTransformFlags = local.DynamicTransformFlags;
                return(!dynamicTransformFlags.IsEmpty &&
                       dynamicTransformFlags.Length <= dynamicAttributeSize &&
                       local.Name.Length < identifierSize);
            },
                (scope, local) => local);

            if (dynamicLocals == null)
            {
                return;
            }

            const int         blobSize = dynamicAttributeSize + 4 + 4 + identifierSize * 2;//DynamicAttribute: 64, DynamicAttributeLength: 4, SlotIndex: 4, IdentifierName: 128
            PooledBlobBuilder cmw      = PooledBlobBuilder.GetInstance();

            cmw.WriteByte(CustomDebugInfoConstants.Version);
            cmw.WriteByte((byte)CustomDebugInfoKind.DynamicLocals);
            cmw.Align(4);
            // size = Version,Kind + size + cBuckets + (dynamicCount * sizeOf(Local Blob))
            cmw.WriteUInt32(4 + 4 + 4 + (uint)dynamicLocals.Count * blobSize);//Size of the Dynamic Block
            cmw.WriteUInt32((uint)dynamicLocals.Count);

            foreach (ILocalDefinition local in dynamicLocals)
            {
                System.Collections.Immutable.ImmutableArray <TypedConstant> dynamicTransformFlags = local.DynamicTransformFlags;
                byte[] flag = new byte[dynamicAttributeSize];
                for (int k = 0; k < dynamicTransformFlags.Length; k++)
                {
                    if ((bool)dynamicTransformFlags[k].Value)
                    {
                        flag[k] = 1;
                    }
                }
                cmw.WriteBytes(flag);                                //Written Flag
                cmw.WriteUInt32((uint)dynamicTransformFlags.Length); //Written Length

                int localIndex = local.SlotIndex;
                cmw.WriteUInt32((localIndex < 0) ? 0u : (uint)localIndex);

                char[] localName = new char[identifierSize];
                local.Name.CopyTo(0, localName, 0, local.Name.Length);
                cmw.WriteUTF16(localName);
            }

            dynamicLocals.Free();
            customDebugInfo.Add(cmw);
        }