Esempio n. 1
0
		private static void PrintMethodContentViaSemanticModel(SyntaxTree tree)
		{
			Console.Out.WriteLine(nameof(Program.PrintMethodContentViaSemanticModel));
			var compilation = CSharpCompilation.Create(
				"MethodContent",
				syntaxTrees: new[] { tree },
				references: new[]
				{
					MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
				});

			var model = compilation.GetSemanticModel(tree, true);

			var methods = tree.GetRoot().DescendantNodes(_ => true)
				.OfType<MethodDeclarationSyntax>();

			foreach (var method in methods)
			{
				var methodInfo = model.GetDeclaredSymbol(method) as IMethodSymbol;
				var parameters = new List<string>();

				foreach (var parameter in methodInfo.Parameters)
				{
					var isRef = parameter.RefKind == RefKind.Ref ? "ref " : string.Empty;
					parameters.Add($"{isRef}{parameter.Type.Name} {parameter.Name}");
				}

				Console.Out.WriteLine(
					$"{methodInfo.Name}({string.Join(", ", parameters)})");
			}
		}
 public static void DumpSyntaxTree(SyntaxTree syntaxTree, string declarationFilter, string description)
 {
     if (syntaxTree != null)
     {
         PanelManager.DisplayControl(new SyntaxTreePanel(syntaxTree, declarationFilter), description ?? "Syntax Tree");
     }
 }
            public AbstractIndenter(
                ISyntaxFactsService syntaxFacts,
                SyntaxTree syntaxTree,
                IEnumerable<IFormattingRule> rules,
                OptionSet optionSet,
                TextLine lineToBeIndented,
                CancellationToken cancellationToken)
            {
                var syntaxRoot = syntaxTree.GetRoot(cancellationToken);

                this._syntaxFacts = syntaxFacts;
                this.OptionSet = optionSet;
                this.Tree = syntaxTree;
                this.LineToBeIndented = lineToBeIndented;
                this.TabSize = this.OptionSet.GetOption(FormattingOptions.TabSize, syntaxRoot.Language);
                this.CancellationToken = cancellationToken;

                this.Rules = rules;
                this.Finder = new BottomUpBaseIndentationFinder(
                         new ChainedFormattingRules(this.Rules, OptionSet),
                         this.TabSize,
                         this.OptionSet.GetOption(FormattingOptions.IndentationSize, syntaxRoot.Language),
                         tokenStream: null,
                         lastToken: default(SyntaxToken));
            }
 protected override AbstractIndenter GetIndenter(
     ISyntaxFactsService syntaxFacts, SyntaxTree syntaxTree, TextLine lineToBeIndented, IEnumerable<IFormattingRule> formattingRules, OptionSet optionSet, CancellationToken cancellationToken)
 {
     return new Indenter(
         syntaxFacts, syntaxTree, formattingRules,
         optionSet, lineToBeIndented, cancellationToken);
 }
        public static SemanticModel GetSemanticModel(SyntaxTree tree, string extDll)
        {
            var Mscorlib = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
            var current = PortableExecutableReference.CreateFromFile(Assembly.GetExecutingAssembly().Location);
            var current2 = PortableExecutableReference.CreateFromFile(typeof(Hide).Assembly.Location);
            var current3 = PortableExecutableReference.CreateFromFile(extDll);
            var current4 = PortableExecutableReference.CreateFromFile(@"D:\ghostnguyen\daccf960-44f9-4f95-91c4-b1aba37effe1\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll");
            var current5 = PortableExecutableReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Web.dll");
            var current6 = PortableExecutableReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Xml.Linq.dll");
            var current7 = PortableExecutableReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Xml.dll");
            var current8 = PortableExecutableReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Core.dll");
            var current9 = PortableExecutableReference.CreateFromFile(@"D:\ghostnguyen\daccf960-44f9-4f95-91c4-b1aba37effe1\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll");

            var compilation = CSharpCompilation.Create("MyCompilation",
                syntaxTrees: new[] { tree }, references: new[] { Mscorlib,
                    current,
                    current2,
                    current3,
                    current4,
                    current5,
                    current6,
                    current7,
                    current8,
                    current9
                });

            var model = compilation.GetSemanticModel(tree);
            var dia1 = model.GetDiagnostics();
            var dia2 = compilation.GetDiagnostics();

            return model;
        }
Esempio n. 6
0
 public static IEnumerable<PropertyDeclarationSyntax> GetProperties(SyntaxTree syntaxTree)
 {
     var result = syntaxTree.GetRoot().DescendantNodes()
         .Where(node => node.IsKind(SyntaxKind.PropertyDeclaration))
         .Cast<PropertyDeclarationSyntax>();
     return result;
 }
		internal CodeProvider(SyntaxTree tree, Compilation compilation)
		{
			this.SyntaxTree = tree;	//project.GetCompilationAsync().Result;
			this.Compilation = compilation;

			this.SemanticModel = this.Compilation.GetSemanticModel(tree);
		}
        public int? FromIndentBlockOperations(
            SyntaxTree tree, SyntaxToken token, int position, CancellationToken cancellationToken)
        {
            // we use operation service to see whether it is a starting point of new indentation.
            // ex)
            //  if (true)
            //  {
            //     | <= this is new starting point of new indentation
            var operation = GetIndentationDataFor(tree.GetRoot(cancellationToken), token, position);

            // try find indentation based on indentation operation
            if (operation != null)
            {
                // make sure we found new starting point of new indentation.
                // such operation should start span after the token (a token that is right before the new indentation),
                // contains current position, and position should be before the existing next token
                if (token.Span.End <= operation.TextSpan.Start &&
                    operation.TextSpan.IntersectsWith(position) &&
                    position <= token.GetNextToken(includeZeroWidth: true).SpanStart)
                {
                    return GetIndentationOfCurrentPosition(tree, token, position, cancellationToken);
                }
            }

            return null;
        }
 protected SyntacticDocument(Document document, SourceText text, SyntaxTree tree, SyntaxNode root)
 {
     this.Document = document;
     this.Text = text;
     this.SyntaxTree = tree;
     this.Root = root;
 }
Esempio n. 10
0
        private static IEnumerable<Conflict> GetConflicts(IEnumerable<Diff> local, IEnumerable<Diff> remote,
            SyntaxTree ancestorTree, SyntaxTree localTree, SyntaxTree remoteTree)
        {
            var localChanges = local.Select(DiffWithOrigin.Local);
            var remoteChanges = remote.Select(DiffWithOrigin.Remote);

            var changes = Extensions.GetMergedQueue(localChanges, remoteChanges,
                                                            d => d.Diff.Ancestor.Span.Start);
            var potentialConflict = new List<DiffWithOrigin>();
            while (changes.Count > 0)
            {
                potentialConflict.Clear();
                do
                {
                    var change = changes.Dequeue();
                    potentialConflict.Add(change);
                }
                while (changes.Count > 0
                      && Diff.IntersectsAny(changes.Peek().Diff,
                                                   potentialConflict.Select(dwo => dwo.Diff)));

                if (potentialConflict.Count >= 2)
                    yield return Conflict.Create(potentialConflict, ancestorTree, localTree, remoteTree);
            }
            yield break;
        }
        private static void OneSide(Repo repo, SyntaxTree local, SyntaxTree remote, SyntaxTree ancestor, string path)
        {
            //Fake a call te to GetRemoteChange() by placeing the remote and ancestor trees into the RemoteChangesData list
            repo.PullRequests.Clear();
            repo.PullRequests.Add(new PullRequest
            {
                Updated = DateTime.Now,
                Files = new[] { new Core.RepoFile {
                    BaseTree = ancestor,
                    HeadTree = remote,
                    Filename = path,
                    Status = RepoFile.StatusEnum.Modified,
                } },
                Title = "Fake Pull Request",
                Url = "http://github.com/example/repo",
                Number = 1,
                State = "open",
                LastWrite = DateTime.MinValue,
                Base = new PullRequest.HeadBase { Sha = "" },
                Head = new PullRequest.HeadBase { Sha = "" },
            });
            var pr = repo.PullRequests.First();
            pr.ParentRepo = repo;
            pr.ValidFiles.First().ParentPullRequst = pr;

            var res = Analysis.ForFalsePositive(repo, local);
            Assert.IsTrue(res.Any());
        }
        public static bool IsEntirelyWithinStringLiteral(
            SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true);

            // If we ask right at the end of the file, we'll get back nothing. We handle that case
            // specially for now, though SyntaxTree.FindToken should work at the end of a file.
            if (IsKind(token, SyntaxKind.EndOfDirectiveToken, SyntaxKind.EndOfFileToken))
            {
                token = token.GetPreviousToken(includeSkipped: true, includeDirectives: true);
            }

            if (token.IsKind(SyntaxKind.StringLiteralToken))
            {
                var span = token.Span;

                // cases:
                // "|"
                // "|  (e.g. incomplete string literal)
                return (position > span.Start && position < span.End)
                       || AtEndOfIncompleteStringOrCharLiteral(token, position, '"');
            }

            if (IsKind(token, SyntaxKind.InterpolatedStringStartToken, SyntaxKind.InterpolatedStringTextToken,
                SyntaxKind.InterpolatedStringEndToken))
            {
                return token.SpanStart < position && token.Span.End > position;
            }

            return false;
        }
 public Microsoft.CodeAnalysis.SyntaxTree Translate(VSGraphModel graphModel, CompilationOptions options)
 {
     Profiler.BeginSample("Translation");
     Microsoft.CodeAnalysis.SyntaxTree syntaxTree = ToSyntaxTree(graphModel, options);
     Profiler.EndSample();
     return(syntaxTree);
 }
Esempio n. 14
0
 internal static Compilation CreateCompilation(SyntaxTree tree)
 {
     var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
     var compilation = CSharpCompilation.Create("MyCompilation",
         syntaxTrees: new[] { tree }, references: new[] { mscorlib });
     return compilation;
 }
Esempio n. 15
0
        public Assembly Compile(string guid, string text, params Assembly[] referencedAssemblies)
        {
            //return CSScript.Evaluator.ReferenceAssembly(Assembly.GetExecutingAssembly()).CompileCode(text,new CompileInfo() { RootClass = "tet", PreferLoadingFromFile=true });
            Logger.LogDebug("Compiler", $"Compiler cout is{referencedAssemblies.Length}");
            var references = referencedAssemblies.Select(it => Microsoft.CodeAnalysis.MetadataReference
                                                         .CreateFromFile(it.Location));
            var options      = new CSharpCompilationOptions(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary);
            var assemblyName = guid;// "_" + Guid.NewGuid().ToString("D");
            var syntaxTrees  = new  Microsoft.CodeAnalysis.SyntaxTree[] { CSharpSyntaxTree.ParseText(text) };
            var compilation  = CSharpCompilation.Create(
                assemblyName, syntaxTrees, references, options);

            using var stream = new MemoryStream();
            var compilationResult = compilation.Emit(stream);

            if (compilationResult.Success)
            {
                stream.Seek(0, SeekOrigin.Begin);
                return(Assembly.Load(stream.ToArray()));
            }
            else
            {
                var allerrro = new StringBuilder();
                var i        = 1;
                foreach (var item in compilationResult.Diagnostics)
                {
                    allerrro.AppendFormat("{0}-->Info:{1}\r\n=================================\r\n", i, item.ToString());
                    i++;
                }
                throw new InvalidOperationException($"Compilation error;\r\n{ allerrro.ToString()}");
            }
        }
        /// <summary>
        /// Rewrites the syntax tree with create machine expressions.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>SyntaxTree</returns>
        internal SyntaxTree Rewrite(SyntaxTree tree)
        {
            var statements = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().
                Where(val => val.Expression is IdentifierNameSyntax).
                Where(val => (val.Expression as IdentifierNameSyntax).Identifier.ValueText.Equals("create")).
                ToList();

            if (statements.Count == 0)
            {
                return tree;
            }

            var root = tree.GetRoot().ReplaceNodes(
                nodes: statements,
                computeReplacementNode: (node, rewritten) => this.RewriteStatement(rewritten));

            var models = root.DescendantNodes().
                Where(val => val is LocalDeclarationStatementSyntax).
                Where(val => this.ToReplace.Any(n => n.IsEquivalentTo(val)));

            root = root.ReplaceNodes(
                nodes: models,
                computeReplacementNode: (node, rewritten) => SyntaxFactory.ParseStatement(";"));

            root = root.RemoveNodes(this.ToRemove, SyntaxRemoveOptions.KeepNoTrivia);

            return base.UpdateSyntaxTree(tree, root.ToString());
        }
Esempio n. 17
0
        private Compilation CompileScript(Microsoft.CodeAnalysis.SyntaxTree tree, OptimizationLevel level)
        {
            var references = new MetadataReference[] {
                MetadataReference.CreateFromFile(typeof(Object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Console).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
            };

            var all = references.Concat(GetReferences());

            var usings  = GetUsings();
            var options = ScriptOptions.Default
                          .WithImports(usings)
                          .WithReferences(references);

            var script = CSharpScript.Create(tree.ToString(), options);
            var com    = script.GetCompilation();

            if (level == OptimizationLevel.Release)
            {
                SetReleaseOptimizationLevel(com);
            }

            return(com);
        }
Esempio n. 18
0
        /// <summary>
        /// Get assembly from the given text.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>Assembly</returns>
        protected Assembly GetAssembly(SyntaxTree tree)
        {
            Assembly assembly = null;
            
            var references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Machine).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(PSharpBugFindingRuntime).Assembly.Location)
            };

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

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);
                if (result.Success)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    assembly = Assembly.Load(ms.ToArray());
                }
            }

            return assembly;
        }
        public CSharpCompilation GetCompilation(string assemblyName, IDictionary<string, string> files, out SyntaxTree[] trees)
        {
            var options = new CSharpParseOptions(_languageVersion);
            trees = files.Select(x =>
            {
                var text = x.Value;
                var tree = CSharpSyntaxTree.ParseText(text, options: options);
                if (tree.GetDiagnostics().Any())
                    throw new Exception(string.Format("Syntax error in file \"{0}\".", x.Key));
                return tree;
            }).ToArray();

            // adding everything is going to cause issues with dynamic assemblies
            // so we would want to filter them anyway... but we don't need them really
            //var refs = AssemblyUtility.GetAllReferencedAssemblyLocations().Select(x => new MetadataFileReference(x));
            // though that one is not ok either since we want our own reference
            //var refs = Enumerable.Empty<MetadataReference>();
            // so use the bare minimum
            var asms = ReferencedAssemblies;
            var a1 = typeof(Builder).Assembly;
            asms.Add(a1);
            foreach (var a in GetDeepReferencedAssemblies(a1)) asms.Add(a);
            var refs = asms.Select(x => MetadataReference.CreateFromFile(x.Location));

            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var compilation = CSharpCompilation.Create(
                assemblyName,
                /*syntaxTrees:*/ trees,
                /*references:*/ refs,
                compilationOptions);

            return compilation;
        }
 public IEnumerable<AttributeListSyntax> GetAttributeListsNodes(SyntaxTree syntaxTree)
 {
     if (syntaxTree == null) throw new ArgumentNullException(nameof(syntaxTree));
     return syntaxTree.GetRoot()
        .DescendantNodes()
        .OfType<AttributeListSyntax>();
 }
        static CompilationResult CheckSemanticModel(Microsoft.CodeAnalysis.SyntaxTree syntaxTree,
                                                    CompilationResult compilationResult)
        {
            SemanticModel semanticModel = GetSemanticModel(syntaxTree);

            // run all the semantic code analyzers
            var diagnostics = new List <CompilerError>();

            Profiler.BeginSample("GetDiagnostics");
            ImmutableArray <Diagnostic> rawDiagnostics = semanticModel.GetDiagnostics();

            Profiler.EndSample();

            Profiler.BeginSample("ProcessDiagnostics");
            ProcessDiagnostics(rawDiagnostics, diagnostics);
            Profiler.EndSample();

            Profiler.BeginSample("Format");

            var codeText = syntaxTree.GetText().ToString();

            compilationResult.sourceCode[(int)SourceCodePhases.Final] = codeText;

            Profiler.EndSample();

            if (diagnostics.Any())
            {
                compilationResult.errors = diagnostics;
            }

            return(compilationResult);
        }
Esempio n. 22
0
 public IEnumerable<Match> Run(SyntaxTree tree)
 {
     return tree.GetRoot()
                .DescendantNodesAndTokensAndSelf()
                .Select(CreateMatch)
                .Where(n => n.IsMatch);
 }
Esempio n. 23
0
        /// <summary>
        /// Rewrites the syntax tree with raise statements.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>SyntaxTree</returns>
        internal SyntaxTree Rewrite(SyntaxTree tree)
        {
            var statements = tree.GetRoot().DescendantNodes().OfType<ExpressionStatementSyntax>().
                Where(val => val.Expression is InvocationExpressionSyntax).
                Where(val => (val.Expression as InvocationExpressionSyntax).Expression is IdentifierNameSyntax).
                Where(val => ((val.Expression as InvocationExpressionSyntax).Expression as IdentifierNameSyntax).
                    Identifier.ValueText.Equals("raise")).
                ToList();

            if (statements.Count == 0)
            {
                return tree;
            }

            var root = tree.GetRoot().ReplaceNodes(
                nodes: statements,
                computeReplacementNode: (node, rewritten) => this.RewriteStatement(rewritten));

            var raiseStmts = root.DescendantNodes().OfType<ExpressionStatementSyntax>().
                Where(val => this.RaiseStmts.Any(v => SyntaxFactory.AreEquivalent(v, val))).ToList();

            foreach (var stmt in raiseStmts)
            {
                root = root.InsertNodesAfter(stmt, new List<SyntaxNode> { this.CreateReturnStatement() });
            }

            return base.UpdateSyntaxTree(tree, root.ToString());
        }
Esempio n. 24
0
        /// <summary>
        /// Creates a fresh new compilation of source files.
        /// Does not load any assembly.
        /// </summary>
        /// <returns>Success if no compilation erros were encountered.</returns>
        public bool Compile()
        {
            if (SourceFiles.Count == 0 && SourceTexts.Count == 0) return false;

            SyntaxTree [] syntaxTrees = new SyntaxTree[SourceFiles.Count + SourceTexts.Count];
            int currentIndex = 0;

            try
            {
                foreach (string sourceFile in SourceFiles)
                {
                    using (StreamReader reader = new StreamReader(MyFileSystem.OpenRead(sourceFile)))
                    {
                        var text = reader.ReadToEnd();
                        syntaxTrees[currentIndex] = CSharpSyntaxTree.ParseText(text);
                        currentIndex++;
                    }
                }

                foreach (var sourceText in SourceTexts)
                    syntaxTrees[currentIndex++] = CSharpSyntaxTree.ParseText(sourceText);

                m_compilation = CSharpCompilation.Create(AssemblyName, syntaxTrees, 
                    DependencyCollector.References, m_defaultCompilationOptions);

            }
            catch (Exception e)
            {
                Debug.Fail(e.ToString());
                return false;
            }

            return true;
        }
 public StatMachineGeneratorFixer(Compilation compilation, SyntaxTree syntaxTree, SemanticModel semanticModel, string enclosingTypeName)
 {
     this.compilation = compilation;
     this.syntaxTree = syntaxTree;
     this.semanticModel = semanticModel;
     this.enclosingTypeName = enclosingTypeName;
 }
Esempio n. 26
0
        public SourceWithMarkedNodes(string markedSource, Func<string, SyntaxTree> parser, Func<string, int> getSyntaxKind)
        {
            Source = ClearTags(markedSource);
            Tree = parser(Source);

            SpansAndKindsAndIds = ImmutableArray.CreateRange(GetSpansRecursive(markedSource, 0, getSyntaxKind));
        }
        public void TestSetup()
        {
            syntaxTree = CSharpSyntaxTree.ParseText(Source);

            ifMethod = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "IfMethod");
            switchMethod = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(m => m.Identifier.ValueText == "SwitchMethod");
        }
Esempio n. 28
0
        /// <summary>
        /// Rewrites the syntax tree with raise statements.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>SyntaxTree</returns>
        internal SyntaxTree Rewrite(SyntaxTree tree)
        {
            var stmts1 = tree.GetRoot().DescendantNodes().OfType<ExpressionStatementSyntax>().
                Where(val => val.Expression is InvocationExpressionSyntax).
                Where(val => (val.Expression as InvocationExpressionSyntax).Expression is IdentifierNameSyntax).
                Where(val => ((val.Expression as InvocationExpressionSyntax).Expression as IdentifierNameSyntax).
                    Identifier.ValueText.Equals("Raise")).
                ToList();

            var stmts2 = tree.GetRoot().DescendantNodes().OfType<ExpressionStatementSyntax>().
                Where(val => val.Expression is InvocationExpressionSyntax).
                Where(val => (val.Expression as InvocationExpressionSyntax).Expression is MemberAccessExpressionSyntax).
                Where(val => ((val.Expression as InvocationExpressionSyntax).Expression as MemberAccessExpressionSyntax).
                    Name.Identifier.ValueText.Equals("Raise")).
                ToList();

            var statements = stmts1;
            statements.AddRange(stmts2);

            if (statements.Count == 0)
            {
                return tree;
            }

            var root = tree.GetRoot().ReplaceNodes(
                nodes: statements,
                computeReplacementNode: (node, rewritten) => this.RewriteStatement(rewritten));

            return base.UpdateSyntaxTree(tree, root.ToString());
        }
