Ejemplo n.º 1
0
        protected override void Visit(MacroChunk chunk)
        {
            _source.Write(string.Format("\r\n    object {0}(", chunk.Name));
            string delimiter = "";

            foreach (var parameter in chunk.Parameters)
            {
                _source.Write(delimiter).WriteCode(parameter.Type).Write(" ").Write(parameter.Name);
                delimiter = ", ";
            }
            _source.WriteLine(")");
            CodeIndent(chunk).WriteLine("{");
            CodeHidden();
            _source.WriteLine("        using(OutputScope(new System.IO.StringWriter()))");
            _source.WriteLine("        {");
            CodeDefault();

            var variables = new Dictionary <string, object>();

            foreach (var param in chunk.Parameters)
            {
                variables.Add(param.Name, null);
            }
            var generator = new GeneratedCodeVisitor(_source, variables, _nullBehaviour);

            generator.Accept(chunk.Body);

            CodeHidden();
            _source.WriteLine("            return HTML(Output);");
            _source.WriteLine("        }");
            _source.WriteLine("    }");
            CodeDefault();
        }
Ejemplo n.º 2
0
        protected override void Visit(MacroChunk chunk)
        {
            _source.Write("def ").Write(chunk.Name).Write("(");
            string delimiter = "";

            foreach (var parameter in chunk.Parameters)
            {
                _source.Write(delimiter).Write(parameter.Name);
                delimiter = ",";
            }
            _source.WriteLine("):");
            _source.Indent++;
            foreach (var global in _globals.Keys)
            {
                _source.Write("global ").WriteLine(global);
            }
            var generator = new GeneratedCodeVisitor(_source, _globals);

            _source.WriteLine("__output__scope__=OutputScopeAdapter(None)");

            _source.WriteLine("try:");
            _source.Indent++;
            generator.Accept(chunk.Body);
            _source.WriteLine("return Output.ToString()");
            _source.Indent--;

            _source.WriteLine("finally:");
            _source.Indent++;
            _source.WriteLine("__output__scope__.Dispose()");
            _source.Indent--;

            _source.Indent--;
        }
Ejemplo n.º 3
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            sw.Write("{");

            var i = 0;

            foreach (var value in _values)
            {
                if (i++ != 0)
                {
                    sw.Write(",");
                }

                sw.Write(" ");

                DumpChild(value, sw);
            }

            if (i != 0)
            {
                sw.Write(" ");
            }

            sw.Write("}");
        }
        private static void GenerateGetKeywordKind(KindList kinds, SourceWriter writer)
        {
            var optimized = new OptimizedSwitch();

            foreach (var keyword in kinds.Keywords.OrderBy(kind => kind.Field.Name))
            {
                optimized.AddClause(keyword.TokenInfo !.Value.Text !, writer =>
                {
                    writer.Write("return SyntaxKind.");
                    writer.Write(keyword.Field.Name);
                    writer.WriteLine(';');
                });
            }
            optimized.DefaultBodyWriter = writer => writer.WriteLine("return SyntaxKind.IdentifierToken;");

            writeHeader(writer);
            using (writer.CurlyIndenter("public static SyntaxKind GetKeywordKind(String text)"))
            {
                optimized.Generate(writer, "text", false);
            }

            writer.WriteLine();
            writeHeader(writer);
            using (writer.CurlyIndenter("public static SyntaxKind GetKeywordKind(ReadOnlySpan<char> span)"))
            {
                optimized.Generate(writer, "span", true);
            }
Ejemplo n.º 5
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            base.Dump(sw, indentChange);

            if (_initializer != null)
            {
                DumpChild(_initializer, sw, indentChange);
            }
            else
            {
                sw.Write(" { ");

                int i = 0;
                foreach (var memberBinding in _memberBindings)
                {
                    if (i++ != 0)
                    {
                        sw.Write(", ");
                    }
                    DumpChild(memberBinding, sw, indentChange);
                }

                sw.Write(_memberBindings.Any() ? " }" : "}");
            }
        }
Ejemplo n.º 6
0
        protected override void Visit(MacroChunk chunk)
        {
            _source.Write("def ").Write(chunk.Name).Write("(");
            string delimiter = "";

            foreach (var parameter in chunk.Parameters)
            {
                _source.Write(delimiter).Write(parameter.Name);
                delimiter = ",";
            }
            _source.WriteLine(")");
            _source.Indent++;

            var generator = new GeneratedCodeVisitor(_source, _globals);

            _source.WriteLine("__output__scope__=output_scope");

            _source.WriteLine("begin");
            _source.Indent++;
            generator.Accept(chunk.Body);
            _source.WriteLine("return output.to_string");
            _source.Indent--;
            _source.WriteLine("ensure");
            _source.Indent++;
            _source.WriteLine("__output__scope__.dispose");
            _source.Indent--;
            _source.WriteLine("end");

            _source.Indent--;
            _source.WriteLine("end");
        }
Ejemplo n.º 7
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            sw.Write("from ");
            DumpChild(RangeVariable, sw, indentChange);
            sw.Write(" in");

            var initializerIsQuery = Initializer is QueryExpression;

            if (initializerIsQuery)
            {
                sw.WriteLine();
                sw.Indent += 4;
            }
            else
            {
                sw.Write(' ');
            }

            try
            {
                DumpChild(Initializer, sw, indentChange + 4);
            }
            finally
            {
                if (initializerIsQuery)
                {
                    sw.Indent -= 4;
                }
            }

            sw.WriteLine();
            DumpChild(Next, sw, indentChange);
        }
Ejemplo n.º 8
0
        public virtual void BeginHeaders()
        {
            headers.WriteLine();
            headers.WriteLine($"/** Class {Name}");
            headers.WriteLine($" *  Corresponding .NET Qualified Name: `{AssemblyQualifiedName}`");
            headers.WriteLine(" */");
            headers.Write($"@interface {Name} : {BaseTypeName}");
            var pcount = Protocols.Count;

            if (pcount > 0)
            {
                headers.Write(" <");
                for (int i = 0; i < pcount; i++)
                {
                    if (i > 0)
                    {
                        headers.Write(", ");
                    }
                    headers.Write(Protocols [i]);
                }
                headers.Write(">");
            }
            headers.WriteLine(" {");
            if (!IsStatic && !IsBaseTypeBound)
            {
                headers.Indent++;
                headers.WriteLine("@public MonoEmbedObject* _object;");
                headers.Indent--;
            }
            headers.WriteLine("}");
            headers.WriteLine();
        }
Ejemplo n.º 9
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            Expression.Dump(sw, indentChange);

            sw.Write(" ");
            sw.Write(Direction.ToString().ToLowerInvariant());
        }
Ejemplo n.º 10
0
 public override void Dump(SourceWriter sw, int indentChange)
 {
     Test.Dump(sw, indentChange);
     sw.Write(" ? ");
     IfTrue.Dump(sw, indentChange);
     sw.Write(" : ");
     IfFalse.Dump(sw, indentChange);
 }
Ejemplo n.º 11
0
 public override void Dump(SourceWriter sw, int indentChange)
 {
     DumpChild(Initializer, sw, indentChange);
     sw.Write(" into ");
     DumpChild(RangeVariable, sw, indentChange);
     sw.WriteLine();
     sw.Write(' ', Span.Start.Column - 1);
     DumpChild(Next, sw, indentChange);
 }
Ejemplo n.º 12
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            sw.Write("let ");
            DumpChild(RangeVariable, sw, indentChange);
            sw.Write(" = ");
            DumpChild(Initializer, sw, indentChange);

            sw.WriteLine();
            DumpChild(Next, sw, indentChange);
        }
Ejemplo n.º 13
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            sw.Write("group ");

            DumpChild(_projection, sw, indentChange);

            sw.Write(" by ");

            DumpChild(_discriminator, sw, indentChange);
        }
Ejemplo n.º 14
0
        public void indention_within_a_block()
        {
            var writer = new SourceWriter();

            writer.Write("BLOCK:public void Go()");
            writer.Write("var x = 0;");

            var lines = writer.Code().ReadLines().ToArray();

            lines[2].ShouldBe("    var x = 0;");
        }
Ejemplo n.º 15
0
        protected override void Visit(SendLiteralChunk chunk)
        {
            if (string.IsNullOrEmpty(chunk.Text))
            {
                return;
            }

            CodeHidden();
            _source.Write("Output.Write(\"").Write(EscapeStringContents(chunk.Text)).WriteLine("\");");
            CodeDefault();
        }
Ejemplo n.º 16
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            var elementType = ElementType;

            if (elementType != null)
            {
                elementType.Dump(sw, indentChange);
                sw.Write(" ");
            }

            sw.Write(VariableName);
        }
Ejemplo n.º 17
0
        public void multi_level_indention()
        {
            var writer = new SourceWriter();

            writer.Write("BLOCK:public void Go()");
            writer.Write("BLOCK:try");
            writer.Write("var x = 0;");

            var lines = writer.Code().ReadLines().ToArray();

            lines[4].ShouldBe("        var x = 0;");
        }
Ejemplo n.º 18
0
        public void end_block()
        {
            var writer = new SourceWriter();

            writer.Write("BLOCK:public void Go()");
            writer.Write("var x = 0;");
            writer.Write("END");

            var lines = writer.Code().ReadLines().ToArray();

            lines[3].ShouldBe("}");
        }
Ejemplo n.º 19
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            var type = Type;

            if (type != null)
            {
                type.Dump(sw, indentChange);
                sw.Write(" ");
            }

            sw.Write(Name);
        }
Ejemplo n.º 20
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            var parenthesize = !_target.IsPrimaryExpression;

            if (parenthesize)
            {
                sw.Write("(");
            }

            _target.Dump(sw, indentChange);

            if (parenthesize)
            {
                sw.Write(")");
            }

            sw.Write(".");
            sw.Write(Method != null ? Method.Name : MethodName);

            if (_typeArguments.Count != 0)
            {
                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(">");
            }

            sw.Write("(");

            for (var i = 0; i < _arguments.Count; i++)
            {
                var argument = _arguments[i];

                if (i != 0)
                {
                    sw.Write(", ");
                }

                argument.Dump(sw, indentChange);
            }

            sw.Write(")");
        }
Ejemplo n.º 21
0
 public override void Dump(SourceWriter sw, int indentChange)
 {
     sw.Write("{ ");
     for (var i = 0; i < Arguments.Count; i++)
     {
         if (i != 0)
         {
             sw.Write(", ");
         }
         DumpChild(Arguments[i], sw, indentChange);
     }
     sw.Write(" }");
 }
Ejemplo n.º 22
0
 public override void Dump(SourceWriter sw, int indentChange)
 {
     if (IsImplicitConversionRequired)
     {
         DumpChild(_operand, sw, indentChange);
     }
     else
     {
         sw.Write("(");
         DumpChild(_targetType, sw, indentChange);
         sw.Write(")");
     }
 }
Ejemplo n.º 23
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            if (IsStatic)
            {
                sw.Write(TypeManager.GetCSharpName(_containerType));
            }
            else
            {
                DumpChild(InstanceExpression, sw, indentChange);
            }

            sw.Write(".");
            sw.Write(_fieldInfo.Name);
        }
Ejemplo n.º 24
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            var name = Name;

            if (IsBuiltinType)
            {
                var builtinType = TypeManager.GetClrTypeFromBuiltinType(
                    (BuiltinType)Enum.Parse(typeof(BuiltinType),
                                            Name));

                if (builtinType != null)
                {
                    name = TypeManager.GetCSharpName(builtinType);
                }
            }

            sw.Write(name);

            if (!HasTypeArguments && !IsGenericTypeDefinition)
            {
                return;
            }

            sw.Write("<");

            if (IsGenericTypeDefinition)
            {
                for (int i = 0; i < GenericArity - 1; i++)
                {
                    sw.Write(",");
                }
            }
            else
            {
                for (int i = 0; i < TypeArguments.Count; i++)
                {
                    var typeArgument = TypeArguments[i];

                    if (i != 0)
                    {
                        sw.Write(", ");
                    }

                    typeArgument.Dump(sw, indentChange);
                }
            }

            sw.Write(">");
        }
