Exemplo n.º 1
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());
        }
Exemplo n.º 2
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());
        }
Exemplo n.º 3
0
        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");
        }
Exemplo n.º 4
0
        /// <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());
        }
Exemplo n.º 5
0
 protected override IEnumerable<string> ReportAllErrors(SyntaxTree userSolution)
 {
     var recursiveMethods = userSolution.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Where(IsRecursive).ToList();
     if (requireRecursion && !recursiveMethods.Any())
         yield return Report(userSolution.GetRoot(), "Решение должно быть рекурсивным");
     if (!requireRecursion && recursiveMethods.Any())
         yield return Report(userSolution.GetRoot(), "Решение должно быть нерекурсивным");
 }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
0
		public ExerciseBlock BuildBlockFrom(SyntaxTree tree)
		{
			ExerciseClassName = null;
			Exercise.ExerciseInitialCode = GetUncomment(tree.GetRoot()) ?? ""; //for uncomment-comment without exercise method
			SyntaxNode result = Visit(tree.GetRoot());
			var exerciseInsertIndex = GetExerciseInsertIndex(result);
			const string pragma = "\n#line 1\n";
			Exercise.ExerciseCode = prelude + result.ToFullString().Insert(exerciseInsertIndex, pragma);
			Exercise.IndexToInsertSolution = prelude.Length + exerciseInsertIndex + pragma.Length;
			return Exercise;
		}
Exemplo n.º 8
0
 public IEnumerable<Match> Run(SyntaxTree tree)
 {
     return tree.GetRoot()
                .DescendantNodesAndTokensAndSelf()
                .Select(CreateMatch)
                .Where(n => n.IsMatch);
 }
        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 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;
        }
            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));
            }
Exemplo n.º 12
0
 public static IEnumerable<PropertyDeclarationSyntax> GetProperties(SyntaxTree syntaxTree)
 {
     var result = syntaxTree.GetRoot().DescendantNodes()
         .Where(node => node.IsKind(SyntaxKind.PropertyDeclaration))
         .Cast<PropertyDeclarationSyntax>();
     return result;
 }
Exemplo n.º 13
0
 public IEnumerable<AttributeListSyntax> GetAttributeListsNodes(SyntaxTree syntaxTree)
 {
     if (syntaxTree == null) throw new ArgumentNullException(nameof(syntaxTree));
     return syntaxTree.GetRoot()
        .DescendantNodes()
        .OfType<AttributeListSyntax>();
 }
Exemplo n.º 14
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)})");
			}
		}
Exemplo n.º 15
0
        /// <summary>
        /// Rewrites the syntax tree with field access expressions.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>SyntaxTree</returns>
        internal SyntaxTree Rewrite(SyntaxTree tree)
        {
            var expressions = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().
                ToList();

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

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

            return base.UpdateSyntaxTree(tree, root.ToString());
        }
Exemplo n.º 16
0
 public static string GetNamespace(SyntaxTree syntaxTree)
 {
     return syntaxTree.GetRoot().DescendantNodes()
         .Where(node => node.IsKind(SyntaxKind.NamespaceDeclaration))
         .Cast<NamespaceDeclarationSyntax>()
         .First()
         .Name.ToString();
 }
Exemplo n.º 17
0
		private static void ModifyTreeViaRewriter(SyntaxTree tree)
		{
			Console.Out.WriteLine(nameof(Program.ModifyTreeViaRewriter));

			Console.Out.WriteLine(tree);
			var newTree = new MethodRewriter().Visit(tree.GetRoot());
			Console.Out.WriteLine(newTree);
		}
Exemplo n.º 18
0
		public static bool IsExercise(SyntaxTree tree)
		{
			return 
				tree.GetRoot()
				.DescendantNodes()
				.OfType<MethodDeclarationSyntax>()
				.Any(m => m.HasAttribute<ExpectedOutputAttribute>());
		}
Exemplo n.º 19
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));
		}
Exemplo n.º 20
0
 public static IEnumerable<ClassDeclarationSyntax> GetAttributedClasses(SyntaxTree syntaxTree)
 {
     return syntaxTree.GetRoot().DescendantNodes()
         .OfType<AttributeSyntax>()
         .Where(attribute => attribute.Name.ToString().Equals("AutoGetHashCode"))
         .Select(attribute => attribute.Parent.Parent)
         .Cast<ClassDeclarationSyntax>();
 }
Exemplo n.º 21
0
        /// <summary>
        /// Rewrites the syntax tree with halt event types.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>SyntaxTree</returns>
        internal SyntaxTree Rewrite(SyntaxTree tree)
        {
            var types = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().
                Where(val => val.Identifier.ValueText.Equals("halt")).
                ToList();

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

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

            return base.UpdateSyntaxTree(tree, root.ToString());
        }
Exemplo n.º 22
0
 public Metrics(SyntaxTree tree) : base(tree)
 {
     var root = tree.GetRoot();
     if (root.Language != LanguageNames.VisualBasic)
     {
         throw new ArgumentException(InitalizationErrorTextPattern, nameof(tree));
     }
 }
 private Boolean IsAutoGenerated(SyntaxTree tree)
     => tree.GetRoot()
         .GetLeadingTrivia()
         .Where(t =>
             t.IsKind(SyntaxKind.SingleLineCommentTrivia)
             && t.ToString().IndexOf("<auto-generated>", StringComparison.OrdinalIgnoreCase) != -1
         )
         .Any();
        /// <summary>
        /// Rewrites the syntax tree with nondetermnistic choice expressions.
        /// </summary>
        /// <param name="tree">SyntaxTree</param>
        /// <returns>SyntaxTree</returns>
        internal SyntaxTree Rewrite(SyntaxTree tree)
        {
            var expressions = tree.GetRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().
                Where(val => val.Kind() == SyntaxKind.PointerIndirectionExpression).
                Where(val => val.Parent is IfStatementSyntax).
                ToList();

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

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

            return base.UpdateSyntaxTree(tree, root.ToString());
        }
Exemplo n.º 25
0
		public string FindError(SyntaxTree userSolution)
		{
			var cu = userSolution.GetRoot() as CompilationUnitSyntax;
			if (cu == null) return ShouldBeMethod;
			if (cu.Members.Count > 1) return ShouldBeSingleMethod;
			var method = cu.Members[0] as MethodDeclarationSyntax;
			if (method == null) return ShouldBeMethod;
			return FindError(method);
		}
Exemplo n.º 26
0
        /// <summary>
        /// Rewrites the syntax tree with assert statements.
        /// </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("assert")).
                ToList();

            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());
        }
 private static bool HasGeneratedRegion(SyntaxTree tree)
 {
     return tree
         .GetRoot()
         .DescendantTrivia()
         .Any(
             t =>
                 t.IsKind(SyntaxKind.RegionDirectiveTrivia) &&
                 CultureInfo.InvariantCulture.CompareInfo.IndexOf(t.ToString(), "generated", CompareOptions.IgnoreCase) >= 0);
 }
Exemplo n.º 28
0
        public void Compile()
        {
            using (var workspace = new AdhocWorkspace())
            {
                var document = workspace.CurrentSolution.AddProject("foo", "foo.dll", LanguageNames.CSharp)
                    .AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                    .AddMetadataReference(MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location))
                    .AddDocument("test", SymbolHelperTest.TestInput);
                compilation = document.Project.GetCompilationAsync().Result;
                tree = compilation.SyntaxTrees.First();
                semanticModel = compilation.GetSemanticModel(tree);

                baseClassDeclaration = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>()
                    .First(m => m.Identifier.ValueText == "Base");
                derivedClassDeclaration1 = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>()
                    .First(m => m.Identifier.ValueText == "Derived1");
                derivedClassDeclaration2 = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>()
                    .First(m => m.Identifier.ValueText == "Derived2");
            }
        }
Exemplo n.º 29
0
		private static Slide ParseSyntaxTree(SyntaxTree tree, SlideInfo slideInfo, string prelude,
			IFileSystem getInclude)
		{
			var blocksBuilder = new SlideBuilder(getInclude);
			blocksBuilder.Visit(tree.GetRoot());
			if (!ExerciseBuilder.IsExercise(tree))
				return new Slide(blocksBuilder.Blocks, slideInfo, blocksBuilder.Title, blocksBuilder.Id);
			var exerciseBlock = new ExerciseBuilder(SlideBuilder.LangId, prelude).BuildBlockFrom(tree);
			blocksBuilder.Blocks.Add(exerciseBlock);
			return new ExerciseSlide(blocksBuilder.Blocks, slideInfo, blocksBuilder.Title, blocksBuilder.Id);
		}
