示例#1
0
 private void BindCompilationUnit(CompilationUnitSyntax compilationUnit)
 {
     foreach (var declaration in compilationUnit.Declarations)
     {
         switch (declaration.Kind)
         {
             case SyntaxKind.VariableDeclarationStatement:
                 BindGlobalVariable((VariableDeclarationStatementSyntax) declaration);
                 break;
             case SyntaxKind.FunctionDeclaration:
                 BindFunctionDeclaration((FunctionDeclarationSyntax)declaration);
                 break;
             case SyntaxKind.FunctionDefinition:
                 BindFunctionDefinition((FunctionDefinitionSyntax) declaration);
                 break;
             case SyntaxKind.ConstantBufferDeclaration:
                 BindConstantBufferDeclaration((ConstantBufferSyntax) declaration);
                 break;
             case SyntaxKind.ClassType:
                 BindClassDeclaration((ClassTypeSyntax) declaration);
                 break;
             case SyntaxKind.StructType:
                 BindStructDeclaration((StructTypeSyntax) declaration);
                 break;
             case SyntaxKind.InterfaceType:
                 BindInterfaceDeclaration((InterfaceTypeSyntax) declaration);
                 break;
             default:
                 throw new ArgumentOutOfRangeException();
         }
     }
 }
示例#2
0
        public BindingResult(CompilationUnitSyntax root)
        {
            Root = root;

            _symbolFromSyntaxNode = new Dictionary<SyntaxNode, Symbol>();
            _boundNodeFromSyntaxNode = new Dictionary<SyntaxNode, BoundNode>();
            _diagnostics = new List<Diagnostic>();
        }
示例#3
0
 public virtual void Visit(CompilationUnitSyntax compilationUnitSyntax)
 {
     foreach (var usingSyntax in compilationUnitSyntax.Usings)
     {
         Visit(usingSyntax);
     }
     foreach (var namespaceSyntax in compilationUnitSyntax.Namespaces)
     {
         Visit(namespaceSyntax);
     }
 }
示例#4
0
        public override void visit(Tree.CompilationUnit that)
        {
            _log.debug("Start of compilation unit");

            if (_compUnit != null) throw new NotSupportedException("Compilation defined twice");

            _compUnit = Syntax.CompilationUnit();

            base.visit(that);
            _log.debug("End of compilation unit");
        }
示例#5
0
 public Model.ParsingResults ParseSource(string filename)
 {
     try
     {
         mTree = VisualBasicSyntaxTree.ParseFile(filename);
         mRoot = (CompilationUnitSyntax)mTree.GetRoot();
     }
     catch
     {
         throw;
     }
     return Model.ParsingResults.Success;
 }
示例#6
0
        public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
        {
            UsingDirectiveSyntax[] usingNodes = node.ChildNodes().Where(x => x.Kind == SyntaxKind.UsingDirective).Cast<UsingDirectiveSyntax>().ToArray();
            NamespaceDeclarationSyntax namespaceNode = (NamespaceDeclarationSyntax)node.ChildNodes().FirstOrDefault(x => x.Kind == SyntaxKind.NamespaceDeclaration);

            if (usingNodes.Length > 0 && namespaceNode != null)
            {
                SyntaxTriviaList leadingTrivia = usingNodes[0].GetLeadingTrivia();

                // Remove the existing using statements.
                node = node.ReplaceNodes(usingNodes, (a, b) => null);

                // Leading comment trivia will be added to the namespace. This allows file comments
                // to remain at the top of the file.
                var namespaceTrivia = leadingTrivia.TakeWhile(x =>
                    x.Kind == SyntaxKind.SingleLineCommentTrivia ||
                    x.Kind == SyntaxKind.EndOfLineTrivia);

                // All other trivia will be preserved on the first using directive.
                var preservedTrivia = leadingTrivia.Skip(namespaceTrivia.Count());
                usingNodes[0] = usingNodes[0].WithLeadingTrivia(preservedTrivia);

                // Leading trivia from the namespace needs to be added as trailing trivia to the
                // last using. This allows for #regions around the using statements (as of the
                // Roslyn Sept 2012 CTP, the #endregion appears as leading trivia on the namespace)
                // TODO: See if this is still necessary with the next CTP.
                var trailingTrivia = usingNodes.Last().GetTrailingTrivia()
                    .Concat(namespaceNode.GetLeadingTrivia());

                usingNodes[usingNodes.Length - 1] = usingNodes.Last().WithTrailingTrivia(trailingTrivia);

                // Add any using directives already on the namespace.
                var namespaceUsings = usingNodes.Concat(namespaceNode.Usings);

                // Create a new namespace statment with the usings and the leading trivia we removed earlier.
                SyntaxNode newNamespaceNode = namespaceNode
                    .WithUsings(Syntax.List<UsingDirectiveSyntax>(namespaceUsings))
                    .WithLeadingTrivia(namespaceTrivia);

                // Replace the namespace with the one with usings.
                node = node.ReplaceNodes(
                    node.ChildNodes().Take(1),
                    (a, b) => newNamespaceNode);

            }

            return node;
        }
示例#7
0
文件: Chunk.cs 项目: Noob536/ls2csc
        public Chunk(CompilationUnitSyntax root, Compilation compilation, SemanticModel model)
        {
            Root = root;
            Compilation = compilation;
            Model = model;

            Functions = new Dictionary<MethodSymbol, LS2IL.Function>();
            FunctionsByNumber = new List<LS2IL.Function>();
            EmittedChunkValues = new List<string>();
            ChunkValues = new List<FlatValue>();
            TypeExtraInfo = new Dictionary<NamedTypeSymbol, TypeExtraInfo>();
            MetaValues = new Dictionary<string, FlatValue>();

            //MetaValues.Add("Author", FlatValue.String("Lax"));
            MetaValues.Add("Build Date", FlatValue.String(DateTime.UtcNow.ToString()+" UTC"));
            MetaValues.Add("Compiler", FlatValue.String("ls2csc"));
            MetaValues.Add("Language", FlatValue.String("C#"));
        }
示例#8
0
        public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
        {
            string comment = string.Format(
                "//-----------------------------------------------------------------------\n" +
                "// <copyright file=\"{0}\" company=\"{1}\">\n" +
                "// {2}\n" +
                "// </copyright>\n" +
                "//-----------------------------------------------------------------------\n" +
                "\n",
                Path.GetFileName(node.SyntaxTree.FilePath),
                this.settings.CompanyName,
                this.settings.Copyright.Replace("\n", "\n// "));

            // TODO: figure out how to do this properly.
            comment = comment.Replace("\n", Environment.NewLine);

            SyntaxTriviaList commentTrivia = Syntax.ParseLeadingTrivia(comment);
            var preservedTrivia = node.GetLeadingTrivia().SkipWhile(x =>
                x.Kind == SyntaxKind.SingleLineCommentTrivia ||
                x.Kind == SyntaxKind.EndOfLineTrivia);

            return node.WithLeadingTrivia(commentTrivia.Concat(preservedTrivia));
        }
示例#9
0
 public CompilationUnitSyntax BuildNamespace(CompilationUnitSyntax @base, SyntaxList <MemberDeclarationSyntax> members)
 {
     return(@base.WithMembers(SingletonList <MemberDeclarationSyntax>(NamespaceDeclaration(IdentifierName(_name)).WithMembers(members))));
 }
 public DummySyntaxTree()
 {
     this.node = this.CloneNodeAsRoot<CompilationUnitSyntax>(Syntax.ParseCompilationUnit(string.Empty, 0, null));
 }
