/// <summary> /// Generates the type. /// </summary> /// <param name="writer">The writer.</param> /// <param name="cppTypename"></param> protected override void GenerateType(SourceWriter writer, string cppTypename) { writer.WriteLine("/**"); writer.WriteLine(" * Type {0}", cppTypename); writer.WriteLine(" */"); writer.WriteLine("struct {0}", cppTypename); writer.OpenBlock(); { FieldInfo[] fields = Type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (FieldInfo fieldInfo in fields) { WriteField(writer, fieldInfo); } } writer.CloseBlock(";"); writer.WriteLine(); var attribute = Type.GetAttribute<CppValueObjectAttribute>(true); if (attribute.IsDescriptor) { writer.WriteLine("{0} descriptor_of_{1}(InvHandle handle);", cppTypename, (attribute.Typename ?? Type.Name.Replace("Descriptor", string.Empty)).ToLower()); writer.WriteLine(); } }
public static string GenerateDocumentStorageCode(DocumentMapping[] mappings) { var writer = new SourceWriter(); // TODO -- get rid of the magic strings var namespaces = new List<string> {"System", "Marten", "Marten.Schema", "Marten.Linq", "Marten.Util", "Npgsql", "Remotion.Linq"}; namespaces.AddRange(mappings.Select(x => x.DocumentType.Namespace)); namespaces.Distinct().OrderBy(x => x).Each(x => writer.WriteLine($"using {x};")); writer.BlankLine(); writer.StartNamespace("Marten.GeneratedCode"); mappings.Each(x => { x.GenerateDocumentStorage(writer); writer.BlankLine(); writer.BlankLine(); }); writer.FinishBlock(); var code = writer.Code(); return code; }
public GeneratedCodeVisitor(SourceWriter source, Dictionary<string, object> globalSymbols, NullBehaviour nullBehaviour) { _nullBehaviour = nullBehaviour; _source = source; _scope = new Scope(new Scope(null) { Variables = globalSymbols }); }
/// <summary> /// Generates the specified options. /// </summary> /// <param name="configOptions">The options.</param> /// <param name="types">The types.</param> public virtual void Generate(ConfigOptions configOptions, IEnumerable<Type> types) { Options = configOptions; _filename = (ProjectName + ".h").ToLower(); _defineFilename = _filename.Replace('.', '_').ToUpper(); using (_writer = new SourceWriter(Path.Combine(Path.GetFullPath(Options.CppOutputDir), _filename))) { IEnumerable<Type> functionTypes = types.Where(t => t.HasAttribute<CppFunctionAttribute>()); IEnumerable<Type> wrapperTypes = types.Where(t => t.HasAttribute<CppClassAttribute>(true)); IEnumerable<Type> enumerations = types.Where(t => t.IsEnum); IEnumerable<Type> valueObjects = types.Where(t => t.HasAttribute<CppValueObjectAttribute>() && t.IsValueType && !t.IsEnum); IEnumerable<Type> functionProviders = types.Where( t => t.HasAttribute<CppTypeAttribute>() && !t.HasAttribute<CppClassAttribute>(true) && t.IsInterface); IEnumerable<Type> converters = types.Where(t => t.HasAttribute<HandleConverterAttribute>()); WriteHeader(); _writer.WriteLine("extern \"C\""); _writer.WriteLine("{"); _writer.Indent(); WriteEnumerations(enumerations); WritePrototypes(valueObjects); //WriteWrapperDescriptorPrototypes(wrapperTypes); WriteFunctionHandlers(functionTypes); WriteTypeDefinitions(valueObjects); //WriteWrapperDescriptorDefinitions(wrapperTypes); _writer.WriteLine(); WriteFunctionProviders(functionProviders); WriteWrappersMethods(wrapperTypes.OrderBy(x => x.Name)); _writer.Deindent(); _writer.WriteLine("}"); _writer.WriteLine(); WriteInlineConvertersAndConverters(converters.Union(wrapperTypes).Distinct(), wrapperTypes); WriteFooter(); _writer.Close(); } }
public void tryit() { var mapping = new DocumentMapping(typeof(User)); var writer = new SourceWriter(); writer.StartNamespace("MyApplication"); mapping.GenerateDocumentStorage(writer); writer.FinishBlock(); Debug.WriteLine(writer.Code()); }
/// <summary> /// Generates this instance. /// </summary> /// <returns></returns> protected override void GenerateType(SourceWriter writer, string cppTypename) { writer.WriteLine("/**"); writer.WriteLine(" * Type {0}", cppTypename); writer.WriteLine(" */"); writer.WriteLine("struct {0}", cppTypename); writer.OpenBlock(); WriteBaseDescriptorField(writer); WriteDescriptorFields(writer); writer.CloseBlock(";"); writer.WriteLine(); }
/// <summary> /// Writes the descriptor fields. /// </summary> /// <param name="writer"></param> /// <param name="type">The type.</param> private void WriteDescriptorFields(SourceWriter writer) { IEnumerable<PropertyInfo> properties = from property in Type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) where property.HasAttribute<FieldAttribute>(true) select property; foreach (PropertyInfo property in properties) { string fieldName = property.Name; string translatedType = ConfigOptions.ToCppTypename(property, property.PropertyType) + "*"; WriteField(writer, fieldName, translatedType); } }
/// <summary> /// Generates the specified types. /// </summary> /// <param name="types">The types.</param> /// <param name="suffix">The suffix.</param> public void Generate(IEnumerable<Type> types, string suffix) { var outputFile = _options.ProjectName + suffix + ".cs"; outputFile = outputFile.Replace("_", ""); outputFile = Path.Combine(_options.CsOutputDir, outputFile); using (_writer = new SourceWriter(outputFile)) { _writer.WriteLine("/*"); _writer.WriteLine(" * GENERATED CODE"); _writer.WriteLine(" * DO NOT EDIT THIS"); _writer.WriteLine(" */"); _writer.WriteLine(); GenerateContent(types); } }
/// <summary> /// Generates the specified options. /// </summary> /// <param name="configOptions">The options.</param> /// <param name="types">The types.</param> public override void Generate(ConfigOptions configOptions, IEnumerable<Type> types) { Options = configOptions; var headerFilename = (ProjectName + ".h").ToLower(); var filename = (ProjectName + ".cpp").ToLower(); var wrapperTypes = types.Where(t => t.HasAttribute<CppClassAttribute>(true)); using (Writer = new SourceWriter(Path.Combine(Path.GetFullPath(Options.CppOutputDir), filename))) { var definitions = (from type in types let attribute = type.GetAttribute<CppTypeAttribute>(true) where attribute != null select new { attribute.DefinitionFile, attribute.LocalDefinition }).Distinct(); Writer.WriteLine("#include \"{0}\"", headerFilename); foreach (var definition in definitions) { if (string.IsNullOrEmpty(definition.DefinitionFile)) continue; if (definition.LocalDefinition) Writer.WriteLine("#include \"{0}\"", definition.DefinitionFile); else Writer.WriteLine("#include <{0}>", definition.DefinitionFile); } Writer.WriteLine(); Writer.WriteLine("using namespace invision;"); Writer.WriteLine(); WriteImplementations(wrapperTypes); Writer.WriteLine(); Writer.Close(); } }
/// <summary> /// Writes the base descriptor field. /// </summary> /// <param name="writer">The writer.</param> private void WriteBaseDescriptorField(SourceWriter writer) { IEnumerable<Type> parentInterfaces = Type.GetInterfaces().Where(i => i.HasAttribute<CppClassAttribute>(true)); var baseInterface = (from i in parentInterfaces let attr = i.GetAttribute<CppClassAttribute>(true) where attr.Type == ClassType.Concrete select new { Interface = i, Attribute = attr }).SingleOrDefault(); if (baseInterface != null) { const string fieldName = "base"; string translatedType = ConfigOptions.GetCppWrapperDescriptorTypename(baseInterface.Interface); WriteField(writer, fieldName, translatedType); } else { WriteField(writer, "self", "InvHandle"); } }
public void EscrowLineWritesFirstAtIndentationWhenItWasAdded() { var writer = new StringWriter(); var source = new SourceWriter(writer); source.WriteLine().AddIndent(); source .WriteLine("one") .AddIndent() .WriteLine("two") .EscrowLine("two-b") .RemoveIndent() .WriteLine("three") .RemoveIndent(); Assert.That(source.ToString(), Is.EqualTo(@" one two two-b three ")); }
private string[] GenerateMethodBody(Expression <Action <MethodTarget> > expression, Action <MethodCall> configure = null) { var @call = MethodCall.For(expression); @call.Target = Variable.For <MethodTarget>("target"); configure?.Invoke(@call); var writer = new SourceWriter(); theMethod.Frames.Clear(); theMethod.Frames.Add(@call); theMethod.WriteMethod(writer); var allLines = writer.Code().ReadLines().ToArray(); // Skip method declaration and { // Do not take first 2 lines, nor closing } return(allLines.Skip(2) .Take(allLines.Length - 3) .Select(l => l.Trim()) .ToArray()); }
private static int WriteCSharpSourceFiles(string inputFile, bool writeSource, bool writeTests, bool writeSignatures, string outputFile) { var tree = ReadTree(inputFile); // The syntax.xml doc contains some nodes that are useful for other tools, but which are // not needed by this syntax generator. Specifically, we have `<Choice>` and // `<Sequence>` nodes in the xml file to help others tools understand the relationship // between some fields (i.e. 'only one of these children can be non-null'). To make our // life easier, we just flatten all those nodes, grabbing all the nested `<Field>` nodes // and placing into a single linear list that we can then process. TreeFlattening.FlattenChildren(tree); if (writeSignatures) { SignatureWriter.Write(Console.Out, tree); } else { if (writeSource) { var outputPath = outputFile.Trim('"'); var prefix = Path.GetFileName(inputFile); var outputMainFile = Path.Combine(outputPath, $"{prefix}.Main.Generated.cs"); var outputInternalFile = Path.Combine(outputPath, $"{prefix}.Internal.Generated.cs"); var outputSyntaxFile = Path.Combine(outputPath, $"{prefix}.Syntax.Generated.cs"); WriteToFile(writer => SourceWriter.WriteMain(writer, tree), outputMainFile); WriteToFile(writer => SourceWriter.WriteInternal(writer, tree), outputInternalFile); WriteToFile(writer => SourceWriter.WriteSyntax(writer, tree), outputSyntaxFile); } if (writeTests) { WriteToFile(writer => TestWriter.Write(writer, tree), outputFile); } } return(0); }
public override void Dump(SourceWriter sw, int indentChange) { sw.Write("new"); if (BaseType != null) { sw.Write(" "); DumpChild(BaseType, sw); } sw.Write("["); var i = 0; foreach (var dimension in _dimensions) { if (i++ != 0) { sw.Write(", "); } DumpChild(dimension, sw); } sw.Write("]"); if (RankSpecifier != null) { sw.Write(RankSpecifier.Substring(2)); } if (_initializer == null) { return; } sw.Write(" "); DumpChild(_initializer, sw); }
public static string GenerateDocumentStorageCode(IDocumentMapping[] mappings) { var writer = new SourceWriter(); // TODO -- get rid of the magic strings var namespaces = new List<string> { "System", "Marten", "Marten.Schema", "Marten.Services", "Marten.Linq", "Marten.Util", "Npgsql", "Remotion.Linq", typeof (NpgsqlDbType).Namespace, typeof (IEnumerable<>).Namespace, typeof(DbDataReader).Namespace, typeof(CancellationToken).Namespace, typeof(Task).Namespace }; namespaces.AddRange(mappings.Select(x => x.DocumentType.Namespace)); namespaces.Distinct().OrderBy(x => x).Each(x => writer.WriteLine($"using {x};")); writer.BlankLine(); writer.StartNamespace("Marten.GeneratedCode"); mappings.Each(x => { GenerateDocumentStorage(x, writer); writer.BlankLine(); writer.BlankLine(); }); writer.FinishBlock(); return writer.Code(); }
public override void Dump(SourceWriter sw, int indentChange) { if (_openType == TypeManager.CoreTypes.GenericNullable) { if (_typeArguments.ResolvedTypes != null) { sw.Write(TypeManager.GetCSharpName(_typeArguments.ResolvedTypes[0])); sw.Write("?"); return; } DumpChild(_typeArguments[0], sw); sw.Write("?"); return; } if (_typeArguments.ResolvedTypes != null) { sw.Write(TypeManager.GetCSharpName(_openType.MakeGenericType(_typeArguments.ResolvedTypes))); return; } sw.Write(TypeManager.GetCSharpName(ReflectionUtils.GetNormalizedTypeName(_openType), _openType)); sw.Write("<"); int i = 0; foreach (var typeArgument in _typeArguments) { if (i++ != 0) { sw.Write(", "); } typeArgument.Dump(sw); } sw.Write(">"); }
public override void Dump(SourceWriter sw, int indentChange) { sw.Write(Name); if (_typeArguments.Count == 0) { return; } sw.Write("<"); for (var i = 0; i < _typeArguments.Count; i++) { var typeArgument = _typeArguments[i]; if (i != 0) { sw.Write(", "); } typeArgument.Dump(sw, indentChange); } sw.Write(">"); }
private static void GenerateIsX(KindList kinds, SourceWriter writer, string typeName, Func <KindInfo, bool> filter) { writer.WriteLine("/// <summary>"); writer.WriteLine($"/// Checks whether the provided <see cref=\"SyntaxKind\"/> is a {typeName.ToLower()}'s."); writer.WriteLine("/// </summary>"); writer.WriteLine("/// <param name=\"kind\"></param>"); writer.WriteLine("/// <returns></returns>"); using (writer.CurlyIndenter($"public static bool Is{typeName}(SyntaxKind kind)")) using (writer.CurlyIndenter("switch(kind)")) { var filteredKinds = kinds.Where(filter); foreach (var keyword in filteredKinds.OrderBy(kw => kw.Field.Name)) { writer.WriteLine($"case SyntaxKind.{keyword.Field.Name}:"); } using (writer.Indenter()) writer.WriteLine("return true;"); writer.WriteLineNoTabs(""); using (writer.Indenter("default:")) writer.WriteLine("return false;"); } }
public override void Dump(SourceWriter sw, int indentChange) { sw.Write("orderby "); DumpChild(Expression, sw, indentChange); if (Direction.HasValue) { sw.Write(" "); sw.Write(Direction.Value.ToString().ToLowerInvariant()); } if (Next is ThenbyClause) { sw.Write(", "); } else { sw.WriteLine(); } DumpChild(Next, sw, indentChange); }
/// <summary> /// Generates this instance. /// </summary> /// <returns></returns> public string Generate() { string cppTypename = GetTypename(); string filename = ConfigOptions.AdditionalInclude(cppTypename); string fullFilename = Path.Combine(ConfigOptions.CppOutputDir, filename); using (var writer = new SourceWriter(fullFilename)) { string deffilename = string.Format("__{0}__", filename.Replace('.', '_').ToUpper()); writer.WriteLine("#ifndef {0}", deffilename); writer.WriteLine("#define {0}", deffilename); writer.WriteLine(); writer.WriteLine("#include <InvisionHandle.h>"); foreach (string include in ScanIncludes()) { writer.WriteLine("#include \"{0}\"", include); } writer.WriteLine("#include \"{0}\"", ConfigOptions.IncludeCppHeader); writer.WriteLine(); writer.WriteLine("extern \"C\""); writer.OpenBlock(); { GenerateType(writer, cppTypename); } writer.CloseBlock(); writer.WriteLine(); writer.WriteLine("#endif // {0}", deffilename); writer.WriteLine(); } return filename; }
public string GenerateCode(IGenerationConfig generation) { beforeGeneratingCode(); var writer = new SourceWriter(); writer.UsingNamespace <Task>(); writer.BlankLine(); writer.Namespace(generation.ApplicationNamespace); foreach (var chain in chains) { var generationModel = chain.ToGenerationModel(generation); // TODO -- figure out how to get the source code for each handler writer.WriteLine($"// START: {chain.TypeName}"); HandlerSourceWriter.Write(generationModel, writer); writer.WriteLine($"// END: {chain.TypeName}"); writer.WriteLine(""); writer.WriteLine(""); } writer.FinishBlock(); var code = writer.Code(); attachSourceCodeToChains(code); return(code); }
public override void GenerateSourceCode(IEnumerable<IList<Chunk>> viewTemplates, IEnumerable<IList<Chunk>> allResources) { var script = new SourceWriter(); var globals = new Dictionary<string, object>(); script.WriteLine(ScriptHeader); script.WriteLine("class<<view"); script.Indent++; var globalMembersVisitor = new GlobalMembersVisitor(script, globals); foreach (var resource in allResources) globalMembersVisitor.Accept(resource); var globalFunctionsVisitor = new GlobalFunctionsVisitor(script, globals); foreach (var resource in allResources) globalFunctionsVisitor.Accept(resource); var templateIndex = 0; foreach (var template in viewTemplates) { script.Write("def render_view_level").WriteLine(templateIndex); script.Indent++; var generator = new GeneratedCodeVisitor(script, globals); generator.Accept(template); script.Indent--; script.WriteLine("end"); templateIndex++; } script.WriteLine("def render"); script.Indent++; var globalInitializeVisitor = new GlobalInitializeVisitor(script); foreach(var resource in allResources) globalInitializeVisitor.Accept(resource); for (var renderIndex = 0; renderIndex != templateIndex; ++renderIndex) { if (renderIndex < templateIndex - 1) { script.WriteLine("scope = output_scope"); script. Write("render_view_level").WriteLine(renderIndex); script.WriteLine("content.set_Item \"view\", output"); script.WriteLine("scope.dispose"); } else { script.Write("render_view_level").WriteLine(renderIndex); } } script.Indent--; script.WriteLine("end"); script.Indent--; script.WriteLine("end"); script.WriteLine("view.view_data.each {|kv| view.instance_variable_set \"@\"+kv.key, kv.value}"); script.WriteLine("view.render"); var baseClassGenerator = new BaseClassVisitor { BaseClass = BaseClass }; foreach (var resource in allResources) baseClassGenerator.Accept(resource); BaseClass = baseClassGenerator.BaseClassTypeName; var source = new StringBuilder(); var viewClassName = "View" + GeneratedViewId.ToString("n"); if (Descriptor != null && !string.IsNullOrEmpty(Descriptor.TargetNamespace)) { ViewClassFullName = Descriptor.TargetNamespace + "." + viewClassName; source.Append("namespace ").AppendLine(Descriptor.TargetNamespace); source.AppendLine("{"); } else { ViewClassFullName = viewClassName; } if (Descriptor != null) { // [SparkView] attribute source.AppendLine("[global::Spark.SparkViewAttribute("); if (TargetNamespace != null) source.AppendFormat(" TargetNamespace=\"{0}\",", TargetNamespace).AppendLine(); source.AppendLine(" Templates = new string[] {"); source.Append(" ").AppendLine(string.Join(",\r\n ", Descriptor.Templates.Select( t => "\"" + t.Replace("\\", "\\\\") + "\"").ToArray())); source.AppendLine(" })]"); } source.Append("public class ").Append(viewClassName).Append(" : ").Append(BaseClass).AppendLine(", global::Spark.Ruby.IScriptingSparkView"); source.AppendLine("{"); source.Append("static System.Guid _generatedViewId = new System.Guid(\"").Append(GeneratedViewId).AppendLine("\");"); source.AppendLine("public override System.Guid GeneratedViewId"); source.AppendLine("{"); source.AppendLine("get { return _generatedViewId; }"); source.AppendLine("}"); source.AppendLine("public global::System.IDisposable OutputScopeAdapter(object arg) "); source.AppendLine("{"); source.AppendLine("if (arg == null) return OutputScope();"); source.AppendLine("if (arg is global::System.IO.TextWriter) return OutputScope((global::System.IO.TextWriter)arg);"); source.AppendLine("return OutputScope(global::System.Convert.ToString(arg));"); source.AppendLine("}"); source.AppendLine("public void OutputWriteAdapter(object arg) "); source.AppendLine("{"); source.AppendLine("Output.Write(arg);"); source.AppendLine("}"); source.AppendLine("public global::Microsoft.Scripting.Hosting.CompiledCode CompiledCode {get;set;}"); source.AppendLine("public string ScriptSource"); source.AppendLine("{"); source.Append("get { return @\"").Append(script.ToString().Replace("\"", "\"\"")).AppendLine("\"; }"); source.AppendLine("}"); source.AppendLine("public override void Render()"); source.AppendLine("{"); source.AppendLine("CompiledCode.Execute("); source.AppendLine("CompiledCode.Engine.CreateScope("); source.AppendLine("new global::Spark.Ruby.ScriptingViewSymbolDictionary(this)"); source.AppendLine("));"); source.AppendLine("}"); source.AppendLine("}"); if (Descriptor != null && !string.IsNullOrEmpty(Descriptor.TargetNamespace)) { source.AppendLine("}"); } SourceCode = source.ToString(); }
public HashHelper(SourceWriter headers, SourceWriter implementation) : base(headers, implementation) { MonoSignature = "GetHashCode()"; ObjCSignature = "hash"; ReturnType = "NSUInteger"; }
public static void GenerateDocumentStorage(DocumentMapping mapping, SourceWriter writer) { var extraUpsertArguments = mapping.DuplicatedFields.Any() ? mapping.DuplicatedFields.Select(x => x.WithParameterCode()).Join("") : ""; // TODO -- move more of this into DocumentMapping, DuplicatedField, IField, etc. var id_NpgsqlDbType = TypeMappings.ToDbType(mapping.IdMember.GetMemberType()); var duplicatedFieldsInBulkLoading = mapping.DuplicatedFields.Any() ? ", " + mapping.DuplicatedFields.Select(x => x.ColumnName).Join(", ") : string.Empty; var duplicatedFieldsInBulkLoadingWriter = ""; if (mapping.DuplicatedFields.Any()) { duplicatedFieldsInBulkLoadingWriter = mapping.DuplicatedFields.Select(field => { return field.ToBulkWriterCode(); }).Join("\n"); } var typeName = mapping.DocumentType.IsNested ? $"{mapping.DocumentType.DeclaringType.Name}.{mapping.DocumentType.Name}" : mapping.DocumentType.Name; var storageArguments = mapping.IdStrategy.ToArguments(); var ctorArgs = storageArguments.Select(x => x.ToCtorArgument()).Join(", "); var ctorLines = storageArguments.Select(x => x.ToCtorLine()).Join("\n"); var fields = storageArguments.Select(x => x.ToFieldDeclaration()).Join("\n"); writer.Write( $@" BLOCK:public class {mapping.DocumentType.Name}Storage : IDocumentStorage, IBulkLoader<{typeName }>, IdAssignment<{typeName}>, IResolver<{typeName}> {fields} BLOCK:public {mapping.DocumentType.Name}Storage({ ctorArgs}) {ctorLines} END public Type DocumentType => typeof ({typeName }); BLOCK:public NpgsqlCommand UpsertCommand(object document, string json) return UpsertCommand(({ typeName })document, json); END BLOCK:public NpgsqlCommand LoaderCommand(object id) return new NpgsqlCommand(`select data from { mapping.TableName } where id = :id`).With(`id`, id); END BLOCK:public NpgsqlCommand DeleteCommandForId(object id) return new NpgsqlCommand(`delete from { mapping.TableName } where id = :id`).With(`id`, id); END BLOCK:public NpgsqlCommand DeleteCommandForEntity(object entity) return DeleteCommandForId((({ typeName})entity).{mapping.IdMember.Name }); END BLOCK:public NpgsqlCommand LoadByArrayCommand<T>(T[] ids) return new NpgsqlCommand(`select data, id from { mapping.TableName } where id = ANY(:ids)`).With(`ids`, ids); END BLOCK:public NpgsqlCommand UpsertCommand({ typeName} document, string json) return new NpgsqlCommand(`{mapping.UpsertName }`) .AsSproc() .With(`id`, document.{mapping.IdMember.Name }) .WithJsonParameter(`doc`, json){extraUpsertArguments}; END BLOCK:public object Assign({ typeName} document) {mapping.IdStrategy.AssignmentBodyCode(mapping.IdMember)} return document.{ mapping.IdMember.Name}; END BLOCK:public object Retrieve({typeName} document) return document.{ mapping.IdMember.Name}; END public NpgsqlDbType IdType => NpgsqlDbType.{id_NpgsqlDbType }; BLOCK:public object Identity(object document) return (({typeName})document).{ mapping.IdMember.Name}; END BLOCK:public {typeName} Resolve(DbDataReader reader, IIdentityMap map) var json = reader.GetString(0); var id = reader[1]; return map.Get<{typeName}>(id, json); END {toUpdateBatchMethod(mapping, id_NpgsqlDbType, typeName) } BLOCK:public void Load(ISerializer serializer, NpgsqlConnection conn, IEnumerable<{typeName }> documents) BLOCK:using (var writer = conn.BeginBinaryImport(`COPY {mapping.TableName}(id, data{ duplicatedFieldsInBulkLoading }) FROM STDIN BINARY`)) BLOCK:foreach (var x in documents) writer.StartRow(); writer.Write(x.Id, NpgsqlDbType.{ id_NpgsqlDbType}); writer.Write(serializer.ToJson(x), NpgsqlDbType.Jsonb); { duplicatedFieldsInBulkLoadingWriter} END END END END "); }
private static void GenerateSyntaxFacts(GeneratorExecutionContext context, KindList kinds) { SourceText sourceText; using (var writer = new SourceWriter()) { writer.WriteLine("// <auto-generated />"); writer.WriteLine(); writer.WriteLine("using System;"); writer.WriteLine("using System.Collections.Generic;"); writer.WriteLine("using System.Collections.Immutable;"); writer.WriteLine("using System.Diagnostics.CodeAnalysis;"); writer.WriteLine("using Tsu;"); writer.WriteLine(); writer.WriteLine("#nullable enable"); writer.WriteLine(); using (writer.CurlyIndenter("namespace Loretta.CodeAnalysis.Lua")) using (writer.CurlyIndenter("public static partial class SyntaxFacts")) { GenerateMinMaxLength(kinds.Tokens.Concat(kinds.Keywords), writer, "Token"); GenerateMinMaxLength(kinds.Tokens, writer, "NonKeywordToken"); GenerateMinMaxLength(kinds.Keywords, writer, "Keyword"); GenerateMinMaxLength(kinds.UnaryOperators, writer, "UnaryOperator"); GenerateMinMaxLength(kinds.BinaryOperators, writer, "BinaryOperator"); writer.WriteLineNoTabs(""); GenerateGetUnaryOperatorPrecedence(kinds, writer); writer.WriteLineNoTabs(""); GenerateGetUnaryExpression(kinds, writer); writer.WriteLineNoTabs(""); GenerateGetBinaryOperatorPrecedence(kinds, writer); writer.WriteLineNoTabs(""); GenerateGetBinaryExpression(kinds, writer); writer.WriteLineNoTabs(""); GenerateGetKeywordKind(kinds, writer); writer.WriteLineNoTabs(""); GenerateGetUnaryOperatorKinds(kinds, writer); writer.WriteLineNoTabs(""); GenerateGetBinaryOperatorKinds(kinds, writer); writer.WriteLineNoTabs(""); GenerateGetText(kinds, writer); var properties = kinds.SelectMany(kind => kind.Properties.Select(kv => (kind, key: kv.Key, value: kv.Value))) .GroupBy(t => t.key, t => (t.kind, t.value)); foreach (var propertyGroup in properties) { var possibleTypes = propertyGroup.Select(t => t.value.Type) .Where(t => t is not null) .Distinct(SymbolEqualityComparer.Default) .ToImmutableArray(); string type; if (possibleTypes.Length > 1) { type = context.Compilation.GetSpecialType(SpecialType.System_Object) + "?"; } else { type = possibleTypes.Single() !.ToString(); } writer.WriteLineNoTabs(""); using (new CurlyIndenter(writer, $"public static partial Option<{type}> Get{propertyGroup.Key}(SyntaxKind kind)")) { var values = propertyGroup.GroupBy(t => t.value, t => t.kind); writer.WriteLine("return kind switch"); writer.WriteLine("{"); using (new Indenter(writer)) { foreach (var value in values) { writer.Write(string.Join(" or ", value.Select(k => $"SyntaxKind.{k.Field.Name}"))); writer.Write(" => "); writer.Write(value.Key.ToCSharpString()); writer.WriteLine(","); } writer.WriteLine("_ => default,"); } writer.WriteLine("};"); } } writer.WriteLineNoTabs(""); // Generate IsTrivia GenerateIsX(kinds, writer, "Trivia", kind => kind.IsTrivia); writer.WriteLineNoTabs(""); // Generate IsKeyword GenerateIsX(kinds, writer, "Keyword", kind => kind.TokenInfo?.IsKeyword is true); writer.WriteLineNoTabs(""); // Generate IsToken GenerateIsX(kinds, writer, "Token", kind => kind.TokenInfo is not null); // Generate Is(Unary|Binary)Operator GenerateIsX(kinds, writer, "OperatorToken", kind => kind.UnaryOperatorInfo is not null || kind.BinaryOperatorInfo is not null); GenerateIsX(kinds, writer, "UnaryOperatorToken", kind => kind.UnaryOperatorInfo is not null); GenerateIsX(kinds, writer, "BinaryOperatorToken", kind => kind.BinaryOperatorInfo is not null); writer.WriteLineNoTabs(""); // Extra Categories var extraCategories = kinds.SelectMany(kind => kind.ExtraCategories.Select(cat => (cat, kind))) .GroupBy(t => t.cat, t => t.kind); foreach (var group in extraCategories) { writer.WriteLineNoTabs(""); var groupKinds = new KindList(group.ToImmutableArray()); GenerateIsX(groupKinds, writer, group.Key, k => true); writer.WriteLineNoTabs(""); writer.WriteLine("/// <summary>"); writer.WriteLine($"/// Returns all <see cref=\"SyntaxKind\"/>s that are in the {group.Key} category."); writer.WriteLine("/// </summary>"); writer.WriteLine("/// <returns></returns>"); using (writer.CurlyIndenter($"public static IEnumerable<SyntaxKind> Get{group.Key}Kinds() => ImmutableArray.Create(new[]", ");")) { foreach (var kind in group) { writer.WriteLine($"SyntaxKind.{kind.Field.Name},"); } } } } sourceText = writer.GetText(); } context.AddSource("SyntaxFacts.g.cs", sourceText); }
public override void GenerateSourceCode(IEnumerable<IList<Chunk>> viewTemplates, IEnumerable<IList<Chunk>> allResources) { var script = new SourceWriter(); var globals = new Dictionary<string, object>(); var globalMembersVisitor = new GlobalMembersVisitor(script, globals); foreach(var resource in allResources) globalMembersVisitor.Accept(resource); var globalFunctionsVisitor = new GlobalFunctionsVisitor(script, globals); foreach (var resource in allResources) globalFunctionsVisitor.Accept(resource); var templateIndex = 0; foreach (var template in viewTemplates) { script.Write("def RenderViewLevel").Write(templateIndex).WriteLine("():"); script.Indent++; foreach (var global in globals.Keys) script.Write("global ").WriteLine(global); var generator = new GeneratedCodeVisitor(script, globals); generator.Accept(template); script.Indent--; script.WriteLine(); templateIndex++; } for (var renderIndex = 0; renderIndex != templateIndex; ++renderIndex) { if (renderIndex < templateIndex - 1) { script.WriteLine("scope=OutputScopeAdapter(None)"); script.Write("RenderViewLevel").Write(renderIndex).WriteLine("()"); script.WriteLine("Content[\"view\"] = Output"); script.WriteLine("scope.Dispose()"); } else { script.Write("RenderViewLevel").Write(renderIndex).WriteLine("()"); } } var baseClassGenerator = new BaseClassVisitor { BaseClass = BaseClass }; foreach (var resource in allResources) baseClassGenerator.Accept(resource); BaseClass = baseClassGenerator.BaseClassTypeName; var source = new StringBuilder(); var viewClassName = "View" + GeneratedViewId.ToString("n"); if (Descriptor != null && !string.IsNullOrEmpty(Descriptor.TargetNamespace)) { ViewClassFullName = Descriptor.TargetNamespace + "." + viewClassName; source.Append("namespace ").AppendLine(Descriptor.TargetNamespace); source.AppendLine("{"); } else { ViewClassFullName = viewClassName; } if (Descriptor != null) { // [SparkView] attribute source.AppendLine("[global::Spark.SparkViewAttribute("); if (TargetNamespace != null) source.AppendFormat(" TargetNamespace=\"{0}\",", TargetNamespace).AppendLine(); source.AppendLine(" Templates = new string[] {"); source.Append(" ").AppendLine(string.Join(",\r\n ", Descriptor.Templates.Select( t => "\"" + SparkViewAttribute.ConvertToAttributeFormat(t) + "\"").ToArray())); source.AppendLine(" })]"); } source.Append("public class ").Append(viewClassName).Append(" : ").Append(BaseClass).AppendLine(", global::Spark.Python.IScriptingSparkView"); source.AppendLine("{"); source.Append("static System.Guid _generatedViewId = new System.Guid(\"").Append(GeneratedViewId).AppendLine("\");"); source.AppendLine("public override System.Guid GeneratedViewId"); source.AppendLine("{"); source.AppendLine("get { return _generatedViewId; }"); source.AppendLine("}"); source.AppendLine("public global::System.IDisposable OutputScopeAdapter(object arg) "); source.AppendLine("{"); source.AppendLine("if (arg == null) return OutputScope();"); source.AppendLine("if (arg is string) return OutputScope((string)arg);"); source.AppendLine("if (arg is global::System.IO.TextWriter) return OutputScope((global::System.IO.TextWriter)arg);"); source.AppendLine("throw new global::Spark.Compiler.CompilerException(\"Invalid argument for OutputScopeAdapter\");"); source.AppendLine("}"); source.AppendLine("public void OutputWriteAdapter(object arg) "); source.AppendLine("{"); source.AppendLine("Output.Write(arg);"); source.AppendLine("}"); source.AppendLine("public global::Microsoft.Scripting.Hosting.CompiledCode CompiledCode {get;set;}"); source.AppendLine("public string ScriptSource"); source.AppendLine("{"); source.Append("get { return @\"").Append(script.ToString().Replace("\"", "\"\"")).AppendLine("\"; }"); source.AppendLine("}"); source.AppendLine("public override void Render()"); source.AppendLine("{"); source.AppendLine("CompiledCode.Execute("); source.AppendLine("CompiledCode.Engine.CreateScope("); source.AppendLine("new global::Spark.Python.ScriptingViewSymbolDictionary(this)"); source.AppendLine("));"); source.AppendLine("}"); source.AppendLine("}"); if (Descriptor != null && !string.IsNullOrEmpty(Descriptor.TargetNamespace)) { source.AppendLine("}"); } SourceCode = source.ToString(); }
public GlobalFunctionsVisitor(SourceWriter source, IDictionary<string, object> globals) { _source = source; _globals = globals; }
public void Write(SourceWriter writer) { writer.StartLine(ToString()); }
public UsingNamespaceVisitor(SourceWriter output) { _source = output; }
public override void GenerateSourceCode(IEnumerable <IList <Chunk> > viewTemplates, IEnumerable <IList <Chunk> > allResources) { Dictionary <string, object> globalSymbols = new Dictionary <string, object>(); StringWriter writer = new StringWriter(); SourceWriter output = new SourceWriter(writer); UsingNamespaceVisitor visitor = new UsingNamespaceVisitor(output); BaseClassVisitor visitor2 = new BaseClassVisitor { BaseClass = base.BaseClass }; GlobalMembersVisitor visitor3 = new GlobalMembersVisitor(output, globalSymbols, base.NullBehaviour); foreach (string str in base.UseNamespaces ?? ((IEnumerable <string>) new string[0])) { visitor.UsingNamespace(str); } foreach (string str2 in base.UseAssemblies ?? ((IEnumerable <string>) new string[0])) { visitor.UsingAssembly(str2); } foreach (IList <Chunk> list in allResources) { visitor.Accept(list); } foreach (IList <Chunk> list2 in allResources) { visitor2.Accept(list2); } string str3 = "View" + base.GeneratedViewId.ToString("n"); if (string.IsNullOrEmpty(base.TargetNamespace)) { base.ViewClassFullName = str3; } else { base.ViewClassFullName = base.TargetNamespace + "." + str3; output.WriteLine().WriteLine(string.Format("namespace {0}", base.TargetNamespace)).WriteLine("{").AddIndent(); } output.WriteLine(); if (base.Descriptor != null) { output.WriteLine("[global::Spark.SparkViewAttribute("); if (base.TargetNamespace != null) { output.WriteFormat(" TargetNamespace=\"{0}\",", new object[] { base.TargetNamespace }).WriteLine(); } output.WriteLine(" Templates = new string[] {"); output.Write(" ").WriteLine(string.Join(",\r\n ", (from t in base.Descriptor.Templates select "\"" + SparkViewAttribute.ConvertToAttributeFormat(t) + "\"").ToArray <string>())); output.WriteLine(" })]"); } output.Write("public class ").Write(str3).Write(" : ").WriteCode(visitor2.BaseClassTypeName).WriteLine(); output.WriteLine("{").AddIndent(); output.WriteLine(); EditorBrowsableStateNever(output, 4); output.WriteLine("private static System.Guid _generatedViewId = new System.Guid(\"{0:n}\");", new object[] { base.GeneratedViewId }); output.WriteLine("public override System.Guid GeneratedViewId"); output.WriteLine("{ get { return _generatedViewId; } }"); if ((base.Descriptor != null) && (base.Descriptor.Accessors != null)) { foreach (SparkViewDescriptor.Accessor accessor in base.Descriptor.Accessors) { output.WriteLine(); output.Write("public ").WriteLine(accessor.Property); output.Write("{ get { return ").Write(accessor.GetValue).WriteLine("; } }"); } } foreach (IList <Chunk> list3 in allResources) { visitor3.Accept(list3); } int num = 0; foreach (IList <Chunk> list4 in viewTemplates) { output.WriteLine(); EditorBrowsableStateNever(output, 4); output.WriteLine(string.Format("private void RenderViewLevel{0}()", num)); output.WriteLine("{").AddIndent(); new GeneratedCodeVisitor(output, globalSymbols, base.NullBehaviour).Accept(list4); output.RemoveIndent().WriteLine("}"); num++; } output.WriteLine(); EditorBrowsableStateNever(output, 4); output.WriteLine("public override void Render()"); output.WriteLine("{").AddIndent(); for (int i = 0; i != num; i++) { if (i != (num - 1)) { output.WriteLine("using (OutputScope()) {{RenderViewLevel{0}(); Content[\"view\"] = Output;}}", new object[] { i }); } else { output.WriteLine(" RenderViewLevel{0}();", new object[] { i }); } } output.RemoveIndent().WriteLine("}"); output.RemoveIndent().WriteLine("}"); if (!string.IsNullOrEmpty(base.TargetNamespace)) { output.RemoveIndent().WriteLine("}"); } base.SourceCode = output.ToString(); base.SourceMappings = output.Mappings; }
public override void Dump(SourceWriter sw, int indentChange) { sw.Write(MemberName); sw.Write(" = "); DumpChild(Value, sw, indentChange); }
public override void GenerateSourceCode(IEnumerable <IList <Chunk> > viewTemplates, IEnumerable <IList <Chunk> > allResources) { var globalSymbols = new Dictionary <string, object>(); var writer = new StringWriter(); var source = new SourceWriter(writer); var usingGenerator = new UsingNamespaceVisitor(source); var baseClassGenerator = new BaseClassVisitor { BaseClass = BaseClass }; var globalsGenerator = new GlobalMembersVisitor(source, globalSymbols, NullBehaviour); // using <namespaces>; foreach (var ns in UseNamespaces ?? new string[0]) { usingGenerator.UsingNamespace(ns); } foreach (var assembly in UseAssemblies ?? new string[0]) { usingGenerator.UsingAssembly(assembly); } foreach (var resource in allResources) { usingGenerator.Accept(resource); } foreach (var resource in allResources) { baseClassGenerator.Accept(resource); } var viewClassName = "View" + GeneratedViewId.ToString("n"); if (string.IsNullOrEmpty(TargetNamespace)) { ViewClassFullName = viewClassName; } else { ViewClassFullName = TargetNamespace + "." + viewClassName; source .WriteLine() .WriteLine(string.Format("namespace {0}", TargetNamespace)) .WriteLine("{").AddIndent(); } source.WriteLine(); if (Descriptor != null) { // [SparkView] attribute source.WriteLine("[global::Spark.SparkViewAttribute("); if (TargetNamespace != null) { source.WriteFormat(" TargetNamespace=\"{0}\",", TargetNamespace).WriteLine(); } source.WriteLine(" Templates = new string[] {"); source.Write(" ").WriteLine(string.Join(",\r\n ", Descriptor.Templates.Select( t => "\"" + SparkViewAttribute.ConvertToAttributeFormat(t) + "\"").ToArray())); source.WriteLine(" })]"); } // public class ViewName : BasePageType source .Write("public class ") .Write(viewClassName) .Write(" : ") .WriteCode(baseClassGenerator.BaseClassTypeName) .WriteLine(); source.WriteLine("{").AddIndent(); source.WriteLine(); EditorBrowsableStateNever(source, 4); source.WriteLine("private static System.Guid _generatedViewId = new System.Guid(\"{0:n}\");", GeneratedViewId); source.WriteLine("public override System.Guid GeneratedViewId"); source.WriteLine("{ get { return _generatedViewId; } }"); if (Descriptor != null && Descriptor.Accessors != null) { foreach (var accessor in Descriptor.Accessors) { source.WriteLine(); source.Write("public ").WriteLine(accessor.Property); source.Write("{ get { return ").Write(accessor.GetValue).WriteLine("; } }"); } } // properties and macros foreach (var resource in allResources) { globalsGenerator.Accept(resource); } // public void RenderViewLevelx() int renderLevel = 0; foreach (var viewTemplate in viewTemplates) { source.WriteLine(); EditorBrowsableStateNever(source, 4); source.WriteLine(string.Format("private void RenderViewLevel{0}()", renderLevel)); source.WriteLine("{").AddIndent(); var viewGenerator = new GeneratedCodeVisitor(source, globalSymbols, NullBehaviour); viewGenerator.Accept(viewTemplate); source.RemoveIndent().WriteLine("}"); ++renderLevel; } // public void RenderView() source.WriteLine(); EditorBrowsableStateNever(source, 4); source.WriteLine("public override void Render()"); source.WriteLine("{").AddIndent(); for (var invokeLevel = 0; invokeLevel != renderLevel; ++invokeLevel) { if (invokeLevel != renderLevel - 1) { source.WriteLine("using (OutputScope()) {{DelegateFirstRender(RenderViewLevel{0}); Content[\"view\"] = Output;}}", invokeLevel); } else { if (renderLevel <= 1) { source.WriteLine(" DelegateFirstRender(RenderViewLevel{0});", invokeLevel); } else { source.WriteLine(" RenderViewLevel{0}();", invokeLevel); } } } source.RemoveIndent().WriteLine("}"); // end class source.RemoveIndent().WriteLine("}"); if (!string.IsNullOrEmpty(TargetNamespace)) { source.RemoveIndent().WriteLine("}"); } SourceCode = source.ToString(); SourceMappings = source.Mappings; }
public Compiler(SourceWriter writer) { this.writer = writer; }
public GeneratedCodeVisitor(SourceWriter source, IDictionary <string, object> globals) { _source = source; _variables = new VariableTracker(globals); }
public override void Dump(SourceWriter sw, int indentChange) { sw.Write("select "); DumpChild(Projection, sw, indentChange); }
private static void EditorBrowsableStateNever(SourceWriter source, int indentation) { source .Indent(indentation) .WriteLine("[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]"); }
public GlobalFunctionsVisitor(SourceWriter source, IDictionary <string, object> globals) { _source = source; _globals = globals; }
public GlobalMembersVisitor(SourceWriter output, Dictionary <string, object> globalSymbols, NullBehaviour nullBehaviour) { _source = output; _globalSymbols = globalSymbols; _nullBehaviour = nullBehaviour; }
public GlobalInitializeVisitor(SourceWriter sourceWriter) { _source = sourceWriter; }
public static void GenerateDocumentStorage(IDocumentMapping mapping, SourceWriter writer) { var upsertFunction = mapping.ToUpsertFunction(); var id_NpgsqlDbType = TypeMappings.ToDbType(mapping.IdMember.GetMemberType()); var typeName = mapping.DocumentType.GetTypeName(); var storageArguments = mapping.ToArguments().ToArray(); var ctorArgs = storageArguments.Select(x => x.ToCtorArgument()).Join(", "); var ctorLines = storageArguments.Select(x => x.ToCtorLine()).Join("\n"); var fields = storageArguments.Select(x => x.ToFieldDeclaration()).Join("\n"); writer.Write( $@" BLOCK:public class {mapping.DocumentType.Name}Storage : IDocumentStorage, IBulkLoader<{typeName}>, IdAssignment<{typeName}>, IResolver<{typeName}> {fields} BLOCK:public {mapping.DocumentType.Name}Storage({ctorArgs}) {ctorLines} END public Type DocumentType => typeof ({typeName}); BLOCK:public NpgsqlCommand UpsertCommand(object document, string json) return UpsertCommand(({typeName})document, json); END BLOCK:public NpgsqlCommand LoaderCommand(object id) return new NpgsqlCommand(`select {mapping.SelectFields("d")} from {mapping.TableName} as d where id = :id`).With(`id`, id); END BLOCK:public NpgsqlCommand DeleteCommandForId(object id) return new NpgsqlCommand(`delete from {mapping.TableName} where id = :id`).With(`id`, id); END BLOCK:public NpgsqlCommand DeleteCommandForEntity(object entity) return DeleteCommandForId((({typeName})entity).{mapping.IdMember.Name}); END BLOCK:public NpgsqlCommand LoadByArrayCommand<T>(T[] ids) return new NpgsqlCommand(`select {mapping.SelectFields("d")} from {mapping.TableName} as d where id = ANY(:ids)`).With(`ids`, ids); END BLOCK:public void Remove(IIdentityMap map, object entity) var id = Identity(entity); map.Remove<{typeName}>(id); END BLOCK:public void Delete(IIdentityMap map, object id) map.Remove<{typeName}>(id); END BLOCK:public void Store(IIdentityMap map, object id, object entity) map.Store<{typeName}>(id, ({typeName})entity); END BLOCK:public object Assign({typeName} document) {mapping.IdStrategy.AssignmentBodyCode(mapping.IdMember)} return document.{mapping.IdMember.Name}; END BLOCK:public object Retrieve({typeName} document) return document.{mapping.IdMember.Name}; END BLOCK:public {typeName} Build(DbDataReader reader, ISerializer serializer) return serializer.FromJson<{typeName}>(reader.GetString(0)); END public NpgsqlDbType IdType => NpgsqlDbType.{id_NpgsqlDbType}; BLOCK:public object Identity(object document) return (({typeName})document).{mapping.IdMember.Name}; END BLOCK:public {typeName} Resolve(IIdentityMap map, ILoader loader, object id) return map.Get(id, () => loader.LoadDocument<{typeName}>(id)) as {typeName}; END BLOCK:public Task<{typeName}> ResolveAsync(IIdentityMap map, ILoader loader, CancellationToken token, object id) return map.GetAsync(id, (tk => loader.LoadDocumentAsync<{typeName}>(id, tk)), token).ContinueWith(x => x.Result as {typeName}, token); END {mapping.ToResolveMethod(typeName)} {upsertFunction.ToUpdateBatchMethod(typeName)} {upsertFunction.ToBulkInsertMethod(typeName)} END "); }
public BrowserCompiler(SourceWriter writer) : base(writer) { }
public void Generate(SourceWriter writer) { writer.WriteModifiers(this.Modifiers); writer.WriteLine($"{this.Type} {this.Name};"); }
public override void Dump(SourceWriter sw, int indentChange) { DumpChild(Expression, sw); }
public static void GenerateDocumentStorage(DocumentMapping mapping, SourceWriter writer) { var upsertFunction = mapping.ToUpsertFunction(); var id_NpgsqlDbType = TypeMappings.ToDbType(mapping.IdMember.GetMemberType()); var typeName = mapping.DocumentType.GetTypeName(); var storeName = _storenameSanitizer.Replace(mapping.DocumentType.GetPrettyName(), string.Empty); var storageArguments = mapping.ToArguments().ToArray(); var ctorArgs = storageArguments.Select(x => x.ToCtorArgument()).Join(", "); var ctorLines = storageArguments.Select(x => x.ToCtorLine()).Join("\n"); var fields = storageArguments.Select(x => x.ToFieldDeclaration()).Join("\n"); var baseType = mapping.IsHierarchy() ? "HierarchicalResolver" : "Resolver"; var callBaseCtor = mapping.IsHierarchy() ? $": base({HierarchyArgument.Hierarchy})" : string.Empty; writer.Write( $@" BLOCK:public class {storeName}Storage : {baseType}<{typeName}>, IDocumentStorage, IBulkLoader<{typeName}>, IdAssignment<{typeName}>, IResolver<{typeName}> {fields} BLOCK:public {storeName}Storage({ctorArgs}) {callBaseCtor} {ctorLines} END public Type DocumentType => typeof ({typeName}); BLOCK:public NpgsqlCommand UpsertCommand(object document, string json) return UpsertCommand(({typeName})document, json); END BLOCK:public NpgsqlCommand LoaderCommand(object id) return new NpgsqlCommand(`select {mapping.SelectFields().Join(", ")} from {mapping.QualifiedTableName} as d where id = :id`).With(`id`, id); END BLOCK:public NpgsqlCommand DeleteCommandForId(object id) return new NpgsqlCommand(`delete from {mapping.QualifiedTableName} where id = :id`).With(`id`, id); END BLOCK:public NpgsqlCommand DeleteCommandForEntity(object entity) return DeleteCommandForId((({typeName})entity).{mapping.IdMember.Name}); END BLOCK:public NpgsqlCommand LoadByArrayCommand<T>(T[] ids) return new NpgsqlCommand(`select {mapping.SelectFields().Join(", ")} from {mapping.QualifiedTableName} as d where id = ANY(:ids)`).With(`ids`, ids); END BLOCK:public void Remove(IIdentityMap map, object entity) var id = Identity(entity); map.Remove<{typeName}>(id); END BLOCK:public void Delete(IIdentityMap map, object id) map.Remove<{typeName}>(id); END BLOCK:public void Store(IIdentityMap map, object id, object entity) map.Store<{typeName}>(id, ({typeName})entity); END BLOCK:public object Assign({typeName} document, out bool assigned) {mapping.IdStrategy.AssignmentBodyCode(mapping.IdMember)} return document.{mapping.IdMember.Name}; END BLOCK:public object Retrieve({typeName} document) return document.{mapping.IdMember.Name}; END public NpgsqlDbType IdType => NpgsqlDbType.{id_NpgsqlDbType}; BLOCK:public object Identity(object document) return (({typeName})document).{mapping.IdMember.Name}; END {upsertFunction.ToUpdateBatchMethod(typeName)} {upsertFunction.ToBulkInsertMethod(typeName)} END "); }
/// <summary> /// Writes the field. /// </summary> /// <param name="writer">The writer.</param> /// <param name="fieldInfo">The field info.</param> protected void WriteField(SourceWriter writer, FieldInfo fieldInfo) { Type fieldType = fieldInfo.FieldType; string fieldName = fieldInfo.Name; string translatedType = ConfigOptions.ToCppTypename(fieldInfo, fieldType); WriteField(writer, fieldName, translatedType); }
static void writeHeader(SourceWriter writer) { writer.WriteLine("/// <summary>"); writer.WriteLine("/// Returns the <see cref=\"SyntaxKind\"/> for a given keyword or <see cref=\"SyntaxKind.IdentifierName\"/> if not a keyword."); writer.WriteLine("/// </summary>"); }
/// <summary> /// Generates the specified writer. /// </summary> /// <param name="writer">The writer.</param> public void Generate(SourceWriter writer) { string cppTypename = GetTypename(); GenerateType(writer, cppTypename); }
private static void EditorBrowsableStateNever(SourceWriter source, int indentation) { source .Indent(indentation) .WriteLine("<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> _"); }
public GlobalMembersVisitor(SourceWriter output, Dictionary<string, object> globalSymbols, NullBehaviour nullBehaviour) { _source = output; _globalSymbols = globalSymbols; _nullBehaviour = nullBehaviour; }
public override void GenerateSourceCode(IEnumerable <IList <Chunk> > viewTemplates, IEnumerable <IList <Chunk> > allResources) { var globalSymbols = new Dictionary <string, object>(); var writer = new StringWriter(); var source = new SourceWriter(writer); // debug symbols not adjusted until the matching-directive issue resolved source.AdjustDebugSymbols = false; var usingGenerator = new UsingNamespaceVisitor(source); var baseClassGenerator = new BaseClassVisitor { BaseClass = BaseClass }; var globalsGenerator = new GlobalMembersVisitor(source, globalSymbols, NullBehaviour); // needed for proper vb functionality source.WriteLine("Option Infer On"); usingGenerator.UsingNamespace("Microsoft.VisualBasic"); foreach (var ns in UseNamespaces ?? new string[0]) { usingGenerator.UsingNamespace(ns); } usingGenerator.UsingAssembly("Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); foreach (var assembly in UseAssemblies ?? new string[0]) { usingGenerator.UsingAssembly(assembly); } foreach (var resource in allResources) { usingGenerator.Accept(resource); } foreach (var resource in allResources) { baseClassGenerator.Accept(resource); } var viewClassName = "View" + GeneratedViewId.ToString("n"); if (string.IsNullOrEmpty(TargetNamespace)) { ViewClassFullName = viewClassName; } else { ViewClassFullName = TargetNamespace + "." + viewClassName; source.WriteLine(); source.WriteLine(string.Format("Namespace {0}", TargetNamespace)); } source.WriteLine(); if (Descriptor != null) { // [SparkView] attribute source.WriteLine("<Global.Spark.SparkViewAttribute( _"); if (TargetNamespace != null) { source.WriteFormat(" TargetNamespace:=\"{0}\", _", TargetNamespace).WriteLine(); } source.WriteLine(" Templates := New String() { _"); source.Write(" ").Write(string.Join(", _\r\n ", Descriptor.Templates.Select( t => "\"" + t + "\"").ToArray())); source.WriteLine(" })> _"); } // public class ViewName : BasePageType source .Write("Public Class ") .WriteLine(viewClassName) .Write(" Inherits ") .WriteLine(baseClassGenerator.BaseClassTypeName) .AddIndent(); source.WriteLine(); source.WriteLine(string.Format(" Private Shared ReadOnly _generatedViewId As Global.System.Guid = New Global.System.Guid(\"{0:n}\")", GeneratedViewId)); source .WriteLine(" Public Overrides ReadOnly Property GeneratedViewId() As Global.System.Guid") .WriteLine(" Get") .WriteLine(" Return _generatedViewId") .WriteLine(" End Get") .WriteLine(" End Property"); if (Descriptor != null && Descriptor.Accessors != null) { //TODO: correct this foreach (var accessor in Descriptor.Accessors) { source.WriteLine(); source.Write(" public ").WriteLine(accessor.Property); source.Write(" { get { return ").Write(accessor.GetValue).WriteLine("; } }"); } } // properties and macros foreach (var resource in allResources) { globalsGenerator.Accept(resource); } // public void RenderViewLevelx() int renderLevel = 0; foreach (var viewTemplate in viewTemplates) { source.WriteLine(); EditorBrowsableStateNever(source, 4); source .WriteLine("Private Sub RenderViewLevel{0}()", renderLevel) .AddIndent(); var viewGenerator = new GeneratedCodeVisitor(source, globalSymbols, NullBehaviour); viewGenerator.Accept(viewTemplate); source .RemoveIndent() .WriteLine("End Sub"); ++renderLevel; } // public void RenderView() source.WriteLine(); EditorBrowsableStateNever(source, 4); source .WriteLine("Public Overrides Sub Render()") .AddIndent(); for (var invokeLevel = 0; invokeLevel != renderLevel; ++invokeLevel) { if (invokeLevel != renderLevel - 1) { source .WriteLine("Using OutputScope()") .AddIndent() .WriteLine("RenderViewLevel{0}()", invokeLevel) .WriteLine("Content(\"view\") = Output") .RemoveIndent() .WriteLine("End Using"); } else { source .WriteLine("RenderViewLevel{0}()", invokeLevel); } } source .RemoveIndent() .WriteLine("End Sub"); source .RemoveIndent() .WriteLine("End Class"); if (!string.IsNullOrEmpty(TargetNamespace)) { source.WriteLine("End Namespace"); } SourceCode = source.ToString(); SourceMappings = source.Mappings; }
public override void GenerateSourceCode(IEnumerable<IList<Chunk>> viewTemplates, IEnumerable<IList<Chunk>> allResources) { var globalSymbols = new Dictionary<string, object>(); var writer = new StringWriter(); var source = new SourceWriter(writer); var usingGenerator = new UsingNamespaceVisitor(source); var baseClassGenerator = new BaseClassVisitor { BaseClass = BaseClass }; var globalsGenerator = new GlobalMembersVisitor(source, globalSymbols, NullBehaviour); var globalsImplementationGenerator = new GlobalMembersImplementationVisitor(source, globalSymbols, NullBehaviour); if (string.IsNullOrEmpty(TargetNamespace)) { source.WriteLine("namespace ;"); } else { source.WriteLine(string.Format("namespace {0};", TargetNamespace)); } source.WriteLine("interface"); // using <namespaces>; if (UseNamespaces != null) { foreach (var ns in UseNamespaces ?? new string[0]) { usingGenerator.UsingNamespace(ns); } if (usingGenerator._namespaceAdded.Count > 0) { source.Write(";").WriteLine(""); } } //foreach (var ns in UseNamespaces ?? new string[0]) //{ // usingGenerator.UsingNamespace(ns); //} foreach (var assembly in UseAssemblies ?? new string[0]) { usingGenerator.UsingAssembly(assembly); } foreach (var resource in allResources) { usingGenerator.Accept(resource); } foreach (var resource in allResources) { baseClassGenerator.Accept(resource); } var viewClassName = "View" + GeneratedViewId.ToString("n"); if (string.IsNullOrEmpty(TargetNamespace)) { ViewClassFullName = viewClassName; } else { ViewClassFullName = TargetNamespace + "." + viewClassName; //source // .WriteLine() // .WriteLine(string.Format("namespace {0}", TargetNamespace)) // .WriteLine("{").AddIndent(); } source.WriteLine(); var descriptorText = new StringBuilder(); if (Descriptor != null) { // [SparkView] attribute descriptorText.Append("[Spark.SparkViewAttribute("); if (TargetNamespace != null) descriptorText.Append(String.Format(" TargetNamespace:=\"{0}\",", TargetNamespace)); descriptorText.Append(" Templates := array of System.String (["); descriptorText.Append(" "); descriptorText.Append(string.Join(",\r\n ", Descriptor.Templates.Select( //t => "\"" + t.Replace("\\", "\\\\") + "\"").ToArray())); t => "'" + t+ "'").ToArray())); descriptorText.Append(" ]))]"); } // public class ViewName : BasePageType source .WriteLine("type ") .WriteLine(descriptorText.ToString()) .Write(viewClassName) .Write(" = public class (") .WriteCode(baseClassGenerator.BaseClassTypeName) .Write(")") .WriteLine(); source.WriteLine(); source.WriteLine("private class var "); EditorBrowsableStateNever(source, 4); source.WriteLine("_generatedViewId : System.Guid := new System.Guid('{0:n}');", GeneratedViewId); source.WriteLine("public property GeneratedViewId : System.Guid "); source.WriteLine("read _generatedViewId; override;"); if (Descriptor != null && Descriptor.Accessors != null) { foreach (var accessor in Descriptor.Accessors) { source.WriteLine(); source.Write("public ").WriteLine(accessor.Property); source.Write("{ get { return ").Write(accessor.GetValue).WriteLine("; } }"); } } // properties and macros // Note: macros are methods, implementation is delegated to later on... foreach (var resource in allResources) { globalsGenerator.Accept(resource); } // public void RenderViewLevelx() int renderLevel = 0; foreach (var viewTemplate in viewTemplates) { source.WriteLine(); source.WriteLine("public"); EditorBrowsableStateNever(source, 4); source.WriteLine(string.Format("method RenderViewLevel{0};", renderLevel)); ++renderLevel; } // public void RenderView() source.WriteLine(); source.WriteLine("public"); EditorBrowsableStateNever(source, 4); source.WriteLine("method Render; override;"); source.WriteLine(); source.WriteLine("end;"); source.WriteLine(""); source.WriteLine("implementation"); globalsImplementationGenerator.ViewClassName = viewClassName; foreach (var resource in allResources) { globalsImplementationGenerator.Accept(resource); } // public void RenderViewLevelx() renderLevel = 0; foreach (var viewTemplate in viewTemplates) { source.WriteLine(); source.WriteLine(string.Format("method {0}.RenderViewLevel{1}();", viewClassName, renderLevel)); source.WriteLine("begin").AddIndent(); var viewGenerator = new GeneratedCodeVisitor(source, globalSymbols, NullBehaviour); viewGenerator.Accept(viewTemplate); source.RemoveIndent().WriteLine("end;"); ++renderLevel; } // public void RenderView() source.WriteLine(); source.WriteLine(string.Format("method {0}.Render();", viewClassName)); source.WriteLine("begin").AddIndent(); for (var invokeLevel = 0; invokeLevel != renderLevel; ++invokeLevel) { if (invokeLevel != renderLevel - 1) { source.WriteLine("using OutputScope do begin RenderViewLevel{0}(); Content['view'] := Output; end;", invokeLevel); } else { source.WriteLine(" RenderViewLevel{0};", invokeLevel); } } source.RemoveIndent().WriteLine("end;"); // end class source.WriteLine("end."); SourceCode = source.ToString(); SourceMappings = source.Mappings; }
public override void GenerateSourceCode(IEnumerable<IList<Chunk>> viewTemplates, IEnumerable<IList<Chunk>> allResources) { var globalSymbols = new Dictionary<string, object>(); var writer = new StringWriter(); var source = new SourceWriter(writer); // debug symbols not adjusted until the matching-directive issue resolved source.AdjustDebugSymbols = false; var usingGenerator = new UsingNamespaceVisitor(source); var baseClassGenerator = new BaseClassVisitor { BaseClass = BaseClass }; var globalsGenerator = new GlobalMembersVisitor(source, globalSymbols, NullBehaviour); // needed for proper vb functionality source.WriteLine("Option Infer On"); usingGenerator.UsingNamespace("Microsoft.VisualBasic"); foreach (var ns in UseNamespaces ?? new string[0]) usingGenerator.UsingNamespace(ns); usingGenerator.UsingAssembly("Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); foreach (var assembly in UseAssemblies ?? new string[0]) usingGenerator.UsingAssembly(assembly); foreach (var resource in allResources) usingGenerator.Accept(resource); foreach (var resource in allResources) baseClassGenerator.Accept(resource); var viewClassName = "View" + GeneratedViewId.ToString("n"); if (string.IsNullOrEmpty(TargetNamespace)) { ViewClassFullName = viewClassName; } else { ViewClassFullName = TargetNamespace + "." + viewClassName; source.WriteLine(); source.WriteLine(string.Format("Namespace {0}", TargetNamespace)); } source.WriteLine(); if (Descriptor != null) { // [SparkView] attribute source.WriteLine("<Global.Spark.SparkViewAttribute( _"); if (TargetNamespace != null) source.WriteFormat(" TargetNamespace:=\"{0}\", _", TargetNamespace).WriteLine(); source.WriteLine(" Templates := New String() { _"); source.Write(" ").Write(string.Join(", _\r\n ", Descriptor.Templates.Select(t => "\"" + SparkViewAttribute.ConvertToAttributeFormat(t) + "\"").ToArray())); source.WriteLine(" })> _"); } // public class ViewName : BasePageType source .Write("Public Class ") .WriteLine(viewClassName) .Write(" Inherits ") .WriteLine(baseClassGenerator.BaseClassTypeName) .AddIndent(); source.WriteLine(); source.WriteLine(string.Format(" Private Shared ReadOnly _generatedViewId As Global.System.Guid = New Global.System.Guid(\"{0:n}\")", GeneratedViewId)); source .WriteLine(" Public Overrides ReadOnly Property GeneratedViewId() As Global.System.Guid") .WriteLine(" Get") .WriteLine(" Return _generatedViewId") .WriteLine(" End Get") .WriteLine(" End Property"); if (Descriptor != null && Descriptor.Accessors != null) { //TODO: correct this foreach (var accessor in Descriptor.Accessors) { source.WriteLine(); source.Write(" public ").WriteLine(accessor.Property); source.Write(" { get { return ").Write(accessor.GetValue).WriteLine("; } }"); } } // properties and macros foreach (var resource in allResources) globalsGenerator.Accept(resource); // public void RenderViewLevelx() int renderLevel = 0; foreach (var viewTemplate in viewTemplates) { source.WriteLine(); EditorBrowsableStateNever(source, 4); source .WriteLine("Private Sub RenderViewLevel{0}()", renderLevel) .AddIndent(); var viewGenerator = new GeneratedCodeVisitor(source, globalSymbols, NullBehaviour); viewGenerator.Accept(viewTemplate); source .RemoveIndent() .WriteLine("End Sub"); ++renderLevel; } // public void RenderView() source.WriteLine(); EditorBrowsableStateNever(source, 4); source .WriteLine("Public Overrides Sub Render()") .AddIndent(); for (var invokeLevel = 0; invokeLevel != renderLevel; ++invokeLevel) { if (invokeLevel != renderLevel - 1) { source .WriteLine("Using OutputScope()") .AddIndent() .WriteLine("RenderViewLevel{0}()", invokeLevel) .WriteLine("Content(\"view\") = Output") .RemoveIndent() .WriteLine("End Using"); } else { source .WriteLine("RenderViewLevel{0}()", invokeLevel); } } source .RemoveIndent() .WriteLine("End Sub"); source .RemoveIndent() .WriteLine("End Class"); if (!string.IsNullOrEmpty(TargetNamespace)) { source.WriteLine("End Namespace"); } SourceCode = source.ToString(); SourceMappings = source.Mappings; }
/// <summary> /// Writes the field. /// </summary> /// <param name="writer">The writer.</param> /// <param name="fieldName">Name of the field.</param> /// <param name="translatedType">Type of the translated.</param> protected void WriteField(SourceWriter writer, string fieldName, string translatedType) { fieldName = ConfigOptions.GetFieldName(fieldName); writer.WriteLine("{0} {1};", translatedType, fieldName); }
public NodeCompiler(SourceWriter writer) : base(writer) { }
public void Dump(SourceWriter sb) { Dump(sb, 0); }
public virtual void Dump(SourceWriter sw, int indentChange) { }
public override void GenerateSourceCode(IEnumerable<IList<Chunk>> viewTemplates, IEnumerable<IList<Chunk>> allResources) { var globalSymbols = new Dictionary<string, object>(); var writer = new StringWriter(); var source = new SourceWriter(writer); var usingGenerator = new UsingNamespaceVisitor(source); var baseClassGenerator = new BaseClassVisitor { BaseClass = BaseClass }; var globalsGenerator = new GlobalMembersVisitor(source, globalSymbols, NullBehaviour); // using <namespaces>; foreach (var ns in UseNamespaces ?? new string[0]) usingGenerator.UsingNamespace(ns); foreach (var assembly in UseAssemblies ?? new string[0]) usingGenerator.UsingAssembly(assembly); foreach (var resource in allResources) usingGenerator.Accept(resource); foreach (var resource in allResources) baseClassGenerator.Accept(resource); var viewClassName = "View" + GeneratedViewId.ToString("n"); if (string.IsNullOrEmpty(TargetNamespace)) { ViewClassFullName = viewClassName; } else { ViewClassFullName = TargetNamespace + "." + viewClassName; source .WriteLine() .WriteLine(string.Format("namespace {0}", TargetNamespace)) .WriteLine("{").AddIndent(); } source.WriteLine(); if (Descriptor != null) { // [SparkView] attribute source.WriteLine("[global::Spark.SparkViewAttribute("); if (TargetNamespace != null) source.WriteFormat(" TargetNamespace=\"{0}\",", TargetNamespace).WriteLine(); source.WriteLine(" Templates = new string[] {"); source.Write(" ").WriteLine(string.Join(",\r\n ", Descriptor.Templates.Select( t => "\"" + t.Replace("\\", "\\\\") + "\"").ToArray())); source.WriteLine(" })]"); } // public class ViewName : BasePageType source .Write("public class ") .Write(viewClassName) .Write(" : ") .WriteCode(baseClassGenerator.BaseClassTypeName) .WriteLine(); source.WriteLine("{").AddIndent(); source.WriteLine(); EditorBrowsableStateNever(source, 4); source.WriteLine("private static System.Guid _generatedViewId = new System.Guid(\"{0:n}\");", GeneratedViewId); source.WriteLine("public override System.Guid GeneratedViewId"); source.WriteLine("{ get { return _generatedViewId; } }"); if (Descriptor != null && Descriptor.Accessors != null) { foreach (var accessor in Descriptor.Accessors) { source.WriteLine(); source.Write("public ").WriteLine(accessor.Property); source.Write("{ get { return ").Write(accessor.GetValue).WriteLine("; } }"); } } // properties and macros foreach (var resource in allResources) globalsGenerator.Accept(resource); // public void RenderViewLevelx() int renderLevel = 0; foreach (var viewTemplate in viewTemplates) { source.WriteLine(); EditorBrowsableStateNever(source, 4); source.WriteLine(string.Format("private void RenderViewLevel{0}()", renderLevel)); source.WriteLine("{").AddIndent(); var viewGenerator = new GeneratedCodeVisitor(source, globalSymbols, NullBehaviour); viewGenerator.Accept(viewTemplate); source.RemoveIndent().WriteLine("}"); ++renderLevel; } // public void RenderView() source.WriteLine(); EditorBrowsableStateNever(source, 4); source.WriteLine("public override void Render()"); source.WriteLine("{").AddIndent(); for (var invokeLevel = 0; invokeLevel != renderLevel; ++invokeLevel) { if (invokeLevel != renderLevel - 1) { source.WriteLine("using (OutputScope()) {{RenderViewLevel{0}(); Content[\"view\"] = Output;}}", invokeLevel); } else { source.WriteLine(" RenderViewLevel{0}();", invokeLevel); } } source.RemoveIndent().WriteLine("}"); // end class source.RemoveIndent().WriteLine("}"); if (!string.IsNullOrEmpty(TargetNamespace)) { source.RemoveIndent().WriteLine("}"); } SourceCode = source.ToString(); SourceMappings = source.Mappings; }
public override void Dump(SourceWriter sw, int indentChange) { sw.Write(TypeManager.GetCSharpName(Type)); }