public void EnsureCreateClass_FromSqlTableReference_AndFromQuery_ProduceEquivalentResults() { string classFromQuery = string.Empty, classFromTable = string.Empty; "Given a C# class generated from a query" ._(() => { var query = string.Format("select * from {0}", TableName); classFromQuery = CSharpClassGeneratorFromQueryViaSqlDescribeResultSet .GenerateClass(SqlConnectionProviders.AdventureWorksDb, query, "Employee"); var compileResults = RoslynHelper.TryCompile(classFromQuery); compileResults.IsValid().Should().BeTrue(); }); "Given a C# class generated from SQL InformationSchema metadata" ._(() => { var sqlTableReference = new SqlTableReference(SqlConnectionProviders.AdventureWorksDb, TableName); classFromTable = CSharpClassGeneratorFromInformationSchema.CreateCSharpClass(sqlTableReference); var compileResults = RoslynHelper.TryCompile(classFromTable); compileResults.IsValid().Should().BeTrue(); }); "They should produce identical output" ._(() => { Console.WriteLine("From Query:\r\n" + classFromQuery); Console.WriteLine("From Table:\r\n" + classFromTable); classFromTable.Should().BeEquivalentTo(classFromQuery); }); }
private static MemberDeclarationSyntax CreateClass(string indexName, IndexDefinition indexDefinition) { var safeName = GetCSharpSafeName(indexName); //Create a class var @class = RoslynHelper.PublicClass(safeName) .WithBaseClass <AbstractIndexCreationTask>(); // Create a IndexName get property PropertyDeclarationSyntax indexNameProperty = PropertyDeclaration(ParseTypeName("string"), Identifier(IndexName)) .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword)) .AddAccessorListAccessors( AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, Block( List(new[] { ReturnStatement(IdentifierName($"\"{indexName}\"")) } )))); // Add the property to the class @class = @class.AddMembers(indexNameProperty); //Create CreateIndexDefinition method MethodDeclarationSyntax indexDefinitionMethod = MethodDeclaration(ParseTypeName(typeof(IndexDefinition).Name), Identifier(CreateIndexDefinition)) .AddModifiers(Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.OverrideKeyword)) .WithBody(Block(SingletonList <StatementSyntax>( ReturnStatement(ObjectCreationExpression(IdentifierName(typeof(IndexDefinition).Name)) .WithInitializer(InitializerExpression(SyntaxKind.ObjectInitializerExpression, SeparatedList <ExpressionSyntax>(CreateStatements(indexDefinition)))))))); // Add the Method to the class @class = @class.AddMembers(indexDefinitionMethod); return(@class); }
private static string GetText(string indexName, IndexDefinition indexDefinition) { var usings = RoslynHelper.CreateUsings(Usings); // Create a IndexName get property PropertyDeclarationSyntax indexNameProperty = PropertyDeclaration(PredefinedType(Token(TriviaList(), SyntaxKind.StringKeyword, TriviaList(Space))), Identifier(TriviaList(), IndexName, TriviaList(Space))) .WithModifiers(TokenList(Token(TriviaList(Tab), SyntaxKind.PublicKeyword, TriviaList(Space)), Token(TriviaList(), SyntaxKind.OverrideKeyword, TriviaList(Space)))) .WithExpressionBody(ArrowExpressionClause( LiteralExpression(SyntaxKind.StringLiteralExpression, Literal($"{indexName}"))) .WithArrowToken(Token(TriviaList(), SyntaxKind.EqualsGreaterThanToken, TriviaList(Space)))) .WithSemicolonToken(Token(TriviaList(), SyntaxKind.SemicolonToken, TriviaList(LineFeed, LineFeed))); MethodDeclarationSyntax createIndexDefinition = MethodDeclaration(IdentifierName(Identifier(TriviaList(), "IndexDefinition", TriviaList(Space))), Identifier(CreateIndexDefinition)) .WithModifiers(TokenList(Token(TriviaList(Tab), SyntaxKind.PublicKeyword, TriviaList(Space)), Token(TriviaList(), SyntaxKind.OverrideKeyword, TriviaList(Space)))) .WithParameterList(ParameterList().WithCloseParenToken(Token(TriviaList(), SyntaxKind.CloseParenToken, TriviaList(LineFeed)))) .WithBody(Block( SingletonList <StatementSyntax>(ReturnStatement( ObjectCreationExpression(IdentifierName(Identifier(TriviaList(), "IndexDefinition", TriviaList(LineFeed)))) .WithNewKeyword(Token(TriviaList(), SyntaxKind.NewKeyword, TriviaList(Space))) .WithInitializer(InitializerExpression(SyntaxKind.ObjectInitializerExpression, SeparatedList <ExpressionSyntax>(ParsingIndexDefinitionFields(indexDefinition))) .WithOpenBraceToken(Token(TriviaList(Tab, Tab), SyntaxKind.OpenBraceToken, TriviaList(LineFeed))) .WithCloseBraceToken(Token(TriviaList(LineFeed, Tab, Tab), SyntaxKind.CloseBraceToken, TriviaList())))) .WithReturnKeyword(Token(TriviaList(Tab, Tab), SyntaxKind.ReturnKeyword, TriviaList(Space))) .WithSemicolonToken(Token(TriviaList(), SyntaxKind.SemicolonToken, TriviaList(LineFeed))))) .WithOpenBraceToken(Token(TriviaList(Tab), SyntaxKind.OpenBraceToken, TriviaList(LineFeed))) .WithCloseBraceToken(Token(TriviaList(Tab), SyntaxKind.CloseBraceToken, TriviaList(LineFeed)))); ClassDeclarationSyntax c = ClassDeclaration(Identifier(TriviaList(), GetCSharpSafeName(indexName), TriviaList(Space))) .AddModifiers(Token(TriviaList(LineFeed, LineFeed), SyntaxKind.PublicKeyword, TriviaList(Space))) .WithKeyword(Token(TriviaList(), SyntaxKind.ClassKeyword, TriviaList(Space))) .AddBaseListTypes(SimpleBaseType(IdentifierName(Identifier(TriviaList(), "AbstractIndexCreationTask", TriviaList(LineFeed))))) .WithOpenBraceToken(Token(TriviaList(), SyntaxKind.OpenBraceToken, TriviaList(LineFeed))) .WithMembers(List(new List <MemberDeclarationSyntax> { indexNameProperty, createIndexDefinition })); CompilationUnitSyntax cu = CompilationUnit() .WithUsings(usings) .NormalizeWhitespace() .AddMembers(c); SyntaxNode formattedCompilationUnit; using (var workspace = new AdhocWorkspace()) { formattedCompilationUnit = Formatter.Format(cu, workspace); } return(formattedCompilationUnit.ToFullString()); }
public async Task Generator_OKResponse_Test() { var appGen = new TestAppGenConfig(); await AssertOKResponse(appGen); RoslynHelper.ValidateDotNetFolder(m_whamGeneratorController.TaskFolder); }
public async Task Generator_ContikiGen_Test() { var appGen = GetResourceConfig("ContikiGen.json"); await AssertOKResponse(appGen); RoslynHelper.ValidateDotNetFolder(m_whamGeneratorController.TaskFolder); }
private static string GetCSharpClassFromAdoSchemaTableColumns(IList <CSharpProperty> cSharpProperties) { var cSharpClass = CSharpClassTextGenerator.GenerateClassText("SysTypes", cSharpProperties, CSharpClassTextGeneratorOptions.Default); var compileResult = RoslynHelper.TryCompile(cSharpClass); compileResult.IsValid().Should().BeTrue(); return(cSharpClass); }
public void CreateClassFromSqlTableReference() { var sqlTableReference = new SqlTableReference(SqlConnectionProviders.AdventureWorksDb, TableName); var cSharpClass = CSharpClassGeneratorFromInformationSchema.CreateCSharpClass(sqlTableReference); var compileResult = RoslynHelper.TryCompile(cSharpClass); compileResult.IsValid().Should().BeTrue(); Console.WriteLine(cSharpClass); }
public void CreateClassForDocumentTableFromQueryTest() { var cSharpClass = CSharpClassGeneratorFromQueryViaSqlDescribeResultSet.GenerateClass( SqlConnectionProviders.AdventureWorksDb, $"SELECT * from Production.Document", "Document"); var compileResult = RoslynHelper.TryCompile(cSharpClass); compileResult.IsValid().Should().BeTrue(); Console.WriteLine(cSharpClass); }
public void CreateClassFromQueryTest() { var cSharpClass = CSharpClassGeneratorFromQueryViaSqlDescribeResultSet.GenerateClass( SqlConnectionProviders.AdventureWorksDb, $"SELECT * from {TableName}", "Employee"); var compileResult = RoslynHelper.TryCompile(cSharpClass); compileResult.IsValid().Should().BeTrue(); Console.WriteLine(cSharpClass); cSharpClass.Should().Be(EmployeeCSharpClassText); }
private static string GetText(MemberDeclarationSyntax indexClassDefinition) { StringBuilder sb = new StringBuilder(); var u = RoslynHelper.CreateUsings(Usings); u.ForEach(item => sb.Append($"{item.NormalizeWhitespace()}{Environment.NewLine}")); sb.Append(Environment.NewLine); sb.Append(indexClassDefinition.NormalizeWhitespace().ToFullString()); return(sb.ToString()); }
private static StatementSyntax HandleSyntaxInTransformResults(TransformFunctionProcessor processor, ExpressionSyntax expression) { var rewrittenExpression = (CSharpSyntaxNode)processor.Visit(expression); var indexingFunction = SyntaxFactory.SimpleLambdaExpression(SyntaxFactory.Parameter(SyntaxFactory.Identifier("results")), rewrittenExpression); return(RoslynHelper .This(nameof(TransformerBase.TransformResults)) .Assign(indexingFunction) .AsExpressionStatement()); }
protected MemberDeclarationSyntax GeneratePropertyForProxy(string uniqueName, string typeName, params string[] genericTypeNames) { return(SyntaxFactory.PropertyDeclaration( RoslynHelper.ParseTypeName(typeName, genericTypeNames), uniqueName ) .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .AddAccessorListAccessors( SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) )); }
private static List <StatementSyntax> HandleSyntaxInMap(FieldNamesValidator fieldValidator, MapFunctionProcessor mapRewriter, ExpressionSyntax expression, ref SyntaxList <MemberDeclarationSyntax> members) { var rewrittenExpression = (CSharpSyntaxNode)mapRewriter.Visit(expression); var optimized = new RavenLinqOptimizer(fieldValidator).Visit(new RavenLinqPrettifier().Visit(rewrittenExpression)) as StatementSyntax; var collectionName = string.IsNullOrWhiteSpace(mapRewriter.CollectionName) ? Constants.Documents.Collections.AllDocumentsCollection : mapRewriter.CollectionName; var collection = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(collectionName)); var results = new List <StatementSyntax>(); if (optimized != null) { var method = SyntaxFactory.MethodDeclaration(SyntaxFactory.IdentifierName("IEnumerable"), SyntaxFactory.Identifier("Map_" + members.Count)) .WithParameterList( SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Parameter(SyntaxFactory.Identifier("docs")) .WithType( SyntaxFactory.GenericName("IEnumerable") .WithTypeArgumentList( SyntaxFactory.TypeArgumentList( SyntaxFactory.SingletonSeparatedList <TypeSyntax>(SyntaxFactory.IdentifierName("dynamic")) ) ) ) )) ) .WithBody(SyntaxFactory.Block().AddStatements(optimized)); members = members.Add(method); results.Add(RoslynHelper.This(nameof(StaticIndexBase.AddMap)).Invoke(collection, RoslynHelper.This(method.Identifier.Text)).AsExpressionStatement()); // this.AddMap("Users", docs => from doc in docs ... ) } else { var indexingFunction = SyntaxFactory.SimpleLambdaExpression(SyntaxFactory.Parameter(SyntaxFactory.Identifier("docs")), rewrittenExpression); results.Add(RoslynHelper.This(nameof(StaticIndexBase.AddMap)).Invoke(collection, indexingFunction).AsExpressionStatement()); // this.AddMap("Users", docs => from doc in docs ... ) } if (mapRewriter.ReferencedCollections != null) { foreach (var referencedCollection in mapRewriter.ReferencedCollections) { var rc = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(referencedCollection)); results.Add(RoslynHelper.This(nameof(StaticIndexBase.AddReferencedCollection)).Invoke(collection, rc).AsExpressionStatement()); } } return(results); }
private static StatementSyntax HandleSyntaxInReduce(ReduceFunctionProcessor reduceFunctionProcessor, ExpressionSyntax expression, out string[] groupByFields) { var rewrittenExpression = (CSharpSyntaxNode)reduceFunctionProcessor.Visit(expression); var reducingFunction = SyntaxFactory.SimpleLambdaExpression( SyntaxFactory.Parameter(SyntaxFactory.Identifier(ResultsVariableNameRewriter.ResultsVariable)), rewrittenExpression); groupByFields = reduceFunctionProcessor.GroupByFields; return(RoslynHelper.This(nameof(StaticIndexBase.Reduce)).Assign(reducingFunction).AsExpressionStatement()); }
public void FormatTest() { string input = @" public partial class InsertIntoXlfAndConstantCsUC : UserControl, IUserControl, IKeysHandler, IUserControlWithSettingsManager, IUserControlWithSuMenuItemsList, IWindowOpener, IUserControlWithSizeChange { #region Class data static InsertIntoXlfAndConstantCsUC instance = null; #endregion }"; var s = RoslynHelper.Format(input); Debug.WriteLine(s); }
private static MemberDeclarationSyntax CreateClass(string name, IndexDefinition definition) { var statements = new List <StatementSyntax>(); var maps = definition.Maps.ToList(); var fieldNamesValidator = new FieldNamesValidator(); var methodDetector = new MethodDetectorRewriter(); var members = new SyntaxList <MemberDeclarationSyntax>(); for (var i = 0; i < maps.Count; i++) { var map = maps[i]; statements.AddRange(HandleMap(map, fieldNamesValidator, methodDetector, ref members)); } if (string.IsNullOrWhiteSpace(definition.Reduce) == false) { statements.Add(HandleReduce(definition.Reduce, fieldNamesValidator, methodDetector, out string[] groupByFields)); var groupByFieldsArray = GetArrayCreationExpression(groupByFields); statements.Add(RoslynHelper.This(nameof(StaticIndexBase.GroupByFields)).Assign(groupByFieldsArray).AsExpressionStatement()); } var fields = GetIndexedFields(definition, fieldNamesValidator); var outputFieldsArray = GetArrayCreationExpression(fields); statements.Add(RoslynHelper.This(nameof(StaticIndexBase.OutputFields)).Assign(outputFieldsArray).AsExpressionStatement()); var methods = methodDetector.Methods; if (methods.HasCreateField) { statements.Add(RoslynHelper.This(nameof(StaticIndexBase.HasDynamicFields)).Assign(SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression)).AsExpressionStatement()); } if (methods.HasBoost) { statements.Add(RoslynHelper.This(nameof(StaticIndexBase.HasBoostedFields)).Assign(SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression)).AsExpressionStatement()); } var ctor = RoslynHelper.PublicCtor(name) .AddBodyStatements(statements.ToArray()); return(RoslynHelper.PublicClass(name) .WithBaseClass <StaticIndexBase>() .WithMembers(members.Add(ctor))); }
protected StatementSyntax GenerateInitializerForControl(string propertyName, string selector, string typeName) { return(SyntaxFactory.ExpressionStatement( SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(propertyName), SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseTypeName(typeName)) .WithArgumentList(SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Argument(SyntaxFactory.IdentifierName("webDriver")), SyntaxFactory.Argument(SyntaxFactory.ThisExpression()), SyntaxFactory.Argument(RoslynHelper.GetPathSelectorObjectInitialization(selector)) }))) ) )); }
protected StatementSyntax GenerateInitializerForProxy(SeleniumGeneratorContext context, string typeName, params string[] genericTypeNames) { return(SyntaxFactory.ExpressionStatement( SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(context.UniqueName), SyntaxFactory.ObjectCreationExpression(RoslynHelper.ParseTypeName(typeName, genericTypeNames)) .WithArgumentList( SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Argument(SyntaxFactory.ThisExpression()), SyntaxFactory.Argument(RoslynHelper.GetPathSelectorObjectInitialization(context.Selector)) })) ) ) )); }
public AD7StackFrame(AD7Engine engine, AD7Thread thread, Mono.Debugger.Soft.StackFrame threadContext) { Debug.Assert(threadContext != null, "ThreadContext is null"); Engine = engine; Thread = thread; ThreadContext = threadContext; _textPosition = RoslynHelper.GetStatementRange(ThreadContext.FileName, ThreadContext.LineNumber, ThreadContext.ColumnNumber); _functionName = threadContext.Method.Name; if (_textPosition != null) { docContext = new AD7DocumentContext(_textPosition); } this.LocalVariables = threadContext.GetVisibleVariables().Select(x => new MonoProperty(threadContext, x)).ToList(); }
public IHttpActionResult ByLinq(int id, string query) { object obj; var type = RoslynHelper.Compile(query, out obj); using (var session = Store.Instance.OpenSession()) { //session.Advanced.DocumentQuery<Record>("Records/ByWebLog") // .SelectFields<WebLog>() // .Where(query); var result = type.InvokeMember("Compile", BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, new object[] { session }); return(Ok(result)); } }
private int TryBindBreakpoints() { int countBounded = 0; try { AD7PendingBreakpoint[] pendingList; lock (_pendingBreakpoints) pendingList = _pendingBreakpoints.Where(x => !x.Bound).ToArray(); foreach (AD7PendingBreakpoint bp in pendingList) { MonoBreakpointLocation location; if (bp.TryBind(_types, out location)) { try { int ilOffset; RoslynHelper.GetILOffset(bp, location.Method, out ilOffset); BreakpointEventRequest request = _vm.SetBreakpoint(location.Method, ilOffset); request.Enable(); bp.Bound = true; bp.LastRequest = request; _engine.Callback.BoundBreakpoint(bp); //_vm.Resume(); bp.CurrentThread = _mainThread; countBounded++; } catch (Exception ex) { logger.Error("Cant bind breakpoint: " + ex); } } } } catch (Exception ex) { logger.Error("Cant bind breakpoint: " + ex); } return(countBounded); }
public void TestCompilationOfManyClasses() { int errorCount = 0; int successCount = 0; IList <SqlTableReference> randomSqlTableReferences = null; "Given a list of SqlTableReferences" ._(() => { randomSqlTableReferences = RandomTableSelector.GetRandomSqlTableReferences(SqlConnectionProviders.AdventureWorksDb, 400); }); "Convert each table reference to a C# class and check for syntax errors using Roslyn" ._foreach(randomSqlTableReferences, sqlTableReference => { var sqlTable = SqlTableFactory.Create(sqlTableReference); var cSharpClass = CSharpClassGeneratorFromSqlTable.GenerateClass(sqlTable); var compileResult = RoslynHelper.TryCompile(cSharpClass); if (compileResult.IsValid()) { successCount++; } else { errorCount++; Console.WriteLine("Error found in the following:\r\n" + cSharpClass); } }); "Then print out testing results" ._(() => { Console.WriteLine("Successes: {0}", successCount); Console.WriteLine("Failures: {0}", errorCount); errorCount.Should().Be(0); }); }
private static MemberDeclarationSyntax CreateClass(string name, TransformerDefinition definition) { var statements = new List <StatementSyntax>(); var methodDetector = new MethodDetectorRewriter(); statements.Add(HandleTransformResults(definition.TransformResults, methodDetector)); var methods = methodDetector.Methods; if (methods.HasGroupBy) { statements.Add(RoslynHelper.This(nameof(TransformerBase.HasGroupBy)).Assign(SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression)).AsExpressionStatement()); } if (methods.HasLoadDocument) { statements.Add(RoslynHelper.This(nameof(TransformerBase.HasLoadDocument)).Assign(SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression)).AsExpressionStatement()); } if (methods.HasTransformWith) { statements.Add(RoslynHelper.This(nameof(TransformerBase.HasTransformWith)).Assign(SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression)).AsExpressionStatement()); } if (methods.HasInclude) { statements.Add(RoslynHelper.This(nameof(TransformerBase.HasInclude)).Assign(SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression)).AsExpressionStatement()); } var ctor = RoslynHelper.PublicCtor(name).AddBodyStatements(statements.ToArray()); return(RoslynHelper.PublicClass(name) .WithBaseClass <TransformerBase>() .WithMembers(SyntaxFactory.SingletonList <MemberDeclarationSyntax>(ctor))); }
public void AddXmlDocumentationCommentTest() { var s = @" class C1{ private int var1; public string var2; void action1() { int var3; var3=var1*var1; var2=""Completed""; } void action2() { var1 = 5; var2=""Completed""; } }"; RoslynHelper.AddWhereIsUsedVariablesInMethods(s); }
private static List <StatementSyntax> HandleSyntaxInMap(MapFunctionProcessor mapRewriter, ExpressionSyntax expression) { var rewrittenExpression = (CSharpSyntaxNode)mapRewriter.Visit(expression); var collectionName = string.IsNullOrWhiteSpace(mapRewriter.CollectionName) ? Constants.Indexing.AllDocumentsCollection : mapRewriter.CollectionName; var collection = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(collectionName)); var indexingFunction = SyntaxFactory.SimpleLambdaExpression(SyntaxFactory.Parameter(SyntaxFactory.Identifier("docs")), rewrittenExpression); var results = new List <StatementSyntax>(); results.Add(RoslynHelper.This(nameof(StaticIndexBase.AddMap)).Invoke(collection, indexingFunction).AsExpressionStatement()); // this.AddMap("Users", docs => from doc in docs ... ) if (mapRewriter.ReferencedCollections != null) { foreach (var referencedCollection in mapRewriter.ReferencedCollections) { var rc = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(referencedCollection)); results.Add(RoslynHelper.This(nameof(StaticIndexBase.AddReferencedCollection)).Invoke(collection, rc).AsExpressionStatement()); } } return(results); }
private static CompilationResult CompileInternal(string originalName, string cSharpSafeName, MemberDeclarationSyntax @class, IndexDefinition definition) { var name = cSharpSafeName + "." + Guid.NewGuid() + IndexExtension; var @namespace = RoslynHelper.CreateNamespace(IndexNamespace) .WithMembers(SyntaxFactory.SingletonList(@class)); var res = GetUsingDirectiveAndSyntaxTreesAndReferences(definition); var compilationUnit = SyntaxFactory.CompilationUnit() .WithUsings(RoslynHelper.CreateUsings(res.UsingDirectiveSyntaxes)) .WithMembers(SyntaxFactory.SingletonList <MemberDeclarationSyntax>(@namespace)) .NormalizeWhitespace(); SyntaxNode formattedCompilationUnit; using (var workspace = new AdhocWorkspace()) { formattedCompilationUnit = Formatter.Format(compilationUnit, workspace); } string sourceFile = null; if (EnableDebugging) { sourceFile = Path.Combine(Path.GetTempPath(), name + ".cs"); File.WriteAllText(sourceFile, formattedCompilationUnit.ToFullString(), Encoding.UTF8); } var st = EnableDebugging ? SyntaxFactory.ParseSyntaxTree(File.ReadAllText(sourceFile), path: sourceFile, encoding: Encoding.UTF8) : SyntaxFactory.ParseSyntaxTree(formattedCompilationUnit.ToFullString()); res.SyntaxTrees.Add(st); var compilation = CSharpCompilation.Create( assemblyName: name, syntaxTrees: res.SyntaxTrees, references: res.References, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithOptimizationLevel(EnableDebugging ? OptimizationLevel.Debug : OptimizationLevel.Release) ); var code = formattedCompilationUnit.SyntaxTree.ToString(); var asm = new MemoryStream(); var pdb = EnableDebugging ? new MemoryStream() : null; var result = compilation.Emit(asm, pdb, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); if (result.Success == false) { IEnumerable <Diagnostic> failures = result.Diagnostics .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); var sb = new StringBuilder(); sb.AppendLine($"Failed to compile index {originalName}"); sb.AppendLine(); sb.AppendLine(code); sb.AppendLine(); foreach (var diagnostic in failures) { sb.AppendLine(diagnostic.ToString()); } throw new IndexCompilationException(sb.ToString()); } asm.Position = 0; Assembly assembly; if (EnableDebugging) { pdb.Position = 0; assembly = AssemblyLoadContext.Default.LoadFromStream(asm, pdb); } else { assembly = AssemblyLoadContext.Default.LoadFromStream(asm); } return(new CompilationResult { Code = code, Type = assembly.GetType($"{IndexNamespace}.{cSharpSafeName}") }); }
public object Process() { return(RoslynHelper.GetEntities <T>(_entity)); }
public MonoDocumentContext(string fileName, int startLine, int startColumn) { _fileName = fileName; _currentStatementRange = RoslynHelper.GetStatementRange(fileName, startLine, startColumn); }
// Util の名前空間に Roslyn 系を書きたくなかったから RoslynHelper 経由にしたが、余計だったか? public async static Task <SearchResultInfo> FindSymbolAtPositionAsync(string sourceFile, int offset) { return(await RoslynHelper.FindSymbolAtPositionAsync(sourceFile, offset)); }
public static void GenerateSetupInTester(ZTWPackage pkg) { string name = pkg.Name; if (pkg == null) { throw new ArgumentNullException("pkg"); } string testerPath = SetupController.TesterPath; if (!SetupController.CheckTesterPathDetermined()) { throw new Exception("Tester path is null. It must be specified by going to 'Enter Package Creator -> Locate Tester Path'."); } if (!testerPath.IsDirectory() && Path.GetExtension(testerPath) == "csproj" || testerPath.IsDirectory()) { throw new Exception("The stored Tester isn't a csproj file."); } // First, we will create the template && store it on a file // Declare the Hello world expression CodeSnippetExpression helloWorld = new CodeSnippetExpression(@"Console.WriteLine(""Hello world!"")"); // Declare the class && the "OnSetup" method with its expression var c = new CodeTypeDeclaration(pkg.SetupClass) { Attributes = MemberAttributes.Public, IsClass = true, Members = { new CodeMemberMethod() { Name = PackageConsts.OnSetupMethod, Attributes = MemberAttributes.Public | MemberAttributes.Static, Statements ={ new CodeExpressionStatement(helloWorld) } }, new CodeMemberMethod() { Name = PackageConsts.OnFinishMethod, Attributes = MemberAttributes.Public | MemberAttributes.Static, Statements ={ new CodeExpressionStatement(helloWorld) } } }, StartDirectives = { new CodeRegionDirective(CodeRegionMode.Start, "\nstatic") }, EndDirectives = { new CodeRegionDirective(CodeRegionMode.End, string.Empty) } }; // Specify and add Namespace var ns = new CodeNamespace(pkg.SetupNamespace) { Types = { c } }; // Create && add "System" import into existing namespace ns.Imports.Add(new CodeNamespaceImport("System")); // Then, create the unit && add everything into current namespace var cu = new CodeCompileUnit() { Namespaces = { ns } }; // Specify the language var provider = CodeDomProvider.CreateProvider("CSharp"); // Output generated code to string Builder var sb = new StringBuilder(); using (var sourceWriter = new StringWriter(sb)) provider.GenerateCodeFromCompileUnit(cu, sourceWriter, new CodeGeneratorOptions()); var text = sb.ToString(); string testerFolderPath = Path.GetDirectoryName(testerPath), saveFilePath = Path.Combine(testerFolderPath, "Setups", pkg.PrettyName + ".cs"), saveFolderPath = Path.GetDirectoryName(saveFilePath); if (!Directory.Exists(saveFolderPath)) { Directory.CreateDirectory(saveFolderPath); } // Overwrite confirmation bool overwrite = true; if (File.Exists(saveFilePath)) { overwrite = SmartInput.NextConfirm("Do you want to overwrite the current file?"); } if (overwrite) { File.WriteAllText(saveFilePath, text); } // Then, we will add the item && save it on the csproj RoslynHelper.AddItem(testerPath, testerFolderPath, saveFilePath); }