@@ -24,33 +24,66 @@ struct Compiler {
2424
2525/// Compile a given sourcecode into a bytecode object.
2626pub fn compile ( source : & str , mode : & Mode , source_path : String ) -> Result < CodeObject , CompileError > {
27- let mut compiler = Compiler :: new ( ) ;
28- compiler. source_path = Some ( source_path) ;
29- compiler. push_new_code_object ( "<module>" . to_string ( ) ) ;
30-
3127 match mode {
3228 Mode :: Exec => {
3329 let ast = parser:: parse_program ( source) ?;
34- let symbol_table = make_symbol_table ( & ast) ?;
35- compiler. compile_program ( & ast, symbol_table)
30+ compile_program ( ast, source_path)
3631 }
3732 Mode :: Eval => {
3833 let statement = parser:: parse_statement ( source) ?;
39- let symbol_table = statements_to_symbol_table ( & statement) ?;
40- compiler. compile_statement_eval ( & statement, symbol_table)
34+ compile_statement_eval ( statement, source_path)
4135 }
4236 Mode :: Single => {
4337 let ast = parser:: parse_program ( source) ?;
44- let symbol_table = make_symbol_table ( & ast) ?;
45- compiler. compile_program_single ( & ast, symbol_table)
38+ compile_program_single ( ast, source_path)
4639 }
47- } ?;
40+ }
41+ }
4842
43+ /// A helper function for the shared code of the different compile functions
44+ fn with_compiler (
45+ source_path : String ,
46+ f : impl FnOnce ( & mut Compiler ) -> Result < ( ) , CompileError > ,
47+ ) -> Result < CodeObject , CompileError > {
48+ let mut compiler = Compiler :: new ( ) ;
49+ compiler. source_path = Some ( source_path) ;
50+ compiler. push_new_code_object ( "<module>" . to_string ( ) ) ;
51+ f ( & mut compiler) ?;
4952 let code = compiler. pop_code_object ( ) ;
5053 trace ! ( "Compilation completed: {:?}" , code) ;
5154 Ok ( code)
5255}
5356
57+ /// Compile a standard Python program to bytecode
58+ pub fn compile_program ( ast : ast:: Program , source_path : String ) -> Result < CodeObject , CompileError > {
59+ with_compiler ( source_path, |compiler| {
60+ let symbol_table = make_symbol_table ( & ast) ?;
61+ compiler. compile_program ( & ast, symbol_table)
62+ } )
63+ }
64+
65+ /// Compile a single Python expression to bytecode
66+ pub fn compile_statement_eval (
67+ statement : Vec < ast:: LocatedStatement > ,
68+ source_path : String ,
69+ ) -> Result < CodeObject , CompileError > {
70+ with_compiler ( source_path, |compiler| {
71+ let symbol_table = statements_to_symbol_table ( & statement) ?;
72+ compiler. compile_statement_eval ( & statement, symbol_table)
73+ } )
74+ }
75+
76+ /// Compile a Python program to bytecode for the context of a REPL
77+ pub fn compile_program_single (
78+ ast : ast:: Program ,
79+ source_path : String ,
80+ ) -> Result < CodeObject , CompileError > {
81+ with_compiler ( source_path, |compiler| {
82+ let symbol_table = make_symbol_table ( & ast) ?;
83+ compiler. compile_program_single ( & ast, symbol_table)
84+ } )
85+ }
86+
5487pub enum Mode {
5588 Exec ,
5689 Eval ,
0 commit comments