compile.c 138 KB

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