コード例 #1
0
        public static void Deconstruct(
            this string text,
            out SyntaxTree tree,
            out string formatter,
            out IEnumerable <Diagnostic> errors)
        {
            tree = CSharpSyntaxTree.ParseText(text.Trim(), _options);
            SyntaxNode root = Formatter.Format(tree.GetCompilationUnitRoot(), _workSpace);

            _workSpace.ClearSolution();
            tree      = root.SyntaxTree;
            formatter = tree.ToString();
            errors    = tree.GetDiagnostics();
        }
コード例 #2
0
        public void CompileScript(string code)
        {
            try
            {
                _script = CSharpScript.Create(code, ScriptOptions.Default
                                              .WithReferences(
                                                  typeof(object).Assembly,
                                                  typeof(CsvReader).Assembly,
                                                  typeof(ICsvEditSharpConfigurationHost).Assembly)
                                              .WithImports(
                                                  "System",
                                                  "System.Collections.Generic",
                                                  "System.Linq",
                                                  "System.Globalization",
                                                  "System.Text",
                                                  "CsvHelper.Configuration",
                                                  "CsvHelper",
                                                  "CsvEditSharp.Models"),
                                              typeof(ICsvEditSharpConfigurationHost));

                _workspace.ClearSolution();
                var project    = _workspace.AddProject(_projectInfo);
                var sourcetext = Microsoft.CodeAnalysis.Text.SourceText.From(code);
                _workspace.AddDocument(project.Id, "Config.csx", sourcetext);

                var compilation = _script.GetCompilation();
                var syntaxTree  = compilation.SyntaxTrees.First();
                _semanticModel = compilation.GetSemanticModel(syntaxTree);
            }
            catch (CompilationErrorException e)
            {
                _errorMessages.Add(e.Message + Environment.NewLine + e.Diagnostics);
                _script = null;
            }
        }
コード例 #3
0
        public void CompileScript(string code)
        {
            try
            {
                workspace.ClearSolution();
                workspace.AddProject(projectInfo);
                var scriptDocumentInfo = DocumentInfo.Create(
                    documentId,
                    "Config.csx",
                    sourceCodeKind: SourceCodeKind.Script,
                    loader: TextLoader.From(TextAndVersion.Create(SourceText.From(code), VersionStamp.Create())));
                document          = workspace.AddDocument(scriptDocumentInfo);
                completionService = CompletionService.GetService(document);

                script = CSharpScript.Create(
                    code,
                    ScriptOptions.Default
                    .WithReferences(referenceTypes.Select(t => t.Assembly).Distinct())
                    .WithImports(referenceTypes.Select(t => t.Namespace).Distinct()),
                    typeof(ICsvEditSharpConfigurationHost));
            }
            catch (CompilationErrorException e)
            {
                errorMessages.Add(e.Message + Environment.NewLine + e.Diagnostics);
                script = null;
            }
        }
コード例 #4
0
        public override SyntaxTree LoadTree(SyntaxTree tree)
        {
            SyntaxNode root = Formatter.Format(tree.GetCompilationUnitRoot(), _workSpace);

            tree = root.SyntaxTree;
            _workSpace.ClearSolution();
            return(tree);
        }
コード例 #5
0
        public bool PopulateIntellisenseListBox()
        {
            IntellisenseListBox.Items.Clear();
            _workspace.ClearSolution();
            _completionList    = new List <string>();
            _charsToRemoveList = new List <int>();

            string script = "";

            if (ActiveTextBox is TextBox)
            {
                Variables.ForEach(v => script += $"{v.VariableType.GetRealTypeFullName()}? {v.VariableName} = " +
                                                 $"{(v.VariableValue == null || (v.VariableValue is string && string.IsNullOrEmpty(v.VariableValue.ToString())) ? "null" : v.VariableValue.ToString().Trim())};");
                Arguments.ForEach(a => script += $"{a.ArgumentType.GetRealTypeFullName()}? {a.ArgumentName} = " +
                                                 $"{(a.ArgumentValue == null || (a.ArgumentValue is string && string.IsNullOrEmpty(a.ArgumentValue.ToString())) ? "null" : a.ArgumentValue.ToString().Trim())};");

                TextBox activeTextBox = (TextBox)ActiveTextBox;

                var scriptCode = script + activeTextBox.Text;

                var results = LoadIntellisenseScript(script, scriptCode);

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

                foreach (var i in results.Items)
                {
                    string recString = activeTextBox.Text.Substring(i.Span.Start - script.Length, i.Span.Length);
                    if (scriptCode[script.Length + activeTextBox.SelectionStart - 1] != '.')
                    {
                        if (recString != "" && i.DisplayText.Length >= recString.Length && i.DisplayText.Substring(0, recString.Length).ToLower().Equals(recString.ToLower()))
                        {
                            if (recString != "")
                            {
                                _completionList.Add(i.DisplayText);
                                _charsToRemoveList.Add(recString.Length);
                            }
                            else
                            {
                                _completionList.Add(i.DisplayText);
                                _charsToRemoveList.Add(0);
                            }
                            IntellisenseListBox.Items.Add(new UIIntellisenseListBoxItem(i.DisplayText, GetIntellisenseIcon(i)));
                        }
                    }
                    else
                    {
                        _completionList.Add(i.DisplayText);
                        _charsToRemoveList.Add(0);
                        IntellisenseListBox.Items.Add(new UIIntellisenseListBoxItem(i.DisplayText, GetIntellisenseIcon(i)));
                    }
                }
            }
            else if (ActiveTextBox is UIScintilla)
            {
                UIScintilla activeScintilla = (UIScintilla)ActiveTextBox;

                var scriptCode = script + activeScintilla.Text;

                if (activeScintilla.SelectionStart >= scriptCode.Length)
                {
                    activeScintilla.SelectionStart = scriptCode.Length - 1;
                }
                var results = LoadIntellisenseScript(script, scriptCode);

                if (results == null)
                {
                    return(false);
                }
                try
                {
                    foreach (var i in results.Items)
                    {
                        int trueLength = i.Span.Length;
                        if (i.Span.Length == 0)
                        {
                            trueLength = 1;
                        }
                        string recString = activeScintilla.Text.Substring(i.Span.Start - script.Length, trueLength);
                        if (scriptCode[script.Length + activeScintilla.SelectionStart] != '.')
                        {
                            if (recString != "" && i.DisplayText.Length >= recString.Length && i.DisplayText.Substring(0, recString.Length).ToLower().Equals(recString.ToLower()))
                            {
                                if (recString != "")
                                {
                                    _completionList.Add(i.DisplayText);
                                    _charsToRemoveList.Add(recString.Length);
                                }
                                else
                                {
                                    _completionList.Add(i.DisplayText);
                                    _charsToRemoveList.Add(0);
                                }
                                IntellisenseListBox.Items.Add(new UIIntellisenseListBoxItem(i.DisplayText, GetIntellisenseIcon(i)));
                            }
                        }
                        else
                        {
                            _completionList.Add(i.DisplayText);
                            _charsToRemoveList.Add(0);
                            IntellisenseListBox.Items.Add(new UIIntellisenseListBoxItem(i.DisplayText, GetIntellisenseIcon(i)));
                        }
                    }
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    Console.WriteLine(ex);
                }
            }

            if (IntellisenseListBox.Items.Count <= 0)
            {
                return(false);
            }

            return(true);
        }
