public IEnumerable<SyntaxTreeDiagnosticResult> Compile(string sourceCode, ScriptOptions options = null) { if (String.IsNullOrEmpty(sourceCode)) throw new ArgumentException(nameof(sourceCode)); _previousCompilations.Push(sourceCode); Script prev = _scriptQueue.Any() ? _scriptQueue.Pop() : null; var script = CSharpScript.Create(sourceCode, options ?? DefaultOptions).WithPrevious(prev); ScriptState endState = null; try { endState = script.RunAsync(); } catch (CompilationErrorException ex) { var compilationError = new SyntaxTreeDiagnosticResult(ex.Message); _diagnosticMessages.Add(compilationError); } _scriptQueue.Push(endState.Script); if (endState.Variables != null) { var res = endState.Variables .Select(v => new SyntaxTreeDiagnosticResult(-1, -1, v.Name + v.Value) { Name = v.Name, Value = v.Value.ToString() }) .ToList(); _variables.AddRange(res); } return _diagnosticMessages.Any() ? _diagnosticMessages : _variables; }
public List<SyntaxTreeDiagnosticResult> Compile(string sourceCode) { var errors = GetSourceCodeDiagnostics(sourceCode); if (errors != null && errors.Count > 0) return errors.ToList(); var compilation = CSharpCompilation.Create("TestCompile", new[] { Tree }, new MetadataReference[] { MetadataReference.CreateFromFile(typeof(Object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location), MetadataReference.CreateFromFile(typeof(Thread).Assembly.Location) }, new CSharpCompilationOptions(OutputKind.ConsoleApplication)); var semanticModel = compilation.GetSemanticModel(Tree); var binaryExpressions = Root.DescendantNodes() .OfType<BinaryExpressionSyntax>() .OrderBy(x => x.FullSpan) .Cast<ExpressionSyntax>() .ToList(); var literals = Root.DescendantNodes() .OfType<LiteralExpressionSyntax>() .OrderBy(x => x.FullSpan) .Cast<ExpressionSyntax>() .ToList(); var resultingList = new List<SyntaxTreeDiagnosticResult>(); foreach (var variable in literals.Concat(binaryExpressions)) { var startLine = Tree.GetLineSpan(variable.Span).StartLinePosition; var value = semanticModel.GetConstantValue(variable); var syntaxResult = new SyntaxTreeDiagnosticResult(startLine.Line, 0, value.Value?.ToString()); if (!value.HasValue) { var res = new StringBuilder(); foreach (var item in variable.ChildNodesAndTokens()) { if (item.IsToken) { res.Append(item.ToFullString()); continue; } var expressionValue = semanticModel.GetConstantValue(item.AsNode()); if (!expressionValue.HasValue) { res.Append(item.ToFullString()); } else res.Append(expressionValue.Value?.ToString()); } syntaxResult.LinePosition = -1; syntaxResult.Message = res.ToString(); resultingList.Add(syntaxResult); } else resultingList.Add(syntaxResult); } return resultingList; }