Esempio n. 29
0
		public static bool IsExercise(SyntaxTree tree)
		{
			return 
				tree.GetRoot()
				.DescendantNodes()
				.OfType<MethodDeclarationSyntax>()
				.Any(m => m.HasAttribute<ExpectedOutputAttribute>());
		}
Esempio n. 30
0
		public Checker(Stream file)
		{
			using (var reader = new StreamReader(file, Encoding.UTF8, true, 16 * 1024, true))
			{
				_tree = CSharpSyntaxTree.ParseText(reader.ReadToEnd(),
					options: ParseOptions);
			}
		}
Esempio n. 31
0
		protected override Compilation CreateCompilation(SyntaxTree syntaxTree, string assemblyName, IEnumerable<PortableExecutableReference> references)
		{
			return VisualBasicCompilation.Create(
				assemblyName,
				syntaxTrees: new[] { syntaxTree },
				references: references,
				options: new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
		}
 private Boolean IsAutoGenerated(SyntaxTree tree)
     => tree.GetRoot()
         .GetLeadingTrivia()
         .Where(t =>
             t.IsKind(SyntaxKind.SingleLineCommentTrivia)
             && t.ToString().IndexOf("<auto-generated>", StringComparison.OrdinalIgnoreCase) != -1
         )
         .Any();
 internal static Compilation CreateCompilation(SyntaxTree tree)
 {
     var mscorlibAssembly = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
     var debugAssembly = MetadataReference.CreateFromFile(typeof(System.Diagnostics.Debug).Assembly.Location);
     var compilation = CSharpCompilation.Create("MyCompilation",
         syntaxTrees: new[] { tree }, references: new[] { mscorlibAssembly, debugAssembly }, options: new CSharpCompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary));
     return compilation;
 }
Esempio n. 34
0
		/// <summary>
		///     Normalizes the <paramref name="syntaxTree" /> of the <see cref="Compilation" />.
		/// </summary>
		/// <param name="syntaxTree">The syntax tree that should be normalized.</param>
		protected override SyntaxTree Normalize(SyntaxTree syntaxTree)
		{
			var root = syntaxTree.GetRoot();
			var firstNode = root.GetFirstToken(true, true, true, true).Parent;
			var updatedNode = firstNode.PrependLineDirective(1, syntaxTree.FilePath);

			return syntaxTree.WithFilePath(syntaxTree.FilePath + Guid.NewGuid()).WithRoot(root.ReplaceNode(firstNode, updatedNode));
		}
Esempio n. 35
0
        public static List <string> GetMethodParams(string scriptCode, int position, ILogger log = null)
        {
            //position = position - 2;
            List <string> overloads = new List <string>();
            var           meta      = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES");

            string[] assembliesNames = meta.ToString().Split(';', StringSplitOptions.None);
            var      sourceLanguage  = new CSharpLanguage();
            //SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(scriptCode);
            SyntaxTree syntaxTree   = sourceLanguage.ParseText(scriptCode, SourceCodeKind.Script);
            var        root         = (CompilationUnitSyntax)syntaxTree.GetRoot();
            var        thisAssembly = typeof(CompleteCode).Assembly;
            var        loadContext  = AssemblyLoadContext.GetLoadContext(thisAssembly);


            var Mscorlib    = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
            var compilation = CSharpCompilation.Create("MyCompilation",
                                                       syntaxTrees: new[] { syntaxTree }, references: CompileResources.PortableExecutableCompletionReferences);

            var model = compilation.GetSemanticModel(syntaxTree);

            var theToken = syntaxTree.GetRoot().FindToken(position);
            var theNode  = theToken.Parent;

            while (!theNode.IsKind(SyntaxKind.InvocationExpression))
            {
                theNode = theNode.Parent;
                if (theNode == null)
                {
                    break;                  // There isn't an InvocationExpression in this branch of the tree
                }
            }

            if (theNode == null)
            {
                overloads = null;
            }
            else
            {
                var symbolInfo     = model.GetSymbolInfo(theNode);
                var symbol         = symbolInfo.Symbol;
                var containingType = symbol?.ContainingType;

                if (symbolInfo.CandidateSymbols != default && symbolInfo.CandidateSymbols.Length > 0)
                {
                    foreach (var parameters in symbolInfo.CandidateSymbols)
                    {
                        var i = parameters.ToMinimalDisplayParts(model, position);
                        if (parameters.Kind == SymbolKind.Method)
                        {
                            var mp = parameters.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
                            overloads.Add(mp);
                        }
                    }
                }
            }
            return(overloads);
        }
Esempio n. 36
0
        public Microsoft.CodeAnalysis.SyntaxTree Translate(VSGraphModel graphModel, CompilationOptions options)
        {
            Profiler.BeginSample("Translation");
            Microsoft.CodeAnalysis.SyntaxTree syntaxTree = ToSyntaxTree(graphModel, options);
            Profiler.EndSample();
            var compilationResult = new CompilationResult();

            ApplyPluginsToAst(ref syntaxTree, options, graphModel.Stencil, ref compilationResult);
            return(syntaxTree);
        }