Ejemplo n.º 25
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            sw.Write("join ");
            DumpChild(_variableName, sw, indentChange);
            sw.Write(" in ");
            DumpChild(_initializer, sw, indentChange);
            sw.Write(" on ");
            DumpChild(_leftKey, sw, indentChange);
            sw.Write(" equals ");
            DumpChild(_rightKey, sw, indentChange);

            sw.WriteLine();
            sw.Write(' ', Span.Start.Column - 1);
            DumpChild(_body, sw, indentChange);
        }
        void GenerateEnum(ProcessedType type)
        {
            Type t               = type.Type;
            var  managed_name    = type.ObjCName;
            var  underlying_type = t.GetEnumUnderlyingType();
            var  base_type       = NameGenerator.GetTypeName(underlying_type);

            // it's nicer to expose flags as unsigned integers - but .NET defaults to `int`
            bool flags = t.HasCustomAttribute("System", "FlagsAttribute");

            if (flags)
            {
                switch (Type.GetTypeCode(underlying_type))
                {
                case TypeCode.SByte:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                    base_type = "unsigned " + base_type;
                    break;
                }
            }

            var macro = flags ? "NS_OPTIONS" : "NS_ENUM";

            headers.WriteLine($"/** Enumeration {managed_name}");
            headers.WriteLine($" *  Corresponding .NET Qualified Name: `{t.AssemblyQualifiedName}`");
            headers.WriteLine(" */");
            headers.WriteLine($"typedef {macro}({base_type}, {managed_name}) {{");
            headers.Indent++;
            foreach (var name in t.GetEnumNames())
            {
                var value = t.GetField(name).GetRawConstantValue();
                headers.Write($"{managed_name}{name} = ");
                if (flags)
                {
                    headers.Write($"0x{value:x}");
                }
                else
                {
                    headers.Write(value);
                }
                headers.WriteLine(',');
            }
            headers.Indent--;
            headers.WriteLine("};");
            headers.WriteLine();
        }
