compile.c 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013-2020 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdbool.h>
  27. #include <stdint.h>
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include <assert.h>
  31. #include "py/scope.h"
  32. #include "py/emit.h"
  33. #include "py/compile.h"
  34. #include "py/runtime.h"
  35. #include "py/asmbase.h"
  36. #include "py/persistentcode.h"
  37. #if MICROPY_ENABLE_COMPILER
  38. // TODO need to mangle __attr names
  39. #define INVALID_LABEL (0xffff)
  40. typedef enum {
  41. // define rules with a compile function
  42. #define DEF_RULE(rule, comp, kind, ...) PN_##rule,
  43. #define DEF_RULE_NC(rule, kind, ...)
  44. #include "py/grammar.h"
  45. #undef DEF_RULE
  46. #undef DEF_RULE_NC
  47. PN_const_object, // special node for a constant, generic Python object
  48. // define rules without a compile function
  49. #define DEF_RULE(rule, comp, kind, ...)
  50. #define DEF_RULE_NC(rule, kind, ...) PN_##rule,
  51. #include "py/grammar.h"
  52. #undef DEF_RULE
  53. #undef DEF_RULE_NC
  54. } pn_kind_t;
  55. #define NEED_METHOD_TABLE MICROPY_EMIT_NATIVE
  56. #if NEED_METHOD_TABLE
  57. // we need a method table to do the lookup for the emitter functions
  58. #define EMIT(fun) (comp->emit_method_table->fun(comp->emit))
  59. #define EMIT_ARG(fun, ...) (comp->emit_method_table->fun(comp->emit, __VA_ARGS__))
  60. #define EMIT_LOAD_FAST(qst, local_num) (comp->emit_method_table->load_id.local(comp->emit, qst, local_num, MP_EMIT_IDOP_LOCAL_FAST))
  61. #define EMIT_LOAD_GLOBAL(qst) (comp->emit_method_table->load_id.global(comp->emit, qst, MP_EMIT_IDOP_GLOBAL_GLOBAL))
  62. #else
  63. // if we only have the bytecode emitter enabled then we can do a direct call to the functions
  64. #define EMIT(fun) (mp_emit_bc_##fun(comp->emit))
  65. #define EMIT_ARG(fun, ...) (mp_emit_bc_##fun(comp->emit, __VA_ARGS__))
  66. #define EMIT_LOAD_FAST(qst, local_num) (mp_emit_bc_load_local(comp->emit, qst, local_num, MP_EMIT_IDOP_LOCAL_FAST))
  67. #define EMIT_LOAD_GLOBAL(qst) (mp_emit_bc_load_global(comp->emit, qst, MP_EMIT_IDOP_GLOBAL_GLOBAL))
  68. #endif
  69. #if MICROPY_EMIT_NATIVE && MICROPY_DYNAMIC_COMPILER
  70. #define NATIVE_EMITTER(f) emit_native_table[mp_dynamic_compiler.native_arch]->emit_##f
  71. #define NATIVE_EMITTER_TABLE emit_native_table[mp_dynamic_compiler.native_arch]
  72. STATIC const emit_method_table_t *emit_native_table[] = {
  73. NULL,
  74. &emit_native_x86_method_table,
  75. &emit_native_x64_method_table,
  76. &emit_native_arm_method_table,
  77. &emit_native_thumb_method_table,
  78. &emit_native_thumb_method_table,
  79. &emit_native_thumb_method_table,
  80. &emit_native_thumb_method_table,
  81. &emit_native_thumb_method_table,
  82. &emit_native_xtensa_method_table,
  83. &emit_native_xtensawin_method_table,
  84. };
  85. #elif MICROPY_EMIT_NATIVE
  86. // define a macro to access external native emitter
  87. #if MICROPY_EMIT_X64
  88. #define NATIVE_EMITTER(f) emit_native_x64_##f
  89. #elif MICROPY_EMIT_X86
  90. #define NATIVE_EMITTER(f) emit_native_x86_##f
  91. #elif MICROPY_EMIT_THUMB
  92. #define NATIVE_EMITTER(f) emit_native_thumb_##f
  93. #elif MICROPY_EMIT_ARM
  94. #define NATIVE_EMITTER(f) emit_native_arm_##f
  95. #elif MICROPY_EMIT_XTENSA
  96. #define NATIVE_EMITTER(f) emit_native_xtensa_##f
  97. #elif MICROPY_EMIT_XTENSAWIN
  98. #define NATIVE_EMITTER(f) emit_native_xtensawin_##f
  99. #else
  100. #error "unknown native emitter"
  101. #endif
  102. #define NATIVE_EMITTER_TABLE &NATIVE_EMITTER(method_table)
  103. #endif
  104. #if MICROPY_EMIT_INLINE_ASM && MICROPY_DYNAMIC_COMPILER
  105. #define ASM_EMITTER(f) emit_asm_table[mp_dynamic_compiler.native_arch]->asm_##f
  106. #define ASM_EMITTER_TABLE emit_asm_table[mp_dynamic_compiler.native_arch]
  107. STATIC const emit_inline_asm_method_table_t *emit_asm_table[] = {
  108. NULL,
  109. NULL,
  110. NULL,
  111. &emit_inline_thumb_method_table,
  112. &emit_inline_thumb_method_table,
  113. &emit_inline_thumb_method_table,
  114. &emit_inline_thumb_method_table,
  115. &emit_inline_thumb_method_table,
  116. &emit_inline_thumb_method_table,
  117. &emit_inline_xtensa_method_table,
  118. NULL,
  119. };
  120. #elif MICROPY_EMIT_INLINE_ASM
  121. // define macros for inline assembler
  122. #if MICROPY_EMIT_INLINE_THUMB
  123. #define ASM_DECORATOR_QSTR MP_QSTR_asm_thumb
  124. #define ASM_EMITTER(f) emit_inline_thumb_##f
  125. #elif MICROPY_EMIT_INLINE_XTENSA
  126. #define ASM_DECORATOR_QSTR MP_QSTR_asm_xtensa
  127. #define ASM_EMITTER(f) emit_inline_xtensa_##f
  128. #else
  129. #error "unknown asm emitter"
  130. #endif
  131. #define ASM_EMITTER_TABLE &ASM_EMITTER(method_table)
  132. #endif
  133. #define EMIT_INLINE_ASM(fun) (comp->emit_inline_asm_method_table->fun(comp->emit_inline_asm))
  134. #define EMIT_INLINE_ASM_ARG(fun, ...) (comp->emit_inline_asm_method_table->fun(comp->emit_inline_asm, __VA_ARGS__))
  135. // elements in this struct are ordered to make it compact
  136. typedef struct _compiler_t {
  137. qstr source_file;
  138. uint8_t is_repl;
  139. uint8_t pass; // holds enum type pass_kind_t
  140. uint8_t have_star;
  141. // try to keep compiler clean from nlr
  142. mp_obj_t compile_error; // set to an exception object if there's an error
  143. size_t compile_error_line; // set to best guess of line of error
  144. uint next_label;
  145. uint16_t num_dict_params;
  146. uint16_t num_default_params;
  147. uint16_t break_label; // highest bit set indicates we are breaking out of a for loop
  148. uint16_t continue_label;
  149. uint16_t cur_except_level; // increased for SETUP_EXCEPT, SETUP_FINALLY; decreased for POP_BLOCK, POP_EXCEPT
  150. uint16_t break_continue_except_level;
  151. scope_t *scope_head;
  152. scope_t *scope_cur;
  153. emit_t *emit; // current emitter
  154. #if NEED_METHOD_TABLE
  155. const emit_method_table_t *emit_method_table; // current emit method table
  156. #endif
  157. #if MICROPY_EMIT_INLINE_ASM
  158. emit_inline_asm_t *emit_inline_asm; // current emitter for inline asm
  159. const emit_inline_asm_method_table_t *emit_inline_asm_method_table; // current emit method table for inline asm
  160. #endif
  161. } compiler_t;
  162. STATIC void compile_error_set_line(compiler_t *comp, mp_parse_node_t pn) {
  163. // if the line of the error is unknown then try to update it from the pn
  164. if (comp->compile_error_line == 0 && MP_PARSE_NODE_IS_STRUCT(pn)) {
  165. comp->compile_error_line = ((mp_parse_node_struct_t *)pn)->source_line;
  166. }
  167. }
  168. STATIC void compile_syntax_error(compiler_t *comp, mp_parse_node_t pn, mp_rom_error_text_t msg) {
  169. // only register the error if there has been no other error
  170. if (comp->compile_error == MP_OBJ_NULL) {
  171. comp->compile_error = mp_obj_new_exception_msg(&mp_type_SyntaxError, msg);
  172. compile_error_set_line(comp, pn);
  173. }
  174. }
  175. STATIC void compile_trailer_paren_helper(compiler_t *comp, mp_parse_node_t pn_arglist, bool is_method_call, int n_positional_extra);
  176. STATIC void compile_comprehension(compiler_t *comp, mp_parse_node_struct_t *pns, scope_kind_t kind);
  177. STATIC void compile_atom_brace_helper(compiler_t *comp, mp_parse_node_struct_t *pns, bool create_map);
  178. STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn);
  179. STATIC uint comp_next_label(compiler_t *comp) {
  180. return comp->next_label++;
  181. }
  182. #if MICROPY_EMIT_NATIVE
  183. STATIC void reserve_labels_for_native(compiler_t *comp, int n) {
  184. if (comp->scope_cur->emit_options != MP_EMIT_OPT_BYTECODE) {
  185. comp->next_label += n;
  186. }
  187. }
  188. #else
  189. #define reserve_labels_for_native(comp, n)
  190. #endif
  191. STATIC void compile_increase_except_level(compiler_t *comp, uint label, int kind) {
  192. EMIT_ARG(setup_block, label, kind);
  193. comp->cur_except_level += 1;
  194. if (comp->cur_except_level > comp->scope_cur->exc_stack_size) {
  195. comp->scope_cur->exc_stack_size = comp->cur_except_level;
  196. }
  197. }
  198. STATIC void compile_decrease_except_level(compiler_t *comp) {
  199. assert(comp->cur_except_level > 0);
  200. comp->cur_except_level -= 1;
  201. EMIT(end_finally);
  202. reserve_labels_for_native(comp, 1);
  203. }
  204. STATIC scope_t *scope_new_and_link(compiler_t *comp, scope_kind_t kind, mp_parse_node_t pn, uint emit_options) {
  205. scope_t *scope = scope_new(kind, pn, comp->source_file, emit_options);
  206. scope->parent = comp->scope_cur;
  207. scope->next = NULL;
  208. if (comp->scope_head == NULL) {
  209. comp->scope_head = scope;
  210. } else {
  211. scope_t *s = comp->scope_head;
  212. while (s->next != NULL) {
  213. s = s->next;
  214. }
  215. s->next = scope;
  216. }
  217. return scope;
  218. }
  219. typedef void (*apply_list_fun_t)(compiler_t *comp, mp_parse_node_t pn);
  220. STATIC void apply_to_single_or_list(compiler_t *comp, mp_parse_node_t pn, pn_kind_t pn_list_kind, apply_list_fun_t f) {
  221. if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, pn_list_kind)) {
  222. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  223. int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  224. for (int i = 0; i < num_nodes; i++) {
  225. f(comp, pns->nodes[i]);
  226. }
  227. } else if (!MP_PARSE_NODE_IS_NULL(pn)) {
  228. f(comp, pn);
  229. }
  230. }
  231. STATIC void compile_generic_all_nodes(compiler_t *comp, mp_parse_node_struct_t *pns) {
  232. int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  233. for (int i = 0; i < num_nodes; i++) {
  234. compile_node(comp, pns->nodes[i]);
  235. if (comp->compile_error != MP_OBJ_NULL) {
  236. // add line info for the error in case it didn't have a line number
  237. compile_error_set_line(comp, pns->nodes[i]);
  238. return;
  239. }
  240. }
  241. }
  242. STATIC void compile_load_id(compiler_t *comp, qstr qst) {
  243. if (comp->pass == MP_PASS_SCOPE) {
  244. mp_emit_common_get_id_for_load(comp->scope_cur, qst);
  245. } else {
  246. #if NEED_METHOD_TABLE
  247. mp_emit_common_id_op(comp->emit, &comp->emit_method_table->load_id, comp->scope_cur, qst);
  248. #else
  249. mp_emit_common_id_op(comp->emit, &mp_emit_bc_method_table_load_id_ops, comp->scope_cur, qst);
  250. #endif
  251. }
  252. }
  253. STATIC void compile_store_id(compiler_t *comp, qstr qst) {
  254. if (comp->pass == MP_PASS_SCOPE) {
  255. mp_emit_common_get_id_for_modification(comp->scope_cur, qst);
  256. } else {
  257. #if NEED_METHOD_TABLE
  258. mp_emit_common_id_op(comp->emit, &comp->emit_method_table->store_id, comp->scope_cur, qst);
  259. #else
  260. mp_emit_common_id_op(comp->emit, &mp_emit_bc_method_table_store_id_ops, comp->scope_cur, qst);
  261. #endif
  262. }
  263. }
  264. STATIC void compile_delete_id(compiler_t *comp, qstr qst) {
  265. if (comp->pass == MP_PASS_SCOPE) {
  266. mp_emit_common_get_id_for_modification(comp->scope_cur, qst);
  267. } else {
  268. #if NEED_METHOD_TABLE
  269. mp_emit_common_id_op(comp->emit, &comp->emit_method_table->delete_id, comp->scope_cur, qst);
  270. #else
  271. mp_emit_common_id_op(comp->emit, &mp_emit_bc_method_table_delete_id_ops, comp->scope_cur, qst);
  272. #endif
  273. }
  274. }
  275. STATIC void c_tuple(compiler_t *comp, mp_parse_node_t pn, mp_parse_node_struct_t *pns_list) {
  276. int total = 0;
  277. if (!MP_PARSE_NODE_IS_NULL(pn)) {
  278. compile_node(comp, pn);
  279. total += 1;
  280. }
  281. if (pns_list != NULL) {
  282. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns_list);
  283. for (int i = 0; i < n; i++) {
  284. compile_node(comp, pns_list->nodes[i]);
  285. }
  286. total += n;
  287. }
  288. EMIT_ARG(build, total, MP_EMIT_BUILD_TUPLE);
  289. }
  290. STATIC void compile_generic_tuple(compiler_t *comp, mp_parse_node_struct_t *pns) {
  291. // a simple tuple expression
  292. c_tuple(comp, MP_PARSE_NODE_NULL, pns);
  293. }
  294. STATIC void c_if_cond(compiler_t *comp, mp_parse_node_t pn, bool jump_if, int label) {
  295. if (mp_parse_node_is_const_false(pn)) {
  296. if (jump_if == false) {
  297. EMIT_ARG(jump, label);
  298. }
  299. return;
  300. } else if (mp_parse_node_is_const_true(pn)) {
  301. if (jump_if == true) {
  302. EMIT_ARG(jump, label);
  303. }
  304. return;
  305. } else if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  306. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  307. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  308. if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_or_test) {
  309. if (jump_if == false) {
  310. and_or_logic1:;
  311. uint label2 = comp_next_label(comp);
  312. for (int i = 0; i < n - 1; i++) {
  313. c_if_cond(comp, pns->nodes[i], !jump_if, label2);
  314. }
  315. c_if_cond(comp, pns->nodes[n - 1], jump_if, label);
  316. EMIT_ARG(label_assign, label2);
  317. } else {
  318. and_or_logic2:
  319. for (int i = 0; i < n; i++) {
  320. c_if_cond(comp, pns->nodes[i], jump_if, label);
  321. }
  322. }
  323. return;
  324. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_and_test) {
  325. if (jump_if == false) {
  326. goto and_or_logic2;
  327. } else {
  328. goto and_or_logic1;
  329. }
  330. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_not_test_2) {
  331. c_if_cond(comp, pns->nodes[0], !jump_if, label);
  332. return;
  333. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_atom_paren) {
  334. // cond is something in parenthesis
  335. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  336. // empty tuple, acts as false for the condition
  337. if (jump_if == false) {
  338. EMIT_ARG(jump, label);
  339. }
  340. } else {
  341. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp));
  342. // non-empty tuple, acts as true for the condition
  343. if (jump_if == true) {
  344. EMIT_ARG(jump, label);
  345. }
  346. }
  347. return;
  348. }
  349. }
  350. // nothing special, fall back to default compiling for node and jump
  351. compile_node(comp, pn);
  352. EMIT_ARG(pop_jump_if, jump_if, label);
  353. }
  354. typedef enum { ASSIGN_STORE, ASSIGN_AUG_LOAD, ASSIGN_AUG_STORE } assign_kind_t;
  355. STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t kind);
  356. STATIC void c_assign_atom_expr(compiler_t *comp, mp_parse_node_struct_t *pns, assign_kind_t assign_kind) {
  357. if (assign_kind != ASSIGN_AUG_STORE) {
  358. compile_node(comp, pns->nodes[0]);
  359. }
  360. if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
  361. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1];
  362. if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_atom_expr_trailers) {
  363. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns1);
  364. if (assign_kind != ASSIGN_AUG_STORE) {
  365. for (int i = 0; i < n - 1; i++) {
  366. compile_node(comp, pns1->nodes[i]);
  367. }
  368. }
  369. assert(MP_PARSE_NODE_IS_STRUCT(pns1->nodes[n - 1]));
  370. pns1 = (mp_parse_node_struct_t *)pns1->nodes[n - 1];
  371. }
  372. if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_bracket) {
  373. if (assign_kind == ASSIGN_AUG_STORE) {
  374. EMIT(rot_three);
  375. EMIT_ARG(subscr, MP_EMIT_SUBSCR_STORE);
  376. } else {
  377. compile_node(comp, pns1->nodes[0]);
  378. if (assign_kind == ASSIGN_AUG_LOAD) {
  379. EMIT(dup_top_two);
  380. EMIT_ARG(subscr, MP_EMIT_SUBSCR_LOAD);
  381. } else {
  382. EMIT_ARG(subscr, MP_EMIT_SUBSCR_STORE);
  383. }
  384. }
  385. return;
  386. } else if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_period) {
  387. assert(MP_PARSE_NODE_IS_ID(pns1->nodes[0]));
  388. if (assign_kind == ASSIGN_AUG_LOAD) {
  389. EMIT(dup_top);
  390. EMIT_ARG(attr, MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]), MP_EMIT_ATTR_LOAD);
  391. } else {
  392. if (assign_kind == ASSIGN_AUG_STORE) {
  393. EMIT(rot_two);
  394. }
  395. EMIT_ARG(attr, MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]), MP_EMIT_ATTR_STORE);
  396. }
  397. return;
  398. }
  399. }
  400. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("can't assign to expression"));
  401. }
  402. // we need to allow for a caller passing in 1 initial node (node_head) followed by an array of nodes (nodes_tail)
  403. STATIC void c_assign_tuple(compiler_t *comp, mp_parse_node_t node_head, uint num_tail, mp_parse_node_t *nodes_tail) {
  404. uint num_head = (node_head == MP_PARSE_NODE_NULL) ? 0 : 1;
  405. // look for star expression
  406. uint have_star_index = -1;
  407. if (num_head != 0 && MP_PARSE_NODE_IS_STRUCT_KIND(node_head, PN_star_expr)) {
  408. EMIT_ARG(unpack_ex, 0, num_tail);
  409. have_star_index = 0;
  410. }
  411. for (uint i = 0; i < num_tail; i++) {
  412. if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes_tail[i], PN_star_expr)) {
  413. if (have_star_index == (uint)-1) {
  414. EMIT_ARG(unpack_ex, num_head + i, num_tail - i - 1);
  415. have_star_index = num_head + i;
  416. } else {
  417. compile_syntax_error(comp, nodes_tail[i], MP_ERROR_TEXT("multiple *x in assignment"));
  418. return;
  419. }
  420. }
  421. }
  422. if (have_star_index == (uint)-1) {
  423. EMIT_ARG(unpack_sequence, num_head + num_tail);
  424. }
  425. if (num_head != 0) {
  426. if (0 == have_star_index) {
  427. c_assign(comp, ((mp_parse_node_struct_t *)node_head)->nodes[0], ASSIGN_STORE);
  428. } else {
  429. c_assign(comp, node_head, ASSIGN_STORE);
  430. }
  431. }
  432. for (uint i = 0; i < num_tail; i++) {
  433. if (num_head + i == have_star_index) {
  434. c_assign(comp, ((mp_parse_node_struct_t *)nodes_tail[i])->nodes[0], ASSIGN_STORE);
  435. } else {
  436. c_assign(comp, nodes_tail[i], ASSIGN_STORE);
  437. }
  438. }
  439. }
  440. // assigns top of stack to pn
  441. STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_kind) {
  442. assert(!MP_PARSE_NODE_IS_NULL(pn));
  443. if (MP_PARSE_NODE_IS_LEAF(pn)) {
  444. if (MP_PARSE_NODE_IS_ID(pn)) {
  445. qstr arg = MP_PARSE_NODE_LEAF_ARG(pn);
  446. switch (assign_kind) {
  447. case ASSIGN_STORE:
  448. case ASSIGN_AUG_STORE:
  449. compile_store_id(comp, arg);
  450. break;
  451. case ASSIGN_AUG_LOAD:
  452. default:
  453. compile_load_id(comp, arg);
  454. break;
  455. }
  456. } else {
  457. goto cannot_assign;
  458. }
  459. } else {
  460. // pn must be a struct
  461. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  462. switch (MP_PARSE_NODE_STRUCT_KIND(pns)) {
  463. case PN_atom_expr_normal:
  464. // lhs is an index or attribute
  465. c_assign_atom_expr(comp, pns, assign_kind);
  466. break;
  467. case PN_testlist_star_expr:
  468. case PN_exprlist:
  469. // lhs is a tuple
  470. if (assign_kind != ASSIGN_STORE) {
  471. goto cannot_assign;
  472. }
  473. c_assign_tuple(comp, MP_PARSE_NODE_NULL, MP_PARSE_NODE_STRUCT_NUM_NODES(pns), pns->nodes);
  474. break;
  475. case PN_atom_paren:
  476. // lhs is something in parenthesis
  477. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  478. // empty tuple
  479. goto cannot_assign;
  480. } else {
  481. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp));
  482. if (assign_kind != ASSIGN_STORE) {
  483. goto cannot_assign;
  484. }
  485. pns = (mp_parse_node_struct_t *)pns->nodes[0];
  486. goto testlist_comp;
  487. }
  488. break;
  489. case PN_atom_bracket:
  490. // lhs is something in brackets
  491. if (assign_kind != ASSIGN_STORE) {
  492. goto cannot_assign;
  493. }
  494. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  495. // empty list, assignment allowed
  496. c_assign_tuple(comp, MP_PARSE_NODE_NULL, 0, NULL);
  497. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) {
  498. pns = (mp_parse_node_struct_t *)pns->nodes[0];
  499. goto testlist_comp;
  500. } else {
  501. // brackets around 1 item
  502. c_assign_tuple(comp, pns->nodes[0], 0, NULL);
  503. }
  504. break;
  505. default:
  506. goto cannot_assign;
  507. }
  508. return;
  509. testlist_comp:
  510. // lhs is a sequence
  511. if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
  512. mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1];
  513. if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3b) {
  514. // sequence of one item, with trailing comma
  515. assert(MP_PARSE_NODE_IS_NULL(pns2->nodes[0]));
  516. c_assign_tuple(comp, pns->nodes[0], 0, NULL);
  517. } else if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3c) {
  518. // sequence of many items
  519. uint n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns2);
  520. c_assign_tuple(comp, pns->nodes[0], n, pns2->nodes);
  521. } else if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_comp_for) {
  522. goto cannot_assign;
  523. } else {
  524. // sequence with 2 items
  525. goto sequence_with_2_items;
  526. }
  527. } else {
  528. // sequence with 2 items
  529. sequence_with_2_items:
  530. c_assign_tuple(comp, MP_PARSE_NODE_NULL, 2, pns->nodes);
  531. }
  532. return;
  533. }
  534. return;
  535. cannot_assign:
  536. compile_syntax_error(comp, pn, MP_ERROR_TEXT("can't assign to expression"));
  537. }
  538. // stuff for lambda and comprehensions and generators:
  539. // if n_pos_defaults > 0 then there is a tuple on the stack with the positional defaults
  540. // if n_kw_defaults > 0 then there is a dictionary on the stack with the keyword defaults
  541. // if both exist, the tuple is above the dictionary (ie the first pop gets the tuple)
  542. STATIC void close_over_variables_etc(compiler_t *comp, scope_t *this_scope, int n_pos_defaults, int n_kw_defaults) {
  543. assert(n_pos_defaults >= 0);
  544. assert(n_kw_defaults >= 0);
  545. // set flags
  546. if (n_kw_defaults > 0) {
  547. this_scope->scope_flags |= MP_SCOPE_FLAG_DEFKWARGS;
  548. }
  549. this_scope->num_def_pos_args = n_pos_defaults;
  550. #if MICROPY_EMIT_NATIVE
  551. // When creating a function/closure it will take a reference to the current globals
  552. comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_REFGLOBALS | MP_SCOPE_FLAG_HASCONSTS;
  553. #endif
  554. // make closed over variables, if any
  555. // ensure they are closed over in the order defined in the outer scope (mainly to agree with CPython)
  556. int nfree = 0;
  557. if (comp->scope_cur->kind != SCOPE_MODULE) {
  558. for (int i = 0; i < comp->scope_cur->id_info_len; i++) {
  559. id_info_t *id = &comp->scope_cur->id_info[i];
  560. if (id->kind == ID_INFO_KIND_CELL || id->kind == ID_INFO_KIND_FREE) {
  561. for (int j = 0; j < this_scope->id_info_len; j++) {
  562. id_info_t *id2 = &this_scope->id_info[j];
  563. if (id2->kind == ID_INFO_KIND_FREE && id->qst == id2->qst) {
  564. // in MicroPython we load closures using LOAD_FAST
  565. EMIT_LOAD_FAST(id->qst, id->local_num);
  566. nfree += 1;
  567. }
  568. }
  569. }
  570. }
  571. }
  572. // make the function/closure
  573. if (nfree == 0) {
  574. EMIT_ARG(make_function, this_scope, n_pos_defaults, n_kw_defaults);
  575. } else {
  576. EMIT_ARG(make_closure, this_scope, nfree, n_pos_defaults, n_kw_defaults);
  577. }
  578. }
  579. STATIC void compile_funcdef_lambdef_param(compiler_t *comp, mp_parse_node_t pn) {
  580. // For efficiency of the code below we extract the parse-node kind here
  581. int pn_kind;
  582. if (MP_PARSE_NODE_IS_ID(pn)) {
  583. pn_kind = -1;
  584. } else {
  585. assert(MP_PARSE_NODE_IS_STRUCT(pn));
  586. pn_kind = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn);
  587. }
  588. if (pn_kind == PN_typedargslist_star || pn_kind == PN_varargslist_star) {
  589. comp->have_star = true;
  590. /* don't need to distinguish bare from named star
  591. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  592. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  593. // bare star
  594. } else {
  595. // named star
  596. }
  597. */
  598. } else if (pn_kind == PN_typedargslist_dbl_star || pn_kind == PN_varargslist_dbl_star) {
  599. // named double star
  600. // TODO do we need to do anything with this?
  601. } else {
  602. mp_parse_node_t pn_id;
  603. mp_parse_node_t pn_equal;
  604. if (pn_kind == -1) {
  605. // this parameter is just an id
  606. pn_id = pn;
  607. pn_equal = MP_PARSE_NODE_NULL;
  608. } else if (pn_kind == PN_typedargslist_name) {
  609. // this parameter has a colon and/or equal specifier
  610. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  611. pn_id = pns->nodes[0];
  612. // pn_colon = pns->nodes[1]; // unused
  613. pn_equal = pns->nodes[2];
  614. } else {
  615. assert(pn_kind == PN_varargslist_name); // should be
  616. // this parameter has an equal specifier
  617. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  618. pn_id = pns->nodes[0];
  619. pn_equal = pns->nodes[1];
  620. }
  621. if (MP_PARSE_NODE_IS_NULL(pn_equal)) {
  622. // this parameter does not have a default value
  623. // check for non-default parameters given after default parameters (allowed by parser, but not syntactically valid)
  624. if (!comp->have_star && comp->num_default_params != 0) {
  625. compile_syntax_error(comp, pn, MP_ERROR_TEXT("non-default argument follows default argument"));
  626. return;
  627. }
  628. } else {
  629. // this parameter has a default value
  630. // in CPython, None (and True, False?) as default parameters are loaded with LOAD_NAME; don't understandy why
  631. if (comp->have_star) {
  632. comp->num_dict_params += 1;
  633. // in MicroPython we put the default dict parameters into a dictionary using the bytecode
  634. if (comp->num_dict_params == 1) {
  635. // in MicroPython we put the default positional parameters into a tuple using the bytecode
  636. // we need to do this here before we start building the map for the default keywords
  637. if (comp->num_default_params > 0) {
  638. EMIT_ARG(build, comp->num_default_params, MP_EMIT_BUILD_TUPLE);
  639. } else {
  640. EMIT(load_null); // sentinel indicating empty default positional args
  641. }
  642. // first default dict param, so make the map
  643. EMIT_ARG(build, 0, MP_EMIT_BUILD_MAP);
  644. }
  645. // compile value then key, then store it to the dict
  646. compile_node(comp, pn_equal);
  647. EMIT_ARG(load_const_str, MP_PARSE_NODE_LEAF_ARG(pn_id));
  648. EMIT(store_map);
  649. } else {
  650. comp->num_default_params += 1;
  651. compile_node(comp, pn_equal);
  652. }
  653. }
  654. }
  655. }
  656. STATIC void compile_funcdef_lambdef(compiler_t *comp, scope_t *scope, mp_parse_node_t pn_params, pn_kind_t pn_list_kind) {
  657. // When we call compile_funcdef_lambdef_param below it can compile an arbitrary
  658. // expression for default arguments, which may contain a lambda. The lambda will
  659. // call here in a nested way, so we must save and restore the relevant state.
  660. bool orig_have_star = comp->have_star;
  661. uint16_t orig_num_dict_params = comp->num_dict_params;
  662. uint16_t orig_num_default_params = comp->num_default_params;
  663. // compile default parameters
  664. comp->have_star = false;
  665. comp->num_dict_params = 0;
  666. comp->num_default_params = 0;
  667. apply_to_single_or_list(comp, pn_params, pn_list_kind, compile_funcdef_lambdef_param);
  668. if (comp->compile_error != MP_OBJ_NULL) {
  669. return;
  670. }
  671. // in MicroPython we put the default positional parameters into a tuple using the bytecode
  672. // the default keywords args may have already made the tuple; if not, do it now
  673. if (comp->num_default_params > 0 && comp->num_dict_params == 0) {
  674. EMIT_ARG(build, comp->num_default_params, MP_EMIT_BUILD_TUPLE);
  675. EMIT(load_null); // sentinel indicating empty default keyword args
  676. }
  677. // make the function
  678. close_over_variables_etc(comp, scope, comp->num_default_params, comp->num_dict_params);
  679. // restore state
  680. comp->have_star = orig_have_star;
  681. comp->num_dict_params = orig_num_dict_params;
  682. comp->num_default_params = orig_num_default_params;
  683. }
  684. // leaves function object on stack
  685. // returns function name
  686. STATIC qstr compile_funcdef_helper(compiler_t *comp, mp_parse_node_struct_t *pns, uint emit_options) {
  687. if (comp->pass == MP_PASS_SCOPE) {
  688. // create a new scope for this function
  689. scope_t *s = scope_new_and_link(comp, SCOPE_FUNCTION, (mp_parse_node_t)pns, emit_options);
  690. // store the function scope so the compiling function can use it at each pass
  691. pns->nodes[4] = (mp_parse_node_t)s;
  692. }
  693. // get the scope for this function
  694. scope_t *fscope = (scope_t *)pns->nodes[4];
  695. // compile the function definition
  696. compile_funcdef_lambdef(comp, fscope, pns->nodes[1], PN_typedargslist);
  697. // return its name (the 'f' in "def f(...):")
  698. return fscope->simple_name;
  699. }
  700. // leaves class object on stack
  701. // returns class name
  702. STATIC qstr compile_classdef_helper(compiler_t *comp, mp_parse_node_struct_t *pns, uint emit_options) {
  703. if (comp->pass == MP_PASS_SCOPE) {
  704. // create a new scope for this class
  705. scope_t *s = scope_new_and_link(comp, SCOPE_CLASS, (mp_parse_node_t)pns, emit_options);
  706. // store the class scope so the compiling function can use it at each pass
  707. pns->nodes[3] = (mp_parse_node_t)s;
  708. }
  709. EMIT(load_build_class);
  710. // scope for this class
  711. scope_t *cscope = (scope_t *)pns->nodes[3];
  712. // compile the class
  713. close_over_variables_etc(comp, cscope, 0, 0);
  714. // get its name
  715. EMIT_ARG(load_const_str, cscope->simple_name);
  716. // nodes[1] has parent classes, if any
  717. // empty parenthesis (eg class C():) gets here as an empty PN_classdef_2 and needs special handling
  718. mp_parse_node_t parents = pns->nodes[1];
  719. if (MP_PARSE_NODE_IS_STRUCT_KIND(parents, PN_classdef_2)) {
  720. parents = MP_PARSE_NODE_NULL;
  721. }
  722. compile_trailer_paren_helper(comp, parents, false, 2);
  723. // return its name (the 'C' in class C(...):")
  724. return cscope->simple_name;
  725. }
  726. // returns true if it was a built-in decorator (even if the built-in had an error)
  727. STATIC bool compile_built_in_decorator(compiler_t *comp, size_t name_len, mp_parse_node_t *name_nodes, uint *emit_options) {
  728. if (MP_PARSE_NODE_LEAF_ARG(name_nodes[0]) != MP_QSTR_micropython) {
  729. return false;
  730. }
  731. if (name_len != 2) {
  732. compile_syntax_error(comp, name_nodes[0], MP_ERROR_TEXT("invalid micropython decorator"));
  733. return true;
  734. }
  735. qstr attr = MP_PARSE_NODE_LEAF_ARG(name_nodes[1]);
  736. if (attr == MP_QSTR_bytecode) {
  737. *emit_options = MP_EMIT_OPT_BYTECODE;
  738. #if MICROPY_EMIT_NATIVE
  739. } else if (attr == MP_QSTR_native) {
  740. *emit_options = MP_EMIT_OPT_NATIVE_PYTHON;
  741. } else if (attr == MP_QSTR_viper) {
  742. *emit_options = MP_EMIT_OPT_VIPER;
  743. #endif
  744. #if MICROPY_EMIT_INLINE_ASM
  745. #if MICROPY_DYNAMIC_COMPILER
  746. } else if (attr == MP_QSTR_asm_thumb) {
  747. *emit_options = MP_EMIT_OPT_ASM;
  748. } else if (attr == MP_QSTR_asm_xtensa) {
  749. *emit_options = MP_EMIT_OPT_ASM;
  750. #else
  751. } else if (attr == ASM_DECORATOR_QSTR) {
  752. *emit_options = MP_EMIT_OPT_ASM;
  753. #endif
  754. #endif
  755. } else {
  756. compile_syntax_error(comp, name_nodes[1], MP_ERROR_TEXT("invalid micropython decorator"));
  757. }
  758. #if MICROPY_DYNAMIC_COMPILER
  759. if (*emit_options == MP_EMIT_OPT_NATIVE_PYTHON || *emit_options == MP_EMIT_OPT_VIPER) {
  760. if (emit_native_table[mp_dynamic_compiler.native_arch] == NULL) {
  761. compile_syntax_error(comp, name_nodes[1], MP_ERROR_TEXT("invalid arch"));
  762. }
  763. } else if (*emit_options == MP_EMIT_OPT_ASM) {
  764. if (emit_asm_table[mp_dynamic_compiler.native_arch] == NULL) {
  765. compile_syntax_error(comp, name_nodes[1], MP_ERROR_TEXT("invalid arch"));
  766. }
  767. }
  768. #endif
  769. return true;
  770. }
  771. STATIC void compile_decorated(compiler_t *comp, mp_parse_node_struct_t *pns) {
  772. // get the list of decorators
  773. mp_parse_node_t *nodes;
  774. size_t n = mp_parse_node_extract_list(&pns->nodes[0], PN_decorators, &nodes);
  775. // inherit emit options for this function/class definition
  776. uint emit_options = comp->scope_cur->emit_options;
  777. // compile each decorator
  778. size_t num_built_in_decorators = 0;
  779. for (size_t i = 0; i < n; i++) {
  780. assert(MP_PARSE_NODE_IS_STRUCT_KIND(nodes[i], PN_decorator)); // should be
  781. mp_parse_node_struct_t *pns_decorator = (mp_parse_node_struct_t *)nodes[i];
  782. // nodes[0] contains the decorator function, which is a dotted name
  783. mp_parse_node_t *name_nodes;
  784. size_t name_len = mp_parse_node_extract_list(&pns_decorator->nodes[0], PN_dotted_name, &name_nodes);
  785. // check for built-in decorators
  786. if (compile_built_in_decorator(comp, name_len, name_nodes, &emit_options)) {
  787. // this was a built-in
  788. num_built_in_decorators += 1;
  789. } else {
  790. // not a built-in, compile normally
  791. // compile the decorator function
  792. compile_node(comp, name_nodes[0]);
  793. for (size_t j = 1; j < name_len; j++) {
  794. assert(MP_PARSE_NODE_IS_ID(name_nodes[j])); // should be
  795. EMIT_ARG(attr, MP_PARSE_NODE_LEAF_ARG(name_nodes[j]), MP_EMIT_ATTR_LOAD);
  796. }
  797. // nodes[1] contains arguments to the decorator function, if any
  798. if (!MP_PARSE_NODE_IS_NULL(pns_decorator->nodes[1])) {
  799. // call the decorator function with the arguments in nodes[1]
  800. compile_node(comp, pns_decorator->nodes[1]);
  801. }
  802. }
  803. }
  804. // compile the body (funcdef, async funcdef or classdef) and get its name
  805. mp_parse_node_struct_t *pns_body = (mp_parse_node_struct_t *)pns->nodes[1];
  806. qstr body_name = 0;
  807. if (MP_PARSE_NODE_STRUCT_KIND(pns_body) == PN_funcdef) {
  808. body_name = compile_funcdef_helper(comp, pns_body, emit_options);
  809. #if MICROPY_PY_ASYNC_AWAIT
  810. } else if (MP_PARSE_NODE_STRUCT_KIND(pns_body) == PN_async_funcdef) {
  811. assert(MP_PARSE_NODE_IS_STRUCT(pns_body->nodes[0]));
  812. mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns_body->nodes[0];
  813. body_name = compile_funcdef_helper(comp, pns0, emit_options);
  814. scope_t *fscope = (scope_t *)pns0->nodes[4];
  815. fscope->scope_flags |= MP_SCOPE_FLAG_GENERATOR;
  816. #endif
  817. } else {
  818. assert(MP_PARSE_NODE_STRUCT_KIND(pns_body) == PN_classdef); // should be
  819. body_name = compile_classdef_helper(comp, pns_body, emit_options);
  820. }
  821. // call each decorator
  822. for (size_t i = 0; i < n - num_built_in_decorators; i++) {
  823. EMIT_ARG(call_function, 1, 0, 0);
  824. }
  825. // store func/class object into name
  826. compile_store_id(comp, body_name);
  827. }
  828. STATIC void compile_funcdef(compiler_t *comp, mp_parse_node_struct_t *pns) {
  829. qstr fname = compile_funcdef_helper(comp, pns, comp->scope_cur->emit_options);
  830. // store function object into function name
  831. compile_store_id(comp, fname);
  832. }
  833. STATIC void c_del_stmt(compiler_t *comp, mp_parse_node_t pn) {
  834. if (MP_PARSE_NODE_IS_ID(pn)) {
  835. compile_delete_id(comp, MP_PARSE_NODE_LEAF_ARG(pn));
  836. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_expr_normal)) {
  837. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  838. compile_node(comp, pns->nodes[0]); // base of the atom_expr_normal node
  839. if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
  840. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1];
  841. if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_atom_expr_trailers) {
  842. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns1);
  843. for (int i = 0; i < n - 1; i++) {
  844. compile_node(comp, pns1->nodes[i]);
  845. }
  846. assert(MP_PARSE_NODE_IS_STRUCT(pns1->nodes[n - 1]));
  847. pns1 = (mp_parse_node_struct_t *)pns1->nodes[n - 1];
  848. }
  849. if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_bracket) {
  850. compile_node(comp, pns1->nodes[0]);
  851. EMIT_ARG(subscr, MP_EMIT_SUBSCR_DELETE);
  852. } else if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_period) {
  853. assert(MP_PARSE_NODE_IS_ID(pns1->nodes[0]));
  854. EMIT_ARG(attr, MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]), MP_EMIT_ATTR_DELETE);
  855. } else {
  856. goto cannot_delete;
  857. }
  858. } else {
  859. goto cannot_delete;
  860. }
  861. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_paren)) {
  862. pn = ((mp_parse_node_struct_t *)pn)->nodes[0];
  863. if (MP_PARSE_NODE_IS_NULL(pn)) {
  864. goto cannot_delete;
  865. } else {
  866. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_testlist_comp));
  867. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  868. // TODO perhaps factorise testlist_comp code with other uses of PN_testlist_comp
  869. if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
  870. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1];
  871. if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_testlist_comp_3b) {
  872. // sequence of one item, with trailing comma
  873. assert(MP_PARSE_NODE_IS_NULL(pns1->nodes[0]));
  874. c_del_stmt(comp, pns->nodes[0]);
  875. } else if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_testlist_comp_3c) {
  876. // sequence of many items
  877. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns1);
  878. c_del_stmt(comp, pns->nodes[0]);
  879. for (int i = 0; i < n; i++) {
  880. c_del_stmt(comp, pns1->nodes[i]);
  881. }
  882. } else if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_comp_for) {
  883. goto cannot_delete;
  884. } else {
  885. // sequence with 2 items
  886. goto sequence_with_2_items;
  887. }
  888. } else {
  889. // sequence with 2 items
  890. sequence_with_2_items:
  891. c_del_stmt(comp, pns->nodes[0]);
  892. c_del_stmt(comp, pns->nodes[1]);
  893. }
  894. }
  895. } else {
  896. // some arbitrary statement that we can't delete (eg del 1)
  897. goto cannot_delete;
  898. }
  899. return;
  900. cannot_delete:
  901. compile_syntax_error(comp, (mp_parse_node_t)pn, MP_ERROR_TEXT("can't delete expression"));
  902. }
  903. STATIC void compile_del_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  904. apply_to_single_or_list(comp, pns->nodes[0], PN_exprlist, c_del_stmt);
  905. }
  906. STATIC void compile_break_cont_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  907. uint16_t label;
  908. if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_break_stmt) {
  909. label = comp->break_label;
  910. } else {
  911. label = comp->continue_label;
  912. }
  913. if (label == INVALID_LABEL) {
  914. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("'break'/'continue' outside loop"));
  915. }
  916. assert(comp->cur_except_level >= comp->break_continue_except_level);
  917. EMIT_ARG(unwind_jump, label, comp->cur_except_level - comp->break_continue_except_level);
  918. }
  919. STATIC void compile_return_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  920. #if MICROPY_CPYTHON_COMPAT
  921. if (comp->scope_cur->kind != SCOPE_FUNCTION) {
  922. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("'return' outside function"));
  923. return;
  924. }
  925. #endif
  926. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  927. // no argument to 'return', so return None
  928. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  929. } else if (MICROPY_COMP_RETURN_IF_EXPR
  930. && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_test_if_expr)) {
  931. // special case when returning an if-expression; to match CPython optimisation
  932. mp_parse_node_struct_t *pns_test_if_expr = (mp_parse_node_struct_t *)pns->nodes[0];
  933. mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t *)pns_test_if_expr->nodes[1];
  934. uint l_fail = comp_next_label(comp);
  935. c_if_cond(comp, pns_test_if_else->nodes[0], false, l_fail); // condition
  936. compile_node(comp, pns_test_if_expr->nodes[0]); // success value
  937. EMIT(return_value);
  938. EMIT_ARG(label_assign, l_fail);
  939. compile_node(comp, pns_test_if_else->nodes[1]); // failure value
  940. } else {
  941. compile_node(comp, pns->nodes[0]);
  942. }
  943. EMIT(return_value);
  944. }
  945. STATIC void compile_yield_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  946. compile_node(comp, pns->nodes[0]);
  947. EMIT(pop_top);
  948. }
  949. STATIC void compile_raise_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  950. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  951. // raise
  952. EMIT_ARG(raise_varargs, 0);
  953. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_raise_stmt_arg)) {
  954. // raise x from y
  955. pns = (mp_parse_node_struct_t *)pns->nodes[0];
  956. compile_node(comp, pns->nodes[0]);
  957. compile_node(comp, pns->nodes[1]);
  958. EMIT_ARG(raise_varargs, 2);
  959. } else {
  960. // raise x
  961. compile_node(comp, pns->nodes[0]);
  962. EMIT_ARG(raise_varargs, 1);
  963. }
  964. }
  965. // q_base holds the base of the name
  966. // eg a -> q_base=a
  967. // a.b.c -> q_base=a
  968. STATIC void do_import_name(compiler_t *comp, mp_parse_node_t pn, qstr *q_base) {
  969. bool is_as = false;
  970. if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_dotted_as_name)) {
  971. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  972. // a name of the form x as y; unwrap it
  973. *q_base = MP_PARSE_NODE_LEAF_ARG(pns->nodes[1]);
  974. pn = pns->nodes[0];
  975. is_as = true;
  976. }
  977. if (MP_PARSE_NODE_IS_NULL(pn)) {
  978. // empty name (eg, from . import x)
  979. *q_base = MP_QSTR_;
  980. EMIT_ARG(import, MP_QSTR_, MP_EMIT_IMPORT_NAME); // import the empty string
  981. } else if (MP_PARSE_NODE_IS_ID(pn)) {
  982. // just a simple name
  983. qstr q_full = MP_PARSE_NODE_LEAF_ARG(pn);
  984. if (!is_as) {
  985. *q_base = q_full;
  986. }
  987. EMIT_ARG(import, q_full, MP_EMIT_IMPORT_NAME);
  988. } else {
  989. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_dotted_name)); // should be
  990. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  991. {
  992. // a name of the form a.b.c
  993. if (!is_as) {
  994. *q_base = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]);
  995. }
  996. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  997. int len = n - 1;
  998. for (int i = 0; i < n; i++) {
  999. len += qstr_len(MP_PARSE_NODE_LEAF_ARG(pns->nodes[i]));
  1000. }
  1001. char *q_ptr = mp_local_alloc(len);
  1002. char *str_dest = q_ptr;
  1003. for (int i = 0; i < n; i++) {
  1004. if (i > 0) {
  1005. *str_dest++ = '.';
  1006. }
  1007. size_t str_src_len;
  1008. const byte *str_src = qstr_data(MP_PARSE_NODE_LEAF_ARG(pns->nodes[i]), &str_src_len);
  1009. memcpy(str_dest, str_src, str_src_len);
  1010. str_dest += str_src_len;
  1011. }
  1012. qstr q_full = qstr_from_strn(q_ptr, len);
  1013. mp_local_free(q_ptr);
  1014. EMIT_ARG(import, q_full, MP_EMIT_IMPORT_NAME);
  1015. if (is_as) {
  1016. for (int i = 1; i < n; i++) {
  1017. EMIT_ARG(attr, MP_PARSE_NODE_LEAF_ARG(pns->nodes[i]), MP_EMIT_ATTR_LOAD);
  1018. }
  1019. }
  1020. }
  1021. }
  1022. }
  1023. STATIC void compile_dotted_as_name(compiler_t *comp, mp_parse_node_t pn) {
  1024. EMIT_ARG(load_const_small_int, 0); // level 0 import
  1025. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // not importing from anything
  1026. qstr q_base;
  1027. do_import_name(comp, pn, &q_base);
  1028. compile_store_id(comp, q_base);
  1029. }
  1030. STATIC void compile_import_name(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1031. apply_to_single_or_list(comp, pns->nodes[0], PN_dotted_as_names, compile_dotted_as_name);
  1032. }
  1033. STATIC void compile_import_from(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1034. mp_parse_node_t pn_import_source = pns->nodes[0];
  1035. // extract the preceding .'s (if any) for a relative import, to compute the import level
  1036. uint import_level = 0;
  1037. do {
  1038. mp_parse_node_t pn_rel;
  1039. if (MP_PARSE_NODE_IS_TOKEN(pn_import_source) || MP_PARSE_NODE_IS_STRUCT_KIND(pn_import_source, PN_one_or_more_period_or_ellipsis)) {
  1040. // This covers relative imports with dots only like "from .. import"
  1041. pn_rel = pn_import_source;
  1042. pn_import_source = MP_PARSE_NODE_NULL;
  1043. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn_import_source, PN_import_from_2b)) {
  1044. // This covers relative imports starting with dot(s) like "from .foo import"
  1045. mp_parse_node_struct_t *pns_2b = (mp_parse_node_struct_t *)pn_import_source;
  1046. pn_rel = pns_2b->nodes[0];
  1047. pn_import_source = pns_2b->nodes[1];
  1048. assert(!MP_PARSE_NODE_IS_NULL(pn_import_source)); // should not be
  1049. } else {
  1050. // Not a relative import
  1051. break;
  1052. }
  1053. // get the list of . and/or ...'s
  1054. mp_parse_node_t *nodes;
  1055. size_t n = mp_parse_node_extract_list(&pn_rel, PN_one_or_more_period_or_ellipsis, &nodes);
  1056. // count the total number of .'s
  1057. for (size_t i = 0; i < n; i++) {
  1058. if (MP_PARSE_NODE_IS_TOKEN_KIND(nodes[i], MP_TOKEN_DEL_PERIOD)) {
  1059. import_level++;
  1060. } else {
  1061. // should be an MP_TOKEN_ELLIPSIS
  1062. import_level += 3;
  1063. }
  1064. }
  1065. } while (0);
  1066. if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_STAR)) {
  1067. #if MICROPY_CPYTHON_COMPAT
  1068. if (comp->scope_cur->kind != SCOPE_MODULE) {
  1069. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("import * not at module level"));
  1070. return;
  1071. }
  1072. #endif
  1073. EMIT_ARG(load_const_small_int, import_level);
  1074. // build the "fromlist" tuple
  1075. EMIT_ARG(load_const_str, MP_QSTR__star_);
  1076. EMIT_ARG(build, 1, MP_EMIT_BUILD_TUPLE);
  1077. // do the import
  1078. qstr dummy_q;
  1079. do_import_name(comp, pn_import_source, &dummy_q);
  1080. EMIT_ARG(import, MP_QSTRnull, MP_EMIT_IMPORT_STAR);
  1081. } else {
  1082. EMIT_ARG(load_const_small_int, import_level);
  1083. // build the "fromlist" tuple
  1084. mp_parse_node_t *pn_nodes;
  1085. size_t n = mp_parse_node_extract_list(&pns->nodes[1], PN_import_as_names, &pn_nodes);
  1086. for (size_t i = 0; i < n; i++) {
  1087. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_nodes[i], PN_import_as_name));
  1088. mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pn_nodes[i];
  1089. qstr id2 = MP_PARSE_NODE_LEAF_ARG(pns3->nodes[0]); // should be id
  1090. EMIT_ARG(load_const_str, id2);
  1091. }
  1092. EMIT_ARG(build, n, MP_EMIT_BUILD_TUPLE);
  1093. // do the import
  1094. qstr dummy_q;
  1095. do_import_name(comp, pn_import_source, &dummy_q);
  1096. for (size_t i = 0; i < n; i++) {
  1097. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_nodes[i], PN_import_as_name));
  1098. mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pn_nodes[i];
  1099. qstr id2 = MP_PARSE_NODE_LEAF_ARG(pns3->nodes[0]); // should be id
  1100. EMIT_ARG(import, id2, MP_EMIT_IMPORT_FROM);
  1101. if (MP_PARSE_NODE_IS_NULL(pns3->nodes[1])) {
  1102. compile_store_id(comp, id2);
  1103. } else {
  1104. compile_store_id(comp, MP_PARSE_NODE_LEAF_ARG(pns3->nodes[1]));
  1105. }
  1106. }
  1107. EMIT(pop_top);
  1108. }
  1109. }
  1110. STATIC void compile_declare_global(compiler_t *comp, mp_parse_node_t pn, id_info_t *id_info) {
  1111. if (id_info->kind != ID_INFO_KIND_UNDECIDED && id_info->kind != ID_INFO_KIND_GLOBAL_EXPLICIT) {
  1112. compile_syntax_error(comp, pn, MP_ERROR_TEXT("identifier redefined as global"));
  1113. return;
  1114. }
  1115. id_info->kind = ID_INFO_KIND_GLOBAL_EXPLICIT;
  1116. // if the id exists in the global scope, set its kind to EXPLICIT_GLOBAL
  1117. id_info = scope_find_global(comp->scope_cur, id_info->qst);
  1118. if (id_info != NULL) {
  1119. id_info->kind = ID_INFO_KIND_GLOBAL_EXPLICIT;
  1120. }
  1121. }
  1122. STATIC void compile_declare_nonlocal(compiler_t *comp, mp_parse_node_t pn, id_info_t *id_info) {
  1123. if (id_info->kind == ID_INFO_KIND_UNDECIDED) {
  1124. id_info->kind = ID_INFO_KIND_GLOBAL_IMPLICIT;
  1125. scope_check_to_close_over(comp->scope_cur, id_info);
  1126. if (id_info->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) {
  1127. compile_syntax_error(comp, pn, MP_ERROR_TEXT("no binding for nonlocal found"));
  1128. }
  1129. } else if (id_info->kind != ID_INFO_KIND_FREE) {
  1130. compile_syntax_error(comp, pn, MP_ERROR_TEXT("identifier redefined as nonlocal"));
  1131. }
  1132. }
  1133. STATIC void compile_global_nonlocal_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1134. if (comp->pass == MP_PASS_SCOPE) {
  1135. bool is_global = MP_PARSE_NODE_STRUCT_KIND(pns) == PN_global_stmt;
  1136. if (!is_global && comp->scope_cur->kind == SCOPE_MODULE) {
  1137. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("can't declare nonlocal in outer code"));
  1138. return;
  1139. }
  1140. mp_parse_node_t *nodes;
  1141. size_t n = mp_parse_node_extract_list(&pns->nodes[0], PN_name_list, &nodes);
  1142. for (size_t i = 0; i < n; i++) {
  1143. qstr qst = MP_PARSE_NODE_LEAF_ARG(nodes[i]);
  1144. id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, qst, ID_INFO_KIND_UNDECIDED);
  1145. if (is_global) {
  1146. compile_declare_global(comp, (mp_parse_node_t)pns, id_info);
  1147. } else {
  1148. compile_declare_nonlocal(comp, (mp_parse_node_t)pns, id_info);
  1149. }
  1150. }
  1151. }
  1152. }
  1153. STATIC void compile_assert_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1154. // with optimisations enabled we don't compile assertions
  1155. if (MP_STATE_VM(mp_optimise_value) != 0) {
  1156. return;
  1157. }
  1158. uint l_end = comp_next_label(comp);
  1159. c_if_cond(comp, pns->nodes[0], true, l_end);
  1160. EMIT_LOAD_GLOBAL(MP_QSTR_AssertionError); // we load_global instead of load_id, to be consistent with CPython
  1161. if (!MP_PARSE_NODE_IS_NULL(pns->nodes[1])) {
  1162. // assertion message
  1163. compile_node(comp, pns->nodes[1]);
  1164. EMIT_ARG(call_function, 1, 0, 0);
  1165. }
  1166. EMIT_ARG(raise_varargs, 1);
  1167. EMIT_ARG(label_assign, l_end);
  1168. }
  1169. STATIC void compile_if_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1170. uint l_end = comp_next_label(comp);
  1171. // optimisation: don't emit anything when "if False"
  1172. if (!mp_parse_node_is_const_false(pns->nodes[0])) {
  1173. uint l_fail = comp_next_label(comp);
  1174. c_if_cond(comp, pns->nodes[0], false, l_fail); // if condition
  1175. compile_node(comp, pns->nodes[1]); // if block
  1176. // optimisation: skip everything else when "if True"
  1177. if (mp_parse_node_is_const_true(pns->nodes[0])) {
  1178. goto done;
  1179. }
  1180. if (
  1181. // optimisation: don't jump over non-existent elif/else blocks
  1182. !(MP_PARSE_NODE_IS_NULL(pns->nodes[2]) && MP_PARSE_NODE_IS_NULL(pns->nodes[3]))
  1183. // optimisation: don't jump if last instruction was return
  1184. && !EMIT(last_emit_was_return_value)
  1185. ) {
  1186. // jump over elif/else blocks
  1187. EMIT_ARG(jump, l_end);
  1188. }
  1189. EMIT_ARG(label_assign, l_fail);
  1190. }
  1191. // compile elif blocks (if any)
  1192. mp_parse_node_t *pn_elif;
  1193. size_t n_elif = mp_parse_node_extract_list(&pns->nodes[2], PN_if_stmt_elif_list, &pn_elif);
  1194. for (size_t i = 0; i < n_elif; i++) {
  1195. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_elif[i], PN_if_stmt_elif)); // should be
  1196. mp_parse_node_struct_t *pns_elif = (mp_parse_node_struct_t *)pn_elif[i];
  1197. // optimisation: don't emit anything when "if False"
  1198. if (!mp_parse_node_is_const_false(pns_elif->nodes[0])) {
  1199. uint l_fail = comp_next_label(comp);
  1200. c_if_cond(comp, pns_elif->nodes[0], false, l_fail); // elif condition
  1201. compile_node(comp, pns_elif->nodes[1]); // elif block
  1202. // optimisation: skip everything else when "elif True"
  1203. if (mp_parse_node_is_const_true(pns_elif->nodes[0])) {
  1204. goto done;
  1205. }
  1206. // optimisation: don't jump if last instruction was return
  1207. if (!EMIT(last_emit_was_return_value)) {
  1208. EMIT_ARG(jump, l_end);
  1209. }
  1210. EMIT_ARG(label_assign, l_fail);
  1211. }
  1212. }
  1213. // compile else block
  1214. compile_node(comp, pns->nodes[3]); // can be null
  1215. done:
  1216. EMIT_ARG(label_assign, l_end);
  1217. }
  1218. #define START_BREAK_CONTINUE_BLOCK \
  1219. uint16_t old_break_label = comp->break_label; \
  1220. uint16_t old_continue_label = comp->continue_label; \
  1221. uint16_t old_break_continue_except_level = comp->break_continue_except_level; \
  1222. uint break_label = comp_next_label(comp); \
  1223. uint continue_label = comp_next_label(comp); \
  1224. comp->break_label = break_label; \
  1225. comp->continue_label = continue_label; \
  1226. comp->break_continue_except_level = comp->cur_except_level;
  1227. #define END_BREAK_CONTINUE_BLOCK \
  1228. comp->break_label = old_break_label; \
  1229. comp->continue_label = old_continue_label; \
  1230. comp->break_continue_except_level = old_break_continue_except_level;
  1231. STATIC void compile_while_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1232. START_BREAK_CONTINUE_BLOCK
  1233. if (!mp_parse_node_is_const_false(pns->nodes[0])) { // optimisation: don't emit anything for "while False"
  1234. uint top_label = comp_next_label(comp);
  1235. if (!mp_parse_node_is_const_true(pns->nodes[0])) { // optimisation: don't jump to cond for "while True"
  1236. EMIT_ARG(jump, continue_label);
  1237. }
  1238. EMIT_ARG(label_assign, top_label);
  1239. compile_node(comp, pns->nodes[1]); // body
  1240. EMIT_ARG(label_assign, continue_label);
  1241. c_if_cond(comp, pns->nodes[0], true, top_label); // condition
  1242. }
  1243. // break/continue apply to outer loop (if any) in the else block
  1244. END_BREAK_CONTINUE_BLOCK
  1245. compile_node(comp, pns->nodes[2]); // else
  1246. EMIT_ARG(label_assign, break_label);
  1247. }
  1248. // This function compiles an optimised for-loop of the form:
  1249. // for <var> in range(<start>, <end>, <step>):
  1250. // <body>
  1251. // else:
  1252. // <else>
  1253. // <var> must be an identifier and <step> must be a small-int.
  1254. //
  1255. // Semantics of for-loop require:
  1256. // - final failing value should not be stored in the loop variable
  1257. // - if the loop never runs, the loop variable should never be assigned
  1258. // - assignments to <var>, <end> or <step> in the body do not alter the loop
  1259. // (<step> is a constant for us, so no need to worry about it changing)
  1260. //
  1261. // If <end> is a small-int, then the stack during the for-loop contains just
  1262. // the current value of <var>. Otherwise, the stack contains <end> then the
  1263. // current value of <var>.
  1264. STATIC void compile_for_stmt_optimised_range(compiler_t *comp, mp_parse_node_t pn_var, mp_parse_node_t pn_start, mp_parse_node_t pn_end, mp_parse_node_t pn_step, mp_parse_node_t pn_body, mp_parse_node_t pn_else) {
  1265. START_BREAK_CONTINUE_BLOCK
  1266. uint top_label = comp_next_label(comp);
  1267. uint entry_label = comp_next_label(comp);
  1268. // put the end value on the stack if it's not a small-int constant
  1269. bool end_on_stack = !MP_PARSE_NODE_IS_SMALL_INT(pn_end);
  1270. if (end_on_stack) {
  1271. compile_node(comp, pn_end);
  1272. }
  1273. // compile: start
  1274. compile_node(comp, pn_start);
  1275. EMIT_ARG(jump, entry_label);
  1276. EMIT_ARG(label_assign, top_label);
  1277. // duplicate next value and store it to var
  1278. EMIT(dup_top);
  1279. c_assign(comp, pn_var, ASSIGN_STORE);
  1280. // compile body
  1281. compile_node(comp, pn_body);
  1282. EMIT_ARG(label_assign, continue_label);
  1283. // compile: var + step
  1284. compile_node(comp, pn_step);
  1285. EMIT_ARG(binary_op, MP_BINARY_OP_INPLACE_ADD);
  1286. EMIT_ARG(label_assign, entry_label);
  1287. // compile: if var <cond> end: goto top
  1288. if (end_on_stack) {
  1289. EMIT(dup_top_two);
  1290. EMIT(rot_two);
  1291. } else {
  1292. EMIT(dup_top);
  1293. compile_node(comp, pn_end);
  1294. }
  1295. assert(MP_PARSE_NODE_IS_SMALL_INT(pn_step));
  1296. if (MP_PARSE_NODE_LEAF_SMALL_INT(pn_step) >= 0) {
  1297. EMIT_ARG(binary_op, MP_BINARY_OP_LESS);
  1298. } else {
  1299. EMIT_ARG(binary_op, MP_BINARY_OP_MORE);
  1300. }
  1301. EMIT_ARG(pop_jump_if, true, top_label);
  1302. // break/continue apply to outer loop (if any) in the else block
  1303. END_BREAK_CONTINUE_BLOCK
  1304. // Compile the else block. We must pop the iterator variables before
  1305. // executing the else code because it may contain break/continue statements.
  1306. uint end_label = 0;
  1307. if (!MP_PARSE_NODE_IS_NULL(pn_else)) {
  1308. // discard final value of "var", and possible "end" value
  1309. EMIT(pop_top);
  1310. if (end_on_stack) {
  1311. EMIT(pop_top);
  1312. }
  1313. compile_node(comp, pn_else);
  1314. end_label = comp_next_label(comp);
  1315. EMIT_ARG(jump, end_label);
  1316. EMIT_ARG(adjust_stack_size, 1 + end_on_stack);
  1317. }
  1318. EMIT_ARG(label_assign, break_label);
  1319. // discard final value of var that failed the loop condition
  1320. EMIT(pop_top);
  1321. // discard <end> value if it's on the stack
  1322. if (end_on_stack) {
  1323. EMIT(pop_top);
  1324. }
  1325. if (!MP_PARSE_NODE_IS_NULL(pn_else)) {
  1326. EMIT_ARG(label_assign, end_label);
  1327. }
  1328. }
  1329. STATIC void compile_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1330. // this bit optimises: for <x> in range(...), turning it into an explicitly incremented variable
  1331. // this is actually slower, but uses no heap memory
  1332. // for viper it will be much, much faster
  1333. if (/*comp->scope_cur->emit_options == MP_EMIT_OPT_VIPER &&*/ MP_PARSE_NODE_IS_ID(pns->nodes[0]) && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_atom_expr_normal)) {
  1334. mp_parse_node_struct_t *pns_it = (mp_parse_node_struct_t *)pns->nodes[1];
  1335. if (MP_PARSE_NODE_IS_ID(pns_it->nodes[0])
  1336. && MP_PARSE_NODE_LEAF_ARG(pns_it->nodes[0]) == MP_QSTR_range
  1337. && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pns_it->nodes[1]) == PN_trailer_paren) {
  1338. mp_parse_node_t pn_range_args = ((mp_parse_node_struct_t *)pns_it->nodes[1])->nodes[0];
  1339. mp_parse_node_t *args;
  1340. size_t n_args = mp_parse_node_extract_list(&pn_range_args, PN_arglist, &args);
  1341. mp_parse_node_t pn_range_start;
  1342. mp_parse_node_t pn_range_end;
  1343. mp_parse_node_t pn_range_step;
  1344. bool optimize = false;
  1345. if (1 <= n_args && n_args <= 3) {
  1346. optimize = true;
  1347. if (n_args == 1) {
  1348. pn_range_start = mp_parse_node_new_small_int(0);
  1349. pn_range_end = args[0];
  1350. pn_range_step = mp_parse_node_new_small_int(1);
  1351. } else if (n_args == 2) {
  1352. pn_range_start = args[0];
  1353. pn_range_end = args[1];
  1354. pn_range_step = mp_parse_node_new_small_int(1);
  1355. } else {
  1356. pn_range_start = args[0];
  1357. pn_range_end = args[1];
  1358. pn_range_step = args[2];
  1359. // the step must be a non-zero constant integer to do the optimisation
  1360. if (!MP_PARSE_NODE_IS_SMALL_INT(pn_range_step)
  1361. || MP_PARSE_NODE_LEAF_SMALL_INT(pn_range_step) == 0) {
  1362. optimize = false;
  1363. }
  1364. }
  1365. // arguments must be able to be compiled as standard expressions
  1366. if (optimize && MP_PARSE_NODE_IS_STRUCT(pn_range_start)) {
  1367. int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_range_start);
  1368. if (k == PN_arglist_star || k == PN_arglist_dbl_star || k == PN_argument) {
  1369. optimize = false;
  1370. }
  1371. }
  1372. if (optimize && MP_PARSE_NODE_IS_STRUCT(pn_range_end)) {
  1373. int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_range_end);
  1374. if (k == PN_arglist_star || k == PN_arglist_dbl_star || k == PN_argument) {
  1375. optimize = false;
  1376. }
  1377. }
  1378. }
  1379. if (optimize) {
  1380. compile_for_stmt_optimised_range(comp, pns->nodes[0], pn_range_start, pn_range_end, pn_range_step, pns->nodes[2], pns->nodes[3]);
  1381. return;
  1382. }
  1383. }
  1384. }
  1385. START_BREAK_CONTINUE_BLOCK
  1386. comp->break_label |= MP_EMIT_BREAK_FROM_FOR;
  1387. uint pop_label = comp_next_label(comp);
  1388. compile_node(comp, pns->nodes[1]); // iterator
  1389. EMIT_ARG(get_iter, true);
  1390. EMIT_ARG(label_assign, continue_label);
  1391. EMIT_ARG(for_iter, pop_label);
  1392. c_assign(comp, pns->nodes[0], ASSIGN_STORE); // variable
  1393. compile_node(comp, pns->nodes[2]); // body
  1394. if (!EMIT(last_emit_was_return_value)) {
  1395. EMIT_ARG(jump, continue_label);
  1396. }
  1397. EMIT_ARG(label_assign, pop_label);
  1398. EMIT(for_iter_end);
  1399. // break/continue apply to outer loop (if any) in the else block
  1400. END_BREAK_CONTINUE_BLOCK
  1401. compile_node(comp, pns->nodes[3]); // else (may be empty)
  1402. EMIT_ARG(label_assign, break_label);
  1403. }
  1404. STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_except, mp_parse_node_t *pn_excepts, mp_parse_node_t pn_else) {
  1405. // setup code
  1406. uint l1 = comp_next_label(comp);
  1407. uint success_label = comp_next_label(comp);
  1408. compile_increase_except_level(comp, l1, MP_EMIT_SETUP_BLOCK_EXCEPT);
  1409. compile_node(comp, pn_body); // body
  1410. EMIT_ARG(pop_except_jump, success_label, false); // jump over exception handler
  1411. EMIT_ARG(label_assign, l1); // start of exception handler
  1412. EMIT(start_except_handler);
  1413. // at this point the top of the stack contains the exception instance that was raised
  1414. uint l2 = comp_next_label(comp);
  1415. for (int i = 0; i < n_except; i++) {
  1416. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_excepts[i], PN_try_stmt_except)); // should be
  1417. mp_parse_node_struct_t *pns_except = (mp_parse_node_struct_t *)pn_excepts[i];
  1418. qstr qstr_exception_local = 0;
  1419. uint end_finally_label = comp_next_label(comp);
  1420. #if MICROPY_PY_SYS_SETTRACE
  1421. EMIT_ARG(set_source_line, pns_except->source_line);
  1422. #endif
  1423. if (MP_PARSE_NODE_IS_NULL(pns_except->nodes[0])) {
  1424. // this is a catch all exception handler
  1425. if (i + 1 != n_except) {
  1426. compile_syntax_error(comp, pn_excepts[i], MP_ERROR_TEXT("default 'except' must be last"));
  1427. compile_decrease_except_level(comp);
  1428. return;
  1429. }
  1430. } else {
  1431. // this exception handler requires a match to a certain type of exception
  1432. mp_parse_node_t pns_exception_expr = pns_except->nodes[0];
  1433. if (MP_PARSE_NODE_IS_STRUCT(pns_exception_expr)) {
  1434. mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pns_exception_expr;
  1435. if (MP_PARSE_NODE_STRUCT_KIND(pns3) == PN_try_stmt_as_name) {
  1436. // handler binds the exception to a local
  1437. pns_exception_expr = pns3->nodes[0];
  1438. qstr_exception_local = MP_PARSE_NODE_LEAF_ARG(pns3->nodes[1]);
  1439. }
  1440. }
  1441. EMIT(dup_top);
  1442. compile_node(comp, pns_exception_expr);
  1443. EMIT_ARG(binary_op, MP_BINARY_OP_EXCEPTION_MATCH);
  1444. EMIT_ARG(pop_jump_if, false, end_finally_label);
  1445. }
  1446. // either discard or store the exception instance
  1447. if (qstr_exception_local == 0) {
  1448. EMIT(pop_top);
  1449. } else {
  1450. compile_store_id(comp, qstr_exception_local);
  1451. }
  1452. // If the exception is bound to a variable <e> then the <body> of the
  1453. // exception handler is wrapped in a try-finally so that the name <e> can
  1454. // be deleted (per Python semantics) even if the <body> has an exception.
  1455. // In such a case the generated code for the exception handler is:
  1456. // try:
  1457. // <body>
  1458. // finally:
  1459. // <e> = None
  1460. // del <e>
  1461. uint l3 = 0;
  1462. if (qstr_exception_local != 0) {
  1463. l3 = comp_next_label(comp);
  1464. compile_increase_except_level(comp, l3, MP_EMIT_SETUP_BLOCK_FINALLY);
  1465. }
  1466. compile_node(comp, pns_except->nodes[1]); // the <body>
  1467. if (qstr_exception_local != 0) {
  1468. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  1469. EMIT_ARG(label_assign, l3);
  1470. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  1471. compile_store_id(comp, qstr_exception_local);
  1472. compile_delete_id(comp, qstr_exception_local);
  1473. compile_decrease_except_level(comp);
  1474. }
  1475. EMIT_ARG(pop_except_jump, l2, true);
  1476. EMIT_ARG(label_assign, end_finally_label);
  1477. EMIT_ARG(adjust_stack_size, 1); // stack adjust for the exception instance
  1478. }
  1479. compile_decrease_except_level(comp);
  1480. EMIT(end_except_handler);
  1481. EMIT_ARG(label_assign, success_label);
  1482. compile_node(comp, pn_else); // else block, can be null
  1483. EMIT_ARG(label_assign, l2);
  1484. }
  1485. STATIC void compile_try_finally(compiler_t *comp, mp_parse_node_t pn_body, int n_except, mp_parse_node_t *pn_except, mp_parse_node_t pn_else, mp_parse_node_t pn_finally) {
  1486. uint l_finally_block = comp_next_label(comp);
  1487. compile_increase_except_level(comp, l_finally_block, MP_EMIT_SETUP_BLOCK_FINALLY);
  1488. if (n_except == 0) {
  1489. assert(MP_PARSE_NODE_IS_NULL(pn_else));
  1490. EMIT_ARG(adjust_stack_size, 3); // stack adjust for possible UNWIND_JUMP state
  1491. compile_node(comp, pn_body);
  1492. EMIT_ARG(adjust_stack_size, -3);
  1493. } else {
  1494. compile_try_except(comp, pn_body, n_except, pn_except, pn_else);
  1495. }
  1496. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  1497. EMIT_ARG(label_assign, l_finally_block);
  1498. compile_node(comp, pn_finally);
  1499. compile_decrease_except_level(comp);
  1500. }
  1501. STATIC void compile_try_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1502. assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should be
  1503. {
  1504. mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1];
  1505. if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_try_stmt_finally) {
  1506. // just try-finally
  1507. compile_try_finally(comp, pns->nodes[0], 0, NULL, MP_PARSE_NODE_NULL, pns2->nodes[0]);
  1508. } else if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_try_stmt_except_and_more) {
  1509. // try-except and possibly else and/or finally
  1510. mp_parse_node_t *pn_excepts;
  1511. size_t n_except = mp_parse_node_extract_list(&pns2->nodes[0], PN_try_stmt_except_list, &pn_excepts);
  1512. if (MP_PARSE_NODE_IS_NULL(pns2->nodes[2])) {
  1513. // no finally
  1514. compile_try_except(comp, pns->nodes[0], n_except, pn_excepts, pns2->nodes[1]);
  1515. } else {
  1516. // have finally
  1517. compile_try_finally(comp, pns->nodes[0], n_except, pn_excepts, pns2->nodes[1], ((mp_parse_node_struct_t *)pns2->nodes[2])->nodes[0]);
  1518. }
  1519. } else {
  1520. // just try-except
  1521. mp_parse_node_t *pn_excepts;
  1522. size_t n_except = mp_parse_node_extract_list(&pns->nodes[1], PN_try_stmt_except_list, &pn_excepts);
  1523. compile_try_except(comp, pns->nodes[0], n_except, pn_excepts, MP_PARSE_NODE_NULL);
  1524. }
  1525. }
  1526. }
  1527. STATIC void compile_with_stmt_helper(compiler_t *comp, size_t n, mp_parse_node_t *nodes, mp_parse_node_t body) {
  1528. if (n == 0) {
  1529. // no more pre-bits, compile the body of the with
  1530. compile_node(comp, body);
  1531. } else {
  1532. uint l_end = comp_next_label(comp);
  1533. if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) {
  1534. // this pre-bit is of the form "a as b"
  1535. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0];
  1536. compile_node(comp, pns->nodes[0]);
  1537. compile_increase_except_level(comp, l_end, MP_EMIT_SETUP_BLOCK_WITH);
  1538. c_assign(comp, pns->nodes[1], ASSIGN_STORE);
  1539. } else {
  1540. // this pre-bit is just an expression
  1541. compile_node(comp, nodes[0]);
  1542. compile_increase_except_level(comp, l_end, MP_EMIT_SETUP_BLOCK_WITH);
  1543. EMIT(pop_top);
  1544. }
  1545. // compile additional pre-bits and the body
  1546. compile_with_stmt_helper(comp, n - 1, nodes + 1, body);
  1547. // finish this with block
  1548. EMIT_ARG(with_cleanup, l_end);
  1549. reserve_labels_for_native(comp, 3); // used by native's with_cleanup
  1550. compile_decrease_except_level(comp);
  1551. }
  1552. }
  1553. STATIC void compile_with_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1554. // get the nodes for the pre-bit of the with (the a as b, c as d, ... bit)
  1555. mp_parse_node_t *nodes;
  1556. size_t n = mp_parse_node_extract_list(&pns->nodes[0], PN_with_stmt_list, &nodes);
  1557. assert(n > 0);
  1558. // compile in a nested fashion
  1559. compile_with_stmt_helper(comp, n, nodes, pns->nodes[1]);
  1560. }
  1561. STATIC void compile_yield_from(compiler_t *comp) {
  1562. EMIT_ARG(get_iter, false);
  1563. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  1564. EMIT_ARG(yield, MP_EMIT_YIELD_FROM);
  1565. reserve_labels_for_native(comp, 3);
  1566. }
  1567. #if MICROPY_PY_ASYNC_AWAIT
  1568. STATIC void compile_await_object_method(compiler_t *comp, qstr method) {
  1569. EMIT_ARG(load_method, method, false);
  1570. EMIT_ARG(call_method, 0, 0, 0);
  1571. compile_yield_from(comp);
  1572. }
  1573. STATIC void compile_async_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1574. // comp->break_label |= MP_EMIT_BREAK_FROM_FOR;
  1575. qstr context = MP_PARSE_NODE_LEAF_ARG(pns->nodes[1]);
  1576. uint while_else_label = comp_next_label(comp);
  1577. uint try_exception_label = comp_next_label(comp);
  1578. uint try_else_label = comp_next_label(comp);
  1579. uint try_finally_label = comp_next_label(comp);
  1580. compile_node(comp, pns->nodes[1]); // iterator
  1581. EMIT_ARG(load_method, MP_QSTR___aiter__, false);
  1582. EMIT_ARG(call_method, 0, 0, 0);
  1583. compile_store_id(comp, context);
  1584. START_BREAK_CONTINUE_BLOCK
  1585. EMIT_ARG(label_assign, continue_label);
  1586. compile_increase_except_level(comp, try_exception_label, MP_EMIT_SETUP_BLOCK_EXCEPT);
  1587. compile_load_id(comp, context);
  1588. compile_await_object_method(comp, MP_QSTR___anext__);
  1589. c_assign(comp, pns->nodes[0], ASSIGN_STORE); // variable
  1590. EMIT_ARG(pop_except_jump, try_else_label, false);
  1591. EMIT_ARG(label_assign, try_exception_label);
  1592. EMIT(start_except_handler);
  1593. EMIT(dup_top);
  1594. EMIT_LOAD_GLOBAL(MP_QSTR_StopAsyncIteration);
  1595. EMIT_ARG(binary_op, MP_BINARY_OP_EXCEPTION_MATCH);
  1596. EMIT_ARG(pop_jump_if, false, try_finally_label);
  1597. EMIT(pop_top); // pop exception instance
  1598. EMIT_ARG(pop_except_jump, while_else_label, true);
  1599. EMIT_ARG(label_assign, try_finally_label);
  1600. EMIT_ARG(adjust_stack_size, 1); // if we jump here, the exc is on the stack
  1601. compile_decrease_except_level(comp);
  1602. EMIT(end_except_handler);
  1603. EMIT_ARG(label_assign, try_else_label);
  1604. compile_node(comp, pns->nodes[2]); // body
  1605. EMIT_ARG(jump, continue_label);
  1606. // break/continue apply to outer loop (if any) in the else block
  1607. END_BREAK_CONTINUE_BLOCK
  1608. EMIT_ARG(label_assign, while_else_label);
  1609. compile_node(comp, pns->nodes[3]); // else
  1610. EMIT_ARG(label_assign, break_label);
  1611. }
  1612. STATIC void compile_async_with_stmt_helper(compiler_t *comp, size_t n, mp_parse_node_t *nodes, mp_parse_node_t body) {
  1613. if (n == 0) {
  1614. // no more pre-bits, compile the body of the with
  1615. compile_node(comp, body);
  1616. } else {
  1617. uint l_finally_block = comp_next_label(comp);
  1618. uint l_aexit_no_exc = comp_next_label(comp);
  1619. uint l_ret_unwind_jump = comp_next_label(comp);
  1620. uint l_end = comp_next_label(comp);
  1621. if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) {
  1622. // this pre-bit is of the form "a as b"
  1623. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0];
  1624. compile_node(comp, pns->nodes[0]);
  1625. EMIT(dup_top);
  1626. compile_await_object_method(comp, MP_QSTR___aenter__);
  1627. c_assign(comp, pns->nodes[1], ASSIGN_STORE);
  1628. } else {
  1629. // this pre-bit is just an expression
  1630. compile_node(comp, nodes[0]);
  1631. EMIT(dup_top);
  1632. compile_await_object_method(comp, MP_QSTR___aenter__);
  1633. EMIT(pop_top);
  1634. }
  1635. // To keep the Python stack size down, and because we can't access values on
  1636. // this stack further down than 3 elements (via rot_three), we don't preload
  1637. // __aexit__ (as per normal with) but rather wait until we need it below.
  1638. // Start the try-finally statement
  1639. compile_increase_except_level(comp, l_finally_block, MP_EMIT_SETUP_BLOCK_FINALLY);
  1640. // Compile any additional pre-bits of the "async with", and also the body
  1641. EMIT_ARG(adjust_stack_size, 3); // stack adjust for possible UNWIND_JUMP state
  1642. compile_async_with_stmt_helper(comp, n - 1, nodes + 1, body);
  1643. EMIT_ARG(adjust_stack_size, -3);
  1644. // We have now finished the "try" block and fall through to the "finally"
  1645. // At this point, after the with body has executed, we have 3 cases:
  1646. // 1. no exception, we just fall through to this point; stack: (..., ctx_mgr)
  1647. // 2. exception propagating out, we get to the finally block; stack: (..., ctx_mgr, exc)
  1648. // 3. return or unwind jump, we get to the finally block; stack: (..., ctx_mgr, X, INT)
  1649. // Handle case 1: call __aexit__
  1650. // Stack: (..., ctx_mgr)
  1651. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // to tell end_finally there's no exception
  1652. EMIT(rot_two);
  1653. EMIT_ARG(jump, l_aexit_no_exc); // jump to code below to call __aexit__
  1654. // Start of "finally" block
  1655. // At this point we have case 2 or 3, we detect which one by the TOS being an exception or not
  1656. EMIT_ARG(label_assign, l_finally_block);
  1657. // Detect if TOS an exception or not
  1658. EMIT(dup_top);
  1659. EMIT_LOAD_GLOBAL(MP_QSTR_BaseException);
  1660. EMIT_ARG(binary_op, MP_BINARY_OP_EXCEPTION_MATCH);
  1661. EMIT_ARG(pop_jump_if, false, l_ret_unwind_jump); // if not an exception then we have case 3
  1662. // Handle case 2: call __aexit__ and either swallow or re-raise the exception
  1663. // Stack: (..., ctx_mgr, exc)
  1664. EMIT(dup_top);
  1665. EMIT(rot_three);
  1666. EMIT(rot_two);
  1667. EMIT_ARG(load_method, MP_QSTR___aexit__, false);
  1668. EMIT(rot_three);
  1669. EMIT(rot_three);
  1670. EMIT(dup_top);
  1671. #if MICROPY_CPYTHON_COMPAT
  1672. EMIT_ARG(attr, MP_QSTR___class__, MP_EMIT_ATTR_LOAD); // get type(exc)
  1673. #else
  1674. compile_load_id(comp, MP_QSTR_type);
  1675. EMIT(rot_two);
  1676. EMIT_ARG(call_function, 1, 0, 0); // get type(exc)
  1677. #endif
  1678. EMIT(rot_two);
  1679. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // dummy traceback value
  1680. // Stack: (..., exc, __aexit__, ctx_mgr, type(exc), exc, None)
  1681. EMIT_ARG(call_method, 3, 0, 0);
  1682. compile_yield_from(comp);
  1683. EMIT_ARG(pop_jump_if, false, l_end);
  1684. EMIT(pop_top); // pop exception
  1685. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); // replace with None to swallow exception
  1686. EMIT_ARG(jump, l_end);
  1687. EMIT_ARG(adjust_stack_size, 2);
  1688. // Handle case 3: call __aexit__
  1689. // Stack: (..., ctx_mgr, X, INT)
  1690. EMIT_ARG(label_assign, l_ret_unwind_jump);
  1691. EMIT(rot_three);
  1692. EMIT(rot_three);
  1693. EMIT_ARG(label_assign, l_aexit_no_exc);
  1694. EMIT_ARG(load_method, MP_QSTR___aexit__, false);
  1695. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  1696. EMIT(dup_top);
  1697. EMIT(dup_top);
  1698. EMIT_ARG(call_method, 3, 0, 0);
  1699. compile_yield_from(comp);
  1700. EMIT(pop_top);
  1701. EMIT_ARG(adjust_stack_size, -1);
  1702. // End of "finally" block
  1703. // Stack can have one of three configurations:
  1704. // a. (..., None) - from either case 1, or case 2 with swallowed exception
  1705. // b. (..., exc) - from case 2 with re-raised exception
  1706. // c. (..., X, INT) - from case 3
  1707. EMIT_ARG(label_assign, l_end);
  1708. compile_decrease_except_level(comp);
  1709. }
  1710. }
  1711. STATIC void compile_async_with_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1712. // get the nodes for the pre-bit of the with (the a as b, c as d, ... bit)
  1713. mp_parse_node_t *nodes;
  1714. size_t n = mp_parse_node_extract_list(&pns->nodes[0], PN_with_stmt_list, &nodes);
  1715. assert(n > 0);
  1716. // compile in a nested fashion
  1717. compile_async_with_stmt_helper(comp, n, nodes, pns->nodes[1]);
  1718. }
  1719. STATIC void compile_async_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1720. assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[0]));
  1721. mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns->nodes[0];
  1722. if (MP_PARSE_NODE_STRUCT_KIND(pns0) == PN_funcdef) {
  1723. // async def
  1724. compile_funcdef(comp, pns0);
  1725. scope_t *fscope = (scope_t *)pns0->nodes[4];
  1726. fscope->scope_flags |= MP_SCOPE_FLAG_GENERATOR;
  1727. } else if (MP_PARSE_NODE_STRUCT_KIND(pns0) == PN_for_stmt) {
  1728. // async for
  1729. compile_async_for_stmt(comp, pns0);
  1730. } else {
  1731. // async with
  1732. assert(MP_PARSE_NODE_STRUCT_KIND(pns0) == PN_with_stmt);
  1733. compile_async_with_stmt(comp, pns0);
  1734. }
  1735. }
  1736. #endif
  1737. STATIC void compile_expr_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1738. mp_parse_node_t pn_rhs = pns->nodes[1];
  1739. if (MP_PARSE_NODE_IS_NULL(pn_rhs)) {
  1740. if (comp->is_repl && comp->scope_cur->kind == SCOPE_MODULE) {
  1741. // for REPL, evaluate then print the expression
  1742. compile_load_id(comp, MP_QSTR___repl_print__);
  1743. compile_node(comp, pns->nodes[0]);
  1744. EMIT_ARG(call_function, 1, 0, 0);
  1745. EMIT(pop_top);
  1746. } else {
  1747. // for non-REPL, evaluate then discard the expression
  1748. if ((MP_PARSE_NODE_IS_LEAF(pns->nodes[0]) && !MP_PARSE_NODE_IS_ID(pns->nodes[0]))
  1749. || MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_const_object)) {
  1750. // do nothing with a lonely constant
  1751. } else {
  1752. compile_node(comp, pns->nodes[0]); // just an expression
  1753. EMIT(pop_top); // discard last result since this is a statement and leaves nothing on the stack
  1754. }
  1755. }
  1756. } else if (MP_PARSE_NODE_IS_STRUCT(pn_rhs)) {
  1757. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pn_rhs;
  1758. int kind = MP_PARSE_NODE_STRUCT_KIND(pns1);
  1759. if (kind == PN_annassign) {
  1760. // the annotation is in pns1->nodes[0] and is ignored
  1761. if (MP_PARSE_NODE_IS_NULL(pns1->nodes[1])) {
  1762. // an annotation of the form "x: y"
  1763. // inside a function this declares "x" as a local
  1764. if (comp->scope_cur->kind == SCOPE_FUNCTION) {
  1765. if (MP_PARSE_NODE_IS_ID(pns->nodes[0])) {
  1766. qstr lhs = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]);
  1767. scope_find_or_add_id(comp->scope_cur, lhs, ID_INFO_KIND_LOCAL);
  1768. }
  1769. }
  1770. } else {
  1771. // an assigned annotation of the form "x: y = z"
  1772. pn_rhs = pns1->nodes[1];
  1773. goto plain_assign;
  1774. }
  1775. } else if (kind == PN_expr_stmt_augassign) {
  1776. c_assign(comp, pns->nodes[0], ASSIGN_AUG_LOAD); // lhs load for aug assign
  1777. compile_node(comp, pns1->nodes[1]); // rhs
  1778. assert(MP_PARSE_NODE_IS_TOKEN(pns1->nodes[0]));
  1779. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]);
  1780. mp_binary_op_t op = MP_BINARY_OP_INPLACE_OR + (tok - MP_TOKEN_DEL_PIPE_EQUAL);
  1781. EMIT_ARG(binary_op, op);
  1782. c_assign(comp, pns->nodes[0], ASSIGN_AUG_STORE); // lhs store for aug assign
  1783. } else if (kind == PN_expr_stmt_assign_list) {
  1784. int rhs = MP_PARSE_NODE_STRUCT_NUM_NODES(pns1) - 1;
  1785. compile_node(comp, pns1->nodes[rhs]); // rhs
  1786. // following CPython, we store left-most first
  1787. if (rhs > 0) {
  1788. EMIT(dup_top);
  1789. }
  1790. c_assign(comp, pns->nodes[0], ASSIGN_STORE); // lhs store
  1791. for (int i = 0; i < rhs; i++) {
  1792. if (i + 1 < rhs) {
  1793. EMIT(dup_top);
  1794. }
  1795. c_assign(comp, pns1->nodes[i], ASSIGN_STORE); // middle store
  1796. }
  1797. } else {
  1798. plain_assign:
  1799. #if MICROPY_COMP_DOUBLE_TUPLE_ASSIGN
  1800. if (MP_PARSE_NODE_IS_STRUCT_KIND(pn_rhs, PN_testlist_star_expr)
  1801. && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_star_expr)) {
  1802. mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns->nodes[0];
  1803. pns1 = (mp_parse_node_struct_t *)pn_rhs;
  1804. uint32_t n_pns0 = MP_PARSE_NODE_STRUCT_NUM_NODES(pns0);
  1805. // Can only optimise a tuple-to-tuple assignment when all of the following hold:
  1806. // - equal number of items in LHS and RHS tuples
  1807. // - 2 or 3 items in the tuples
  1808. // - there are no star expressions in the LHS tuple
  1809. if (n_pns0 == MP_PARSE_NODE_STRUCT_NUM_NODES(pns1)
  1810. && (n_pns0 == 2
  1811. #if MICROPY_COMP_TRIPLE_TUPLE_ASSIGN
  1812. || n_pns0 == 3
  1813. #endif
  1814. )
  1815. && !MP_PARSE_NODE_IS_STRUCT_KIND(pns0->nodes[0], PN_star_expr)
  1816. && !MP_PARSE_NODE_IS_STRUCT_KIND(pns0->nodes[1], PN_star_expr)
  1817. #if MICROPY_COMP_TRIPLE_TUPLE_ASSIGN
  1818. && (n_pns0 == 2 || !MP_PARSE_NODE_IS_STRUCT_KIND(pns0->nodes[2], PN_star_expr))
  1819. #endif
  1820. ) {
  1821. // Optimisation for a, b = c, d or a, b, c = d, e, f
  1822. compile_node(comp, pns1->nodes[0]); // rhs
  1823. compile_node(comp, pns1->nodes[1]); // rhs
  1824. #if MICROPY_COMP_TRIPLE_TUPLE_ASSIGN
  1825. if (n_pns0 == 3) {
  1826. compile_node(comp, pns1->nodes[2]); // rhs
  1827. EMIT(rot_three);
  1828. }
  1829. #endif
  1830. EMIT(rot_two);
  1831. c_assign(comp, pns0->nodes[0], ASSIGN_STORE); // lhs store
  1832. c_assign(comp, pns0->nodes[1], ASSIGN_STORE); // lhs store
  1833. #if MICROPY_COMP_TRIPLE_TUPLE_ASSIGN
  1834. if (n_pns0 == 3) {
  1835. c_assign(comp, pns0->nodes[2], ASSIGN_STORE); // lhs store
  1836. }
  1837. #endif
  1838. return;
  1839. }
  1840. }
  1841. #endif
  1842. compile_node(comp, pn_rhs); // rhs
  1843. c_assign(comp, pns->nodes[0], ASSIGN_STORE); // lhs store
  1844. }
  1845. } else {
  1846. goto plain_assign;
  1847. }
  1848. }
  1849. STATIC void compile_test_if_expr(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1850. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_test_if_else));
  1851. mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t *)pns->nodes[1];
  1852. uint l_fail = comp_next_label(comp);
  1853. uint l_end = comp_next_label(comp);
  1854. c_if_cond(comp, pns_test_if_else->nodes[0], false, l_fail); // condition
  1855. compile_node(comp, pns->nodes[0]); // success value
  1856. EMIT_ARG(jump, l_end);
  1857. EMIT_ARG(label_assign, l_fail);
  1858. EMIT_ARG(adjust_stack_size, -1); // adjust stack size
  1859. compile_node(comp, pns_test_if_else->nodes[1]); // failure value
  1860. EMIT_ARG(label_assign, l_end);
  1861. }
  1862. STATIC void compile_lambdef(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1863. if (comp->pass == MP_PASS_SCOPE) {
  1864. // create a new scope for this lambda
  1865. scope_t *s = scope_new_and_link(comp, SCOPE_LAMBDA, (mp_parse_node_t)pns, comp->scope_cur->emit_options);
  1866. // store the lambda scope so the compiling function (this one) can use it at each pass
  1867. pns->nodes[2] = (mp_parse_node_t)s;
  1868. }
  1869. // get the scope for this lambda
  1870. scope_t *this_scope = (scope_t *)pns->nodes[2];
  1871. // compile the lambda definition
  1872. compile_funcdef_lambdef(comp, this_scope, pns->nodes[0], PN_varargslist);
  1873. }
  1874. #if MICROPY_PY_ASSIGN_EXPR
  1875. STATIC void compile_namedexpr_helper(compiler_t *comp, mp_parse_node_t pn_name, mp_parse_node_t pn_expr) {
  1876. if (!MP_PARSE_NODE_IS_ID(pn_name)) {
  1877. compile_syntax_error(comp, (mp_parse_node_t)pn_name, MP_ERROR_TEXT("can't assign to expression"));
  1878. }
  1879. compile_node(comp, pn_expr);
  1880. EMIT(dup_top);
  1881. scope_t *old_scope = comp->scope_cur;
  1882. if (SCOPE_IS_COMP_LIKE(comp->scope_cur->kind)) {
  1883. // Use parent's scope for assigned value so it can "escape"
  1884. comp->scope_cur = comp->scope_cur->parent;
  1885. }
  1886. compile_store_id(comp, MP_PARSE_NODE_LEAF_ARG(pn_name));
  1887. comp->scope_cur = old_scope;
  1888. }
  1889. STATIC void compile_namedexpr(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1890. compile_namedexpr_helper(comp, pns->nodes[0], pns->nodes[1]);
  1891. }
  1892. #endif
  1893. STATIC void compile_or_and_test(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1894. bool cond = MP_PARSE_NODE_STRUCT_KIND(pns) == PN_or_test;
  1895. uint l_end = comp_next_label(comp);
  1896. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  1897. for (int i = 0; i < n; i += 1) {
  1898. compile_node(comp, pns->nodes[i]);
  1899. if (i + 1 < n) {
  1900. EMIT_ARG(jump_if_or_pop, cond, l_end);
  1901. }
  1902. }
  1903. EMIT_ARG(label_assign, l_end);
  1904. }
  1905. STATIC void compile_not_test_2(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1906. compile_node(comp, pns->nodes[0]);
  1907. EMIT_ARG(unary_op, MP_UNARY_OP_NOT);
  1908. }
  1909. STATIC void compile_comparison(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1910. int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  1911. compile_node(comp, pns->nodes[0]);
  1912. bool multi = (num_nodes > 3);
  1913. uint l_fail = 0;
  1914. if (multi) {
  1915. l_fail = comp_next_label(comp);
  1916. }
  1917. for (int i = 1; i + 1 < num_nodes; i += 2) {
  1918. compile_node(comp, pns->nodes[i + 1]);
  1919. if (i + 2 < num_nodes) {
  1920. EMIT(dup_top);
  1921. EMIT(rot_three);
  1922. }
  1923. if (MP_PARSE_NODE_IS_TOKEN(pns->nodes[i])) {
  1924. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(pns->nodes[i]);
  1925. mp_binary_op_t op;
  1926. if (tok == MP_TOKEN_KW_IN) {
  1927. op = MP_BINARY_OP_IN;
  1928. } else {
  1929. op = MP_BINARY_OP_LESS + (tok - MP_TOKEN_OP_LESS);
  1930. }
  1931. EMIT_ARG(binary_op, op);
  1932. } else {
  1933. assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[i])); // should be
  1934. mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[i];
  1935. int kind = MP_PARSE_NODE_STRUCT_KIND(pns2);
  1936. if (kind == PN_comp_op_not_in) {
  1937. EMIT_ARG(binary_op, MP_BINARY_OP_NOT_IN);
  1938. } else {
  1939. assert(kind == PN_comp_op_is); // should be
  1940. if (MP_PARSE_NODE_IS_NULL(pns2->nodes[0])) {
  1941. EMIT_ARG(binary_op, MP_BINARY_OP_IS);
  1942. } else {
  1943. EMIT_ARG(binary_op, MP_BINARY_OP_IS_NOT);
  1944. }
  1945. }
  1946. }
  1947. if (i + 2 < num_nodes) {
  1948. EMIT_ARG(jump_if_or_pop, false, l_fail);
  1949. }
  1950. }
  1951. if (multi) {
  1952. uint l_end = comp_next_label(comp);
  1953. EMIT_ARG(jump, l_end);
  1954. EMIT_ARG(label_assign, l_fail);
  1955. EMIT_ARG(adjust_stack_size, 1);
  1956. EMIT(rot_two);
  1957. EMIT(pop_top);
  1958. EMIT_ARG(label_assign, l_end);
  1959. }
  1960. }
  1961. STATIC void compile_star_expr(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1962. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("*x must be assignment target"));
  1963. }
  1964. STATIC void compile_binary_op(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1965. MP_STATIC_ASSERT(MP_BINARY_OP_OR + PN_xor_expr - PN_expr == MP_BINARY_OP_XOR);
  1966. MP_STATIC_ASSERT(MP_BINARY_OP_OR + PN_and_expr - PN_expr == MP_BINARY_OP_AND);
  1967. mp_binary_op_t binary_op = MP_BINARY_OP_OR + MP_PARSE_NODE_STRUCT_KIND(pns) - PN_expr;
  1968. int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  1969. compile_node(comp, pns->nodes[0]);
  1970. for (int i = 1; i < num_nodes; ++i) {
  1971. compile_node(comp, pns->nodes[i]);
  1972. EMIT_ARG(binary_op, binary_op);
  1973. }
  1974. }
  1975. STATIC void compile_term(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1976. int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  1977. compile_node(comp, pns->nodes[0]);
  1978. for (int i = 1; i + 1 < num_nodes; i += 2) {
  1979. compile_node(comp, pns->nodes[i + 1]);
  1980. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(pns->nodes[i]);
  1981. mp_binary_op_t op = MP_BINARY_OP_LSHIFT + (tok - MP_TOKEN_OP_DBL_LESS);
  1982. EMIT_ARG(binary_op, op);
  1983. }
  1984. }
  1985. STATIC void compile_factor_2(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1986. compile_node(comp, pns->nodes[1]);
  1987. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]);
  1988. mp_unary_op_t op;
  1989. if (tok == MP_TOKEN_OP_TILDE) {
  1990. op = MP_UNARY_OP_INVERT;
  1991. } else {
  1992. assert(tok == MP_TOKEN_OP_PLUS || tok == MP_TOKEN_OP_MINUS);
  1993. op = MP_UNARY_OP_POSITIVE + (tok - MP_TOKEN_OP_PLUS);
  1994. }
  1995. EMIT_ARG(unary_op, op);
  1996. }
  1997. STATIC void compile_atom_expr_normal(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1998. // compile the subject of the expression
  1999. compile_node(comp, pns->nodes[0]);
  2000. // compile_atom_expr_await may call us with a NULL node
  2001. if (MP_PARSE_NODE_IS_NULL(pns->nodes[1])) {
  2002. return;
  2003. }
  2004. // get the array of trailers (known to be an array of PARSE_NODE_STRUCT)
  2005. size_t num_trail = 1;
  2006. mp_parse_node_struct_t **pns_trail = (mp_parse_node_struct_t **)&pns->nodes[1];
  2007. if (MP_PARSE_NODE_STRUCT_KIND(pns_trail[0]) == PN_atom_expr_trailers) {
  2008. num_trail = MP_PARSE_NODE_STRUCT_NUM_NODES(pns_trail[0]);
  2009. pns_trail = (mp_parse_node_struct_t **)&pns_trail[0]->nodes[0];
  2010. }
  2011. // the current index into the array of trailers
  2012. size_t i = 0;
  2013. // handle special super() call
  2014. if (comp->scope_cur->kind == SCOPE_FUNCTION
  2015. && MP_PARSE_NODE_IS_ID(pns->nodes[0])
  2016. && MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]) == MP_QSTR_super
  2017. && MP_PARSE_NODE_STRUCT_KIND(pns_trail[0]) == PN_trailer_paren
  2018. && MP_PARSE_NODE_IS_NULL(pns_trail[0]->nodes[0])) {
  2019. // at this point we have matched "super()" within a function
  2020. // load the class for super to search for a parent
  2021. compile_load_id(comp, MP_QSTR___class__);
  2022. // look for first argument to function (assumes it's "self")
  2023. bool found = false;
  2024. id_info_t *id = &comp->scope_cur->id_info[0];
  2025. for (size_t n = comp->scope_cur->id_info_len; n > 0; --n, ++id) {
  2026. if (id->flags & ID_FLAG_IS_PARAM) {
  2027. // first argument found; load it
  2028. compile_load_id(comp, id->qst);
  2029. found = true;
  2030. break;
  2031. }
  2032. }
  2033. if (!found) {
  2034. compile_syntax_error(comp, (mp_parse_node_t)pns_trail[0],
  2035. MP_ERROR_TEXT("super() can't find self")); // really a TypeError
  2036. return;
  2037. }
  2038. if (num_trail >= 3
  2039. && MP_PARSE_NODE_STRUCT_KIND(pns_trail[1]) == PN_trailer_period
  2040. && MP_PARSE_NODE_STRUCT_KIND(pns_trail[2]) == PN_trailer_paren) {
  2041. // optimisation for method calls super().f(...), to eliminate heap allocation
  2042. mp_parse_node_struct_t *pns_period = pns_trail[1];
  2043. mp_parse_node_struct_t *pns_paren = pns_trail[2];
  2044. EMIT_ARG(load_method, MP_PARSE_NODE_LEAF_ARG(pns_period->nodes[0]), true);
  2045. compile_trailer_paren_helper(comp, pns_paren->nodes[0], true, 0);
  2046. i = 3;
  2047. } else {
  2048. // a super() call
  2049. EMIT_ARG(call_function, 2, 0, 0);
  2050. i = 1;
  2051. }
  2052. #if MICROPY_COMP_CONST_LITERAL && MICROPY_PY_COLLECTIONS_ORDEREDDICT
  2053. // handle special OrderedDict constructor
  2054. } else if (MP_PARSE_NODE_IS_ID(pns->nodes[0])
  2055. && MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]) == MP_QSTR_OrderedDict
  2056. && MP_PARSE_NODE_STRUCT_KIND(pns_trail[0]) == PN_trailer_paren
  2057. && MP_PARSE_NODE_IS_STRUCT_KIND(pns_trail[0]->nodes[0], PN_atom_brace)) {
  2058. // at this point we have matched "OrderedDict({...})"
  2059. EMIT_ARG(call_function, 0, 0, 0);
  2060. mp_parse_node_struct_t *pns_dict = (mp_parse_node_struct_t *)pns_trail[0]->nodes[0];
  2061. compile_atom_brace_helper(comp, pns_dict, false);
  2062. i = 1;
  2063. #endif
  2064. }
  2065. // compile the remaining trailers
  2066. for (; i < num_trail; i++) {
  2067. if (i + 1 < num_trail
  2068. && MP_PARSE_NODE_STRUCT_KIND(pns_trail[i]) == PN_trailer_period
  2069. && MP_PARSE_NODE_STRUCT_KIND(pns_trail[i + 1]) == PN_trailer_paren) {
  2070. // optimisation for method calls a.f(...), following PyPy
  2071. mp_parse_node_struct_t *pns_period = pns_trail[i];
  2072. mp_parse_node_struct_t *pns_paren = pns_trail[i + 1];
  2073. EMIT_ARG(load_method, MP_PARSE_NODE_LEAF_ARG(pns_period->nodes[0]), false);
  2074. compile_trailer_paren_helper(comp, pns_paren->nodes[0], true, 0);
  2075. i += 1;
  2076. } else {
  2077. // node is one of: trailer_paren, trailer_bracket, trailer_period
  2078. compile_node(comp, (mp_parse_node_t)pns_trail[i]);
  2079. }
  2080. }
  2081. }
  2082. STATIC void compile_power(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2083. compile_generic_all_nodes(comp, pns); // 2 nodes, arguments of power
  2084. EMIT_ARG(binary_op, MP_BINARY_OP_POWER);
  2085. }
  2086. STATIC void compile_trailer_paren_helper(compiler_t *comp, mp_parse_node_t pn_arglist, bool is_method_call, int n_positional_extra) {
  2087. // function to call is on top of stack
  2088. // get the list of arguments
  2089. mp_parse_node_t *args;
  2090. size_t n_args = mp_parse_node_extract_list(&pn_arglist, PN_arglist, &args);
  2091. // compile the arguments
  2092. // Rather than calling compile_node on the list, we go through the list of args
  2093. // explicitly here so that we can count the number of arguments and give sensible
  2094. // error messages.
  2095. int n_positional = n_positional_extra;
  2096. uint n_keyword = 0;
  2097. uint star_flags = 0;
  2098. mp_parse_node_struct_t *star_args_node = NULL, *dblstar_args_node = NULL;
  2099. for (size_t i = 0; i < n_args; i++) {
  2100. if (MP_PARSE_NODE_IS_STRUCT(args[i])) {
  2101. mp_parse_node_struct_t *pns_arg = (mp_parse_node_struct_t *)args[i];
  2102. if (MP_PARSE_NODE_STRUCT_KIND(pns_arg) == PN_arglist_star) {
  2103. if (star_flags & MP_EMIT_STAR_FLAG_SINGLE) {
  2104. compile_syntax_error(comp, (mp_parse_node_t)pns_arg, MP_ERROR_TEXT("can't have multiple *x"));
  2105. return;
  2106. }
  2107. star_flags |= MP_EMIT_STAR_FLAG_SINGLE;
  2108. star_args_node = pns_arg;
  2109. } else if (MP_PARSE_NODE_STRUCT_KIND(pns_arg) == PN_arglist_dbl_star) {
  2110. if (star_flags & MP_EMIT_STAR_FLAG_DOUBLE) {
  2111. compile_syntax_error(comp, (mp_parse_node_t)pns_arg, MP_ERROR_TEXT("can't have multiple **x"));
  2112. return;
  2113. }
  2114. star_flags |= MP_EMIT_STAR_FLAG_DOUBLE;
  2115. dblstar_args_node = pns_arg;
  2116. } else if (MP_PARSE_NODE_STRUCT_KIND(pns_arg) == PN_argument) {
  2117. #if MICROPY_PY_ASSIGN_EXPR
  2118. if (MP_PARSE_NODE_IS_STRUCT_KIND(pns_arg->nodes[1], PN_argument_3)) {
  2119. compile_namedexpr_helper(comp, pns_arg->nodes[0], ((mp_parse_node_struct_t *)pns_arg->nodes[1])->nodes[0]);
  2120. n_positional++;
  2121. } else
  2122. #endif
  2123. if (!MP_PARSE_NODE_IS_STRUCT_KIND(pns_arg->nodes[1], PN_comp_for)) {
  2124. if (!MP_PARSE_NODE_IS_ID(pns_arg->nodes[0])) {
  2125. compile_syntax_error(comp, (mp_parse_node_t)pns_arg, MP_ERROR_TEXT("LHS of keyword arg must be an id"));
  2126. return;
  2127. }
  2128. EMIT_ARG(load_const_str, MP_PARSE_NODE_LEAF_ARG(pns_arg->nodes[0]));
  2129. compile_node(comp, pns_arg->nodes[1]);
  2130. n_keyword += 1;
  2131. } else {
  2132. compile_comprehension(comp, pns_arg, SCOPE_GEN_EXPR);
  2133. n_positional++;
  2134. }
  2135. } else {
  2136. goto normal_argument;
  2137. }
  2138. } else {
  2139. normal_argument:
  2140. if (star_flags) {
  2141. compile_syntax_error(comp, args[i], MP_ERROR_TEXT("non-keyword arg after */**"));
  2142. return;
  2143. }
  2144. if (n_keyword > 0) {
  2145. compile_syntax_error(comp, args[i], MP_ERROR_TEXT("non-keyword arg after keyword arg"));
  2146. return;
  2147. }
  2148. compile_node(comp, args[i]);
  2149. n_positional++;
  2150. }
  2151. }
  2152. // compile the star/double-star arguments if we had them
  2153. // if we had one but not the other then we load "null" as a place holder
  2154. if (star_flags != 0) {
  2155. if (star_args_node == NULL) {
  2156. EMIT(load_null);
  2157. } else {
  2158. compile_node(comp, star_args_node->nodes[0]);
  2159. }
  2160. if (dblstar_args_node == NULL) {
  2161. EMIT(load_null);
  2162. } else {
  2163. compile_node(comp, dblstar_args_node->nodes[0]);
  2164. }
  2165. }
  2166. // emit the function/method call
  2167. if (is_method_call) {
  2168. EMIT_ARG(call_method, n_positional, n_keyword, star_flags);
  2169. } else {
  2170. EMIT_ARG(call_function, n_positional, n_keyword, star_flags);
  2171. }
  2172. }
  2173. // pns needs to have 2 nodes, first is lhs of comprehension, second is PN_comp_for node
  2174. STATIC void compile_comprehension(compiler_t *comp, mp_parse_node_struct_t *pns, scope_kind_t kind) {
  2175. assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 2);
  2176. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_comp_for));
  2177. mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t *)pns->nodes[1];
  2178. if (comp->pass == MP_PASS_SCOPE) {
  2179. // create a new scope for this comprehension
  2180. scope_t *s = scope_new_and_link(comp, kind, (mp_parse_node_t)pns, comp->scope_cur->emit_options);
  2181. // store the comprehension scope so the compiling function (this one) can use it at each pass
  2182. pns_comp_for->nodes[3] = (mp_parse_node_t)s;
  2183. }
  2184. // get the scope for this comprehension
  2185. scope_t *this_scope = (scope_t *)pns_comp_for->nodes[3];
  2186. // compile the comprehension
  2187. close_over_variables_etc(comp, this_scope, 0, 0);
  2188. compile_node(comp, pns_comp_for->nodes[1]); // source of the iterator
  2189. if (kind == SCOPE_GEN_EXPR) {
  2190. EMIT_ARG(get_iter, false);
  2191. }
  2192. EMIT_ARG(call_function, 1, 0, 0);
  2193. }
  2194. STATIC void compile_atom_paren(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2195. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  2196. // an empty tuple
  2197. c_tuple(comp, MP_PARSE_NODE_NULL, NULL);
  2198. } else {
  2199. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp));
  2200. pns = (mp_parse_node_struct_t *)pns->nodes[0];
  2201. assert(!MP_PARSE_NODE_IS_NULL(pns->nodes[1]));
  2202. if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
  2203. mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1];
  2204. if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3b) {
  2205. // tuple of one item, with trailing comma
  2206. assert(MP_PARSE_NODE_IS_NULL(pns2->nodes[0]));
  2207. c_tuple(comp, pns->nodes[0], NULL);
  2208. } else if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3c) {
  2209. // tuple of many items
  2210. c_tuple(comp, pns->nodes[0], pns2);
  2211. } else if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_comp_for) {
  2212. // generator expression
  2213. compile_comprehension(comp, pns, SCOPE_GEN_EXPR);
  2214. } else {
  2215. // tuple with 2 items
  2216. goto tuple_with_2_items;
  2217. }
  2218. } else {
  2219. // tuple with 2 items
  2220. tuple_with_2_items:
  2221. c_tuple(comp, MP_PARSE_NODE_NULL, pns);
  2222. }
  2223. }
  2224. }
  2225. STATIC void compile_atom_bracket(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2226. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  2227. // empty list
  2228. EMIT_ARG(build, 0, MP_EMIT_BUILD_LIST);
  2229. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) {
  2230. mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[0];
  2231. if (MP_PARSE_NODE_IS_STRUCT(pns2->nodes[1])) {
  2232. mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pns2->nodes[1];
  2233. if (MP_PARSE_NODE_STRUCT_KIND(pns3) == PN_testlist_comp_3b) {
  2234. // list of one item, with trailing comma
  2235. assert(MP_PARSE_NODE_IS_NULL(pns3->nodes[0]));
  2236. compile_node(comp, pns2->nodes[0]);
  2237. EMIT_ARG(build, 1, MP_EMIT_BUILD_LIST);
  2238. } else if (MP_PARSE_NODE_STRUCT_KIND(pns3) == PN_testlist_comp_3c) {
  2239. // list of many items
  2240. compile_node(comp, pns2->nodes[0]);
  2241. compile_generic_all_nodes(comp, pns3);
  2242. EMIT_ARG(build, 1 + MP_PARSE_NODE_STRUCT_NUM_NODES(pns3), MP_EMIT_BUILD_LIST);
  2243. } else if (MP_PARSE_NODE_STRUCT_KIND(pns3) == PN_comp_for) {
  2244. // list comprehension
  2245. compile_comprehension(comp, pns2, SCOPE_LIST_COMP);
  2246. } else {
  2247. // list with 2 items
  2248. goto list_with_2_items;
  2249. }
  2250. } else {
  2251. // list with 2 items
  2252. list_with_2_items:
  2253. compile_node(comp, pns2->nodes[0]);
  2254. compile_node(comp, pns2->nodes[1]);
  2255. EMIT_ARG(build, 2, MP_EMIT_BUILD_LIST);
  2256. }
  2257. } else {
  2258. // list with 1 item
  2259. compile_node(comp, pns->nodes[0]);
  2260. EMIT_ARG(build, 1, MP_EMIT_BUILD_LIST);
  2261. }
  2262. }
  2263. STATIC void compile_atom_brace_helper(compiler_t *comp, mp_parse_node_struct_t *pns, bool create_map) {
  2264. mp_parse_node_t pn = pns->nodes[0];
  2265. if (MP_PARSE_NODE_IS_NULL(pn)) {
  2266. // empty dict
  2267. if (create_map) {
  2268. EMIT_ARG(build, 0, MP_EMIT_BUILD_MAP);
  2269. }
  2270. } else if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  2271. pns = (mp_parse_node_struct_t *)pn;
  2272. if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_dictorsetmaker_item) {
  2273. // dict with one element
  2274. if (create_map) {
  2275. EMIT_ARG(build, 1, MP_EMIT_BUILD_MAP);
  2276. }
  2277. compile_node(comp, pn);
  2278. EMIT(store_map);
  2279. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_dictorsetmaker) {
  2280. assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should succeed
  2281. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1];
  2282. if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_dictorsetmaker_list) {
  2283. // dict/set with multiple elements
  2284. // get tail elements (2nd, 3rd, ...)
  2285. mp_parse_node_t *nodes;
  2286. size_t n = mp_parse_node_extract_list(&pns1->nodes[0], PN_dictorsetmaker_list2, &nodes);
  2287. // first element sets whether it's a dict or set
  2288. bool is_dict;
  2289. if (!MICROPY_PY_BUILTINS_SET || MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_dictorsetmaker_item)) {
  2290. // a dictionary
  2291. if (create_map) {
  2292. EMIT_ARG(build, 1 + n, MP_EMIT_BUILD_MAP);
  2293. }
  2294. compile_node(comp, pns->nodes[0]);
  2295. EMIT(store_map);
  2296. is_dict = true;
  2297. } else {
  2298. // a set
  2299. compile_node(comp, pns->nodes[0]); // 1st value of set
  2300. is_dict = false;
  2301. }
  2302. // process rest of elements
  2303. for (size_t i = 0; i < n; i++) {
  2304. mp_parse_node_t pn_i = nodes[i];
  2305. bool is_key_value = MP_PARSE_NODE_IS_STRUCT_KIND(pn_i, PN_dictorsetmaker_item);
  2306. compile_node(comp, pn_i);
  2307. if (is_dict) {
  2308. if (!is_key_value) {
  2309. #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
  2310. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("invalid syntax"));
  2311. #else
  2312. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("expecting key:value for dict"));
  2313. #endif
  2314. return;
  2315. }
  2316. EMIT(store_map);
  2317. } else {
  2318. if (is_key_value) {
  2319. #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
  2320. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("invalid syntax"));
  2321. #else
  2322. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("expecting just a value for set"));
  2323. #endif
  2324. return;
  2325. }
  2326. }
  2327. }
  2328. #if MICROPY_PY_BUILTINS_SET
  2329. // if it's a set, build it
  2330. if (!is_dict) {
  2331. EMIT_ARG(build, 1 + n, MP_EMIT_BUILD_SET);
  2332. }
  2333. #endif
  2334. } else {
  2335. assert(MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_comp_for); // should be
  2336. // dict/set comprehension
  2337. if (!MICROPY_PY_BUILTINS_SET || MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_dictorsetmaker_item)) {
  2338. // a dictionary comprehension
  2339. compile_comprehension(comp, pns, SCOPE_DICT_COMP);
  2340. } else {
  2341. // a set comprehension
  2342. compile_comprehension(comp, pns, SCOPE_SET_COMP);
  2343. }
  2344. }
  2345. } else {
  2346. // set with one element
  2347. goto set_with_one_element;
  2348. }
  2349. } else {
  2350. // set with one element
  2351. set_with_one_element:
  2352. #if MICROPY_PY_BUILTINS_SET
  2353. compile_node(comp, pn);
  2354. EMIT_ARG(build, 1, MP_EMIT_BUILD_SET);
  2355. #else
  2356. assert(0);
  2357. #endif
  2358. }
  2359. }
  2360. STATIC void compile_atom_brace(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2361. compile_atom_brace_helper(comp, pns, true);
  2362. }
  2363. STATIC void compile_trailer_paren(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2364. compile_trailer_paren_helper(comp, pns->nodes[0], false, 0);
  2365. }
  2366. STATIC void compile_trailer_bracket(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2367. // object who's index we want is on top of stack
  2368. compile_node(comp, pns->nodes[0]); // the index
  2369. EMIT_ARG(subscr, MP_EMIT_SUBSCR_LOAD);
  2370. }
  2371. STATIC void compile_trailer_period(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2372. // object who's attribute we want is on top of stack
  2373. EMIT_ARG(attr, MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]), MP_EMIT_ATTR_LOAD); // attribute to get
  2374. }
  2375. #if MICROPY_PY_BUILTINS_SLICE
  2376. STATIC void compile_subscript(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2377. if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_2) {
  2378. compile_node(comp, pns->nodes[0]); // start of slice
  2379. assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should always be
  2380. pns = (mp_parse_node_struct_t *)pns->nodes[1];
  2381. } else {
  2382. // pns is a PN_subscript_3, load None for start of slice
  2383. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  2384. }
  2385. assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_3); // should always be
  2386. mp_parse_node_t pn = pns->nodes[0];
  2387. if (MP_PARSE_NODE_IS_NULL(pn)) {
  2388. // [?:]
  2389. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  2390. EMIT_ARG(build, 2, MP_EMIT_BUILD_SLICE);
  2391. } else if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  2392. pns = (mp_parse_node_struct_t *)pn;
  2393. if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_3c) {
  2394. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  2395. pn = pns->nodes[0];
  2396. if (MP_PARSE_NODE_IS_NULL(pn)) {
  2397. // [?::]
  2398. EMIT_ARG(build, 2, MP_EMIT_BUILD_SLICE);
  2399. } else {
  2400. // [?::x]
  2401. compile_node(comp, pn);
  2402. EMIT_ARG(build, 3, MP_EMIT_BUILD_SLICE);
  2403. }
  2404. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_3d) {
  2405. compile_node(comp, pns->nodes[0]);
  2406. assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should always be
  2407. pns = (mp_parse_node_struct_t *)pns->nodes[1];
  2408. assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_sliceop); // should always be
  2409. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  2410. // [?:x:]
  2411. EMIT_ARG(build, 2, MP_EMIT_BUILD_SLICE);
  2412. } else {
  2413. // [?:x:x]
  2414. compile_node(comp, pns->nodes[0]);
  2415. EMIT_ARG(build, 3, MP_EMIT_BUILD_SLICE);
  2416. }
  2417. } else {
  2418. // [?:x]
  2419. compile_node(comp, pn);
  2420. EMIT_ARG(build, 2, MP_EMIT_BUILD_SLICE);
  2421. }
  2422. } else {
  2423. // [?:x]
  2424. compile_node(comp, pn);
  2425. EMIT_ARG(build, 2, MP_EMIT_BUILD_SLICE);
  2426. }
  2427. }
  2428. #endif // MICROPY_PY_BUILTINS_SLICE
  2429. STATIC void compile_dictorsetmaker_item(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2430. // if this is called then we are compiling a dict key:value pair
  2431. compile_node(comp, pns->nodes[1]); // value
  2432. compile_node(comp, pns->nodes[0]); // key
  2433. }
  2434. STATIC void compile_classdef(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2435. qstr cname = compile_classdef_helper(comp, pns, comp->scope_cur->emit_options);
  2436. // store class object into class name
  2437. compile_store_id(comp, cname);
  2438. }
  2439. STATIC void compile_yield_expr(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2440. if (comp->scope_cur->kind != SCOPE_FUNCTION && comp->scope_cur->kind != SCOPE_LAMBDA) {
  2441. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("'yield' outside function"));
  2442. return;
  2443. }
  2444. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  2445. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  2446. EMIT_ARG(yield, MP_EMIT_YIELD_VALUE);
  2447. reserve_labels_for_native(comp, 1);
  2448. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_yield_arg_from)) {
  2449. pns = (mp_parse_node_struct_t *)pns->nodes[0];
  2450. compile_node(comp, pns->nodes[0]);
  2451. compile_yield_from(comp);
  2452. } else {
  2453. compile_node(comp, pns->nodes[0]);
  2454. EMIT_ARG(yield, MP_EMIT_YIELD_VALUE);
  2455. reserve_labels_for_native(comp, 1);
  2456. }
  2457. }
  2458. #if MICROPY_PY_ASYNC_AWAIT
  2459. STATIC void compile_atom_expr_await(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2460. if (comp->scope_cur->kind != SCOPE_FUNCTION && comp->scope_cur->kind != SCOPE_LAMBDA) {
  2461. compile_syntax_error(comp, (mp_parse_node_t)pns, MP_ERROR_TEXT("'await' outside function"));
  2462. return;
  2463. }
  2464. compile_atom_expr_normal(comp, pns);
  2465. compile_yield_from(comp);
  2466. }
  2467. #endif
  2468. STATIC mp_obj_t get_const_object(mp_parse_node_struct_t *pns) {
  2469. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  2470. // nodes are 32-bit pointers, but need to extract 64-bit object
  2471. return (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32);
  2472. #else
  2473. return (mp_obj_t)pns->nodes[0];
  2474. #endif
  2475. }
  2476. STATIC void compile_const_object(compiler_t *comp, mp_parse_node_struct_t *pns) {
  2477. EMIT_ARG(load_const_obj, get_const_object(pns));
  2478. }
  2479. typedef void (*compile_function_t)(compiler_t *, mp_parse_node_struct_t *);
  2480. STATIC const compile_function_t compile_function[] = {
  2481. // only define rules with a compile function
  2482. #define c(f) compile_##f
  2483. #define DEF_RULE(rule, comp, kind, ...) comp,
  2484. #define DEF_RULE_NC(rule, kind, ...)
  2485. #include "py/grammar.h"
  2486. #undef c
  2487. #undef DEF_RULE
  2488. #undef DEF_RULE_NC
  2489. compile_const_object,
  2490. };
  2491. STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) {
  2492. if (MP_PARSE_NODE_IS_NULL(pn)) {
  2493. // pass
  2494. } else if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
  2495. mp_int_t arg = MP_PARSE_NODE_LEAF_SMALL_INT(pn);
  2496. #if MICROPY_DYNAMIC_COMPILER
  2497. mp_uint_t sign_mask = -((mp_uint_t)1 << (mp_dynamic_compiler.small_int_bits - 1));
  2498. if ((arg & sign_mask) == 0 || (arg & sign_mask) == sign_mask) {
  2499. // integer fits in target runtime's small-int
  2500. EMIT_ARG(load_const_small_int, arg);
  2501. } else {
  2502. // integer doesn't fit, so create a multi-precision int object
  2503. // (but only create the actual object on the last pass)
  2504. if (comp->pass != MP_PASS_EMIT) {
  2505. EMIT_ARG(load_const_obj, mp_const_none);
  2506. } else {
  2507. EMIT_ARG(load_const_obj, mp_obj_new_int_from_ll(arg));
  2508. }
  2509. }
  2510. #else
  2511. EMIT_ARG(load_const_small_int, arg);
  2512. #endif
  2513. } else if (MP_PARSE_NODE_IS_LEAF(pn)) {
  2514. uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn);
  2515. switch (MP_PARSE_NODE_LEAF_KIND(pn)) {
  2516. case MP_PARSE_NODE_ID:
  2517. compile_load_id(comp, arg);
  2518. break;
  2519. case MP_PARSE_NODE_STRING:
  2520. EMIT_ARG(load_const_str, arg);
  2521. break;
  2522. case MP_PARSE_NODE_BYTES:
  2523. // only create and load the actual bytes object on the last pass
  2524. if (comp->pass != MP_PASS_EMIT) {
  2525. EMIT_ARG(load_const_obj, mp_const_none);
  2526. } else {
  2527. size_t len;
  2528. const byte *data = qstr_data(arg, &len);
  2529. EMIT_ARG(load_const_obj, mp_obj_new_bytes(data, len));
  2530. }
  2531. break;
  2532. case MP_PARSE_NODE_TOKEN:
  2533. default:
  2534. if (arg == MP_TOKEN_NEWLINE) {
  2535. // this can occur when file_input lets through a NEWLINE (eg if file starts with a newline)
  2536. // or when single_input lets through a NEWLINE (user enters a blank line)
  2537. // do nothing
  2538. } else {
  2539. EMIT_ARG(load_const_tok, arg);
  2540. }
  2541. break;
  2542. }
  2543. } else {
  2544. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  2545. EMIT_ARG(set_source_line, pns->source_line);
  2546. assert(MP_PARSE_NODE_STRUCT_KIND(pns) <= PN_const_object);
  2547. compile_function_t f = compile_function[MP_PARSE_NODE_STRUCT_KIND(pns)];
  2548. f(comp, pns);
  2549. }
  2550. }
  2551. #if MICROPY_EMIT_NATIVE
  2552. STATIC int compile_viper_type_annotation(compiler_t *comp, mp_parse_node_t pn_annotation) {
  2553. int native_type = MP_NATIVE_TYPE_OBJ;
  2554. if (MP_PARSE_NODE_IS_NULL(pn_annotation)) {
  2555. // No annotation, type defaults to object
  2556. } else if (MP_PARSE_NODE_IS_ID(pn_annotation)) {
  2557. qstr type_name = MP_PARSE_NODE_LEAF_ARG(pn_annotation);
  2558. native_type = mp_native_type_from_qstr(type_name);
  2559. if (native_type < 0) {
  2560. comp->compile_error = mp_obj_new_exception_msg_varg(&mp_type_ViperTypeError, MP_ERROR_TEXT("unknown type '%q'"), type_name);
  2561. native_type = 0;
  2562. }
  2563. } else {
  2564. compile_syntax_error(comp, pn_annotation, MP_ERROR_TEXT("annotation must be an identifier"));
  2565. }
  2566. return native_type;
  2567. }
  2568. #endif
  2569. STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn, pn_kind_t pn_name, pn_kind_t pn_star, pn_kind_t pn_dbl_star) {
  2570. (void)pn_dbl_star;
  2571. // check that **kw is last
  2572. if ((comp->scope_cur->scope_flags & MP_SCOPE_FLAG_VARKEYWORDS) != 0) {
  2573. compile_syntax_error(comp, pn, MP_ERROR_TEXT("invalid syntax"));
  2574. return;
  2575. }
  2576. qstr param_name = MP_QSTRnull;
  2577. uint param_flag = ID_FLAG_IS_PARAM;
  2578. mp_parse_node_struct_t *pns = NULL;
  2579. if (MP_PARSE_NODE_IS_ID(pn)) {
  2580. param_name = MP_PARSE_NODE_LEAF_ARG(pn);
  2581. if (comp->have_star) {
  2582. // comes after a star, so counts as a keyword-only parameter
  2583. comp->scope_cur->num_kwonly_args += 1;
  2584. } else {
  2585. // comes before a star, so counts as a positional parameter
  2586. comp->scope_cur->num_pos_args += 1;
  2587. }
  2588. } else {
  2589. assert(MP_PARSE_NODE_IS_STRUCT(pn));
  2590. pns = (mp_parse_node_struct_t *)pn;
  2591. if (MP_PARSE_NODE_STRUCT_KIND(pns) == pn_name) {
  2592. // named parameter with possible annotation
  2593. param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]);
  2594. if (comp->have_star) {
  2595. // comes after a star, so counts as a keyword-only parameter
  2596. comp->scope_cur->num_kwonly_args += 1;
  2597. } else {
  2598. // comes before a star, so counts as a positional parameter
  2599. comp->scope_cur->num_pos_args += 1;
  2600. }
  2601. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == pn_star) {
  2602. if (comp->have_star) {
  2603. // more than one star
  2604. compile_syntax_error(comp, pn, MP_ERROR_TEXT("invalid syntax"));
  2605. return;
  2606. }
  2607. comp->have_star = true;
  2608. param_flag = ID_FLAG_IS_PARAM | ID_FLAG_IS_STAR_PARAM;
  2609. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  2610. // bare star
  2611. // TODO see http://www.python.org/dev/peps/pep-3102/
  2612. // assert(comp->scope_cur->num_dict_params == 0);
  2613. pns = NULL;
  2614. } else if (MP_PARSE_NODE_IS_ID(pns->nodes[0])) {
  2615. // named star
  2616. comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_VARARGS;
  2617. param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]);
  2618. pns = NULL;
  2619. } else {
  2620. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_tfpdef)); // should be
  2621. // named star with possible annotation
  2622. comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_VARARGS;
  2623. pns = (mp_parse_node_struct_t *)pns->nodes[0];
  2624. param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]);
  2625. }
  2626. } else {
  2627. // double star with possible annotation
  2628. assert(MP_PARSE_NODE_STRUCT_KIND(pns) == pn_dbl_star); // should be
  2629. param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]);
  2630. param_flag = ID_FLAG_IS_PARAM | ID_FLAG_IS_DBL_STAR_PARAM;
  2631. comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_VARKEYWORDS;
  2632. }
  2633. }
  2634. if (param_name != MP_QSTRnull) {
  2635. id_info_t *id_info = scope_find_or_add_id(comp->scope_cur, param_name, ID_INFO_KIND_UNDECIDED);
  2636. if (id_info->kind != ID_INFO_KIND_UNDECIDED) {
  2637. compile_syntax_error(comp, pn, MP_ERROR_TEXT("argument name reused"));
  2638. return;
  2639. }
  2640. id_info->kind = ID_INFO_KIND_LOCAL;
  2641. id_info->flags = param_flag;
  2642. #if MICROPY_EMIT_NATIVE
  2643. if (comp->scope_cur->emit_options == MP_EMIT_OPT_VIPER && pn_name == PN_typedargslist_name && pns != NULL) {
  2644. id_info->flags |= compile_viper_type_annotation(comp, pns->nodes[1]) << ID_FLAG_VIPER_TYPE_POS;
  2645. }
  2646. #else
  2647. (void)pns;
  2648. #endif
  2649. }
  2650. }
  2651. STATIC void compile_scope_func_param(compiler_t *comp, mp_parse_node_t pn) {
  2652. compile_scope_func_lambda_param(comp, pn, PN_typedargslist_name, PN_typedargslist_star, PN_typedargslist_dbl_star);
  2653. }
  2654. STATIC void compile_scope_lambda_param(compiler_t *comp, mp_parse_node_t pn) {
  2655. compile_scope_func_lambda_param(comp, pn, PN_varargslist_name, PN_varargslist_star, PN_varargslist_dbl_star);
  2656. }
  2657. STATIC void compile_scope_comp_iter(compiler_t *comp, mp_parse_node_struct_t *pns_comp_for, mp_parse_node_t pn_inner_expr, int for_depth) {
  2658. uint l_top = comp_next_label(comp);
  2659. uint l_end = comp_next_label(comp);
  2660. EMIT_ARG(label_assign, l_top);
  2661. EMIT_ARG(for_iter, l_end);
  2662. c_assign(comp, pns_comp_for->nodes[0], ASSIGN_STORE);
  2663. mp_parse_node_t pn_iter = pns_comp_for->nodes[2];
  2664. tail_recursion:
  2665. if (MP_PARSE_NODE_IS_NULL(pn_iter)) {
  2666. // no more nested if/for; compile inner expression
  2667. compile_node(comp, pn_inner_expr);
  2668. if (comp->scope_cur->kind == SCOPE_GEN_EXPR) {
  2669. EMIT_ARG(yield, MP_EMIT_YIELD_VALUE);
  2670. reserve_labels_for_native(comp, 1);
  2671. EMIT(pop_top);
  2672. } else {
  2673. EMIT_ARG(store_comp, comp->scope_cur->kind, 4 * for_depth + 5);
  2674. }
  2675. } else if (MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_iter) == PN_comp_if) {
  2676. // if condition
  2677. mp_parse_node_struct_t *pns_comp_if = (mp_parse_node_struct_t *)pn_iter;
  2678. c_if_cond(comp, pns_comp_if->nodes[0], false, l_top);
  2679. pn_iter = pns_comp_if->nodes[1];
  2680. goto tail_recursion;
  2681. } else {
  2682. assert(MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_iter) == PN_comp_for); // should be
  2683. // for loop
  2684. mp_parse_node_struct_t *pns_comp_for2 = (mp_parse_node_struct_t *)pn_iter;
  2685. compile_node(comp, pns_comp_for2->nodes[1]);
  2686. EMIT_ARG(get_iter, true);
  2687. compile_scope_comp_iter(comp, pns_comp_for2, pn_inner_expr, for_depth + 1);
  2688. }
  2689. EMIT_ARG(jump, l_top);
  2690. EMIT_ARG(label_assign, l_end);
  2691. EMIT(for_iter_end);
  2692. }
  2693. STATIC void check_for_doc_string(compiler_t *comp, mp_parse_node_t pn) {
  2694. #if MICROPY_ENABLE_DOC_STRING
  2695. // see http://www.python.org/dev/peps/pep-0257/
  2696. // look for the first statement
  2697. if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_expr_stmt)) {
  2698. // a statement; fall through
  2699. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_file_input_2)) {
  2700. // file input; find the first non-newline node
  2701. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  2702. int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  2703. for (int i = 0; i < num_nodes; i++) {
  2704. pn = pns->nodes[i];
  2705. if (!(MP_PARSE_NODE_IS_LEAF(pn) && MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_TOKEN && MP_PARSE_NODE_LEAF_ARG(pn) == MP_TOKEN_NEWLINE)) {
  2706. // not a newline, so this is the first statement; finish search
  2707. break;
  2708. }
  2709. }
  2710. // if we didn't find a non-newline then it's okay to fall through; pn will be a newline and so doc-string test below will fail gracefully
  2711. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_suite_block_stmts)) {
  2712. // a list of statements; get the first one
  2713. pn = ((mp_parse_node_struct_t *)pn)->nodes[0];
  2714. } else {
  2715. return;
  2716. }
  2717. // check the first statement for a doc string
  2718. if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_expr_stmt)) {
  2719. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  2720. if ((MP_PARSE_NODE_IS_LEAF(pns->nodes[0])
  2721. && MP_PARSE_NODE_LEAF_KIND(pns->nodes[0]) == MP_PARSE_NODE_STRING)
  2722. || (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_const_object)
  2723. && mp_obj_is_str(get_const_object((mp_parse_node_struct_t *)pns->nodes[0])))) {
  2724. // compile the doc string
  2725. compile_node(comp, pns->nodes[0]);
  2726. // store the doc string
  2727. compile_store_id(comp, MP_QSTR___doc__);
  2728. }
  2729. }
  2730. #else
  2731. (void)comp;
  2732. (void)pn;
  2733. #endif
  2734. }
  2735. STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) {
  2736. comp->pass = pass;
  2737. comp->scope_cur = scope;
  2738. comp->next_label = 0;
  2739. EMIT_ARG(start_pass, pass, scope);
  2740. reserve_labels_for_native(comp, 6); // used by native's start_pass
  2741. if (comp->pass == MP_PASS_SCOPE) {
  2742. // reset maximum stack sizes in scope
  2743. // they will be computed in this first pass
  2744. scope->stack_size = 0;
  2745. scope->exc_stack_size = 0;
  2746. }
  2747. // compile
  2748. if (MP_PARSE_NODE_IS_STRUCT_KIND(scope->pn, PN_eval_input)) {
  2749. assert(scope->kind == SCOPE_MODULE);
  2750. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
  2751. compile_node(comp, pns->nodes[0]); // compile the expression
  2752. EMIT(return_value);
  2753. } else if (scope->kind == SCOPE_MODULE) {
  2754. if (!comp->is_repl) {
  2755. check_for_doc_string(comp, scope->pn);
  2756. }
  2757. compile_node(comp, scope->pn);
  2758. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  2759. EMIT(return_value);
  2760. } else if (scope->kind == SCOPE_FUNCTION) {
  2761. assert(MP_PARSE_NODE_IS_STRUCT(scope->pn));
  2762. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
  2763. assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_funcdef);
  2764. // work out number of parameters, keywords and default parameters, and add them to the id_info array
  2765. // must be done before compiling the body so that arguments are numbered first (for LOAD_FAST etc)
  2766. if (comp->pass == MP_PASS_SCOPE) {
  2767. comp->have_star = false;
  2768. apply_to_single_or_list(comp, pns->nodes[1], PN_typedargslist, compile_scope_func_param);
  2769. #if MICROPY_EMIT_NATIVE
  2770. if (scope->emit_options == MP_EMIT_OPT_VIPER) {
  2771. // Compile return type; pns->nodes[2] is return/whole function annotation
  2772. scope->scope_flags |= compile_viper_type_annotation(comp, pns->nodes[2]) << MP_SCOPE_FLAG_VIPERRET_POS;
  2773. }
  2774. #endif // MICROPY_EMIT_NATIVE
  2775. }
  2776. compile_node(comp, pns->nodes[3]); // 3 is function body
  2777. // emit return if it wasn't the last opcode
  2778. if (!EMIT(last_emit_was_return_value)) {
  2779. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  2780. EMIT(return_value);
  2781. }
  2782. } else if (scope->kind == SCOPE_LAMBDA) {
  2783. assert(MP_PARSE_NODE_IS_STRUCT(scope->pn));
  2784. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
  2785. assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 3);
  2786. // Set the source line number for the start of the lambda
  2787. EMIT_ARG(set_source_line, pns->source_line);
  2788. // work out number of parameters, keywords and default parameters, and add them to the id_info array
  2789. // must be done before compiling the body so that arguments are numbered first (for LOAD_FAST etc)
  2790. if (comp->pass == MP_PASS_SCOPE) {
  2791. comp->have_star = false;
  2792. apply_to_single_or_list(comp, pns->nodes[0], PN_varargslist, compile_scope_lambda_param);
  2793. }
  2794. compile_node(comp, pns->nodes[1]); // 1 is lambda body
  2795. // if the lambda is a generator, then we return None, not the result of the expression of the lambda
  2796. if (scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) {
  2797. EMIT(pop_top);
  2798. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  2799. }
  2800. EMIT(return_value);
  2801. } else if (SCOPE_IS_COMP_LIKE(scope->kind)) {
  2802. // a bit of a hack at the moment
  2803. assert(MP_PARSE_NODE_IS_STRUCT(scope->pn));
  2804. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
  2805. assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 2);
  2806. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_comp_for));
  2807. mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t *)pns->nodes[1];
  2808. // We need a unique name for the comprehension argument (the iterator).
  2809. // CPython uses .0, but we should be able to use anything that won't
  2810. // clash with a user defined variable. Best to use an existing qstr,
  2811. // so we use the blank qstr.
  2812. qstr qstr_arg = MP_QSTR_;
  2813. if (comp->pass == MP_PASS_SCOPE) {
  2814. scope_find_or_add_id(comp->scope_cur, qstr_arg, ID_INFO_KIND_LOCAL);
  2815. scope->num_pos_args = 1;
  2816. }
  2817. // Set the source line number for the start of the comprehension
  2818. EMIT_ARG(set_source_line, pns->source_line);
  2819. if (scope->kind == SCOPE_LIST_COMP) {
  2820. EMIT_ARG(build, 0, MP_EMIT_BUILD_LIST);
  2821. } else if (scope->kind == SCOPE_DICT_COMP) {
  2822. EMIT_ARG(build, 0, MP_EMIT_BUILD_MAP);
  2823. #if MICROPY_PY_BUILTINS_SET
  2824. } else if (scope->kind == SCOPE_SET_COMP) {
  2825. EMIT_ARG(build, 0, MP_EMIT_BUILD_SET);
  2826. #endif
  2827. }
  2828. // There are 4 slots on the stack for the iterator, and the first one is
  2829. // NULL to indicate that the second one points to the iterator object.
  2830. if (scope->kind == SCOPE_GEN_EXPR) {
  2831. MP_STATIC_ASSERT(MP_OBJ_ITER_BUF_NSLOTS == 4);
  2832. EMIT(load_null);
  2833. compile_load_id(comp, qstr_arg);
  2834. EMIT(load_null);
  2835. EMIT(load_null);
  2836. } else {
  2837. compile_load_id(comp, qstr_arg);
  2838. EMIT_ARG(get_iter, true);
  2839. }
  2840. compile_scope_comp_iter(comp, pns_comp_for, pns->nodes[0], 0);
  2841. if (scope->kind == SCOPE_GEN_EXPR) {
  2842. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  2843. }
  2844. EMIT(return_value);
  2845. } else {
  2846. assert(scope->kind == SCOPE_CLASS);
  2847. assert(MP_PARSE_NODE_IS_STRUCT(scope->pn));
  2848. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
  2849. assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_classdef);
  2850. if (comp->pass == MP_PASS_SCOPE) {
  2851. scope_find_or_add_id(scope, MP_QSTR___class__, ID_INFO_KIND_LOCAL);
  2852. }
  2853. #if MICROPY_PY_SYS_SETTRACE
  2854. EMIT_ARG(set_source_line, pns->source_line);
  2855. #endif
  2856. compile_load_id(comp, MP_QSTR___name__);
  2857. compile_store_id(comp, MP_QSTR___module__);
  2858. EMIT_ARG(load_const_str, MP_PARSE_NODE_LEAF_ARG(pns->nodes[0])); // 0 is class name
  2859. compile_store_id(comp, MP_QSTR___qualname__);
  2860. check_for_doc_string(comp, pns->nodes[2]);
  2861. compile_node(comp, pns->nodes[2]); // 2 is class body
  2862. id_info_t *id = scope_find(scope, MP_QSTR___class__);
  2863. assert(id != NULL);
  2864. if (id->kind == ID_INFO_KIND_LOCAL) {
  2865. EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
  2866. } else {
  2867. EMIT_LOAD_FAST(MP_QSTR___class__, id->local_num);
  2868. }
  2869. EMIT(return_value);
  2870. }
  2871. EMIT(end_pass);
  2872. // make sure we match all the exception levels
  2873. assert(comp->cur_except_level == 0);
  2874. }
  2875. #if MICROPY_EMIT_INLINE_ASM
  2876. // requires 3 passes: SCOPE, CODE_SIZE, EMIT
  2877. STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind_t pass) {
  2878. comp->pass = pass;
  2879. comp->scope_cur = scope;
  2880. comp->next_label = 0;
  2881. if (scope->kind != SCOPE_FUNCTION) {
  2882. compile_syntax_error(comp, MP_PARSE_NODE_NULL, MP_ERROR_TEXT("inline assembler must be a function"));
  2883. return;
  2884. }
  2885. if (comp->pass > MP_PASS_SCOPE) {
  2886. EMIT_INLINE_ASM_ARG(start_pass, comp->pass, &comp->compile_error);
  2887. }
  2888. // get the function definition parse node
  2889. assert(MP_PARSE_NODE_IS_STRUCT(scope->pn));
  2890. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn;
  2891. assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_funcdef);
  2892. // qstr f_id = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); // function name
  2893. // parameters are in pns->nodes[1]
  2894. if (comp->pass == MP_PASS_CODE_SIZE) {
  2895. mp_parse_node_t *pn_params;
  2896. size_t n_params = mp_parse_node_extract_list(&pns->nodes[1], PN_typedargslist, &pn_params);
  2897. scope->num_pos_args = EMIT_INLINE_ASM_ARG(count_params, n_params, pn_params);
  2898. if (comp->compile_error != MP_OBJ_NULL) {
  2899. goto inline_asm_error;
  2900. }
  2901. }
  2902. // pns->nodes[2] is function return annotation
  2903. mp_uint_t type_sig = MP_NATIVE_TYPE_INT;
  2904. mp_parse_node_t pn_annotation = pns->nodes[2];
  2905. if (!MP_PARSE_NODE_IS_NULL(pn_annotation)) {
  2906. // nodes[2] can be null or a test-expr
  2907. if (MP_PARSE_NODE_IS_ID(pn_annotation)) {
  2908. qstr ret_type = MP_PARSE_NODE_LEAF_ARG(pn_annotation);
  2909. switch (ret_type) {
  2910. case MP_QSTR_object:
  2911. type_sig = MP_NATIVE_TYPE_OBJ;
  2912. break;
  2913. case MP_QSTR_bool:
  2914. type_sig = MP_NATIVE_TYPE_BOOL;
  2915. break;
  2916. case MP_QSTR_int:
  2917. type_sig = MP_NATIVE_TYPE_INT;
  2918. break;
  2919. case MP_QSTR_uint:
  2920. type_sig = MP_NATIVE_TYPE_UINT;
  2921. break;
  2922. default:
  2923. compile_syntax_error(comp, pn_annotation, MP_ERROR_TEXT("unknown type"));
  2924. return;
  2925. }
  2926. } else {
  2927. compile_syntax_error(comp, pn_annotation, MP_ERROR_TEXT("return annotation must be an identifier"));
  2928. }
  2929. }
  2930. mp_parse_node_t pn_body = pns->nodes[3]; // body
  2931. mp_parse_node_t *nodes;
  2932. size_t num = mp_parse_node_extract_list(&pn_body, PN_suite_block_stmts, &nodes);
  2933. for (size_t i = 0; i < num; i++) {
  2934. assert(MP_PARSE_NODE_IS_STRUCT(nodes[i]));
  2935. mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)nodes[i];
  2936. if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_pass_stmt) {
  2937. // no instructions
  2938. continue;
  2939. } else if (MP_PARSE_NODE_STRUCT_KIND(pns2) != PN_expr_stmt) {
  2940. // not an instruction; error
  2941. not_an_instruction:
  2942. compile_syntax_error(comp, nodes[i], MP_ERROR_TEXT("expecting an assembler instruction"));
  2943. return;
  2944. }
  2945. // check structure of parse node
  2946. assert(MP_PARSE_NODE_IS_STRUCT(pns2->nodes[0]));
  2947. if (!MP_PARSE_NODE_IS_NULL(pns2->nodes[1])) {
  2948. goto not_an_instruction;
  2949. }
  2950. pns2 = (mp_parse_node_struct_t *)pns2->nodes[0];
  2951. if (MP_PARSE_NODE_STRUCT_KIND(pns2) != PN_atom_expr_normal) {
  2952. goto not_an_instruction;
  2953. }
  2954. if (!MP_PARSE_NODE_IS_ID(pns2->nodes[0])) {
  2955. goto not_an_instruction;
  2956. }
  2957. if (!MP_PARSE_NODE_IS_STRUCT_KIND(pns2->nodes[1], PN_trailer_paren)) {
  2958. goto not_an_instruction;
  2959. }
  2960. // parse node looks like an instruction
  2961. // get instruction name and args
  2962. qstr op = MP_PARSE_NODE_LEAF_ARG(pns2->nodes[0]);
  2963. pns2 = (mp_parse_node_struct_t *)pns2->nodes[1]; // PN_trailer_paren
  2964. mp_parse_node_t *pn_arg;
  2965. size_t n_args = mp_parse_node_extract_list(&pns2->nodes[0], PN_arglist, &pn_arg);
  2966. // emit instructions
  2967. if (op == MP_QSTR_label) {
  2968. if (!(n_args == 1 && MP_PARSE_NODE_IS_ID(pn_arg[0]))) {
  2969. compile_syntax_error(comp, nodes[i], MP_ERROR_TEXT("'label' requires 1 argument"));
  2970. return;
  2971. }
  2972. uint lab = comp_next_label(comp);
  2973. if (pass > MP_PASS_SCOPE) {
  2974. if (!EMIT_INLINE_ASM_ARG(label, lab, MP_PARSE_NODE_LEAF_ARG(pn_arg[0]))) {
  2975. compile_syntax_error(comp, nodes[i], MP_ERROR_TEXT("label redefined"));
  2976. return;
  2977. }
  2978. }
  2979. } else if (op == MP_QSTR_align) {
  2980. if (!(n_args == 1 && MP_PARSE_NODE_IS_SMALL_INT(pn_arg[0]))) {
  2981. compile_syntax_error(comp, nodes[i], MP_ERROR_TEXT("'align' requires 1 argument"));
  2982. return;
  2983. }
  2984. if (pass > MP_PASS_SCOPE) {
  2985. mp_asm_base_align((mp_asm_base_t *)comp->emit_inline_asm,
  2986. MP_PARSE_NODE_LEAF_SMALL_INT(pn_arg[0]));
  2987. }
  2988. } else if (op == MP_QSTR_data) {
  2989. if (!(n_args >= 2 && MP_PARSE_NODE_IS_SMALL_INT(pn_arg[0]))) {
  2990. compile_syntax_error(comp, nodes[i], MP_ERROR_TEXT("'data' requires at least 2 arguments"));
  2991. return;
  2992. }
  2993. if (pass > MP_PASS_SCOPE) {
  2994. mp_int_t bytesize = MP_PARSE_NODE_LEAF_SMALL_INT(pn_arg[0]);
  2995. for (uint j = 1; j < n_args; j++) {
  2996. if (!MP_PARSE_NODE_IS_SMALL_INT(pn_arg[j])) {
  2997. compile_syntax_error(comp, nodes[i], MP_ERROR_TEXT("'data' requires integer arguments"));
  2998. return;
  2999. }
  3000. mp_asm_base_data((mp_asm_base_t *)comp->emit_inline_asm,
  3001. bytesize, MP_PARSE_NODE_LEAF_SMALL_INT(pn_arg[j]));
  3002. }
  3003. }
  3004. } else {
  3005. if (pass > MP_PASS_SCOPE) {
  3006. EMIT_INLINE_ASM_ARG(op, op, n_args, pn_arg);
  3007. }
  3008. }
  3009. if (comp->compile_error != MP_OBJ_NULL) {
  3010. pns = pns2; // this is the parse node that had the error
  3011. goto inline_asm_error;
  3012. }
  3013. }
  3014. if (comp->pass > MP_PASS_SCOPE) {
  3015. EMIT_INLINE_ASM_ARG(end_pass, type_sig);
  3016. if (comp->pass == MP_PASS_EMIT) {
  3017. void *f = mp_asm_base_get_code((mp_asm_base_t *)comp->emit_inline_asm);
  3018. mp_emit_glue_assign_native(comp->scope_cur->raw_code, MP_CODE_NATIVE_ASM,
  3019. f, mp_asm_base_get_code_size((mp_asm_base_t *)comp->emit_inline_asm),
  3020. NULL,
  3021. #if MICROPY_PERSISTENT_CODE_SAVE
  3022. 0, 0, 0, 0, NULL,
  3023. #endif
  3024. comp->scope_cur->num_pos_args, 0, type_sig);
  3025. }
  3026. }
  3027. if (comp->compile_error != MP_OBJ_NULL) {
  3028. // inline assembler had an error; set line for its exception
  3029. inline_asm_error:
  3030. comp->compile_error_line = pns->source_line;
  3031. }
  3032. }
  3033. #endif
  3034. STATIC void scope_compute_things(scope_t *scope) {
  3035. // in MicroPython we put the *x parameter after all other parameters (except **y)
  3036. if (scope->scope_flags & MP_SCOPE_FLAG_VARARGS) {
  3037. id_info_t *id_param = NULL;
  3038. for (int i = scope->id_info_len - 1; i >= 0; i--) {
  3039. id_info_t *id = &scope->id_info[i];
  3040. if (id->flags & ID_FLAG_IS_STAR_PARAM) {
  3041. if (id_param != NULL) {
  3042. // swap star param with last param
  3043. id_info_t temp = *id_param;
  3044. *id_param = *id;
  3045. *id = temp;
  3046. }
  3047. break;
  3048. } else if (id_param == NULL && id->flags == ID_FLAG_IS_PARAM) {
  3049. id_param = id;
  3050. }
  3051. }
  3052. }
  3053. // in functions, turn implicit globals into explicit globals
  3054. // compute the index of each local
  3055. scope->num_locals = 0;
  3056. for (int i = 0; i < scope->id_info_len; i++) {
  3057. id_info_t *id = &scope->id_info[i];
  3058. if (scope->kind == SCOPE_CLASS && id->qst == MP_QSTR___class__) {
  3059. // __class__ is not counted as a local; if it's used then it becomes a ID_INFO_KIND_CELL
  3060. continue;
  3061. }
  3062. if (SCOPE_IS_FUNC_LIKE(scope->kind) && id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) {
  3063. id->kind = ID_INFO_KIND_GLOBAL_EXPLICIT;
  3064. }
  3065. #if MICROPY_EMIT_NATIVE
  3066. if (id->kind == ID_INFO_KIND_GLOBAL_EXPLICIT) {
  3067. // This function makes a reference to a global variable
  3068. if (scope->emit_options == MP_EMIT_OPT_VIPER
  3069. && mp_native_type_from_qstr(id->qst) >= MP_NATIVE_TYPE_INT) {
  3070. // A casting operator in viper mode, not a real global reference
  3071. } else {
  3072. scope->scope_flags |= MP_SCOPE_FLAG_REFGLOBALS;
  3073. }
  3074. }
  3075. #endif
  3076. // params always count for 1 local, even if they are a cell
  3077. if (id->kind == ID_INFO_KIND_LOCAL || (id->flags & ID_FLAG_IS_PARAM)) {
  3078. id->local_num = scope->num_locals++;
  3079. }
  3080. }
  3081. // compute the index of cell vars
  3082. for (int i = 0; i < scope->id_info_len; i++) {
  3083. id_info_t *id = &scope->id_info[i];
  3084. // in MicroPython the cells come right after the fast locals
  3085. // parameters are not counted here, since they remain at the start
  3086. // of the locals, even if they are cell vars
  3087. if (id->kind == ID_INFO_KIND_CELL && !(id->flags & ID_FLAG_IS_PARAM)) {
  3088. id->local_num = scope->num_locals;
  3089. scope->num_locals += 1;
  3090. }
  3091. }
  3092. // compute the index of free vars
  3093. // make sure they are in the order of the parent scope
  3094. if (scope->parent != NULL) {
  3095. int num_free = 0;
  3096. for (int i = 0; i < scope->parent->id_info_len; i++) {
  3097. id_info_t *id = &scope->parent->id_info[i];
  3098. if (id->kind == ID_INFO_KIND_CELL || id->kind == ID_INFO_KIND_FREE) {
  3099. for (int j = 0; j < scope->id_info_len; j++) {
  3100. id_info_t *id2 = &scope->id_info[j];
  3101. if (id2->kind == ID_INFO_KIND_FREE && id->qst == id2->qst) {
  3102. assert(!(id2->flags & ID_FLAG_IS_PARAM)); // free vars should not be params
  3103. // in MicroPython the frees come first, before the params
  3104. id2->local_num = num_free;
  3105. num_free += 1;
  3106. }
  3107. }
  3108. }
  3109. }
  3110. // in MicroPython shift all other locals after the free locals
  3111. if (num_free > 0) {
  3112. for (int i = 0; i < scope->id_info_len; i++) {
  3113. id_info_t *id = &scope->id_info[i];
  3114. if (id->kind != ID_INFO_KIND_FREE || (id->flags & ID_FLAG_IS_PARAM)) {
  3115. id->local_num += num_free;
  3116. }
  3117. }
  3118. scope->num_pos_args += num_free; // free vars are counted as params for passing them into the function
  3119. scope->num_locals += num_free;
  3120. }
  3121. }
  3122. }
  3123. #if !MICROPY_PERSISTENT_CODE_SAVE
  3124. STATIC
  3125. #endif
  3126. mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_file, bool is_repl) {
  3127. // put compiler state on the stack, it's relatively small
  3128. compiler_t comp_state = {0};
  3129. compiler_t *comp = &comp_state;
  3130. comp->source_file = source_file;
  3131. comp->is_repl = is_repl;
  3132. comp->break_label = INVALID_LABEL;
  3133. comp->continue_label = INVALID_LABEL;
  3134. // create the module scope
  3135. #if MICROPY_EMIT_NATIVE
  3136. const uint emit_opt = MP_STATE_VM(default_emit_opt);
  3137. #else
  3138. const uint emit_opt = MP_EMIT_OPT_NONE;
  3139. #endif
  3140. scope_t *module_scope = scope_new_and_link(comp, SCOPE_MODULE, parse_tree->root, emit_opt);
  3141. // create standard emitter; it's used at least for MP_PASS_SCOPE
  3142. emit_t *emit_bc = emit_bc_new();
  3143. // compile pass 1
  3144. comp->emit = emit_bc;
  3145. #if MICROPY_EMIT_NATIVE
  3146. comp->emit_method_table = &emit_bc_method_table;
  3147. #endif
  3148. uint max_num_labels = 0;
  3149. for (scope_t *s = comp->scope_head; s != NULL && comp->compile_error == MP_OBJ_NULL; s = s->next) {
  3150. #if MICROPY_EMIT_INLINE_ASM
  3151. if (s->emit_options == MP_EMIT_OPT_ASM) {
  3152. compile_scope_inline_asm(comp, s, MP_PASS_SCOPE);
  3153. } else
  3154. #endif
  3155. {
  3156. compile_scope(comp, s, MP_PASS_SCOPE);
  3157. // Check if any implicitly declared variables should be closed over
  3158. for (size_t i = 0; i < s->id_info_len; ++i) {
  3159. id_info_t *id = &s->id_info[i];
  3160. if (id->kind == ID_INFO_KIND_GLOBAL_IMPLICIT) {
  3161. scope_check_to_close_over(s, id);
  3162. }
  3163. }
  3164. }
  3165. // update maximim number of labels needed
  3166. if (comp->next_label > max_num_labels) {
  3167. max_num_labels = comp->next_label;
  3168. }
  3169. }
  3170. // compute some things related to scope and identifiers
  3171. for (scope_t *s = comp->scope_head; s != NULL && comp->compile_error == MP_OBJ_NULL; s = s->next) {
  3172. scope_compute_things(s);
  3173. }
  3174. // set max number of labels now that it's calculated
  3175. emit_bc_set_max_num_labels(emit_bc, max_num_labels);
  3176. // compile pass 2 and 3
  3177. #if MICROPY_EMIT_NATIVE
  3178. emit_t *emit_native = NULL;
  3179. #endif
  3180. for (scope_t *s = comp->scope_head; s != NULL && comp->compile_error == MP_OBJ_NULL; s = s->next) {
  3181. #if MICROPY_EMIT_INLINE_ASM
  3182. if (s->emit_options == MP_EMIT_OPT_ASM) {
  3183. // inline assembly
  3184. if (comp->emit_inline_asm == NULL) {
  3185. comp->emit_inline_asm = ASM_EMITTER(new)(max_num_labels);
  3186. }
  3187. comp->emit = NULL;
  3188. comp->emit_inline_asm_method_table = ASM_EMITTER_TABLE;
  3189. compile_scope_inline_asm(comp, s, MP_PASS_CODE_SIZE);
  3190. #if MICROPY_EMIT_INLINE_XTENSA
  3191. // Xtensa requires an extra pass to compute size of l32r const table
  3192. // TODO this can be improved by calculating it during SCOPE pass
  3193. // but that requires some other structural changes to the asm emitters
  3194. #if MICROPY_DYNAMIC_COMPILER
  3195. if (mp_dynamic_compiler.native_arch == MP_NATIVE_ARCH_XTENSA)
  3196. #endif
  3197. {
  3198. compile_scope_inline_asm(comp, s, MP_PASS_CODE_SIZE);
  3199. }
  3200. #endif
  3201. if (comp->compile_error == MP_OBJ_NULL) {
  3202. compile_scope_inline_asm(comp, s, MP_PASS_EMIT);
  3203. }
  3204. } else
  3205. #endif
  3206. {
  3207. // choose the emit type
  3208. switch (s->emit_options) {
  3209. #if MICROPY_EMIT_NATIVE
  3210. case MP_EMIT_OPT_NATIVE_PYTHON:
  3211. case MP_EMIT_OPT_VIPER:
  3212. if (emit_native == NULL) {
  3213. emit_native = NATIVE_EMITTER(new)(&comp->compile_error, &comp->next_label, max_num_labels);
  3214. }
  3215. comp->emit_method_table = NATIVE_EMITTER_TABLE;
  3216. comp->emit = emit_native;
  3217. break;
  3218. #endif // MICROPY_EMIT_NATIVE
  3219. default:
  3220. comp->emit = emit_bc;
  3221. #if MICROPY_EMIT_NATIVE
  3222. comp->emit_method_table = &emit_bc_method_table;
  3223. #endif
  3224. break;
  3225. }
  3226. // need a pass to compute stack size
  3227. compile_scope(comp, s, MP_PASS_STACK_SIZE);
  3228. // second last pass: compute code size
  3229. if (comp->compile_error == MP_OBJ_NULL) {
  3230. compile_scope(comp, s, MP_PASS_CODE_SIZE);
  3231. }
  3232. // final pass: emit code
  3233. if (comp->compile_error == MP_OBJ_NULL) {
  3234. compile_scope(comp, s, MP_PASS_EMIT);
  3235. }
  3236. }
  3237. }
  3238. if (comp->compile_error != MP_OBJ_NULL) {
  3239. // if there is no line number for the error then use the line
  3240. // number for the start of this scope
  3241. compile_error_set_line(comp, comp->scope_cur->pn);
  3242. // add a traceback to the exception using relevant source info
  3243. mp_obj_exception_add_traceback(comp->compile_error, comp->source_file,
  3244. comp->compile_error_line, comp->scope_cur->simple_name);
  3245. }
  3246. // free the emitters
  3247. emit_bc_free(emit_bc);
  3248. #if MICROPY_EMIT_NATIVE
  3249. if (emit_native != NULL) {
  3250. NATIVE_EMITTER(free)(emit_native);
  3251. }
  3252. #endif
  3253. #if MICROPY_EMIT_INLINE_ASM
  3254. if (comp->emit_inline_asm != NULL) {
  3255. ASM_EMITTER(free)(comp->emit_inline_asm);
  3256. }
  3257. #endif
  3258. // free the parse tree
  3259. mp_parse_tree_clear(parse_tree);
  3260. // free the scopes
  3261. mp_raw_code_t *outer_raw_code = module_scope->raw_code;
  3262. for (scope_t *s = module_scope; s;) {
  3263. scope_t *next = s->next;
  3264. scope_free(s);
  3265. s = next;
  3266. }
  3267. if (comp->compile_error != MP_OBJ_NULL) {
  3268. nlr_raise(comp->compile_error);
  3269. } else {
  3270. return outer_raw_code;
  3271. }
  3272. }
  3273. mp_obj_t mp_compile(mp_parse_tree_t *parse_tree, qstr source_file, bool is_repl) {
  3274. mp_raw_code_t *rc = mp_compile_to_raw_code(parse_tree, source_file, is_repl);
  3275. // return function that executes the outer module
  3276. return mp_make_function_from_raw_code(rc, MP_OBJ_NULL, MP_OBJ_NULL);
  3277. }
  3278. #endif // MICROPY_ENABLE_COMPILER