Subscribe to The Madman Scribblings        RSS Feed
-----

Template Functions?

Icon Leave Comment
Template Functions?

Currently
Generating code via Roslyn (const)
var constField = SyntaxFactory.FieldDeclaration(
                    SyntaxFactory.List<AttributeListSyntax>(),
                    SyntaxFactory.TokenList(SyntaxFactory.Token(visibility), SyntaxFactory.Token(SyntaxKind.ConstKeyword)),
                    SyntaxFactory.VariableDeclaration(SyntaxFactoryExt.Types.String,
                        SyntaxFactory.SeparatedList<VariableDeclaratorSyntax>()
                            .Add(SyntaxFactory
                                .VariableDeclarator(name)
                                .WithInitializer(
                                    SyntaxFactory.EqualsValueClause(
                                        SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(value))))
                            )));



Concept

Now if we had a basic form of templating for code generation. Some of the above could now be written like.
template function [Const]<T>( name : String! , value : T ) : SyntaxNode<Lang>
{ 
  return Syntax<C#>.Create( $("const {$name} = {$value};") );
}



This would work along the same lines of how Iterator Function is auto-magically synthesize an iterator for you.
template function would generate the syntax code for that template.


template function [Dim](Of T)( id As String!, value : T) : SyntaxNode(Of VB)
{
 return Syntax<VB>.Create( $("Dim {$id} = {$value){\n}") )
}



Coding Pattern match

Now that we can easily generate code, why not also be able to pattern match it.
template function VB6_CodeSmell ( input : Syntax(OF VB) ) : Syntax(Of VB)
{
  var m  = Syntax(Of VB).CreateMatcher( S("Dim {$name} As {$type}{\n}{$name} = {$value}{\n}"))
  if( m == input )
  {
    var output = Syntax(Of VB).Create( $("Dim {$m("name")} As {$m("type")} = {$m("value")}{\n}")
    return output
  }
  else
  {
   return input
  }
}



template function SingleLine_IF( pred : Expr<Bool>, value : Syntax<C#> ): Syntax<C#>
{
  return Syntax<C#>.Create( $("if($pred) return {$value};") );
}

template function [IfElse]( pred : Expr<Bool>, true_expr : Syntax<C#>, false_expr : Syntax ) : Syntax<C#>
{
  return Syntax<C#>.Create($("if($pred){{$true_expr}} else {{ {$false_expr} }}"); 
}



You could also have inlining of LINQ expressions.
template function [Comment] ( Text : String! ) : Syntax<C#>
{
  return $("/* {$Text} */")(Syntax<C#>);
}


template function Any<T> ( source : Expr<ICollection<T>> , pred : Expr<T,Boolean> ) : Syntax<C#>
{
 return $("int _lim = {$ Source.Count };")(Syntax<C#>) + 
  $("for( int index = 0; index < _lim; index++ )")(Syntax<C#>) +
  $("{{")(Syntax<C#>) + [Comment]("Check the predicate")
  $("if( {$pred}(index) ) {{ return true; }}")(Syntax<C#>)
  $("}}")(Syntax<C#>) +
  $("return false;")(Syntax<C#>)
}

0 Comments On This Entry

 

Search My Blog

Recent Entries

Recent Comments