compile.c 146 KB

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