compile.c 139 KB

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