Esempio n. 37
0
        public void Compile()
        {
            Profiler.BeginSample("UdonSharp Compile");

            System.Diagnostics.Stopwatch compileTimer = new System.Diagnostics.Stopwatch();
            compileTimer.Start();

            int totalErrorCount = 0;

            try
            {
                EditorUtility.DisplayProgressBar("UdonSharp Compile", "Parsing Syntax Trees...", 0f);

                UdonSharpProgramAsset[] allPrograms = UdonSharpProgramAsset.GetAllUdonSharpPrograms();
                List <(UdonSharpProgramAsset, string)> programAssetsAndPaths = new List <(UdonSharpProgramAsset, string)>();

                foreach (UdonSharpProgramAsset programAsset in allPrograms)
                {
                    if (programAsset == null || programAsset.sourceCsScript == null)
                    {
                        continue;
                    }

                    programAssetsAndPaths.Add((programAsset, AssetDatabase.GetAssetPath(programAsset.sourceCsScript)));
                }

                UdonSharpProgramAsset[] programAssetsToCompile = modules.Select(e => e.programAsset).Where(e => e != null && e.sourceCsScript != null).ToArray();

                try
                {
                    beforeCompile?.Invoke(programAssetsToCompile);
                }
                catch (System.Exception e)
                {
                    Debug.LogError($"Exception thrown by pre compile listener\n{e}");
                }

                object syntaxTreeLock = new object();
                List <(UdonSharpProgramAsset, Microsoft.CodeAnalysis.SyntaxTree)> programsAndSyntaxTrees = new List <(UdonSharpProgramAsset, Microsoft.CodeAnalysis.SyntaxTree)>();
                Dictionary <UdonSharpProgramAsset, (string, Microsoft.CodeAnalysis.SyntaxTree)> syntaxTreeSourceLookup = new Dictionary <UdonSharpProgramAsset, (string, Microsoft.CodeAnalysis.SyntaxTree)>();

                string[] defines = UdonSharpUtils.GetProjectDefines(isEditorBuild);

                Parallel.ForEach(programAssetsAndPaths, (currentProgram) =>
                {
                    string programSource = UdonSharpUtils.ReadFileTextSync(currentProgram.Item2);

                    Microsoft.CodeAnalysis.SyntaxTree programSyntaxTree = CSharpSyntaxTree.ParseText(programSource, CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.None).WithPreprocessorSymbols(defines));

                    lock (syntaxTreeLock)
                    {
                        programsAndSyntaxTrees.Add((currentProgram.Item1, programSyntaxTree));
                        syntaxTreeSourceLookup.Add(currentProgram.Item1, (programSource, programSyntaxTree));
                    }
                });
Esempio n. 38
0
        private List <ClassDefinition> BuildClassDefinitions()
        {
            string[] udonSharpDataAssets = AssetDatabase.FindAssets($"t:{typeof(UdonSharpProgramAsset).Name}");

            List <UdonSharpProgramAsset> udonSharpPrograms = new List <UdonSharpProgramAsset>();

            foreach (string dataGuid in udonSharpDataAssets)
            {
                udonSharpPrograms.Add(AssetDatabase.LoadAssetAtPath <UdonSharpProgramAsset>(AssetDatabase.GUIDToAssetPath(dataGuid)));
            }

            List <ClassDefinition> classDefinitions = new List <ClassDefinition>();

            foreach (UdonSharpProgramAsset udonSharpProgram in udonSharpPrograms)
            {
                if (udonSharpProgram.sourceCsScript == null)
                {
                    continue;
                }

                string sourcePath    = AssetDatabase.GetAssetPath(udonSharpProgram.sourceCsScript);
                string programSource = UdonSharpUtils.ReadFileTextSync(sourcePath);

                ResolverContext resolver     = new ResolverContext();
                SymbolTable     classSymbols = new SymbolTable(resolver, null);

                classSymbols.OpenSymbolTable();

                LabelTable classLabels = new LabelTable();

                Microsoft.CodeAnalysis.SyntaxTree tree = CSharpSyntaxTree.ParseText(programSource);

                ClassVisitor classVisitor = new ClassVisitor(resolver, classSymbols, classLabels);

                try
                {
                    classVisitor.Visit(tree.GetRoot());
                }
                catch (System.Exception e)
                {
                    UdonSharpUtils.LogBuildError($"{e.GetType()}: {e.Message}", sourcePath.Replace("/", "\\"), 0, 0);

                    return(null);
                }

                classSymbols.CloseSymbolTable();

                classVisitor.classDefinition.classScript = udonSharpProgram.sourceCsScript;
                classDefinitions.Add(classVisitor.classDefinition);
            }

            return(classDefinitions);
        }
 public Microsoft.CodeAnalysis.SyntaxTree Translate(VSGraphModel graphModel, CompilationOptions options)
 {
     Profiler.BeginSample("Translation");
     Microsoft.CodeAnalysis.SyntaxTree syntaxTree = ToSyntaxTree(graphModel, options);
     Profiler.EndSample();
     if (syntaxTree is CSharpSyntaxTree cSharpSyntaxTree && syntaxTree.TryGetRoot(out var treeRoot))
     {
         var treeOptions = cSharpSyntaxTree.Options.WithLanguageVersion(LanguageVersion);
         return(syntaxTree.WithRootAndOptions(treeRoot, treeOptions));
     }
     return(syntaxTree);
 }
Esempio n. 40
0
        static SemanticModel GetSemanticModel(Microsoft.CodeAnalysis.SyntaxTree syntaxTree)
        {
            Profiler.BeginSample("CreateCompilation");
            CSharpCompilation compilation = CSharpCompilation.Create("VSScriptCompilation", options: CompilationOptions,
                                                                     syntaxTrees: new[] { syntaxTree }, references: s_CachedAllReferences);

            Profiler.EndSample();
            Profiler.BeginSample("GetSemModel");
            SemanticModel semanticModel = compilation.GetSemanticModel(syntaxTree);

            Profiler.EndSample();
            return(semanticModel);
        }
        public virtual Microsoft.CodeAnalysis.SyntaxTree OnTranslate(VSGraphModel graphModel, AssemblyType assemblyType, CompilationOptions compilationOptions, ref CompilationResult compilationResult)
        {
            const string windowsLineEndings = "\r\n";
            const string unixLineEndings    = "\n";

            Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Translate(graphModel, compilationOptions); // we will measure plugins time later

            string          preferredLineEndings;
            LineEndingsMode lineEndingsForNewScripts = EditorSettings.lineEndingsForNewScripts;

            switch (lineEndingsForNewScripts)
            {
            case LineEndingsMode.OSNative:
                preferredLineEndings = Application.platform == RuntimePlatform.WindowsEditor ? windowsLineEndings : unixLineEndings;
                break;

            case LineEndingsMode.Unix:
                preferredLineEndings = unixLineEndings;
                break;

            case LineEndingsMode.Windows:
                preferredLineEndings = windowsLineEndings;
                break;

            default:
                preferredLineEndings = unixLineEndings;
                break;
            }

            var adHocWorkspace = new AdhocWorkspace();

            var options = adHocWorkspace.Options
                          .WithChangedOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, true)
                          .WithChangedOption(CSharpFormattingOptions.WrappingPreserveSingleLine, false)
                          .WithChangedOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, false)
                          .WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, true)
                          .WithChangedOption(FormattingOptions.NewLine, LanguageNames.CSharp, preferredLineEndings);

            compilationResult.sourceCode[(int)SourceCodePhases.Initial] = syntaxTree.GetText().ToString();

            var formattedTree = Formatter.Format(syntaxTree.GetCompilationUnitRoot(), adHocWorkspace, options);

            formattedTree = new VisualScriptingCSharpFormatter().Visit(formattedTree);
            string codeText = formattedTree.GetText().ToString();

            compilationResult.sourceCode[(int)SourceCodePhases.Final] = codeText;

            return(syntaxTree);
        }
        protected override void Initialize()
        {
            base.Initialize();

            parseTree = VisualBasicSyntaxTree.ParseText(Editor.Text);
            var sourceText = SourceText.From(Editor.Text);

            var projectId = ProjectId.CreateNewId();

            documentId = DocumentId.CreateNewId(projectId);
            var projectInfo = ProjectInfo.Create(
                projectId,
                VersionStamp.Create(),
                "TestProject",
                "TestProject",
                LanguageNames.VisualBasic,
                null,
                null,
                new VisualBasicCompilationOptions(
                    OutputKind.DynamicallyLinkedLibrary
                    ),
                new VisualBasicParseOptions(),
                new [] {
                DocumentInfo.Create(
                    documentId,
                    Editor.FileName,
                    null,
                    SourceCodeKind.Regular,
                    TextLoader.From(TextAndVersion.Create(sourceText, VersionStamp.Create())),
                    filePath: Editor.FileName
                    )
            },
                null,
                DefaultMetadataReferences
                );
            var sInfo = SolutionInfo.Create(
                SolutionId.CreateNewId(),
                VersionStamp.Create(),
                null,
                new [] { projectInfo }
                );

            workspace.OpenSolutionInfo(sInfo);

            Editor.SyntaxHighlighting = new ClassificationSyntaxHighlighting(workspace, documentId);
            workspace.InformDocumentOpen(documentId, Editor);
        }
Esempio n. 43
0
        static void ApplyPluginsToAst(ref Microsoft.CodeAnalysis.SyntaxTree syntaxTree, CompilationOptions options, Stencil stencil, ref CompilationResult result)
        {
            Profiler.BeginSample("Code Analysis");

            // run all the syntactic code analyzers
            CompilationStatus status = CompilationStatus.Succeeded;

            result.pluginSourceCode = new Dictionary <Type, string>();

            foreach (IRoslynPluginHandler handler in stencil.GetCompilationPluginHandlers(options).OfType <IRoslynPluginHandler>())
            {
                handler.Apply(ref syntaxTree, options);
                result.pluginSourceCode[handler.GetType()] = syntaxTree.GetText().ToString();
            }
            result.status = status;
            Profiler.EndSample();
        }
Esempio n. 44
0
        private Compilation CompileCSharp(Microsoft.CodeAnalysis.SyntaxTree tree, OptimizationLevel level)
        {
            var references = new MetadataReference[] {
                MetadataReference.CreateFromFile(typeof(Object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Console).Assembly.Location),
            };

            var all = references.Concat(GetReferences());
            var com = CSharpCompilation.Create(
                "Hello",
                syntaxTrees: new[] { tree },
                references: all,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                .WithOptimizationLevel(level)
                );

            return(com);
        }
Esempio n. 45
0
        internal FileModel(Microsoft.CodeAnalysis.SyntaxTree tree, ParseOptions options)
        {
            Tree = tree;
            var structs = tree.GetCompilationUnitRoot().DescendantNodes(n => !(n is StructDeclarationSyntax)).OfType <StructDeclarationSyntax>();
            var classes = tree.GetCompilationUnitRoot().DescendantNodes(n => !(n is ClassDeclarationSyntax)).OfType <ClassDeclarationSyntax>();

            Structs = new List <StructModel>();
            foreach (var s in structs)
            {
                var matchingProxy = classes.SingleOrDefault(c => c.Identifier.Text == StructModel.MakeProxyName(s.Identifier.Text));
                var model         = ParseStruct(s, matchingProxy);
                if (model != null)
                {
                    Structs.Add(model);
                }
            }

            if (Structs.Count > 1 && options == ParseOptions.DisallowMultipleStructs)
            {
                throw new InvalidOperationException("File contains multiple component definitions");
            }
        }
        static CompilationResult CheckSemanticModel(Microsoft.CodeAnalysis.SyntaxTree syntaxTree,
                                                    CompilationResult compilationResult)
        {
            SemanticModel semanticModel = GetSemanticModel(syntaxTree);

            // run all the semantic code analyzers
            var diagnostics = new List <CompilerError>();

            Profiler.BeginSample("GetDiagnostics");
            ImmutableArray <Diagnostic> rawDiagnostics = semanticModel.GetDiagnostics();

            Profiler.EndSample();

            Profiler.BeginSample("ProcessDiagnostics");
            ProcessDiagnostics(rawDiagnostics, diagnostics);
            Profiler.EndSample();

            if (diagnostics.Any())
            {
                compilationResult.errors = diagnostics;
            }

            return(compilationResult);
        }
Esempio n. 47
0
        public CompileTaskResult Compile(List <ClassDefinition> classDefinitions)
        {
            programAsset.compileErrors.Clear();

            Microsoft.CodeAnalysis.SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode);

            CompileTaskResult result = new CompileTaskResult();

            result.programAsset = programAsset;

            int errorCount = 0;

            foreach (Diagnostic diagnostic in tree.GetDiagnostics())
            {
                if (diagnostic.Severity == DiagnosticSeverity.Error)
                {
                    errorCount++;

                    LinePosition linePosition = diagnostic.Location.GetLineSpan().StartLinePosition;

                    CompileError error = new CompileError();
                    error.script   = programAsset.sourceCsScript;
                    error.errorStr = $"error {diagnostic.Descriptor.Id}: {diagnostic.GetMessage()}";
                    error.lineIdx  = linePosition.Line;
                    error.charIdx  = linePosition.Character;

                    result.compileErrors.Add(error);
                }
            }

            if (errorCount > 0)
            {
                return(result);
            }

            moduleSymbols.OpenSymbolTable();

            UdonSharpFieldVisitor fieldVisitor = new UdonSharpFieldVisitor(fieldsWithInitializers);

            fieldVisitor.Visit(tree.GetRoot());

            MethodVisitor methodVisitor = new MethodVisitor(resolver, moduleSymbols, moduleLabels);

            methodVisitor.Visit(tree.GetRoot());

            ClassDebugInfo debugInfo = null;

            if (settings == null || settings.buildDebugInfo)
            {
                debugInfo = new ClassDebugInfo(sourceCode, settings == null || settings.includeInlineCode);
            }

            ASTVisitor visitor = new ASTVisitor(resolver, moduleSymbols, moduleLabels, methodVisitor.definedMethods, classDefinitions, debugInfo);

            try
            {
                visitor.Visit(tree.GetRoot());
                visitor.VerifyIntegrity();
            }
            catch (System.Exception e)
            {
                SyntaxNode currentNode = visitor.visitorContext.currentNode;

                string logMessage = "";

                if (currentNode != null)
                {
                    FileLinePositionSpan lineSpan = currentNode.GetLocation().GetLineSpan();

                    CompileError error = new CompileError();
                    error.script   = programAsset.sourceCsScript;
                    error.errorStr = $"{e.GetType()}: {e.Message}";
                    error.lineIdx  = lineSpan.StartLinePosition.Line;
                    error.charIdx  = lineSpan.StartLinePosition.Character;

                    result.compileErrors.Add(error);
                }
                else
                {
                    logMessage = e.ToString();
                    Debug.LogException(e);
                }
#if UDONSHARP_DEBUG
                Debug.LogException(e);
                Debug.LogError(e.StackTrace);
#endif

                programAsset.compileErrors.Add(logMessage);

                errorCount++;
            }

            if (errorCount > 0)
            {
                return(result);
            }

            moduleSymbols.CloseSymbolTable();

            if (errorCount == 0)
            {
                compiledClassDefinition = classDefinitions.Find(e => e.userClassType == visitor.visitorContext.behaviourUserType);

                string dataBlock = BuildHeapDataBlock();
                string codeBlock = visitor.GetCompiledUasm();

                result.compiledAssembly = dataBlock + codeBlock;
                result.symbolCount      = (uint)(moduleSymbols.GetAllUniqueChildSymbols().Count + visitor.GetExternStrCount());

                programAsset.behaviourIDHeapVarName = visitor.GetIDHeapVarName();

                programAsset.fieldDefinitions = visitor.visitorContext.localFieldDefinitions;

                if (debugInfo != null)
                {
                    debugInfo.FinalizeDebugInfo();
                }

                programAsset.debugInfo = debugInfo;
            }

            return(result);
        }
