Skip to content

Instantly share code, notes, and snippets.

@joseoliv
Last active November 20, 2019 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joseoliv/feb567b7f7ea96b22aa43d0d74852adf to your computer and use it in GitHub Desktop.
Save joseoliv/feb567b7f7ea96b22aa43d0d74852adf to your computer and use it in GitHub Desktop.
insertCode
package metaobjectTest
@doc{**
Annotation 'insertCode' can be used:
a) inside a prototype and outside any method or;
b) inside a method
In case a), it can use send message 'insert: strSlot, code'
to 'self' to add fields and methods to the current prototype.
'strSlot' is the signatures of the fields and methods, as a
string. 'code', the second parameter, is the full code to be
inserted. As an example, we can add a field 'count', initialized
to '0' in its declaration, and a method 'getCount' by putting
the annotation below outside any method:
@insertCode{*
insert: """
var Int count;
func getCount -> Int
""",
"""
var Int count = 0;
func getCount -> Int {
return count
}
""";
*}
In case b), just call 'insert:' with the code to be generated:
@insertCode{*
insert: "currentMethodName = \"" ++
env getCurrentMethod getName ++ "\";";
*}
Inside the 'insertCode' DSL, variables 'metaobject' and 'env'
can be used, as in this last example. See the description of
action_afti_dsa for more details
**}
object InsertCode
@insertCode{*
var Int n = 0;
for elem in [ "red", "green", "blue" ] {
var String s = " func " ++ elem ++ " -> Int; ";
insert: s, " func " ++ elem ++ " -> Int = " ++ n ++ ";" ++ '\n';
n = n + 1
}
*}
@insertCode{*
insert: """
var Int count;
func getCount -> Int
""",
"""
var Int count = 0;
func getCount -> Int {
return count
}
""";
*}
func run {
var currentMethodName = "";
@insertCode{*
insert: "currentMethodName = \"" ++
env getCurrentMethod getName ++ "\";";
*}
printexpr currentMethodName;
++count;
printexpr getCount;
assert red == 0 && green == 1 && blue == 2;
var Int fat12;
@insertCode{*
var p = 2;
for n in 3..12 {
p = p*n
}
insert: " fat12 = " ++ p ++ ";" ++ '\n';
*}
"The factorial of 12 is $fat12" println;
@insertCode{*
// print values returned by methods red, green, and blue
for elem in [ "red", "green", "blue" ] {
insert: "self " ++ elem ++ " println;" ++ '\n';
}
*}
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment