├── stm ├── .gitignore ├── audio.h ├── timer.h ├── i2c.h ├── rtc.h ├── file.h ├── lexerfatfs.h ├── pybwlan.h ├── adc.h ├── stmperiph │ └── stm32f4xx.h ├── usrsw.h ├── lcd.h ├── flash.h ├── servo.h ├── stmusbd │ ├── usbd_pyb_core.h │ ├── usbd_conf.h │ └── usbd_cdc_vcp.h ├── gccollect.h ├── systick.h ├── storage.h ├── cc3k │ ├── pybcc3k.h │ ├── ccdebug.h │ └── host_driver_version.h ├── mma.h ├── qstrdefsport.h ├── usb.h ├── led.h ├── delay.s ├── usart.h ├── fatfs │ └── integer.h ├── std.h ├── gchelper.s ├── malloc0.c ├── gccollect.c ├── sdio.c ├── systick.c ├── stm32fxxx_it.h ├── stmusbh │ └── usbh_conf.h ├── usrsw.c ├── stmusb │ └── usb_otg.h └── lexerfatfs.c ├── tests ├── basics │ ├── import1b.py │ ├── set_union.py │ ├── float1.py │ ├── import1a.py │ ├── zip.py │ ├── fun1.py │ ├── set_clear.py │ ├── set_discard.py │ ├── dict_iterator.py │ ├── lambda1.py │ ├── list_mult.py │ ├── set_iter.py │ ├── generator2.py │ ├── list_clear.py │ ├── dict_get.py │ ├── list_sum.py │ ├── set1.py │ ├── set_add.py │ ├── 0prelim.py │ ├── dict_clear.py │ ├── list_reverse.py │ ├── filter.py │ ├── sorted.py │ ├── class-subclass-builtin.py │ ├── dict_copy.py │ ├── list_copy.py │ ├── builtin-callable.py │ ├── list_count.py │ ├── set_copy.py │ ├── dict_views.py │ ├── fun2.py │ ├── fun3.py │ ├── list_insert.py │ ├── bytes.py │ ├── set_isfooset.py │ ├── set_pop.py │ ├── try1.py │ ├── set_isdisjoint.py │ ├── map.py │ ├── dict_update.py │ ├── enumerate.py │ ├── set_remove.py │ ├── dict_fromkeys.py │ ├── string_startswith.py │ ├── set_update.py │ ├── bytearray1.py │ ├── dict2.py │ ├── set_symmetric_difference.py │ ├── eval1.py │ ├── string-escape.py │ ├── builtin-len1.py │ ├── list_remove.py │ ├── try2.py │ ├── exception1.py │ ├── break.py │ ├── while1.py │ ├── dict_popitem.py │ ├── string-format.py │ ├── list_pop.py │ ├── list_sort.py │ ├── dict1.py │ ├── dict_setdefault.py │ ├── set_intersection.py │ ├── class_store.py │ ├── string_split.py │ ├── list1.py │ ├── is-isnot.py │ ├── closure1.py │ ├── dict_pop.py │ ├── class2.py │ ├── try3.py │ ├── class_item.py │ ├── closure2.py │ ├── continue.py │ ├── class_number.py │ ├── try4.py │ ├── class_inherit1.py │ ├── generator1.py │ ├── int-small.py │ ├── class3.py │ ├── for1.py │ ├── getitem.py │ ├── string_find.py │ ├── class1.py │ ├── set_difference.py │ ├── true-value.py │ ├── comprehension1.py │ ├── list_index.py │ ├── string1.py │ ├── types1.py │ ├── string-slice.py │ ├── generator_send.py │ ├── set_binop.py │ ├── list_compare.py │ ├── containment.py │ └── int1.py ├── bytecode │ ├── mp-tests │ │ ├── call1.py │ │ ├── ifexpr1.py │ │ ├── import2.py │ │ ├── lambda2.py │ │ ├── listcomp2.py │ │ ├── assert1.py │ │ ├── class1.py │ │ ├── fun1.py │ │ ├── closure1.py │ │ ├── slice2.py │ │ ├── lambda1.py │ │ ├── dict1.py │ │ ├── class2.py │ │ ├── setcomp1.py │ │ ├── dictcomp1.py │ │ ├── docstring2.py │ │ ├── import4.py │ │ ├── import1.py │ │ ├── tuple3.py │ │ ├── augassign1.py │ │ ├── try2.py │ │ ├── listcomp1.py │ │ ├── listcomp3.py │ │ ├── yield2.py │ │ ├── fun3.py │ │ ├── if3.py │ │ ├── scope1.py │ │ ├── set1.py │ │ ├── scope0.py │ │ ├── try5.py │ │ ├── docstring1.py │ │ ├── if4.py │ │ ├── import5.py │ │ ├── list2.py │ │ ├── listcomp4.py │ │ ├── class5.py │ │ ├── compare1.py │ │ ├── with1.py │ │ ├── scope6.py │ │ ├── closure2.py │ │ ├── const1.py │ │ ├── list1.py │ │ ├── import3.py │ │ ├── assign2.py │ │ ├── del2.py │ │ ├── string1.py │ │ ├── raise1.py │ │ ├── try6.py │ │ ├── assign1.py │ │ ├── class3.py │ │ ├── class4.py │ │ ├── scope4.py │ │ ├── scope3.py │ │ ├── scope5.py │ │ ├── try3.py │ │ ├── string2.py │ │ ├── decorate1.py │ │ ├── slice1.py │ │ ├── try1.py │ │ ├── closure3.py │ │ ├── tuple2.py │ │ ├── super1.py │ │ ├── tuple1.py │ │ ├── try4.py │ │ ├── closure4.py │ │ ├── del1.py │ │ ├── if1.py │ │ ├── scope2.py │ │ ├── yield1.py │ │ ├── scope7.py │ │ ├── listcomp5.py │ │ ├── locals1.py │ │ ├── fun2.py │ │ ├── if2.py │ │ └── continue1.py │ ├── .gitignore │ ├── pylib-tests │ │ ├── struct.py │ │ ├── antigravity.py │ │ ├── tty.py │ │ ├── this.py │ │ ├── crypt.py │ │ ├── keyword.py │ │ ├── symbol.py │ │ └── nturl2path.py │ ├── README.md │ ├── run-tests │ └── check.py ├── io │ ├── argv.py │ ├── data │ │ └── file1 │ ├── file-iter.py │ └── file1.py ├── README └── run-tests ├── unix-cpy ├── .gitignore ├── Makefile ├── mpconfigport.h └── main.c ├── unix ├── .gitignore ├── qstrdefsport.h ├── Makefile └── mpconfigport.h ├── teensy ├── memzip_files │ ├── boot.py │ ├── test.py │ └── src │ │ ├── test.py │ │ └── main.py ├── lexermemzip.h ├── led.h ├── lcd.c ├── usb.h ├── lexermemzip.c ├── lexerfatfs.c ├── README.md ├── usart.c ├── mpconfigport.h ├── std.h ├── add-memzip.sh ├── usb.c ├── memzip.c ├── led.c ├── memzip.h └── Makefile ├── logo ├── logo.jpg ├── trans-logo.png ├── vector-logo-2.png ├── vector-logo-3.png ├── upython-with-micro.jpg ├── upython-with-micro.png └── micropythonpowered-art.png ├── py ├── compile.h ├── repl.h ├── lexerunix.h ├── objarray.h ├── objtuple.h ├── bc.h ├── stream.h ├── objint.h ├── gc.h ├── nlr.h ├── sequence.c ├── objcell.c ├── objnone.c ├── map.h ├── lexerstr.c ├── qstr.h ├── mkenv.mk ├── qstrdefs.h ├── builtin.h ├── builtinmp.c ├── repl.c ├── objenumerate.c ├── builtineval.c ├── objzip.c ├── lexerunix.c ├── objfilter.c ├── objboundmeth.c ├── objgetitemiter.c ├── objmap.c ├── objclosure.c ├── objbool.c ├── objrange.c ├── runtime.h ├── nlrx86.S ├── unicode.c ├── runtime0.h ├── strtonum.c ├── scope.h └── makeqstrdata.py ├── examples ├── micropython.py ├── pyb.py ├── ledangle.py ├── accellog.py ├── mandel.py ├── unix │ ├── sock-client.py │ └── sock-server.py ├── lcd.py └── conwaylife.py ├── .gitignore ├── LICENSE ├── CODECONVENTIONS.md └── README.md /stm/.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | -------------------------------------------------------------------------------- /stm/audio.h: -------------------------------------------------------------------------------- 1 | void audio_init(void); 2 | -------------------------------------------------------------------------------- /stm/timer.h: -------------------------------------------------------------------------------- 1 | void timer_init(void); 2 | -------------------------------------------------------------------------------- /tests/basics/import1b.py: -------------------------------------------------------------------------------- 1 | var = 123 2 | -------------------------------------------------------------------------------- /unix-cpy/.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | cpy 3 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/call1.py: -------------------------------------------------------------------------------- 1 | f(a, b=c) 2 | -------------------------------------------------------------------------------- /tests/basics/set_union.py: -------------------------------------------------------------------------------- 1 | print({1}.union({2})) 2 | -------------------------------------------------------------------------------- /tests/io/argv.py: -------------------------------------------------------------------------------- 1 | import sys 2 | print(sys.argv) 3 | -------------------------------------------------------------------------------- /unix/.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | micropython 3 | *.py 4 | -------------------------------------------------------------------------------- /teensy/memzip_files/boot.py: -------------------------------------------------------------------------------- 1 | print("Executing boot.py") 2 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/ifexpr1.py: -------------------------------------------------------------------------------- 1 | x = 1 if a else 2 2 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/import2.py: -------------------------------------------------------------------------------- 1 | from a import b 2 | -------------------------------------------------------------------------------- /tests/io/data/file1: -------------------------------------------------------------------------------- 1 | longer line1 2 | line2 3 | line3 4 | -------------------------------------------------------------------------------- /teensy/memzip_files/test.py: -------------------------------------------------------------------------------- 1 | print("Executing /test.py") 2 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/lambda2.py: -------------------------------------------------------------------------------- 1 | f = lambda *args: args 2 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/listcomp2.py: -------------------------------------------------------------------------------- 1 | [x.y for x in k.l] 2 | -------------------------------------------------------------------------------- /stm/i2c.h: -------------------------------------------------------------------------------- 1 | mp_obj_t pyb_I2C(mp_obj_t i2c_id, mp_obj_t i2c_addr); 2 | -------------------------------------------------------------------------------- /stm/rtc.h: -------------------------------------------------------------------------------- 1 | void rtc_init(void); 2 | mp_obj_t pyb_rtc_read(void); 3 | -------------------------------------------------------------------------------- /teensy/memzip_files/src/test.py: -------------------------------------------------------------------------------- 1 | print("Executing /src/test.py") 2 | -------------------------------------------------------------------------------- /tests/basics/float1.py: -------------------------------------------------------------------------------- 1 | # basic float 2 | x = 1 / 2 3 | print(x) 4 | -------------------------------------------------------------------------------- /tests/basics/import1a.py: -------------------------------------------------------------------------------- 1 | import import1b 2 | print(import1b.var) 3 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/assert1.py: -------------------------------------------------------------------------------- 1 | assert x 2 | assert x, 'test' 3 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/class1.py: -------------------------------------------------------------------------------- 1 | class C: 2 | pass 3 | C() 4 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/fun1.py: -------------------------------------------------------------------------------- 1 | def f(*args): 2 | g(*args) 3 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/closure1.py: -------------------------------------------------------------------------------- 1 | # basic closure 2 | # to write! 3 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/slice2.py: -------------------------------------------------------------------------------- 1 | x = x[a, b] 2 | 3 | x[a, b] = x 4 | -------------------------------------------------------------------------------- /stm/file.h: -------------------------------------------------------------------------------- 1 | mp_obj_t pyb_io_open(mp_obj_t o_filename, mp_obj_t o_mode); 2 | -------------------------------------------------------------------------------- /stm/lexerfatfs.h: -------------------------------------------------------------------------------- 1 | mp_lexer_t *mp_lexer_new_from_file(const char *filename); 2 | -------------------------------------------------------------------------------- /stm/pybwlan.h: -------------------------------------------------------------------------------- 1 | void pyb_wlan_init(void); 2 | void pyb_wlan_start(void); 3 | -------------------------------------------------------------------------------- /tests/basics/zip.py: -------------------------------------------------------------------------------- 1 | print(list(zip())) 2 | print(list(zip([1], {2,3}))) 3 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/lambda1.py: -------------------------------------------------------------------------------- 1 | f = lambda: 0 2 | f = lambda x: 1 + x 3 | -------------------------------------------------------------------------------- /logo/logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lite/micropython/master/logo/logo.jpg -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/dict1.py: -------------------------------------------------------------------------------- 1 | x = {} 2 | x = {'a':1} 3 | x = {'a':1, 'b':2} 4 | -------------------------------------------------------------------------------- /tests/basics/fun1.py: -------------------------------------------------------------------------------- 1 | # calling a function 2 | 3 | def f(): 4 | print(1) 5 | f() 6 | -------------------------------------------------------------------------------- /tests/basics/set_clear.py: -------------------------------------------------------------------------------- 1 | s = {1, 2, 3, 4} 2 | print(s.clear()) 3 | print(list(s)) 4 | -------------------------------------------------------------------------------- /tests/basics/set_discard.py: -------------------------------------------------------------------------------- 1 | s = {1, 2} 2 | print(s.discard(1)) 3 | print(list(s)) 4 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/class2.py: -------------------------------------------------------------------------------- 1 | class A: 2 | x = 1 3 | y = x + z 4 | A() 5 | -------------------------------------------------------------------------------- /tests/io/file-iter.py: -------------------------------------------------------------------------------- 1 | f = open("io/data/file1") 2 | for l in f: 3 | print(l) 4 | -------------------------------------------------------------------------------- /logo/trans-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lite/micropython/master/logo/trans-logo.png -------------------------------------------------------------------------------- /py/compile.h: -------------------------------------------------------------------------------- 1 | mp_obj_t mp_compile(mp_parse_node_t pn, qstr source_file, bool is_repl); 2 | -------------------------------------------------------------------------------- /tests/basics/dict_iterator.py: -------------------------------------------------------------------------------- 1 | d = {1: 2, 3: 4} 2 | for i in d: 3 | print(i, d[i]) 4 | -------------------------------------------------------------------------------- /tests/basics/lambda1.py: -------------------------------------------------------------------------------- 1 | # lambda 2 | 3 | f = lambda x, y: x + 3 * y 4 | print(f(3, 5)) 5 | -------------------------------------------------------------------------------- /tests/basics/list_mult.py: -------------------------------------------------------------------------------- 1 | print([0] * 5) 2 | a = [1, 2, 3] 3 | c = a * 3 4 | print(c) 5 | -------------------------------------------------------------------------------- /tests/basics/set_iter.py: -------------------------------------------------------------------------------- 1 | s = {1, 2, 3, 4} 2 | l = list(s) 3 | l.sort() 4 | print(l) 5 | 6 | -------------------------------------------------------------------------------- /tests/bytecode/.gitignore: -------------------------------------------------------------------------------- 1 | output 2 | mp-tests/__pycache__ 3 | pylib-tests/__pycache__ 4 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/setcomp1.py: -------------------------------------------------------------------------------- 1 | x = {a for a in l} 2 | x = {a + b for a, b in l if b} 3 | -------------------------------------------------------------------------------- /logo/vector-logo-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lite/micropython/master/logo/vector-logo-2.png -------------------------------------------------------------------------------- /logo/vector-logo-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lite/micropython/master/logo/vector-logo-3.png -------------------------------------------------------------------------------- /teensy/lexermemzip.h: -------------------------------------------------------------------------------- 1 | mp_lexer_t *mp_lexer_new_from_memzip_file(const char *filename); 2 | 3 | -------------------------------------------------------------------------------- /tests/basics/generator2.py: -------------------------------------------------------------------------------- 1 | gen = (i for i in range(10)) 2 | for i in gen: 3 | print(i) 4 | -------------------------------------------------------------------------------- /tests/basics/list_clear.py: -------------------------------------------------------------------------------- 1 | # tests list.clear 2 | x = [1, 2, 3, 4] 3 | x.clear() 4 | print(x) 5 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/dictcomp1.py: -------------------------------------------------------------------------------- 1 | x = {a:None for a in l} 2 | x = {b:c for c, b in l if c} 3 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/docstring2.py: -------------------------------------------------------------------------------- 1 | # comment before doc string 2 | 3 | """Doc string""" 4 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/import4.py: -------------------------------------------------------------------------------- 1 | import a as y 2 | import a.b as y 3 | import a.b.c as y 4 | -------------------------------------------------------------------------------- /stm/adc.h: -------------------------------------------------------------------------------- 1 | MP_DECLARE_CONST_FUN_OBJ(pyb_ADC_all_obj); 2 | MP_DECLARE_CONST_FUN_OBJ(pyb_ADC_obj); 3 | -------------------------------------------------------------------------------- /tests/basics/dict_get.py: -------------------------------------------------------------------------------- 1 | for d in {}, {42:2}: 2 | print(d.get(42)) 3 | print(d.get(42,2)) 4 | -------------------------------------------------------------------------------- /tests/basics/list_sum.py: -------------------------------------------------------------------------------- 1 | # list addition 2 | a = [1,2,3] 3 | b = [4,5,6] 4 | c = a + b 5 | print(c) 6 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/import1.py: -------------------------------------------------------------------------------- 1 | a = 1 2 | def f(): 3 | global a 4 | import a 5 | import b, c 6 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/tuple3.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | return x, x + 1 3 | for a in b, c: 4 | f(a) 5 | -------------------------------------------------------------------------------- /logo/upython-with-micro.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lite/micropython/master/logo/upython-with-micro.jpg -------------------------------------------------------------------------------- /logo/upython-with-micro.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lite/micropython/master/logo/upython-with-micro.png -------------------------------------------------------------------------------- /stm/stmperiph/stm32f4xx.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lite/micropython/master/stm/stmperiph/stm32f4xx.h -------------------------------------------------------------------------------- /tests/basics/set1.py: -------------------------------------------------------------------------------- 1 | # basic sets 2 | 3 | s = {1} 4 | print(s) 5 | 6 | s = {3, 4, 3, 1} 7 | print(s) 8 | -------------------------------------------------------------------------------- /tests/basics/set_add.py: -------------------------------------------------------------------------------- 1 | s = {1, 2, 3, 4} 2 | print(s.add(5)) 3 | l = list(s) 4 | l.sort() 5 | print(l) 6 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/augassign1.py: -------------------------------------------------------------------------------- 1 | [] = () 2 | x += 1 3 | x.y += 1 4 | x.f().y += 1 5 | x[1] += 2 6 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/try2.py: -------------------------------------------------------------------------------- 1 | def f(): 2 | try: 3 | f() 4 | finally: 5 | g() 6 | -------------------------------------------------------------------------------- /py/repl.h: -------------------------------------------------------------------------------- 1 | #if MICROPY_ENABLE_REPL_HELPERS 2 | bool mp_repl_is_compound_stmt(const char *line); 3 | #endif 4 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/listcomp1.py: -------------------------------------------------------------------------------- 1 | x = (a for a in l) 2 | 3 | f(a for a in l) 4 | f(a + b for a, b in f()) 5 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/listcomp3.py: -------------------------------------------------------------------------------- 1 | x = (a + 1 for a in l if a.f()) 2 | 3 | x = [a + 1 for a in l if a.f()] 4 | -------------------------------------------------------------------------------- /tests/io/file1.py: -------------------------------------------------------------------------------- 1 | f = open("io/data/file1") 2 | print(f.read(5)) 3 | print(f.readline()) 4 | print(f.read()) 5 | -------------------------------------------------------------------------------- /logo/micropythonpowered-art.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lite/micropython/master/logo/micropythonpowered-art.png -------------------------------------------------------------------------------- /stm/usrsw.h: -------------------------------------------------------------------------------- 1 | void switch_init(void); 2 | int switch_get(void); 3 | 4 | MP_DECLARE_CONST_FUN_OBJ(pyb_switch_obj); 5 | -------------------------------------------------------------------------------- /tests/basics/0prelim.py: -------------------------------------------------------------------------------- 1 | # all tests need print to work! make sure it does work 2 | 3 | print(1) 4 | print('abc') 5 | -------------------------------------------------------------------------------- /tests/basics/dict_clear.py: -------------------------------------------------------------------------------- 1 | d = {1: 2, 3: 4} 2 | print(d) 3 | d.clear() 4 | print(d) 5 | d[2] = 42 6 | print(d) 7 | -------------------------------------------------------------------------------- /tests/basics/list_reverse.py: -------------------------------------------------------------------------------- 1 | a = [] 2 | for i in range(100): 3 | a.append(i) 4 | a.reverse() 5 | print(a) 6 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/yield2.py: -------------------------------------------------------------------------------- 1 | def f(): 2 | yield from a 3 | yield from (a, b) 4 | yield from f(a) 5 | -------------------------------------------------------------------------------- /tests/basics/filter.py: -------------------------------------------------------------------------------- 1 | print(list(filter(lambda x: x & 1, range(-3, 4)))) 2 | print(list(filter(None, range(-3, 4)))) 3 | -------------------------------------------------------------------------------- /tests/basics/sorted.py: -------------------------------------------------------------------------------- 1 | print(sorted(set(range(100)))) 2 | print(sorted(set(range(100)), key=lambda x: x + 100*(x % 2))) 3 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/fun3.py: -------------------------------------------------------------------------------- 1 | def f(a, b): 2 | def g(c, d=None, *, e=True): 3 | return a + b + c + d + e 4 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/if3.py: -------------------------------------------------------------------------------- 1 | if a and b: 2 | f() 3 | if a or b: 4 | f() 5 | if a and (b or c): 6 | f() 7 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/scope1.py: -------------------------------------------------------------------------------- 1 | x = 1 2 | print(x) 3 | def f1(): 4 | print(x) 5 | def f2(x): 6 | print(x) 7 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/set1.py: -------------------------------------------------------------------------------- 1 | x = set() 2 | x = {1} 3 | x = {1,} 4 | x = {1, 2} 5 | x = {1, 2,} 6 | x = {1, 2, 3} 7 | -------------------------------------------------------------------------------- /py/lexerunix.h: -------------------------------------------------------------------------------- 1 | mp_lexer_t *mp_lexer_new_from_file(const char *filename); 2 | 3 | void mp_import_set_directory(const char *dir); 4 | -------------------------------------------------------------------------------- /py/objarray.h: -------------------------------------------------------------------------------- 1 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_bytearray_obj); 2 | 3 | mp_obj_t mp_obj_new_bytearray(uint n, void *items); 4 | -------------------------------------------------------------------------------- /tests/basics/class-subclass-builtin.py: -------------------------------------------------------------------------------- 1 | #class mylist(list): 2 | # pass 3 | 4 | #l = mylist() 5 | #l.append(1) 6 | #print(l) 7 | -------------------------------------------------------------------------------- /stm/lcd.h: -------------------------------------------------------------------------------- 1 | void lcd_init(void); 2 | void lcd_print_str(const char *str); 3 | void lcd_print_strn(const char *str, unsigned int len); 4 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/scope0.py: -------------------------------------------------------------------------------- 1 | x = 1 2 | print(x) 3 | 4 | # local store after load 5 | def f(): 6 | print(x) 7 | x = 1 8 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/try5.py: -------------------------------------------------------------------------------- 1 | try: 2 | f() 3 | except A: 4 | g() 5 | except B as b: 6 | h() 7 | finally: 8 | i() 9 | -------------------------------------------------------------------------------- /tests/basics/dict_copy.py: -------------------------------------------------------------------------------- 1 | a = {i: 2*i for i in range(1000)} 2 | b = a.copy() 3 | for i in range(1000): 4 | print(i, b[i]) 5 | print(len(b)) 6 | -------------------------------------------------------------------------------- /tests/basics/list_copy.py: -------------------------------------------------------------------------------- 1 | # list copy tests 2 | a = [1, 2, []] 3 | b = a.copy() 4 | a[-1].append(1) 5 | a.append(4) 6 | print(a) 7 | print(b) 8 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/docstring1.py: -------------------------------------------------------------------------------- 1 | """Module""" 2 | 3 | class A: 4 | """Class""" 5 | pass 6 | 7 | class B: 8 | """Class B""" 9 | -------------------------------------------------------------------------------- /tests/basics/builtin-callable.py: -------------------------------------------------------------------------------- 1 | import sys 2 | print(callable(1)) 3 | print(callable("dfsd")) 4 | print(callable(callable)) 5 | print(callable(sys)) 6 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/if4.py: -------------------------------------------------------------------------------- 1 | if not a: 2 | f() 3 | if not a and b: 4 | f() 5 | if not a and not b: 6 | f() 7 | while not a: 8 | f() 9 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/import5.py: -------------------------------------------------------------------------------- 1 | from a import b as c 2 | from a.b import c as d 3 | from a.b.c import d as e 4 | from a.b.c import d as e, f as h 5 | -------------------------------------------------------------------------------- /tests/basics/list_count.py: -------------------------------------------------------------------------------- 1 | # list count tests 2 | a = [1, 2, 3] 3 | a = a + a + a 4 | b = [0, 0, a, 0, a, 0] 5 | print(a.count(2)) 6 | print(b.count(a)) 7 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/list2.py: -------------------------------------------------------------------------------- 1 | x = [()] 2 | x = [(a)] 3 | x = [(a,)] 4 | x = [(a)] 5 | x = [(a,)] 6 | x = [a, b] 7 | x = [(a, b)] 8 | x = [(a, b, c)] 9 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/listcomp4.py: -------------------------------------------------------------------------------- 1 | # closing over a local variable in a list comprehension 2 | def f(): 3 | a = 1 4 | x = [a + b for b in l] 5 | -------------------------------------------------------------------------------- /tests/basics/set_copy.py: -------------------------------------------------------------------------------- 1 | s = {1, 2, 3, 4} 2 | t = s.copy() 3 | s.add(5) 4 | t.add(7) 5 | for i in s, t: 6 | l = list(i) 7 | l.sort() 8 | print(l) 9 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/class5.py: -------------------------------------------------------------------------------- 1 | class A(B): 2 | pass 3 | class A(object): 4 | pass 5 | class A(x.y()): 6 | pass 7 | class A(B, C): 8 | pass 9 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/compare1.py: -------------------------------------------------------------------------------- 1 | if 1 <= x <= 5: 2 | f() 3 | 4 | if 1 <= x <= y <= 7: 5 | f() 6 | 7 | if a < b > c in l != c is not d: 8 | f() 9 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/with1.py: -------------------------------------------------------------------------------- 1 | with x: 2 | f() 3 | with x(): 4 | f() 5 | with f() as x: 6 | f(x) 7 | with f() as x, g() as y: 8 | f(x, y) 9 | -------------------------------------------------------------------------------- /tests/basics/dict_views.py: -------------------------------------------------------------------------------- 1 | d = {1: 2} 2 | for m in d.items, d.values, d.keys: 3 | print(m()) 4 | print(list(m())) 5 | 6 | # set operations still to come 7 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/scope6.py: -------------------------------------------------------------------------------- 1 | # closed over variable 2 deep 2 | 3 | def f(): 4 | x = 1 5 | def g(): 6 | def h(): 7 | return 1 + x 8 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/closure2.py: -------------------------------------------------------------------------------- 1 | # test closing over an argument 2 | 3 | def f(x): 4 | y = 2 * x 5 | def g(z): 6 | return x + y + z 7 | return g 8 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/const1.py: -------------------------------------------------------------------------------- 1 | x = 1 2 | #x = 1.2 3 | #x = 1.2e5 4 | #x = 1.2e+5 5 | #x = 1.2e-5 6 | x = () 7 | x = (1,) 8 | x = (1,2) 9 | x = ('a',None,3) 10 | -------------------------------------------------------------------------------- /tests/basics/fun2.py: -------------------------------------------------------------------------------- 1 | # calling a function from a function 2 | 3 | def f(x): 4 | print(x + 1) 5 | 6 | def g(x): 7 | f(2 * x) 8 | f(4 * x) 9 | 10 | g(3) 11 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/list1.py: -------------------------------------------------------------------------------- 1 | x = [] 2 | x = [1] 3 | x = [1,] # not implemented 4 | x = [1, 2] 5 | x = [1, 2,] 6 | x = [1, 2, 3] 7 | x = [1, 2, 3, 4] 8 | x = [1, 2, 3, 4, 5] 9 | -------------------------------------------------------------------------------- /stm/flash.h: -------------------------------------------------------------------------------- 1 | uint32_t flash_get_sector_info(uint32_t addr, uint32_t *start_addr, uint32_t *size); 2 | void flash_write(uint32_t flash_dest, const uint32_t *src, uint32_t num_word32); 3 | -------------------------------------------------------------------------------- /tests/basics/fun3.py: -------------------------------------------------------------------------------- 1 | # function with large number of arguments 2 | 3 | def fun(a, b, c, d, e, f, g): 4 | return a + b + c * d + e * f * g 5 | 6 | print(fun(1, 2, 3, 4, 5, 6, 7)) 7 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/import3.py: -------------------------------------------------------------------------------- 1 | import a.b 2 | import a.b.c 3 | from a.b import d 4 | from a.b.c import d 5 | 6 | from a import * 7 | from a import d, e 8 | from a import (d, e) 9 | -------------------------------------------------------------------------------- /tests/basics/list_insert.py: -------------------------------------------------------------------------------- 1 | a = [1, 2, 3] 2 | a.insert(1, 42) 3 | print(a) 4 | a.insert(-1, -1) 5 | print(a) 6 | a.insert(99, 99) 7 | print(a) 8 | a.insert(-99, -99) 9 | print(a) 10 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/assign2.py: -------------------------------------------------------------------------------- 1 | *a, = b 2 | a, *b = c 3 | a, *b, = c 4 | a, *b, c = d 5 | 6 | [*a] = b 7 | [*a,] = b 8 | [a, *b] = c 9 | #[a, *b,] = c 10 | #[a, *b, c] = d 11 | -------------------------------------------------------------------------------- /examples/micropython.py: -------------------------------------------------------------------------------- 1 | # micropython module placeholder for CPython 2 | 3 | # Dummy function decorators 4 | 5 | def nodecor(x): 6 | return x 7 | 8 | byte_code = native = viper = nodecor 9 | -------------------------------------------------------------------------------- /tests/basics/bytes.py: -------------------------------------------------------------------------------- 1 | a = b"123" 2 | print(a) 3 | print(str(a)) 4 | print(repr(a)) 5 | print(a[0], a[2]) 6 | print(a[-1]) 7 | 8 | s = 0 9 | for i in a: 10 | s += i 11 | print(s) 12 | -------------------------------------------------------------------------------- /tests/basics/set_isfooset.py: -------------------------------------------------------------------------------- 1 | sets = [set(), {1}, {1, 2, 3}, {3, 4, 5}, {5, 6, 7}] 2 | for i in sets: 3 | for j in sets: 4 | print(i.issubset(j)) 5 | print(i.issuperset(j)) 6 | -------------------------------------------------------------------------------- /tests/basics/set_pop.py: -------------------------------------------------------------------------------- 1 | s = {1} 2 | print(s.pop()) 3 | try: 4 | print(s.pop(), "!!!") 5 | except KeyError: 6 | pass 7 | else: 8 | print("Failed to raise KeyError") 9 | 10 | -------------------------------------------------------------------------------- /tests/basics/try1.py: -------------------------------------------------------------------------------- 1 | # basic exceptions 2 | x = 1 3 | try: 4 | x.a() 5 | except: 6 | print(x) 7 | 8 | try: 9 | raise IndexError 10 | except IndexError: 11 | print("caught") 12 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/del2.py: -------------------------------------------------------------------------------- 1 | del x 2 | del x, 3 | del x, y 4 | del x, y, 5 | del x, y, z 6 | del (x) 7 | del (x,) 8 | del (x, y) 9 | del (x, y,) 10 | del (x, y, z) 11 | del a, (b, c) 12 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/string1.py: -------------------------------------------------------------------------------- 1 | x = 'abc' 2 | x = "abc" 3 | x = r'abc' 4 | x = 'abc' \ 5 | 'def' 6 | x = ('abc' 7 | 'def') 8 | 9 | x = 'ab"c' 10 | x = "ab'c" 11 | x = '''ab'c''' 12 | -------------------------------------------------------------------------------- /stm/servo.h: -------------------------------------------------------------------------------- 1 | void servo_init(void); 2 | 3 | mp_obj_t pyb_servo_set(mp_obj_t port, mp_obj_t value); 4 | mp_obj_t pyb_pwm_set(mp_obj_t period, mp_obj_t pulse); 5 | mp_obj_t pyb_Servo(mp_obj_t servo_id); 6 | -------------------------------------------------------------------------------- /tests/basics/set_isdisjoint.py: -------------------------------------------------------------------------------- 1 | s = {1, 2, 3, 4} 2 | print(s.isdisjoint({1})) 3 | print(s.isdisjoint([2])) 4 | print(s.isdisjoint([])) 5 | print(s.isdisjoint({7,8,9,10})) 6 | print(s.isdisjoint([7,8,9,1])) 7 | -------------------------------------------------------------------------------- /tests/basics/map.py: -------------------------------------------------------------------------------- 1 | print(list(map(lambda x: x & 1, range(-3, 4)))) 2 | print(list(map(abs, range(-3, 4)))) 3 | print(list(map(set, [[i] for i in range(-3, 4)]))) 4 | print(list(map(pow, range(4), range(4)))) 5 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/raise1.py: -------------------------------------------------------------------------------- 1 | def f(): 2 | raise 3 | def g(): 4 | raise 1 5 | def h(): 6 | raise 1 from 2 7 | def i(): 8 | try: 9 | f() 10 | except: 11 | raise 12 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/try6.py: -------------------------------------------------------------------------------- 1 | try: 2 | f() 3 | except: 4 | g() 5 | else: 6 | h() 7 | 8 | try: 9 | f() 10 | except: 11 | g() 12 | else: 13 | h() 14 | finally: 15 | i() 16 | -------------------------------------------------------------------------------- /teensy/memzip_files/src/main.py: -------------------------------------------------------------------------------- 1 | print("Executing main.py") 2 | 3 | x=pyb.led(1) 4 | pyb.delay(100) 5 | x=pyb.led(0) 6 | pyb.delay(100) 7 | x=pyb.led(1) 8 | pyb.delay(100) 9 | x=pyb.led(0) 10 | 11 | 12 | -------------------------------------------------------------------------------- /tests/basics/dict_update.py: -------------------------------------------------------------------------------- 1 | d = {1:2, 3:4} 2 | print(d) 3 | d.update(["ab"]) 4 | print(d[1]) 5 | print(d[3]) 6 | print(d["a"]) 7 | print(len(d)) 8 | d.update([(1,4)]) 9 | print(d[1]) 10 | print(len(d)) 11 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/assign1.py: -------------------------------------------------------------------------------- 1 | [] = () 2 | [] = [] 3 | a = b 4 | (a) = b 5 | a, b = c, d 6 | a, b, c = d, e, f 7 | a, b, c, d = e, f, g, h 8 | #(a, b) = c, d 9 | #a, b = (c, d) 10 | #(a, b) = (c, d) 11 | -------------------------------------------------------------------------------- /stm/stmusbd/usbd_pyb_core.h: -------------------------------------------------------------------------------- 1 | extern USBD_Class_cb_TypeDef USBD_PYB_cb; 2 | extern USBD_Class_cb_TypeDef USBD_PYB_HID_cb; 3 | 4 | uint8_t USBD_HID_SendReport(USB_OTG_CORE_HANDLE *pdev, uint8_t *report, uint16_t len); 5 | -------------------------------------------------------------------------------- /tests/basics/enumerate.py: -------------------------------------------------------------------------------- 1 | print(list(enumerate([]))) 2 | print(list(enumerate([1, 2, 3]))) 3 | print(list(enumerate([1, 2, 3], 5))) 4 | print(list(enumerate([1, 2, 3], -5))) 5 | print(list(enumerate(range(10000)))) 6 | 7 | -------------------------------------------------------------------------------- /tests/basics/set_remove.py: -------------------------------------------------------------------------------- 1 | s = {1} 2 | print(s.remove(1)) 3 | print(list(s)) 4 | try: 5 | print(s.remove(1), "!!!") 6 | except KeyError: 7 | pass 8 | else: 9 | print("failed to raise KeyError") 10 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/class3.py: -------------------------------------------------------------------------------- 1 | class A: 2 | def f(x): 3 | return x 4 | def g(y): 5 | def h(z): 6 | return x + y + z 7 | h(y) 8 | A() 9 | A.f(1) 10 | A.g(2)(3) 11 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/class4.py: -------------------------------------------------------------------------------- 1 | class A: 2 | def __init__(self, x): 3 | self.x = x 4 | self.y = 0 5 | 6 | def get(self): 7 | return self.x + self.y 8 | A(1) 9 | A(2).get() 10 | -------------------------------------------------------------------------------- /tests/basics/dict_fromkeys.py: -------------------------------------------------------------------------------- 1 | d = dict.fromkeys([1, 2, 3, 4]) 2 | l = list(d.keys()) 3 | l.sort() 4 | print(l) 5 | 6 | d = dict.fromkeys([1, 2, 3, 4], 42) 7 | l = list(d.values()) 8 | l.sort() 9 | print(l) 10 | 11 | -------------------------------------------------------------------------------- /tests/basics/string_startswith.py: -------------------------------------------------------------------------------- 1 | print("foobar".startswith("foo")) 2 | print("foobar".startswith("Foo")) 3 | print("foobar".startswith("foo1")) 4 | print("foobar".startswith("foobar")) 5 | print("foobar".startswith("")) 6 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/scope4.py: -------------------------------------------------------------------------------- 1 | # test scope 2 | 3 | def f(x): 4 | global x42 5 | print(x, x42) 6 | x42 = x 7 | 8 | x42 = 123 9 | f(1) 10 | print(x42) 11 | 12 | x42 = 456 13 | f(2) 14 | print(x42) 15 | -------------------------------------------------------------------------------- /tests/basics/set_update.py: -------------------------------------------------------------------------------- 1 | def report(s): 2 | l = list(s) 3 | l.sort() 4 | print(l) 5 | 6 | s = {1} 7 | s.update() 8 | report(s) 9 | s.update([2]) 10 | report(s) 11 | s.update([1,3], [2,2,4]) 12 | report(s) 13 | -------------------------------------------------------------------------------- /tests/basics/bytearray1.py: -------------------------------------------------------------------------------- 1 | a = bytearray([1, 2, 200]) 2 | print(a[0], a[2]) 3 | print(a[-1]) 4 | a[2] = 255 5 | print(a[-1]) 6 | a.append(10) 7 | print(len(a)) 8 | 9 | s = 0 10 | for i in a: 11 | s += i 12 | print(s) 13 | -------------------------------------------------------------------------------- /tests/basics/dict2.py: -------------------------------------------------------------------------------- 1 | # using strings as keys in dict 2 | 3 | d = {'1': 1, '2': 2} 4 | print(d['1'], d['2']) 5 | 6 | d['3'] = 3 7 | print(d['1'], d['2'], d['3']) 8 | 9 | d['2'] = 222 10 | print(d['1'], d['2'], d['3']) 11 | -------------------------------------------------------------------------------- /tests/basics/set_symmetric_difference.py: -------------------------------------------------------------------------------- 1 | print({1,2}.symmetric_difference({2,3})) 2 | print({1,2}.symmetric_difference([2,3])) 3 | s = {1,2} 4 | print(s.symmetric_difference_update({2,3})) 5 | l = list(s) 6 | l.sort() 7 | print(l) 8 | -------------------------------------------------------------------------------- /teensy/led.h: -------------------------------------------------------------------------------- 1 | typedef enum { 2 | PYB_LED_BUILTIN = 0, 3 | } pyb_led_t; 4 | 5 | void led_init(void); 6 | void led_state(pyb_led_t led, int state); 7 | void led_toggle(pyb_led_t led); 8 | 9 | mp_obj_t pyb_Led(mp_obj_t led_id); 10 | -------------------------------------------------------------------------------- /tests/basics/eval1.py: -------------------------------------------------------------------------------- 1 | # builtin eval 2 | 3 | eval('1 + 2') 4 | eval('1 + 2\n') 5 | eval('1 + 2\n\n#comment\n') 6 | 7 | x = 4 8 | eval('x') 9 | 10 | eval('lambda x: x + 10')(-5) 11 | 12 | y = 6 13 | eval('lambda: y * 2')() 14 | -------------------------------------------------------------------------------- /tests/basics/string-escape.py: -------------------------------------------------------------------------------- 1 | a = "a\1b" 2 | print(len(a)) 3 | print(ord(a[1])) 4 | print(len("a\123b")) 5 | a = "a\12345b" 6 | print(len(a)) 7 | print(ord(a[1])) 8 | 9 | a = "a\xffb" 10 | print(len(a)) 11 | print(ord(a[1])) 12 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/scope3.py: -------------------------------------------------------------------------------- 1 | # test nested functions and scope 2 | 3 | def f(x): 4 | def f2(y): 5 | return y + x 6 | print(f2(x)) 7 | return f2 8 | x=f(2) 9 | print(x, x(5)) 10 | f=123 11 | print(f(f)) 12 | -------------------------------------------------------------------------------- /tests/basics/builtin-len1.py: -------------------------------------------------------------------------------- 1 | # builtin len 2 | 3 | print(len(())) 4 | print(len((1,))) 5 | print(len((1, 2))) 6 | 7 | print(len([])) 8 | x = [1, 2, 3] 9 | print(len(x)) 10 | 11 | f = len 12 | print(f({})) 13 | print(f({1:2, 3:4})) 14 | -------------------------------------------------------------------------------- /tests/basics/list_remove.py: -------------------------------------------------------------------------------- 1 | a = [1, 2, 3] 2 | print(a.remove(2)) 3 | print(a) 4 | try: 5 | a.remove(2) 6 | except ValueError: 7 | print("Raised ValueError") 8 | else: 9 | raise AssertionError("Did not raise ValueError") 10 | -------------------------------------------------------------------------------- /tests/basics/try2.py: -------------------------------------------------------------------------------- 1 | # nested try's 2 | 3 | try: 4 | print("try 1") 5 | try: 6 | print("try 2") 7 | foo() 8 | except: 9 | print("except 2") 10 | bar() 11 | except: 12 | print("except 1") 13 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/scope5.py: -------------------------------------------------------------------------------- 1 | # test scope 2 | 3 | def f(x): 4 | def f2(y): 5 | print(y, x42, y42) 6 | x42 = x = y42 = 123 7 | myf2 = f2 8 | x42 = 456 9 | return myf2 10 | 11 | myf = f(1) 12 | myf(1) 13 | -------------------------------------------------------------------------------- /tests/basics/exception1.py: -------------------------------------------------------------------------------- 1 | print(repr(IndexError())) 2 | print(str(IndexError())) 3 | 4 | print(repr(IndexError("foo"))) 5 | print(str(IndexError("foo"))) 6 | 7 | a = IndexError(1, "test", [100, 200]) 8 | print(repr(a)) 9 | print(str(a)) 10 | -------------------------------------------------------------------------------- /tests/basics/break.py: -------------------------------------------------------------------------------- 1 | while True: 2 | break 3 | 4 | for i in range(4): 5 | print('one', i) 6 | if i > 2: 7 | break 8 | print('two', i) 9 | 10 | for i in [1, 2, 3, 4]: 11 | if i == 3: 12 | break 13 | print(i) 14 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/try3.py: -------------------------------------------------------------------------------- 1 | def f(): 2 | try: 3 | f() 4 | except: 5 | g() 6 | finally: 7 | f() 8 | 9 | try: 10 | f() 11 | except Exception: 12 | g() 13 | finally: 14 | f() 15 | -------------------------------------------------------------------------------- /tests/basics/while1.py: -------------------------------------------------------------------------------- 1 | # basic while loop 2 | 3 | x = 0 4 | while x < 2: 5 | y = 0 6 | while y < 2: 7 | z = 0 8 | while z < 2: 9 | z = z + 1 10 | print(x, y, z) 11 | y = y + 1 12 | x = x + 1 13 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/string2.py: -------------------------------------------------------------------------------- 1 | 'abc' 2 | class f: 3 | u"123" 4 | pass 5 | x = 'abc' 6 | x = u"abc" 7 | x = u"ab\\c" 8 | x = r"ab\\c" 9 | x = b"abc" 10 | x = rb"abc" 11 | x = b"ab\\c" 12 | x = rb"ab\\c" 13 | x = """abc""" 14 | x = b"""abc""" 15 | -------------------------------------------------------------------------------- /stm/gccollect.h: -------------------------------------------------------------------------------- 1 | #define HEAP_END (0x2001c000) // tunable 2 | #define RAM_END (0x20020000) // fixed for chip 3 | 4 | extern uint32_t _ram_start; 5 | extern uint32_t _heap_start; 6 | 7 | void gc_collect(void); 8 | 9 | MP_DECLARE_CONST_FUN_OBJ(pyb_gc_obj); 10 | -------------------------------------------------------------------------------- /py/objtuple.h: -------------------------------------------------------------------------------- 1 | typedef struct _mp_obj_tuple_t { 2 | mp_obj_base_t base; 3 | machine_uint_t len; 4 | mp_obj_t items[]; 5 | } mp_obj_tuple_t; 6 | 7 | void tuple_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t o_in, mp_print_kind_t kind); 8 | -------------------------------------------------------------------------------- /tests/README: -------------------------------------------------------------------------------- 1 | This directory contains tests for various functionality areas of MicroPython. 2 | To run all stable tests, run "run-tests" script in this directory. Note 3 | that bytecode tests are not yet stable and should be run separately in 4 | "bytecode" subdirectory. 5 | -------------------------------------------------------------------------------- /tests/basics/dict_popitem.py: -------------------------------------------------------------------------------- 1 | d={1:2,3:4} 2 | print(d.popitem()) 3 | print(d) 4 | print(d.popitem()) 5 | print(d) 6 | try: 7 | print(d.popitem(), "!!!",) 8 | except KeyError: 9 | print("Raised KeyError") 10 | else: 11 | print("Did not raise KeyError") 12 | -------------------------------------------------------------------------------- /tests/basics/string-format.py: -------------------------------------------------------------------------------- 1 | print("{}-{}".format(1, [4, 5])) 2 | print("{0}-{1}".format(1, [4, 5])) 3 | print("{:x}".format(1)) 4 | print("{!r}".format(2)) 5 | # TODO 6 | #print("{1}-{0}".format(1, [4, 5])) 7 | #print("{:x}".format(0x10)) 8 | #print("{!r}".format("foo")) 9 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/decorate1.py: -------------------------------------------------------------------------------- 1 | @d 2 | def f(): 3 | pass 4 | 5 | @d 6 | @e 7 | def g(): 8 | pass 9 | 10 | @d.e.f 11 | def h(): 12 | pass 13 | 14 | @d(a + 1) 15 | def i(): 16 | pass 17 | 18 | @d(a + 1, b + 2) 19 | def i(): 20 | pass 21 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/slice1.py: -------------------------------------------------------------------------------- 1 | x = x[:] 2 | x = x[::] 3 | x = x[::c] 4 | x = x[:b] 5 | x = x[:b:] 6 | x = x[:b:c] 7 | x = x[a] 8 | x = x[a:] 9 | x = x[a::] 10 | x = x[a::c] 11 | x = x[a:b] 12 | x = x[a:b:] 13 | x = x[a:b:c] 14 | 15 | x[0] = 1 16 | x[x] = x 17 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/try1.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | try: 3 | f(x) 4 | except: 5 | f(x) 6 | try: 7 | f(x) 8 | except Exception: 9 | f(x) 10 | try: 11 | f(x) 12 | except Exception as e: 13 | f(x, e) 14 | -------------------------------------------------------------------------------- /tests/basics/list_pop.py: -------------------------------------------------------------------------------- 1 | # list poppin' 2 | a = [1, 2, 3] 3 | print(a.pop()) 4 | print(a.pop()) 5 | print(a.pop()) 6 | try: 7 | print(a.pop()) 8 | except IndexError: 9 | print("IndexError raised") 10 | else: 11 | raise AssertionError("No IndexError raised") 12 | -------------------------------------------------------------------------------- /tests/basics/list_sort.py: -------------------------------------------------------------------------------- 1 | l = [1, 3, 2, 5] 2 | print(l) 3 | l.sort() 4 | print(l) 5 | l.sort(key=lambda x: -x) 6 | print(l) 7 | l.sort(key=lambda x: -x, reverse=True) 8 | print(l) 9 | l.sort(reverse=True) 10 | print(l) 11 | l.sort(reverse=False) 12 | print(l) 13 | 14 | -------------------------------------------------------------------------------- /py/bc.h: -------------------------------------------------------------------------------- 1 | mp_obj_t mp_execute_byte_code(const byte *code, const mp_obj_t *args, uint n_args, uint n_state); 2 | bool mp_execute_byte_code_2(const byte *code_info, const byte **ip_in_out, mp_obj_t *fastn, mp_obj_t **sp_in_out); 3 | void mp_byte_code_print(const byte *code, int len); 4 | -------------------------------------------------------------------------------- /tests/basics/dict1.py: -------------------------------------------------------------------------------- 1 | # basic dictionary 2 | 3 | d = {} 4 | print(d) 5 | d[2] = 123 6 | print(d) 7 | d = {1:2} 8 | d[3] = 3 9 | print(d) 10 | d[1] = 0 11 | print(d) 12 | print(d[1]) 13 | 14 | x = 1 15 | while x < 1000: 16 | d[x] = x 17 | x += 1 18 | print(d[500]) 19 | -------------------------------------------------------------------------------- /tests/basics/dict_setdefault.py: -------------------------------------------------------------------------------- 1 | d = {} 2 | print(d.setdefault(1)) 3 | print(d.setdefault(1)) 4 | print(d.setdefault(5, 42)) 5 | print(d.setdefault(5, 1)) 6 | print(d[1]) 7 | print(d[5]) 8 | d.pop(5) 9 | print(d.setdefault(5, 1)) 10 | print(d[1]) 11 | print(d[5]) 12 | 13 | 14 | -------------------------------------------------------------------------------- /tests/basics/set_intersection.py: -------------------------------------------------------------------------------- 1 | def report(s): 2 | l = list(s) 3 | l.sort() 4 | print(l) 5 | 6 | s = {1, 2, 3, 4} 7 | report(s) 8 | report(s.intersection({1, 3})) 9 | report(s.intersection([3, 4])) 10 | 11 | print(s.intersection_update([1])) 12 | report(s) 13 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/closure3.py: -------------------------------------------------------------------------------- 1 | # test when different variables are closed over by different functions 2 | 3 | def f(): 4 | l1 = 1 5 | l2 = 2 6 | l3 = 3 7 | 8 | def g(): 9 | return l1 + l2 10 | 11 | def h(): 12 | return l2 + l3 13 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/tuple2.py: -------------------------------------------------------------------------------- 1 | x = t 2 | x, = t 3 | x, y = t 4 | x, y, = t 5 | x, y, z = t 6 | x, y, z, = t 7 | x, y, z, z = a, b, c, d 8 | 9 | (x) = t 10 | (x,) = t 11 | (x, y) = t 12 | (x, y,) = t 13 | (x, y, z) = t 14 | (x, y, z,) = t 15 | (x, y, z, z) = a, b, c, d 16 | -------------------------------------------------------------------------------- /unix/qstrdefsport.h: -------------------------------------------------------------------------------- 1 | // qstrs specific to this port 2 | 3 | Q(sys) 4 | Q(argv) 5 | Q(open) 6 | Q(stdin) 7 | Q(stdout) 8 | Q(stderr) 9 | Q(rawsocket) 10 | Q(socket) 11 | Q(sockaddr_in) 12 | Q(htons) 13 | Q(inet_aton) 14 | Q(gethostbyname) 15 | Q(getaddrinfo) 16 | Q(rawsocket) 17 | -------------------------------------------------------------------------------- /teensy/lcd.c: -------------------------------------------------------------------------------- 1 | #include "misc.h" 2 | #include "../stm/lcd.h" 3 | 4 | void lcd_init(void) { 5 | } 6 | 7 | void lcd_print_str(const char *str) { 8 | (void)str; 9 | } 10 | 11 | void lcd_print_strn(const char *str, unsigned int len) { 12 | (void)str; 13 | (void)len; 14 | } 15 | -------------------------------------------------------------------------------- /tests/basics/class_store.py: -------------------------------------------------------------------------------- 1 | # store to class vs instance 2 | 3 | class C: 4 | pass 5 | 6 | c = C() 7 | c.x = 1 8 | print(c.x) 9 | C.x = 2 10 | C.y = 3 11 | print(c.x, c.y) 12 | print(C.x, C.y) 13 | print(C().x, C().y) 14 | c = C() 15 | print(c.x) 16 | c.x = 4 17 | print(c.x) 18 | -------------------------------------------------------------------------------- /stm/systick.h: -------------------------------------------------------------------------------- 1 | extern volatile uint32_t sys_tick_counter; 2 | 3 | void sys_tick_init(void); 4 | void SysTick_Handler(void); 5 | void sys_tick_delay_ms(uint32_t delay_ms); 6 | void sys_tick_wait_at_least(uint32_t stc, uint32_t delay_ms); 7 | bool sys_tick_has_passed(uint32_t stc, uint32_t delay_ms); 8 | -------------------------------------------------------------------------------- /tests/basics/string_split.py: -------------------------------------------------------------------------------- 1 | print("a b".split()) 2 | print(" a b ".split(None)) 3 | print(" a b ".split(None, 1)) 4 | print(" a b ".split(None, 2)) 5 | print(" a b c ".split(None, 1)) 6 | print(" a b c ".split(None, 0)) 7 | print(" a b c ".split(None, -1)) 8 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/super1.py: -------------------------------------------------------------------------------- 1 | class A(B): 2 | def f(): 3 | super.a() 4 | 5 | class B(C): 6 | def g(): 7 | def h(): 8 | super.a() 9 | 10 | super.a() 11 | 12 | def i(): 13 | super.a() 14 | 15 | def j(): 16 | def k(): 17 | super.a() 18 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/tuple1.py: -------------------------------------------------------------------------------- 1 | x = () 2 | x = a 3 | x = a, 4 | x = a, 2 5 | x = a, 2, 6 | x = a, 2, 3 7 | x = a, 2, 3, 4 8 | x = a, 2, 3, 4, 5 9 | 10 | x = () 11 | x = (a) 12 | x = (a,) 13 | x = (a, 2) 14 | x = (a, 2,) 15 | x = (a, 2, 3) 16 | x = (a, 2, 3, 4) 17 | x = (a, 2, 3, 4, 5) 18 | -------------------------------------------------------------------------------- /tests/basics/list1.py: -------------------------------------------------------------------------------- 1 | # basic list functionality 2 | x = [1, 2, 3 * 4] 3 | print(x) 4 | x[0] = 4 5 | print(x) 6 | x[1] += -4 7 | print(x) 8 | x.append(5) 9 | print(x) 10 | f = x.append 11 | f(4) 12 | print(x) 13 | 14 | x.extend([100, 200]) 15 | print(x) 16 | 17 | x += [2, 1] 18 | print(x) 19 | -------------------------------------------------------------------------------- /tests/basics/is-isnot.py: -------------------------------------------------------------------------------- 1 | print(1 is 1) 2 | print(1 is 2) 3 | print(1 is not 1) 4 | print(1 is not 2) 5 | 6 | 7 | print([1, 2] is [1, 2]) 8 | a = [1, 2] 9 | b = a 10 | print(b is a) 11 | 12 | # TODO: strings require special "is" handling, postponed 13 | # until qstr refactor. 14 | #print("a" is "a") 15 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/try4.py: -------------------------------------------------------------------------------- 1 | try: 2 | f() 3 | except A: 4 | g() 5 | except: 6 | h() 7 | 8 | try: 9 | f() 10 | except A: 11 | g() 12 | except B as c: 13 | h() 14 | 15 | try: 16 | f() 17 | except A: 18 | g() 19 | except B as c: 20 | h() 21 | except: 22 | i() 23 | -------------------------------------------------------------------------------- /stm/storage.h: -------------------------------------------------------------------------------- 1 | void storage_init(void); 2 | uint32_t storage_get_block_size(void); 3 | uint32_t storage_get_block_count(void); 4 | bool storage_needs_flush(void); 5 | void storage_flush(void); 6 | bool storage_read_block(uint8_t *dest, uint32_t block); 7 | bool storage_write_block(const uint8_t *src, uint32_t block); 8 | -------------------------------------------------------------------------------- /tests/basics/closure1.py: -------------------------------------------------------------------------------- 1 | # closures 2 | 3 | def f(x): 4 | y = 2 * x 5 | def g(z): 6 | return y + z 7 | return g 8 | 9 | print(f(1)(1)) 10 | 11 | x = f(2) 12 | y = f(3) 13 | print(x(1), x(2), x(3)) 14 | print(y(1), y(2), y(3)) 15 | print(x(1), x(2), x(3)) 16 | print(y(1), y(2), y(3)) 17 | -------------------------------------------------------------------------------- /tests/basics/dict_pop.py: -------------------------------------------------------------------------------- 1 | d = {1: 2, 3: 4} 2 | print(d.pop(3), d) 3 | print(d) 4 | print(d.pop(1, 42), d) 5 | print(d.pop(1, 42), d) 6 | print(d.pop(1, None), d) 7 | try: 8 | print(d.pop(1), "!!!",) 9 | except KeyError: 10 | print("Raised KeyError") 11 | else: 12 | print("Did not rise KeyError!") 13 | -------------------------------------------------------------------------------- /tests/basics/class2.py: -------------------------------------------------------------------------------- 1 | # class with __init__ 2 | 3 | class C1: 4 | def __init__(self): 5 | self.x = 1 6 | 7 | c1 = C1() 8 | print(type(c1) == C1) 9 | print(c1.x) 10 | 11 | class C2: 12 | def __init__(self, x): 13 | self.x = x 14 | 15 | c2 = C2(4) 16 | print(type(c2) == C2) 17 | print(c2.x) 18 | -------------------------------------------------------------------------------- /tests/basics/try3.py: -------------------------------------------------------------------------------- 1 | # nested exceptions 2 | 3 | def f(): 4 | try: 5 | foo() 6 | except: 7 | print("except 1") 8 | try: 9 | baz() 10 | except: 11 | print("except 2") 12 | bar() 13 | 14 | try: 15 | f() 16 | except: 17 | print("f except") 18 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/closure4.py: -------------------------------------------------------------------------------- 1 | # test when a function has cell and free vars 2 | 3 | def f(): 4 | f_local = 1 5 | f_cell = 2 6 | 7 | def g(): 8 | g_local = 3 9 | g_cell = f_cell + 4 10 | 11 | def h(): 12 | h1_local = 4 13 | h2_local = f_cell + g_cell 14 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/del1.py: -------------------------------------------------------------------------------- 1 | del x 2 | del x.y 3 | del x().y 4 | del g 5 | del x[a] 6 | def f(): 7 | global g 8 | del x 9 | del g 10 | local = 1 11 | local2 = 2 12 | local3 = 3 13 | del local, local2, local3 14 | def f2(): 15 | nonlocal local3 16 | del local2, local3 17 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/if1.py: -------------------------------------------------------------------------------- 1 | if x: 2 | x() 3 | if x: 4 | x() 5 | elif y: 6 | y() 7 | if x: 8 | x() 9 | else: 10 | zz() 11 | if x: 12 | x() 13 | elif y: 14 | y() 15 | else: 16 | zz() 17 | if x: 18 | x() 19 | elif y: 20 | y() 21 | elif z: 22 | z() 23 | else: 24 | zz() 25 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/scope2.py: -------------------------------------------------------------------------------- 1 | # scope 2 | 3 | gl = 1 4 | 5 | def f(x): 6 | global gl 7 | gl += 2 8 | lo1 = 3 9 | lo2 = 4 10 | lo3 = 5 11 | 12 | def f2(x, y): 13 | global gl 14 | nonlocal lo3 15 | lo3 = 5 16 | lo4 = gl + lo2 + lo3 17 | 18 | return f2 19 | -------------------------------------------------------------------------------- /tests/basics/class_item.py: -------------------------------------------------------------------------------- 1 | # test class with __getitem__ and __setitem__ methods 2 | 3 | class C: 4 | def __getitem__(self, item): 5 | print('get', item) 6 | return 'item' 7 | 8 | def __setitem__(self, item, value): 9 | print('set', item, value) 10 | 11 | c = C() 12 | print(c[1]) 13 | c[1] = 2 14 | -------------------------------------------------------------------------------- /tests/bytecode/pylib-tests/struct.py: -------------------------------------------------------------------------------- 1 | __all__ = [ 2 | # Functions 3 | 'calcsize', 'pack', 'pack_into', 'unpack', 'unpack_from', 4 | 5 | # Classes 6 | 'Struct', 7 | 8 | # Exceptions 9 | 'error' 10 | ] 11 | 12 | from _struct import * 13 | from _struct import _clearcache 14 | from _struct import __doc__ 15 | -------------------------------------------------------------------------------- /tests/basics/closure2.py: -------------------------------------------------------------------------------- 1 | # closures; closing over an argument 2 | 3 | def f(x): 4 | y = 2 * x 5 | def g(z): 6 | return x + y + z 7 | return g 8 | 9 | print(f(1)(1)) 10 | 11 | x = f(2) 12 | y = f(3) 13 | print(x(1), x(2), x(3)) 14 | print(y(1), y(2), y(3)) 15 | print(x(1), x(2), x(3)) 16 | print(y(1), y(2), y(3)) 17 | -------------------------------------------------------------------------------- /tests/basics/continue.py: -------------------------------------------------------------------------------- 1 | for i in range(4): 2 | print('one', i) 3 | if i > 2: 4 | continue 5 | print('two', i) 6 | 7 | for i in range(4): 8 | print('one', i) 9 | if i < 2: 10 | continue 11 | print('two', i) 12 | 13 | for i in [1, 2, 3, 4]: 14 | if i == 3: 15 | continue 16 | print(i) 17 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/yield1.py: -------------------------------------------------------------------------------- 1 | # generators and yield 2 | 3 | def main(): 4 | def f(): 5 | print(123) 6 | yield 7 | print(456) 8 | yield 2 9 | print(789) 10 | 11 | a = f() 12 | print(a) 13 | print(a.__next__()) 14 | print(a.__next__()) 15 | #print(a.__next__()) 16 | 17 | main() 18 | -------------------------------------------------------------------------------- /tests/basics/class_number.py: -------------------------------------------------------------------------------- 1 | # test class with __add__ and __sub__ methods 2 | 3 | class C: 4 | def __init__(self, value): 5 | self.value = value 6 | 7 | def __add__(self, rhs): 8 | print(self.value, '+', rhs) 9 | 10 | def __sub__(self, rhs): 11 | print(self.value, '-', rhs) 12 | 13 | c = C(0) 14 | c + 1 15 | c - 2 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Sources 2 | ################### 3 | *.o 4 | *.a 5 | *.elf 6 | *.bin 7 | *.map 8 | *.hex 9 | *.dis 10 | 11 | # Packages 12 | ############ 13 | 14 | # Logs and Databases 15 | ###################### 16 | *.log 17 | 18 | # VIM Swap Files 19 | ###################### 20 | *.swp 21 | 22 | # Build directory 23 | ###################### 24 | build/ 25 | -------------------------------------------------------------------------------- /py/stream.h: -------------------------------------------------------------------------------- 1 | extern const mp_obj_fun_native_t mp_stream_read_obj; 2 | extern const mp_obj_fun_native_t mp_stream_readall_obj; 3 | extern const mp_obj_fun_native_t mp_stream_unbuffered_readline_obj; 4 | extern const mp_obj_fun_native_t mp_stream_write_obj; 5 | 6 | // Iterator which uses mp_stream_unbuffered_readline_obj 7 | mp_obj_t mp_stream_unbuffered_iter(mp_obj_t self); 8 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/scope7.py: -------------------------------------------------------------------------------- 1 | # test order of closed over locals 2 | # not that CPython seems to sort closed over variables (but not fast locals) 3 | 4 | def f(): 5 | l1 = 1 6 | l2 = 4 7 | l3 = 3 8 | l4 = 2 9 | l5 = 5 10 | 11 | def g(): 12 | return l1 + l4 + l3 + l2 + l5 13 | 14 | def h(): 15 | return l1 + l2 + l3 + l4 + l5 16 | -------------------------------------------------------------------------------- /py/objint.h: -------------------------------------------------------------------------------- 1 | typedef struct _mp_obj_int_t { 2 | mp_obj_base_t base; 3 | #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE 4 | mp_longint_impl_t val; 5 | #endif 6 | } mp_obj_int_t; 7 | 8 | void int_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind); 9 | mp_obj_t int_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in); 10 | -------------------------------------------------------------------------------- /teensy/usb.h: -------------------------------------------------------------------------------- 1 | void usb_init(void); 2 | int usb_vcp_is_enabled(void); 3 | int usb_vcp_is_connected(void); 4 | int usb_vcp_rx_any(void); 5 | char usb_vcp_rx_get(void); 6 | void usb_vcp_send_str(const char* str); 7 | void usb_vcp_send_strn(const char* str, int len); 8 | void usb_vcp_send_strn_cooked(const char *str, int len); 9 | void usb_hid_send_report(uint8_t *buf); // 4 bytes for mouse: ?, x, y, ? 10 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/listcomp5.py: -------------------------------------------------------------------------------- 1 | # nested ifs 2 | x = [a for a in l if a if a + 1] 3 | x = [a for a in l if a if a + 1 if a + 2] 4 | 5 | # nested for loops 6 | x = [a for a in l for l in ls] 7 | x = [a for ls in lss for l in ls for a in l] 8 | x = [a for a in l for l in ls for ls in lss] 9 | 10 | # nested ifs and for loops 11 | x = [a for a in l if a for l in ls if l if a for ls in lss if ls] 12 | -------------------------------------------------------------------------------- /stm/cc3k/pybcc3k.h: -------------------------------------------------------------------------------- 1 | void pyb_delay_us(uint32_t us); 2 | 3 | void pyb_cc3000_set_en(int val); 4 | void pyb_cc3000_set_cs(int val); 5 | int pyb_cc3000_get_irq(void); 6 | void pyb_cc3000_enable_irq(void); 7 | void pyb_cc3000_disable_irq(void); 8 | void pyb_cc3000_pause_spi(void); 9 | void pyb_cc3000_resume_spi(void); 10 | 11 | void pyb_cc3000_spi_init(void); 12 | uint8_t pyb_cc3000_spi_send(uint8_t val); 13 | -------------------------------------------------------------------------------- /stm/mma.h: -------------------------------------------------------------------------------- 1 | void mma_init(void); 2 | void mma_restart(uint8_t addr, int write); 3 | void mma_start(uint8_t addr, int write); 4 | void mma_send_byte(uint8_t data); 5 | uint8_t mma_read_ack(void); 6 | uint8_t mma_read_nack(void); 7 | void mma_stop(void); 8 | 9 | MP_DECLARE_CONST_FUN_OBJ(pyb_mma_read_obj); 10 | MP_DECLARE_CONST_FUN_OBJ(pyb_mma_read_all_obj); 11 | MP_DECLARE_CONST_FUN_OBJ(pyb_mma_write_mode_obj); 12 | -------------------------------------------------------------------------------- /stm/qstrdefsport.h: -------------------------------------------------------------------------------- 1 | // qstrs specific to this port 2 | 3 | Q(help) 4 | Q(pyb) 5 | Q(info) 6 | Q(sd_test) 7 | Q(stop) 8 | Q(standby) 9 | Q(source_dir) 10 | Q(main) 11 | Q(sync) 12 | Q(gc) 13 | Q(delay) 14 | Q(switch) 15 | Q(servo) 16 | Q(pwm) 17 | Q(accel) 18 | Q(mma_read) 19 | Q(mma_mode) 20 | Q(hid) 21 | Q(time) 22 | Q(rand) 23 | Q(Led) 24 | Q(Servo) 25 | Q(I2C) 26 | Q(gpio) 27 | Q(Usart) 28 | Q(ADC) 29 | Q(open) 30 | -------------------------------------------------------------------------------- /examples/pyb.py: -------------------------------------------------------------------------------- 1 | # pyboard testing functions for CPython 2 | import time 3 | 4 | def delay(n): 5 | #time.sleep(float(n) / 1000) 6 | pass 7 | 8 | rand_seed = 1 9 | def rand(): 10 | global rand_seed 11 | # for these choice of numbers, see P L'Ecuyer, "Tables of linear congruential generators of different sizes and good lattice structure" 12 | rand_seed = (rand_seed * 653276) % 8388593 13 | return rand_seed 14 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/locals1.py: -------------------------------------------------------------------------------- 1 | # to test the order of locals and arguments (LOAD_FAST, STORE_FAST) 2 | 3 | def f1(): 4 | b = 1 5 | a = 2 6 | return a + b 7 | 8 | def f2(b): 9 | a = 2 10 | return a + b 11 | 12 | def f3(): 13 | def f3f(): 14 | return True 15 | a = 1 16 | return f3f(a) 17 | 18 | def f4(): 19 | x = 1 20 | def f3f(): 21 | return True 22 | return f3f(x) 23 | -------------------------------------------------------------------------------- /tests/basics/try4.py: -------------------------------------------------------------------------------- 1 | # triple nested exceptions 2 | 3 | def f(): 4 | try: 5 | foo() 6 | except: 7 | print("except 1") 8 | try: 9 | bar() 10 | except: 11 | print("except 2") 12 | try: 13 | baz() 14 | except: 15 | print("except 3") 16 | bak() 17 | 18 | try: 19 | f() 20 | except: 21 | print("f except") 22 | -------------------------------------------------------------------------------- /tests/basics/class_inherit1.py: -------------------------------------------------------------------------------- 1 | class A: 2 | def __init__(self, x): 3 | print('A init', x) 4 | self.x = x 5 | 6 | def f(self): 7 | print(self.x, self.y) 8 | 9 | class B(A): 10 | def __init__(self, x, y): 11 | A.__init__(self, x) 12 | print('B init', x, y) 13 | self.y = y 14 | 15 | def g(self): 16 | print(self.x, self.y) 17 | 18 | A(1) 19 | b = B(1, 2) 20 | b.f() 21 | b.g() 22 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/fun2.py: -------------------------------------------------------------------------------- 1 | def f(*, b): 2 | return b 3 | 4 | def f(a, *, b): 5 | return a + b 6 | 7 | def f(a, *, b, c): 8 | return a + b + c 9 | 10 | def f(a, *, b=c): 11 | return a + b 12 | 13 | def f(a, *, b=c, c): 14 | return a + b + c 15 | 16 | def f(a, *, b=c, c=d): 17 | return a + b + c 18 | 19 | def f(a, *, b=c, c, d=e): 20 | return a + b + c + d 21 | 22 | def f(a=None, *, b=None): 23 | return a + b 24 | -------------------------------------------------------------------------------- /tests/basics/generator1.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | print('a') 3 | y = x 4 | print('b') 5 | while y > 0: 6 | print('c') 7 | y -= 1 8 | print('d') 9 | yield y 10 | print('e') 11 | print('f') 12 | return None 13 | 14 | for val in f(3): 15 | print(val) 16 | 17 | #gen = f(3) 18 | #print(gen) 19 | #print(gen.__next__()) 20 | #print(gen.__next__()) 21 | #print(gen.__next__()) 22 | #print(gen.__next__()) 23 | -------------------------------------------------------------------------------- /tests/basics/int-small.py: -------------------------------------------------------------------------------- 1 | # This test small int range for 32-bit machine 2 | 3 | a = 0x3fffff 4 | print(a) 5 | a *= 0x10 6 | print(a) 7 | a *= 0x10 8 | print(a) 9 | a += 0xff 10 | print(a) 11 | # This would overflow 12 | #a += 1 13 | 14 | a = -0x3fffff 15 | print(a) 16 | a *= 0x10 17 | print(a) 18 | a *= 0x10 19 | print(a) 20 | a -= 0xff 21 | print(a) 22 | # This still doesn't overflow 23 | a -= 1 24 | print(a) 25 | # This would overflow 26 | #a -= 1 27 | -------------------------------------------------------------------------------- /teensy/lexermemzip.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "misc.h" 5 | #include "lexer.h" 6 | #include "memzip.h" 7 | 8 | mp_lexer_t *mp_lexer_new_from_memzip_file(const char *filename) 9 | { 10 | void *data; 11 | size_t len; 12 | 13 | if (memzip_locate(filename, &data, &len) != MZ_OK) { 14 | return NULL; 15 | } 16 | return mp_lexer_new_from_str_len(filename, (const char *)data, (uint)len, 0); 17 | } 18 | 19 | -------------------------------------------------------------------------------- /tests/basics/class3.py: -------------------------------------------------------------------------------- 1 | # inheritance 2 | 3 | class A: 4 | def a(): 5 | print('A.a() called') 6 | 7 | class B(A): 8 | pass 9 | 10 | print(type(A)) 11 | print(type(B)) 12 | 13 | print(issubclass(A, A)) 14 | print(issubclass(A, B)) 15 | print(issubclass(B, A)) 16 | print(issubclass(B, B)) 17 | 18 | print(isinstance(A(), A)) 19 | print(isinstance(A(), B)) 20 | print(isinstance(B(), A)) 21 | print(isinstance(B(), B)) 22 | 23 | A.a() 24 | B.a() 25 | -------------------------------------------------------------------------------- /tests/basics/for1.py: -------------------------------------------------------------------------------- 1 | # basic for loop 2 | 3 | def f(): 4 | for x in range(2): 5 | for y in range(2): 6 | for z in range(2): 7 | print(x, y, z) 8 | 9 | f() 10 | 11 | # range with negative step 12 | for i in range(3, -1, -1): 13 | print(i) 14 | 15 | a = -1 16 | # range with non-constant step - we optimize constant steps, so this 17 | # will be executed differently 18 | for i in range(3, -1, a): 19 | print(i) 20 | -------------------------------------------------------------------------------- /teensy/lexerfatfs.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "misc.h" 5 | #include "lexer.h" 6 | typedef int FIL; 7 | #include "../stm/lexerfatfs.h" 8 | 9 | mp_lexer_t *mp_lexer_new_from_file(const char *filename, mp_lexer_file_buf_t *fb) { 10 | printf("import not implemented\n"); 11 | return NULL; 12 | } 13 | 14 | mp_lexer_t *mp_import_open_file(qstr mod_name) { 15 | printf("import not implemented\n"); 16 | return NULL; 17 | } 18 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/if2.py: -------------------------------------------------------------------------------- 1 | def f(x): 2 | if x: 3 | return 4 | if x: 5 | return 6 | elif y: 7 | return 8 | if x: 9 | return 10 | else: 11 | return 12 | if x: 13 | return 14 | elif y: 15 | return 16 | else: 17 | return 18 | if x: 19 | return 20 | elif y: 21 | return 22 | elif z: 23 | return 24 | else: 25 | return 26 | return None 27 | -------------------------------------------------------------------------------- /tests/basics/getitem.py: -------------------------------------------------------------------------------- 1 | # create a class that has a __getitem__ method 2 | class A: 3 | def __getitem__(self, index): 4 | print('getitem', index) 5 | if index > 10: 6 | raise StopIteration 7 | 8 | # test __getitem__ 9 | A()[0] 10 | A()[1] 11 | 12 | # iterate using a for loop 13 | for i in A(): 14 | pass 15 | 16 | # iterate manually 17 | it = iter(A()) 18 | try: 19 | while True: 20 | next(it) 21 | except StopIteration: 22 | pass 23 | -------------------------------------------------------------------------------- /tests/basics/string_find.py: -------------------------------------------------------------------------------- 1 | print("hello world".find("ll")) 2 | print("hello world".find("ll", None)) 3 | print("hello world".find("ll", 1)) 4 | print("hello world".find("ll", 1, None)) 5 | print("hello world".find("ll", None, None)) 6 | print("hello world".find("ll", 1, -1)) 7 | print("hello world".find("ll", 1, 1)) 8 | print("hello world".find("ll", 1, 2)) 9 | print("hello world".find("ll", 1, 3)) 10 | print("hello world".find("ll", 1, 4)) 11 | print("hello world".find("ll", 1, 5)) 12 | -------------------------------------------------------------------------------- /stm/usb.h: -------------------------------------------------------------------------------- 1 | void pyb_usb_dev_init(void); 2 | bool usb_vcp_is_enabled(void); 3 | int usb_vcp_rx_any(void); 4 | char usb_vcp_rx_get(void); 5 | void usb_vcp_send_str(const char* str); 6 | void usb_vcp_send_strn(const char* str, int len); 7 | void usb_vcp_send_strn_cooked(const char *str, int len); 8 | void usb_hid_send_report(uint8_t *buf); // 4 bytes for mouse: ?, x, y, ? 9 | 10 | void pyb_usb_host_init(void); 11 | void pyb_usb_host_process(void); 12 | uint pyb_usb_host_get_keyboard(void); 13 | -------------------------------------------------------------------------------- /teensy/README.md: -------------------------------------------------------------------------------- 1 | Build Instructions for Teensy 3.1 2 | 3 | This assumes that you have TeensyDuino installed and set the ARUINO environment 4 | variable pointing to the where Arduino with TeensyDuino is installed. 5 | 6 | ``` 7 | cd teensy 8 | ARDUINO=~/arduino-1.0.5 make 9 | ``` 10 | 11 | To upload micropython to the Teensy 3.1. 12 | 13 | Press the Program button on the Teensy 3.1 14 | ``` 15 | make upload 16 | ``` 17 | 18 | Currently, the python prompt is through the USB serial interface. 19 | -------------------------------------------------------------------------------- /tests/basics/class1.py: -------------------------------------------------------------------------------- 1 | # basic class 2 | 3 | def go(): 4 | class C: 5 | def f(): 6 | print(1) 7 | 8 | def g(self): 9 | print(2) 10 | 11 | def set(self, value): 12 | self.value = value 13 | 14 | def print(self): 15 | print(self.value) 16 | 17 | C.f() 18 | C() 19 | C().g() 20 | 21 | o = C() 22 | o.set(3) 23 | o.print() 24 | 25 | C.set(o, 4) 26 | C.print(o) 27 | 28 | go() 29 | -------------------------------------------------------------------------------- /tests/basics/set_difference.py: -------------------------------------------------------------------------------- 1 | def report(s): 2 | l = list(s) 3 | l.sort() 4 | print(l) 5 | 6 | l = [1, 2, 3, 4] 7 | s = set(l) 8 | outs = [s.difference(), 9 | s.difference({1}), 10 | s.difference({1}, [1, 2]), 11 | s.difference({1}, {1, 2}, {2, 3})] 12 | for out in outs: 13 | report(out) 14 | 15 | s = set(l) 16 | print(s.difference_update()) 17 | report(s) 18 | print(s.difference_update({1})) 19 | report(s) 20 | print(s.difference_update({1}, [2])) 21 | report(s) 22 | -------------------------------------------------------------------------------- /tests/basics/true-value.py: -------------------------------------------------------------------------------- 1 | # Test true-ish value handling 2 | 3 | if not False: 4 | print("False") 5 | 6 | if not 0: 7 | print("0") 8 | 9 | if not "": 10 | print("Empty string") 11 | if "foo": 12 | print("Non-empty string") 13 | 14 | if not (): 15 | print("Empty tuple") 16 | if ("",): 17 | print("Non-empty tuple") 18 | 19 | if not []: 20 | print("Empty list") 21 | if [0]: 22 | print("Non-empty list") 23 | 24 | if not {}: 25 | print("Empty dict") 26 | if {0:0}: 27 | print("Non-empty dict") 28 | -------------------------------------------------------------------------------- /tests/basics/comprehension1.py: -------------------------------------------------------------------------------- 1 | def f(): 2 | # list comprehension 3 | 4 | print([a + 1 for a in range(5)]) 5 | print([(a, b) for a in range(3) for b in range(2)]) 6 | print([a * 2 for a in range(7) if a > 3]) 7 | 8 | print([a for a in [1, 3, 5]]) 9 | print([a for a in [a for a in range(4)]]) 10 | 11 | # dict comprehension 12 | 13 | d = {a : 2 * a for a in range(5)} 14 | print(d[0], d[1], d[2], d[3], d[4]) 15 | 16 | # set comprehension 17 | 18 | print({a for a in range(5)}) 19 | 20 | f() 21 | -------------------------------------------------------------------------------- /teensy/usart.c: -------------------------------------------------------------------------------- 1 | #include "misc.h" 2 | #include "../stm/usart.h" 3 | 4 | void usart_init(void) { 5 | } 6 | 7 | bool usart_is_enabled(void) { 8 | return false; 9 | } 10 | 11 | bool usart_rx_any(void) { 12 | return false; 13 | } 14 | 15 | int usart_rx_char(void) { 16 | return 0; 17 | } 18 | 19 | void usart_tx_char(int c) { 20 | (void)c; 21 | } 22 | 23 | void usart_tx_str(const char *str) { 24 | (void)str; 25 | } 26 | 27 | void usart_tx_strn_cooked(const char *str, int len) { 28 | (void)str; 29 | (void)len; 30 | } 31 | -------------------------------------------------------------------------------- /tests/basics/list_index.py: -------------------------------------------------------------------------------- 1 | a = [1, 2, 3] 2 | print(a.index(1)) 3 | print(a.index(2)) 4 | print(a.index(3)) 5 | print(a.index(3, 2)) 6 | try: 7 | print(a.index(3, 2, 2)) 8 | except ValueError: 9 | print("Raised ValueError") 10 | else: 11 | print("Did not raise ValueError") 12 | 13 | a = a + a 14 | b = [0, 0, a] 15 | print(a.index(2)) 16 | print(b.index(a)) 17 | print(a.index(2, 2)) 18 | 19 | try: 20 | a.index(2, 2, 2) 21 | except ValueError: 22 | print("Raised ValueError") 23 | else: 24 | print("Did not raise ValueError") 25 | -------------------------------------------------------------------------------- /stm/led.h: -------------------------------------------------------------------------------- 1 | typedef enum { 2 | // PYBv3 3 | PYB_LED_R1 = 1, 4 | PYB_LED_R2 = 2, 5 | PYB_LED_G1 = 3, 6 | PYB_LED_G2 = 4, 7 | // PYBv4 8 | PYB_LED_RED = 1, 9 | PYB_LED_GREEN = 2, 10 | PYB_LED_YELLOW = 3, 11 | PYB_LED_BLUE = 4, 12 | //STM32F4DISC 13 | PYB_LED_R = 1, 14 | PYB_LED_G = 2, 15 | PYB_LED_B = 3, 16 | PYB_LED_O = 4, 17 | } pyb_led_t; 18 | 19 | void led_init(void); 20 | void led_state(pyb_led_t led, int state); 21 | void led_toggle(pyb_led_t led); 22 | 23 | MP_DECLARE_CONST_FUN_OBJ(pyb_Led_obj); 24 | -------------------------------------------------------------------------------- /unix-cpy/Makefile: -------------------------------------------------------------------------------- 1 | include ../py/mkenv.mk 2 | 3 | # define main target 4 | PROG = cpy 5 | 6 | # include py core make definitions 7 | include ../py/py.mk 8 | 9 | # compiler settings 10 | CFLAGS = -I. -I$(PY_SRC) -Wall -Werror -ansi -std=gnu99 -DUNIX 11 | LDFLAGS = -lm 12 | 13 | # Debugging/Optimization 14 | ifdef DEBUG 15 | CFLAGS += -O0 -g 16 | else 17 | CFLAGS += -Os #-DNDEBUG 18 | endif 19 | 20 | # source files 21 | SRC_C = \ 22 | main.c \ 23 | 24 | OBJ = $(PY_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) 25 | LIB = 26 | 27 | include ../py/mkrules.mk 28 | 29 | -------------------------------------------------------------------------------- /tests/basics/string1.py: -------------------------------------------------------------------------------- 1 | # basic strings 2 | 3 | x = 'abc' 4 | print(x) 5 | 6 | x += 'def' 7 | print(x) 8 | 9 | print('123' + "456") 10 | 11 | print('123' * 5) 12 | 13 | print('abc'[1]) 14 | print('abc'[-1]) 15 | try: 16 | 'abc'[100] 17 | except IndexError: 18 | print('caught') 19 | try: 20 | 'abc'[-4] 21 | except IndexError: 22 | print('caught2') 23 | 24 | # iter 25 | print(list('str')) 26 | 27 | print('123' + '789' == '123789') 28 | print('a' + 'b' != 'a' + 'b ') 29 | 30 | # Not implemented so far 31 | # print('1' + '2' > '2') 32 | # print('1' + '2' < '2') 33 | -------------------------------------------------------------------------------- /tests/bytecode/pylib-tests/antigravity.py: -------------------------------------------------------------------------------- 1 | 2 | import webbrowser 3 | import hashlib 4 | 5 | webbrowser.open("http://xkcd.com/353/") 6 | 7 | def geohash(latitude, longitude, datedow): 8 | '''Compute geohash() using the Munroe algorithm. 9 | 10 | >>> geohash(37.421542, -122.085589, b'2005-05-26-10458.68') 11 | 37.857713 -122.544543 12 | 13 | ''' 14 | # http://xkcd.com/426/ 15 | h = hashlib.md5(datedow).hexdigest() 16 | p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])] 17 | print('%d%s %d%s' % (latitude, p[1:], longitude, q[1:])) 18 | -------------------------------------------------------------------------------- /examples/ledangle.py: -------------------------------------------------------------------------------- 1 | def led_angle(seconds_to_run_for): 2 | # make LED objects 3 | l1 = pyb.Led(1) 4 | l2 = pyb.Led(2) 5 | 6 | for i in range(20 * seconds_to_run_for): 7 | # get x-axis 8 | accel = pyb.accel()[0] 9 | 10 | # turn on LEDs depending on angle 11 | if accel < -10: 12 | l1.on() 13 | l2.off() 14 | elif accel > 10: 15 | l1.off() 16 | l2.on() 17 | else: 18 | l1.off() 19 | l2.off() 20 | 21 | # delay so that loop runs at at 1/50ms = 20Hz 22 | pyb.delay(50) 23 | -------------------------------------------------------------------------------- /stm/delay.s: -------------------------------------------------------------------------------- 1 | .syntax unified 2 | .cpu cortex-m4 3 | .thumb 4 | .text 5 | .align 2 6 | .global delay_ms 7 | .thumb 8 | .thumb_func 9 | .type delay_ms, %function 10 | @ void delay_ms(int ms) 11 | delay_ms: 12 | @ r0 is argument, trashes r2, r3 13 | adds r3, r0, #0 14 | b .L2 15 | .L5: 16 | movw r2, #55999 17 | b .L3 18 | .L4: 19 | subs r2, r2, #1 20 | .L3: 21 | cmp r2, #0 22 | bgt .L4 23 | subs r3, r3, #1 24 | .L2: 25 | cmp r3, #0 26 | bgt .L5 27 | bx lr 28 | .size delay_ms, .-delay_ms 29 | -------------------------------------------------------------------------------- /stm/usart.h: -------------------------------------------------------------------------------- 1 | typedef enum { 2 | PYB_USART_NONE = 0, 3 | PYB_USART_1 = 1, 4 | PYB_USART_2 = 2, 5 | PYB_USART_3 = 3, 6 | PYB_USART_6 = 4, 7 | PYB_USART_MAX = 4, 8 | } pyb_usart_t; 9 | 10 | extern pyb_usart_t pyb_usart_global_debug; 11 | 12 | void usart_init(pyb_usart_t usart_id, uint32_t baudrate); 13 | bool usart_rx_any(pyb_usart_t usart_id); 14 | int usart_rx_char(pyb_usart_t usart_id); 15 | void usart_tx_str(pyb_usart_t usart_id, const char *str); 16 | void usart_tx_strn_cooked(pyb_usart_t usart_id, const char *str, int len); 17 | 18 | mp_obj_t pyb_Usart(mp_obj_t usart_id, mp_obj_t baudrate); 19 | -------------------------------------------------------------------------------- /examples/accellog.py: -------------------------------------------------------------------------------- 1 | # log the accelerometer values to a file, 1 per second 2 | 3 | f = open('motion.dat', 'w') # open the file for writing 4 | 5 | for i in range(60): # loop 60 times 6 | time = pyb.time() # get the current time 7 | accel = pyb.accel() # get the accelerometer data 8 | 9 | # write time and x,y,z values to the file 10 | f.write('{} {} {} {}\n'.format(time, accel[0], accel[1], accel[2])) 11 | 12 | pyb.delay(1000) # wait 1000 ms = 1 second 13 | 14 | f.close() # close the file 15 | -------------------------------------------------------------------------------- /py/gc.h: -------------------------------------------------------------------------------- 1 | void gc_init(void *start, void *end); 2 | void gc_collect_start(void); 3 | void gc_collect_root(void **ptrs, machine_uint_t len); 4 | void gc_collect_end(void); 5 | void gc_collect(void); 6 | void *gc_alloc(machine_uint_t n_bytes); 7 | void gc_free(void *ptr); 8 | machine_uint_t gc_nbytes(void *ptr); 9 | void *gc_realloc(void *ptr, machine_uint_t n_bytes); 10 | 11 | typedef struct _gc_info_t { 12 | machine_uint_t total; 13 | machine_uint_t used; 14 | machine_uint_t free; 15 | machine_uint_t num_1block; 16 | machine_uint_t num_2block; 17 | machine_uint_t max_block; 18 | } gc_info_t; 19 | 20 | void gc_info(gc_info_t *info); 21 | -------------------------------------------------------------------------------- /tests/bytecode/README.md: -------------------------------------------------------------------------------- 1 | This directory contains the framework and test files for testing the byte code 2 | output of the Micro Python compiler. 3 | 4 | You need to first build the 'cpy' executable in the directory micropython/unix-cpy/. 5 | This executable is a minimal version of Micro Python which compiles a single source 6 | file and outputs the corresponding byte code. 7 | 8 | The output of Micro Python is checked against CPython 3.3. 9 | 10 | To run the tests use: 11 | 12 | ./run-tests 13 | 14 | Note that the tests in pylib-test/ are from the Python 3.3 library, and are licensed 15 | under the relevant license, as per pylib-test/LICENSE.txt. 16 | -------------------------------------------------------------------------------- /examples/mandel.py: -------------------------------------------------------------------------------- 1 | try: 2 | import micropython 3 | except: 4 | pass 5 | 6 | def mandelbrot(): 7 | # returns True if c, complex, is in the Mandelbrot set 8 | #@micropython.native 9 | def in_set(c): 10 | z = 0 11 | for i in range(40): 12 | z = z*z + c 13 | if abs(z) > 60: 14 | return False 15 | return True 16 | 17 | lcd.clear() 18 | for u in range(91): 19 | for v in range(31): 20 | if in_set((u / 30 - 2) + (v / 15 - 1) * 1j): 21 | lcd.set(u, v) 22 | lcd.show() 23 | 24 | # PC testing 25 | import lcd 26 | lcd = lcd.LCD(128, 32) 27 | mandelbrot() 28 | -------------------------------------------------------------------------------- /tests/basics/types1.py: -------------------------------------------------------------------------------- 1 | # basic types 2 | 3 | print(bool) 4 | print(int) 5 | print(float) 6 | print(complex) 7 | print(tuple) 8 | print(list) 9 | print(set) 10 | print(dict) 11 | 12 | print(type(bool()) == bool) 13 | print(type(int()) == int) 14 | print(type(float()) == float) 15 | print(type(complex()) == complex) 16 | print(type(tuple()) == tuple) 17 | print(type(list()) == list) 18 | print(type(set()) == set) 19 | print(type(dict()) == dict) 20 | 21 | print(type(False) == bool) 22 | print(type(0) == int) 23 | print(type(0.0) == float) 24 | print(type(1j) == complex) 25 | print(type(()) == tuple) 26 | print(type([]) == list) 27 | print(type({None}) == set) 28 | print(type({}) == dict) 29 | -------------------------------------------------------------------------------- /tests/basics/string-slice.py: -------------------------------------------------------------------------------- 1 | print("123"[0:1]) 2 | 3 | print("123"[0:2]) 4 | 5 | print("123"[:1]) 6 | 7 | print("123"[1:]) 8 | 9 | # Idiom for copying sequence 10 | print("123"[:]) 11 | 12 | print("123"[:-1]) 13 | 14 | # Weird cases 15 | print("123"[0:0]) 16 | print("123"[1:0]) 17 | print("123"[1:1]) 18 | print("123"[-1:-1]) 19 | print("123"[-3:]) 20 | print("123"[-3:3]) 21 | print("123"[0:]) 22 | print("123"[:0]) 23 | print("123"[:-3]) 24 | print("123"[:-4]) 25 | # Range check testing, don't segfault, please ;-) 26 | print("123"[:1000000]) 27 | print("123"[1000000:]) 28 | print("123"[:-1000000]) 29 | print("123"[-1000000:]) 30 | # No IndexError! 31 | print(""[1:1]) 32 | print(""[-1:-1]) 33 | -------------------------------------------------------------------------------- /tests/basics/generator_send.py: -------------------------------------------------------------------------------- 1 | def f(): 2 | n = 0 3 | while True: 4 | n = yield n + 1 5 | print(n) 6 | 7 | g = f() 8 | try: 9 | g.send(1) 10 | except TypeError: 11 | print("caught") 12 | 13 | print(g.send(None)) 14 | print(g.send(100)) 15 | print(g.send(200)) 16 | 17 | 18 | def f2(): 19 | print("entering") 20 | for i in range(3): 21 | print(i) 22 | yield 23 | print("returning 1") 24 | print("returning 2") 25 | 26 | g = f2() 27 | g.send(None) 28 | g.send(1) 29 | g.send(1) 30 | try: 31 | g.send(1) 32 | except StopIteration: 33 | print("caught") 34 | try: 35 | g.send(1) 36 | except StopIteration: 37 | print("caught") 38 | -------------------------------------------------------------------------------- /py/nlr.h: -------------------------------------------------------------------------------- 1 | // non-local return 2 | // exception handling, basically a stack of setjmp/longjmp buffers 3 | 4 | #include 5 | 6 | //#ifndef __WORDSIZE 7 | //#error __WORDSIZE needs to be defined 8 | //#endif 9 | 10 | typedef struct _nlr_buf_t nlr_buf_t; 11 | struct _nlr_buf_t { 12 | // the entries here must all be machine word size 13 | nlr_buf_t *prev; 14 | void *ret_val; 15 | #if __WORDSIZE == 32 16 | void *regs[6]; 17 | #elif __WORDSIZE == 64 18 | void *regs[8]; 19 | #else 20 | // hack for thumb 21 | void *regs[10]; 22 | //#error Unsupported __WORDSIZE 23 | #endif 24 | }; 25 | 26 | unsigned int nlr_push(nlr_buf_t *); 27 | void nlr_pop(void); 28 | void nlr_jump(void *val) __attribute__((noreturn)); 29 | -------------------------------------------------------------------------------- /py/sequence.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include "nlr.h" 7 | #include "misc.h" 8 | #include "mpconfig.h" 9 | #include "qstr.h" 10 | #include "obj.h" 11 | #include "map.h" 12 | #include "runtime0.h" 13 | #include "runtime.h" 14 | 15 | // Helpers for sequence types 16 | 17 | // Implements backend of sequence * integer operation. Assumes elements are 18 | // memory-adjacent in sequence. 19 | void mp_seq_multiply(const void *items, uint item_sz, uint len, uint times, void *dest) { 20 | for (int i = 0; i < times; i++) { 21 | uint copy_sz = item_sz * len; 22 | memcpy(dest, items, copy_sz); 23 | dest = (char*)dest + copy_sz; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tests/bytecode/mp-tests/continue1.py: -------------------------------------------------------------------------------- 1 | for a in b: 2 | continue 3 | 4 | for a in b: 5 | try: 6 | f() 7 | except: 8 | continue 9 | g() 10 | 11 | for a in b: 12 | try: 13 | f() 14 | continue 15 | except: 16 | g() 17 | 18 | for a in b: 19 | try: 20 | f() 21 | except: 22 | try: 23 | g() 24 | except: 25 | continue 26 | 27 | for a in b: 28 | try: 29 | f() 30 | except: 31 | try: 32 | g() 33 | continue 34 | except: 35 | h() 36 | 37 | for a in b: 38 | try: 39 | f() 40 | except: 41 | pass 42 | else: 43 | continue 44 | g() 45 | -------------------------------------------------------------------------------- /unix/Makefile: -------------------------------------------------------------------------------- 1 | include ../py/mkenv.mk 2 | 3 | # define main target 4 | PROG = micropython 5 | 6 | # qstr definitions (must come before including py.mk) 7 | QSTR_DEFS = qstrdefsport.h 8 | 9 | # include py core make definitions 10 | include ../py/py.mk 11 | 12 | # compiler settings 13 | CFLAGS = -I. -I$(PY_SRC) -Wall -Werror -ansi -std=gnu99 -DUNIX 14 | LDFLAGS = -lm 15 | 16 | # Debugging/Optimization 17 | ifdef DEBUG 18 | CFLAGS += -O0 -g 19 | else 20 | CFLAGS += -Os #-DNDEBUG 21 | endif 22 | 23 | # source files 24 | SRC_C = \ 25 | main.c \ 26 | file.c \ 27 | socket.c \ 28 | 29 | OBJ = $(PY_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) 30 | LIB = -lreadline 31 | # the following is needed for BSD 32 | #LIB += -ltermcap 33 | 34 | include ../py/mkrules.mk 35 | 36 | -------------------------------------------------------------------------------- /teensy/mpconfigport.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // options to control how Micro Python is built 4 | 5 | #define MICROPY_EMIT_THUMB (1) 6 | #define MICROPY_EMIT_INLINE_THUMB (1) 7 | #define MICROPY_ENABLE_GC (1) 8 | #define MICROPY_ENABLE_REPL_HELPERS (1) 9 | #define MICROPY_ENABLE_FLOAT (1) 10 | 11 | // type definitions for the specific machine 12 | 13 | #define BYTES_PER_WORD (4) 14 | 15 | typedef int32_t machine_int_t; // must be pointer size 16 | typedef uint32_t machine_uint_t; // must be pointer size 17 | typedef void *machine_ptr_t; // must be of pointer size 18 | typedef const void *machine_const_ptr_t; // must be of pointer size 19 | typedef float machine_float_t; 20 | 21 | machine_float_t machine_sqrt(machine_float_t x); 22 | -------------------------------------------------------------------------------- /teensy/std.h: -------------------------------------------------------------------------------- 1 | typedef unsigned int size_t; 2 | 3 | void __assert_func(void); 4 | 5 | void *malloc(size_t n); 6 | void free(void *ptr); 7 | void *calloc(size_t sz, size_t n); 8 | void *realloc(void *ptr, size_t n); 9 | 10 | void *memcpy(void *dest, const void *src, size_t n); 11 | void *memmove(void *dest, const void *src, size_t n); 12 | void *memset(void *s, int c, size_t n); 13 | 14 | int strlen(const char *str); 15 | int strcmp(const char *s1, const char *s2); 16 | int strncmp(const char *s1, const char *s2, size_t n); 17 | char *strndup(const char *s, size_t n); 18 | char *strcpy(char *dest, const char *src); 19 | char *strcat(char *dest, const char *src); 20 | 21 | int printf(const char *fmt, ...); 22 | int snprintf(char *str, size_t size, const char *fmt, ...); 23 | -------------------------------------------------------------------------------- /tests/bytecode/run-tests: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | CPYTHON3=python3.3 4 | MP_CPY=../../unix-cpy/cpy 5 | 6 | RM=/bin/rm 7 | 8 | mkdir -p output 9 | 10 | function run_test_on_dir() { 11 | echo "" 12 | echo "Testing directory $1..." 13 | echo "" 14 | 15 | for file in $1/*.py 16 | do 17 | basename=$(basename $file .py) 18 | 19 | $CPYTHON3 -B -c "import compileall; compileall.compile_file('$file', quiet=True)" 20 | #/usr/lib/python3.3/compileall.py $file 21 | $CPYTHON3 -B unpyc.py $1/__pycache__/$basename.cpython-33.pyc > output/$basename.pycout 22 | 23 | $MP_CPY $file | $CPYTHON3 -B check.py output/$basename.pycout 24 | done 25 | 26 | echo "" 27 | } 28 | 29 | run_test_on_dir mp-tests 30 | run_test_on_dir pylib-tests 31 | -------------------------------------------------------------------------------- /teensy/add-memzip.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ "$#" != 3 ]; then 4 | echo "Usage: add-memzip.sh input.hex output.hex file-directory" 5 | exit 1 6 | fi 7 | 8 | #set -x 9 | 10 | input_hex=$1 11 | output_hex=$2 12 | memzip_src_dir=$3 13 | 14 | input_bin=${input_hex}.bin 15 | output_bin=${output_hex}.bin 16 | zip_file=${output_hex}.zip 17 | zip_base=$(basename ${zip_file}) 18 | zip_dir=$(dirname ${zip_file}) 19 | abs_zip_dir=$(realpath ${zip_dir}) 20 | 21 | rm -f ${zip_file} 22 | (cd ${memzip_src_dir}; zip -0 -r -D ${abs_zip_dir}/${zip_base} .) 23 | objcopy -I ihex -O binary ${input_hex} ${input_bin} 24 | cat ${input_bin} ${zip_file} > ${output_bin} 25 | objcopy -I binary -O ihex ${output_bin} ${output_hex} 26 | echo "Added ${memzip_src_dir} to ${input_hex} creating ${output_hex}" 27 | 28 | -------------------------------------------------------------------------------- /stm/fatfs/integer.h: -------------------------------------------------------------------------------- 1 | /*-------------------------------------------*/ 2 | /* Integer type definitions for FatFs module */ 3 | /*-------------------------------------------*/ 4 | 5 | #ifndef _FF_INTEGER 6 | #define _FF_INTEGER 7 | 8 | #ifdef _WIN32 /* FatFs development platform */ 9 | 10 | #include 11 | #include 12 | 13 | #else /* Embedded platform */ 14 | 15 | /* This type MUST be 8 bit */ 16 | typedef unsigned char BYTE; 17 | 18 | /* These types MUST be 16 bit */ 19 | typedef short SHORT; 20 | typedef unsigned short WORD; 21 | typedef unsigned short WCHAR; 22 | 23 | /* These types MUST be 16 bit or 32 bit */ 24 | typedef int INT; 25 | typedef unsigned int UINT; 26 | 27 | /* These types MUST be 32 bit */ 28 | typedef long LONG; 29 | typedef unsigned long DWORD; 30 | 31 | #endif 32 | 33 | #endif 34 | -------------------------------------------------------------------------------- /stm/std.h: -------------------------------------------------------------------------------- 1 | typedef unsigned int size_t; 2 | 3 | void __assert_func(void); 4 | 5 | void *malloc(size_t n); 6 | void free(void *ptr); 7 | void *calloc(size_t sz, size_t n); 8 | void *realloc(void *ptr, size_t n); 9 | 10 | void *memcpy(void *dest, const void *src, size_t n); 11 | void *memmove(void *dest, const void *src, size_t n); 12 | void *memset(void *s, int c, size_t n); 13 | 14 | size_t strlen(const char *str); 15 | int strcmp(const char *s1, const char *s2); 16 | int strncmp(const char *s1, const char *s2, size_t n); 17 | char *strndup(const char *s, size_t n); 18 | char *strcpy(char *dest, const char *src); 19 | char *strcat(char *dest, const char *src); 20 | char *strchr(const char *s, int c); 21 | char *strstr(const char *haystack, const char *needle); 22 | 23 | int printf(const char *fmt, ...); 24 | int snprintf(char *str, size_t size, const char *fmt, ...); 25 | -------------------------------------------------------------------------------- /py/objcell.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "nlr.h" 6 | #include "misc.h" 7 | #include "mpconfig.h" 8 | #include "qstr.h" 9 | #include "obj.h" 10 | #include "runtime.h" 11 | 12 | typedef struct _mp_obj_cell_t { 13 | mp_obj_base_t base; 14 | mp_obj_t obj; 15 | } mp_obj_cell_t; 16 | 17 | mp_obj_t mp_obj_cell_get(mp_obj_t self_in) { 18 | mp_obj_cell_t *self = self_in; 19 | return self->obj; 20 | } 21 | 22 | void mp_obj_cell_set(mp_obj_t self_in, mp_obj_t obj) { 23 | mp_obj_cell_t *self = self_in; 24 | self->obj = obj; 25 | } 26 | 27 | const mp_obj_type_t cell_type = { 28 | { &mp_const_type }, 29 | "cell", 30 | }; 31 | 32 | mp_obj_t mp_obj_new_cell(mp_obj_t obj) { 33 | mp_obj_cell_t *o = m_new_obj(mp_obj_cell_t); 34 | o->base.type = &cell_type; 35 | o->obj = obj; 36 | return o; 37 | } 38 | -------------------------------------------------------------------------------- /py/objnone.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "nlr.h" 5 | #include "misc.h" 6 | #include "mpconfig.h" 7 | #include "qstr.h" 8 | #include "obj.h" 9 | 10 | typedef struct _mp_obj_none_t { 11 | mp_obj_base_t base; 12 | } mp_obj_none_t; 13 | 14 | void none_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) { 15 | print(env, "None"); 16 | } 17 | 18 | const mp_obj_type_t none_type = { 19 | { &mp_const_type }, 20 | "NoneType", 21 | .print = none_print, 22 | }; 23 | 24 | static const mp_obj_none_t none_obj = {{&none_type}}; 25 | const mp_obj_t mp_const_none = (mp_obj_t)&none_obj; 26 | 27 | // the stop-iteration object just needs to be something unique 28 | // it's not the StopIteration exception 29 | static const mp_obj_none_t stop_it_obj = {{&none_type}}; 30 | const mp_obj_t mp_const_stop_iteration = (mp_obj_t)&stop_it_obj; 31 | -------------------------------------------------------------------------------- /teensy/usb.c: -------------------------------------------------------------------------------- 1 | #include "Arduino.h" 2 | 3 | #include "usb.h" 4 | #include "usb_serial.h" 5 | 6 | int usb_vcp_is_connected(void) 7 | { 8 | return usb_configuration && (usb_cdc_line_rtsdtr & (USB_SERIAL_DTR | USB_SERIAL_RTS)); 9 | } 10 | 11 | int usb_vcp_is_enabled(void) 12 | { 13 | return 1; 14 | } 15 | 16 | int usb_vcp_rx_any(void) 17 | { 18 | return usb_serial_available(); 19 | } 20 | 21 | char usb_vcp_rx_get(void) 22 | { 23 | return usb_serial_getchar(); 24 | } 25 | 26 | void usb_vcp_send_str(const char* str) 27 | { 28 | usb_vcp_send_strn(str, strlen(str)); 29 | } 30 | 31 | void usb_vcp_send_strn(const char* str, int len) 32 | { 33 | usb_serial_write(str, len); 34 | } 35 | 36 | void usb_vcp_send_strn_cooked(const char *str, int len) 37 | { 38 | for (const char *top = str + len; str < top; str++) { 39 | if (*str == '\n') { 40 | usb_serial_putchar('\r'); 41 | } 42 | usb_serial_putchar(*str); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /unix-cpy/mpconfigport.h: -------------------------------------------------------------------------------- 1 | // options to control how Micro Python is built 2 | 3 | #define MICROPY_EMIT_CPYTHON (1) 4 | #define MICROPY_ENABLE_LEXER_UNIX (1) 5 | #define MICROPY_ENABLE_FLOAT (1) 6 | 7 | // type definitions for the specific machine 8 | 9 | #ifdef __LP64__ 10 | typedef long machine_int_t; // must be pointer size 11 | typedef unsigned long machine_uint_t; // must be pointer size 12 | #else 13 | // These are definitions for machines where sizeof(int) == sizeof(void*), 14 | // regardless for actual size. 15 | typedef int machine_int_t; // must be pointer size 16 | typedef unsigned int machine_uint_t; // must be pointer size 17 | #endif 18 | 19 | #define BYTES_PER_WORD sizeof(machine_int_t) 20 | 21 | typedef void *machine_ptr_t; // must be of pointer size 22 | typedef const void *machine_const_ptr_t; // must be of pointer size 23 | typedef double machine_float_t; 24 | 25 | machine_float_t machine_sqrt(machine_float_t x); 26 | -------------------------------------------------------------------------------- /examples/unix/sock-client.py: -------------------------------------------------------------------------------- 1 | try: 2 | import rawsocket as _socket 3 | except: 4 | import _socket 5 | 6 | 7 | s = _socket.socket() 8 | 9 | if 1: 10 | ai = _socket.getaddrinfo("google.com", 80) 11 | print("Address infos:", ai) 12 | addr = ai[0][4] 13 | else: 14 | # Deprecated ways to construct connection address 15 | addr = _socket.sockaddr_in() 16 | addr.sin_family = 2 17 | #addr.sin_addr = (0x0100 << 16) + 0x007f 18 | #addr.sin_addr = (0x7f00 << 16) + 0x0001 19 | #addr.sin_addr = _socket.inet_aton("127.0.0.1") 20 | addr.sin_addr = _socket.gethostbyname("google.com") 21 | addr.sin_port = _socket.htons(80) 22 | 23 | print("Connect address:", addr) 24 | s.connect(addr) 25 | 26 | if 0: 27 | # MicroPython rawsocket module supports file interface directly 28 | s.write("GET / HTTP/1.0\n\n") 29 | print(s.readall()) 30 | else: 31 | s.send(b"GET / HTTP/1.0\n\n") 32 | print(s.recv(4096)) 33 | -------------------------------------------------------------------------------- /tests/basics/set_binop.py: -------------------------------------------------------------------------------- 1 | def r(s): 2 | l = list(s) 3 | l.sort() 4 | return l 5 | sets = [set(), {1}, {1, 2}, {1, 2, 3}, {2, 3}, {2, 3, 5}, {5}, {7}] 6 | for s in sets: 7 | for t in sets: 8 | print(s, '|', t, '=', r(s | t)) 9 | print(s, '^', t, '=', r(s ^ t)) 10 | print(s, '&', t, '=', r(s & t)) 11 | print(s, '-', t, '=', r(s - t)) 12 | u = s.copy() 13 | u |= t 14 | print(s, "|=", t, '-->', r(u)) 15 | u = s.copy() 16 | u ^= t 17 | print(s, "^=", t, '-->', r(u)) 18 | u = s.copy() 19 | u &= t 20 | print(s, "&=", t, "-->", r(u)) 21 | u = s.copy() 22 | u -= t 23 | print(s, "-=", t, "-->", r(u)) 24 | 25 | print(s, '==', t, '=', s == t) 26 | print(s, '!=', t, '=', s != t) 27 | print(s, '>', t, '=', s > t) 28 | print(s, '>=', t, '=', s >= t) 29 | print(s, '<', t, '=', s < t) 30 | print(s, '<=', t, '=', s <= t) 31 | -------------------------------------------------------------------------------- /tests/bytecode/pylib-tests/tty.py: -------------------------------------------------------------------------------- 1 | """Terminal utilities.""" 2 | 3 | # Author: Steen Lumholt. 4 | 5 | from termios import * 6 | 7 | __all__ = ["setraw", "setcbreak"] 8 | 9 | # Indexes for termios list. 10 | IFLAG = 0 11 | OFLAG = 1 12 | CFLAG = 2 13 | LFLAG = 3 14 | ISPEED = 4 15 | OSPEED = 5 16 | CC = 6 17 | 18 | def setraw(fd, when=TCSAFLUSH): 19 | """Put terminal into a raw mode.""" 20 | mode = tcgetattr(fd) 21 | mode[IFLAG] = mode[IFLAG] & ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON) 22 | mode[OFLAG] = mode[OFLAG] & ~(OPOST) 23 | mode[CFLAG] = mode[CFLAG] & ~(CSIZE | PARENB) 24 | mode[CFLAG] = mode[CFLAG] | CS8 25 | mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON | IEXTEN | ISIG) 26 | mode[CC][VMIN] = 1 27 | mode[CC][VTIME] = 0 28 | tcsetattr(fd, when, mode) 29 | 30 | def setcbreak(fd, when=TCSAFLUSH): 31 | """Put terminal into a cbreak mode.""" 32 | mode = tcgetattr(fd) 33 | mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON) 34 | mode[CC][VMIN] = 1 35 | mode[CC][VTIME] = 0 36 | tcsetattr(fd, when, mode) 37 | -------------------------------------------------------------------------------- /stm/gchelper.s: -------------------------------------------------------------------------------- 1 | .syntax unified 2 | .cpu cortex-m4 3 | .thumb 4 | .text 5 | .align 2 6 | 7 | @ void gc_helper_get_regs_and_clean_stack(r0=uint regs[10], r1=heap_end) 8 | .global gc_helper_get_regs_and_clean_stack 9 | .thumb 10 | .thumb_func 11 | .type gc_helper_get_regs_and_clean_stack, %function 12 | gc_helper_get_regs_and_clean_stack: 13 | @ store registers into given array 14 | str r4, [r0], #4 15 | str r5, [r0], #4 16 | str r6, [r0], #4 17 | str r7, [r0], #4 18 | str r8, [r0], #4 19 | str r9, [r0], #4 20 | str r10, [r0], #4 21 | str r11, [r0], #4 22 | str r12, [r0], #4 23 | str r13, [r0], #4 24 | 25 | @ clean the stack from given pointer up to current sp 26 | movs r0, #0 27 | mov r2, sp 28 | b.n .entry 29 | .loop: 30 | str r0, [r1], #4 31 | .entry: 32 | cmp r1, r2 33 | bcc.n .loop 34 | bx lr 35 | 36 | .size gc_helper_get_regs_and_clean_stack, .-gc_helper_get_regs_and_clean_stack 37 | -------------------------------------------------------------------------------- /tests/basics/list_compare.py: -------------------------------------------------------------------------------- 1 | print([] == []) 2 | print([] > []) 3 | print([] < []) 4 | print([] == [1]) 5 | print([1] == []) 6 | print([] > [1]) 7 | print([1] > []) 8 | print([] < [1]) 9 | print([1] < []) 10 | print([] >= [1]) 11 | print([1] >= []) 12 | print([] <= [1]) 13 | print([1] <= []) 14 | 15 | print([1] == [1]) 16 | print([1] != [1]) 17 | print([1] == [2]) 18 | print([1] == [1, 0]) 19 | 20 | print([1] > [1]) 21 | print([1] > [2]) 22 | print([2] > [1]) 23 | print([1, 0] > [1]) 24 | print([1, -1] > [1]) 25 | print([1] > [1, 0]) 26 | print([1] > [1, -1]) 27 | 28 | print([1] < [1]) 29 | print([2] < [1]) 30 | print([1] < [2]) 31 | print([1] < [1, 0]) 32 | print([1] < [1, -1]) 33 | print([1, 0] < [1]) 34 | print([1, -1] < [1]) 35 | 36 | print([1] >= [1]) 37 | print([1] >= [2]) 38 | print([2] >= [1]) 39 | print([1, 0] >= [1]) 40 | print([1, -1] >= [1]) 41 | print([1] >= [1, 0]) 42 | print([1] >= [1, -1]) 43 | 44 | print([1] <= [1]) 45 | print([2] <= [1]) 46 | print([1] <= [2]) 47 | print([1] <= [1, 0]) 48 | print([1] <= [1, -1]) 49 | print([1, 0] <= [1]) 50 | print([1, -1] <= [1]) 51 | -------------------------------------------------------------------------------- /examples/unix/sock-server.py: -------------------------------------------------------------------------------- 1 | try: 2 | import rawsocket as socket 3 | except: 4 | import socket 5 | 6 | 7 | CONTENT = """\ 8 | HTTP/1.0 200 OK 9 | 10 | Hello #{} from MicroPython! 11 | """ 12 | 13 | s = socket.socket() 14 | 15 | ai = socket.getaddrinfo("127.0.0.1", 8080) 16 | print("Bind address info:", ai) 17 | addr = ai[0][4] 18 | 19 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 20 | s.bind(addr) 21 | s.listen(5) 22 | print("Listening, connect your browser to http://127.0.0.1:8080/") 23 | 24 | counter = 0 25 | while True: 26 | res = s.accept() 27 | client_s = res[0] 28 | client_addr = res[1] 29 | print("Client address:", client_addr) 30 | print("Client socket:", client_s) 31 | print("Request:") 32 | if 0: 33 | # MicroPython rawsocket module supports file interface directly 34 | print(client_s.read(4096)) 35 | #print(client_s.readall()) 36 | client_s.write(CONTENT.format(counter)) 37 | else: 38 | print(client_s.recv(4096)) 39 | client_s.send(bytes(CONTENT.format(counter), "ascii")) 40 | client_s.close() 41 | counter += 1 42 | -------------------------------------------------------------------------------- /tests/bytecode/pylib-tests/this.py: -------------------------------------------------------------------------------- 1 | s = """Gur Mra bs Clguba, ol Gvz Crgref 2 | 3 | Ornhgvshy vf orggre guna htyl. 4 | Rkcyvpvg vf orggre guna vzcyvpvg. 5 | Fvzcyr vf orggre guna pbzcyrk. 6 | Pbzcyrk vf orggre guna pbzcyvpngrq. 7 | Syng vf orggre guna arfgrq. 8 | Fcnefr vf orggre guna qrafr. 9 | Ernqnovyvgl pbhagf. 10 | Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf. 11 | Nygubhtu cenpgvpnyvgl orngf chevgl. 12 | Reebef fubhyq arire cnff fvyragyl. 13 | Hayrff rkcyvpvgyl fvyraprq. 14 | Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff. 15 | Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg. 16 | Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu. 17 | Abj vf orggre guna arire. 18 | Nygubhtu arire vf bsgra orggre guna *evtug* abj. 19 | Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn. 20 | Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn. 21 | Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!""" 22 | 23 | d = {} 24 | for c in (x+65, 97): 25 | for i in range(26): 26 | d[chr(i+c)] = chr((i+13) % 26 + c) 27 | 28 | print("".join([d.get(c, c) for c in s])) 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013 Damien P. George 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /stm/stmusbd/usbd_conf.h: -------------------------------------------------------------------------------- 1 | #ifndef __USBD_CONF__H__ 2 | #define __USBD_CONF__H__ 3 | 4 | #define USBD_CFG_MAX_NUM 1 5 | #define USBD_ITF_MAX_NUM 1 // TODO need more than 1? 6 | 7 | // CDC Endpoints parameters 8 | #define CDC_IN_EP 0x81 /* EP1 for data IN */ 9 | #define CDC_OUT_EP 0x01 /* EP1 for data OUT */ 10 | #define CDC_CMD_EP 0x82 /* EP2 for CDC commands */ 11 | #define CDC_DATA_MAX_PACKET_SIZE 64 /* Endpoint IN & OUT Packet size */ 12 | #define CDC_CMD_PACKET_SZE 8 /* Control Endpoint Packet size */ 13 | #define CDC_IN_FRAME_INTERVAL 5 /* Number of frames between IN transfers */ 14 | #define APP_RX_DATA_SIZE 2048 /* Total size of IN buffer: 15 | APP_RX_DATA_SIZE*8/MAX_BAUDARATE*1000 should be > CDC_IN_FRAME_INTERVAL */ 16 | 17 | // MSC parameters 18 | #define MSC_IN_EP 0x83 19 | #define MSC_OUT_EP 0x03 20 | #define MSC_MAX_PACKET 64 21 | #define MSC_MEDIA_PACKET 2048 /* XXX was 4096; how small can we make it? */ 22 | 23 | #endif //__USBD_CONF__H__ 24 | -------------------------------------------------------------------------------- /tests/basics/containment.py: -------------------------------------------------------------------------------- 1 | for i in 1, 2: 2 | for o in {1:2}, {1}, {1:2}.keys(): 3 | print("{} in {}: {}".format(i, o, i in o)) 4 | print("{} not in {}: {}".format(i, o, i not in o)) 5 | 6 | haystack = "supercalifragilistc" 7 | for needle in (haystack[i:] for i in range(len(haystack))): 8 | print(needle, "in", haystack, "::", needle in haystack) 9 | print(needle, "not in", haystack, "::", needle not in haystack) 10 | print(haystack, "in", needle, "::", haystack in needle) 11 | print(haystack, "not in", needle, "::", haystack not in needle) 12 | for needle in (haystack[:i+1] for i in range(len(haystack))): 13 | print(needle, "in", haystack, "::", needle in haystack) 14 | print(needle, "not in", haystack, "::", needle not in haystack) 15 | print(haystack, "in", needle, "::", haystack in needle) 16 | print(haystack, "not in", needle, "::", haystack not in needle) 17 | 18 | # until here, the tests would work without the 'second attempt' iteration thing. 19 | 20 | for i in 1, 2: 21 | for o in [], [1], [1, 2]: 22 | print("{} in {}: {}".format(i, o, i in o)) 23 | print("{} not in {}: {}".format(i, o, i not in o)) 24 | -------------------------------------------------------------------------------- /tests/run-tests: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | RM="/bin/rm -f" 4 | CPYTHON3=python3.3 5 | MP_PY=../unix/micropython 6 | 7 | numtests=0 8 | numtestcases=0 9 | numpassed=0 10 | numfailed=0 11 | namefailed= 12 | 13 | if [ $# -eq 0 ] 14 | then 15 | tests="basics/*.py io/*.py" 16 | else 17 | tests="$@" 18 | fi 19 | 20 | for infile in $tests 21 | do 22 | basename=`basename $infile .py` 23 | outfile=${basename}.out 24 | expfile=${basename}.exp 25 | 26 | $CPYTHON3 -B $infile > $expfile 27 | $MP_PY $infile > $outfile 28 | ((numtestcases = numtestcases + $(cat $expfile | wc -l))) 29 | 30 | diff --brief $expfile $outfile > /dev/null 31 | 32 | if [ $? -eq 0 ] 33 | then 34 | echo "pass $infile" 35 | $RM $outfile 36 | $RM $expfile 37 | ((numpassed=numpassed + 1)) 38 | else 39 | echo "FAIL $infile" 40 | ((numfailed=numfailed + 1)) 41 | namefailed="$namefailed $basename" 42 | fi 43 | 44 | ((numtests=numtests + 1)) 45 | done 46 | 47 | echo "$numtests tests performed ($numtestcases individual testcases)" 48 | echo "$numpassed tests passed" 49 | if [[ $numfailed != 0 ]] 50 | then 51 | echo "$numfailed tests failed -$namefailed" 52 | exit 1 53 | else 54 | exit 0 55 | fi 56 | -------------------------------------------------------------------------------- /py/map.h: -------------------------------------------------------------------------------- 1 | typedef struct _mp_map_elem_t { 2 | mp_obj_t key; 3 | mp_obj_t value; 4 | } mp_map_elem_t; 5 | 6 | typedef struct _mp_map_t { 7 | struct { 8 | machine_uint_t all_keys_are_qstrs : 1; 9 | machine_uint_t used : (8 * sizeof(machine_uint_t) - 1); 10 | }; 11 | machine_uint_t alloc; 12 | mp_map_elem_t *table; 13 | } mp_map_t; 14 | 15 | typedef struct _mp_set_t { 16 | machine_uint_t alloc; 17 | machine_uint_t used; 18 | mp_obj_t *table; 19 | } mp_set_t; 20 | 21 | typedef enum _mp_map_lookup_kind_t { 22 | MP_MAP_LOOKUP, // 0 23 | MP_MAP_LOOKUP_ADD_IF_NOT_FOUND, // 1 24 | MP_MAP_LOOKUP_REMOVE_IF_FOUND, // 2 25 | MP_MAP_LOOKUP_FIRST = 4, 26 | } mp_map_lookup_kind_t; 27 | 28 | int get_doubling_prime_greater_or_equal_to(int x); 29 | void mp_map_init(mp_map_t *map, int n); 30 | mp_map_t *mp_map_new(int n); 31 | void mp_map_deinit(mp_map_t *map); 32 | void mp_map_free(mp_map_t *map); 33 | mp_map_elem_t* mp_map_lookup(mp_map_t *map, mp_obj_t index, mp_map_lookup_kind_t lookup_kind); 34 | void mp_map_clear(mp_map_t *map); 35 | 36 | void mp_set_init(mp_set_t *set, int n); 37 | mp_obj_t mp_set_lookup(mp_set_t *set, mp_obj_t index, mp_map_lookup_kind_t lookup_kind); 38 | void mp_set_clear(mp_set_t *set); 39 | -------------------------------------------------------------------------------- /stm/malloc0.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "std.h" 3 | #include "mpconfig.h" 4 | #include "gc.h" 5 | 6 | #if 0 7 | static uint32_t mem = 0; 8 | 9 | void *malloc(size_t n) { 10 | if (mem == 0) { 11 | extern uint32_t _heap_start; 12 | mem = (uint32_t)&_heap_start; // need to use big ram block so we can execute code from it (is it true that we can't execute from CCM?) 13 | } 14 | void *ptr = (void*)mem; 15 | mem = (mem + n + 3) & (~3); 16 | if (mem > 0x20000000 + 0x18000) { 17 | void __fatal_error(const char*); 18 | __fatal_error("out of memory"); 19 | } 20 | return ptr; 21 | } 22 | 23 | void free(void *ptr) { 24 | } 25 | 26 | void *realloc(void *ptr, size_t n) { 27 | return malloc(n); 28 | } 29 | 30 | #endif 31 | 32 | void *calloc(size_t sz, size_t n) { 33 | char *ptr = malloc(sz * n); 34 | for (int i = 0; i < sz * n; i++) { 35 | ptr[i] = 0; 36 | } 37 | return ptr; 38 | } 39 | 40 | void *malloc(size_t n) { 41 | return gc_alloc(n); 42 | } 43 | 44 | void free(void *ptr) { 45 | gc_free(ptr); 46 | } 47 | 48 | void *realloc(void *ptr, size_t n) { 49 | return gc_realloc(ptr, n); 50 | } 51 | 52 | void __assert_func(void) { 53 | printf("\nASSERT FAIL!"); 54 | for (;;) { 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /CODECONVENTIONS.md: -------------------------------------------------------------------------------- 1 | Code conventions 2 | ================ 3 | 4 | When writing new code, please adhere to the following conventions. 5 | 6 | White space: 7 | - Expand tabs to 4 spaces. 8 | - Don't leave trailing whitespace at the end of a line. 9 | - For control blocks (if, for, while), put 1 space between the 10 | keyword and the opening parenthesis. 11 | - Put 1 space after a comma, and 1 space around operators. 12 | 13 | Braces: 14 | - Use braces for all blocks, even no-line and single-line pieces of 15 | code. 16 | - Put opening braces on the end of the line it belongs to, not on 17 | a new line. 18 | - For else-statements, put the else on the same line as the previous 19 | closing brace. 20 | 21 | Include directives: 22 | - Don't include within a header file. 23 | 24 | Type names and declarations: 25 | - When defining a type, put '_t' after it. 26 | 27 | Examples 28 | -------- 29 | 30 | Braces and spaces: 31 | 32 | int foo(int x, int y) { 33 | if (x < y) { 34 | foo(y, x); 35 | } else { 36 | foo(x + 1, y - 1); 37 | } 38 | 39 | for (int i = 0; i < x; i++) { 40 | } 41 | } 42 | 43 | Type declarations: 44 | 45 | typedef struct _my_struct_t { 46 | int member; 47 | void *data; 48 | } my_struct_t; 49 | -------------------------------------------------------------------------------- /teensy/memzip.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "memzip.h" 5 | 6 | extern uint8_t _staticfs[]; 7 | 8 | MEMZIP_RESULT memzip_locate(const char *filename, void **data, size_t *len) 9 | { 10 | const MEMZIP_FILE_HDR *file_hdr = (const MEMZIP_FILE_HDR *)_staticfs; 11 | uint8_t *mem_data; 12 | 13 | /* Zip file filenames don't have a leading /, so we strip it off */ 14 | 15 | if (*filename == '/') { 16 | filename++; 17 | } 18 | while (file_hdr->signature == MEMZIP_FILE_HEADER_SIGNATURE) { 19 | const char *file_hdr_filename = (const char *)&file_hdr[1]; 20 | mem_data = (uint8_t *)file_hdr_filename; 21 | mem_data += file_hdr->filename_len; 22 | mem_data += file_hdr->extra_len; 23 | if (!strncmp(file_hdr_filename, filename, file_hdr->filename_len)) { 24 | /* We found a match */ 25 | if (file_hdr->compression_method != 0) { 26 | return MZ_FILE_COMPRESSED; 27 | } 28 | 29 | *data = mem_data; 30 | *len = file_hdr->uncompressed_size; 31 | return MZ_OK; 32 | } 33 | mem_data += file_hdr->uncompressed_size; 34 | file_hdr = (const MEMZIP_FILE_HDR *)mem_data; 35 | } 36 | return MZ_NO_FILE; 37 | } 38 | -------------------------------------------------------------------------------- /examples/lcd.py: -------------------------------------------------------------------------------- 1 | # LCD testing object for PC 2 | # uses double buffering 3 | class LCD: 4 | def __init__(self, width, height): 5 | self.width = width 6 | self.height = height 7 | self.buf1 = [[0 for x in range(self.width)] for y in range(self.height)] 8 | self.buf2 = [[0 for x in range(self.width)] for y in range(self.height)] 9 | 10 | def clear(self): 11 | for y in range(self.height): 12 | for x in range(self.width): 13 | self.buf1[y][x] = self.buf2[y][x] = 0 14 | 15 | def show(self): 16 | print('') # blank line to separate frames 17 | for y in range(self.height): 18 | for x in range(self.width): 19 | self.buf1[y][x] = self.buf2[y][x] 20 | for y in range(self.height): 21 | row = ''.join(['*' if self.buf1[y][x] else ' ' for x in range(self.width)]) 22 | print(row) 23 | 24 | def get(self, x, y): 25 | if 0 <= x < self.width and 0 <= y < self.height: 26 | return self.buf1[y][x] 27 | else: 28 | return 0 29 | 30 | def reset(self, x, y): 31 | if 0 <= x < self.width and 0 <= y < self.height: 32 | self.buf2[y][x] = 0 33 | 34 | def set(self, x, y): 35 | if 0 <= x < self.width and 0 <= y < self.height: 36 | self.buf2[y][x] = 1 37 | -------------------------------------------------------------------------------- /py/lexerstr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "misc.h" 5 | #include "mpconfig.h" 6 | #include "qstr.h" 7 | #include "lexer.h" 8 | 9 | typedef struct _mp_lexer_str_buf_t { 10 | uint free_len; // if > 0, src_beg will be freed when done by: m_free(src_beg, free_len) 11 | const char *src_beg; // beginning of source 12 | const char *src_cur; // current location in source 13 | const char *src_end; // end (exclusive) of source 14 | } mp_lexer_str_buf_t; 15 | 16 | static unichar str_buf_next_char(mp_lexer_str_buf_t *sb) { 17 | if (sb->src_cur < sb->src_end) { 18 | return *sb->src_cur++; 19 | } else { 20 | return MP_LEXER_CHAR_EOF; 21 | } 22 | } 23 | 24 | static void str_buf_free(mp_lexer_str_buf_t *sb) { 25 | if (sb->free_len > 0) { 26 | m_free((char*)sb->src_beg, sb->free_len); 27 | } 28 | m_del_obj(mp_lexer_str_buf_t, sb); 29 | } 30 | 31 | mp_lexer_t *mp_lexer_new_from_str_len(qstr src_name, const char *str, uint len, uint free_len) { 32 | mp_lexer_str_buf_t *sb = m_new_obj(mp_lexer_str_buf_t); 33 | sb->free_len = free_len; 34 | sb->src_beg = str; 35 | sb->src_cur = str; 36 | sb->src_end = str + len; 37 | return mp_lexer_new(src_name, sb, (mp_lexer_stream_next_char_t)str_buf_next_char, (mp_lexer_stream_close_t)str_buf_free); 38 | } 39 | -------------------------------------------------------------------------------- /stm/gccollect.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "misc.h" 4 | #include "mpconfig.h" 5 | #include "qstr.h" 6 | #include "obj.h" 7 | #include "gc.h" 8 | #include "gccollect.h" 9 | #include "systick.h" 10 | 11 | void gc_helper_get_regs_and_clean_stack(machine_uint_t *regs, machine_uint_t heap_end); 12 | 13 | void gc_collect(void) { 14 | uint32_t start = sys_tick_counter; 15 | gc_collect_start(); 16 | gc_collect_root((void**)&_ram_start, ((uint32_t)&_heap_start - (uint32_t)&_ram_start) / 4); 17 | machine_uint_t regs[10]; 18 | gc_helper_get_regs_and_clean_stack(regs, HEAP_END); 19 | gc_collect_root((void**)HEAP_END, (RAM_END - HEAP_END) / 4); // will trace regs since they now live in this function on the stack 20 | gc_collect_end(); 21 | uint32_t ticks = sys_tick_counter - start; // TODO implement a function that does this properly 22 | 23 | if (0) { 24 | // print GC info 25 | gc_info_t info; 26 | gc_info(&info); 27 | printf("GC@%lu %lums\n", start, ticks); 28 | printf(" %lu total\n", info.total); 29 | printf(" %lu : %lu\n", info.used, info.free); 30 | printf(" 1=%lu 2=%lu m=%lu\n", info.num_1block, info.num_2block, info.max_block); 31 | } 32 | } 33 | 34 | static mp_obj_t pyb_gc(void) { 35 | gc_collect(); 36 | return mp_const_none; 37 | } 38 | 39 | MP_DEFINE_CONST_FUN_OBJ_0(pyb_gc_obj, pyb_gc); 40 | -------------------------------------------------------------------------------- /unix/mpconfigport.h: -------------------------------------------------------------------------------- 1 | // options to control how Micro Python is built 2 | 3 | // Linking with GNU readline causes binary to be licensed under GPL 4 | #ifndef MICROPY_USE_READLINE 5 | #define MICROPY_USE_READLINE (1) 6 | #endif 7 | 8 | #define MICROPY_EMIT_X64 (1) 9 | #define MICROPY_EMIT_THUMB (0) 10 | #define MICROPY_EMIT_INLINE_THUMB (0) 11 | #define MICROPY_MEM_STATS (1) 12 | #define MICROPY_DEBUG_PRINTERS (1) 13 | #define MICROPY_ENABLE_REPL_HELPERS (1) 14 | #define MICROPY_ENABLE_LEXER_UNIX (1) 15 | #define MICROPY_ENABLE_FLOAT (1) 16 | #define MICROPY_LONGINT_IMPL (MICROPY_LONGINT_IMPL_LONGLONG) 17 | 18 | // type definitions for the specific machine 19 | 20 | #ifdef __LP64__ 21 | typedef long machine_int_t; // must be pointer size 22 | typedef unsigned long machine_uint_t; // must be pointer size 23 | #else 24 | // These are definitions for machines where sizeof(int) == sizeof(void*), 25 | // regardless for actual size. 26 | typedef int machine_int_t; // must be pointer size 27 | typedef unsigned int machine_uint_t; // must be pointer size 28 | #endif 29 | 30 | #define BYTES_PER_WORD sizeof(machine_int_t) 31 | 32 | typedef void *machine_ptr_t; // must be of pointer size 33 | typedef const void *machine_const_ptr_t; // must be of pointer size 34 | typedef double machine_float_t; 35 | 36 | machine_float_t machine_sqrt(machine_float_t x); 37 | -------------------------------------------------------------------------------- /py/qstr.h: -------------------------------------------------------------------------------- 1 | // See qstrraw.h for a list of qstr's that are available as constants. 2 | // Reference them as MP_QSTR_xxxx. 3 | // 4 | // Note: it would be possible to define MP_QSTR_xxx as qstr_from_str_static("xxx") 5 | // for qstrs that are referenced this way, but you don't want to have them in ROM. 6 | 7 | enum { 8 | MP_QSTR_NULL = 0, // indicates invalid/no qstr 9 | MP_QSTR_ = 1, // the empty qstr 10 | #define Q(id, str) MP_QSTR_##id, 11 | // TODO having 'build/py.' here is a bit of a hack, should take config variable from Makefile 12 | #include "build/py/qstrdefs.generated.h" 13 | #undef Q 14 | MP_QSTR_number_of, 15 | } category_t; 16 | 17 | typedef machine_uint_t qstr; 18 | 19 | #define QSTR_FROM_STR_STATIC(s) (qstr_from_strn((s), strlen(s))) 20 | 21 | void qstr_init(void); 22 | 23 | machine_uint_t qstr_compute_hash(const byte *data, uint len); 24 | qstr qstr_find_strn(const byte *str, uint str_len); // returns MP_QSTR_NULL if not found 25 | 26 | qstr qstr_from_str(const char *str); 27 | qstr qstr_from_strn(const char *str, uint len); 28 | //qstr qstr_from_str_static(const char *str); 29 | qstr qstr_from_strn_take(char *str, uint alloc_len, uint len); 30 | //qstr qstr_from_strn_copy(const char *str, int len); 31 | 32 | byte* qstr_build_start(uint len, byte **q_ptr); 33 | qstr qstr_build_end(byte *q_ptr); 34 | 35 | machine_uint_t qstr_hash(qstr q); 36 | const char* qstr_str(qstr q); 37 | uint qstr_len(qstr q); 38 | const byte* qstr_data(qstr q, uint *len); 39 | -------------------------------------------------------------------------------- /py/mkenv.mk: -------------------------------------------------------------------------------- 1 | ifneq ($(lastword a b),b) 2 | $(error These Makefiles require make 3.81 or newer) 3 | endif 4 | 5 | # Set TOP to be the path to get from the current directory (where make was 6 | # invoked) to the top of the tree. $(lastword $(MAKEFILE_LIST)) returns 7 | # the name of this makefile relative to where make was invoked. 8 | # 9 | # We assume that this file is in the py directory so we use $(dir ) twice 10 | # to get to the top of the tree. 11 | 12 | THIS_MAKEFILE := $(lastword $(MAKEFILE_LIST)) 13 | TOP := $(patsubst %/py/mkenv.mk,%,$(THIS_MAKEFILE)) 14 | 15 | # Turn on increased build verbosity by defining BUILD_VERBOSE in your main 16 | # Makefile or in your environment. You can also use V=1 on the make command 17 | # line. 18 | 19 | ifeq ("$(origin V)", "command line") 20 | BUILD_VERBOSE=$(V) 21 | endif 22 | ifndef BUILD_VERBOSE 23 | BUILD_VERBOSE = 0 24 | endif 25 | ifeq ($(BUILD_VERBOSE),0) 26 | Q = @ 27 | else 28 | Q = 29 | endif 30 | # Since this is a new feature, advertise it 31 | ifeq ($(BUILD_VERBOSE),0) 32 | $(info Use make V=1 or set BUILD_VERBOSE in your environment to increase build verbosity.) 33 | endif 34 | 35 | # default settings; can be overriden in main Makefile 36 | 37 | PY_SRC ?= $(TOP)/py 38 | BUILD ?= build 39 | 40 | RM = rm 41 | ECHO = @echo 42 | 43 | AS = $(CROSS_COMPILE)as 44 | CC = $(CROSS_COMPILE)gcc 45 | LD = $(CROSS_COMPILE)ld 46 | OBJCOPY = $(CROSS_COMPILE)objcopy 47 | SIZE = $(CROSS_COMPILE)size 48 | 49 | all: 50 | .PHONY: all 51 | 52 | MKENV_INCLUDED = 1 53 | -------------------------------------------------------------------------------- /py/qstrdefs.h: -------------------------------------------------------------------------------- 1 | // All the qstr definitions in this file are available as constants. 2 | // That is, they are in ROM and you can reference them simple as MP_QSTR_xxxx. 3 | 4 | Q(__build_class__) 5 | Q(__class__) 6 | Q(__doc__) 7 | Q(__init__) 8 | Q(__locals__) 9 | Q(__main__) 10 | Q(__module__) 11 | Q(__name__) 12 | Q(__next__) 13 | Q(__qualname__) 14 | Q(__repl_print__) 15 | 16 | Q(__getitem__) 17 | Q(__add__) 18 | Q(__sub__) 19 | 20 | Q(micropython) 21 | Q(byte_code) 22 | Q(native) 23 | Q(viper) 24 | Q(asm_thumb) 25 | 26 | Q(Ellipsis) 27 | Q(StopIteration) 28 | 29 | Q(AssertionError) 30 | Q(AttributeError) 31 | Q(IndentationError) 32 | Q(IndexError) 33 | Q(KeyError) 34 | Q(NameError) 35 | Q(OSError) 36 | Q(SyntaxError) 37 | Q(TypeError) 38 | Q(ValueError) 39 | Q(OverflowError) 40 | 41 | Q(abs) 42 | Q(all) 43 | Q(any) 44 | Q(array) 45 | Q(bool) 46 | Q(bytearray) 47 | Q(bytes) 48 | Q(callable) 49 | Q(chr) 50 | Q(complex) 51 | Q(dict) 52 | Q(divmod) 53 | Q(enumerate) 54 | Q(eval) 55 | Q(filter) 56 | Q(float) 57 | Q(hash) 58 | Q(int) 59 | Q(isinstance) 60 | Q(issubclass) 61 | Q(iter) 62 | Q(len) 63 | Q(list) 64 | Q(map) 65 | Q(max) 66 | Q(min) 67 | Q(next) 68 | Q(ord) 69 | Q(pow) 70 | Q(print) 71 | Q(range) 72 | Q(repr) 73 | Q(set) 74 | Q(sorted) 75 | Q(sum) 76 | Q(str) 77 | Q(tuple) 78 | Q(type) 79 | Q(zip) 80 | 81 | Q(append) 82 | Q(pop) 83 | Q(sort) 84 | Q(join) 85 | Q(strip) 86 | Q(format) 87 | 88 | Q() 89 | Q() 90 | Q() 91 | Q() 92 | Q() 93 | Q() 94 | Q() 95 | Q() 96 | -------------------------------------------------------------------------------- /py/builtin.h: -------------------------------------------------------------------------------- 1 | mp_obj_t mp_builtin___import__(int n_args, mp_obj_t *args); 2 | 3 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin___build_class___obj); 4 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin___repl_print___obj); 5 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_abs_obj); 6 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_all_obj); 7 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_any_obj); 8 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_bytes_obj); // Temporary hack 9 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_callable_obj); 10 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_chr_obj); 11 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_divmod_obj); 12 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_eval_obj); 13 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_hash_obj); 14 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_isinstance_obj); 15 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_issubclass_obj); 16 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_iter_obj); 17 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_len_obj); 18 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_list_obj); 19 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_max_obj); 20 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_min_obj); 21 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_next_obj); 22 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_ord_obj); 23 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_pow_obj); 24 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_print_obj); 25 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_range_obj); 26 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_repr_obj); 27 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_sorted_obj); 28 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_sum_obj); 29 | MP_DECLARE_CONST_FUN_OBJ(mp_builtin_str_obj); 30 | 31 | void mp_module_micropython_init(void); 32 | -------------------------------------------------------------------------------- /py/builtinmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "misc.h" 9 | #include "mpconfig.h" 10 | #include "qstr.h" 11 | #include "obj.h" 12 | #include "runtime.h" 13 | #include "builtin.h" 14 | 15 | // Various builtins specific to MicroPython runtime, 16 | // living in micropython module 17 | 18 | #if MICROPY_MEM_STATS 19 | static mp_obj_t mem_total() { 20 | return MP_OBJ_NEW_SMALL_INT((machine_int_t)m_get_total_bytes_allocated()); 21 | } 22 | 23 | static mp_obj_t mem_current() { 24 | return MP_OBJ_NEW_SMALL_INT((machine_int_t)m_get_current_bytes_allocated()); 25 | } 26 | 27 | static mp_obj_t mem_peak() { 28 | return MP_OBJ_NEW_SMALL_INT((machine_int_t)m_get_peak_bytes_allocated()); 29 | } 30 | 31 | MP_DEFINE_CONST_FUN_OBJ_0(mp_builtin_mem_total_obj, mem_total); 32 | MP_DEFINE_CONST_FUN_OBJ_0(mp_builtin_mem_current_obj, mem_current); 33 | MP_DEFINE_CONST_FUN_OBJ_0(mp_builtin_mem_peak_obj, mem_peak); 34 | #endif 35 | 36 | void mp_module_micropython_init(void) { 37 | mp_obj_t m_mp = mp_obj_new_module(MP_QSTR_micropython); 38 | rt_store_name(MP_QSTR_micropython, m_mp); 39 | 40 | #if MICROPY_MEM_STATS 41 | rt_store_attr(m_mp, QSTR_FROM_STR_STATIC("mem_total"), (mp_obj_t)&mp_builtin_mem_total_obj); 42 | rt_store_attr(m_mp, QSTR_FROM_STR_STATIC("mem_current"), (mp_obj_t)&mp_builtin_mem_current_obj); 43 | rt_store_attr(m_mp, QSTR_FROM_STR_STATIC("mem_peak"), (mp_obj_t)&mp_builtin_mem_peak_obj); 44 | #endif 45 | } 46 | -------------------------------------------------------------------------------- /py/repl.c: -------------------------------------------------------------------------------- 1 | #include "misc.h" 2 | #include "mpconfig.h" 3 | #include "repl.h" 4 | 5 | #if MICROPY_ENABLE_REPL_HELPERS 6 | 7 | bool str_startswith_word(const char *str, const char *head) { 8 | int i; 9 | for (i = 0; str[i] && head[i]; i++) { 10 | if (str[i] != head[i]) { 11 | return false; 12 | } 13 | } 14 | return head[i] == '\0' && (str[i] == '\0' || !unichar_isalpha(str[i])); 15 | } 16 | 17 | bool mp_repl_is_compound_stmt(const char *line) { 18 | // compound if line starts with a certain keyword 19 | if ( 20 | str_startswith_word(line, "if") 21 | || str_startswith_word(line, "while") 22 | || str_startswith_word(line, "for") 23 | || str_startswith_word(line, "try") 24 | || str_startswith_word(line, "with") 25 | || str_startswith_word(line, "def") 26 | || str_startswith_word(line, "class") 27 | || str_startswith_word(line, "@") 28 | ) { 29 | return true; 30 | } 31 | 32 | // also "compound" if unmatched open bracket 33 | int n_paren = 0; 34 | int n_brack = 0; 35 | int n_brace = 0; 36 | for (const char *l = line; *l; l++) { 37 | switch (*l) { 38 | case '(': n_paren += 1; break; 39 | case ')': n_paren -= 1; break; 40 | case '[': n_brack += 1; break; 41 | case ']': n_brack -= 1; break; 42 | case '{': n_brace += 1; break; 43 | case '}': n_brace -= 1; break; 44 | } 45 | } 46 | return n_paren > 0 || n_brack > 0 || n_brace > 0; 47 | } 48 | 49 | #endif // MICROPY_ENABLE_REPL_HELPERS 50 | -------------------------------------------------------------------------------- /tests/basics/int1.py: -------------------------------------------------------------------------------- 1 | print(int(0)) 2 | print(int(1)) 3 | print(int(+1)) 4 | print(int(-1)) 5 | 6 | print(int('0')) 7 | print(int('+0')) 8 | print(int('-0')) 9 | print(int('1')) 10 | print(int('+1')) 11 | print(int('-1')) 12 | print(int('01')) 13 | print(int('9')) 14 | print(int('10')) 15 | print(int('+10')) 16 | print(int('-10')) 17 | print(int('12')) 18 | print(int('-12')) 19 | print(int('99')) 20 | print(int('100')) 21 | print(int('314')) 22 | print(int(' 314')) 23 | print(int('314 ')) 24 | print(int(' \t\t 314 \t\t ')) 25 | print(int(' 1 ')) 26 | print(int(' -3 ')) 27 | 28 | print(int('0', 10)) 29 | print(int('1', 10)) 30 | print(int(' \t 1 \t ', 10)) 31 | print(int('11', 10)) 32 | print(int('11', 16)) 33 | print(int('11', 8)) 34 | print(int('11', 2)) 35 | print(int('11', 36)) 36 | print(int('0o123', 0)) 37 | print(int('8388607')) 38 | print(int('0x123', 16)) 39 | print(int('0X123', 16)) 40 | print(int('0o123', 8)) 41 | print(int('0O123', 8)) 42 | print(int('0123', 8)) 43 | print(int('0b100', 2)) 44 | print(int('0B100', 2)) 45 | print(int('0100', 2)) 46 | print(int(' \t 0o12', 8)) 47 | print(int('0o12 \t ', 8)) 48 | 49 | 50 | def test(value, base): 51 | try: 52 | print(int(value, base)) 53 | except ValueError: 54 | print('ValueError') 55 | 56 | 57 | test('x', 0) 58 | test('1x', 0) 59 | test(' 1x', 0) 60 | test(' 1' + chr(2) + ' ', 0) 61 | test('', 0) 62 | test(' ', 0) 63 | test(' \t\t ', 0) 64 | test("\u0200", 0) 65 | test('0x', 16) 66 | test('0x', 0) 67 | test('0o', 8) 68 | test('0o', 0) 69 | test('0b', 2) 70 | test('0b', 0) 71 | test('0b2', 2) 72 | test('0o8', 8) 73 | test('0xg', 16) 74 | test('1 1', 16) 75 | -------------------------------------------------------------------------------- /py/objenumerate.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "misc.h" 5 | #include "mpconfig.h" 6 | #include "qstr.h" 7 | #include "obj.h" 8 | #include "runtime.h" 9 | 10 | typedef struct _mp_obj_enumerate_t { 11 | mp_obj_base_t base; 12 | mp_obj_t iter; 13 | machine_int_t cur; 14 | } mp_obj_enumerate_t; 15 | 16 | static mp_obj_t enumerate_getiter(mp_obj_t self_in) { 17 | return self_in; 18 | } 19 | 20 | static mp_obj_t enumerate_iternext(mp_obj_t self_in); 21 | 22 | /* TODO: enumerate is one of the ones that can take args or kwargs. 23 | Sticking to args for now */ 24 | static mp_obj_t enumerate_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { 25 | assert(n_args > 0); 26 | mp_obj_enumerate_t *o = m_new_obj(mp_obj_enumerate_t); 27 | o->base.type = &enumerate_type; 28 | o->iter = rt_getiter(args[0]); 29 | o->cur = n_args > 1 ? mp_obj_get_int(args[1]) : 0; 30 | return o; 31 | } 32 | 33 | const mp_obj_type_t enumerate_type = { 34 | { &mp_const_type }, 35 | "enumerate", 36 | .make_new = enumerate_make_new, 37 | .iternext = enumerate_iternext, 38 | .getiter = enumerate_getiter, 39 | }; 40 | 41 | static mp_obj_t enumerate_iternext(mp_obj_t self_in) { 42 | assert(MP_OBJ_IS_TYPE(self_in, &enumerate_type)); 43 | mp_obj_enumerate_t *self = self_in; 44 | mp_obj_t next = rt_iternext(self->iter); 45 | if (next == mp_const_stop_iteration) { 46 | return mp_const_stop_iteration; 47 | } else { 48 | mp_obj_t items[] = {MP_OBJ_NEW_SMALL_INT(self->cur++), next}; 49 | return mp_obj_new_tuple(2, items); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /py/builtineval.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "nlr.h" 9 | #include "misc.h" 10 | #include "mpconfig.h" 11 | #include "qstr.h" 12 | #include "lexer.h" 13 | #include "lexerunix.h" 14 | #include "parse.h" 15 | #include "obj.h" 16 | #include "compile.h" 17 | #include "runtime0.h" 18 | #include "runtime.h" 19 | #include "map.h" 20 | #include "builtin.h" 21 | 22 | static mp_obj_t mp_builtin_eval(mp_obj_t o_in) { 23 | uint str_len; 24 | const byte *str = mp_obj_str_get_data(o_in, &str_len); 25 | 26 | // create the lexer 27 | mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_string_gt_, (const char*)str, str_len, 0); 28 | qstr source_name = mp_lexer_source_name(lex); 29 | 30 | // parse the string 31 | qstr parse_exc_id; 32 | const char *parse_exc_msg; 33 | mp_parse_node_t pn = mp_parse(lex, MP_PARSE_EVAL_INPUT, &parse_exc_id, &parse_exc_msg); 34 | mp_lexer_free(lex); 35 | 36 | if (pn == MP_PARSE_NODE_NULL) { 37 | // parse error; raise exception 38 | nlr_jump(mp_obj_new_exception_msg(parse_exc_id, parse_exc_msg)); 39 | } 40 | 41 | // compile the string 42 | mp_obj_t module_fun = mp_compile(pn, source_name, false); 43 | mp_parse_node_free(pn); 44 | 45 | if (module_fun == mp_const_none) { 46 | // TODO handle compile error correctly 47 | return mp_const_none; 48 | } 49 | 50 | // complied successfully, execute it 51 | return rt_call_function_0(module_fun); 52 | } 53 | 54 | MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_eval_obj, mp_builtin_eval); 55 | -------------------------------------------------------------------------------- /stm/sdio.c: -------------------------------------------------------------------------------- 1 | // TODO 2 | // make it work with DMA 3 | 4 | #include 5 | //#include "stm32f4xx_sdio.h" 6 | #include "stm324x7i_eval_sdio_sd.h" 7 | #include "misc.h" 8 | #include "systick.h" 9 | 10 | #define BLOCK_SIZE 512 /* Block Size in Bytes */ 11 | 12 | uint8_t aBuffer_Block_Rx[BLOCK_SIZE]; 13 | 14 | void sdio_init(void) { 15 | SD_Error error = SD_Init(); 16 | printf("Init: %x\n", error); 17 | uint8_t det = SD_Detect(); 18 | printf("Detc: %x\n", det); 19 | 20 | if (!det) { 21 | printf("no card detected\n"); 22 | SD_PowerOFF(); 23 | SD_DeInit(); 24 | return; 25 | } 26 | 27 | // read a block! 28 | error = SD_ReadBlock(aBuffer_Block_Rx, 512, BLOCK_SIZE); 29 | printf("ReadBlock: %d\n", error); 30 | 31 | /* 32 | // Check if the Transfer is finished 33 | error = SD_WaitReadOperation(); 34 | printf("WaitReadOp: %d\n", error); 35 | */ 36 | 37 | uint32_t stc = sys_tick_counter; 38 | while (SD_GetStatus() != SD_TRANSFER_OK) { 39 | if (sys_tick_has_passed(stc, 2000)) { 40 | printf("timeout waiting for read to finish\n"); 41 | break; 42 | } 43 | } 44 | printf("done!!\n"); 45 | 46 | printf("%.16s", aBuffer_Block_Rx); 47 | 48 | /* 49 | snprintf((char*)aBuffer_Block_Rx, BLOCK_SIZE, "Here is some data back for you!\nBLOCK_SIZE=%d\n", BLOCK_SIZE); 50 | error = SD_WriteBlock(aBuffer_Block_Rx, 512, BLOCK_SIZE); 51 | printf("WriteBlock: %d\n", error); 52 | 53 | while (SD_GetStatus() != SD_TRANSFER_OK) { 54 | } 55 | printf("done writing!\n"); 56 | */ 57 | 58 | SD_PowerOFF(); 59 | SD_DeInit(); 60 | } 61 | -------------------------------------------------------------------------------- /py/objzip.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "misc.h" 5 | #include "mpconfig.h" 6 | #include "qstr.h" 7 | #include "obj.h" 8 | #include "runtime.h" 9 | 10 | typedef struct _mp_obj_zip_t { 11 | mp_obj_base_t base; 12 | int n_iters; 13 | mp_obj_t iters[]; 14 | } mp_obj_zip_t; 15 | 16 | static mp_obj_t zip_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { 17 | // TODO check n_kw == 0 18 | 19 | mp_obj_zip_t *o = m_new_obj_var(mp_obj_zip_t, mp_obj_t, n_args); 20 | o->base.type = &zip_type; 21 | o->n_iters = n_args; 22 | for (int i = 0; i < n_args; i++) { 23 | o->iters[i] = rt_getiter(args[i]); 24 | } 25 | return o; 26 | } 27 | 28 | static mp_obj_t zip_getiter(mp_obj_t self_in) { 29 | return self_in; 30 | } 31 | 32 | static mp_obj_t zip_iternext(mp_obj_t self_in) { 33 | assert(MP_OBJ_IS_TYPE(self_in, &zip_type)); 34 | mp_obj_zip_t *self = self_in; 35 | mp_obj_t *items; 36 | if (self->n_iters == 0) { 37 | return mp_const_stop_iteration; 38 | } 39 | mp_obj_t o = mp_obj_new_tuple(self->n_iters, NULL); 40 | mp_obj_tuple_get(o, NULL, &items); 41 | 42 | for (int i = 0; i < self->n_iters; i++) { 43 | mp_obj_t next = rt_iternext(self->iters[i]); 44 | if (next == mp_const_stop_iteration) { 45 | mp_obj_tuple_del(o); 46 | return mp_const_stop_iteration; 47 | } 48 | items[i] = next; 49 | } 50 | return o; 51 | } 52 | 53 | const mp_obj_type_t zip_type = { 54 | { &mp_const_type }, 55 | "zip", 56 | .make_new = zip_make_new, 57 | .getiter = zip_getiter, 58 | .iternext = zip_iternext, 59 | }; 60 | -------------------------------------------------------------------------------- /py/lexerunix.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include "misc.h" 7 | #include "mpconfig.h" 8 | #include "qstr.h" 9 | #include "lexer.h" 10 | #include "lexerunix.h" 11 | 12 | #if MICROPY_ENABLE_LEXER_UNIX 13 | 14 | mp_lexer_t *mp_lexer_new_from_file(const char *filename) { 15 | int fd = open(filename, O_RDONLY); 16 | if (fd < 0) { 17 | printf("cannot open file %s\n", filename); 18 | return NULL; 19 | } 20 | uint size = lseek(fd, 0, SEEK_END); 21 | lseek(fd, 0, SEEK_SET); 22 | char *data = m_new(char, size); 23 | int read_size = read(fd, data, size); 24 | close(fd); 25 | if (read_size != size) { 26 | printf("error reading file %s\n", filename); 27 | m_del(char, data, size); 28 | return NULL; 29 | } 30 | 31 | return mp_lexer_new_from_str_len(qstr_from_str(filename), data, size, size); 32 | } 33 | 34 | /******************************************************************************/ 35 | /* unix implementation of import */ 36 | 37 | // TODO properly! 38 | 39 | static const char *import_base_dir = NULL; 40 | 41 | void mp_import_set_directory(const char *dir) { 42 | import_base_dir = dir; 43 | } 44 | 45 | mp_lexer_t *mp_import_open_file(qstr mod_name) { 46 | vstr_t *vstr = vstr_new(); 47 | if (import_base_dir != NULL) { 48 | vstr_printf(vstr, "%s/", import_base_dir); 49 | } 50 | vstr_printf(vstr, "%s.py", qstr_str(mod_name)); 51 | return mp_lexer_new_from_file(vstr_str(vstr)); // TODO does lexer need to copy the string? can we free it here? 52 | } 53 | 54 | #endif // MICROPY_ENABLE_LEXER_UNIX 55 | -------------------------------------------------------------------------------- /py/objfilter.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "nlr.h" 5 | #include "misc.h" 6 | #include "mpconfig.h" 7 | #include "qstr.h" 8 | #include "obj.h" 9 | #include "runtime.h" 10 | 11 | typedef struct _mp_obj_filter_t { 12 | mp_obj_base_t base; 13 | mp_obj_t fun; 14 | mp_obj_t iter; 15 | } mp_obj_filter_t; 16 | 17 | static mp_obj_t filter_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { 18 | if (n_args != 2 || n_kw != 0) { 19 | nlr_jump(mp_obj_new_exception_msg(MP_QSTR_TypeError, "filter expected 2 arguments")); 20 | } 21 | assert(n_args == 2); 22 | mp_obj_filter_t *o = m_new_obj(mp_obj_filter_t); 23 | o->base.type = &filter_type; 24 | o->fun = args[0]; 25 | o->iter = rt_getiter(args[1]); 26 | return o; 27 | } 28 | 29 | static mp_obj_t filter_getiter(mp_obj_t self_in) { 30 | return self_in; 31 | } 32 | 33 | static mp_obj_t filter_iternext(mp_obj_t self_in) { 34 | assert(MP_OBJ_IS_TYPE(self_in, &filter_type)); 35 | mp_obj_filter_t *self = self_in; 36 | mp_obj_t next; 37 | while ((next = rt_iternext(self->iter)) != mp_const_stop_iteration) { 38 | mp_obj_t val; 39 | if (self->fun != mp_const_none) { 40 | val = rt_call_function_n_kw(self->fun, 1, 0, &next); 41 | } else { 42 | val = next; 43 | } 44 | if (rt_is_true(val)) { 45 | return next; 46 | } 47 | } 48 | return mp_const_stop_iteration; 49 | } 50 | 51 | const mp_obj_type_t filter_type = { 52 | { &mp_const_type }, 53 | "filter", 54 | .make_new = filter_make_new, 55 | .getiter = filter_getiter, 56 | .iternext = filter_iternext, 57 | }; 58 | -------------------------------------------------------------------------------- /py/objboundmeth.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include "nlr.h" 7 | #include "misc.h" 8 | #include "mpconfig.h" 9 | #include "qstr.h" 10 | #include "obj.h" 11 | #include "runtime.h" 12 | 13 | typedef struct _mp_obj_bound_meth_t { 14 | mp_obj_base_t base; 15 | mp_obj_t meth; 16 | mp_obj_t self; 17 | } mp_obj_bound_meth_t; 18 | 19 | mp_obj_t bound_meth_call(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args) { 20 | mp_obj_bound_meth_t *self = self_in; 21 | 22 | // need to insert self->self before all other args and then call self->meth 23 | 24 | int n_total = n_args + 2 * n_kw; 25 | if (n_total <= 4) { 26 | // use stack to allocate temporary args array 27 | mp_obj_t args2[5]; 28 | args2[0] = self->self; 29 | memcpy(args2 + 1, args, n_total * sizeof(mp_obj_t)); 30 | return rt_call_function_n_kw(self->meth, n_args + 1, n_kw, &args2[0]); 31 | } else { 32 | // use heap to allocate temporary args array 33 | mp_obj_t *args2 = m_new(mp_obj_t, 1 + n_total); 34 | args2[0] = self->self; 35 | memcpy(args2 + 1, args, n_total * sizeof(mp_obj_t)); 36 | mp_obj_t res = rt_call_function_n_kw(self->meth, n_args + 1, n_kw, &args2[0]); 37 | m_del(mp_obj_t, args2, 1 + n_total); 38 | return res; 39 | } 40 | } 41 | 42 | const mp_obj_type_t bound_meth_type = { 43 | { &mp_const_type }, 44 | "bound_method", 45 | .call = bound_meth_call, 46 | }; 47 | 48 | mp_obj_t mp_obj_new_bound_meth(mp_obj_t meth, mp_obj_t self) { 49 | mp_obj_bound_meth_t *o = m_new_obj(mp_obj_bound_meth_t); 50 | o->base.type = &bound_meth_type; 51 | o->meth = meth; 52 | o->self = self; 53 | return o; 54 | } 55 | -------------------------------------------------------------------------------- /stm/cc3k/ccdebug.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | @file Adafruit_CC3000.cpp 4 | @author KTOWN (Kevin Townsend for Adafruit Industries) 5 | @license BSD (see license.txt) 6 | 7 | This is a library for the Adafruit CC3000 WiFi breakout board 8 | This library works with the Adafruit CC3000 breakout 9 | ----> https://www.adafruit.com/products/1469 10 | 11 | Check out the links above for our tutorials and wiring diagrams 12 | These chips use SPI to communicate. 13 | 14 | Adafruit invests time and resources providing this open source code, 15 | please support Adafruit and open-source hardware by purchasing 16 | products from Adafruit! 17 | 18 | @section HISTORY 19 | 20 | v1.0 - Initial release 21 | */ 22 | /**************************************************************************/ 23 | 24 | //#include 25 | 26 | #ifndef _CC3000_DEBUG 27 | #define _CC3000_DEBUG 28 | 29 | #define DEBUG_MODE (0) 30 | 31 | #define PRINT_F(__s) DEBUGPRINT(FLASHIFY(__s)) 32 | 33 | #if (DEBUG_MODE != 0) 34 | #define DEBUGPRINT_F(__s) DEBUGPRINT(FLASHIFY(__s)) 35 | #define DEBUGPRINT_DEC(x) printDec(x) 36 | #define DEBUGPRINT_DEC16(x) printDec16(x) 37 | #define DEBUGPRINT_HEX(x) printHex(x) 38 | #define DEBUGPRINT_HEX16(x) printHex16(x) 39 | #else 40 | #define DEBUGPRINT_F(__s) /* do nothing! */ 41 | #define DEBUGPRINT_DEC(x) 42 | #define DEBUGPRINT_DEC16(x) 43 | #define DEBUGPRINT_HEX(x) 44 | #define DEBUGPRINT_HEX16(x) 45 | #endif 46 | 47 | #if 0 // print debugging info 48 | #define DEBUG_PRINT (1) 49 | #define DEBUG_printf(args...) printf(args) 50 | #else // don't print debugging info 51 | #define DEBUG_printf(args...) (void)0 52 | #endif 53 | 54 | int printf(const char *fmt, ...); 55 | 56 | #endif 57 | -------------------------------------------------------------------------------- /py/objgetitemiter.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "nlr.h" 5 | #include "misc.h" 6 | #include "mpconfig.h" 7 | #include "qstr.h" 8 | #include "obj.h" 9 | #include "runtime.h" 10 | 11 | // this is a wrapper object that is turns something that has a __getitem__ method into an iterator 12 | 13 | typedef struct _mp_obj_getitem_iter_t { 14 | mp_obj_base_t base; 15 | mp_obj_t args[3]; 16 | } mp_obj_getitem_iter_t; 17 | 18 | static mp_obj_t it_iternext(mp_obj_t self_in) { 19 | mp_obj_getitem_iter_t *self = self_in; 20 | nlr_buf_t nlr; 21 | if (nlr_push(&nlr) == 0) { 22 | // try to get next item 23 | mp_obj_t value = rt_call_method_n_kw(1, 0, self->args); 24 | self->args[2] = MP_OBJ_NEW_SMALL_INT(MP_OBJ_SMALL_INT_VALUE(self->args[2]) + 1); 25 | nlr_pop(); 26 | return value; 27 | } else { 28 | // an exception was raised 29 | if (MP_OBJ_IS_TYPE(nlr.ret_val, &exception_type) && mp_obj_exception_get_type(nlr.ret_val) == MP_QSTR_StopIteration) { 30 | // return mp_const_stop_iteration instead of raising StopIteration 31 | return mp_const_stop_iteration; 32 | } else { 33 | // re-raise exception 34 | nlr_jump(nlr.ret_val); 35 | } 36 | } 37 | } 38 | 39 | static const mp_obj_type_t it_type = { 40 | { &mp_const_type }, 41 | "iterator", 42 | .iternext = it_iternext 43 | }; 44 | 45 | // args are those returned from rt_load_method_maybe (ie either an attribute or a method) 46 | mp_obj_t mp_obj_new_getitem_iter(mp_obj_t *args) { 47 | mp_obj_getitem_iter_t *o = m_new_obj(mp_obj_getitem_iter_t); 48 | o->base.type = &it_type; 49 | o->args[0] = args[0]; 50 | o->args[1] = args[1]; 51 | o->args[2] = MP_OBJ_NEW_SMALL_INT(0); 52 | return o; 53 | } 54 | -------------------------------------------------------------------------------- /examples/conwaylife.py: -------------------------------------------------------------------------------- 1 | #import essential libraries 2 | import lcd 3 | import pyb 4 | 5 | # do 1 iteration of Conway's Game of Life 6 | def conway_step(): 7 | for x in range(128): # loop over x coordinates 8 | for y in range(32): # loop over y coordinates 9 | # count number of neigbours 10 | num_neighbours = (lcd.get(x - 1, y - 1) + 11 | lcd.get(x, y - 1) + 12 | lcd.get(x + 1, y - 1) + 13 | lcd.get(x - 1, y) + 14 | lcd.get(x + 1, y) + 15 | lcd.get(x + 1, y + 1) + 16 | lcd.get(x, y + 1) + 17 | lcd.get(x - 1, y + 1)) 18 | 19 | # check if the centre cell is alive or not 20 | self = lcd.get(x, y) 21 | 22 | # apply the rules of life 23 | if self and not (2 <= num_neighbours <= 3): 24 | lcd.reset(x, y) # not enough, or too many neighbours: cell dies 25 | elif not self and num_neighbours == 3: 26 | lcd.set(x, y) # exactly 3 neigbours around an empty cell: cell is born 27 | 28 | # randomise the start 29 | def conway_rand(): 30 | lcd.clear() # clear the LCD 31 | for x in range(128): # loop over x coordinates 32 | for y in range(32): # loop over y coordinates 33 | if pyb.rand() & 1: # get a 1-bit random number 34 | lcd.set(x, y) # set the pixel randomly 35 | 36 | # loop for a certain number of frames, doing iterations of Conway's Game of Life 37 | def conway_go(num_frames): 38 | for i in range(num_frames): 39 | conway_step() # do 1 iteration 40 | lcd.show() # update the LCD 41 | pyb.delay(300) 42 | 43 | # PC testing 44 | lcd = lcd.LCD(128, 32) 45 | conway_rand() 46 | conway_go(1000) 47 | -------------------------------------------------------------------------------- /py/objmap.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "nlr.h" 5 | #include "misc.h" 6 | #include "mpconfig.h" 7 | #include "qstr.h" 8 | #include "obj.h" 9 | #include "runtime.h" 10 | 11 | typedef struct _mp_obj_map_t { 12 | mp_obj_base_t base; 13 | machine_uint_t n_iters; 14 | mp_obj_t fun; 15 | mp_obj_t iters[]; 16 | } mp_obj_map_t; 17 | 18 | static mp_obj_t map_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { 19 | if (n_args < 2 || n_kw != 0) { 20 | nlr_jump(mp_obj_new_exception_msg(MP_QSTR_TypeError, "map must have at least 2 arguments and no keyword arguments")); 21 | } 22 | assert(n_args >= 2); 23 | mp_obj_map_t *o = m_new_obj_var(mp_obj_map_t, mp_obj_t, n_args - 1); 24 | o->base.type = &map_type; 25 | o->n_iters = n_args - 1; 26 | o->fun = args[0]; 27 | for (int i = 0; i < n_args - 1; i++) { 28 | o->iters[i] = rt_getiter(args[i + 1]); 29 | } 30 | return o; 31 | } 32 | 33 | static mp_obj_t map_getiter(mp_obj_t self_in) { 34 | return self_in; 35 | } 36 | 37 | static mp_obj_t map_iternext(mp_obj_t self_in) { 38 | assert(MP_OBJ_IS_TYPE(self_in, &map_type)); 39 | mp_obj_map_t *self = self_in; 40 | mp_obj_t *nextses = m_new(mp_obj_t, self->n_iters); 41 | 42 | for (int i = 0; i < self->n_iters; i++) { 43 | mp_obj_t next = rt_iternext(self->iters[i]); 44 | if (next == mp_const_stop_iteration) { 45 | m_del(mp_obj_t, nextses, self->n_iters); 46 | return mp_const_stop_iteration; 47 | } 48 | nextses[i] = next; 49 | } 50 | return rt_call_function_n_kw(self->fun, self->n_iters, 0, nextses); 51 | } 52 | 53 | const mp_obj_type_t map_type = { 54 | { &mp_const_type }, 55 | "map", 56 | .make_new = map_make_new, 57 | .getiter = map_getiter, 58 | .iternext = map_iternext, 59 | }; 60 | -------------------------------------------------------------------------------- /py/objclosure.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include "nlr.h" 7 | #include "misc.h" 8 | #include "mpconfig.h" 9 | #include "qstr.h" 10 | #include "obj.h" 11 | #include "runtime.h" 12 | 13 | typedef struct _mp_obj_closure_t { 14 | mp_obj_base_t base; 15 | mp_obj_t fun; 16 | uint n_closed; 17 | mp_obj_t *closed; 18 | } mp_obj_closure_t; 19 | 20 | mp_obj_t closure_call(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args) { 21 | mp_obj_closure_t *self = self_in; 22 | 23 | // need to concatenate closed-over-vars and args 24 | 25 | int n_total = self->n_closed + n_args + 2 * n_kw; 26 | if (n_total <= 5) { 27 | // use stack to allocate temporary args array 28 | mp_obj_t args2[5]; 29 | memcpy(args2, self->closed, self->n_closed * sizeof(mp_obj_t)); 30 | memcpy(args2 + self->n_closed, args, (n_args + 2 * n_kw) * sizeof(mp_obj_t)); 31 | return rt_call_function_n_kw(self->fun, self->n_closed + n_args, n_kw, args2); 32 | } else { 33 | // use heap to allocate temporary args array 34 | mp_obj_t *args2 = m_new(mp_obj_t, n_total); 35 | memcpy(args2, self->closed, self->n_closed * sizeof(mp_obj_t)); 36 | memcpy(args2 + self->n_closed, args, (n_args + 2 * n_kw) * sizeof(mp_obj_t)); 37 | mp_obj_t res = rt_call_function_n_kw(self->fun, self->n_closed + n_args, n_kw, args2); 38 | m_del(mp_obj_t, args2, n_total); 39 | return res; 40 | } 41 | } 42 | 43 | const mp_obj_type_t closure_type = { 44 | { &mp_const_type }, 45 | "closure", 46 | .call = closure_call, 47 | }; 48 | 49 | mp_obj_t mp_obj_new_closure(mp_obj_t fun, mp_obj_t closure_tuple) { 50 | mp_obj_closure_t *o = m_new_obj(mp_obj_closure_t); 51 | o->base.type = &closure_type; 52 | o->fun = fun; 53 | mp_obj_tuple_get(closure_tuple, &o->n_closed, &o->closed); 54 | return o; 55 | } 56 | -------------------------------------------------------------------------------- /py/objbool.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "nlr.h" 5 | #include "misc.h" 6 | #include "mpconfig.h" 7 | #include "qstr.h" 8 | #include "obj.h" 9 | #include "runtime0.h" 10 | #include "runtime.h" 11 | 12 | typedef struct _mp_obj_bool_t { 13 | mp_obj_base_t base; 14 | bool value; 15 | } mp_obj_bool_t; 16 | 17 | static void bool_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) { 18 | mp_obj_bool_t *self = self_in; 19 | if (self->value) { 20 | print(env, "True"); 21 | } else { 22 | print(env, "False"); 23 | } 24 | } 25 | 26 | static mp_obj_t bool_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { 27 | // TODO check n_kw == 0 28 | 29 | switch (n_args) { 30 | case 0: return mp_const_false; 31 | case 1: if (rt_is_true(args[0])) { return mp_const_true; } else { return mp_const_false; } 32 | default: nlr_jump(mp_obj_new_exception_msg_varg(MP_QSTR_TypeError, "bool takes at most 1 argument, %d given", n_args)); 33 | } 34 | } 35 | 36 | static mp_obj_t bool_unary_op(int op, mp_obj_t o_in) { 37 | machine_int_t value = ((mp_obj_bool_t*)o_in)->value; 38 | switch (op) { 39 | case RT_UNARY_OP_NOT: if (value) { return mp_const_false; } else { return mp_const_true; } 40 | case RT_UNARY_OP_POSITIVE: return MP_OBJ_NEW_SMALL_INT(value); 41 | case RT_UNARY_OP_NEGATIVE: return MP_OBJ_NEW_SMALL_INT(-value); 42 | case RT_UNARY_OP_INVERT: 43 | default: // no other cases 44 | return MP_OBJ_NEW_SMALL_INT(~value); 45 | } 46 | } 47 | 48 | const mp_obj_type_t bool_type = { 49 | { &mp_const_type }, 50 | "bool", 51 | .print = bool_print, 52 | .make_new = bool_make_new, 53 | .unary_op = bool_unary_op, 54 | }; 55 | 56 | static const mp_obj_bool_t false_obj = {{&bool_type}, false}; 57 | static const mp_obj_bool_t true_obj = {{&bool_type}, true}; 58 | 59 | const mp_obj_t mp_const_false = (mp_obj_t)&false_obj; 60 | const mp_obj_t mp_const_true = (mp_obj_t)&true_obj; 61 | -------------------------------------------------------------------------------- /stm/systick.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "misc.h" 3 | #include "systick.h" 4 | 5 | volatile uint32_t sys_tick_counter; 6 | 7 | void sys_tick_init(void) { 8 | // sys-tick interrupt called at 1ms intervals 9 | sys_tick_counter = 0; 10 | SysTick_Config(SystemCoreClock / 1000); 11 | NVIC_SetPriority(SysTick_IRQn, 0); // make it highest priority 12 | } 13 | 14 | // called on SysTick interrupt 15 | void SysTick_Handler(void) { 16 | sys_tick_counter++; 17 | // hack! 18 | //void audio_drain(void); 19 | //audio_drain(); 20 | } 21 | 22 | void sys_tick_delay_ms(uint32_t delay_ms) { 23 | sys_tick_wait_at_least(sys_tick_counter, delay_ms); 24 | } 25 | 26 | // waits until at least delay_ms milliseconds have passed from the sampling of sys_tick_counter in stc 27 | // handles overflow properl 28 | // assumes stc was taken from sys_tick_counter some time before calling this function 29 | // eg stc <= sys_tick_counter for the case of no wrap around of sys_tick_counter 30 | void sys_tick_wait_at_least(uint32_t stc, uint32_t delay_ms) { 31 | // stc_wait is the value of sys_tick_counter that we wait for 32 | uint32_t stc_wait = stc + delay_ms; 33 | if (stc_wait < stc) { 34 | // stc_wait wrapped around 35 | while (stc <= sys_tick_counter || sys_tick_counter < stc_wait) { 36 | __WFI(); // enter sleep mode, waiting for interrupt 37 | } 38 | } else { 39 | // stc_wait did not wrap around 40 | while (stc <= sys_tick_counter && sys_tick_counter < stc_wait) { 41 | __WFI(); // enter sleep mode, waiting for interrupt 42 | } 43 | } 44 | } 45 | 46 | bool sys_tick_has_passed(uint32_t stc, uint32_t delay_ms) { 47 | // stc_wait is the value of sys_tick_counter that we wait for 48 | uint32_t stc_wait = stc + delay_ms; 49 | if (stc_wait < stc) { 50 | // stc_wait wrapped around 51 | return !(stc <= sys_tick_counter || sys_tick_counter < stc_wait); 52 | } else { 53 | // stc_wait did not wrap around 54 | return !(stc <= sys_tick_counter && sys_tick_counter < stc_wait); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /teensy/led.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "misc.h" 4 | #include "mpconfig.h" 5 | #include "obj.h" 6 | #include "led.h" 7 | 8 | #include "Arduino.h" 9 | 10 | void led_init(void) { 11 | } 12 | 13 | void led_state(pyb_led_t led, int state) { 14 | uint8_t pin; 15 | 16 | if (led == 0) { 17 | pin = LED_BUILTIN; 18 | } else { 19 | return; 20 | } 21 | digitalWrite(pin, state); 22 | } 23 | 24 | void led_toggle(pyb_led_t led) { 25 | uint8_t pin; 26 | 27 | if (led == 0) { 28 | pin = LED_BUILTIN; 29 | } else { 30 | return; 31 | } 32 | 33 | digitalWrite(pin, !digitalRead(pin)); 34 | } 35 | 36 | /******************************************************************************/ 37 | /* Micro Python bindings */ 38 | 39 | typedef struct _pyb_led_obj_t { 40 | mp_obj_base_t base; 41 | uint led_id; 42 | } pyb_led_obj_t; 43 | 44 | void led_obj_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in) { 45 | pyb_led_obj_t *self = self_in; 46 | print(env, "", self->led_id); 47 | } 48 | 49 | mp_obj_t led_obj_on(mp_obj_t self_in) { 50 | pyb_led_obj_t *self = self_in; 51 | led_state(self->led_id, 1); 52 | return mp_const_none; 53 | } 54 | 55 | mp_obj_t led_obj_off(mp_obj_t self_in) { 56 | pyb_led_obj_t *self = self_in; 57 | led_state(self->led_id, 0); 58 | return mp_const_none; 59 | } 60 | 61 | static MP_DEFINE_CONST_FUN_OBJ_1(led_obj_on_obj, led_obj_on); 62 | static MP_DEFINE_CONST_FUN_OBJ_1(led_obj_off_obj, led_obj_off); 63 | 64 | static const mp_method_t led_methods[] = { 65 | { "on", &led_obj_on_obj }, 66 | { "off", &led_obj_off_obj }, 67 | { NULL, NULL }, 68 | }; 69 | 70 | static const mp_obj_type_t led_obj_type = { 71 | { &mp_const_type }, 72 | "Led", 73 | .print = led_obj_print, 74 | .methods = led_methods, 75 | }; 76 | 77 | mp_obj_t pyb_Led(mp_obj_t led_id) { 78 | pyb_led_obj_t *o = m_new_obj(pyb_led_obj_t); 79 | o->base.type = &led_obj_type; 80 | o->led_id = mp_obj_get_int(led_id); 81 | return o; 82 | } 83 | -------------------------------------------------------------------------------- /tests/bytecode/pylib-tests/crypt.py: -------------------------------------------------------------------------------- 1 | """Wrapper to the POSIX crypt library call and associated functionality.""" 2 | 3 | import _crypt 4 | import string as _string 5 | from random import SystemRandom as _SystemRandom 6 | from collections import namedtuple as _namedtuple 7 | 8 | 9 | _saltchars = _string.ascii_letters + _string.digits + './' 10 | _sr = _SystemRandom() 11 | 12 | 13 | class _Method(_namedtuple('_Method', 'name ident salt_chars total_size')): 14 | 15 | """Class representing a salt method per the Modular Crypt Format or the 16 | legacy 2-character crypt method.""" 17 | 18 | def __repr__(self): 19 | return ''.format(self.name) 20 | 21 | 22 | def mksalt(method=None): 23 | """Generate a salt for the specified method. 24 | 25 | If not specified, the strongest available method will be used. 26 | 27 | """ 28 | if method is None: 29 | method = methods[0] 30 | s = '${}$'.format(method.ident) if method.ident else '' 31 | s += ''.join(_sr.sample(_saltchars, method.salt_chars)) 32 | return s 33 | 34 | 35 | def crypt(word, salt=None): 36 | """Return a string representing the one-way hash of a password, with a salt 37 | prepended. 38 | 39 | If ``salt`` is not specified or is ``None``, the strongest 40 | available method will be selected and a salt generated. Otherwise, 41 | ``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as 42 | returned by ``crypt.mksalt()``. 43 | 44 | """ 45 | if salt is None or isinstance(salt, _Method): 46 | salt = mksalt(salt) 47 | return _crypt.crypt(word, salt) 48 | 49 | 50 | # available salting/crypto methods 51 | METHOD_CRYPT = _Method('CRYPT', None, 2, 13) 52 | METHOD_MD5 = _Method('MD5', '1', 8, 34) 53 | METHOD_SHA256 = _Method('SHA256', '5', 16, 63) 54 | METHOD_SHA512 = _Method('SHA512', '6', 16, 106) 55 | 56 | methods = [] 57 | for _method in (METHOD_SHA512, METHOD_SHA256, METHOD_MD5): 58 | _result = crypt('', _method) 59 | if _result and len(_result) == _method.total_size: 60 | methods.append(_method) 61 | methods.append(METHOD_CRYPT) 62 | del _result, _method 63 | -------------------------------------------------------------------------------- /stm/stmusbd/usbd_cdc_vcp.h: -------------------------------------------------------------------------------- 1 | /** 2 | ****************************************************************************** 3 | * @file usbd_cdc_vcp.h 4 | * @author MCD Application Team 5 | * @version V1.1.0 6 | * @date 19-March-2012 7 | * @brief Header for usbd_cdc_vcp.c file. 8 | ****************************************************************************** 9 | * @attention 10 | * 11 | *

© COPYRIGHT 2012 STMicroelectronics

12 | * 13 | * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); 14 | * You may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at: 16 | * 17 | * http://www.st.com/software_license_agreement_liberty_v2 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | ****************************************************************************** 26 | */ 27 | 28 | /* Define to prevent recursive inclusion -------------------------------------*/ 29 | #ifndef __USBD_CDC_VCP_H 30 | #define __USBD_CDC_VCP_H 31 | 32 | #include "usbd_cdc_core.h" 33 | #include "usbd_conf.h" 34 | 35 | /* Exported typef ------------------------------------------------------------*/ 36 | /* The following structures groups all needed parameters to be configured for the 37 | ComPort. These parameters can modified on the fly by the host through CDC class 38 | command class requests. */ 39 | typedef struct 40 | { 41 | uint32_t bitrate; 42 | uint8_t format; 43 | uint8_t paritytype; 44 | uint8_t datatype; 45 | } LINE_CODING; 46 | 47 | #define DEFAULT_CONFIG 0 48 | #define OTHER_CONFIG 1 49 | 50 | #endif /* __USBD_CDC_VCP_H */ 51 | 52 | /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ 53 | -------------------------------------------------------------------------------- /unix-cpy/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "nlr.h" 6 | #include "misc.h" 7 | #include "mpconfig.h" 8 | #include "qstr.h" 9 | #include "lexer.h" 10 | #include "lexerunix.h" 11 | #include "parse.h" 12 | #include "obj.h" 13 | #include "compile.h" 14 | #include "runtime0.h" 15 | 16 | void do_file(const char *file) { 17 | mp_lexer_t *lex = mp_lexer_new_from_file(file); 18 | if (lex == NULL) { 19 | return; 20 | } 21 | 22 | if (0) { 23 | // just tokenise 24 | while (!mp_lexer_is_kind(lex, MP_TOKEN_END)) { 25 | mp_token_show(mp_lexer_cur(lex)); 26 | mp_lexer_to_next(lex); 27 | } 28 | mp_lexer_free(lex); 29 | 30 | } else { 31 | // parse 32 | qstr parse_exc_id; 33 | const char *parse_exc_msg; 34 | mp_parse_node_t pn = mp_parse(lex, MP_PARSE_FILE_INPUT, &parse_exc_id, &parse_exc_msg); 35 | 36 | if (pn == MP_PARSE_NODE_NULL) { 37 | // parse error 38 | mp_lexer_show_error_pythonic_prefix(lex); 39 | printf("%s: %s\n", qstr_str(parse_exc_id), parse_exc_msg); 40 | mp_lexer_free(lex); 41 | return; 42 | } 43 | 44 | mp_lexer_free(lex); 45 | 46 | if (pn != MP_PARSE_NODE_NULL) { 47 | //printf("----------------\n"); 48 | //mp_parse_node_print(pn, 0); 49 | //printf("----------------\n"); 50 | 51 | // compile 52 | mp_obj_t module_fun = mp_compile(pn, 0, false); 53 | 54 | //printf("----------------\n"); 55 | 56 | if (module_fun == mp_const_none) { 57 | printf("compile error\n"); 58 | } 59 | } 60 | } 61 | } 62 | 63 | int main(int argc, char **argv) { 64 | qstr_init(); 65 | rt_init(); 66 | 67 | if (argc == 2) { 68 | do_file(argv[1]); 69 | } else { 70 | printf("usage: py []\n"); 71 | return 1; 72 | } 73 | rt_deinit(); 74 | 75 | return 0; 76 | } 77 | 78 | // for sqrt 79 | #include 80 | machine_float_t machine_sqrt(machine_float_t x) { 81 | return sqrt(x); 82 | } 83 | -------------------------------------------------------------------------------- /stm/cc3k/host_driver_version.h: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | * 3 | * host_driver_version.h - CC3000 Host Driver Implementation. 4 | * Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 10 | * Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 13 | * Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the 16 | * distribution. 17 | * 18 | * Neither the name of Texas Instruments Incorporated nor the names of 19 | * its contributors may be used to endorse or promote products derived 20 | * from this software without specific prior written permission. 21 | * 22 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 23 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 24 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 25 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 26 | * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 27 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 28 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 32 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 | * 34 | *****************************************************************************/ 35 | #ifndef __HOST_DRIVER_VERSION_H__ 36 | #define __HOST_DRIVER_VERSION_H__ 37 | 38 | #define DRIVER_VERSION_NUMBER 13 39 | 40 | 41 | 42 | #endif // __VERSION_H__ 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /teensy/memzip.h: -------------------------------------------------------------------------------- 1 | #pragma pack(push, 1) 2 | 3 | #define MEMZIP_FILE_HEADER_SIGNATURE 0x04034b50 4 | typedef struct 5 | { 6 | uint32_t signature; 7 | uint16_t version; 8 | uint16_t flags; 9 | uint16_t compression_method; 10 | uint16_t last_mod_time; 11 | uint16_t last_mod_date; 12 | uint32_t crc32; 13 | uint32_t compressed_size; 14 | uint32_t uncompressed_size; 15 | uint16_t filename_len; 16 | uint16_t extra_len; 17 | 18 | /* char filename[filename_len] */ 19 | /* uint8_t extra[extra_len] */ 20 | 21 | } MEMZIP_FILE_HDR; 22 | 23 | #define MEMZIP_CENTRAL_DIRECTORY_SIGNATURE 0x02014b50 24 | typedef struct 25 | { 26 | uint32_t signature; 27 | uint16_t version_made_by; 28 | uint16_t version_read_with; 29 | uint16_t flags; 30 | uint16_t compression_method; 31 | uint16_t last_mod_time; 32 | uint16_t last_mod_date; 33 | uint32_t crc32; 34 | uint32_t compressed_size; 35 | uint32_t uncompressed_size; 36 | uint16_t filename_len; 37 | uint16_t extra_len; 38 | uint16_t disk_num; 39 | uint16_t internal_file_attributes; 40 | uint32_t external_file_attributes; 41 | uint32_t file_header_offset; 42 | 43 | /* char filename[filename_len] */ 44 | /* uint8_t extra[extra_len] */ 45 | 46 | } MEMZIP_CENTRAL_DIRECTORY_HDR; 47 | 48 | #define MEMZIP_END_OF_CENTRAL_DIRECTORY_SIGNATURE 0x06054b50 49 | typedef struct 50 | { 51 | uint32_t signature; 52 | uint16_t disk_num; 53 | uint16_t central_directory_disk; 54 | uint16_t num_central_directories_this_disk; 55 | uint16_t total_central_directories; 56 | uint32_t central_directory_size; 57 | uint32_t central_directory_offset; 58 | uint16_t comment_len; 59 | 60 | /* char comment[comment_len] */ 61 | 62 | } MEMZIP_END_OF_CENTRAL_DIRECTORY; 63 | 64 | #pragma pack(pop) 65 | 66 | typedef enum { 67 | MZ_OK = 0, /* (0) Succeeded */ 68 | MZ_NO_FILE, /* (1) Could not find the file. */ 69 | MZ_FILE_COMPRESSED, /* (2) File is compressed (expecting uncompressed) */ 70 | 71 | } MEMZIP_RESULT; 72 | 73 | MEMZIP_RESULT memzip_locate(const char *filename, void **data, size_t *len); 74 | -------------------------------------------------------------------------------- /stm/stm32fxxx_it.h: -------------------------------------------------------------------------------- 1 | /** 2 | ****************************************************************************** 3 | * @file stm32fxxx_it.h 4 | * @author MCD Application Team 5 | * @version V1.1.0 6 | * @date 19-March-2012 7 | * @brief This file contains the headers of the interrupt handlers. 8 | ****************************************************************************** 9 | * @attention 10 | * 11 | *

© COPYRIGHT 2012 STMicroelectronics

12 | * 13 | * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); 14 | * You may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at: 16 | * 17 | * http://www.st.com/software_license_agreement_liberty_v2 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | ****************************************************************************** 26 | */ 27 | 28 | /* Define to prevent recursive inclusion -------------------------------------*/ 29 | #ifndef __STM32Fxxx_IT_H 30 | #define __STM32Fxxx_IT_H 31 | 32 | #ifdef __cplusplus 33 | extern "C" { 34 | #endif 35 | 36 | /* Includes ------------------------------------------------------------------*/ 37 | #include "usb_conf.h" 38 | 39 | /* Exported types ------------------------------------------------------------*/ 40 | /* Exported constants --------------------------------------------------------*/ 41 | /* Exported macro ------------------------------------------------------------*/ 42 | /* Exported functions ------------------------------------------------------- */ 43 | 44 | void NMI_Handler(void); 45 | void HardFault_Handler(void); 46 | void MemManage_Handler(void); 47 | void BusFault_Handler(void); 48 | void UsageFault_Handler(void); 49 | void SVC_Handler(void); 50 | void DebugMon_Handler(void); 51 | void PendSV_Handler(void); 52 | 53 | #ifdef __cplusplus 54 | } 55 | #endif 56 | 57 | #endif /* __STM32Fxxx_IT_H */ 58 | 59 | /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ 60 | -------------------------------------------------------------------------------- /py/objrange.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "nlr.h" 5 | #include "misc.h" 6 | #include "mpconfig.h" 7 | #include "qstr.h" 8 | #include "obj.h" 9 | 10 | /******************************************************************************/ 11 | /* range */ 12 | 13 | typedef struct _mp_obj_range_t { 14 | mp_obj_base_t base; 15 | // TODO make these values generic objects or something 16 | machine_int_t start; 17 | machine_int_t stop; 18 | machine_int_t step; 19 | } mp_obj_range_t; 20 | 21 | mp_obj_t range_getiter(mp_obj_t o_in) { 22 | mp_obj_range_t *o = o_in; 23 | return mp_obj_new_range_iterator(o->start, o->stop, o->step); 24 | } 25 | 26 | static const mp_obj_type_t range_type = { 27 | { &mp_const_type} , 28 | "range", 29 | .getiter = range_getiter, 30 | }; 31 | 32 | // range is a class and instances are immutable sequence objects 33 | mp_obj_t mp_obj_new_range(int start, int stop, int step) { 34 | mp_obj_range_t *o = m_new_obj(mp_obj_range_t); 35 | o->base.type = &range_type; 36 | o->start = start; 37 | o->stop = stop; 38 | o->step = step; 39 | return o; 40 | } 41 | 42 | /******************************************************************************/ 43 | /* range iterator */ 44 | 45 | typedef struct _mp_obj_range_it_t { 46 | mp_obj_base_t base; 47 | // TODO make these values generic objects or something 48 | machine_int_t cur; 49 | machine_int_t stop; 50 | machine_int_t step; 51 | } mp_obj_range_it_t; 52 | 53 | mp_obj_t range_it_iternext(mp_obj_t o_in) { 54 | mp_obj_range_it_t *o = o_in; 55 | if ((o->step > 0 && o->cur < o->stop) || (o->step < 0 && o->cur > o->stop)) { 56 | mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(o->cur); 57 | o->cur += o->step; 58 | return o_out; 59 | } else { 60 | return mp_const_stop_iteration; 61 | } 62 | } 63 | 64 | static const mp_obj_type_t range_it_type = { 65 | { &mp_const_type }, 66 | "range_iterator", 67 | .iternext = range_it_iternext, 68 | }; 69 | 70 | mp_obj_t mp_obj_new_range_iterator(int cur, int stop, int step) { 71 | mp_obj_range_it_t *o = m_new_obj(mp_obj_range_it_t); 72 | o->base.type = &range_it_type; 73 | o->cur = cur; 74 | o->stop = stop; 75 | o->step = step; 76 | return o; 77 | } 78 | -------------------------------------------------------------------------------- /tests/bytecode/pylib-tests/keyword.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | 3 | """Keywords (from "graminit.c") 4 | 5 | This file is automatically generated; please don't muck it up! 6 | 7 | To update the symbols in this file, 'cd' to the top directory of 8 | the python source tree after building the interpreter and run: 9 | 10 | ./python Lib/keyword.py 11 | """ 12 | 13 | __all__ = ["iskeyword", "kwlist"] 14 | 15 | kwlist = [ 16 | #--start keywords-- 17 | 'False', 18 | 'None', 19 | 'True', 20 | 'and', 21 | 'as', 22 | 'assert', 23 | 'break', 24 | 'class', 25 | 'continue', 26 | 'def', 27 | 'del', 28 | 'elif', 29 | 'else', 30 | 'except', 31 | 'finally', 32 | 'for', 33 | 'from', 34 | 'global', 35 | 'if', 36 | 'import', 37 | 'in', 38 | 'is', 39 | 'lambda', 40 | 'nonlocal', 41 | 'not', 42 | 'or', 43 | 'pass', 44 | 'raise', 45 | 'return', 46 | 'try', 47 | 'while', 48 | 'with', 49 | 'yield', 50 | #--end keywords-- 51 | ] 52 | 53 | iskeyword = frozenset(kwlist).__contains__ 54 | 55 | def main(): 56 | import sys, re 57 | 58 | args = sys.argv[1:] 59 | iptfile = args and args[0] or "Python/graminit.c" 60 | if len(args) > 1: optfile = args[1] 61 | else: optfile = "Lib/keyword.py" 62 | 63 | # scan the source file for keywords 64 | with open(iptfile) as fp: 65 | strprog = re.compile('"([^"]+)"') 66 | lines = [] 67 | for line in fp: 68 | if '{1, "' in line: 69 | match = strprog.search(line) 70 | if match: 71 | lines.append(" '" + match.group(1) + "',\n") 72 | lines.sort() 73 | 74 | # load the output skeleton from the target 75 | with open(optfile) as fp: 76 | format = fp.readlines() 77 | 78 | # insert the lines of keywords 79 | try: 80 | start = format.index("#--start keywords--\n") + 1 81 | end = format.index("#--end keywords--\n") 82 | format[start:end] = lines 83 | except ValueError: 84 | sys.stderr.write("target does not contain format markers\n") 85 | sys.exit(1) 86 | 87 | # write the output file 88 | fp = open(optfile, 'w') 89 | fp.write(''.join(format)) 90 | fp.close() 91 | 92 | if __name__ == "__main__": 93 | main() 94 | -------------------------------------------------------------------------------- /tests/bytecode/check.py: -------------------------------------------------------------------------------- 1 | import sys 2 | name = sys.argv[1].split('/')[-1].split('.')[0] 3 | with open(sys.argv[1]) as f: 4 | lines_correct = [l.strip('\n') for l in f.readlines()] 5 | lines_me = [l.strip('\n') for l in sys.stdin.readlines()] 6 | if len(lines_me) != len(lines_correct): 7 | if len(lines_me) == 0: 8 | print('{:<20}: no output'.format(name)) 9 | elif lines_me[0].find('syntax error') >= 0: 10 | print('{:<20}: syntax error'.format(name)) 11 | elif lines_me[0].find(' cannot be compiled') >= 0: 12 | print('{:<20}: compile error: {}'.format(name, lines_me[0])) 13 | else: 14 | print('{:<20}: mismatch in number of lines'.format(name)) 15 | else: 16 | total = len(lines_me) 17 | same = 0 18 | bad_num_fields = 0 19 | bad_2 = 0 20 | bad_3 = 0 21 | jump_op = ['JUMP_FORWARD', 'JUMP_ABSOLUTE', 'POP_JUMP_IF_FALSE', 'POP_JUMP_IF_TRUE', 'SETUP_LOOP'] 22 | jump_abs_op = ['JUMP_FORWARD', 'JUMP_ABSOLUTE'] 23 | for i in range(total): 24 | if lines_me[i] == lines_correct[i]: 25 | same += 1 26 | else: 27 | # line is different 28 | line_me = lines_me[i].strip().split(' ', 2) 29 | line_correct = lines_correct[i].strip().split(' ', 2) 30 | allow = False 31 | if len(line_me) != len(line_correct): 32 | bad_num_fields += 1 33 | elif len(line_me) == 2: 34 | if line_me[0] == line_correct[0] == 'stacksize': 35 | allow = True 36 | else: 37 | bad_2 += 1 38 | else: 39 | assert(len(line_me) == 3) 40 | if line_me[0] == line_correct[0] and line_me[1] in jump_abs_op and line_correct[1] in jump_abs_op: 41 | allow = True 42 | elif line_me[0] == line_correct[0] and line_me[1] == line_correct[1] in jump_op: 43 | allow = True 44 | else: 45 | bad_3 += 1 46 | #if not allow: 47 | # print(line_me, 'vs', line_correct) 48 | 49 | bad_str = '' 50 | if bad_num_fields > 0: 51 | bad_str += ', {} bad num fields'.format(bad_num_fields) 52 | if bad_2 > 0: 53 | bad_str += ', {} bad 2-field'.format(bad_2) 54 | if bad_3 > 0: 55 | bad_str += ', {} bad 3-field'.format(bad_3) 56 | print('{:<20}: {:>6} lines, {:>5.1f}% correct{}'.format(name, total, 100 * same / total, bad_str)) 57 | -------------------------------------------------------------------------------- /py/runtime.h: -------------------------------------------------------------------------------- 1 | int rt_is_true(mp_obj_t arg); 2 | 3 | mp_obj_t rt_load_const_dec(qstr qstr); 4 | mp_obj_t rt_load_const_str(qstr qstr); 5 | mp_obj_t rt_load_const_bytes(qstr qstr); 6 | mp_obj_t rt_load_name(qstr qstr); 7 | mp_obj_t rt_load_global(qstr qstr); 8 | mp_obj_t rt_load_build_class(void); 9 | mp_obj_t rt_get_cell(mp_obj_t cell); 10 | void rt_set_cell(mp_obj_t cell, mp_obj_t val); 11 | void rt_store_name(qstr qstr, mp_obj_t obj); 12 | void rt_store_global(qstr qstr, mp_obj_t obj); 13 | mp_obj_t rt_unary_op(int op, mp_obj_t arg); 14 | mp_obj_t rt_binary_op(int op, mp_obj_t lhs, mp_obj_t rhs); 15 | mp_obj_t rt_make_function_from_id(int unique_code_id); 16 | mp_obj_t rt_make_function_n(int n_args, void *fun); // fun must have the correct signature for n_args fixed arguments 17 | mp_obj_t rt_make_function_var(int n_args_min, mp_fun_var_t fun); 18 | mp_obj_t rt_make_function_var_between(int n_args_min, int n_args_max, mp_fun_var_t fun); // min and max are inclusive 19 | mp_obj_t rt_make_closure_from_id(int unique_code_id, mp_obj_t closure_tuple); 20 | mp_obj_t rt_call_function_0(mp_obj_t fun); 21 | mp_obj_t rt_call_function_1(mp_obj_t fun, mp_obj_t arg); 22 | mp_obj_t rt_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2); 23 | mp_obj_t rt_call_function_n_kw(mp_obj_t fun, uint n_args, uint n_kw, const mp_obj_t *args); 24 | mp_obj_t rt_call_method_n_kw(uint n_args, uint n_kw, const mp_obj_t *args); 25 | mp_obj_t rt_build_tuple(int n_args, mp_obj_t *items); 26 | mp_obj_t rt_build_list(int n_args, mp_obj_t *items); 27 | mp_obj_t rt_list_append(mp_obj_t list, mp_obj_t arg); 28 | mp_obj_t rt_build_set(int n_args, mp_obj_t *items); 29 | mp_obj_t rt_store_set(mp_obj_t set, mp_obj_t item); 30 | void rt_unpack_sequence(mp_obj_t seq, uint num, mp_obj_t *items); 31 | mp_obj_t rt_build_map(int n_args); 32 | mp_obj_t rt_store_map(mp_obj_t map, mp_obj_t key, mp_obj_t value); 33 | mp_obj_t rt_load_attr(mp_obj_t base, qstr attr); 34 | void rt_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest); 35 | void rt_store_attr(mp_obj_t base, qstr attr, mp_obj_t val); 36 | void rt_store_subscr(mp_obj_t base, mp_obj_t index, mp_obj_t val); 37 | mp_obj_t rt_getiter(mp_obj_t o); 38 | mp_obj_t rt_iternext(mp_obj_t o); 39 | mp_obj_t rt_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level); 40 | mp_obj_t rt_import_from(mp_obj_t module, qstr name); 41 | 42 | struct _mp_map_t; 43 | struct _mp_map_t *rt_locals_get(void); 44 | void rt_locals_set(struct _mp_map_t *m); 45 | struct _mp_map_t *rt_globals_get(void); 46 | void rt_globals_set(struct _mp_map_t *m); 47 | struct _mp_map_t *rt_loaded_modules_get(void); 48 | -------------------------------------------------------------------------------- /py/nlrx86.S: -------------------------------------------------------------------------------- 1 | #ifdef __i386__ 2 | /* x86 callee save: bx, di, si, bp, sp */ 3 | 4 | .file "nlr.s" 5 | .text 6 | 7 | /* uint nlr_push(4(%esp)=nlr_buf_t *nlr) */ 8 | .globl nlr_push 9 | .type nlr_push, @function 10 | nlr_push: 11 | mov 4(%esp), %edx # load nlr_buf 12 | mov (%esp), %eax # load return %ip 13 | mov %eax, 8(%edx) # store %ip into nlr_buf+8 14 | mov %ebp, 12(%edx) # store %bp into nlr_buf+12 15 | mov %esp, 16(%edx) # store %sp into nlr_buf+16 16 | mov %ebx, 20(%edx) # store %bx into nlr_buf+20 17 | mov %edi, 24(%edx) # store %di into nlr_buf 18 | mov %esi, 28(%edx) # store %si into nlr_buf 19 | mov nlr_top, %eax # load nlr_top 20 | mov %eax, (%edx) # store it 21 | mov %edx, nlr_top # stor new nlr_buf (to make linked list) 22 | xor %eax, %eax # return 0, normal return 23 | ret # return 24 | .size nlr_push, .-nlr_push 25 | 26 | /* void nlr_pop() */ 27 | .globl nlr_pop 28 | .type nlr_pop, @function 29 | nlr_pop: 30 | mov nlr_top, %eax # load nlr_top 31 | mov (%eax), %eax # load prev nlr_buf 32 | mov %eax, nlr_top # store nlr_top (to unlink list) 33 | ret # return 34 | .size nlr_pop, .-nlr_pop 35 | 36 | /* void nlr_jump(4(%esp)=uint val) */ 37 | .globl nlr_jump 38 | .type nlr_jump, @function 39 | nlr_jump: 40 | mov nlr_top, %edx # load nlr_top 41 | mov 4(%esp), %eax # load return value 42 | mov %eax, 4(%edx) # store return value 43 | mov (%edx), %eax # load prev nlr_top 44 | mov %eax, nlr_top # store nlr_top (to unlink list) 45 | mov 28(%edx), %esi # load saved %si 46 | mov 24(%edx), %edi # load saved %di 47 | mov 20(%edx), %ebx # load saved %bx 48 | mov 16(%edx), %esp # load saved %sp 49 | mov 12(%edx), %ebp # load saved %bp 50 | mov 8(%edx), %eax # load saved %ip 51 | mov %eax, (%esp) # store saved %ip to stack 52 | xor %eax, %eax # clear return register 53 | inc %al # increase to make 1, non-local return 54 | ret # return 55 | .size nlr_jump, .-nlr_jump 56 | 57 | .local nlr_top 58 | .comm nlr_top,4,4 59 | #endif 60 | -------------------------------------------------------------------------------- /py/unicode.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "misc.h" 4 | 5 | // attribute flags 6 | #define FL_PRINT (0x01) 7 | #define FL_SPACE (0x02) 8 | #define FL_DIGIT (0x04) 9 | #define FL_ALPHA (0x08) 10 | #define FL_UPPER (0x10) 11 | #define FL_LOWER (0x20) 12 | 13 | // shorthand character attributes 14 | #define AT_PR (FL_PRINT) 15 | #define AT_SP (FL_SPACE | FL_PRINT) 16 | #define AT_DI (FL_DIGIT | FL_PRINT) 17 | #define AT_AL (FL_ALPHA | FL_PRINT) 18 | #define AT_UP (FL_UPPER | FL_ALPHA | FL_PRINT) 19 | #define AT_LO (FL_LOWER | FL_ALPHA | FL_PRINT) 20 | 21 | // table of attributes for ascii characters 22 | static const uint8_t attr[] = { 23 | 0, 0, 0, 0, 0, 0, 0, 0, 24 | 0, AT_SP, AT_SP, AT_SP, 0, AT_SP, 0, 0, 25 | 0, 0, 0, 0, 0, 0, 0, 0, 26 | 0, 0, 0, 0, 0, 0, 0, 0, 27 | AT_SP, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, 28 | AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, 29 | AT_DI, AT_DI, AT_DI, AT_DI, AT_DI, AT_DI, AT_DI, AT_DI, 30 | AT_DI, AT_DI, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, 31 | AT_PR, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, 32 | AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, 33 | AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, 34 | AT_UP, AT_UP, AT_UP, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, 35 | AT_PR, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, 36 | AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, 37 | AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, 38 | AT_LO, AT_LO, AT_LO, AT_PR, AT_PR, AT_PR, AT_PR, 0 39 | }; 40 | 41 | unichar utf8_get_char(const char *s) { 42 | return *s; 43 | } 44 | 45 | char *utf8_next_char(const char *s) { 46 | return (char*)(s + 1); 47 | } 48 | 49 | bool unichar_isspace(unichar c) { 50 | return c < 128 && (attr[c] & FL_SPACE) != 0; 51 | } 52 | 53 | bool unichar_isalpha(unichar c) { 54 | return c < 128 && (attr[c] & FL_ALPHA) != 0; 55 | } 56 | 57 | bool unichar_isprint(unichar c) { 58 | return c < 128 && (attr[c] & FL_PRINT) != 0; 59 | } 60 | 61 | bool unichar_isdigit(unichar c) { 62 | return c < 128 && (attr[c] & FL_DIGIT) != 0; 63 | } 64 | 65 | bool unichar_isxdigit(unichar c) { 66 | return unichar_isdigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); 67 | } 68 | 69 | /* 70 | bool char_is_alpha_or_digit(unichar c) { 71 | return c < 128 && (attr[c] & (FL_ALPHA | FL_DIGIT)) != 0; 72 | } 73 | 74 | bool char_is_upper(unichar c) { 75 | return c < 128 && (attr[c] & FL_UPPER) != 0; 76 | } 77 | 78 | bool char_is_lower(unichar c) { 79 | return c < 128 && (attr[c] & FL_LOWER) != 0; 80 | } 81 | */ 82 | -------------------------------------------------------------------------------- /teensy/Makefile: -------------------------------------------------------------------------------- 1 | include ../py/mkenv.mk 2 | 3 | # include py core make definitions 4 | include ../py/py.mk 5 | 6 | ifeq ($(ARDUINO),) 7 | $(error Please define ARDUINO (where TeensyDuino is installed)) 8 | endif 9 | TOOLS_PATH = $(ARDUINO)/hardware/tools 10 | COMPILER_PATH = $(TOOLS_PATH)/arm-none-eabi/bin 11 | CORE_PATH = $(ARDUINO)/hardware/teensy/cores/teensy3 12 | 13 | CROSS_COMPILE = $(COMPILER_PATH)/arm-none-eabi- 14 | 15 | CFLAGS_TEENSY = -DF_CPU=96000000 -DUSB_SERIAL -D__MK20DX256__ 16 | CFLAGS_CORTEX_M4 = -mthumb -mtune=cortex-m4 -mcpu=cortex-m4 -fsingle-precision-constant -Wdouble-promotion $(CFLAGS_TEENSY) 17 | CFLAGS = -I. -I$(PY_SRC) -I$(CORE_PATH) -Wall -ansi -std=gnu99 $(CFLAGS_CORTEX_M4) 18 | LDFLAGS = -nostdlib -T mk20dx256.ld 19 | LIBS = -L $(COMPILER_PATH)/../lib/gcc/arm-none-eabi/4.7.2/thumb2 -lgcc 20 | 21 | #Debugging/Optimization 22 | ifdef DEBUG 23 | CFLAGS += -Og -ggdb 24 | else 25 | CFLAGS += -Os #-DNDEBUG 26 | endif 27 | 28 | SRC_C = \ 29 | main.c \ 30 | lcd.c \ 31 | led.c \ 32 | lexerfatfs.c \ 33 | lexermemzip.c \ 34 | memzip.c \ 35 | usb.c \ 36 | 37 | STM_SRC_C = $(addprefix stm/,\ 38 | malloc0.c \ 39 | printf.c \ 40 | string0.c \ 41 | ) 42 | 43 | STM_SRC_S = $(addprefix stm/,\ 44 | gchelper.s \ 45 | ) 46 | 47 | SRC_TEENSY = \ 48 | mk20dx128.c \ 49 | pins_teensy.c \ 50 | analog.c \ 51 | usb_desc.c \ 52 | usb_dev.c \ 53 | usb_mem.c \ 54 | usb_serial.c \ 55 | yield.c \ 56 | 57 | OBJ = $(addprefix $(BUILD)/, $(SRC_C:.c=.o) $(STM_SRC_C:.c=.o) $(STM_SRC_S:.s=.o) $(SRC_TEENSY:.c=.o)) $(PY_O) 58 | #LIB = -lreadline 59 | # the following is needed for BSD 60 | #LIB += -ltermcap 61 | 62 | all: hex 63 | hex: $(BUILD)/micropython-mz.hex 64 | 65 | post_compile: $(BUILD)/micropython-mz.hex 66 | $(ECHO) "Preparing $@ for upload" 67 | $(Q)$(TOOLS_PATH)/teensy_post_compile -file="$(basename $(BINARY 35 | RT_COMPARE_OP_LESS, 36 | RT_COMPARE_OP_MORE, 37 | RT_COMPARE_OP_EQUAL, 38 | RT_COMPARE_OP_LESS_EQUAL, 39 | RT_COMPARE_OP_MORE_EQUAL, 40 | RT_COMPARE_OP_NOT_EQUAL, 41 | RT_COMPARE_OP_IN, 42 | RT_COMPARE_OP_NOT_IN, 43 | RT_COMPARE_OP_IS, 44 | RT_COMPARE_OP_IS_NOT, 45 | RT_COMPARE_OP_EXCEPTION_MATCH, 46 | } rt_binary_op_t; 47 | 48 | typedef enum { 49 | RT_F_LOAD_CONST_DEC = 0, 50 | RT_F_LOAD_CONST_STR, 51 | RT_F_LOAD_NAME, 52 | RT_F_LOAD_GLOBAL, 53 | RT_F_LOAD_BUILD_CLASS, 54 | RT_F_LOAD_ATTR, 55 | RT_F_LOAD_METHOD, 56 | RT_F_STORE_NAME, 57 | RT_F_STORE_ATTR, 58 | RT_F_STORE_SUBSCR, 59 | RT_F_IS_TRUE, 60 | RT_F_UNARY_OP, 61 | RT_F_BUILD_TUPLE, 62 | RT_F_BUILD_LIST, 63 | RT_F_LIST_APPEND, 64 | RT_F_BUILD_MAP, 65 | RT_F_STORE_MAP, 66 | RT_F_BUILD_SET, 67 | RT_F_STORE_SET, 68 | RT_F_MAKE_FUNCTION_FROM_ID, 69 | RT_F_CALL_FUNCTION_N, 70 | RT_F_CALL_METHOD_N, 71 | RT_F_BINARY_OP, 72 | RT_F_GETITER, 73 | RT_F_ITERNEXT, 74 | RT_F_NUMBER_OF, 75 | } rt_fun_kind_t; 76 | 77 | extern void *const rt_fun_table[RT_F_NUMBER_OF]; 78 | 79 | void rt_init(void); 80 | void rt_deinit(void); 81 | int rt_get_unique_code_id(void); 82 | void rt_assign_byte_code(int unique_code_id, byte *code, uint len, int n_args, int n_locals, int n_stack, bool is_generator); 83 | void rt_assign_native_code(int unique_code_id, void *f, uint len, int n_args); 84 | void rt_assign_inline_asm_code(int unique_code_id, void *f, uint len, int n_args); 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | The Micro Python project 2 | ======================== 3 |

4 | MicroPython Logo 5 |

6 | 7 | This is the Micro Python project, which aims to put an implementation 8 | of Python 3.x on a microcontroller. 9 | 10 | WARNING: this project is in its early stages and is subject to large 11 | changes of the code-base, including project-wide name changes and API 12 | changes. The software will not start to mature until March 2014 at the 13 | earliest. 14 | 15 | See the repository www.github.com/micropython/pyboard for the Micro 16 | Python board. At the moment, finalising the design of the board is 17 | the top priority. 18 | 19 | Major components in this repository: 20 | - py/ -- the core Python implementation, including compiler and runtime. 21 | - unix/ -- a version of Micro Python that runs on Unix. 22 | - stm/ -- a version of Micro Python that runs on the Micro Python board 23 | with an STM32F405RG. 24 | - teensy/ -- a version of Micro Python that runs on the Teensy 3.1 25 | (preliminary but functional). 26 | 27 | Additional components: 28 | - unix-cpy/ -- a version of Micro Python that outputs bytecode (for testing). 29 | - tests/ -- test framework and test scripts. 30 | - tools/ -- various tools. 31 | - examples/ -- a few example Python scripts. 32 | 33 | "make" is used to build the components, or "gmake" on BSD-based systems. 34 | You will also need bash and python (2.7 or 3.3) for the stm port. 35 | 36 | The Unix version 37 | ---------------- 38 | 39 | The "unix" part requires a standard Unix environment with gcc and GNU make. 40 | It works only for 64-bit machines due to a small piece of x86-64 assembler 41 | for the exception handling. 42 | 43 | To build: 44 | 45 | $ cd unix 46 | $ make 47 | 48 | Then to test it: 49 | 50 | $ ./py 51 | >>> list(5 * x + y for x in range(10) for y in [4, 2, 1]) 52 | 53 | Ubuntu and Mint derivatives will require build-essentials and libreadline-dev 54 | packages installed. 55 | 56 | The STM version 57 | --------------- 58 | 59 | The "stm" part requires an ARM compiler, arm-none-eabi-gcc, and associated 60 | bin-utils. For those using Arch Linux, you need arm-none-eabi-binutils and 61 | arm-none-eabi-gcc packages from the AUR. Otherwise, try here: 62 | https://launchpad.net/gcc-arm-embedded 63 | 64 | To build: 65 | 66 | $ cd stm 67 | $ make 68 | 69 | Then to flash it via USB DFU to your device: 70 | 71 | $ dfu-util -a 0 -D build/flash.dfu 72 | 73 | You will need the dfu-util program, on Arch Linux it's dfu-util-git in the AUR. 74 | -------------------------------------------------------------------------------- /stm/stmusbh/usbh_conf.h: -------------------------------------------------------------------------------- 1 | /** 2 | ****************************************************************************** 3 | * @file USBH_conf.h 4 | * @author MCD Application Team 5 | * @version V2.1.0 6 | * @date 19-March-2012 7 | * @brief General low level driver configuration 8 | ****************************************************************************** 9 | * @attention 10 | * 11 | *

© COPYRIGHT 2012 STMicroelectronics

12 | * 13 | * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); 14 | * You may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at: 16 | * 17 | * http://www.st.com/software_license_agreement_liberty_v2 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | ****************************************************************************** 26 | */ 27 | 28 | /* Define to prevent recursive inclusion -------------------------------------*/ 29 | #ifndef __USBH_CONF__H__ 30 | #define __USBH_CONF__H__ 31 | 32 | /* Includes ------------------------------------------------------------------*/ 33 | 34 | /** @addtogroup USBH_OTG_DRIVER 35 | * @{ 36 | */ 37 | 38 | /** @defgroup USBH_CONF 39 | * @brief usb otg low level driver configuration file 40 | * @{ 41 | */ 42 | 43 | /** @defgroup USBH_CONF_Exported_Defines 44 | * @{ 45 | */ 46 | 47 | #define USBH_MAX_NUM_ENDPOINTS 2 48 | #define USBH_MAX_NUM_INTERFACES 2 49 | #define USBH_MSC_MPS_SIZE 0x200 50 | 51 | /** 52 | * @} 53 | */ 54 | 55 | 56 | /** @defgroup USBH_CONF_Exported_Types 57 | * @{ 58 | */ 59 | /** 60 | * @} 61 | */ 62 | 63 | 64 | /** @defgroup USBH_CONF_Exported_Macros 65 | * @{ 66 | */ 67 | /** 68 | * @} 69 | */ 70 | 71 | /** @defgroup USBH_CONF_Exported_Variables 72 | * @{ 73 | */ 74 | /** 75 | * @} 76 | */ 77 | 78 | /** @defgroup USBH_CONF_Exported_FunctionsPrototype 79 | * @{ 80 | */ 81 | /** 82 | * @} 83 | */ 84 | 85 | 86 | #endif //__USBH_CONF__H__ 87 | 88 | 89 | /** 90 | * @} 91 | */ 92 | 93 | /** 94 | * @} 95 | */ 96 | /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ 97 | 98 | -------------------------------------------------------------------------------- /stm/usrsw.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "misc.h" 8 | #include "mpconfig.h" 9 | #include "qstr.h" 10 | #include "obj.h" 11 | #include "usrsw.h" 12 | 13 | void switch_init(void) { 14 | // make it an input with pull-up 15 | GPIO_InitTypeDef GPIO_InitStructure; 16 | GPIO_InitStructure.GPIO_Pin = USRSW_PIN; 17 | GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; 18 | GPIO_InitStructure.GPIO_PuPd = USRSW_PUPD; 19 | GPIO_Init(USRSW_PORT, &GPIO_InitStructure); 20 | 21 | // the rest does the EXTI interrupt 22 | 23 | /* Enable SYSCFG clock */ 24 | RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); 25 | 26 | /* Connect EXTI Line to GPIO pin */ 27 | SYSCFG_EXTILineConfig(USRSW_EXTI_PORT, USRSW_EXTI_PIN); 28 | 29 | /* Configure EXTI Line */ 30 | EXTI_InitTypeDef EXTI_InitStructure; 31 | EXTI_InitStructure.EXTI_Line = USRSW_EXTI_LINE; 32 | EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; 33 | EXTI_InitStructure.EXTI_Trigger = USRSW_EXTI_EDGE; 34 | EXTI_InitStructure.EXTI_LineCmd = ENABLE; 35 | EXTI_Init(&EXTI_InitStructure); 36 | 37 | /* Enable and set EXTI15_10 Interrupt to the lowest priority */ 38 | NVIC_InitTypeDef NVIC_InitStructure; 39 | NVIC_InitStructure.NVIC_IRQChannel = USRSW_EXTI_IRQN; 40 | NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F; 41 | NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F; 42 | NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; 43 | NVIC_Init(&NVIC_InitStructure); 44 | } 45 | 46 | int switch_get(void) { 47 | #if defined (PYBOARD3) || defined (PYBOARD4) 48 | if (USRSW_PORT->IDR & USRSW_PIN) { 49 | // pulled high, so switch is not pressed 50 | return 0; 51 | } else { 52 | // pulled low, so switch is pressed 53 | return 1; 54 | } 55 | #elif defined (STM32F4DISC) 56 | /* switch pulled down */ 57 | if (USRSW_PORT->IDR & USRSW_PIN) { 58 | // pulled high, so switch is pressed 59 | return 1; 60 | } else { 61 | // pulled low, so switch is not pressed 62 | return 0; 63 | } 64 | #endif 65 | } 66 | 67 | /******************************************************************************/ 68 | /* Micro Python bindings */ 69 | 70 | static mp_obj_t pyb_switch(void) { 71 | if (switch_get()) { 72 | return mp_const_true; 73 | } else { 74 | return mp_const_false; 75 | } 76 | } 77 | 78 | MP_DEFINE_CONST_FUN_OBJ_0(pyb_switch_obj, pyb_switch); 79 | -------------------------------------------------------------------------------- /tests/bytecode/pylib-tests/symbol.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | 3 | """Non-terminal symbols of Python grammar (from "graminit.h").""" 4 | 5 | # This file is automatically generated; please don't muck it up! 6 | # 7 | # To update the symbols in this file, 'cd' to the top directory of 8 | # the python source tree after building the interpreter and run: 9 | # 10 | # ./python Lib/symbol.py 11 | 12 | #--start constants-- 13 | single_input = 256 14 | file_input = 257 15 | eval_input = 258 16 | decorator = 259 17 | decorators = 260 18 | decorated = 261 19 | funcdef = 262 20 | parameters = 263 21 | typedargslist = 264 22 | tfpdef = 265 23 | varargslist = 266 24 | vfpdef = 267 25 | stmt = 268 26 | simple_stmt = 269 27 | small_stmt = 270 28 | expr_stmt = 271 29 | testlist_star_expr = 272 30 | augassign = 273 31 | del_stmt = 274 32 | pass_stmt = 275 33 | flow_stmt = 276 34 | break_stmt = 277 35 | continue_stmt = 278 36 | return_stmt = 279 37 | yield_stmt = 280 38 | raise_stmt = 281 39 | import_stmt = 282 40 | import_name = 283 41 | import_from = 284 42 | import_as_name = 285 43 | dotted_as_name = 286 44 | import_as_names = 287 45 | dotted_as_names = 288 46 | dotted_name = 289 47 | global_stmt = 290 48 | nonlocal_stmt = 291 49 | assert_stmt = 292 50 | compound_stmt = 293 51 | if_stmt = 294 52 | while_stmt = 295 53 | for_stmt = 296 54 | try_stmt = 297 55 | with_stmt = 298 56 | with_item = 299 57 | except_clause = 300 58 | suite = 301 59 | test = 302 60 | test_nocond = 303 61 | lambdef = 304 62 | lambdef_nocond = 305 63 | or_test = 306 64 | and_test = 307 65 | not_test = 308 66 | comparison = 309 67 | comp_op = 310 68 | star_expr = 311 69 | expr = 312 70 | xor_expr = 313 71 | and_expr = 314 72 | shift_expr = 315 73 | arith_expr = 316 74 | term = 317 75 | factor = 318 76 | power = 319 77 | atom = 320 78 | testlist_comp = 321 79 | trailer = 322 80 | subscriptlist = 323 81 | subscript = 324 82 | sliceop = 325 83 | exprlist = 326 84 | testlist = 327 85 | dictorsetmaker = 328 86 | classdef = 329 87 | arglist = 330 88 | argument = 331 89 | comp_iter = 332 90 | comp_for = 333 91 | comp_if = 334 92 | encoding_decl = 335 93 | yield_expr = 336 94 | yield_arg = 337 95 | #--end constants-- 96 | 97 | sym_name = {} 98 | for _name, _value in list(globals().items()): 99 | if type(_value) is type(0): 100 | sym_name[_value] = _name 101 | 102 | 103 | def main(): 104 | import sys 105 | import token 106 | if len(sys.argv) == 1: 107 | sys.argv = sys.argv + ["Include/graminit.h", "Lib/symbol.py"] 108 | token._main() 109 | 110 | if __name__ == "__main__": 111 | main() 112 | -------------------------------------------------------------------------------- /py/strtonum.c: -------------------------------------------------------------------------------- 1 | #if defined(UNIX) 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include "misc.h" 8 | #include "mpconfig.h" 9 | #include "qstr.h" 10 | #include "nlr.h" 11 | #include "obj.h" 12 | 13 | long strtonum(const char *restrict s, int base) { 14 | int c, neg = 0; 15 | const char *p = s; 16 | char *num; 17 | long found; 18 | 19 | // check radix base 20 | if ((base != 0 && base < 2) || base > 36) { 21 | nlr_jump(mp_obj_new_exception_msg(MP_QSTR_ValueError, "ValueError: int() arg 2 must be >=2 and <= 36")); 22 | } 23 | // skip surrounded whitespace 24 | while (isspace((c = *(p++)))); 25 | if (c == 0) { 26 | goto value_error; 27 | } 28 | // preced sign 29 | if (c == '+' || c == '-') { 30 | neg = - (c == '-'); 31 | c = *(p++); 32 | } 33 | 34 | // find real radix base, and strip preced '0x', '0o' and '0b' 35 | // TODO somehow merge with similar code in parse.c 36 | if ((base == 0 || base == 16) && c == '0') { 37 | c = *(p++); 38 | if ((c | 32) == 'x') { 39 | base = 16; 40 | } else if (base == 0 && (c | 32) == 'o') { 41 | base = 8; 42 | } else if (base == 0 && (c | 32) == 'b') { 43 | base = 2; 44 | } else { 45 | base = 10; 46 | p -= 2; 47 | } 48 | } else if (base == 8 && c == '0') { 49 | c = *(p++); 50 | if ((c | 32) != 'o') { 51 | p -= 2; 52 | } 53 | } else if (base == 2 && c == '0') { 54 | c = *(p++); 55 | if ((c | 32) != 'b') { 56 | p -= 2; 57 | } 58 | } else { 59 | if (base == 0) base = 10; 60 | p--; 61 | } 62 | 63 | errno = 0; 64 | found = strtol(p, &num, base); 65 | if (errno) { 66 | goto value_error; 67 | } else if (found && *(num) == 0) { 68 | goto done; 69 | } else if (found || num != p) { 70 | goto check_tail_space; 71 | } else { 72 | goto value_error; 73 | } 74 | 75 | check_tail_space: 76 | if (*(num) != 0) { 77 | while (isspace((c = *(num++)))); 78 | if (c != 0) { 79 | goto value_error; 80 | } 81 | } 82 | 83 | done: 84 | return (found ^ neg) - neg; 85 | 86 | value_error: 87 | nlr_jump(mp_obj_new_exception_msg_2_args(MP_QSTR_ValueError, "invalid literal for int() with base %d: '%s'", (void*)(machine_uint_t)base, s)); 88 | } 89 | 90 | #else /* defined(UNIX) */ 91 | 92 | long strtonum(const char *restrict s, int base) { 93 | // TODO port strtol to stm 94 | return 0; 95 | } 96 | 97 | #endif /* defined(UNIX) */ 98 | -------------------------------------------------------------------------------- /tests/bytecode/pylib-tests/nturl2path.py: -------------------------------------------------------------------------------- 1 | """Convert a NT pathname to a file URL and vice versa.""" 2 | 3 | def url2pathname(url): 4 | """OS-specific conversion from a relative URL of the 'file' scheme 5 | to a file system path; not recommended for general use.""" 6 | # e.g. 7 | # ///C|/foo/bar/spam.foo 8 | # becomes 9 | # C:\foo\bar\spam.foo 10 | import string, urllib.parse 11 | # Windows itself uses ":" even in URLs. 12 | url = url.replace(':', '|') 13 | if '|' not in url: 14 | # No drive specifier, just convert slashes 15 | if url[:4] == '////': 16 | # path is something like ////host/path/on/remote/host 17 | # convert this to \\host\path\on\remote\host 18 | # (notice halving of slashes at the start of the path) 19 | url = url[2:] 20 | components = url.split('/') 21 | # make sure not to convert quoted slashes :-) 22 | return urllib.parse.unquote('\\'.join(components)) 23 | comp = url.split('|') 24 | if len(comp) != 2 or comp[0][-1] not in string.ascii_letters: 25 | error = 'Bad URL: ' + url 26 | raise IOError(error) 27 | drive = comp[0][-1].upper() 28 | components = comp[1].split('/') 29 | path = drive + ':' 30 | for comp in components: 31 | if comp: 32 | path = path + '\\' + urllib.parse.unquote(comp) 33 | # Issue #11474 - handing url such as |c/| 34 | if path.endswith(':') and url.endswith('/'): 35 | path += '\\' 36 | return path 37 | 38 | def pathname2url(p): 39 | """OS-specific conversion from a file system path to a relative URL 40 | of the 'file' scheme; not recommended for general use.""" 41 | # e.g. 42 | # C:\foo\bar\spam.foo 43 | # becomes 44 | # ///C|/foo/bar/spam.foo 45 | import urllib.parse 46 | if ':' not in p: 47 | # No drive specifier, just convert slashes and quote the name 48 | if p[:2] == '\\\\': 49 | # path is something like \\host\path\on\remote\host 50 | # convert this to ////host/path/on/remote/host 51 | # (notice doubling of slashes at the start of the path) 52 | p = '\\\\' + p 53 | components = p.split('\\') 54 | return urllib.parse.quote('/'.join(components)) 55 | comp = p.split(':') 56 | if len(comp) != 2 or len(comp[0]) > 1: 57 | error = 'Bad path: ' + p 58 | raise IOError(error) 59 | 60 | drive = urllib.parse.quote(comp[0].upper()) 61 | components = comp[1].split('\\') 62 | path = '///' + drive + ':' 63 | for comp in components: 64 | if comp: 65 | path = path + '/' + urllib.parse.quote(comp) 66 | return path 67 | -------------------------------------------------------------------------------- /stm/stmusb/usb_otg.h: -------------------------------------------------------------------------------- 1 | /** 2 | ****************************************************************************** 3 | * @file usb_otg.h 4 | * @author MCD Application Team 5 | * @version V2.1.0 6 | * @date 19-March-2012 7 | * @brief OTG Core Header 8 | ****************************************************************************** 9 | * @attention 10 | * 11 | *

© COPYRIGHT 2012 STMicroelectronics

12 | * 13 | * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); 14 | * You may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at: 16 | * 17 | * http://www.st.com/software_license_agreement_liberty_v2 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | * 25 | ****************************************************************************** 26 | */ 27 | 28 | /* Define to prevent recursive inclusion -------------------------------------*/ 29 | #ifndef __USB_OTG__ 30 | #define __USB_OTG__ 31 | 32 | 33 | /** @addtogroup USB_OTG_DRIVER 34 | * @{ 35 | */ 36 | 37 | /** @defgroup USB_OTG 38 | * @brief This file is the 39 | * @{ 40 | */ 41 | 42 | 43 | /** @defgroup USB_OTG_Exported_Defines 44 | * @{ 45 | */ 46 | 47 | 48 | void USB_OTG_InitiateSRP(USB_OTG_CORE_HANDLE *pdev); 49 | void USB_OTG_InitiateHNP(USB_OTG_CORE_HANDLE *pdev, uint8_t state, uint8_t mode); 50 | void USB_OTG_Switchback (USB_OTG_CORE_HANDLE *pdev); 51 | uint32_t USB_OTG_GetCurrentState (USB_OTG_CORE_HANDLE *pdev); 52 | 53 | /** 54 | * @} 55 | */ 56 | 57 | 58 | /** @defgroup USB_OTG_Exported_Types 59 | * @{ 60 | */ 61 | /** 62 | * @} 63 | */ 64 | 65 | 66 | /** @defgroup USB_OTG_Exported_Macros 67 | * @{ 68 | */ 69 | /** 70 | * @} 71 | */ 72 | 73 | /** @defgroup USB_OTG_Exported_Variables 74 | * @{ 75 | */ 76 | /** 77 | * @} 78 | */ 79 | 80 | /** @defgroup USB_OTG_Exported_FunctionsPrototype 81 | * @{ 82 | */ 83 | /** 84 | * @} 85 | */ 86 | 87 | 88 | #endif //__USB_OTG__ 89 | 90 | 91 | /** 92 | * @} 93 | */ 94 | 95 | /** 96 | * @} 97 | */ 98 | /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ 99 | 100 | -------------------------------------------------------------------------------- /py/scope.h: -------------------------------------------------------------------------------- 1 | enum { 2 | ID_INFO_KIND_GLOBAL_IMPLICIT, 3 | ID_INFO_KIND_GLOBAL_EXPLICIT, 4 | ID_INFO_KIND_LOCAL, // in a function f, written and only referenced by f 5 | ID_INFO_KIND_CELL, // in a function f, read/written by children of f 6 | ID_INFO_KIND_FREE, // in a function f, belongs to the parent of f 7 | }; 8 | 9 | typedef struct _id_info_t { 10 | // TODO compress this info to make structure smaller in memory 11 | bool param; 12 | int kind; 13 | qstr qstr; 14 | 15 | // when it's an ID_INFO_KIND_LOCAL this is the unique number of the local 16 | // whet it's an ID_INFO_KIND_CELL/FREE this is the unique number of the closed over variable 17 | int local_num; 18 | } id_info_t; 19 | 20 | // taken from python source, Include/code.h 21 | #define SCOPE_FLAG_OPTIMISED 0x0001 22 | #define SCOPE_FLAG_NEWLOCALS 0x0002 23 | #define SCOPE_FLAG_VARARGS 0x0004 24 | #define SCOPE_FLAG_VARKEYWORDS 0x0008 25 | #define SCOPE_FLAG_NESTED 0x0010 26 | #define SCOPE_FLAG_GENERATOR 0x0020 27 | /* The SCOPE_FLAG_NOFREE flag is set if there are no free or cell variables. 28 | This information is redundant, but it allows a single flag test 29 | to determine whether there is any extra work to be done when the 30 | call frame is setup. 31 | */ 32 | #define SCOPE_FLAG_NOFREE 0x0040 33 | 34 | // scope is a "block" in Python parlance 35 | typedef enum { SCOPE_MODULE, SCOPE_FUNCTION, SCOPE_LAMBDA, SCOPE_LIST_COMP, SCOPE_DICT_COMP, SCOPE_SET_COMP, SCOPE_GEN_EXPR, SCOPE_CLASS } scope_kind_t; 36 | typedef struct _scope_t { 37 | scope_kind_t kind; 38 | struct _scope_t *parent; 39 | struct _scope_t *next; 40 | mp_parse_node_t pn; 41 | qstr source_file; 42 | qstr simple_name; 43 | int id_info_alloc; 44 | int id_info_len; 45 | id_info_t *id_info; 46 | int flags; 47 | int num_params; 48 | /* not needed 49 | int num_default_params; 50 | int num_dict_params; 51 | */ 52 | int num_locals; 53 | int stack_size; 54 | uint unique_code_id; 55 | uint emit_options; 56 | } scope_t; 57 | 58 | scope_t *scope_new(scope_kind_t kind, mp_parse_node_t pn, qstr source_file, uint unique_code_id, uint emit_options); 59 | void scope_free(scope_t *scope); 60 | id_info_t *scope_find_or_add_id(scope_t *scope, qstr qstr, bool *added); 61 | id_info_t *scope_find(scope_t *scope, qstr qstr); 62 | id_info_t *scope_find_global(scope_t *scope, qstr qstr); 63 | id_info_t *scope_find_local_in_parent(scope_t *scope, qstr qstr); 64 | void scope_close_over_in_parents(scope_t *scope, qstr qstr); 65 | void scope_declare_global(scope_t *scope, qstr qstr); 66 | void scope_declare_nonlocal(scope_t *scope, qstr qstr); 67 | void scope_print_info(scope_t *s); 68 | -------------------------------------------------------------------------------- /py/makeqstrdata.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import re 3 | 4 | # codepoint2name is different in Python 2 to Python 3 5 | import platform 6 | if platform.python_version_tuple()[0] == '2': 7 | from htmlentitydefs import codepoint2name 8 | elif platform.python_version_tuple()[0] == '3': 9 | from html.entities import codepoint2name 10 | 11 | # this must match the equivalent function in qstr.c 12 | def compute_hash(qstr): 13 | hash = 0 14 | for char in qstr: 15 | hash += ord(char) 16 | return hash & 0xffff 17 | 18 | def do_work(infiles): 19 | # read the qstrs in from the input files 20 | qstrs = {} 21 | for infile in infiles: 22 | with open(infile, 'rt') as f: 23 | line_number = 0 24 | for line in f: 25 | line_number += 1 26 | line = line.strip() 27 | 28 | # ignore blank lines and comments 29 | if len(line) == 0 or line.startswith('//'): 30 | continue 31 | 32 | # verify line is of the correct form 33 | match = re.match(r'Q\((.+)\)$', line) 34 | if not match: 35 | print('({}:{}) bad qstr format, got {}'.format(infile, line_number, line)) 36 | return False 37 | 38 | # get the qstr value 39 | qstr = match.group(1) 40 | ident = re.sub(r'[^A-Za-z0-9_]', lambda s: "_" + codepoint2name[ord(s.group(0))] + "_", qstr) 41 | 42 | # don't add duplicates 43 | if ident in qstrs: 44 | continue 45 | 46 | # add the qstr to the list, with order number to retain original order in file 47 | qstrs[ident] = (len(qstrs), ident, qstr) 48 | 49 | # process the qstrs, printing out the generated C header file 50 | print('// This file was automatically generated by makeqstrdata.py') 51 | print('') 52 | for order, ident, qstr in sorted(qstrs.values(), key=lambda x: x[0]): 53 | qhash = compute_hash(qstr) 54 | qlen = len(qstr) 55 | print('Q({}, (const byte*)"\\x{:02x}\\x{:02x}\\x{:02x}\\x{:02x}" "{}")'.format(ident, qhash & 0xff, (qhash >> 8) & 0xff, qlen & 0xff, (qlen >> 8) & 0xff, qstr)) 56 | 57 | return True 58 | 59 | def main(): 60 | arg_parser = argparse.ArgumentParser(description='Process raw qstr file and output qstr data with length, hash and data bytes') 61 | arg_parser.add_argument('files', nargs='+', help='input file(s)') 62 | args = arg_parser.parse_args() 63 | 64 | result = do_work(args.files) 65 | if not result: 66 | print('exiting with error code') 67 | exit(1) 68 | 69 | if __name__ == "__main__": 70 | main() 71 | -------------------------------------------------------------------------------- /stm/lexerfatfs.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "ff.h" 5 | 6 | #include "misc.h" 7 | #include "mpconfig.h" 8 | #include "qstr.h" 9 | #include "lexer.h" 10 | #include "lexerfatfs.h" 11 | 12 | typedef struct _mp_lexer_file_buf_t { 13 | FIL fp; 14 | char buf[20]; 15 | uint16_t len; 16 | uint16_t pos; 17 | } mp_lexer_file_buf_t; 18 | 19 | static unichar file_buf_next_char(mp_lexer_file_buf_t *fb) { 20 | if (fb->pos >= fb->len) { 21 | if (fb->len < sizeof(fb->buf)) { 22 | return MP_LEXER_CHAR_EOF; 23 | } else { 24 | UINT n; 25 | f_read(&fb->fp, fb->buf, sizeof(fb->buf), &n); 26 | if (n == 0) { 27 | return MP_LEXER_CHAR_EOF; 28 | } 29 | fb->len = n; 30 | fb->pos = 0; 31 | } 32 | } 33 | return fb->buf[fb->pos++]; 34 | } 35 | 36 | static void file_buf_close(mp_lexer_file_buf_t *fb) { 37 | f_close(&fb->fp); 38 | m_del_obj(mp_lexer_file_buf_t, fb); 39 | } 40 | 41 | mp_lexer_t *mp_lexer_new_from_file(const char *filename) { 42 | mp_lexer_file_buf_t *fb = m_new_obj(mp_lexer_file_buf_t); 43 | FRESULT res = f_open(&fb->fp, filename, FA_READ); 44 | if (res != FR_OK) { 45 | m_del_obj(mp_lexer_file_buf_t, fb); 46 | return NULL; 47 | } 48 | UINT n; 49 | f_read(&fb->fp, fb->buf, sizeof(fb->buf), &n); 50 | fb->len = n; 51 | fb->pos = 0; 52 | return mp_lexer_new(qstr_from_str(filename), fb, (mp_lexer_stream_next_char_t)file_buf_next_char, (mp_lexer_stream_close_t)file_buf_close); 53 | } 54 | 55 | /******************************************************************************/ 56 | // implementation of import 57 | 58 | #include "ff.h" 59 | 60 | mp_lexer_t *mp_import_open_file(qstr mod_name) { 61 | vstr_t *vstr = vstr_new(); 62 | FRESULT res; 63 | 64 | // look for module in src/ 65 | vstr_printf(vstr, "0:/src/%s.py", qstr_str(mod_name)); 66 | res = f_stat(vstr_str(vstr), NULL); 67 | if (res == FR_OK) { 68 | // found file 69 | return mp_lexer_new_from_file(vstr_str(vstr)); // TODO does lexer need to copy the string? can we free it here? 70 | } 71 | 72 | // look for module in / 73 | vstr_reset(vstr); 74 | vstr_printf(vstr, "0:/%s.py", qstr_str(mod_name)); 75 | res = f_stat(vstr_str(vstr), NULL); 76 | if (res == FR_OK) { 77 | // found file 78 | return mp_lexer_new_from_file(vstr_str(vstr)); // TODO does lexer need to copy the string? can we free it here? 79 | } 80 | 81 | // could not find file 82 | vstr_free(vstr); 83 | printf("import %s: could not find file in src/ or /\n", qstr_str(mod_name)); 84 | 85 | return NULL; 86 | } 87 | --------------------------------------------------------------------------------