public void TestPublicStaticMethod_Optional() { // Arrange var sb = new SourceBuilder(); // Act sb.PublicStaticMethod("bool", "IsHappy", new[] { (true, "string", "roommate"), (false, "int", "age") }, sb =>
public void BuildScriptTest() { const string source1 = @"namespace TestNamespace { public class TestClass { } }"; const string source2 = @"namespace TestNamespace { public class TestClass2 { } public class TestClass3 { public void DoNothing() { } } }"; var builder = new SourceBuilder(); var result = builder.BuildAssembly(new[] { source1, source2 }); File.WriteAllBytes(@"C:\Users\sharpiro\AppData\Local\SqlMapper\testAssembly.dll", result); }
private static Source[] GetSource() { var builder = new SourceBuilder(new HostContext(null, null)); builder.Directory(GetSourcePath("FromFile.Doc.ps1")); return(builder.Build()); }
public static Assembly CompileMvcToAssembly(string code, IEnumerable <MetadataReference> metadataReferences = null) { metadataReferences ??= Enumerable.Empty <MetadataReference>(); List <MetadataReference> references = GetMvcMetadataReferences(); return(SourceBuilder.CompileToAssembly(code, metadataReferences.Concat(references))); }
public void TestComplete() { // Arrange var sb = new SourceBuilder(); // Act sb.AL("namespace foo"); sb.B(sb => { sb.AL("public class Bar"); sb.B(sb => { sb.A("System.Console.WriteLine(", indent: true); sb.A("\"Hello World!\""); sb.A(");"); sb.NL(); sb.I(sb => { sb.AL("// Indented comment"); }); }); }); var value = sb.ToString(); // Assert Assert.Equal(@"namespace foo { public class Bar { System.Console.WriteLine(""Hello World!""); // Indented comment } } ", value); }
public override void Emit(SourceBuilder sourceCode) { if (InParallelizedBody) { sourceCode.AppendFrontFormat("{0}.{1} match = parallelTaskMatches[threadId].GetNextUnfilledPosition();\n", RulePatternClassName, NamesOfEntities.MatchClassName(PatternName)); } else { sourceCode.AppendFrontFormat("{0}.{1} match = matches.GetNextUnfilledPosition();\n", RulePatternClassName, NamesOfEntities.MatchClassName(PatternName)); } // emit match building operations MatchBuildingOperations.Emit(sourceCode); if (InParallelizedBody) { sourceCode.AppendFront("match.IterationNumber = currentIterationNumber;\n"); sourceCode.AppendFront("parallelTaskMatches[threadId].PositionWasFilledFixIt();\n"); } else { sourceCode.AppendFront("matches.PositionWasFilledFixIt();\n"); } }
private static void WriteCount(this SourceBuilder sb, Entity entity) { var modelName = $"global::Allvis.Kaylee.Generated.SqlKata.Entities.{entity.DisplayName.Replace(".", "").Replace("::", ".")}"; var entityName = entity.DisplayName.Replace(".", "").Replace("::", "_"); var fullPrimaryKey = entity.GetFullPrimaryKey().ToList(); var fields = fullPrimaryKey.Take(fullPrimaryKey.Count - 1).Select(fr => { var field = fr.ResolvedField; return(field.Type.ToCSharp(), field.Name, field.Name.ToCamelCase()); }).ToList(); var stackedGroupable = new Stack <(string Type, string Name, string NameCamel)>(fields); var i = stackedGroupable.Count; while (i >= 0) { var stackedPivotable = new Stack <(string Type, string Name, string NameCamel)>(fields.Take(i)); var j = stackedPivotable.Count; while (j >= 0) { if (j == 0) { var parameters = stackedGroupable.Select(p => (p.Type, p.NameCamel)).Reverse().PrefixWithQueryFactory(); var arguments = string.Join(", ", stackedGroupable.Reverse().Select(p => p.NameCamel)); sb.PublicStaticMethod("global::System.Threading.Tasks.Task<int>", $"Count_{entityName}", parameters, sb => { sb.AL($@"return _db.ExecuteScalarAsync<int>(global::Allvis.Kaylee.Generated.SqlKata.Queries.Count_{entityName}({arguments}));"); }); } else if (i > 0) { var parameters = stackedPivotable.Skip(1).Select(p => (p.Type, p.NameCamel)).Reverse().PrefixWithQueryFactory(); var arguments = string.Join(", ", stackedPivotable.Skip(1).Reverse().Select(p => p.NameCamel)); var resultTuple = stackedGroupable.Reverse().Select(p => (p.Type, p.Name)).Concat(new[] { ("int", "Count") }).Join();
public async Task Returns_ReadJsonPatchAsync_Types() { string code = @" using LaDeak.JsonMergePatch.Http; public class Controller { public class SomeType { } public async System.Threading.Tasks.Task TestMethodAsync() { var client = new System.Net.Http.HttpClient(); var response = await client.GetAsync(""https://test.com""); await response.Content.ReadJsonPatchAsync<SomeType>(); } }"; var compilation = SourceBuilder.Compile(code, new[] { MetadataReference.CreateFromFile(typeof(PatchParameterWalkerTests).Assembly.Location), MetadataReference.CreateFromFile(typeof(Patch <>).Assembly.Location), MetadataReference.CreateFromFile(typeof(HttpClient).Assembly.Location), MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location), MetadataReference.CreateFromFile(typeof(HttpContentExtensions).Assembly.Location), MetadataReference.CreateFromFile(typeof(JsonSerializerOptions).Assembly.Location) }); var sut = new PatchParametersWalker(); var result = sut.Process(await compilation.Tree.GetRootAsync(), compilation.Compilation.GetSemanticModel(compilation.Tree)); Assert.Equal("SomeType", result.First().Name); }
private static void Write(this SourceBuilder sb, Schema schema) { foreach (var entity in schema.Entities) { sb.Write(entity); } }
public override void Emit(SourceBuilder sourceCode) { // TODO: why is the clear needed? is it needed at all? the set being empty must be ensured at this point. if (Parallel) { if (!NeverAboveMaxIsoSpace) { sourceCode.AppendFront("if(isoSpace >= (int) GRGEN_LGSP.LGSPElemFlagsParallel.MAX_ISO_SPACE) {\n"); sourceCode.Indent(); sourceCode.AppendFront("graph.perThreadInIsoSpaceMatchedElements[threadId][isoSpace - " + "(int) GRGEN_LGSP.LGSPElemFlagsParallel.MAX_ISO_SPACE].Clear();\n"); sourceCode.AppendFront("graph.perThreadInIsoSpaceMatchedElementsGlobal[threadId][isoSpace - " + "(int) GRGEN_LGSP.LGSPElemFlagsParallel.MAX_ISO_SPACE].Clear();\n"); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); } } else { if (!NeverAboveMaxIsoSpace) { sourceCode.AppendFront("if(isoSpace >= (int) GRGEN_LGSP.LGSPElemFlags.MAX_ISO_SPACE) {\n"); sourceCode.Indent(); sourceCode.AppendFront("graph.inIsoSpaceMatchedElements[isoSpace - " + "(int) GRGEN_LGSP.LGSPElemFlags.MAX_ISO_SPACE].Clear();\n"); sourceCode.AppendFront("graph.inIsoSpaceMatchedElementsGlobal[isoSpace - " + "(int) GRGEN_LGSP.LGSPElemFlags.MAX_ISO_SPACE].Clear();\n"); sourceCode.Unindent(); sourceCode.AppendFront("}\n"); } } sourceCode.AppendFront("--isoSpace;\n"); }
private string CreateSource(Type type) { var builder = new SourceBuilder(type, Naming.MakeAccessorName(type)); var no = 0; foreach (var method in type.GetMethods()) { var attribute = method.GetCustomAttribute <MethodAttribute>(true); if (attribute == null) { throw new AccessorGeneratorException($"Method is not supported for generation. type=[{type.FullName}], method=[{method.Name}]"); } var nodes = attribute.GetNodes(sqlLoader, option, method); var visitor = new ParameterResolveVisitor(method); visitor.Visit(nodes); var methodMetadata = new MethodMetadata( no, method, attribute.CommandType, attribute.MethodType, (attribute as IReturnValueBehavior)?.ReturnValueAsResult ?? false, nodes, visitor.Parameters, visitor.DynamicParameters); builder.AddMethod(methodMetadata); no++; } return(builder.Build()); }
public GeneratedCodeVisitor(SourceBuilder output, Dictionary<string, object> globalSymbols, NullBehaviour nullBehaviour) { _nullBehaviour = nullBehaviour; _source = output; _scope = new Scope(new Scope(null) { Variables = globalSymbols }); }
public static void Load(this IMethodModel @this, ICodeTextWriter writer, SourceBuilder builder, IMethodSymbol method, ScopeInfo scope, IEnumerable <IMemberInfo> references) { var methodScope = new ScopeInfo(scope); if (method.IsGenericMethod) { methodScope.CreateAliases(method.TypeArguments); } (bool isAsync, bool methodReturnsValue) = SemanticFacts.IsAsyncAndGetReturnType(writer.Compilation, method); bool canUseAsync = true; { SourceBuilder builder2 = builder.AppendNewBuilder(false); writer.WriteIdentifier(builder2, method); if (method.IsGenericMethod) { builder2.Append('<'); writer.WriteTypeArgumentsCall(builder2, method.TypeArguments, methodScope); builder2.Append('>'); } @this.Name = builder2.ToString(); } { SourceBuilder builder2 = builder.AppendNewBuilder(false); writer.WriteTypeReference(builder2, method.ReturnType, methodScope); @this.ReturnType = builder2.ToString(); } { SourceBuilder builder2 = builder.AppendNewBuilder(false); writer.WriteParameterDefinition(builder2, methodScope, method.Parameters); @this.ArgumentsDefinition = builder2.ToString(); } { SourceBuilder builder2 = builder.AppendNewBuilder(false); writer.WriteCallParameters(builder2, method.Parameters); @this.CallArguments = builder2.ToString(); } @this.IsAsync = isAsync && canUseAsync; @this.ReturnExpected = (isAsync && methodReturnsValue == false) ? canUseAsync == false : methodReturnsValue; foreach (IMemberInfo reference in references) { SourceBuilder builder2 = builder.AppendNewBuilder(false); if (isAsync && canUseAsync) { writer.WriteMethodCall(builder2, reference, method, methodScope, false, false, false); } else { writer.WriteMethodCall(builder2, reference, method, methodScope, false, SemanticFacts.IsNullable(writer.Compilation, method.ReturnType), reference.PreferCoalesce); } @this.Expressions.Add(builder2.ToString()); } }
public static void PublicStaticClass( this SourceBuilder sb, string className, Action <SourceBuilder> builder) { sb.AL($"public static class {className}"); sb.B(builder); }
private static void Namespace( this SourceBuilder sb, string ns, Action <SourceBuilder> builder) { sb.AL($"namespace {ns}"); sb.B(builder); }
/// <summary> /// Configure <see cref="ICommandBinding"/> object. /// </summary> /// <param name="list">Binding list</param> /// <param name="command">Source command</param> public static SourceBuilder <T> Command <T> (this BindingList list, T command) where T : ICommand { var builder = new SourceBuilder <T> (command); list.Add(builder.Binding); return(builder); }
private static void Write(this SourceBuilder sb, Entity entity) { sb.WriteEntity(entity); foreach (var child in entity.Children) { sb.Write(child); } }
public override void Dump(SourceBuilder builder) { builder.AppendFront("FinalizeNegativeIndependentMatching "); if (Parallel) { builder.AppendFront("Parallel "); } builder.Append("\n"); }
public override void Dump(SourceBuilder builder) { builder.AppendFront("AcceptCandidate "); builder.AppendFormat("on {0} negNamePrefix:{1} node:{2}", PatternElementName, NegativeIndependentNamePrefix, IsNode); builder.AppendFormat("parallel:{0} all:{1} ", Parallel, LockForAllThreads); builder.Append("\n"); }
public override void Emit(SourceBuilder sourceCode) { if (IsIterationBreaking) { sourceCode.AppendFront("breakIteration = true;\n"); } CheckFailedOperations.Emit(sourceCode); }
public override void Emit(SourceBuilder sourceCode) { string variableContainingCandidate = NamesOfEntities.CandidateVariable(PatternElementName); string variableContainingBackupOfMappedMemberGlobalSome = NamesOfEntities.VariableWithBackupOfIsMatchedGlobalInSomePatternBit(PatternElementName, NegativeIndependentNamePrefix); string isMatchedInSomePatternBit = "(uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED_BY_SOME_ENCLOSING_PATTERN"; sourceCode.AppendFrontFormat("{0}.lgspFlags = {0}.lgspFlags & ~({1}) | {2};\n", variableContainingCandidate, isMatchedInSomePatternBit, variableContainingBackupOfMappedMemberGlobalSome); }
public static void PublicClass( this SourceBuilder sb, string ns, string className, Action <SourceBuilder> builder) { sb.Namespace(ns, sb => { sb.PublicClass(className, builder); }); }
public override void Dump(SourceBuilder builder) { builder.AppendFrontFormat("LeafSubpatternMatched {0}\n", IsIteratedNullMatch ? "IteratedNullMatch " : ""); if (MatchBuildingOperations != null) { builder.Indent(); MatchBuildingOperations.Dump(builder); builder.Unindent(); } }
public override void Dump(SourceBuilder builder) { // first dump check builder.AppendFront("CheckContinueMatching OfIndependentSucceeded \n"); // then operations for case check failed .. wording a bit rotten if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
public override void Dump(SourceBuilder builder) { // first dump check builder.AppendFront("CheckContinueMatching TasksLeft\n"); // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
public override void Emit(SourceBuilder sourceCode) { if (sourceCode.CommentSourceCode) { sourceCode.AppendFrontFormat("// Lookup {0} \n", PatternElementName); } string variableContainingTypeIDForCandidate = NamesOfEntities.TypeIdForCandidateVariable(PatternElementName); sourceCode.AppendFrontFormat("int {0} = {1};\n", variableContainingTypeIDForCandidate, TypeID); }
public override void Dump(SourceBuilder builder) { // first dump local content builder.AppendFront("IteratedMatchingDummyLoopPreventingReturn \n"); // then nested content if (NestedOperationsList != null) { builder.Indent(); NestedOperationsList.Dump(builder); builder.Unindent(); } }
public override void Dump(SourceBuilder builder) { builder.AppendFront("InitializeNegativeIndependentMatching "); if (SetupSubpatternMatching) { builder.AppendFront("SetupSubpatternMatching "); } if (Parallel) { builder.AppendFront("Parallel "); } builder.Append("\n"); }
public override void Dump(SourceBuilder builder) { // first dump local content builder.AppendFrontFormat("AlternativeCaseMatching {0}{1}\n", PathPrefix, CaseName); // then nested content if (OperationsList != null) { builder.Indent(); OperationsList.Dump(builder); builder.Unindent(); } }
public override void Dump(SourceBuilder builder) { // first dump check builder.AppendFrontFormat("CheckContinueMatching IteratedPatternFound {0}\n", IsIterationBreaking ? "IterationBreaking" : ""); // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
public override void Dump(SourceBuilder builder) { // first dump check builder.AppendFront("CheckContinueMatching OfIndependentFailed "); builder.Append(IsIterationBreaking ? "IterationBreaking\n" : "\n"); // then operations for case check failed if (CheckFailedOperations != null) { builder.Indent(); CheckFailedOperations.Dump(builder); builder.Unindent(); } }
private bool BuildInternal(string projectPath) { var projectDiagnostics = new List<ICompilationMessage>(); if (!Runtime.Project.TryGetProject(projectPath, out _currentProject, projectDiagnostics)) { LogError(string.Format("Unable to locate {0}.", Runtime.Project.ProjectFileName)); return false; } var sw = Stopwatch.StartNew(); var baseOutputPath = GetBuildOutputDir(_currentProject); var configurations = _buildOptions.Configurations.DefaultIfEmpty("Debug"); string frameworkSelectionError; var frameworks = FrameworkSelectionHelper.SelectFrameworks(_currentProject, _buildOptions.TargetFrameworks, _applicationEnvironment.RuntimeFramework, out frameworkSelectionError); if (frameworks == null) { LogError(frameworkSelectionError); return false; } if (_buildOptions.GeneratePackages && !ScriptExecutor.Execute(_currentProject, "prepack", GetScriptVariable)) { LogError(ScriptExecutor.ErrorMessage); return false; } if (!ScriptExecutor.Execute(_currentProject, "prebuild", GetScriptVariable)) { LogError(ScriptExecutor.ErrorMessage); return false; } var success = true; var allDiagnostics = new List<ICompilationMessage>(); PackageBuilder packageBuilder = null; PackageBuilder symbolPackageBuilder = null; InstallBuilder installBuilder = null; SourceBuilder sourceBuilder = null; // Build all specified configurations foreach (var configuration in configurations) { if (_buildOptions.GeneratePackages) { // Create a new builder per configuration packageBuilder = new PackageBuilder(); symbolPackageBuilder = new PackageBuilder(); InitializeBuilder(_currentProject, packageBuilder); InitializeBuilder(_currentProject, symbolPackageBuilder); installBuilder = new InstallBuilder(_currentProject, packageBuilder, _buildOptions.Reports); sourceBuilder = new SourceBuilder(_currentProject, packageBuilder, _buildOptions.Reports); } var configurationSuccess = true; var outputPath = Path.Combine(baseOutputPath, configuration); // Build all target frameworks a project supports foreach (var targetFramework in frameworks) { _buildOptions.Reports.Information.WriteLine(); _buildOptions.Reports.Information.WriteLine("Building {0} for {1}", _currentProject.Name, targetFramework.ToString().Yellow().Bold()); var diagnostics = new List<ICompilationMessage>(); var context = new BuildContext(_hostServices, _applicationEnvironment, _cache, _cacheContextAccessor, _currentProject, targetFramework, configuration, outputPath); context.Initialize(_buildOptions.Reports.Quiet); if (context.Build(diagnostics)) { if (_buildOptions.GeneratePackages) { context.PopulateDependencies(packageBuilder); context.AddLibs(packageBuilder, "*.dll"); context.AddLibs(packageBuilder, "*.xml"); context.PopulateDependencies(symbolPackageBuilder); context.AddLibs(symbolPackageBuilder, "*.*"); } } else { configurationSuccess = false; } allDiagnostics.AddRange(diagnostics); WriteDiagnostics(diagnostics); } success = success && configurationSuccess; if (_buildOptions.GeneratePackages) { // Create a package per configuration string nupkg = GetPackagePath(_currentProject, outputPath); string symbolsNupkg = GetPackagePath(_currentProject, outputPath, symbols: true); if (configurationSuccess) { // Generates the application package only if this is an application packages configurationSuccess = installBuilder.Build(outputPath); success = success && configurationSuccess; } if (configurationSuccess) { configurationSuccess = sourceBuilder.Build(outputPath); success = success && configurationSuccess; } if (configurationSuccess) { foreach (var sharedFile in _currentProject.Files.SharedFiles) { var file = new PhysicalPackageFile(); file.SourcePath = sharedFile; file.TargetPath = String.Format(@"shared\{0}", Path.GetFileName(sharedFile)); packageBuilder.Files.Add(file); } var root = _currentProject.ProjectDirectory; foreach (var path in _currentProject.Files.SourceFiles) { var srcFile = new PhysicalPackageFile(); srcFile.SourcePath = path; srcFile.TargetPath = Path.Combine("src", PathUtility.GetRelativePath(root, path)); symbolPackageBuilder.Files.Add(srcFile); } using (var fs = File.Create(nupkg)) { packageBuilder.Save(fs); _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", _currentProject.Name, Path.GetFullPath(nupkg)); } if (symbolPackageBuilder.Files.Any()) { using (var fs = File.Create(symbolsNupkg)) { symbolPackageBuilder.Save(fs); _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", _currentProject.Name, Path.GetFullPath(symbolsNupkg)); } } } } } if (!success) { return false; } if (!ScriptExecutor.Execute(_currentProject, "postbuild", GetScriptVariable)) { LogError(ScriptExecutor.ErrorMessage); return false; } if (_buildOptions.GeneratePackages && !ScriptExecutor.Execute(_currentProject, "postpack", GetScriptVariable)) { LogError(ScriptExecutor.ErrorMessage); return false; } sw.Stop(); if (projectDiagnostics.Any()) { // Add a new line to separate the project diagnostics information from compilation diagnostics _buildOptions.Reports.Information.WriteLine(); projectDiagnostics.ForEach(d => LogWarning(d.FormattedMessage)); } allDiagnostics.AddRange(projectDiagnostics); WriteSummary(allDiagnostics); _buildOptions.Reports.Information.WriteLine("Time elapsed {0}", sw.Elapsed); return success; }
public UsingNamespaceVisitor(SourceBuilder output) { _source = output; }