compile.c 145 KB

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