示例#11
0
        public void VisitCompilationUnit(CompilationUnitSyntax node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            node.Validate();

            WriteLeadingTrivia(node);

            if (node.LeadingTrivia.Count > 0)
                _writer.WriteLine(_writer.Configuration.BlankLines.AfterFileHeaderComment);

            WriteGlobalNodes(
                node.Usings,
                node.Externs,
                node.Members,
                node.AttributeLists
            );

            WriteTrailingTrivia(node);
        }
        public static CompilationUnitSyntax Visit(CompilationUnitSyntax code)
        {
            var    modifications = new Dictionary <SyntaxToken, SyntaxToken>();
            var    token         = code.GetFirstToken();
            Action modifyPrevEol = () => { };
            var    addAtPrevEol  = new List <(string errorCode, bool isRestore)>();
            var    addAtNextEol  = new List <(string errorCode, bool isRestore)>();

            while (!token.IsKind(SyntaxKind.None))
            {
                token = token.GetNextToken();
                var localToken    = token;
                var leadingTrivia = token.GetAllTrivia().TakeWhile(x => x.SpanStart < token.SpanStart).ToList();
                HandleEol(leadingTrivia, t => t.WithLeadingTrivia);
                var warnings = token.GetAnnotations(PragmaWarnings.AnnotationKind);
                if (warnings.Any())
                {
                    var errorCodes = warnings.Select(x => x.Data).ToList();
                    addAtPrevEol.AddRange(errorCodes.Select(x => (x, false)));
                    addAtNextEol.AddRange(errorCodes.Select(x => (x, true)));
                }
                var trailingTrivia = token.GetAllTrivia().SkipWhile(x => x.SpanStart < token.SpanStart).ToList();
                HandleEol(trailingTrivia, t => t.WithTrailingTrivia);

                void HandleEol(IReadOnlyList <SyntaxTrivia> trivia, Func <SyntaxToken, Func <IEnumerable <SyntaxTrivia>, SyntaxToken> > mod)
                {
                    if (trivia.Any(ContainsEol))
                    {
                        modifyPrevEol();
                        addAtPrevEol  = addAtNextEol;
                        addAtNextEol  = new List <(string errorCode, bool isRestore)>();
                        modifyPrevEol = () =>
                        {
                            if (!addAtPrevEol.Any())
                            {
                                return;
                            }
                            var disables0 = addAtPrevEol.Where(x => !x.isRestore).Select(x => x.errorCode).Distinct().ToList();
                            var restores0 = addAtPrevEol.Where(x => x.isRestore).Select(x => x.errorCode).Distinct().ToList();
                            var disables  = disables0.Except(restores0).ToList();
                            var restores  = restores0.Except(disables0).ToList();
                            if (!disables.Any() && !restores.Any())
                            {
                                return;
                            }
                            var preEol         = trivia.TakeWhile(x => !ContainsEol(x)).ToList();
                            var postEol        = Enumerable.Reverse(trivia).TakeWhile(x => !ContainsEol(x)).Reverse().ToList();
                            var midEol         = trivia.Skip(preEol.Count).Take(trivia.Count - preEol.Count - postEol.Count);
                            var modifiedTrivia = preEol
                                                 .Concat(restores.Any() ?
                                                         new[] { WhitespaceFormatterNewLine.NewLine, PragmaWarningRestore(restores.ToArray()) } :
                                                         Enumerable.Empty <SyntaxTrivia>())
                                                 .Concat(midEol)
                                                 .Concat(disables.Any() ?
                                                         new[] { PragmaWarningDisable(disables.ToArray()), WhitespaceFormatterNewLine.NewLine } :
                                                         Enumerable.Empty <SyntaxTrivia>())
                                                 .Concat(postEol);
                            var existingToken = modifications.TryGetValue(localToken, out var modifiedToken) ? modifiedToken : localToken;
                            modifications[localToken] = mod(existingToken)(modifiedTrivia);
                        };
                    }

                    bool ContainsEol(SyntaxTrivia st)
                    {
                        if (st.IsKind(SyntaxKind.EndOfLineTrivia))
                        {
                            return(true);
                        }
                        var structure = st.GetStructure();

                        if (structure is object)
                        {
                            if (structure.DescendantNodesAndTokensAndSelf().Any(nt => nt.GetLeadingTrivia().Concat(nt.GetTrailingTrivia()).Any(ContainsEol)))
                            {
                                return(true);
                            }
                        }
                        return(false);
                    }
                }
            }
            modifyPrevEol();
            code = code.ReplaceTokens(modifications.Keys, (orgtoken, _) => modifications[orgtoken]);
            code = (CompilationUnitSyntax) new PragmaVisitor().Visit(code);
            return(code);
        }
        private static bool TryGetStaticNamespaceString(INamespaceOrTypeSymbol namespaceSymbol, CompilationUnitSyntax root, bool fullyQualify, string alias, out string namespaceString)
        {
            if (namespaceSymbol is INamespaceSymbol)
            {
                namespaceString = null;
                return(false);
            }

            namespaceString = fullyQualify
                    ? namespaceSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
                    : namespaceSymbol.ToDisplayString();

            if (alias != null)
            {
                namespaceString = alias + "::" + namespaceString;
            }

            return(ShouldAddStaticUsing(namespaceString, root));
        }
示例#14
0
 private void RemoveTestClassAttributes(CompilationUnitSyntax root, SemanticModel semanticModel, TransformationTracker transformationTracker)
 {
     RemoveTestAttributes(root, semanticModel, transformationTracker, "TestClassAttribute");
 }
示例#15
0
 public static void Bind(CompilationUnitSyntax compilationUnit, BindingResult bindingResult)
 {
     var binder = new SymbolBinder(bindingResult, null);
     binder.BindCompilationUnit(compilationUnit);
 }
示例#16
0
        /// <summary>
        /// Compiles C# code and creates instances of object types
        /// </summary>
        /// <param name="csharp">C# code text</param>
        /// <returns>Collection of object instances</returns>
        public static IEnumerable <object> CompileClasses(string csharp)
        {
            if (string.IsNullOrEmpty(csharp))
            {
                throw new ArgumentNullException(nameof(csharp));
            }

            SyntaxTree            tree = SyntaxTree.ParseText(csharp);
            CompilationUnitSyntax root = tree.GetRoot();

            // add Using statements to syntax tree
            var system                   = Syntax.IdentifierName("System");
            var systemCollections        = Syntax.QualifiedName(system, Syntax.IdentifierName("Collections"));
            var systemCollectionsGeneric = Syntax.QualifiedName(systemCollections, Syntax.IdentifierName("Generic"));
            var systemLinq               = Syntax.QualifiedName(system, Syntax.IdentifierName("Linq"));
            var systemText               = Syntax.QualifiedName(system, Syntax.IdentifierName("Text"));
            var systemXml                = Syntax.QualifiedName(system, Syntax.IdentifierName("Xml"));

            var declaredUsings = root.Usings.Select(x => x.Name.ToString()).ToList();

            if (!declaredUsings.Contains("System"))
            {
                root = root.AddUsings(Syntax.UsingDirective(system).NormalizeWhitespace());
            }
            if (!declaredUsings.Contains("System.Collections"))
            {
                root = root.AddUsings(Syntax.UsingDirective(systemCollections).NormalizeWhitespace());
            }
            if (!declaredUsings.Contains("System.Collections.Generic"))
            {
                root = root.AddUsings(Syntax.UsingDirective(systemCollectionsGeneric).NormalizeWhitespace());
            }
            if (!declaredUsings.Contains("System.Linq"))
            {
                root = root.AddUsings(Syntax.UsingDirective(systemText).NormalizeWhitespace());
            }
            if (!declaredUsings.Contains("System.Text"))
            {
                root = root.AddUsings(Syntax.UsingDirective(systemLinq).NormalizeWhitespace());
            }
            if (!declaredUsings.Contains("System.Xml"))
            {
                root = root.AddUsings(Syntax.UsingDirective(systemXml).NormalizeWhitespace());
            }

            tree = SyntaxTree.Create(root);
            root = tree.GetRoot();

            // generate compiled object with references to commonly used .NET Framework assemblies
            var compilation = Compilation.Create("CSharp2Json",
                                                 syntaxTrees: new[] { tree },
                                                 references: new[]
            {
                new MetadataFileReference(typeof(object).Assembly.Location),          // mscorelib.dll
                new MetadataFileReference(typeof(Enumerable).Assembly.Location),      // System.Core.dll
                new MetadataFileReference(typeof(Uri).Assembly.Location),             // System.dll
                new MetadataFileReference(typeof(DataSet).Assembly.Location),         // System.Data.dll
                new MetadataFileReference(typeof(EntityKey).Assembly.Location),       // System.Data.Entity.dll
                new MetadataFileReference(typeof(XmlDocument).Assembly.Location),     // System.Xml.dll
            },
                                                 options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                                 );

            // load compiled bits into assembly
            Assembly assembly;

            using (var memoryStream = new MemoryStream())
            {
                var result = compilation.Emit(memoryStream);
                if (!result.Success)
                {
                    throw new RoslynException(result.Diagnostics);
                }

                assembly = AppDomain.CurrentDomain.Load(memoryStream.ToArray());
            }

            // instantiate object instances from assembly types
            foreach (var definedType in assembly.DefinedTypes)
            {
                Type objType = assembly.GetType(definedType.FullName);
                if (objType.BaseType?.FullName != "System.Enum")
                {
                    object instance = null;
                    try
                    {
                        instance = assembly.CreateInstance(definedType.FullName);
                    }
                    catch (MissingMethodException)
                    {
                        // no default constructor - eat the exception
                    }

                    if (instance != null)
                    {
                        yield return(instance);
                    }
                }
            }
        }
示例#17
0
        /// <summary>
        /// Add a using directive.
        /// </summary>
        /// <param name="compilationUnit">The <see cref="CompilationUnitSyntax"/>.</param>
        /// <param name="usingDirective">The <see cref="UsingDirectiveSyntax"/>.</param>
        /// <param name="semanticModel">The <see cref="SemanticModel"/>.</param>
        /// <returns>The updated <see cref="CompilationUnitSyntax"/>.</returns>
        public static CompilationUnitSyntax AddUsing(this CompilationUnitSyntax compilationUnit, UsingDirectiveSyntax usingDirective, SemanticModel semanticModel)
        {
            if (compilationUnit is null)
            {
                throw new System.ArgumentNullException(nameof(compilationUnit));
            }

            if (semanticModel is null)
            {
                throw new System.ArgumentNullException(nameof(semanticModel));
            }

            if (usingDirective is null)
            {
                throw new System.ArgumentNullException(nameof(usingDirective));
            }

            if (compilationUnit.Members.TrySingleOfType <MemberDeclarationSyntax, NamespaceDeclarationSyntax>(out var ns) &&
                UsingDirectiveComparer.IsSameOrContained(ns, usingDirective))
            {
                return(compilationUnit);
            }

            using var walker = UsingDirectiveWalker.Borrow(compilationUnit);
            if (walker.UsingDirectives.Count == 0)
            {
                if (walker.NamespaceDeclarations.TryFirst(out var namespaceDeclaration))
                {
                    if (CodeStyle.UsingDirectivesInsideNamespace(semanticModel) != CodeStyleResult.No)
                    {
                        return(compilationUnit.ReplaceNode(namespaceDeclaration, namespaceDeclaration.WithUsings(SyntaxFactory.SingletonList(usingDirective))));
                    }

                    return(compilationUnit.ReplaceNode(compilationUnit, compilationUnit.WithUsings(SyntaxFactory.SingletonList(usingDirective))));
                }

                if (compilationUnit.Members.TryFirst(out var first) &&
                    first is FileScopedNamespaceDeclarationSyntax fsns)
                {
                    if (CodeStyle.UsingDirectivesInsideNamespace(semanticModel) == CodeStyleResult.Yes)
                    {
                        return(compilationUnit.ReplaceNode(compilationUnit, compilationUnit.WithUsings(SyntaxFactory.SingletonList(usingDirective))));
                    }

                    return(compilationUnit.ReplaceNode(fsns, fsns.WithUsings(SyntaxFactory.SingletonList(usingDirective))));
                }

                return(compilationUnit);
            }

            UsingDirectiveSyntax?previous = null;

            foreach (var directive in walker.UsingDirectives)
            {
                var compare = UsingDirectiveComparer.Compare(directive, usingDirective);
                if (compare == 0)
                {
                    return(compilationUnit);
                }

                if (compare > 0)
                {
                    return(compilationUnit.InsertNodesBefore(directive, new[] { usingDirective.WithTrailingElasticLineFeed() }));
                }

                previous = directive;
            }

            if (previous is null)
            {
                throw new InvalidOperationException("Did not find node to insert after.");
            }

            return(compilationUnit.InsertNodesAfter(previous, new[] { usingDirective.WithTrailingElasticLineFeed() }));
        }
 public override void VisitCompilationUnit(CompilationUnitSyntax node)
 {
     VisitMembers(node.Members);
     //base.VisitCompilationUnit(node);
 }
示例#19
0
        private static ImmutableArray <Diagnostic> GetMisplacedReferenceDirectivesDiagnostics(CompilationUnitSyntax compilation)
        {
            // report errors for the first #r directive - they are not allowed in regular code:
            var directives = compilation.GetReferenceDirectives();

            if (directives.Count == 0)
            {
                return(ImmutableArray <Diagnostic> .Empty);
            }

            return(ImmutableArray.Create <Diagnostic>(
                       new CSDiagnostic(
                           new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_ReferenceDirectiveOnlyAllowedInScripts),
                           new SourceLocation(directives[0]))));
        }
示例#20
0
 public static IEnumerable <MemberDeclarationSyntax> GetNonNestedTypeDeclarations(CompilationUnitSyntax compilationUnit)
 {
     return(GetNonNestedTypeDeclarations(compilationUnit.Members));
 }
示例#21
0
        private void ChangeAssertCalls(CompilationUnitSyntax root, SemanticModel semanticModel, TransformationTracker transformationTracker)
        {
            Dictionary <string, string> assertMethodsToRename = new Dictionary <string, string>()
            {
                { "AreEqual", "Equal" },
                { "AreNotEqual", "NotEqual" },
                { "IsNull", "Null" },
                { "IsNotNull", "NotNull" },
                { "AreSame", "Same" },
                { "AreNotSame", "NotSame" },
                { "IsTrue", "True" },
                { "IsFalse", "False" },
                { "IsInstanceOfType", "IsAssignableFrom" },
            };

            Dictionary <SimpleNameSyntax, string> nameReplacementsForNodes      = new Dictionary <SimpleNameSyntax, string>();
            List <InvocationExpressionSyntax>     methodCallsToReverseArguments = new List <InvocationExpressionSyntax>();

            foreach (var methodCallSyntax in root.DescendantNodes().OfType <MemberAccessExpressionSyntax>())
            {
                var expressionSyntax   = methodCallSyntax.Expression;
                var expressionTypeInfo = semanticModel.GetTypeInfo(expressionSyntax);
                if (expressionTypeInfo.Type != null)
                {
                    string expressionDocID = expressionTypeInfo.Type.GetDocumentationCommentId();
                    if (IsTestNamespaceType(expressionDocID, "Assert"))
                    {
                        string newMethodName;
                        if (assertMethodsToRename.TryGetValue(methodCallSyntax.Name.Identifier.Text, out newMethodName))
                        {
                            nameReplacementsForNodes.Add(methodCallSyntax.Name, newMethodName);

                            if (newMethodName == "IsAssignableFrom" && methodCallSyntax.Parent is InvocationExpressionSyntax)
                            {
                                //  Parameter order is reversed between MSTest Assert.IsInstanceOfType and xUnit Assert.IsAssignableFrom
                                methodCallsToReverseArguments.Add((InvocationExpressionSyntax)methodCallSyntax.Parent);
                            }
                        }
                    }
                }
            }

            if (nameReplacementsForNodes.Any())
            {
                transformationTracker.AddTransformation(nameReplacementsForNodes.Keys, (transformationRoot, rewrittenNodes, originalNodeMap) =>
                {
                    return(transformationRoot.ReplaceNodes(rewrittenNodes, (originalNode, rewrittenNode) =>
                    {
                        var realOriginalNode = (SimpleNameSyntax)originalNodeMap[originalNode];
                        string newName = nameReplacementsForNodes[realOriginalNode];
                        return SyntaxFactory.ParseName(newName);
                    }));
                });

                transformationTracker.AddTransformation(methodCallsToReverseArguments, (transformationRoot, rewrittenNodes, originalNodeMap) =>
                {
                    return(transformationRoot.ReplaceNodes(rewrittenNodes, (originalNode, rewrittenNode) =>
                    {
                        var invocationExpression = (InvocationExpressionSyntax)rewrittenNode;
                        var oldArguments = invocationExpression.ArgumentList.Arguments;
                        var newArguments = new SeparatedSyntaxList <ArgumentSyntax>().AddRange(new[] { oldArguments[1], oldArguments[0] });

                        return invocationExpression.WithArgumentList(invocationExpression.ArgumentList.WithArguments(newArguments));
                    }));
                });
            }
        }
示例#22
0
 public BoundCompilationUnit(CompilationUnitSyntax syntax)
     : base(syntax)
 {
     Namespaces = new List<BoundNamespace>();
     Usings = new List<BoundUsing>();
 }
		public virtual void PostWalkCompilationUnit(CompilationUnitSyntax compilationUnitSyntax) { }
示例#24
0
        private NamespaceDeclarationSyntax GetDeclaringNamespace(List <string> containers, int indexDone, CompilationUnitSyntax compilationUnit)
        {
            foreach (var member in compilationUnit.Members)
            {
                var namespaceDeclaration = GetDeclaringNamespace(containers, 0, member);
                if (namespaceDeclaration != null)
                {
                    return(namespaceDeclaration);
                }
            }

            return(null);
        }
示例#25
0
        private void ParseStatements(SyntaxTree syntaxTree, CompilationUnitSyntax syntaxRoot, SemanticModel model)
        {
            var renderMethod = syntaxRoot.GetRenderMethod();
            var statements   = renderMethod.Body.Statements.ToList();

            foreach (var statement in statements)
            {
                SwitchExtensions.Switch(statement, () => statement.GetType().Name,

                                        SwitchExtensions.Case <ExpressionStatementSyntax>("ExpressionStatementSyntax", (expressionStatement) =>
                {
                    var expression = expressionStatement.Expression;

                    SwitchExtensions.Switch(expression, () => expression.GetType().Name,

                                            SwitchExtensions.Case <AssignmentExpressionSyntax>("AssignmentExpressionSyntax", (assignmentExpression) =>
                    {
                        var left  = assignmentExpression.Left;
                        var right = assignmentExpression.Right;
                        AssignmentNode assignmentNode = null;

                        SwitchExtensions.Switch(left, () => left.GetType().Name,

                                                SwitchExtensions.Case <ElementAccessExpressionSyntax>("ElementAccessExpressionSyntax", (elementAccessExpression) =>
                        {
                            var name    = ((IdentifierNameSyntax)elementAccessExpression.Expression).Identifier.Text;
                            var arg     = elementAccessExpression.ArgumentList.Arguments.Single();
                            var literal = (LiteralExpressionSyntax)arg.Expression;
                            var key     = (string)literal.Token.Value;

                            if (name == "ViewData")
                            {
                                var viewDataNode = new ViewDataNode(null, key, assignmentExpression.ToFullString());

                                viewDataNode.Left = key;

                                assignmentNode = viewDataNode;
                            }
                            else
                            {
                                DebugUtils.Break();
                            }

                            DebugUtils.NoOp();
                        }),
                                                SwitchExtensions.Case <MemberAccessExpressionSyntax>("MemberAccessExpressionSyntax", (memberAccessExpressionSyntax) =>
                        {
                            var name     = ((IdentifierNameSyntax)memberAccessExpressionSyntax.Expression).Identifier.Text;
                            var property = memberAccessExpressionSyntax.Name.Identifier.Text;

                            if (name == "ViewBag")
                            {
                                var viewBagNode = new ViewBagNode(null, property, assignmentExpression.ToFullString());

                                viewBagNode.Left = name;

                                assignmentNode = viewBagNode;
                            }
                            else
                            {
                                DebugUtils.Break();
                            }

                            DebugUtils.NoOp();
                        }),
                                                SwitchExtensions.Case <IdentifierNameSyntax>("IdentifierNameSyntax", (identifierName) =>
                        {
                            var name         = identifierName.Identifier.Text;
                            var propertyNode = new PropertyNode(null, assignmentExpression.ToFullString());

                            propertyNode.Left = name;

                            assignmentNode = propertyNode;

                            DebugUtils.NoOp();
                        }),
                                                SwitchExtensions.CaseElse(() =>
                        {
                            var a = left;
                            var t = left.GetType().Name;

                            // implementation here or throw error

                            DebugUtils.Break();
                        })
                                                );

                        SwitchExtensions.Switch(right, () => right.GetType().Name,

                                                SwitchExtensions.Case <LiteralExpressionSyntax>("LiteralExpressionSyntax", (literalExpression) =>
                        {
                            assignmentNode.Right = literalExpression.Token.Value;
                        }),
                                                SwitchExtensions.CaseElse(() =>
                        {
                            var a = right;
                            var t = right.GetType().Name;

                            // implementation here or throw error

                            DebugUtils.Break();
                        })
                                                );

                        assignmentNode.Right = right;

                        this.AddChild(assignmentNode);
                    }),
                                            SwitchExtensions.CaseElse(() =>
                    {
                        var a = expression;
                        var t = expression.GetType().Name;

                        // implementation here or throw error

                        DebugUtils.Break();
                    })
                                            );
                }),
                                        SwitchExtensions.Case <LocalDeclarationStatementSyntax>("LocalDeclarationStatementSyntax", (localDeclarationStatement) =>
                {
                    var variable     = localDeclarationStatement.Declaration.Variables.Single();
                    var name         = variable.Identifier.Text;
                    var initializer  = variable.Initializer;
                    var variableNode = new VariableNode(name, null, localDeclarationStatement.ToFullString());
                    ModelInvocationNode modelInvocationNode = null;

                    SwitchExtensions.Switch(initializer, () => initializer.GetType().Name,

                                            SwitchExtensions.Case <EqualsValueClauseSyntax>("EqualsValueClauseSyntax", (equalsValueClause) =>
                    {
                        var value = equalsValueClause.Value;

                        if (value is InvocationExpressionSyntax)
                        {
                            var invocationExpression = (InvocationExpressionSyntax)value;

                            if (invocationExpression.Expression is MemberAccessExpressionSyntax)
                            {
                                var memberAccessExpression = (MemberAccessExpressionSyntax)invocationExpression.Expression;

                                if (memberAccessExpression.Expression is IdentifierNameSyntax && ((IdentifierNameSyntax)memberAccessExpression.Expression).Identifier.Text == "Model")
                                {
                                    if (memberAccessExpression.Name is GenericNameSyntax)
                                    {
                                        var identifierName = (GenericNameSyntax)memberAccessExpression.Name;
                                        var methodName     = identifierName.Identifier.Text;
                                        var typeArguments  = identifierName.TypeArgumentList.Arguments;

                                        modelInvocationNode = new ModelInvocationNode(null, invocationExpression.ToFullString(), variableNode, methodName, typeArguments);
                                    }
                                    else
                                    {
                                        DebugUtils.Break();
                                    }
                                }
                                else
                                {
                                    DebugUtils.Break();
                                }
                            }
                            else
                            {
                                DebugUtils.Break();
                            }
                        }
                        else
                        {
                            DebugUtils.Break();
                        }

                        variableNode.Right = value;
                    }),
                                            SwitchExtensions.CaseElse(() =>
                    {
                        var a = initializer;
                        var t = initializer.GetType().Name;

                        // implementation here or throw error

                        DebugUtils.Break();
                    })
                                            );

                    this.AddChild(variableNode);

                    if (modelInvocationNode != null)
                    {
                        variableNode.AddChild(modelInvocationNode);
                    }

                    DebugUtils.NoOp();
                }),
                                        SwitchExtensions.CaseElse(() =>
                {
                    var a = statement;
                    var t = statement.GetType().Name;

                    // implementation here or throw error

                    DebugUtils.Break();
                })
                                        );
            }
        }
示例#26
0
        protected override IList <ModificationBuilder <CSharpSyntaxNode> > CreateModifications(WorkflowExecutionContext context, CompilationUnitSyntax rootUnit)
        {
            var    model       = context.GetVariable <object>("Model");
            string templateDir = context.GetVariable <string>(VariableNames.TemplateDirectory);

            string usingText = TextGenerator.GenerateByTemplateName(templateDir, "WebAutoMapperProfile_Using", model);

            string contents = TextGenerator.GenerateByTemplateName(templateDir, "WebAutoMapperProfile_CreateMap", model);

            return(new List <ModificationBuilder <CSharpSyntaxNode> >
            {
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <UsingDirectiveSyntax>().Last().GetEndLine(),
                    usingText,
                    modifyCondition: root => root.NotContains(usingText)
                    ),
                new InsertionBuilder <CSharpSyntaxNode>(
                    root => root.Descendants <ConstructorDeclarationSyntax>().Single().GetEndLine(),
                    contents,
                    modifyCondition: root => root.Descendants <ConstructorDeclarationSyntax>().Single().NotContains(contents)
                    )
            });
        }
        private static bool TryGetExternAliasString(INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, CompilationUnitSyntax root, out string externAliasString)
        {
            externAliasString = null;
            var metadataReference = semanticModel.Compilation.GetMetadataReference(namespaceSymbol.ContainingAssembly);

            if (metadataReference == null)
            {
                return(false);
            }

            var aliases = metadataReference.Properties.Aliases;

            if (aliases.IsEmpty)
            {
                return(false);
            }

            aliases = metadataReference.Properties.Aliases.Where(a => a != MetadataReferenceProperties.GlobalAlias).ToImmutableArray();
            if (!aliases.Any())
            {
                return(false);
            }

            externAliasString = aliases.First();
            return(ShouldAddExternAlias(aliases, root));
        }
示例#28
0
 internal TestCreator(SyntaxNode root)
 {
     _unit = new Unit(root);
     _test = SyntaxFactory.CompilationUnit();
 }
        private static bool ShouldAddStaticUsing(string usingDirective, CompilationUnitSyntax root)
        {
            var staticUsings = root.Usings.Where(u => u.StaticKeyword.IsKind(SyntaxKind.StaticKeyword));

            return(!staticUsings.Any(u => u.Name.ToString() == usingDirective));
        }
示例#30
0
 public DummySyntaxTree()
 {
     _node = this.CloneNodeAsRoot(SyntaxFactory.ParseCompilationUnit(string.Empty));
 }
        public static void RegisterCodeFix(CodeFixContext context, Diagnostic diagnostic, CompilationUnitSyntax compilationUnitSyntax)
        {
            var codeAction = CodeAction.Create(
                "Add InternalsVisibleTo attribute",
                cancellationToken => RefactorAsync(context.Document, compilationUnitSyntax, cancellationToken),
                diagnostic.Id);

            context.RegisterCodeFix(codeAction, context.Diagnostics);
        }
示例#32
0
        private static void Main(string[] args)
        {
            var console      = SyntaxFactory.IdentifierName("Console");
            var writeline    = SyntaxFactory.IdentifierName("WriteLine");
            var memberaccess = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, console, writeline);

            var argument     = SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("A")));
            var argumentList = SyntaxFactory.SeparatedList(new[] { argument });

            var writeLineCall =
                SyntaxFactory.ExpressionStatement(
                    SyntaxFactory.InvocationExpression(memberaccess,
                                                       SyntaxFactory.ArgumentList(argumentList)));

            string assemblyName = $"cls{Guid.NewGuid():N}".ToUpper(CultureInfo.InvariantCulture);


            PredefinedTypeSyntax voidTypeSyntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword));

            //MethodDeclarationSyntax method = SyntaxFactory.MethodDeclaration(voidTypeSyntax, "Main")
            //	.WithBody(SyntaxFactory.Block());

            MethodDeclarationSyntax methodDeclaration = SyntaxFactory.MethodDeclaration
                                                        (
                attributeLists: SyntaxFactory.List <AttributeListSyntax>(),                 //new Microsoft.CodeAnalysis.SyntaxList<Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax>(),
                modifiers: SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword)),
                returnType: SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)),
                explicitInterfaceSpecifier: (Microsoft.CodeAnalysis.CSharp.Syntax.ExplicitInterfaceSpecifierSyntax)null,
                identifier: SyntaxFactory.Identifier("Main"),
                typeParameterList: (Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax)null,
                parameterList: SyntaxFactory.ParameterList(),
                constraintClauses: SyntaxFactory.List <TypeParameterConstraintClauseSyntax>(),
                body: SyntaxFactory.Block(),                 //(Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax)null,
                expressionBody: (Microsoft.CodeAnalysis.CSharp.Syntax.ArrowExpressionClauseSyntax)null,
                semicolonToken: SyntaxFactory.Token(SyntaxKind.None)
                                                        ).AddBodyStatements(writeLineCall);

            SyntaxList <AttributeListSyntax> attributeLists = SyntaxFactory.List <AttributeListSyntax>();
            SyntaxTokenList         modifiers               = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.InternalKeyword));
            SyntaxToken             classIdentifier         = SyntaxFactory.Identifier("Program");
            TypeParameterListSyntax typeParameterListSyntax = SyntaxFactory.TypeParameterList(default(SeparatedSyntaxList <TypeParameterSyntax>));
            BaseListSyntax          baseListSyntax          = SyntaxFactory.BaseList(default(SeparatedSyntaxList <BaseTypeSyntax>));
            SyntaxList <TypeParameterConstraintClauseSyntax> typeParameterConstraintClauseSyntaxs = SyntaxFactory.List <TypeParameterConstraintClauseSyntax>();

            //SyntaxFactory.ExpressionStatement(
            //SyntaxFactory.InvocationExpression()


            #region Class Defenition

            //SyntaxFactory.ClassDeclaration
            //(
            //	attributeLists: new Microsoft.CodeAnalysis.SyntaxList<Microsoft.CodeAnalysis.CSharp.Syntax.AttributeListSyntax>(),
            //	modifiers: new SyntaxTokenList(),
            //	keyword: SyntaxFactory.Token(SyntaxKind.ClassKeyword),
            //	identifier: SyntaxFactory.Identifier(""),
            //	typeParameterList: (Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterListSyntax)null,
            //	baseList: (Microsoft.CodeAnalysis.CSharp.Syntax.BaseListSyntax)null,
            //	constraintClauses: new Microsoft.CodeAnalysis.SyntaxList<Microsoft.CodeAnalysis.CSharp.Syntax.TypeParameterConstraintClauseSyntax>(),
            //	openBraceToken: SyntaxFactory.Token(SyntaxKind.OpenBraceToken),
            //	members: new Microsoft.CodeAnalysis.SyntaxList<Microsoft.CodeAnalysis.CSharp.Syntax.MemberDeclarationSyntax>(),
            //	closeBraceToken: SyntaxFactory.Token(SyntaxKind.CloseBraceToken),
            //	semicolonToken: new Microsoft.CodeAnalysis.SyntaxToken()
            //);

            #endregion

            var classDeclaration = SyntaxFactory.ClassDeclaration
                                   (
                attributeLists: attributeLists,
                modifiers: modifiers,
                keyword: SyntaxFactory.Token(SyntaxKind.ClassKeyword),
                identifier: SyntaxFactory.Identifier("Program"),
                typeParameterList: null,                                 //typeParameterListSyntax,
                baseList: null,                                          //baseListSyntax,
                constraintClauses: typeParameterConstraintClauseSyntaxs, //default(SyntaxList<TypeParameterConstraintClauseSyntax>),
                openBraceToken: SyntaxFactory.Token(SyntaxKind.OpenBraceToken),
                members: default(SyntaxList <MemberDeclarationSyntax>),
                closeBraceToken: SyntaxFactory.Token(SyntaxKind.CloseBraceToken),
                semicolonToken: SyntaxFactory.Token(SyntaxKind.None)
                                   )
                                   .AddMembers(methodDeclaration); //.AddModifiers(SyntaxFactory.Token(SyntaxKind.InternalKeyword));

            NameSyntax namespaceName = SyntaxFactory.IdentifierName(assemblyName);

            NamespaceDeclarationSyntax namespaceDeclaration = SyntaxFactory.NamespaceDeclaration
                                                              (
                SyntaxFactory.Token(SyntaxKind.NamespaceKeyword),
                namespaceName,
                SyntaxFactory.Token(SyntaxKind.OpenBraceToken),
                default(SyntaxList <ExternAliasDirectiveSyntax>),
                default(SyntaxList <UsingDirectiveSyntax>),
                default(SyntaxList <MemberDeclarationSyntax>),
                SyntaxFactory.Token(SyntaxKind.CloseBraceToken),
                SyntaxFactory.Token(SyntaxKind.None)
                                                              )
                                                              .AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System")))
                                                              .AddMembers(classDeclaration);


            CompilationUnitSyntax compilationUnitSyntax = SyntaxFactory.CompilationUnit()
                                                          .AddMembers(namespaceDeclaration).NormalizeWhitespace("    ");

            SyntaxTree syntaxTree = SyntaxFactory.SyntaxTree(compilationUnitSyntax);


            MetadataReference[] references =
            {
                MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location)
            };

            Compilation compilation = CSharpCompilation.Create
                                      (
                assemblyName: assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.ConsoleApplication /*, mainTypeName: assemblyName + ".Program", usings: new[] { "System" }*/)
                                      );

            EmitResult result;
            byte[]     bytes;

            using (var ms = new MemoryStream())
            {
                result = compilation.Emit(ms);
                bytes  = ms.ToArray();
            }

            if (result.Success)
            {
                Assembly assembly = Assembly.Load(bytes);
                assembly.EntryPoint.Invoke(null, /*new object[] { new[] { Environment.CurrentDirectory } }*/ null);
            }

            var diagnostics = result.Diagnostics.ToArray();
        }
 public override bool TryGetRoot(out CompilationUnitSyntax root)
 {
     root = this.node;
     return true;
 }