Exemplo n.º 30
0
		private static void ModifyTreeViaTree(SyntaxTree tree)
		{
			Console.Out.WriteLine(nameof(Program.ModifyTreeViaTree));
			Console.Out.WriteLine(tree);
			var methods = tree.GetRoot().DescendantNodes(_ => true)
				.OfType<MethodDeclarationSyntax>();

			var newTree = tree.GetRoot().ReplaceNodes(methods, (method, methodWithReplacements) =>
			{
				var visibilityTokens = method.DescendantTokens(_ => true)
					.Where(_ => _.IsKind(SyntaxKind.PublicKeyword) ||
						_.IsKind(SyntaxKind.PrivateKeyword) ||
						_.IsKind(SyntaxKind.ProtectedKeyword) ||
						_.IsKind(SyntaxKind.InternalKeyword)).ToImmutableList();

				if (!visibilityTokens.Any(_ => _.IsKind(SyntaxKind.PublicKeyword)))
				{
					var tokenPosition = 0;

					var newMethod = method.ReplaceTokens(visibilityTokens,
						(_, __) =>
						{
							tokenPosition++;
							
							return tokenPosition == 1 ?
								SyntaxFactory.Token(
									_.LeadingTrivia,
									SyntaxKind.PublicKeyword,
									_.TrailingTrivia) :
								new SyntaxToken();
						});
					return newMethod;
				}
				else
				{
					return method;
				}
			});

			Console.Out.WriteLine(newTree);
		}
Exemplo n.º 31
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);
        }
Exemplo n.º 32
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 virtual SyntaxTree Normalize(SyntaxTree syntaxTree)
		{
			SemanticModel = Compilation.GetSemanticModel(syntaxTree);

			_rootNode = syntaxTree.GetRoot();
			var normalizedRoot = Visit(_rootNode);

			if (_rootNode == normalizedRoot)
				return syntaxTree;

			return syntaxTree.WithRoot(normalizedRoot);
		}