コード例 #6
0
        /// <summary>
        /// Fidns references using Roslyn by the Unity Coroutine paradigm. When Enumator returns, then a frame should be skipped.
        /// </summary>
        /// <param name="asset"></param>
        /// <param name="results"></param>
        public static IEnumerator <State> FindReferencesEnumerator(UnityEngine.Object asset, List <AnalyticResult> results)
        {
            Stopwatch w = new Stopwatch();

            w.Start();

            //Get the parts
            if (asset is MonoBehaviour monoBehaviour)
            {
                asset = MonoScript.FromMonoBehaviour(monoBehaviour);
            }
            else if (asset is ScriptableObject scriptableObject)
            {
                asset = MonoScript.FromScriptableObject(scriptableObject);
            }

            //Make sure its a monoscript
            if (!(asset is MonoScript))
            {
                throw new ArgumentException("Supplied argument is not a MonoScript");
            }

            var    _          = typeof(Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions);
            string scriptPath = Path.GetFullPath(UnityEditor.AssetDatabase.GetAssetPath(asset));

            //Prepare paths
            string folder      = Application.dataPath + "/../";
            string projectPath = Directory.EnumerateFiles(folder, "Assembly-CSharp.csproj", SearchOption.TopDirectoryOnly).First();

            //projectPath = @"D:\Users\Lachee\Documents\Unity Projects\DistanceJam\Assembly-CSharp.csproj";

            //Prepare workspace
            workspace.ClearSolution();

            //Prepare solution
            var solId        = SolutionId.CreateNewId();
            var solutionInfo = SolutionInfo.Create(solId, VersionStamp.Default);
            var solution     = workspace.AddSolution(solutionInfo);

            //Prepare the project
            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "Assembly-CSharp", "Assembly-CSharp", "C#", projectPath);
            var project     = workspace.AddProject(projectInfo);

            yield return(State.ReadingFile);

            //Prepare the documents
            Document    sourceDocument = null;
            XmlDocument xml            = new XmlDocument();

            xml.Load(projectPath);
            var elements = xml.GetElementsByTagName("Compile");

            foreach (XmlElement element in elements)
            {
                var includePath = Path.GetFullPath(Path.GetDirectoryName(projectPath) + "/" + element.GetAttribute("Include"));

                //workspace.AddDocument(compileDocument);
                var name        = Path.GetFileName(includePath);
                var fileContent = File.ReadAllText(includePath);
                var src         = SourceText.From(fileContent);
                var doc         = project.AddDocument(name, src, filePath: includePath);
                project = doc.Project;
                if (includePath.Equals(scriptPath))
                {
                    sourceDocument = doc;
                }
                yield return(State.ReadingFile);
            }

            workspace.TryApplyChanges(solution);

            if (sourceDocument != null)
            {
                //Find the model
                var modelAwait = sourceDocument.GetSemanticModelAsync().ConfigureAwait(false);
                while (!modelAwait.GetAwaiter().IsCompleted)
                {
                    yield return(State.FindingModel);
                }
                var model = modelAwait.GetAwaiter().GetResult();

                //Find hte root
                var rootAwait = sourceDocument.GetSyntaxRootAsync().ConfigureAwait(false);
                while (!rootAwait.GetAwaiter().IsCompleted)
                {
                    yield return(State.FindingRoot);
                }
                var root = rootAwait.GetAwaiter().GetResult();

                //Find the symbol
                var syntax = root.DescendantNodes().OfType <ClassDeclarationSyntax>().First();
                var symbol = model.GetDeclaredSymbol(syntax);

                //Find the references
                var referencesAwait = SymbolFinder.FindReferencesAsync(symbol, sourceDocument.Project.Solution).ConfigureAwait(false);
                while (!referencesAwait.GetAwaiter().IsCompleted)
                {
                    yield return(State.FindingSymbol);
                }
                var references = referencesAwait.GetAwaiter().GetResult();
                results.AddRange(references.SelectMany(s => s.Locations).Select(loc => new AnalyticResult(loc)));
            }

            yield return(State.Done);
        }