Ejemplo n.º 27
0
        public void GenerateDocumentStorage(SourceWriter writer)
        {
            var extraUpsertArguments = DuplicatedFields.Any()
                ? DuplicatedFields.Select(x => x.WithParameterCode()).Join("")
                : "";


            writer.Write(
                $@"
BLOCK:public class {DocumentType.Name
                    }Storage : IDocumentStorage
public Type DocumentType => typeof ({DocumentType.Name
                    });

BLOCK:public NpgsqlCommand UpsertCommand(object document, string json)
return UpsertCommand(({
                    DocumentType.Name
                    })document, json);
END

BLOCK:public NpgsqlCommand LoaderCommand(object id)
return new NpgsqlCommand(`select data from {
                    TableName
                    } where id = :id`).WithParameter(`id`, id);
END

BLOCK:public NpgsqlCommand DeleteCommandForId(object id)
return new NpgsqlCommand(`delete from {
                    TableName
                    } where id = :id`).WithParameter(`id`, id);
END

BLOCK:public NpgsqlCommand DeleteCommandForEntity(object entity)
return DeleteCommandForId((({
                    DocumentType.Name})entity).{IdMember.Name
                    });
END

BLOCK:public NpgsqlCommand LoadByArrayCommand<T>(T[] ids)
return new NpgsqlCommand(`select data from {
                    TableName
                    } where id = ANY(:ids)`).WithParameter(`ids`, ids);
END


// TODO: This wil need to get fancier later
BLOCK:public NpgsqlCommand UpsertCommand({
                    DocumentType.Name} document, string json)
return new NpgsqlCommand(`{UpsertName
                    }`)
    .AsSproc()
    .WithParameter(`id`, document.{IdMember.Name
                    })
    .WithJsonParameter(`doc`, json){extraUpsertArguments};
END

END

");
        }
Ejemplo n.º 28
0
        public override void Dump(SourceWriter sw, int indentChange)
        {
            var quote = (Type == TypeManager.CoreTypes.String);

            if (quote)
            {
                sw.Write("\"");
            }

            sw.Write(_value);

            if (quote)
            {
                sw.Write("\"");
            }
        }
Ejemplo n.º 29
0
        public void Dump(SourceWriter sw)
        {
            int i = 0;

            foreach (var argument in _arguments)
            {
                if (i++ != 0)
                {
                    sw.Write(", ");
                }
                if (argument is NamedArgument)
                {
                    sw.Write(((NamedArgument)argument).Name + ": ");
                }
                argument.Dump(sw);
            }
        }
Ejemplo n.º 30
0
        public void multi_end_blocks()
        {
            var writer = new SourceWriter();

            writer.Write("BLOCK:public void Go()");
            writer.Write("BLOCK:try");
            writer.Write("var x = 0;");
            writer.Write("END");
            writer.Write("END");

            var lines = writer.Code().ReadLines().ToArray();

            lines[5].ShouldBe("    }");

            // There's a line break between the blocks
            lines[7].ShouldBe("}");
        }
Ejemplo n.º 31
0
        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

");
        }
Ejemplo n.º 32
0
        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

");
        }
Ejemplo n.º 33
0
        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

");
        }
Ejemplo n.º 34
0
        public void GenerateDocumentStorage(SourceWriter writer)
        {
            writer.Write($@"
            BLOCK:public class {DocumentType.Name}Storage : IDocumentStorage
            public Type DocumentType => typeof ({DocumentType.Name});

            public string TableName {{ get; }} = `{TableName}`;

            BLOCK:public NpgsqlCommand UpsertCommand(object document, string json)
            return UpsertCommand(({DocumentType.Name})document, json);
            END

            BLOCK:public NpgsqlCommand LoaderCommand(object id)
            return new NpgsqlCommand(`select data from {TableName} where id = :id`).WithParameter(`id`, id);
            END

            BLOCK:public NpgsqlCommand DeleteCommandForId(object id)
            return new NpgsqlCommand(`delete from {TableName} where id = :id`).WithParameter(`id`, id);
            END

            BLOCK:public NpgsqlCommand DeleteCommandForEntity(object entity)
            return DeleteCommandForId((({DocumentType.Name})entity).{IdMember.Name});
            END

            BLOCK:public NpgsqlCommand LoadByArrayCommand<T>(T[] ids)
            return new NpgsqlCommand(`select data from {TableName} where id = ANY(:ids)`).WithParameter(`ids`, ids);
            END

            BLOCK:public NpgsqlCommand AnyCommand(QueryModel queryModel)
            return new DocumentQuery<{DocumentType.Name}>(`{TableName}`, queryModel).ToAnyCommand();
            END

            BLOCK:public NpgsqlCommand CountCommand(QueryModel queryModel)
            return new DocumentQuery<{DocumentType.Name}>(`{TableName}`, queryModel).ToCountCommand();
            END

            // TODO: This wil need to get fancier later
            BLOCK:public NpgsqlCommand UpsertCommand({DocumentType.Name} document, string json)
            return new NpgsqlCommand(`{UpsertName}`)
            .AsSproc()
            .WithParameter(`id`, document.{IdMember.Name})
            .WithJsonParameter(`doc`, json);
            END

            END

            ");
        }
Ejemplo n.º 35
0
        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;
        }
Ejemplo n.º 36
0
        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();
        }
Ejemplo n.º 37
0
        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;
        }
Ejemplo n.º 38
0
        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;
        }
Ejemplo n.º 39
0
        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();
        }