compile.c 140 KB

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