Skip to content

Instantly share code, notes, and snippets.

@bamboo
Created February 9, 2011 19:47
Show Gist options
  • Save bamboo/819133 to your computer and use it in GitHub Desktop.
Save bamboo/819133 to your computer and use it in GitHub Desktop.
Meta method expanding named arguments into property assignments.
import System
import Boo.Lang.Compiler
import Boo.Lang.Compiler.Ast
import Boo.Lang.Compiler.Services
import Boo.Lang.Environments
import Boo.Lang.Compiler.MetaProgramming
[meta]
def assign(e as MethodInvocationExpression):
"""
Expands named arguments into property/field assignments.
assign(foo(Bar: 42))
becomes:
@(tmp=foo(), tmp.Bar = 42, tmp)
"""
namedArgs = e.NamedArguments.ToArray()
e.NamedArguments.Clear()
tmp = ReferenceExpression(my(UniqueNameProvider).GetUniqueName("assign"))
result = [| @($tmp=$e) |]
for namedArg in namedArgs:
name = namedArg.First
arg = namedArg.Second
result.Arguments.Add([| $tmp.$name = $arg |])
result.Arguments.Add(tmp)
return result
preservingLexicalInfo:
code = [|
import System
class Foo:
public Bar = -1
def foo():
return Foo()
print assign(foo(Bar: 42)).Bar
|]
result = compile_(code, System.Reflection.Assembly.GetExecutingAssembly())
print result.CompileUnit.ToCodeString()
errors = result.Errors
if len(errors):
print errors.ToString(true)
else:
result.GeneratedAssembly.EntryPoint.Invoke(null, (null,))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment