compile.c 141 KB

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