Esempio n. 48
0
            public CompilationTracker FreezePartialStateWithTree(Solution solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken)
            {
                ProjectState inProgressProject;
                Compilation  inProgressCompilation;

                GetPartialCompilationState(solution, docState.Id, out inProgressProject, out inProgressCompilation, cancellationToken);

                if (!inProgressCompilation.SyntaxTrees.Contains(tree))
                {
                    var existingTree = inProgressCompilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == tree.FilePath);
                    if (existingTree != null)
                    {
                        inProgressCompilation = inProgressCompilation.ReplaceSyntaxTree(existingTree, tree);
                        inProgressProject     = inProgressProject.UpdateDocument(docState, textChanged: false, recalculateDependentVersions: false);
                    }
                    else
                    {
                        inProgressCompilation = inProgressCompilation.AddSyntaxTrees(tree);
                        Debug.Assert(!inProgressProject.DocumentIds.Contains(docState.Id));
                        inProgressProject = inProgressProject.AddDocument(docState);
                    }
                }

                // The user is asking for an in progress snap.  We don't want to create it and then a
                // have the compilation immediately disappear.  So we force it to stay around with a ConstantValueSource
                return(new CompilationTracker(inProgressProject,
                                              new FinalState(new ConstantValueSource <Compilation>(inProgressCompilation))));
            }
Esempio n. 49
0
        private static TreeAndVersion MakeNewTreeAndVersion(SyntaxTree oldTree, SourceText oldText, VersionStamp oldVersion, SyntaxTree newTree, SourceText newText, VersionStamp newVersion)
        {
            var topLevelChanged = TopLevelChanged(oldTree, oldText, newTree, newText);
            var version         = topLevelChanged ? newVersion : oldVersion;

            return(TreeAndVersion.Create(newTree, version));
        }
Esempio n. 50
0
 /// <summary>
 /// Gets the documentId in this solution with the specified syntax tree.
 /// </summary>
 public DocumentId GetDocumentId(SyntaxTree syntaxTree) => GetDocumentId(syntaxTree, projectId: null);
Esempio n. 51
0
 /// <summary>
 /// Gets the document in this solution with the specified syntax tree.
 /// </summary>
 public Document GetDocument(SyntaxTree syntaxTree)
 {
     return(this.GetDocument(syntaxTree, projectId: null));
 }
Esempio n. 52
0
        /// <summary>
        /// 生成Dll
        /// </summary>
        /// <param name="csprojName"></param>
        /// <param name="path"></param>
        /// <param name="buildType"></param>
        /// <param name="isUseDefine"></param>
        /// <returns></returns>
        public static bool BuildDll(string csprojName, string path, BuildType buildType, bool isUseDefine)
        {
            bool isDebug = buildType == BuildType.Debug ? true : false;
            //项目相关所有宏
            List <string> defineList = new List <string>();
            //项目相关所有dll
            List <string> dllFilePathList = new List <string>();
            //项目本身cs文件
            List <string> csFilePathList = ReadCSPROJ(csprojName, ref defineList, ref dllFilePathList);
            List <Microsoft.CodeAnalysis.SyntaxTree> csFileList = new List <Microsoft.CodeAnalysis.SyntaxTree>();
            List <MetadataReference> dllFileList = new List <MetadataReference>();
            CSharpParseOptions       parseOptions;

            //宏是否开启
            if (isUseDefine)
            {
                parseOptions = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: defineList);
            }
            else
            {
                parseOptions = new CSharpParseOptions(LanguageVersion.Latest);
            }
            //增加dll文件
            foreach (string item in dllFilePathList)
            {
                PortableExecutableReference dll = MetadataReference.CreateFromFile(item);
                if (dll == null)
                {
                    continue;
                }
                dllFileList.Add(dll);
            }
            //增加cs文件
            foreach (string item in csFilePathList)
            {
                if (File.Exists(item))
                {
                    Microsoft.CodeAnalysis.SyntaxTree cs = CSharpSyntaxTree.ParseText(FileUtil.GetAsset(item).GetString(), parseOptions, item, Encoding.UTF8);
                    if (cs == null)
                    {
                        continue;
                    }
                    csFileList.Add(cs);
                }
            }
            //设置编译参数
            CSharpCompilationOptions compilationOptions;

            if (isDebug)
            {
                compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug, warningLevel: 4, allowUnsafe: true);
            }
            else
            {
                compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, warningLevel: 4, allowUnsafe: true);
            }
            string assemblyName = Path.GetFileNameWithoutExtension(path);
            //开始编译
            CSharpCompilation compilation = CSharpCompilation.Create(assemblyName, csFileList, dllFileList, compilationOptions);
            EmitResult        result;

            if (isDebug)
            {
                string      pdbPath     = path.Replace(".dll", ".pdb");
                EmitOptions emitOptions = new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb, pdbFilePath: pdbPath);
                using (MemoryStream dllStream = new MemoryStream())
                {
                    using (MemoryStream pdbStream = new MemoryStream())
                    {
                        result = compilation.Emit(dllStream, pdbStream, options: emitOptions);
                        FileUtil.SaveAsset(path, dllStream.GetBuffer());
                        FileUtil.SaveAsset(pdbPath, pdbStream.GetBuffer());
                    }
                }
            }
            else
            {
                result = compilation.Emit(path);
            }
            if (result.Success)
            {
                LogUtil.Log("编译成功");
            }
            else
            {
                List <Diagnostic> failureList = (from diagnostic in result.Diagnostics where diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error select diagnostic).ToList();
                foreach (Diagnostic item in failureList)
                {
                    LogUtil.Log(item.ToString());
                }
            }
            return(result.Success);
        }
Esempio n. 53
0
 public abstract IList <TextChange> GetChanges(SyntaxTree oldTree);
Esempio n. 54
0
 /// <summary>
 /// Get the document in this project with the specified syntax tree.
 /// </summary>
 public Document GetDocument(SyntaxTree syntaxTree)
 {
     return(_solution.GetDocument(syntaxTree, this.Id));
 }