Exemplo n.º 33
0
        public List <string> GetMethodParams(string scriptCode, int position)
        {
            //position = position - 2;
            List <string> overloads = new List <string>();
            var           meta      = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES");

            string[] assemblies     = 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();

            try
            {
                if (_ref == null)
                {
                    _ref = _ref = new MetadataReference[0];


                    var assembliest = AppDomain.CurrentDomain.GetAssemblies()
                                      .Where(a => !a.IsDynamic && File.Exists(a.Location));


                    MetadataReference[] _refs2 = assembliest
                                                 .Select(asm => MetadataReference.CreateFromFile(asm.Location))
                                                 .ToArray();



                    try
                    {
                        foreach (var item in DependencyContext.Default.CompileLibraries)
                        {
                            try
                            {
                                var arr = item.ResolveReferencePaths().Select(asm => MetadataReference.CreateFromFile(asm))?
                                          .ToArray();
                                _ref = _ref.Concatenate(arr);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }



                    _ref = _ref.Concatenate(_refs2);
                }

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

                var model = compilation.GetSemanticModel(syntaxTree);

                var theToken = syntaxTree.GetRoot().FindToken(position);
                var theNode  = theToken.Parent;
                while (!theNode.IsKind(Microsoft.CodeAnalysis.CSharp.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;

                    //overloads = containingType?.GetMembers(symbol.Name);
                    if (symbolInfo.CandidateSymbols != null)
                    {
                        if (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);
                                    //var smpl = parameters.ToMinimalDisplayString();
                                    overloads.Add(mp);
                                }
                            }
                        }
                    }
                }

                return(overloads);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemplo n.º 34
0
 public AnalyzerWithInvalidDiagnosticLocation(SyntaxTree treeInAnotherCompilation, ActionKind actionKind)
 {
     _invalidLocation = treeInAnotherCompilation.GetRoot().GetLocation();
     _actionKind      = actionKind;
 }
Exemplo n.º 35
0
 private void ReportTreeDiagnostics(SyntaxTree tree, Action <Diagnostic> addDiagnostic)
 {
     ReportDiagnosticsCore(addDiagnostic, tree.GetRoot().GetLastToken().GetLocation(), tree.FilePath);
 }
Exemplo n.º 36
0
 private static SourceText BuildRecoverableTreeText(SyntaxTree tree, Encoding encoding, CancellationToken cancellationToken)
 {
     // build text from root, so recoverable tree won't cycle.
     return(tree.GetRoot(cancellationToken).GetText(encoding));
 }
Exemplo n.º 37
0
        internal static void VerifySource(this SyntaxTree tree, IEnumerable <TextChangeRange> changes = null)
        {
            var        root     = tree.GetRoot();
            var        text     = tree.GetText();
            var        fullSpan = new TextSpan(0, text.Length);
            SyntaxNode node     = null;

            // If only a subset of the document has changed,
            // just check that subset to reduce verification cost.
            if (changes != null)
            {
                var change = TextChangeRange.Collapse(changes).Span;
                if (change != fullSpan)
                {
                    // Find the lowest node in the tree that contains the changed region.
                    node = root.DescendantNodes(n => n.FullSpan.Contains(change)).LastOrDefault();
                }
            }

            if (node == null)
            {
                node = root;
            }

            var  span        = node.FullSpan;
            var  textSpanOpt = span.Intersection(fullSpan);
            int  index;
            char found    = default;
            char expected = default;

            if (textSpanOpt == null)
            {
                index = 0;
            }
            else
            {
                var fromText = text.ToString(textSpanOpt.Value);
                var fromNode = node.ToFullString();
                index = FindFirstDifference(fromText, fromNode);
                if (index >= 0)
                {
                    found    = fromNode[index];
                    expected = fromText[index];
                }
            }

            if (index >= 0)
            {
                index += span.Start;
                string message;
                if (index < text.Length)
                {
                    var position = text.Lines.GetLinePosition(index);
                    var line     = text.Lines[position.Line];
                    var allText  = text.ToString(); // Entire document as string to allow inspecting the text in the debugger.
                    message = $"Unexpected difference at offset {index}: Line {position.Line + 1}, Column {position.Character + 1} \"{line.ToString()}\"  (Found: [{found}] Expected: [{expected}])";
                }
                else
                {
                    message = "Unexpected difference past end of the file";
                }
                Debug.Assert(false, message);
            }
        }
Exemplo n.º 38
0
        public static SourceGeneratedDocumentState Create(
            string hintName,
            SourceText generatedSourceText,
            SyntaxTree generatedSyntaxTree,
            DocumentId documentId,
            ISourceGenerator sourceGenerator,
            HostLanguageServices languageServices,
            SolutionServices solutionServices,
            CancellationToken cancellationToken
            )
        {
            var options  = generatedSyntaxTree.Options;
            var filePath = generatedSyntaxTree.FilePath;

            var textAndVersion = TextAndVersion.Create(generatedSourceText, VersionStamp.Create());
            ValueSource <TextAndVersion> textSource = new ConstantValueSource <TextAndVersion>(
                textAndVersion
                );

            var root = generatedSyntaxTree.GetRoot(cancellationToken);

            Contract.ThrowIfNull(
                languageServices.SyntaxTreeFactory,
                "We should not have a generated syntax tree for a language that doesn't support trees."
                );

            if (languageServices.SyntaxTreeFactory.CanCreateRecoverableTree(root))
            {
                // We will only create recoverable text if we can create a recoverable tree; if we created a
                // recoverable text but not a new tree, it would mean tree.GetText() could still potentially return
                // the non-recoverable text, but asking the document directly for it's text would give a recoverable
                // text with a different object identity.
                textSource = CreateRecoverableText(textAndVersion, solutionServices);

                generatedSyntaxTree = languageServices.SyntaxTreeFactory.CreateRecoverableTree(
                    documentId.ProjectId,
                    filePath: generatedSyntaxTree.FilePath,
                    options,
                    textSource,
                    generatedSourceText.Encoding,
                    root
                    );
            }

            var treeAndVersion = TreeAndVersion.Create(generatedSyntaxTree, textAndVersion.Version);

            return(new SourceGeneratedDocumentState(
                       languageServices,
                       solutionServices,
                       documentServiceProvider: null,
                       new DocumentInfo.DocumentAttributes(
                           documentId,
                           name: hintName,
                           folders: SpecializedCollections.EmptyReadOnlyList <string>(),
                           options.Kind,
                           filePath: filePath,
                           isGenerated: true,
                           designTimeOnly: false
                           ),
                       options,
                       sourceText: null, // don't strongly hold the text
                       textSource,
                       treeAndVersion,
                       sourceGenerator,
                       hintName
                       ));
        }
Exemplo n.º 39
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);
        }
        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);
        }