示例#34
0
            public SyntaxTree ReplaceVars(SyntaxTree syntaxTree, IEnumerable <JObject> ma_values, IEnumerable <JObject> id_values, IEnumerable <JObject> method_values, IEnumerable <JObject> ea_values)
            {
                var memberAccessToParamName  = new Dictionary <string, string>();
                var methodCallToParamName    = new Dictionary <string, string>();
                var elementAccessToParamName = new Dictionary <string, string>();

                CompilationUnitSyntax root = syntaxTree.GetCompilationUnitRoot();

                // 1. Replace all this.a occurrences with this_a_ABDE
                root = root.ReplaceNodes(memberAccesses, (maes, _) =>
                {
                    string ma_str = maes.ToString();
                    if (!memberAccessToParamName.TryGetValue(ma_str, out string id_name))
                    {
                        // Generate a random suffix
                        string suffix = Guid.NewGuid().ToString().Substring(0, 5);
                        string prefix = regexForReplaceVarName.Replace(ma_str, "_");
                        id_name       = $"{prefix}_{suffix}";

                        memberAccessToParamName[ma_str] = id_name;
                    }

                    return(SyntaxFactory.IdentifierName(id_name));
                });

                // 1.1 Replace all this.a() occurrences with this_a_ABDE
                root = root.ReplaceNodes(methodCalls, (m, _) =>
                {
                    string iesStr = m.ToString();
                    if (!methodCallToParamName.TryGetValue(iesStr, out string id_name))
                    {
                        // Generate a random suffix
                        string suffix = Guid.NewGuid().ToString().Substring(0, 5);
                        string prefix = regexForReplaceVarName.Replace(iesStr, "_");
                        id_name       = $"{prefix}_{suffix}";
                        methodCallToParamName[iesStr] = id_name;
                    }

                    return(SyntaxFactory.IdentifierName(id_name));
                });

                // 1.2 Replace all this.a[x] occurrences with this_a_ABDE
                root = root.ReplaceNodes(elementAccess, (ea, _) =>
                {
                    string eaStr = ea.ToString();
                    if (!elementAccessToParamName.TryGetValue(eaStr, out string id_name))
                    {
                        // Generate a random suffix
                        string suffix = Guid.NewGuid().ToString().Substring(0, 5);
                        string prefix = eaStr.Trim().Replace(".", "_").Replace("[", "_").Replace("]", "_");
                        id_name       = $"{prefix}_{suffix}";
                        elementAccessToParamName[eaStr] = id_name;
                    }

                    return(SyntaxFactory.IdentifierName(id_name));
                });

                var localsSet = new HashSet <string>();

                // 2. For every unique member ref, add a corresponding method param
                if (ma_values != null)
                {
                    foreach ((MemberAccessExpressionSyntax maes, JObject value) in memberAccesses.Zip(ma_values))
                    {
                        string node_str = maes.ToString();
                        if (!memberAccessToParamName.TryGetValue(node_str, out string id_name))
                        {
                            throw new Exception($"BUG: Expected to find an id name for the member access string: {node_str}");
                        }
                        memberAccessValues[id_name] = value;
                        AddLocalVariableWithValue(id_name, value);
                    }
                    // do not replace memberAccesses that were already replaced
                    memberAccesses = new List <MemberAccessExpressionSyntax>();
                }

                if (id_values != null)
                {
                    foreach ((IdentifierNameSyntax idns, JObject value) in identifiers.Zip(id_values))
                    {
                        AddLocalVariableWithValue(idns.Identifier.Text, value);
                    }
                }

                if (method_values != null)
                {
                    foreach ((InvocationExpressionSyntax ies, JObject value) in methodCalls.Zip(method_values))
                    {
                        string node_str = ies.ToString();
                        if (!methodCallToParamName.TryGetValue(node_str, out string id_name))
                        {
                            throw new Exception($"BUG: Expected to find an id name for the member access string: {node_str}");
                        }
                        AddLocalVariableWithValue(id_name, value);
                    }
                }

                if (ea_values != null)
                {
                    foreach ((ElementAccessExpressionSyntax eas, JObject value) in elementAccess.Zip(ea_values))
                    {
                        string node_str = eas.ToString();
                        if (!elementAccessToParamName.TryGetValue(node_str, out string id_name))
                        {
                            throw new Exception($"BUG: Expected to find an id name for the element access string: {node_str}");
                        }
                        AddLocalVariableWithValue(id_name, value);
                    }
                }

                return(syntaxTree.WithRootAndOptions(root, syntaxTree.Options));

                void AddLocalVariableWithValue(string idName, JObject value)
                {
                    if (localsSet.Contains(idName))
                    {
                        return;
                    }
                    localsSet.Add(idName);
                    variableDefinitions.Add(ConvertJSToCSharpLocalVariableAssignment(idName, value));
                }
            }