Esempio n. 55
0
        public void Compile()
        {
            Profiler.BeginSample("UdonSharp Compile");

            System.Diagnostics.Stopwatch compileTimer = new System.Diagnostics.Stopwatch();
            compileTimer.Start();

            int totalErrorCount = 0;

            try
            {
                EditorUtility.DisplayProgressBar("UdonSharp Compile", "Initializing...", 0f);

                UdonSharpProgramAsset[] allPrograms = UdonSharpProgramAsset.GetAllUdonSharpPrograms();
                List <(UdonSharpProgramAsset, string)> programAssetsAndPaths = new List <(UdonSharpProgramAsset, string)>();

                foreach (UdonSharpProgramAsset programAsset in allPrograms)
                {
                    if (programAsset == null)
                    {
                        continue;
                    }

                    if (programAsset.sourceCsScript == null)
                    {
                        Debug.LogWarning($"[<color=#FF00FF>UdonSharp</color>] Program asset '{AssetDatabase.GetAssetPath(programAsset)}' is missing a source C# script");
                        continue;
                    }

                    programAssetsAndPaths.Add((programAsset, AssetDatabase.GetAssetPath(programAsset.sourceCsScript)));

                    programAsset.compileErrors.Clear(); // Clear compile errors to keep them from stacking if not resolved
                }

                CheckProgramAssetCollisions(allPrograms);

                UdonSharpProgramAsset[] programAssetsToCompile = modules.Select(e => e.programAsset).Where(e => e != null && e.sourceCsScript != null).ToArray();

                EditorUtility.DisplayProgressBar("UdonSharp Compile", "Executing pre-build events...", 0f);

                try
                {
                    beforeCompile?.Invoke(programAssetsToCompile);
                }
                catch (System.Exception e)
                {
                    Debug.LogError($"Exception thrown by pre compile listener\n{e}");
                }

                EditorUtility.DisplayProgressBar("UdonSharp Compile", "Parsing Syntax Trees...", 0f);

                object syntaxTreeLock = new object();
                List <(UdonSharpProgramAsset, Microsoft.CodeAnalysis.SyntaxTree)> programsAndSyntaxTrees = new List <(UdonSharpProgramAsset, Microsoft.CodeAnalysis.SyntaxTree)>();
                Dictionary <UdonSharpProgramAsset, (string, Microsoft.CodeAnalysis.SyntaxTree)> syntaxTreeSourceLookup = new Dictionary <UdonSharpProgramAsset, (string, Microsoft.CodeAnalysis.SyntaxTree)>();

                string[] defines = UdonSharpUtils.GetProjectDefines(isEditorBuild);

                Parallel.ForEach(programAssetsAndPaths, (currentProgram) =>
                {
                    string programSource = UdonSharpUtils.ReadFileTextSync(currentProgram.Item2);

#pragma warning disable CS1701 // Warning about System.Collections.Immutable versions potentially not matching
                    Microsoft.CodeAnalysis.SyntaxTree programSyntaxTree = CSharpSyntaxTree.ParseText(programSource, CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.None).WithPreprocessorSymbols(defines));
#pragma warning restore CS1701

                    lock (syntaxTreeLock)
                    {
                        programsAndSyntaxTrees.Add((currentProgram.Item1, programSyntaxTree));
                        syntaxTreeSourceLookup.Add(currentProgram.Item1, (programSource, programSyntaxTree));
                    }
                });
Esempio n. 56
0
 public override AnalyzerConfigOptions GetOptions(SyntaxTree tree)
 {
     return(new WorkspaceAnalyzerConfigOptions(_projectState._lazyAnalyzerConfigSet.GetValue(CancellationToken.None).GetOptionsForSourcePath(tree.FilePath)));
 }
Esempio n. 57
0
 public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken)
 {
     // Because we override SourceGeneratedDocument.WithFrozenPartialSemantics directly, we shouldn't be able to get here.
     throw ExceptionUtilities.Unreachable;
 }
Esempio n. 58
0
 public abstract bool IsEquivalentTo(SyntaxTree tree, bool topLevel = false);
Esempio n. 59
0
 public abstract IList <TextSpan> GetChangedSpans(SyntaxTree syntaxTree);
        public CompileTaskResult Compile(List <ClassDefinition> classDefinitions, Microsoft.CodeAnalysis.SyntaxTree syntaxTree, string sourceCode, bool isEditorBuild)
        {
            programAsset.compileErrors.Clear();

            CompileTaskResult result = new CompileTaskResult();

            result.programAsset = programAsset;

            moduleSymbols.OpenSymbolTable();

            UdonSharpFieldVisitor fieldVisitor = new UdonSharpFieldVisitor(fieldsWithInitializers);

            fieldVisitor.Visit(syntaxTree.GetRoot());

            MethodVisitor methodVisitor = new MethodVisitor(resolver, moduleSymbols, moduleLabels);

            int errorCount = 0;

            try
            {
                methodVisitor.Visit(syntaxTree.GetRoot());
            }
            catch (System.Exception e)
            {
                LogException(result, e, methodVisitor.visitorContext.currentNode, out string logMessage);

                programAsset.compileErrors.Add(logMessage);

                errorCount++;
            }

            if (ErrorCount > 0)
            {
                return(result);
            }

            ClassDebugInfo debugInfo = null;

            if (settings == null || settings.buildDebugInfo)
            {
                debugInfo = new ClassDebugInfo(sourceCode, settings == null || settings.includeInlineCode);
            }

            ASTVisitor visitor = new ASTVisitor(resolver, moduleSymbols, moduleLabels, methodVisitor.definedMethods, classDefinitions, debugInfo);

            try
            {
                visitor.Visit(syntaxTree.GetRoot());
                visitor.VerifyIntegrity();
            }
            catch (System.Exception e)
            {
                LogException(result, e, visitor.visitorContext.currentNode, out string logMessage);

                programAsset.compileErrors.Add(logMessage);

                errorCount++;
            }

            if (errorCount > 0)
            {
                return(result);
            }

            moduleSymbols.CloseSymbolTable();

            if (errorCount == 0)
            {
                compiledClassDefinition = classDefinitions.Find(e => e.userClassType == visitor.visitorContext.behaviourUserType);

                string dataBlock = BuildHeapDataBlock();
                string codeBlock = visitor.GetCompiledUasm();

                result.compiledAssembly = dataBlock + codeBlock;
                result.symbolCount      = (uint)(moduleSymbols.GetAllUniqueChildSymbols().Count + visitor.GetExternStrCount());

                programAsset.behaviourIDHeapVarName = visitor.GetIDHeapVarName();

                programAsset.fieldDefinitions = visitor.visitorContext.localFieldDefinitions;
#if UDON_BETA_SDK
                programAsset.behaviourSyncMode = visitor.visitorContext.behaviourSyncMode;
#endif

                if (debugInfo != null)
                {
                    debugInfo.FinalizeDebugInfo();
                }

                UdonSharpEditorCache.Instance.SetDebugInfo(programAsset, isEditorBuild ? UdonSharpEditorCache.DebugInfoType.Editor : UdonSharpEditorCache.DebugInfoType.Client, debugInfo);
                //programAsset.debugInfo = debugInfo;
            }

            return(result);
        }