compile.c 143 KB

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