示例#35
0
 public static string GetNamespace(this CompilationUnitSyntax node)
 {
     return("");
 }
示例#36
0
 public CompilationUnitTranslation(CompilationUnitSyntax syntax, SyntaxTranslation parent) : base(syntax, null)
 {
     //Compilation = compilation;
     //this.semanticModel = semanticModel;
     Members = syntax.Members.Get <MemberDeclarationSyntax, MemberDeclarationTranslation>(this);
 }
示例#37
0
        public static CompilationUnitSyntax CompilationUnit(IEnumerable<ExternAliasDirectiveSyntax> externs = null, IEnumerable<UsingDirectiveSyntax> usings = null, IEnumerable<AttributeListSyntax> attributeLists = null, IEnumerable<MemberDeclarationSyntax> members = null)
        {
            var result = new CompilationUnitSyntax();

            if (externs != null)
                result.Externs.AddRange(externs);
            if (usings != null)
                result.Usings.AddRange(usings);
            if (attributeLists != null)
                result.AttributeLists.AddRange(attributeLists);
            if (members != null)
                result.Members.AddRange(members);

            return result;
        }
示例#38
0
 public SyntaxAnalyserProgramCode(SyntaxTree syntaxTreeProgramCode)
 {
     rootSyntaxTreeCode = (CompilationUnitSyntax)syntaxTreeProgramCode.GetRoot();
 }
		// CompilationUnitSyntax
		public virtual bool WalkCompilationUnit(CompilationUnitSyntax compilationUnitSyntax) { return DefaultWalk(compilationUnitSyntax); }
示例#40
0
 /// <summary>
 /// Not sure if this is good idea
 /// </summary>
 /// <param name="declarationInfo"></param>
 private void VerifyDeclarations(CompilationUnitSyntax node, params DeclarationInfo[] declarationInfo)
 {
     Assert.AreEqual(declarationInfo.Length, node.Declarations.Count);
     var actual = node.Declarations;
     int idx = 0;
     foreach (var exp in declarationInfo)
     {
         var mem = actual[idx++];
         Assert.AreEqual(exp.Kind, mem.Kind);
     }
 }
示例#41
0
        /// <summary>
        /// Checks the <paramref name="compilationUnitDeclaration"/> for syntax and semantic
        /// errors and returns an empty enumerable if any are found.
        /// </summary>
        public IEnumerable <ClousotOutput> AnalyzeMeAUnit(
            Microsoft.CodeAnalysis.Document document,
            CompilationUnitSyntax compilationUnitDeclaration,
            CancellationToken cancellationToken,
            ClousotOptions options,
            string[] extraOptions,
            bool showOnlyAnswersToAskClousot = false
            )
        {
            if (options == null)
            {
                options = new ClousotOptions();
            }

            // Don't do anything if there are syntactic errors.
            if (compilationUnitDeclaration.ContainsDiagnostics)
            {
                yield break;
            }

            var semanticModel = document.GetSemanticModel(cancellationToken);

            // Don't do anything if there are semantic errors.
            var diagnostics = semanticModel.GetDiagnostics(cancellationToken);

            if (diagnostics.Any(d => d.Info.Severity == DiagnosticSeverity.Error || d.Info.IsWarningAsError))
            {
                yield break;
            }

            this.host = new ClousotGlueHost((document.Project).MetadataReferences);

            this.sourceLocationProvider = new SourceLocationProvider();
            string             exceptionMessage = null;
            IAssemblyReference ar = null;

            try {
                // Constructs a full metadata model for the assembly the semantic model is from
                var transformer = new NodeVisitor(this.host, semanticModel, sourceLocationProvider);

                // Constructs the method bodies all of the methods in the compilation unit
                // var tree = document.GetSyntaxTree(cancellationToken);
                var tree2 = transformer.Visit(compilationUnitDeclaration);
                ar = tree2 as IAssemblyReference;
            } catch (ConverterException e) {
                exceptionMessage = e.Message;
            } catch (OperationCanceledException) {
                // just return nothing
                yield break;
            }
            if (exceptionMessage != null)
            {
                yield return(new ClousotOutput(null, exceptionMessage, compilationUnitDeclaration.GetFirstToken().Span, null, (ICodeAction)null, ClousotOutput.ExtraInfo.None));

                yield break;
            }

            var spanToMethodMap = MethodSpanFinder.GetMethodSpans(compilationUnitDeclaration);

            lock (this) { // Clousot is single-threaded
                var cciProvider = Microsoft.Cci.Analysis.CciILCodeProvider.CreateCodeProvider(host);
                var unit        = ar;
                this.host.RegisterUnit(unit.ResolvedUnit);
                cciProvider.MetaDataDecoder.RegisterSourceLocationProvider(unit, sourceLocationProvider);
                var metadataDecoder = cciProvider.MetaDataDecoder;
                var contractDecoder = cciProvider.ContractDecoder;

                var defaultargs = new string[] {
                    "-nonnull",
                    "-bounds",
                    "-arithmetic",
                    "-sortwarns:-",
                    //"-arrays",
                    "-cache",
                    //"-suggest=methodensures",
                    "-suggest=propertyensures",
                    "-suggest=objectinvariants",
                    //"-infer=requires",
                    //"-infer=objectinvariants",
                    //"-clearcache",
                    //"-prefrompost"
                };
                var codefixesargs = new string[] {
                    "-nonnull",
                    "-bounds",
                    "-arithmetic",
                    "-suggest=codefixes",
                    "-cache",
                    "-libpaths:\"c:\\program files (x86)\\Microsoft\\Contracts\\Contracts\\.NetFramework\\v4.0\"",
                    //"-suggest=methodensures",
                    "-suggest=objectinvariants",
                    "-infer=objectinvariants",
                    "-suggest=assumes",
                    "-premode=backwards",
                };
                var args = codefixesargs;
                if (extraOptions != null)
                {
                    args = args.Concat(extraOptions).ToArray();
                }

                var w = (options == null || String.IsNullOrWhiteSpace(options.WarningLevel))
          ? "low"
          : options.WarningLevel;

                var warninglevel = String.Format("-warninglevel={0}", w);
                var x            = new string[] { warninglevel, };
                args = args.Concat(x).ToArray();

                if (options != null)
                {
                    var otherOptions = options.OtherOptions;
                    if (!String.IsNullOrWhiteSpace(otherOptions))
                    {
                        var otherOpts = otherOptions.Split(' ');
                        args = args.Concat(otherOpts).ToArray();
                    }
                }

                this.analysisResults = new List <ClousotOutput>();
                var output         = new RoslynOutput(showOnlyAnswersToAskClousot, this.analysisResults, document, spanToMethodMap, null);
                var methodAnalyzer = Clousot.GetIndividualMethodAnalyzer(metadataDecoder, contractDecoder, args, output,
                                                                         new[] { this.cacheFactory });
                foreach (var path in methodAnalyzer.Options.libPaths)
                {
                    host.AddLibPath(path);
                }
                methodAnalyzer.AnalyzeAssembly(ar);
            }

            foreach (var result in this.analysisResults)
            {
                yield return(result);
            }
        }
示例#42
0
 private BoundCompilationUnit BindCompilationUnit(CompilationUnitSyntax compilationUnit)
 {
     return new BoundCompilationUnit(BindTopLevelDeclarations(compilationUnit.Declarations, null));
 }
            public SyntaxTree ReplaceVars(SyntaxTree syntaxTree, IEnumerable <JObject> ma_values, IEnumerable <JObject> id_values)
            {
                CompilationUnitSyntax root  = syntaxTree.GetCompilationUnitRoot();
                var memberAccessToParamName = new Dictionary <string, string>();

                // 1. Replace all this.a occurrences with this_a_ABDE
                root = root.ReplaceNodes(memberAccesses, (maes, _) =>
                {
                    string ma_str = maes.ToString();
                    if (!memberAccessToParamName.TryGetValue(ma_str, out string id_name))
                    {
                        // Generate a random suffix
                        string suffix = Guid.NewGuid().ToString().Substring(0, 5);
                        string prefix = ma_str.Trim().Replace(".", "_");
                        id_name       = $"{prefix}_{suffix}";

                        memberAccessToParamName[ma_str] = id_name;
                    }

                    return(SyntaxFactory.IdentifierName(id_name));
                });

                var paramsSet = new HashSet <string>();

                // 2. For every unique member ref, add a corresponding method param
                foreach ((MemberAccessExpressionSyntax maes, JObject value) in memberAccesses.Zip(ma_values))
                {
                    string node_str = maes.ToString();
                    if (!memberAccessToParamName.TryGetValue(node_str, out string id_name))
                    {
                        throw new Exception($"BUG: Expected to find an id name for the member access string: {node_str}");
                    }

                    root = UpdateWithNewMethodParam(root, id_name, value);
                }

                foreach ((IdentifierNameSyntax idns, JObject value) in identifiers.Zip(id_values))
                {
                    root = UpdateWithNewMethodParam(root, idns.Identifier.Text, value);
                }

                return(syntaxTree.WithRootAndOptions(root, syntaxTree.Options));

                CompilationUnitSyntax UpdateWithNewMethodParam(CompilationUnitSyntax root, string id_name, JObject value)
                {
                    var classDeclaration = root.Members.ElementAt(0) as ClassDeclarationSyntax;
                    var method           = classDeclaration.Members.ElementAt(0) as MethodDeclarationSyntax;

                    if (paramsSet.Contains(id_name))
                    {
                        // repeated member access expression
                        // eg. this.a + this.a
                        return(root);
                    }

                    argValues.Add(ConvertJSToCSharpType(value));

                    MethodDeclarationSyntax updatedMethod = method.AddParameterListParameters(
                        SyntaxFactory.Parameter(
                            SyntaxFactory.Identifier(id_name))
                        .WithType(SyntaxFactory.ParseTypeName(GetTypeFullName(value))));

                    paramsSet.Add(id_name);
                    root = root.ReplaceNode(method, updatedMethod);

                    return(root);
                }
            }
示例#44
0
 public static string GetTextUtf8(this CompilationUnitSyntax unit)
 => unit.GetText(Encoding.UTF8).ToString();
示例#45
0
 public virtual void VisitCompilationUnit(CompilationUnitSyntax node)
 {
 }
示例#46
0
 private void RemoveContractsRequiredAttributes(CompilationUnitSyntax root, SemanticModel semanticModel, TransformationTracker transformationTracker)
 {
     RemoveTestAttributes(root, semanticModel, transformationTracker, "ContractsRequiredAttribute");
 }
示例#47
0
 public virtual void VisitCompilationUnit(CompilationUnitSyntax node)
 {
     DefaultVisit(node);
 }
示例#48
0
 private static SyntaxList <UsingDirectiveSyntax> GetAllUsingDirectives(
     this CompilationUnitSyntax compilation,
     NamespaceDeclarationSyntax ns)
 => ns != null
         ? compilation.Usings.AddRange(ns.Usings)
         : compilation.Usings;
示例#49
0
        private static void TestRoundTripping(CompilationUnitSyntax node, string text, bool disallowErrors = true)
        {
            Assert.That(node, Is.Not.Null);
            var fullText = node.ToFullString();
            Assert.That(fullText, Is.EqualTo(text));

            if (disallowErrors)
                Assert.That(node.GetDiagnostics(), Is.Empty);
            else
                Assert.That(node.GetDiagnostics(), Is.Not.Empty);
        }
示例#50
0
        public static CompilationUnitSyntax SortUsingDirectives(this CompilationUnitSyntax compilation)
        {
            var ns = compilation.GetNamespaceDeclaration();

            return(compilation.SortUsingDirectives(ref ns));
        }
示例#51
0
 public override void VisitCompilationUnit(CompilationUnitSyntax node)
 {
     foreach (var childNode in node.Declarations)
         Visit(childNode);
 }
        private async Task <CompilationUnitSyntax> AddImportWorkerAsync(
            Document document, CompilationUnitSyntax root, SyntaxNode contextNode,
            INamespaceOrTypeSymbol namespaceOrTypeSymbol, bool placeSystemNamespaceFirst, CancellationToken cancellationToken)
        {
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var simpleUsingDirective      = GetUsingDirective(root, namespaceOrTypeSymbol, semanticModel, fullyQualify: false);
            var externAliasUsingDirective = GetExternAliasUsingDirective(root, namespaceOrTypeSymbol, semanticModel);

            if (externAliasUsingDirective != null)
            {
                root = root.AddExterns(
                    externAliasUsingDirective
                    .WithAdditionalAnnotations(Formatter.Annotation));
            }

            if (simpleUsingDirective == null)
            {
                return(root);
            }

            // Because of the way usings can be nested inside of namespace declarations,
            // we need to check if the usings must be fully qualified so as not to be
            // ambiguous with the containing namespace.
            if (UsingsAreContainedInNamespace(contextNode))
            {
                // When we add usings we try and place them, as best we can, where the user
                // wants them according to their settings.  This means we can't just add the fully-
                // qualified usings and expect the simplifier to take care of it, the usings have to be
                // simplified before we attempt to add them to the document.
                // You might be tempted to think that we could call
                //   AddUsings -> Simplifier -> SortUsings
                // But this will clobber the users using settings without asking.  Instead we create a new
                // Document and check if our using can be simplified.  Worst case we need to back out the
                // fully qualified change and reapply with the simple name.
                var fullyQualifiedUsingDirective = GetUsingDirective(root, namespaceOrTypeSymbol, semanticModel, fullyQualify: true);
                var newRoot = root.AddUsingDirective(
                    fullyQualifiedUsingDirective, contextNode, placeSystemNamespaceFirst,
                    Formatter.Annotation);
                var newUsing = newRoot
                               .DescendantNodes().OfType <UsingDirectiveSyntax>()
                               .Where(uds => uds.IsEquivalentTo(fullyQualifiedUsingDirective, topLevel: true))
                               .Single();
                newRoot = newRoot.TrackNodes(newUsing);
                var documentWithSyntaxRoot = document.WithSyntaxRoot(newRoot);
                var options            = document.Project.Solution.Workspace.Options;
                var simplifiedDocument = await Simplifier.ReduceAsync(documentWithSyntaxRoot, newUsing.Span, options, cancellationToken).ConfigureAwait(false);

                newRoot = (CompilationUnitSyntax)await simplifiedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                var simplifiedUsing = newRoot.GetCurrentNode(newUsing);
                if (simplifiedUsing.Name.IsEquivalentTo(newUsing.Name, topLevel: true))
                {
                    // Not fully qualifying the using causes to refer to a different namespace so we need to keep it as is.
                    return((CompilationUnitSyntax)await documentWithSyntaxRoot.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false));
                }
                else
                {
                    // It does not matter if it is fully qualified or simple so lets return the simple name.
                    return(root.AddUsingDirective(
                               simplifiedUsing.WithoutTrivia().WithoutAnnotations(), contextNode, placeSystemNamespaceFirst,
                               Formatter.Annotation));
                }
            }
            else
            {
                // simple form
                return(root.AddUsingDirective(
                           simpleUsingDirective, contextNode, placeSystemNamespaceFirst,
                           Formatter.Annotation));
            }
        }