Created
September 2, 2020 14:15
-
-
Save kevinw/87b8f8322a09760ba85b1031e7225f2b to your computer and use it in GitHub Desktop.
trying out a jai macro for printing locals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "Basic"; | |
#import "Compiler"; | |
main :: () { | |
foo := 42; | |
bar := "meep"; | |
baz := false; | |
print_locals(#code (foo, bar, baz)); | |
/* | |
This prints the following output: | |
foo: 42 | |
bar: meep | |
baz: false | |
*/ | |
} | |
print_locals :: (code: Code) #expand { | |
generate_print_statements :: (code: Code) -> Code { | |
root, expressions := compiler_get_nodes(code); | |
// Collect all the idents. | |
idents: [..]string; | |
for expressions | |
if it.kind == .IDENT | |
array_add(*idents, (cast(*Code_Ident)it).name); | |
// For each one, make a print statement. | |
statements := NewArray(idents.count, *Code_Node); | |
for idents { | |
proc_call := New(Code_Procedure_Call); | |
proc_call.kind = .PROCEDURE_CALL; | |
proc_call.procedure_expression = New_Ident("print"); | |
arguments_unsorted: [..]Code_Argument; | |
array_add(*arguments_unsorted, | |
make_Code_Argument(make_string_literal(tprint("%: %%\n", it))), | |
make_Code_Argument(New_Ident(it, Code_Ident.HAS_SCOPE_MODIFIER)) | |
); | |
proc_call.arguments_unsorted = arguments_unsorted; | |
arguments_sorted: [..]*Code_Node; | |
for arguments_unsorted | |
array_add(*arguments_sorted, it.expression); | |
proc_call.arguments_sorted = arguments_sorted; | |
statements[it_index] = proc_call; | |
} | |
block := New(Code_Block); | |
block.kind = .BLOCK; | |
block.parent = null; | |
block.statements = statements; | |
block.block_type = Code_Block.Block_Type.IMPERATIVE; | |
return compiler_get_code(block); | |
} | |
#insert_internal #run generate_print_statements(code); | |
} | |
make_Code_Argument :: (expression: *Code_Node, name: *Code_Ident = null) -> Code_Argument { | |
arg: Code_Argument; | |
arg.expression = expression; | |
arg.name = name; | |
return arg; | |
} | |
New_Ident :: (name: string, flags: u32 = 0) -> *Code_Ident { | |
ident := New(Code_Ident); | |
ident.kind = .IDENT; | |
ident.name = name; | |
ident.flags = flags; | |
return ident; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment