From b59fa2da28e13d4b38ff799bc330dd6291a49ff7 Mon Sep 17 00:00:00 2001 From: mux Date: Mon, 6 Jan 2014 06:41:56 +0200 Subject: Fix LED pin enum * Fix LED pin enum, first one should start at 1 * Fix LED initialization typo --- stm/led.c | 4 ++-- stm/led.h | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/stm/led.c b/stm/led.c index 9809c2177..19ce99cec 100644 --- a/stm/led.c +++ b/stm/led.c @@ -63,8 +63,8 @@ void led_init(void) { /* Turn off LEDs */ PYB_LED_OFF(PYB_LED1_PORT, PYB_LED1_PIN); PYB_LED_OFF(PYB_LED2_PORT, PYB_LED2_PIN); - PYB_LED_OFF(PYB_LED3_PORT, PYB_LED1_PIN); - PYB_LED_OFF(PYB_LED4_PORT, PYB_LED2_PIN); + PYB_LED_OFF(PYB_LED3_PORT, PYB_LED3_PIN); + PYB_LED_OFF(PYB_LED4_PORT, PYB_LED4_PIN); /* Initialize LEDs */ GPIO_InitStructure.GPIO_Pin = PYB_LED1_PIN; diff --git a/stm/led.h b/stm/led.h index fcbfa1763..c68f3e414 100644 --- a/stm/led.h +++ b/stm/led.h @@ -1,13 +1,13 @@ typedef enum { - PYB_LED_R1 = 0, - PYB_LED_R2 = 1, - PYB_LED_G1 = 2, - PYB_LED_G2 = 3, + PYB_LED_R1 = 1, + PYB_LED_R2 = 2, + PYB_LED_G1 = 3, + PYB_LED_G2 = 4, //STM32F4DISC - PYB_LED_R = 0, - PYB_LED_G = 1, - PYB_LED_B = 2, - PYB_LED_O = 3, + PYB_LED_R = 1, + PYB_LED_G = 2, + PYB_LED_B = 3, + PYB_LED_O = 4, } pyb_led_t; void led_init(void); -- cgit v1.2.3 From b6e9c7c6970971cc0aeadd38cdf287352c97ddf6 Mon Sep 17 00:00:00 2001 From: Dave Hylands Date: Mon, 6 Jan 2014 00:20:11 -0800 Subject: Initial support for Teensy 3.1 --- teensy/Makefile | 155 +++++++++++++++++ teensy/README.md | 31 ++++ teensy/gchelper.s | 36 ++++ teensy/led.c | 86 +++++++++ teensy/led.h | 9 + teensy/lexerteensy.c | 33 ++++ teensy/lexerteensy.h | 8 + teensy/main.c | 474 ++++++++++++++++++++++++++++++++++++++++++++++++++ teensy/main.cpp | 245 ++++++++++++++++++++++++++ teensy/malloc0.c | 57 ++++++ teensy/mk20dx256.ld | 164 +++++++++++++++++ teensy/mpconfigport.h | 21 +++ teensy/printf.c | 305 ++++++++++++++++++++++++++++++++ teensy/std.h | 22 +++ teensy/string0.c | 110 ++++++++++++ teensy/usb.c | 44 +++++ teensy/usb.h | 9 + 17 files changed, 1809 insertions(+) create mode 100644 teensy/Makefile create mode 100644 teensy/README.md create mode 100644 teensy/gchelper.s create mode 100644 teensy/led.c create mode 100644 teensy/led.h create mode 100644 teensy/lexerteensy.c create mode 100644 teensy/lexerteensy.h create mode 100644 teensy/main.c create mode 100644 teensy/main.cpp create mode 100644 teensy/malloc0.c create mode 100644 teensy/mk20dx256.ld create mode 100644 teensy/mpconfigport.h create mode 100644 teensy/printf.c create mode 100644 teensy/std.h create mode 100644 teensy/string0.c create mode 100644 teensy/usb.c create mode 100644 teensy/usb.h diff --git a/teensy/Makefile b/teensy/Makefile new file mode 100644 index 000000000..98b467a06 --- /dev/null +++ b/teensy/Makefile @@ -0,0 +1,155 @@ +ifeq ($(ARDUINO),) +$(error Please define ARDUINO (where TeensyDuino is installed)) +endif +TOOLS_PATH = $(ARDUINO)/hardware/tools +COMPILER_PATH = $(TOOLS_PATH)/arm-none-eabi/bin +CORE_PATH = $(ARDUINO)/hardware/teensy/cores/teensy3 + +PYSRC=../py +BUILD=build + +AS = $(COMPILER_PATH)/arm-none-eabi-as +CC = $(COMPILER_PATH)/arm-none-eabi-gcc +LD = $(COMPILER_PATH)/arm-none-eabi-ld +OBJCOPY = $(COMPILER_PATH)/arm-none-eabi-objcopy +SIZE = $(COMPILER_PATH)/arm-none-eabi-size + +CFLAGS_TEENSY = -DF_CPU=96000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH -D__MK20DX256__ +CFLAGS_CORTEX_M4 = -mthumb -mtune=cortex-m4 -mcpu=cortex-m4 -fsingle-precision-constant -Wdouble-promotion $(CFLAGS_TEENSY) +CFLAGS = -I. -I$(PYSRC) -I$(CORE_PATH) -Wall -ansi -std=gnu99 -Os -DNDEBUG $(CFLAGS_CORTEX_M4) +LDFLAGS = -nostdlib -T mk20dx256.ld +LIBS = -L $(COMPILER_PATH)/../lib/gcc/arm-none-eabi/4.7.2/thumb2 -lgcc + +SRC_C = \ + main.c \ + lexerteensy.c \ + led.c \ + malloc0.c \ + printf.c \ + string0.c \ + usb.c \ + +SRC_S = \ + gchelper.s \ + +PY_O = \ + nlrthumb.o \ + gc.o \ + malloc.o \ + qstr.o \ + vstr.o \ + unicode.o \ + lexer.o \ + parse.o \ + scope.o \ + compile.o \ + emitcommon.o \ + emitpass1.o \ + emitbc.o \ + asmthumb.o \ + emitnthumb.o \ + emitinlinethumb.o \ + runtime.o \ + map.o \ + obj.o \ + objbool.o \ + objboundmeth.o \ + objcell.o \ + objclass.o \ + objclosure.o \ + objcomplex.o \ + objdict.o \ + objexcept.o \ + objfloat.o \ + objfun.o \ + objgenerator.o \ + objinstance.o \ + objint.o \ + objlist.o \ + objmodule.o \ + objnone.o \ + objrange.o \ + objset.o \ + objslice.o \ + objstr.o \ + objtuple.o \ + objtype.o \ + builtin.o \ + builtinimport.o \ + vm.o \ + showbc.o \ + repl.o \ + +SRC_TEENSY = \ + mk20dx128.c \ + pins_teensy.c \ + analog.c \ + usb_desc.c \ + usb_dev.c \ + usb_mem.c \ + usb_serial.c \ + yield.c \ + +OBJ = $(addprefix $(BUILD)/, $(SRC_C:.c=.o) $(SRC_S:.s=.o) $(PY_O) $(SRC_TEENSY:.c=.o)) +#LIB = -lreadline +# the following is needed for BSD +#LIB += -ltermcap +PROG = micropython + +all: hex +hex: $(PROG).hex + +post_compile: $(PROG).hex + $(TOOLS_PATH)/teensy_post_compile -file="$(basename $<)" -path="$(CURDIR)" -tools="$(TOOLS_PATH)" + +reboot: + -$(TOOLS_PATH)/teensy_reboot + +upload: post_compile reboot + +$(PROG).elf: $(BUILD) $(OBJ) + $(CC) $(LDFLAGS) -o "$@" -Wl,-Map,$(PROG).map $(OBJ) $(LIBS) + +%.hex: %.elf + $(SIZE) "$<" + $(OBJCOPY) -O ihex -R .eeprom "$<" "$@" + +$(BUILD): + mkdir -p $@ + +$(BUILD)/%.o: %.s + $(AS) -o $@ $< + +$(BUILD)/%.o: %.c + $(CC) $(CFLAGS) -c -o $@ $< + +$(BUILD)/%.o: $(PYSRC)/%.S + $(CC) $(CFLAGS) -c -o $@ $< + +$(BUILD)/%.o: $(PYSRC)/%.c mpconfigport.h + $(CC) $(CFLAGS) -c -o $@ $< + +$(BUILD)/%.o: $(CORE_PATH)/%.c + $(CC) $(CFLAGS) -c -o $@ $< + +$(BUILD)/emitnthumb.o: $(PYSRC)/emitnative.c $(PYSRC)/emit.h + $(CC) $(CFLAGS) -DN_THUMB -c -o $@ $< + +# optimising gc for speed; 5ms down to 4ms +$(BUILD)/gc.o: $(PYSRC)/gc.c + $(CC) $(CFLAGS) -O3 -c -o $@ $< + +# optimising vm for speed, adds only a small amount to code size but makes a huge difference to speed (20% faster) +$(BUILD)/vm.o: $(PYSRC)/vm.c + $(CC) $(CFLAGS) -O3 -c -o $@ $< + +$(BUILD)/main.o: mpconfigport.h +$(BUILD)/parse.o: $(PYSRC)/grammar.h +$(BUILD)/compile.o: $(PYSRC)/grammar.h +$(BUILD)/emitbc.o: $(PYSRC)/emit.h + +clean: + /bin/rm -rf $(BUILD) + /bin/rm -f $(PROG).elf $(PROG).hex $(PROG).map + +.PHONY: clean diff --git a/teensy/README.md b/teensy/README.md new file mode 100644 index 000000000..31339cd79 --- /dev/null +++ b/teensy/README.md @@ -0,0 +1,31 @@ +Build Instructions for Teensy 3.1 + +This assumes that you have TeensyDuino installed and set the ARUINO environment +variable pointing to the where Arduino with TeensyDuino is installed. + +``` +cd teensy +ARDUINO=~/arduino-1.0.5 make +``` + +To build the loader + +``` +cd teensy/loader +make +``` + +To upload micropython to the Teensy 3.1. + +Press the Program button on the Teensy 3.1 +``` +make upload +``` + +Currently, the python prompt is through the USB serial interface. + +The LED will blink (100 msec on/100 msec off) while waiting for the USB Serial +device to be configured, and will blink (200 msec on/200 msec off) while +sitting at the readline prompt. + +Currently, there is no I/O support configured (no GPIO, ADC, etc). diff --git a/teensy/gchelper.s b/teensy/gchelper.s new file mode 100644 index 000000000..f8735d283 --- /dev/null +++ b/teensy/gchelper.s @@ -0,0 +1,36 @@ + .syntax unified + .cpu cortex-m4 + .thumb + .text + .align 2 + +@ void gc_helper_get_regs_and_clean_stack(r0=uint regs[10], r1=heap_end) + .global gc_helper_get_regs_and_clean_stack + .thumb + .thumb_func + .type gc_helper_get_regs_and_clean_stack, %function +gc_helper_get_regs_and_clean_stack: + @ store registers into given array + str r4, [r0], #4 + str r5, [r0], #4 + str r6, [r0], #4 + str r7, [r0], #4 + str r8, [r0], #4 + str r9, [r0], #4 + str r10, [r0], #4 + str r11, [r0], #4 + str r12, [r0], #4 + str r13, [r0], #4 + + @ clean the stack from given pointer up to current sp + movs r0, #0 + mov r2, sp + b.n .entry +.loop: + str r0, [r1], #4 +.entry: + cmp r1, r2 + bcc.n .loop + bx lr + + .size gc_helper_get_regs_and_clean_stack, .-gc_helper_get_regs_and_clean_stack diff --git a/teensy/led.c b/teensy/led.c new file mode 100644 index 000000000..1aad2a365 --- /dev/null +++ b/teensy/led.c @@ -0,0 +1,86 @@ +#include + +#include "misc.h" +#include "mpconfig.h" +#include "obj.h" +#include "led.h" + +#include "Arduino.h" + +void led_init(void) { +} + +void led_state(pyb_led_t led, int state) { + uint8_t pin; + + if (led == 0) { + pin = LED_BUILTIN; + } else { + return; + } + digitalWrite(pin, state); +} + +void led_toggle(pyb_led_t led) { + uint8_t pin; + + if (led == 0) { + pin = LED_BUILTIN; + } else { + return; + } + + digitalWrite(pin, !digitalRead(pin)); +} + +/******************************************************************************/ +/* Micro Python bindings */ + +typedef struct _pyb_led_obj_t { + mp_obj_base_t base; + uint led_id; +} pyb_led_obj_t; + +void led_obj_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in) { + pyb_led_obj_t *self = self_in; + print(env, "", self->led_id); +} + +mp_obj_t led_obj_on(mp_obj_t self_in) { + pyb_led_obj_t *self = self_in; + led_state(self->led_id, 1); + return mp_const_none; +} + +mp_obj_t led_obj_off(mp_obj_t self_in) { + pyb_led_obj_t *self = self_in; + led_state(self->led_id, 0); + return mp_const_none; +} + +static MP_DEFINE_CONST_FUN_OBJ_1(led_obj_on_obj, led_obj_on); +static MP_DEFINE_CONST_FUN_OBJ_1(led_obj_off_obj, led_obj_off); + +static const mp_obj_type_t led_obj_type = { + { &mp_const_type }, + "Led", + led_obj_print, // print + NULL, // make_new + NULL, // call_n + NULL, // unary_op + NULL, // binary_op + NULL, // getiter + NULL, // iternext + { // method list + { "on", &led_obj_on_obj }, + { "off", &led_obj_off_obj }, + { NULL, NULL }, + } +}; + +mp_obj_t pyb_Led(mp_obj_t led_id) { + pyb_led_obj_t *o = m_new_obj(pyb_led_obj_t); + o->base.type = &led_obj_type; + o->led_id = mp_obj_get_int(led_id); + return o; +} diff --git a/teensy/led.h b/teensy/led.h new file mode 100644 index 000000000..c5a481254 --- /dev/null +++ b/teensy/led.h @@ -0,0 +1,9 @@ +typedef enum { + PYB_LED_BUILTIN = 0, +} pyb_led_t; + +void led_init(void); +void led_state(pyb_led_t led, int state); +void led_toggle(pyb_led_t led); + +mp_obj_t pyb_Led(mp_obj_t led_id); diff --git a/teensy/lexerteensy.c b/teensy/lexerteensy.c new file mode 100644 index 000000000..eefaf6665 --- /dev/null +++ b/teensy/lexerteensy.c @@ -0,0 +1,33 @@ +#include +#include + +#include "misc.h" +#include "lexer.h" +#include "lexerteensy.h" + +unichar str_buf_next_char(mp_lexer_str_buf_t *sb) { + if (sb->src_cur < sb->src_end) { + return *sb->src_cur++; + } else { + return MP_LEXER_CHAR_EOF; + } +} + +void str_buf_free(mp_lexer_str_buf_t *sb) { + if (sb->free) { + m_del(char, (char*)sb->src_beg, 0 /* don't know allocated size of src */); + } +} + +mp_lexer_t *mp_lexer_new_from_str_len(const char *src_name, const char *str, uint len, bool free_str, mp_lexer_str_buf_t *sb) { + sb->free = free_str; + sb->src_beg = str; + sb->src_cur = str; + sb->src_end = str + len; + 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); +} + +mp_lexer_t *mp_import_open_file(qstr mod_name) { + printf("import not implemented\n"); + return NULL; +} diff --git a/teensy/lexerteensy.h b/teensy/lexerteensy.h new file mode 100644 index 000000000..961a70ada --- /dev/null +++ b/teensy/lexerteensy.h @@ -0,0 +1,8 @@ +typedef struct _py_lexer_str_buf_t { + bool free; // free src_beg when done + const char *src_beg; // beginning of source + const char *src_cur; // current location in source + const char *src_end; // end (exclusive) of source +} mp_lexer_str_buf_t; + +mp_lexer_t *mp_lexer_new_from_str_len(const char *src_name, const char *str, uint len, bool free_str, mp_lexer_str_buf_t *sb); diff --git a/teensy/main.c b/teensy/main.c new file mode 100644 index 000000000..3711cd60d --- /dev/null +++ b/teensy/main.c @@ -0,0 +1,474 @@ +#include +#include +#include +#include + +#include "nlr.h" +#include "misc.h" +#include "mpconfig.h" +#include "mpqstr.h" +#include "lexer.h" +#include "lexerteensy.h" +#include "parse.h" +#include "obj.h" +#include "compile.h" +#include "runtime0.h" +#include "runtime.h" +#include "repl.h" +#include "usb.h" +#include "gc.h" +#include "led.h" + +#include "Arduino.h" + +extern uint32_t _heap_start; + +#ifdef USE_READLINE +#include +#include +#endif + +#if 0 +static char *str_join(const char *s1, int sep_char, const char *s2) { + int l1 = strlen(s1); + int l2 = strlen(s2); + char *s = m_new(char, l1 + l2 + 2); + memcpy(s, s1, l1); + if (sep_char != 0) { + s[l1] = sep_char; + l1 += 1; + } + memcpy(s + l1, s2, l2); + s[l1 + l2] = 0; + return s; +} + +static char *prompt(char *p) { +#ifdef USE_READLINE + char *line = readline(p); + if (line) { + add_history(line); + } +#else + static char buf[256]; + fputs(p, stdout); + char *s = fgets(buf, sizeof(buf), stdin); + if (!s) { + return NULL; + } + int l = strlen(buf); + if (buf[l - 1] == '\n') { + buf[l - 1] = 0; + } else { + l++; + } + char *line = m_new(char, l); + memcpy(line, buf, l); +#endif + return line; +} +#endif + +static const char *help_text = +"Welcome to Micro Python!\n\n" +"This is a *very* early version of Micro Python and has minimal functionality.\n\n" +"Specific commands for the board:\n" +" pyb.info() -- print some general information\n" +" pyb.gc() -- run the garbage collector\n" +" pyb.delay() -- wait for n milliseconds\n" +" pyb.Led() -- create Led object for LED n (n=0)\n" +" Led methods: on(), off()\n" +" pyb.gpio() -- read gpio pin\n" +" pyb.gpio(, ) -- set gpio pin\n" +#if 0 +" pyb.Servo() -- create Servo object for servo n (n=1,2,3,4)\n" +" Servo methods: angle()\n" +" pyb.switch() -- return True/False if switch pressed or not\n" +" pyb.accel() -- get accelerometer values\n" +" pyb.rand() -- get a 16-bit random number\n" +#endif +; + +// get some help about available functions +static mp_obj_t pyb_help(void) { + printf("%s", help_text); + return mp_const_none; +} + +// get lots of info about the board +static mp_obj_t pyb_info(void) { + // get and print unique id; 96 bits + { + byte *id = (byte*)0x40048058; + printf("ID=%02x%02x%02x%02x:%02x%02x%02x%02x:%02x%02x%02x%02x\n", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11]); + } + + // get and print clock speeds + printf("CPU=%u\nBUS=%u\nMEM=%u\n", F_CPU, F_BUS, F_MEM); + + // to print info about memory + { + extern void *_sdata; + extern void *_edata; + extern void *_sbss; + extern void *_ebss; + extern void *_estack; + extern void *_etext; + printf("_sdata=%p\n", &_sdata); + printf("_edata=%p\n", &_edata); + printf("_sbss=%p\n", &_sbss); + printf("_ebss=%p\n", &_ebss); + printf("_estack=%p\n", &_estack); + printf("_etext=%p\n", &_etext); + printf("_heap_start=%p\n", &_heap_start); + } + + // GC info + { + gc_info_t info; + gc_info(&info); + printf("GC:\n"); + printf(" %lu total\n", info.total); + printf(" %lu used %lu free\n", info.used, info.free); + printf(" 1=%lu 2=%lu m=%lu\n", info.num_1block, info.num_2block, info.max_block); + } + +#if 0 + // free space on flash + { + DWORD nclst; + FATFS *fatfs; + f_getfree("0:", &nclst, &fatfs); + printf("LFS free: %u bytes\n", (uint)(nclst * fatfs->csize * 512)); + } +#endif + + return mp_const_none; +} + +#define RAM_START (0x1FFF8000) // fixed for chip +#define HEAP_END (0x20006000) // tunable +#define RAM_END (0x20008000) // fixed for chip + +void gc_helper_get_regs_and_clean_stack(machine_uint_t *regs, machine_uint_t heap_end); + +void gc_collect(void) { + uint32_t start = micros(); + gc_collect_start(); + gc_collect_root((void**)RAM_START, (((uint32_t)&_heap_start) - RAM_START) / 4); + machine_uint_t regs[10]; + gc_helper_get_regs_and_clean_stack(regs, HEAP_END); + gc_collect_root((void**)HEAP_END, (RAM_END - HEAP_END) / 4); // will trace regs since they now live in this function on the stack + gc_collect_end(); + uint32_t ticks = micros() - start; // TODO implement a function that does this properly + + if (0) { + // print GC info + gc_info_t info; + gc_info(&info); + printf("GC@%lu %luus\n", start, ticks); + printf(" %lu total\n", info.total); + printf(" %lu used %lu free\n", info.used, info.free); + printf(" 1=%lu 2=%lu m=%lu\n", info.num_1block, info.num_2block, info.max_block); + } +} + +mp_obj_t pyb_gc(void) { + gc_collect(); + return mp_const_none; +} + +mp_obj_t pyb_gpio(int n_args, mp_obj_t *args) { + //assert(1 <= n_args && n_args <= 2); + + uint pin = mp_obj_get_int(args[0]); + if (pin > CORE_NUM_DIGITAL) { + goto pin_error; + } + + if (n_args == 1) { + // get pin + pinMode(pin, INPUT); + return MP_OBJ_NEW_SMALL_INT(digitalRead(pin)); + } + + // set pin + pinMode(pin, OUTPUT); + digitalWrite(pin, rt_is_true(args[1])); + return mp_const_none; + +pin_error: + nlr_jump(mp_obj_new_exception_msg_1_arg(MP_QSTR_ValueError, "pin %d does not exist", (void *)(machine_uint_t)pin)); +} + +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_gpio_obj, 1, 2, pyb_gpio); + +#if 0 +mp_obj_t pyb_hid_send_report(mp_obj_t arg) { + mp_obj_t *items = mp_obj_get_array_fixed_n(arg, 4); + uint8_t data[4]; + data[0] = mp_obj_get_int(items[0]); + data[1] = mp_obj_get_int(items[1]); + data[2] = mp_obj_get_int(items[2]); + data[3] = mp_obj_get_int(items[3]); + usb_hid_send_report(data); + return mp_const_none; +} +#endif + +mp_obj_t pyb_delay(mp_obj_t count) { + delay(mp_obj_get_int(count)); + return mp_const_none; +} + +mp_obj_t pyb_led(mp_obj_t state) { + led_state(PYB_LED_BUILTIN, rt_is_true(state)); + return state; +} + +char *strdup(const char *str) { + uint32_t len = strlen(str); + char *s2 = m_new(char, len + 1); + memcpy(s2, str, len); + s2[len] = 0; + return s2; +} + +#define READLINE_HIST_SIZE (8) + +static const char *readline_hist[READLINE_HIST_SIZE] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; + +void stdout_tx_str(const char *str) { +// usart_tx_str(str); + usb_vcp_send_str(str); +} + +int readline(vstr_t *line, const char *prompt) { + stdout_tx_str(prompt); + int len = vstr_len(line); + int escape = 0; + int hist_num = 0; + for (;;) { + char c; + for (;;) { + if (usb_vcp_rx_any() != 0) { + c = usb_vcp_rx_get(); + break; +#if 0 + } else if (usart_rx_any()) { + c = usart_rx_char(); + break; +#endif + } + //delay(1); + //if (storage_needs_flush()) { + // storage_flush(); + //} + } + if (escape == 0) { + if (c == 4 && vstr_len(line) == len) { + return 0; + } else if (c == '\r') { + stdout_tx_str("\r\n"); + for (int i = READLINE_HIST_SIZE - 1; i > 0; i--) { + readline_hist[i] = readline_hist[i - 1]; + } + readline_hist[0] = strdup(vstr_str(line)); + return 1; + } else if (c == 27) { + escape = true; + } else if (c == 127) { + if (vstr_len(line) > len) { + vstr_cut_tail(line, 1); + stdout_tx_str("\b \b"); + } + } else if (32 <= c && c <= 126) { + vstr_add_char(line, c); + stdout_tx_str(line->buf + line->len - 1); + } + } else if (escape == 1) { + if (c == '[') { + escape = 2; + } else { + escape = 0; + } + } else if (escape == 2) { + escape = 0; + if (c == 'A') { + // up arrow + if (hist_num < READLINE_HIST_SIZE && readline_hist[hist_num] != NULL) { + // erase line + for (int i = line->len - len; i > 0; i--) { + stdout_tx_str("\b \b"); + } + // set line to history + line->len = len; + vstr_add_str(line, readline_hist[hist_num]); + // draw line + stdout_tx_str(readline_hist[hist_num]); + // increase hist num + hist_num += 1; + } + } + } else { + escape = 0; + } + delay(10); + } +} + +void do_repl(void) { + stdout_tx_str("Micro Python for Teensy 3.1\r\n"); + stdout_tx_str("Type \"help()\" for more information.\r\n"); + + vstr_t line; + vstr_init(&line); + + for (;;) { + vstr_reset(&line); + int ret = readline(&line, ">>> "); + if (ret == 0) { + // EOF + break; + } + + if (vstr_len(&line) == 0) { + continue; + } + + if (mp_repl_is_compound_stmt(vstr_str(&line))) { + for (;;) { + vstr_add_char(&line, '\n'); + int len = vstr_len(&line); + int ret = readline(&line, "... "); + if (ret == 0 || vstr_len(&line) == len) { + // done entering compound statement + break; + } + } + } + + mp_lexer_str_buf_t sb; + mp_lexer_t *lex = mp_lexer_new_from_str_len("", vstr_str(&line), vstr_len(&line), false, &sb); + mp_parse_node_t pn = mp_parse(lex, MP_PARSE_SINGLE_INPUT); + mp_lexer_free(lex); + + if (pn != MP_PARSE_NODE_NULL) { + mp_obj_t module_fun = mp_compile(pn, true); + if (module_fun != mp_const_none) { + nlr_buf_t nlr; + uint32_t start = micros(); + if (nlr_push(&nlr) == 0) { + rt_call_function_0(module_fun); + nlr_pop(); + // optional timing + if (0) { + uint32_t ticks = micros() - start; // TODO implement a function that does this properly + printf("(took %lu us)\n", ticks); + } + } else { + // uncaught exception + mp_obj_print((mp_obj_t)nlr.ret_val); + printf("\n"); + } + } + } + } + + stdout_tx_str("\r\n"); +} + +void main(void) { + pinMode(LED_BUILTIN, OUTPUT); + // Wait for host side to get connected + while (!usb_vcp_is_connected()) { + ; + } + + led_init(); + led_state(PYB_LED_BUILTIN, 1); + +// int first_soft_reset = true; + +soft_reset: + + // GC init + gc_init(&_heap_start, (void*)HEAP_END); + + qstr_init(); + rt_init(); + +#if 1 + printf("About to add functions()\n"); + // add some functions to the python namespace + { + rt_store_name(qstr_from_str_static("help"), rt_make_function_0(pyb_help)); + mp_obj_t m = mp_obj_new_module(qstr_from_str_static("pyb")); + rt_store_attr(m, qstr_from_str_static("info"), rt_make_function_0(pyb_info)); + rt_store_attr(m, qstr_from_str_static("gc"), rt_make_function_0(pyb_gc)); + rt_store_attr(m, qstr_from_str_static("delay"), rt_make_function_1(pyb_delay)); + rt_store_attr(m, qstr_from_str_static("led"), rt_make_function_1(pyb_led)); + rt_store_attr(m, qstr_from_str_static("Led"), rt_make_function_1(pyb_Led)); + rt_store_attr(m, qstr_from_str_static("gpio"), (mp_obj_t)&pyb_gpio_obj); + rt_store_name(qstr_from_str_static("pyb"), m); + } +#endif + + // Turn bootup LED off + led_state(PYB_LED_BUILTIN, 0); + + do_repl(); + + printf("PYB: soft reboot\n"); + +// first_soft_reset = false; + goto soft_reset; +} + +double __aeabi_f2d(float x) { + // TODO + return 0.0; +} + +float __aeabi_d2f(double x) { + // TODO + return 0.0; +} + +double sqrt(double x) { + // TODO + return 0.0; +} + +machine_float_t machine_sqrt(machine_float_t x) { + // TODO + return x; +} + +// stub out __libc_init_array. It's called by mk20dx128.c and is used to call +// global C++ constructors. Since this is a C-only projects, we don't need to +// call constructors. +void __libc_init_array(void) { +} + +char * ultoa(unsigned long val, char *buf, int radix) +{ + unsigned digit; + int i=0, j; + char t; + + while (1) { + digit = val % radix; + buf[i] = ((digit < 10) ? '0' + digit : 'A' + digit - 10); + val /= radix; + if (val == 0) break; + i++; + } + buf[i + 1] = 0; + for (j=0; j < i; j++, i--) { + t = buf[j]; + buf[j] = buf[i]; + buf[i] = t; + } + return buf; +} diff --git a/teensy/main.cpp b/teensy/main.cpp new file mode 100644 index 000000000..52ce51cda --- /dev/null +++ b/teensy/main.cpp @@ -0,0 +1,245 @@ +#include +#include +#include +#include + +#include "Arduino.h" + +extern "C" +{ +#include "nlr.h" +#include "misc.h" +#include "mpconfig.h" +#include "lexer.h" +#include "lexerteensy.h" +#include "parse.h" +#include "obj.h" +#include "compile.h" +#include "runtime0.h" +#include "runtime.h" +#include "repl.h" +#include "usb.h" +} + +#ifdef USE_READLINE +#include +#include +#endif + +#if 0 +static char *str_join(const char *s1, int sep_char, const char *s2) { + int l1 = strlen(s1); + int l2 = strlen(s2); + char *s = m_new(char, l1 + l2 + 2); + memcpy(s, s1, l1); + if (sep_char != 0) { + s[l1] = sep_char; + l1 += 1; + } + memcpy(s + l1, s2, l2); + s[l1 + l2] = 0; + return s; +} + +static char *prompt(char *p) { +#ifdef USE_READLINE + char *line = readline(p); + if (line) { + add_history(line); + } +#else + static char buf[256]; + fputs(p, stdout); + char *s = fgets(buf, sizeof(buf), stdin); + if (!s) { + return NULL; + } + int l = strlen(buf); + if (buf[l - 1] == '\n') { + buf[l - 1] = 0; + } else { + l++; + } + char *line = m_new(char, l); + memcpy(line, buf, l); +#endif + return line; +} +#endif + +#define READLINE_HIST_SIZE (8) + +static const char *readline_hist[READLINE_HIST_SIZE] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; + +void stdout_tx_str(const char *str) { +// usart_tx_str(str); + usb_vcp_send_str(str); +} + +static elapsedMillis ledTime; +static uint8_t ledState; + +int readline(vstr_t *line, const char *prompt) { + stdout_tx_str(prompt); + int len = vstr_len(line); + int escape = 0; + int hist_num = 0; + for (;;) { + char c; + ledState = 1; + ledTime = 0; + digitalWrite(LED_BUILTIN, ledState); + for (;;) { + if (ledTime > 200) { + ledState = !ledState; + digitalWrite(LED_BUILTIN, ledState); + ledTime = 0; + } + if (usb_vcp_rx_any() != 0) { + c = usb_vcp_rx_get(); + break; +#if 0 + } else if (usart_rx_any()) { + c = usart_rx_char(); + break; +#endif + } + //delay(1); + //if (storage_needs_flush()) { + // storage_flush(); + //} + } + if (escape == 0) { + if (c == 4 && vstr_len(line) == len) { + return 0; + } else if (c == '\r') { + stdout_tx_str("\r\n"); + for (int i = READLINE_HIST_SIZE - 1; i > 0; i--) { + readline_hist[i] = readline_hist[i - 1]; + } + readline_hist[0] = strdup(vstr_str(line)); + return 1; + } else if (c == 27) { + escape = true; + } else if (c == 127) { + if (vstr_len(line) > len) { + vstr_cut_tail(line, 1); + stdout_tx_str("\b \b"); + } + } else if (32 <= c && c <= 126) { + vstr_add_char(line, c); + stdout_tx_str(line->buf + line->len - 1); + } + } else if (escape == 1) { + if (c == '[') { + escape = 2; + } else { + escape = 0; + } + } else if (escape == 2) { + escape = 0; + if (c == 'A') { + // up arrow + if (hist_num < READLINE_HIST_SIZE && readline_hist[hist_num] != NULL) { + // erase line + for (int i = line->len - len; i > 0; i--) { + stdout_tx_str("\b \b"); + } + // set line to history + line->len = len; + vstr_add_str(line, readline_hist[hist_num]); + // draw line + stdout_tx_str(readline_hist[hist_num]); + // increase hist num + hist_num += 1; + } + } + } else { + escape = 0; + } + delay(10); + } +} + +void setup(void) { + pinMode(LED_BUILTIN, OUTPUT); + ledState = 1; + digitalWrite(LED_BUILTIN, ledState); + ledTime = 0; + // Wait for host side to get connected + while (!usb_vcp_is_connected()) { + if (ledTime > 100) { + ledState = !ledState; + digitalWrite(LED_BUILTIN, ledState); + ledTime = 0; + } + } + digitalWrite(LED_BUILTIN, 0); + + qstr_init(); + rt_init(); + + stdout_tx_str("Micro Python for Teensy 3.1\r\n"); + stdout_tx_str("Type \"help()\" for more information.\r\n"); +} + +void loop(void) { + vstr_t line; + vstr_init(&line); + + vstr_reset(&line); + int ret = readline(&line, ">>> "); + if (ret == 0) { + // EOF + return; + } + + if (vstr_len(&line) == 0) { + return; + } + + if (mp_repl_is_compound_stmt(vstr_str(&line))) { + for (;;) { + vstr_add_char(&line, '\n'); + int len = vstr_len(&line); + int ret = readline(&line, "... "); + if (ret == 0 || vstr_len(&line) == len) { + // done entering compound statement + break; + } + } + } + + mp_lexer_str_buf_t sb; + mp_lexer_t *lex = mp_lexer_new_from_str_len("", vstr_str(&line), vstr_len(&line), false, &sb); + mp_parse_node_t pn = mp_parse(lex, MP_PARSE_SINGLE_INPUT); + mp_lexer_free(lex); + + if (pn != MP_PARSE_NODE_NULL) { + mp_obj_t module_fun = mp_compile(pn, true); + if (module_fun != mp_const_none) { + nlr_buf_t nlr; + uint32_t start = micros(); + if (nlr_push(&nlr) == 0) { + rt_call_function_0(module_fun); + nlr_pop(); + // optional timing + if (0) { + uint32_t ticks = micros() - start; // TODO implement a function that does this properly + printf("(took %lu us)\n", ticks); + } + } else { + // uncaught exception + mp_obj_print((mp_obj_t)nlr.ret_val); + printf("\r\n"); + } + } + } +} + +// for sqrt +#include +machine_float_t machine_sqrt(machine_float_t x) { + return sqrt(x); +} + diff --git a/teensy/malloc0.c b/teensy/malloc0.c new file mode 100644 index 000000000..1a6cb708e --- /dev/null +++ b/teensy/malloc0.c @@ -0,0 +1,57 @@ +#include +#include "std.h" +#include "mpconfig.h" +#include "gc.h" + +#if 0 +static uint32_t mem = 0; + +void *malloc(size_t n) { + if (mem == 0) { + extern uint32_t _heap_start; + 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?) + } + void *ptr = (void*)mem; + mem = (mem + n + 3) & (~3); + if (mem > 0x20000000 + 0x18000) { + void __fatal_error(const char*); + __fatal_error("out of memory"); + } + return ptr; +} + +void free(void *ptr) { +} + +void *realloc(void *ptr, size_t n) { + return malloc(n); +} + +#endif + +void *calloc(size_t sz, size_t n) { + char *ptr = malloc(sz * n); + for (int i = 0; i < sz * n; i++) { + ptr[i] = 0; + } + return ptr; +} + +void *malloc(size_t n) { + void *m = gc_alloc(n); + return m; +} + +void free(void *ptr) { + gc_free(ptr); +} + +void *realloc(void *ptr, size_t n) { + return gc_realloc(ptr, n); +} + +void __assert_func(void) { + printf("\nASSERT FAIL!"); + for (;;) { + } +} diff --git a/teensy/mk20dx256.ld b/teensy/mk20dx256.ld new file mode 100644 index 000000000..da57cbe5c --- /dev/null +++ b/teensy/mk20dx256.ld @@ -0,0 +1,164 @@ +/* Teensyduino Core Library + * http://www.pjrc.com/teensy/ + * Copyright (c) 2013 PJRC.COM, LLC. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * 1. The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * 2. If the Software is incorporated into a build system that allows + * selection among a list of target devices, then similar target + * devices manufactured by PJRC.COM must be included in the list of + * target devices and selectable in the same manner. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +MEMORY +{ + FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 256K + RAM (rwx) : ORIGIN = 0x1FFF8000, LENGTH = 64K +} + +/* produce a link error if there is not this amount of RAM for these sections */ +_minimum_stack_size = 2K; +_minimum_heap_size = 16K; + +/* INCLUDE common.ld */ + +/* Teensyduino Core Library + * http://www.pjrc.com/teensy/ + * Copyright (c) 2013 PJRC.COM, LLC. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * 1. The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * 2. If the Software is incorporated into a build system that allows + * selection among a list of target devices, then similar target + * devices manufactured by PJRC.COM must be included in the list of + * target devices and selectable in the same manner. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + + + +SECTIONS +{ + .text : { + . = 0; + KEEP(*(.vectors)) + *(.startup*) + /* TODO: does linker detect startup overflow onto flashconfig? */ + . = 0x400; + KEEP(*(.flashconfig*)) + *(.text*) + *(.rodata*) + . = ALIGN(4); + KEEP(*(.init)) + . = ALIGN(4); + __preinit_array_start = .; + KEEP (*(.preinit_array)) + __preinit_array_end = .; + __init_array_start = .; + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array)) + __init_array_end = .; + } > FLASH = 0xFF + + .ARM.exidx : { + __exidx_start = .; + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + __exidx_end = .; + } > FLASH + _etext = .; + + .usbdescriptortable (NOLOAD) : { + /* . = ORIGIN(RAM); */ + . = ALIGN(512); + *(.usbdescriptortable*) + } > RAM + + .dmabuffers (NOLOAD) : { + . = ALIGN(4); + *(.dmabuffers*) + } > RAM + + .usbbuffers (NOLOAD) : { + . = ALIGN(4); + *(.usbbuffers*) + } > RAM + + .data : AT (_etext) { + . = ALIGN(4); + _sdata = .; + *(.data*) + . = ALIGN(4); + _edata = .; + } > RAM + + .noinit (NOLOAD) : { + *(.noinit*) + } > RAM + + .bss : { + . = ALIGN(4); + _sbss = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + _ebss = .; + __bss_end = .; + } > RAM + + /* this is to define the start of the heap, and make sure we have a minimum size */ + .heap : + { + . = ALIGN(4); + _heap_start = .; /* define a global symbol at heap start */ + . = . + _minimum_heap_size; + } >RAM + + /* this just checks there is enough RAM for the stack */ + .stack : + { + . = ALIGN(4); + . = . + _minimum_stack_size; + . = ALIGN(4); + } >RAM + + _estack = ORIGIN(RAM) + LENGTH(RAM); +} + + + + diff --git a/teensy/mpconfigport.h b/teensy/mpconfigport.h new file mode 100644 index 000000000..4cea332f3 --- /dev/null +++ b/teensy/mpconfigport.h @@ -0,0 +1,21 @@ +#include + +// options to control how Micro Python is built + +#define MICROPY_ENABLE_FLOAT (1) +#define MICROPY_EMIT_CPYTHON (0) +#define MICROPY_EMIT_X64 (0) +#define MICROPY_EMIT_THUMB (1) +#define MICROPY_EMIT_INLINE_THUMB (1) + +// type definitions for the specific machine + +#define BYTES_PER_WORD (4) + +typedef int32_t machine_int_t; // must be pointer size +typedef uint32_t machine_uint_t; // must be pointer size +typedef void *machine_ptr_t; // must be of pointer size +typedef const void *machine_const_ptr_t; // must be of pointer size +typedef float machine_float_t; + +machine_float_t machine_sqrt(machine_float_t x); diff --git a/teensy/printf.c b/teensy/printf.c new file mode 100644 index 000000000..71b27b821 --- /dev/null +++ b/teensy/printf.c @@ -0,0 +1,305 @@ +#include +#include +#include "std.h" +#include "misc.h" +//#include "lcd.h" +//#include "usart.h" +#include "usb.h" + +#define PF_FLAG_LEFT_ADJUST (0x01) +#define PF_FLAG_SHOW_SIGN (0x02) +#define PF_FLAG_SPACE_SIGN (0x04) +#define PF_FLAG_NO_TRAILZ (0x08) +#define PF_FLAG_ZERO_PAD (0x10) + +// tricky; we compute pad string by: pad_chars + (flags & PF_FLAG_ZERO_PAD) +#define PF_PAD_SIZE PF_FLAG_ZERO_PAD +static const char *pad_chars = " 0000000000000000"; + +typedef struct _pfenv_t { + void *data; + void (*print_strn)(void *, const char *str, unsigned int len); +} pfenv_t; + +static void print_str_dummy(void *data, const char *str, unsigned int len) { +} + +const pfenv_t pfenv_dummy = {0, print_str_dummy}; + +static int pfenv_print_strn(const pfenv_t *pfenv, const char *str, unsigned int len, int flags, int width) { + int pad = width - len; + if (pad > 0 && (flags & PF_FLAG_LEFT_ADJUST) == 0) { + while (pad > 0) { + int p = pad; + if (p > PF_PAD_SIZE) + p = PF_PAD_SIZE; + pfenv->print_strn(pfenv->data, pad_chars + (flags & PF_FLAG_ZERO_PAD), p); + pad -= p; + } + } + pfenv->print_strn(pfenv->data, str, len); + while (pad > 0) { + int p = pad; + if (p > PF_PAD_SIZE) + p = PF_PAD_SIZE; + pfenv->print_strn(pfenv->data, pad_chars, p); + pad -= p; + } + return len; +} + +// enough room for 32 signed number +#define INT_BUF_SIZE (12) + +static int pfenv_print_int(const pfenv_t *pfenv, unsigned int x, int sgn, int base, int base_char, int flags, int width) { + char sign = 0; + if (sgn) { + if ((int)x < 0) { + sign = '-'; + x = -x; + } else if (flags & PF_FLAG_SHOW_SIGN) { + sign = '+'; + } else if (flags & PF_FLAG_SPACE_SIGN) { + sign = ' '; + } + } + + char buf[INT_BUF_SIZE]; + char *b = buf + INT_BUF_SIZE; + + if (x == 0) { + *(--b) = '0'; + } else { + do { + int c = x % base; + x /= base; + if (c >= 10) { + c += base_char - 10; + } else { + c += '0'; + } + *(--b) = c; + } while (b > buf && x != 0); + } + + if (b > buf && sign != 0) { + *(--b) = sign; + } + + return pfenv_print_strn(pfenv, b, buf + INT_BUF_SIZE - b, flags, width); +} + +void pfenv_prints(const pfenv_t *pfenv, const char *str) { + pfenv->print_strn(pfenv->data, str, strlen(str)); +} + +int pfenv_printf(const pfenv_t *pfenv, const char *fmt, va_list args) { + int chrs = 0; + for (;;) { + { + const char *f = fmt; + while (*f != '\0' && *f != '%') { + ++f; // XXX UTF8 advance char + } + if (f > fmt) { + pfenv->print_strn(pfenv->data, fmt, f - fmt); + chrs += f - fmt; + fmt = f; + } + } + + if (*fmt == '\0') { + break; + } + + // move past % character + ++fmt; + + // parse flags, if they exist + int flags = 0; + while (*fmt != '\0') { + if (*fmt == '-') flags |= PF_FLAG_LEFT_ADJUST; + else if (*fmt == '+') flags |= PF_FLAG_SHOW_SIGN; + else if (*fmt == ' ') flags |= PF_FLAG_SPACE_SIGN; + else if (*fmt == '!') flags |= PF_FLAG_NO_TRAILZ; + else if (*fmt == '0') flags |= PF_FLAG_ZERO_PAD; + else break; + ++fmt; + } + + // parse width, if it exists + int width = 0; + for (; '0' <= *fmt && *fmt <= '9'; ++fmt) { + width = width * 10 + *fmt - '0'; + } + + // parse precision, if it exists + int prec = -1; + if (*fmt == '.') { + ++fmt; + if (*fmt == '*') { + ++fmt; + prec = va_arg(args, int); + } else { + prec = 0; + for (; '0' <= *fmt && *fmt <= '9'; ++fmt) { + prec = prec * 10 + *fmt - '0'; + } + } + if (prec < 0) { + prec = 0; + } + } + + // parse long specifiers (current not used) + //bool long_arg = false; + if (*fmt == 'l') { + ++fmt; + //long_arg = true; + } + + if (*fmt == '\0') { + break; + } + + switch (*fmt) { + case 'b': + if (va_arg(args, int)) { + chrs += pfenv_print_strn(pfenv, "true", 4, flags, width); + } else { + chrs += pfenv_print_strn(pfenv, "false", 5, flags, width); + } + break; + case 'c': + { + char str = va_arg(args, int); + chrs += pfenv_print_strn(pfenv, &str, 1, flags, width); + break; + } + case 's': + { + const char *str = va_arg(args, const char*); + if (str) { + if (prec < 0) { + prec = strlen(str); + } + chrs += pfenv_print_strn(pfenv, str, prec, flags, width); + } else { + chrs += pfenv_print_strn(pfenv, "(null)", 6, flags, width); + } + break; + } + case 'u': + chrs += pfenv_print_int(pfenv, va_arg(args, int), 0, 10, 'a', flags, width); + break; + case 'd': + chrs += pfenv_print_int(pfenv, va_arg(args, int), 1, 10, 'a', flags, width); + break; + case 'x': + case 'p': // ? + chrs += pfenv_print_int(pfenv, va_arg(args, int), 0, 16, 'a', flags, width); + break; + case 'X': + case 'P': // ? + chrs += pfenv_print_int(pfenv, va_arg(args, int), 0, 16, 'A', flags, width); + break; + default: + pfenv->print_strn(pfenv->data, fmt, 1); + chrs += 1; + break; + } + ++fmt; + } + return chrs; +} + +void stdout_print_strn(void *data, const char *str, unsigned int len) { + // send stdout to USART, USB CDC VCP, and LCD if nothing else +#if 0 + int any = 0; + if (usart_is_enabled()) { + usart_tx_strn_cooked(str, len); + any = true; + } +#endif + if (usb_vcp_is_enabled()) { + usb_vcp_send_strn_cooked(str, len); +// any = true; + } +#if 0 + if (!any) { + lcd_print_strn(str, len); + } +#endif +} + +static const pfenv_t pfenv_stdout = {0, stdout_print_strn}; + +int printf(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + int ret = pfenv_printf(&pfenv_stdout, fmt, ap); + va_end(ap); + return ret; +} + +int vprintf(const char *fmt, va_list ap) { + return pfenv_printf(&pfenv_stdout, fmt, ap); +} + +// need this because gcc optimises printf("%c", c) -> putchar(c), and printf("a") -> putchar('a') +int putchar(int c) { + char chr = c; + stdout_print_strn(0, &chr, 1); + return chr; +} + +// need this because gcc optimises printf("string\n") -> puts("string") +int puts(const char *s) { + stdout_print_strn(0, s, strlen(s)); + char chr = '\n'; + stdout_print_strn(0, &chr, 1); + return 1; +} + +typedef struct _strn_pfenv_t { + char *cur; + size_t remain; +} strn_pfenv_t; + +void strn_print_strn(void *data, const char *str, unsigned int len) { + strn_pfenv_t *strn_pfenv = data; + if (len > strn_pfenv->remain) { + len = strn_pfenv->remain; + } + memcpy(strn_pfenv->cur, str, len); + strn_pfenv->cur += len; + strn_pfenv->remain -= len; +} + +int vsnprintf(char *str, size_t size, const char *fmt, va_list ap) { + strn_pfenv_t strn_pfenv; + strn_pfenv.cur = str; + strn_pfenv.remain = size; + pfenv_t pfenv; + pfenv.data = &strn_pfenv; + pfenv.print_strn = strn_print_strn; + int len = pfenv_printf(&pfenv, fmt, ap); + // add terminating null byte + if (size > 0) { + if (strn_pfenv.remain == 0) { + strn_pfenv.cur[-1] = 0; + } else { + strn_pfenv.cur[0] = 0; + } + } + return len; +} + +int snprintf(char *str, size_t size, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + int ret = vsnprintf(str, size, fmt, ap); + va_end(ap); + return ret; +} diff --git a/teensy/std.h b/teensy/std.h new file mode 100644 index 000000000..587b9f888 --- /dev/null +++ b/teensy/std.h @@ -0,0 +1,22 @@ +typedef unsigned int size_t; + +void __assert_func(void); + +void *malloc(size_t n); +void free(void *ptr); +void *calloc(size_t sz, size_t n); +void *realloc(void *ptr, size_t n); + +void *memcpy(void *dest, const void *src, size_t n); +void *memmove(void *dest, const void *src, size_t n); +void *memset(void *s, int c, size_t n); + +int strlen(const char *str); +int strcmp(const char *s1, const char *s2); +int strncmp(const char *s1, const char *s2, size_t n); +char *strndup(const char *s, size_t n); +char *strcpy(char *dest, const char *src); +char *strcat(char *dest, const char *src); + +int printf(const char *fmt, ...); +int snprintf(char *str, size_t size, const char *fmt, ...); diff --git a/teensy/string0.c b/teensy/string0.c new file mode 100644 index 000000000..2a5f25597 --- /dev/null +++ b/teensy/string0.c @@ -0,0 +1,110 @@ +#include +#include "std.h" + +void *memcpy(void *dest, const void *src, size_t n) { + // TODO align and copy 32 bits at a time + uint8_t *d = dest; + const uint8_t *s = src; + for (; n > 0; n--) { + *d++ = *s++; + } + return dest; +} + +void *memmove(void *dest, const void *src, size_t n) { + if (src < dest && dest < src + n) { + // need to copy backwards + uint8_t *d = dest + n - 1; + const uint8_t *s = src + n - 1; + for (; n > 0; n--) { + *d-- = *s--; + } + return dest; + } else { + // can use normal memcpy + return memcpy(dest, src, n); + } +} + +void *memset(void *s, int c, size_t n) { + uint8_t *s2 = s; + for (; n > 0; n--) { + *s2++ = c; + } + return s; +} + +int strlen(const char *str) { + int len = 0; + for (const char *s = str; *s; s++) { + len += 1; + } + return len; +} + +int strcmp(const char *s1, const char *s2) { + while (*s1 && *s2) { + char c1 = *s1++; // XXX UTF8 get char, next char + char c2 = *s2++; // XXX UTF8 get char, next char + if (c1 < c2) return -1; + else if (c1 > c2) return 1; + } + if (*s2) return -1; + else if (*s1) return 1; + else return 0; +} + +int strncmp(const char *s1, const char *s2, size_t n) { + while (*s1 && *s2 && n > 0) { + char c1 = *s1++; // XXX UTF8 get char, next char + char c2 = *s2++; // XXX UTF8 get char, next char + n--; + if (c1 < c2) return -1; + else if (c1 > c2) return 1; + } + if (n == 0) return 0; + else if (*s2) return -1; + else if (*s1) return 1; + else return 0; +} + +char *strndup(const char *s, size_t n) { + size_t len = strlen(s); + if (n > len) { + n = len; + } + char *s2 = malloc(n + 1); + memcpy(s2, s, n); + s2[n] = '\0'; + return s2; +} + +char *strcpy(char *dest, const char *src) { + char *d = dest; + while (*src) { + *d++ = *src++; + } + *d = '\0'; + return dest; +} + +// needed because gcc optimises strcpy + strcat to this +char *stpcpy(char *dest, const char *src) { + while (*src) { + *dest++ = *src++; + } + *dest = '\0'; + return dest; +} + +char *strcat(char *dest, const char *src) { + char *d = dest; + while (*d) { + d++; + } + while (*src) { + *d++ = *src++; + } + *d = '\0'; + return dest; +} diff --git a/teensy/usb.c b/teensy/usb.c new file mode 100644 index 000000000..a045a2ed6 --- /dev/null +++ b/teensy/usb.c @@ -0,0 +1,44 @@ +#include "Arduino.h" + +#include "usb.h" +#include "usb_serial.h" + +int usb_vcp_is_connected(void) +{ + return usb_configuration && (usb_cdc_line_rtsdtr & (USB_SERIAL_DTR | USB_SERIAL_RTS)); +} + +int usb_vcp_is_enabled(void) +{ + return 1; +} + +int usb_vcp_rx_any(void) +{ + return usb_serial_available(); +} + +char usb_vcp_rx_get(void) +{ + return usb_serial_getchar(); +} + +void usb_vcp_send_str(const char* str) +{ + usb_vcp_send_strn(str, strlen(str)); +} + +void usb_vcp_send_strn(const char* str, int len) +{ + usb_serial_write(str, len); +} + +void usb_vcp_send_strn_cooked(const char *str, int len) +{ + for (const char *top = str + len; str < top; str++) { + if (*str == '\n') { + usb_serial_putchar('\r'); + } + usb_serial_putchar(*str); + } +} diff --git a/teensy/usb.h b/teensy/usb.h new file mode 100644 index 000000000..8f32309ec --- /dev/null +++ b/teensy/usb.h @@ -0,0 +1,9 @@ +void usb_init(void); +int usb_vcp_is_enabled(void); +int usb_vcp_is_connected(void); +int usb_vcp_rx_any(void); +char usb_vcp_rx_get(void); +void usb_vcp_send_str(const char* str); +void usb_vcp_send_strn(const char* str, int len); +void usb_vcp_send_strn_cooked(const char *str, int len); +void usb_hid_send_report(uint8_t *buf); // 4 bytes for mouse: ?, x, y, ? -- cgit v1.2.3 From af61a1a4923924b9868d488e2e76126a9fc14069 Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Mon, 6 Jan 2014 17:49:46 +0200 Subject: Use constructor to create small int (avoid exposing mp_obj_t internals to VM). --- py/vm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/py/vm.c b/py/vm.c index 8e7ef7485..5e3ec0baf 100644 --- a/py/vm.c +++ b/py/vm.c @@ -106,7 +106,7 @@ bool mp_execute_byte_code_2(const byte **ip_in_out, mp_obj_t *fastn, mp_obj_t ** case MP_BC_LOAD_CONST_SMALL_INT: unum = (ip[0] | (ip[1] << 8) | (ip[2] << 16)) - 0x800000; ip += 3; - PUSH((mp_obj_t)(unum << 1 | 1)); + PUSH(MP_OBJ_NEW_SMALL_INT(unum)); break; case MP_BC_LOAD_CONST_DEC: -- cgit v1.2.3 From 24507aff7d8a4580ac35d87d8fc762858691c88c Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Mon, 6 Jan 2014 17:49:21 +0200 Subject: Typo fix in comment. --- py/emit.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/py/emit.h b/py/emit.h index ea6573103..66e87fd4c 100644 --- a/py/emit.h +++ b/py/emit.h @@ -5,7 +5,7 @@ * is not known until the end of pass 1. * As a consequence, we don't know the maximum stack size until the end of pass 2. * This is problematic for some emitters (x64) since they need to know the maximum - * stack size to compile the entry to the function, and this effects code size. + * stack size to compile the entry to the function, and this affects code size. */ typedef enum { -- cgit v1.2.3 From a41fe31322e92f84ecee4f3e6295bed2ec9120fd Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Mon, 6 Jan 2014 17:17:02 +0000 Subject: Added dict iterator. --- py/objdict.c | 83 ++++++++++++++++++++++++++++++++----- tests/basics/tests/dict_iterator.py | 3 ++ 2 files changed, 76 insertions(+), 10 deletions(-) create mode 100644 tests/basics/tests/dict_iterator.py diff --git a/py/objdict.c b/py/objdict.c index b3e21aedd..4cd636379 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -17,20 +17,23 @@ typedef struct _mp_obj_dict_t { mp_map_t map; } mp_obj_dict_t; +static mp_obj_t mp_obj_new_dict_iterator(mp_obj_dict_t *dict, int cur); +static mp_map_elem_t *dict_it_iternext_elem(mp_obj_t self_in); + static void dict_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in) { mp_obj_dict_t *self = self_in; bool first = true; print(env, "{"); - for (int i = 0; i < self->map.alloc; i++) { - if (self->map.table[i].key != NULL) { - if (!first) { - print(env, ", "); - } - first = false; - mp_obj_print_helper(print, env, self->map.table[i].key); - print(env, ": "); - mp_obj_print_helper(print, env, self->map.table[i].value); + mp_obj_t *dict_iter = mp_obj_new_dict_iterator(self, 0); + mp_map_elem_t *next = NULL; + while ((next = dict_it_iternext_elem(dict_iter)) != NULL) { + if (!first) { + print(env, ", "); } + first = false; + mp_obj_print_helper(print, env, next->key); + print(env, ": "); + mp_obj_print_helper(print, env, next->value); } print(env, "}"); } @@ -60,13 +63,73 @@ static mp_obj_t dict_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) { } } + +/******************************************************************************/ +/* dict iterator */ + +typedef struct _mp_obj_dict_it_t { + mp_obj_base_t base; + mp_obj_dict_t *dict; + machine_uint_t cur; +} mp_obj_dict_it_t; + +static mp_map_elem_t *dict_it_iternext_elem(mp_obj_t self_in) { + mp_obj_dict_it_t *self = self_in; + machine_uint_t max = self->dict->map.alloc; + mp_map_elem_t *table = self->dict->map.table; + + for (int i = self->cur; i < max; i++) { + if (table[i].key != NULL) { + self->cur = i + 1; + return &(table[i]); + } + } + + return NULL; +} + +mp_obj_t dict_it_iternext(mp_obj_t self_in) { + mp_map_elem_t *next = dict_it_iternext_elem(self_in); + + if (next != NULL) { + return next->key; + } else { + return mp_const_stop_iteration; + } +} + +static const mp_obj_type_t dict_it_type = { + { &mp_const_type }, + "dict_iterator", + .iternext = dict_it_iternext, + .methods = { { NULL, NULL }, }, +}; + +static mp_obj_t mp_obj_new_dict_iterator(mp_obj_dict_t *dict, int cur) { + mp_obj_dict_it_t *o = m_new_obj(mp_obj_dict_it_t); + o->base.type = &dict_it_type; + o->dict = dict; + o->cur = cur; + return o; +} + +static mp_obj_t dict_getiter(mp_obj_t o_in) { + return mp_obj_new_dict_iterator(o_in, 0); +} + +/******************************************************************************/ +/* dict methods */ + +/******************************************************************************/ +/* dict constructors & etc */ + const mp_obj_type_t dict_type = { { &mp_const_type }, "dict", .print = dict_print, .make_new = dict_make_new, .binary_op = dict_binary_op, - .getiter = NULL, + .getiter = dict_getiter, .methods = {{NULL, NULL},}, }; diff --git a/tests/basics/tests/dict_iterator.py b/tests/basics/tests/dict_iterator.py new file mode 100644 index 000000000..f190e32ff --- /dev/null +++ b/tests/basics/tests/dict_iterator.py @@ -0,0 +1,3 @@ +d = {1: 2, 3: 4} +for i in d: + print(i, d[i]) -- cgit v1.2.3 From 4ce6ceadcad294a62f6fb2b23da262dc5cad0793 Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Mon, 6 Jan 2014 17:38:47 +0000 Subject: Added dict.clear. Added 0 to the list of primes. Funky primes, these. --- py/map.c | 48 ++++++++++++++++++++++++++++++---------- py/map.h | 1 + py/objdict.c | 16 +++++++++++++- tests/basics/tests/dict_clear.py | 6 +++++ 4 files changed, 58 insertions(+), 13 deletions(-) create mode 100644 tests/basics/tests/dict_clear.py diff --git a/py/map.c b/py/map.c index 01209c9b7..dff0bdfea 100644 --- a/py/map.c +++ b/py/map.c @@ -9,7 +9,8 @@ #include "map.h" // approximatelly doubling primes; made with Mathematica command: Table[Prime[Floor[(1.7)^n]], {n, 3, 24}] -static int doubling_primes[] = {7, 19, 43, 89, 179, 347, 647, 1229, 2297, 4243, 7829, 14347, 26017, 47149, 84947, 152443, 273253, 488399, 869927, 1547173, 2745121, 4861607}; +// prefixed with zero for the empty case. +static int doubling_primes[] = {0, 7, 19, 43, 89, 179, 347, 647, 1229, 2297, 4243, 7829, 14347, 26017, 47149, 84947, 152443, 273253, 488399, 869927, 1547173, 2745121, 4861607}; int get_doubling_prime_greater_or_equal_to(int x) { for (int i = 0; i < sizeof(doubling_primes) / sizeof(int); i++) { @@ -38,6 +39,31 @@ mp_map_t *mp_map_new(mp_map_kind_t kind, int n) { return map; } +void mp_map_clear(mp_map_t *map) { + map->used = 0; + machine_uint_t a = map->alloc; + map->alloc = 0; + map->table = m_renew(mp_map_elem_t, map->table, a, map->alloc); + mp_map_elem_t nul = {NULL, NULL}; + for (uint i=0; ialloc; i++) { + map->table[i] = nul; + } +} + +static void mp_map_rehash (mp_map_t *map) { + int old_alloc = map->alloc; + mp_map_elem_t *old_table = map->table; + map->alloc = get_doubling_prime_greater_or_equal_to(map->alloc + 1); + map->used = 0; + map->table = m_new0(mp_map_elem_t, map->alloc); + for (int i = 0; i < old_alloc; i++) { + if (old_table[i].key != NULL) { + mp_map_lookup_helper(map, old_table[i].key, true)->value = old_table[i].value; + } + } + m_del(mp_map_elem_t, old_table, old_alloc); +} + mp_map_elem_t* mp_map_lookup_helper(mp_map_t *map, mp_obj_t index, bool add_if_not_found) { bool is_map_mp_obj = (map->kind == MP_MAP_OBJ); machine_uint_t hash; @@ -46,6 +72,13 @@ mp_map_elem_t* mp_map_lookup_helper(mp_map_t *map, mp_obj_t index, bool add_if_n } else { hash = (machine_uint_t)index; } + if (map->alloc == 0) { + if (add_if_not_found) { + mp_map_rehash(map); + } else { + return NULL; + } + } uint pos = hash % map->alloc; for (;;) { mp_map_elem_t *elem = &map->table[pos]; @@ -54,17 +87,7 @@ mp_map_elem_t* mp_map_lookup_helper(mp_map_t *map, mp_obj_t index, bool add_if_n if (add_if_not_found) { if (map->used + 1 >= map->alloc) { // not enough room in table, rehash it - int old_alloc = map->alloc; - mp_map_elem_t *old_table = map->table; - map->alloc = get_doubling_prime_greater_or_equal_to(map->alloc + 1); - map->used = 0; - map->table = m_new0(mp_map_elem_t, map->alloc); - for (int i = 0; i < old_alloc; i++) { - if (old_table[i].key != NULL) { - mp_map_lookup_helper(map, old_table[i].key, true)->value = old_table[i].value; - } - } - m_del(mp_map_elem_t, old_table, old_alloc); + mp_map_rehash(map); // restart the search for the new element pos = hash % map->alloc; } else { @@ -106,6 +129,7 @@ void mp_set_init(mp_set_t *set, int n) { mp_obj_t mp_set_lookup(mp_set_t *set, mp_obj_t index, bool add_if_not_found) { int hash = mp_obj_hash(index); + assert(set->alloc); /* FIXME: if alloc is ever 0 when doing a lookup, this'll fail: */ int pos = hash % set->alloc; for (;;) { mp_obj_t elem = set->table[pos]; diff --git a/py/map.h b/py/map.h index f8ca886aa..b4592c270 100644 --- a/py/map.h +++ b/py/map.h @@ -28,6 +28,7 @@ void mp_map_init(mp_map_t *map, mp_map_kind_t kind, int n); mp_map_t *mp_map_new(mp_map_kind_t kind, int n); mp_map_elem_t* mp_map_lookup_helper(mp_map_t *map, mp_obj_t index, bool add_if_not_found); mp_map_elem_t* mp_qstr_map_lookup(mp_map_t *map, qstr index, bool add_if_not_found); +void mp_map_clear(mp_map_t *map); void mp_set_init(mp_set_t *set, int n); mp_obj_t mp_set_lookup(mp_set_t *set, mp_obj_t index, bool add_if_not_found); diff --git a/py/objdict.c b/py/objdict.c index 4cd636379..1a5e162e5 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -120,9 +120,20 @@ static mp_obj_t dict_getiter(mp_obj_t o_in) { /******************************************************************************/ /* dict methods */ +static mp_obj_t dict_clear(mp_obj_t self_in) { + assert(MP_OBJ_IS_TYPE(self_in, &dict_type)); + mp_obj_dict_t *self = self_in; + + mp_map_clear(&self->map); + + return mp_const_none; +} + /******************************************************************************/ /* dict constructors & etc */ +static MP_DEFINE_CONST_FUN_OBJ_1(dict_clear_obj, dict_clear); + const mp_obj_type_t dict_type = { { &mp_const_type }, "dict", @@ -130,7 +141,10 @@ const mp_obj_type_t dict_type = { .make_new = dict_make_new, .binary_op = dict_binary_op, .getiter = dict_getiter, - .methods = {{NULL, NULL},}, + .methods = { + { "clear", &dict_clear_obj }, + { NULL, NULL }, // end-of-list sentinel + }, }; mp_obj_t mp_obj_new_dict(int n_args) { diff --git a/tests/basics/tests/dict_clear.py b/tests/basics/tests/dict_clear.py new file mode 100644 index 000000000..6be2778be --- /dev/null +++ b/tests/basics/tests/dict_clear.py @@ -0,0 +1,6 @@ +d = {1: 2, 3: 4} +print(d) +d.clear() +print(d) +d[2] = 42 +print(d) -- cgit v1.2.3 From 7d21d516d2eb77242c8ade4ae83f0d438e86f072 Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Mon, 6 Jan 2014 17:54:04 +0000 Subject: make dict_len use the map's used count --- py/objdict.c | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/py/objdict.c b/py/objdict.c index 1a5e162e5..951e1ec06 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -128,12 +128,12 @@ static mp_obj_t dict_clear(mp_obj_t self_in) { return mp_const_none; } +static MP_DEFINE_CONST_FUN_OBJ_1(dict_clear_obj, dict_clear); + /******************************************************************************/ /* dict constructors & etc */ -static MP_DEFINE_CONST_FUN_OBJ_1(dict_clear_obj, dict_clear); - const mp_obj_type_t dict_type = { { &mp_const_type }, "dict", @@ -156,13 +156,7 @@ mp_obj_t mp_obj_new_dict(int n_args) { uint mp_obj_dict_len(mp_obj_t self_in) { mp_obj_dict_t *self = self_in; - uint len = 0; - for (int i = 0; i < self->map.alloc; i++) { - if (self->map.table[i].key != NULL) { - len += 1; - } - } - return len; + return self->map.used; } mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value) { -- cgit v1.2.3 From d90b19eca56a361d432ab6af9c2305bb3f708e1c Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Mon, 6 Jan 2014 18:11:20 +0000 Subject: Added dict.copy --- py/objdict.c | 10 ++++++++++ tests/basics/tests/dict_copy.py | 5 +++++ 2 files changed, 15 insertions(+) create mode 100644 tests/basics/tests/dict_copy.py diff --git a/py/objdict.c b/py/objdict.c index 951e1ec06..7567a612c 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -130,6 +130,15 @@ static mp_obj_t dict_clear(mp_obj_t self_in) { } static MP_DEFINE_CONST_FUN_OBJ_1(dict_clear_obj, dict_clear); +static mp_obj_t dict_copy(mp_obj_t self_in) { + assert(MP_OBJ_IS_TYPE(self_in, &dict_type)); + mp_obj_dict_t *self = self_in; + mp_obj_dict_t *other = mp_obj_new_dict(self->map.alloc); + other->map.used = self->map.used; + memcpy(other->map.table, self->map.table, self->map.alloc * sizeof(mp_map_elem_t)); + return other; +} +static MP_DEFINE_CONST_FUN_OBJ_1(dict_copy_obj, dict_copy); /******************************************************************************/ /* dict constructors & etc */ @@ -143,6 +152,7 @@ const mp_obj_type_t dict_type = { .getiter = dict_getiter, .methods = { { "clear", &dict_clear_obj }, + { "copy", &dict_copy_obj }, { NULL, NULL }, // end-of-list sentinel }, }; diff --git a/tests/basics/tests/dict_copy.py b/tests/basics/tests/dict_copy.py new file mode 100644 index 000000000..c3eb7ffc1 --- /dev/null +++ b/tests/basics/tests/dict_copy.py @@ -0,0 +1,5 @@ +a = {i: 2*i for i in range(1000)} +b = a.copy() +for i in range(1000): + print(i, b[i]) +print(len(b)) -- cgit v1.2.3 From cd0887352d18467ea96728e75255ea36f425450d Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Mon, 6 Jan 2014 18:53:16 +0000 Subject: Added dict.get. --- py/objdict.c | 18 ++++++++++++++++-- tests/basics/tests/dict_get.py | 3 +++ 2 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 tests/basics/tests/dict_get.py diff --git a/py/objdict.c b/py/objdict.c index 7567a612c..fd5e37dfe 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -140,6 +140,20 @@ static mp_obj_t dict_copy(mp_obj_t self_in) { } static MP_DEFINE_CONST_FUN_OBJ_1(dict_copy_obj, dict_copy); +static mp_obj_t dict_get(int n_args, const mp_obj_t *args) { + assert(2 <= n_args && n_args <= 3); + assert(MP_OBJ_IS_TYPE(args[0], &dict_type)); + + mp_map_elem_t *elem = mp_map_lookup_helper(&((mp_obj_dict_t *)args[0])->map, + args[1], false); + if (elem == NULL) { + return n_args >= 3 ? args[2] : mp_const_none; + } else { + return elem->value; + } +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_get_obj, 2, 3, dict_get); + /******************************************************************************/ /* dict constructors & etc */ @@ -153,6 +167,7 @@ const mp_obj_type_t dict_type = { .methods = { { "clear", &dict_clear_obj }, { "copy", &dict_copy_obj }, + { "get", &dict_get_obj }, { NULL, NULL }, // end-of-list sentinel }, }; @@ -165,8 +180,7 @@ mp_obj_t mp_obj_new_dict(int n_args) { } uint mp_obj_dict_len(mp_obj_t self_in) { - mp_obj_dict_t *self = self_in; - return self->map.used; + return ((mp_obj_dict_t *)self_in)->map.used; } mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value) { diff --git a/tests/basics/tests/dict_get.py b/tests/basics/tests/dict_get.py new file mode 100644 index 000000000..fb43a45ea --- /dev/null +++ b/tests/basics/tests/dict_get.py @@ -0,0 +1,3 @@ +for d in {}, {42:2}: + print(d.get(42)) + print(d.get(42,2)) -- cgit v1.2.3 From 0fcbaa442f538c8ffca8a7387f7dc6d280172a5c Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Mon, 6 Jan 2014 19:48:34 +0000 Subject: implemented dict.pop --- py/map.c | 15 ++++++++++--- py/map.h | 2 +- py/objdict.c | 51 ++++++++++++++++++++++++++++++++++-------- tests/basics/tests/dict_pop.py | 12 ++++++++++ 4 files changed, 67 insertions(+), 13 deletions(-) create mode 100644 tests/basics/tests/dict_pop.py diff --git a/py/map.c b/py/map.c index dff0bdfea..8554150ad 100644 --- a/py/map.c +++ b/py/map.c @@ -58,13 +58,13 @@ static void mp_map_rehash (mp_map_t *map) { map->table = m_new0(mp_map_elem_t, map->alloc); for (int i = 0; i < old_alloc; i++) { if (old_table[i].key != NULL) { - mp_map_lookup_helper(map, old_table[i].key, true)->value = old_table[i].value; + mp_map_lookup_helper(map, old_table[i].key, true, false)->value = old_table[i].value; } } m_del(mp_map_elem_t, old_table, old_alloc); } -mp_map_elem_t* mp_map_lookup_helper(mp_map_t *map, mp_obj_t index, bool add_if_not_found) { +mp_map_elem_t* mp_map_lookup_helper(mp_map_t *map, mp_obj_t index, bool add_if_not_found, bool remove_if_found) { bool is_map_mp_obj = (map->kind == MP_MAP_OBJ); machine_uint_t hash; if (is_map_mp_obj) { @@ -105,6 +105,15 @@ mp_map_elem_t* mp_map_lookup_helper(mp_map_t *map, mp_obj_t index, bool add_if_n elem->key = index; } */ + if (remove_if_found) { + map->used--; + /* this leaks this memory (but see dict_get_helper) */ + mp_map_elem_t *retval = m_new(mp_map_elem_t, 1); + retval->key = elem->key; + retval->value = elem->value; + elem->key = NULL; + return retval; + } return elem; } else { // not yet found, keep searching in this table @@ -115,7 +124,7 @@ mp_map_elem_t* mp_map_lookup_helper(mp_map_t *map, mp_obj_t index, bool add_if_n mp_map_elem_t* mp_qstr_map_lookup(mp_map_t *map, qstr index, bool add_if_not_found) { mp_obj_t o = (mp_obj_t)(machine_uint_t)index; - return mp_map_lookup_helper(map, o, add_if_not_found); + return mp_map_lookup_helper(map, o, add_if_not_found, false); } /******************************************************************************/ diff --git a/py/map.h b/py/map.h index b4592c270..f0a57758c 100644 --- a/py/map.h +++ b/py/map.h @@ -26,7 +26,7 @@ typedef struct _mp_set_t { int get_doubling_prime_greater_or_equal_to(int x); void mp_map_init(mp_map_t *map, mp_map_kind_t kind, int n); mp_map_t *mp_map_new(mp_map_kind_t kind, int n); -mp_map_elem_t* mp_map_lookup_helper(mp_map_t *map, mp_obj_t index, bool add_if_not_found); +mp_map_elem_t* mp_map_lookup_helper(mp_map_t *map, mp_obj_t index, bool add_if_not_found, bool remove_if_found); mp_map_elem_t* mp_qstr_map_lookup(mp_map_t *map, qstr index, bool add_if_not_found); void mp_map_clear(mp_map_t *map); diff --git a/py/objdict.c b/py/objdict.c index fd5e37dfe..935829ddb 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -50,7 +50,7 @@ static mp_obj_t dict_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) { case RT_BINARY_OP_SUBSCR: { // dict load - mp_map_elem_t *elem = mp_map_lookup_helper(&o->map, rhs_in, false); + mp_map_elem_t *elem = mp_map_lookup_helper(&o->map, rhs_in, false, false); if (elem == NULL) { nlr_jump(mp_obj_new_exception_msg(MP_QSTR_KeyError, "")); } else { @@ -140,20 +140,52 @@ static mp_obj_t dict_copy(mp_obj_t self_in) { } static MP_DEFINE_CONST_FUN_OBJ_1(dict_copy_obj, dict_copy); +static mp_obj_t dict_get_helper(mp_map_t *self, mp_obj_t key, mp_obj_t deflt, bool pop) { + mp_map_elem_t *elem = mp_map_lookup_helper(self, key, false, pop); + if (elem == NULL) { + if (deflt == NULL) { + if (pop) { + nlr_jump(mp_obj_new_exception_msg(MP_QSTR_KeyError, "")); + } else { + return mp_const_none; + } + } else { + return deflt; + } + } else { + mp_obj_t value = elem->value; + if (pop) { + /* catch the leak (from mp_map_lookup_helper) */ + m_free(elem, 2 * sizeof(mp_obj_t)); + } + return value; + } + +} + static mp_obj_t dict_get(int n_args, const mp_obj_t *args) { assert(2 <= n_args && n_args <= 3); assert(MP_OBJ_IS_TYPE(args[0], &dict_type)); - mp_map_elem_t *elem = mp_map_lookup_helper(&((mp_obj_dict_t *)args[0])->map, - args[1], false); - if (elem == NULL) { - return n_args >= 3 ? args[2] : mp_const_none; - } else { - return elem->value; - } + return dict_get_helper(&((mp_obj_dict_t *)args[0])->map, + args[1], + n_args == 3 ? args[2] : NULL, + false); } static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_get_obj, 2, 3, dict_get); +static mp_obj_t dict_pop(int n_args, const mp_obj_t *args) { + assert(2 <= n_args && n_args <= 3); + assert(MP_OBJ_IS_TYPE(args[0], &dict_type)); + + return dict_get_helper(&((mp_obj_dict_t *)args[0])->map, + args[1], + n_args == 3 ? args[2] : NULL, + true); +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_pop_obj, 2, 3, dict_pop); + + /******************************************************************************/ /* dict constructors & etc */ @@ -168,6 +200,7 @@ const mp_obj_type_t dict_type = { { "clear", &dict_clear_obj }, { "copy", &dict_copy_obj }, { "get", &dict_get_obj }, + { "pop", &dict_pop_obj }, { NULL, NULL }, // end-of-list sentinel }, }; @@ -186,6 +219,6 @@ uint mp_obj_dict_len(mp_obj_t self_in) { mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value) { assert(MP_OBJ_IS_TYPE(self_in, &dict_type)); mp_obj_dict_t *self = self_in; - mp_map_lookup_helper(&self->map, key, true)->value = value; + mp_map_lookup_helper(&self->map, key, true, false)->value = value; return self_in; } diff --git a/tests/basics/tests/dict_pop.py b/tests/basics/tests/dict_pop.py new file mode 100644 index 000000000..602560ce9 --- /dev/null +++ b/tests/basics/tests/dict_pop.py @@ -0,0 +1,12 @@ +d = {1: 2, 3: 4} +print(d.pop(3), d) +print(d) +print(d.pop(1, 42), d) +print(d.pop(1, 42), d) +print(d.pop(1, None), d) +try: + print(d.pop(1), "!!!",) +except KeyError: + print("Raised KeyError") +else: + print("Did not rise KeyError!") -- cgit v1.2.3 From f77dce8a5dda13c759faeabb892d5f439dc05fd5 Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Mon, 6 Jan 2014 20:08:52 +0000 Subject: Added dict.popitem --- py/objdict.c | 21 +++++++++++++++++++++ tests/basics/tests/dict_popitem.py | 11 +++++++++++ 2 files changed, 32 insertions(+) create mode 100644 tests/basics/tests/dict_popitem.py diff --git a/py/objdict.c b/py/objdict.c index 935829ddb..b4cf8f4aa 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -186,6 +186,26 @@ static mp_obj_t dict_pop(int n_args, const mp_obj_t *args) { static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_pop_obj, 2, 3, dict_pop); + +static mp_obj_t dict_popitem(mp_obj_t self_in) { + assert(MP_OBJ_IS_TYPE(self_in, &dict_type)); + mp_obj_dict_t *self = self_in; + if (self->map.used == 0) { + nlr_jump(mp_obj_new_exception_msg(MP_QSTR_KeyError, "popitem(): dictionary is empty")); + } + mp_obj_dict_it_t *iter = mp_obj_new_dict_iterator(self, 0); + + mp_map_elem_t *next = dict_it_iternext_elem(iter); + self->map.used--; + mp_obj_t items[] = {next->key, next->value}; + next->key = NULL; + mp_obj_t tuple = mp_obj_new_tuple(2, items); + + return tuple; +} +static MP_DEFINE_CONST_FUN_OBJ_1(dict_popitem_obj, dict_popitem); + + /******************************************************************************/ /* dict constructors & etc */ @@ -201,6 +221,7 @@ const mp_obj_type_t dict_type = { { "copy", &dict_copy_obj }, { "get", &dict_get_obj }, { "pop", &dict_pop_obj }, + { "popitem", &dict_popitem_obj }, { NULL, NULL }, // end-of-list sentinel }, }; diff --git a/tests/basics/tests/dict_popitem.py b/tests/basics/tests/dict_popitem.py new file mode 100644 index 000000000..184735cde --- /dev/null +++ b/tests/basics/tests/dict_popitem.py @@ -0,0 +1,11 @@ +d={1:2,3:4} +print(d.popitem()) +print(d) +print(d.popitem()) +print(d) +try: + print(d.popitem(), "!!!",) +except KeyError: + print("Raised KeyError") +else: + print("Did not raise KeyError") -- cgit v1.2.3 From be8fe5be2eb89cd8db741b16dcb50bf5966c33ae Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Mon, 6 Jan 2014 20:25:51 +0000 Subject: Added dict.setdefault --- py/map.c | 1 + py/objdict.c | 36 +++++++++++++++++++++++++---------- tests/basics/tests/dict_setdefault.py | 13 +++++++++++++ 3 files changed, 40 insertions(+), 10 deletions(-) create mode 100644 tests/basics/tests/dict_setdefault.py diff --git a/py/map.c b/py/map.c index 8554150ad..b88181989 100644 --- a/py/map.c +++ b/py/map.c @@ -112,6 +112,7 @@ mp_map_elem_t* mp_map_lookup_helper(mp_map_t *map, mp_obj_t index, bool add_if_n retval->key = elem->key; retval->value = elem->value; elem->key = NULL; + elem->value = NULL; return retval; } return elem; diff --git a/py/objdict.c b/py/objdict.c index b4cf8f4aa..753db7d80 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -140,27 +140,30 @@ static mp_obj_t dict_copy(mp_obj_t self_in) { } static MP_DEFINE_CONST_FUN_OBJ_1(dict_copy_obj, dict_copy); -static mp_obj_t dict_get_helper(mp_map_t *self, mp_obj_t key, mp_obj_t deflt, bool pop) { - mp_map_elem_t *elem = mp_map_lookup_helper(self, key, false, pop); - if (elem == NULL) { +static mp_obj_t dict_get_helper(mp_map_t *self, mp_obj_t key, mp_obj_t deflt, bool pop, bool set) { + mp_map_elem_t *elem = mp_map_lookup_helper(self, key, set, pop); + mp_obj_t value; + if (elem == NULL || elem->value == NULL) { if (deflt == NULL) { if (pop) { nlr_jump(mp_obj_new_exception_msg(MP_QSTR_KeyError, "")); } else { - return mp_const_none; + value = mp_const_none; } } else { - return deflt; + value = deflt; } } else { - mp_obj_t value = elem->value; + value = elem->value; if (pop) { /* catch the leak (from mp_map_lookup_helper) */ m_free(elem, 2 * sizeof(mp_obj_t)); } - return value; } - + if (set) { + elem->value = value; + } + return value; } static mp_obj_t dict_get(int n_args, const mp_obj_t *args) { @@ -170,7 +173,7 @@ static mp_obj_t dict_get(int n_args, const mp_obj_t *args) { return dict_get_helper(&((mp_obj_dict_t *)args[0])->map, args[1], n_args == 3 ? args[2] : NULL, - false); + false, false); } static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_get_obj, 2, 3, dict_get); @@ -181,11 +184,22 @@ static mp_obj_t dict_pop(int n_args, const mp_obj_t *args) { return dict_get_helper(&((mp_obj_dict_t *)args[0])->map, args[1], n_args == 3 ? args[2] : NULL, - true); + true, false); } static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_pop_obj, 2, 3, dict_pop); +static mp_obj_t dict_setdefault(int n_args, const mp_obj_t *args) { + assert(2 <= n_args && n_args <= 3); + assert(MP_OBJ_IS_TYPE(args[0], &dict_type)); + + return dict_get_helper(&((mp_obj_dict_t *)args[0])->map, + args[1], + n_args == 3 ? args[2] : NULL, + false, true); +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_setdefault_obj, 2, 3, dict_setdefault); + static mp_obj_t dict_popitem(mp_obj_t self_in) { assert(MP_OBJ_IS_TYPE(self_in, &dict_type)); @@ -199,6 +213,7 @@ static mp_obj_t dict_popitem(mp_obj_t self_in) { self->map.used--; mp_obj_t items[] = {next->key, next->value}; next->key = NULL; + next->value = NULL; mp_obj_t tuple = mp_obj_new_tuple(2, items); return tuple; @@ -222,6 +237,7 @@ const mp_obj_type_t dict_type = { { "get", &dict_get_obj }, { "pop", &dict_pop_obj }, { "popitem", &dict_popitem_obj }, + { "setdefault", &dict_setdefault_obj }, { NULL, NULL }, // end-of-list sentinel }, }; diff --git a/tests/basics/tests/dict_setdefault.py b/tests/basics/tests/dict_setdefault.py new file mode 100644 index 000000000..57d0ba451 --- /dev/null +++ b/tests/basics/tests/dict_setdefault.py @@ -0,0 +1,13 @@ +d = {} +print(d.setdefault(1)) +print(d.setdefault(1)) +print(d.setdefault(5, 42)) +print(d.setdefault(5, 1)) +print(d[1]) +print(d[5]) +d.pop(5) +print(d.setdefault(5, 1)) +print(d[1]) +print(d[5]) + + -- cgit v1.2.3 From 1a9951d5aab681a4ff408d8520696b9f67b83d49 Mon Sep 17 00:00:00 2001 From: Damien George Date: Mon, 6 Jan 2014 22:13:00 +0000 Subject: py: Fix up number operations and coercion. --- examples/mandel.py | 14 ++++++++ py/asmx64.c | 2 +- py/obj.h | 2 ++ py/objcomplex.c | 70 +++++++++++++++++++------------------ py/objfloat.c | 43 +++++++++++++---------- py/runtime.c | 100 ++++++++++++++++++++++++++++------------------------- 6 files changed, 131 insertions(+), 100 deletions(-) create mode 100644 examples/mandel.py diff --git a/examples/mandel.py b/examples/mandel.py new file mode 100644 index 000000000..b13b7d87f --- /dev/null +++ b/examples/mandel.py @@ -0,0 +1,14 @@ +@micropython.native +def in_set(c): + z = 0 + for i in range(40): + z = z*z + c + if abs(z) > 60: + return False + return True + +for v in range(31): + line = [] + for u in range(91): + line.append('*' if in_set((u / 30 - 2) + (v / 15 - 1) * 1j) else ' ') + print(''.join(line)) diff --git a/py/asmx64.c b/py/asmx64.c index ed9ca80f5..226d4efee 100644 --- a/py/asmx64.c +++ b/py/asmx64.c @@ -155,7 +155,7 @@ void asm_x64_end_pass(asm_x64_t *as) { //as->code_base = m_new(byte, as->code_size); need to allocale executable memory uint actual_alloc; as->code_base = alloc_mem(as->code_size, &actual_alloc, true); - printf("code_size: %u\n", as->code_size); + //printf("code_size: %u\n", as->code_size); } /* diff --git a/py/obj.h b/py/obj.h index 88a611ba7..1ba7427cb 100644 --- a/py/obj.h +++ b/py/obj.h @@ -200,10 +200,12 @@ qstr mp_obj_str_get(mp_obj_t self_in); // float extern const mp_obj_type_t float_type; mp_float_t mp_obj_float_get(mp_obj_t self_in); +mp_obj_t mp_obj_float_binary_op(int op, mp_float_t lhs_val, mp_obj_t rhs); // complex extern const mp_obj_type_t complex_type; void mp_obj_complex_get(mp_obj_t self_in, mp_float_t *real, mp_float_t *imag); +mp_obj_t mp_obj_complex_binary_op(int op, mp_float_t lhs_real, mp_float_t lhs_imag, mp_obj_t rhs_in); #endif // tuple diff --git a/py/objcomplex.c b/py/objcomplex.c index fc32f9667..46f43b54b 100644 --- a/py/objcomplex.c +++ b/py/objcomplex.c @@ -48,14 +48,14 @@ static mp_obj_t complex_make_new(mp_obj_t type_in, int n_args, const mp_obj_t *a { mp_float_t real, imag; if (MP_OBJ_IS_TYPE(args[1], &complex_type)) { - mp_obj_get_complex(args[1], &real, &imag); + mp_obj_complex_get(args[1], &real, &imag); } else { real = mp_obj_get_float(args[1]); imag = 0; } if (MP_OBJ_IS_TYPE(args[0], &complex_type)) { mp_float_t real2, imag2; - mp_obj_get_complex(args[0], &real2, &imag2); + mp_obj_complex_get(args[0], &real2, &imag2); real -= imag2; imag += real2; } else { @@ -80,9 +80,41 @@ static mp_obj_t complex_unary_op(int op, mp_obj_t o_in) { } static mp_obj_t complex_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) { - mp_float_t lhs_real, lhs_imag, rhs_real, rhs_imag; - mp_obj_complex_get(lhs_in, &lhs_real, &lhs_imag); - mp_obj_complex_get(rhs_in, &rhs_real, &rhs_imag); + mp_obj_complex_t *lhs = lhs_in; + return mp_obj_complex_binary_op(op, lhs->real, lhs->imag, rhs_in); +} + +const mp_obj_type_t complex_type = { + { &mp_const_type }, + "complex", + complex_print, // print + complex_make_new, // make_new + NULL, // call_n + complex_unary_op, // unary_op + complex_binary_op, // binary_op + NULL, // getiter + NULL, // iternext + .methods = { { NULL, NULL }, }, +}; + +mp_obj_t mp_obj_new_complex(mp_float_t real, mp_float_t imag) { + mp_obj_complex_t *o = m_new_obj(mp_obj_complex_t); + o->base.type = &complex_type; + o->real = real; + o->imag = imag; + return o; +} + +void mp_obj_complex_get(mp_obj_t self_in, mp_float_t *real, mp_float_t *imag) { + assert(MP_OBJ_IS_TYPE(self_in, &complex_type)); + mp_obj_complex_t *self = self_in; + *real = self->real; + *imag = self->imag; +} + +mp_obj_t mp_obj_complex_binary_op(int op, mp_float_t lhs_real, mp_float_t lhs_imag, mp_obj_t rhs_in) { + mp_float_t rhs_real, rhs_imag; + mp_obj_get_complex(rhs_in, &rhs_real, &rhs_imag); // can be any type, this function will convert to float (if possible) switch (op) { case RT_BINARY_OP_ADD: case RT_BINARY_OP_INPLACE_ADD: @@ -115,32 +147,4 @@ static mp_obj_t complex_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) { return mp_obj_new_complex(lhs_real, lhs_imag); } -const mp_obj_type_t complex_type = { - { &mp_const_type }, - "complex", - complex_print, // print - complex_make_new, // make_new - NULL, // call_n - complex_unary_op, // unary_op - complex_binary_op, // binary_op - NULL, // getiter - NULL, // iternext - .methods = { { NULL, NULL }, }, -}; - -mp_obj_t mp_obj_new_complex(mp_float_t real, mp_float_t imag) { - mp_obj_complex_t *o = m_new_obj(mp_obj_complex_t); - o->base.type = &complex_type; - o->real = real; - o->imag = imag; - return o; -} - -void mp_obj_complex_get(mp_obj_t self_in, mp_float_t *real, mp_float_t *imag) { - assert(MP_OBJ_IS_TYPE(self_in, &complex_type)); - mp_obj_complex_t *self = self_in; - *real = self->real; - *imag = self->imag; -} - #endif diff --git a/py/objfloat.c b/py/objfloat.c index 0250172ad..336ae597f 100644 --- a/py/objfloat.c +++ b/py/objfloat.c @@ -53,27 +53,12 @@ static mp_obj_t float_unary_op(int op, mp_obj_t o_in) { } static mp_obj_t float_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) { + mp_obj_float_t *lhs = lhs_in; if (MP_OBJ_IS_TYPE(rhs_in, &complex_type)) { - return complex_type.binary_op(op, lhs_in, rhs_in); + return mp_obj_complex_binary_op(op, lhs->value, 0, rhs_in); + } else { + return mp_obj_float_binary_op(op, lhs->value, rhs_in); } - mp_float_t lhs_val = mp_obj_get_float(lhs_in); - mp_float_t rhs_val = mp_obj_get_float(rhs_in); - switch (op) { - case RT_BINARY_OP_ADD: - case RT_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break; - case RT_BINARY_OP_SUBTRACT: - case RT_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break; - case RT_BINARY_OP_MULTIPLY: - case RT_BINARY_OP_INPLACE_MULTIPLY: lhs_val *= rhs_val; break; - /* TODO floor(?) the value - case RT_BINARY_OP_FLOOR_DIVIDE: - case RT_BINARY_OP_INPLACE_FLOOR_DIVIDE: val = lhs_val / rhs_val; break; - */ - case RT_BINARY_OP_TRUE_DIVIDE: - case RT_BINARY_OP_INPLACE_TRUE_DIVIDE: lhs_val /= rhs_val; break; - return NULL; // op not supported - } - return mp_obj_new_float(lhs_val); } const mp_obj_type_t float_type = { @@ -99,4 +84,24 @@ mp_float_t mp_obj_float_get(mp_obj_t self_in) { return self->value; } +mp_obj_t mp_obj_float_binary_op(int op, mp_float_t lhs_val, mp_obj_t rhs_in) { + mp_float_t rhs_val = mp_obj_get_float(rhs_in); // can be any type, this function will convert to float (if possible) + switch (op) { + case RT_BINARY_OP_ADD: + case RT_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break; + case RT_BINARY_OP_SUBTRACT: + case RT_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break; + case RT_BINARY_OP_MULTIPLY: + case RT_BINARY_OP_INPLACE_MULTIPLY: lhs_val *= rhs_val; break; + /* TODO floor(?) the value + case RT_BINARY_OP_FLOOR_DIVIDE: + case RT_BINARY_OP_INPLACE_FLOOR_DIVIDE: val = lhs_val / rhs_val; break; + */ + case RT_BINARY_OP_TRUE_DIVIDE: + case RT_BINARY_OP_INPLACE_TRUE_DIVIDE: lhs_val /= rhs_val; break; + return NULL; // op not supported + } + return mp_obj_new_float(lhs_val); +} + #endif diff --git a/py/runtime.c b/py/runtime.c index 197c08b55..6bc71abff 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -452,57 +452,63 @@ mp_obj_t rt_binary_op(int op, mp_obj_t lhs, mp_obj_t rhs) { // then fail // note that list does not implement + or +=, so that inplace_concat is reached first for += - if (MP_OBJ_IS_SMALL_INT(lhs) && MP_OBJ_IS_SMALL_INT(rhs)) { + if (MP_OBJ_IS_SMALL_INT(lhs)) { mp_small_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs); - mp_small_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs); - switch (op) { - case RT_BINARY_OP_OR: - case RT_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break; - case RT_BINARY_OP_XOR: - case RT_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break; - case RT_BINARY_OP_AND: - case RT_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break; - case RT_BINARY_OP_LSHIFT: - case RT_BINARY_OP_INPLACE_LSHIFT: lhs_val <<= rhs_val; break; - case RT_BINARY_OP_RSHIFT: - case RT_BINARY_OP_INPLACE_RSHIFT: lhs_val >>= rhs_val; break; - case RT_BINARY_OP_ADD: - case RT_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break; - case RT_BINARY_OP_SUBTRACT: - case RT_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break; - case RT_BINARY_OP_MULTIPLY: - case RT_BINARY_OP_INPLACE_MULTIPLY: lhs_val *= rhs_val; break; - case RT_BINARY_OP_FLOOR_DIVIDE: - case RT_BINARY_OP_INPLACE_FLOOR_DIVIDE: lhs_val /= rhs_val; break; -#if MICROPY_ENABLE_FLOAT - case RT_BINARY_OP_TRUE_DIVIDE: - case RT_BINARY_OP_INPLACE_TRUE_DIVIDE: return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val); -#endif - - // TODO implement modulo as specified by Python - case RT_BINARY_OP_MODULO: - case RT_BINARY_OP_INPLACE_MODULO: lhs_val %= rhs_val; break; - - // TODO check for negative power, and overflow - case RT_BINARY_OP_POWER: - case RT_BINARY_OP_INPLACE_POWER: - { - int ans = 1; - while (rhs_val > 0) { - if (rhs_val & 1) { - ans *= lhs_val; + if (MP_OBJ_IS_SMALL_INT(rhs)) { + mp_small_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs); + switch (op) { + case RT_BINARY_OP_OR: + case RT_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break; + case RT_BINARY_OP_XOR: + case RT_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break; + case RT_BINARY_OP_AND: + case RT_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break; + case RT_BINARY_OP_LSHIFT: + case RT_BINARY_OP_INPLACE_LSHIFT: lhs_val <<= rhs_val; break; + case RT_BINARY_OP_RSHIFT: + case RT_BINARY_OP_INPLACE_RSHIFT: lhs_val >>= rhs_val; break; + case RT_BINARY_OP_ADD: + case RT_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break; + case RT_BINARY_OP_SUBTRACT: + case RT_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break; + case RT_BINARY_OP_MULTIPLY: + case RT_BINARY_OP_INPLACE_MULTIPLY: lhs_val *= rhs_val; break; + case RT_BINARY_OP_FLOOR_DIVIDE: + case RT_BINARY_OP_INPLACE_FLOOR_DIVIDE: lhs_val /= rhs_val; break; + #if MICROPY_ENABLE_FLOAT + case RT_BINARY_OP_TRUE_DIVIDE: + case RT_BINARY_OP_INPLACE_TRUE_DIVIDE: return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val); + #endif + + // TODO implement modulo as specified by Python + case RT_BINARY_OP_MODULO: + case RT_BINARY_OP_INPLACE_MODULO: lhs_val %= rhs_val; break; + + // TODO check for negative power, and overflow + case RT_BINARY_OP_POWER: + case RT_BINARY_OP_INPLACE_POWER: + { + int ans = 1; + while (rhs_val > 0) { + if (rhs_val & 1) { + ans *= lhs_val; + } + lhs_val *= lhs_val; + rhs_val /= 2; } - lhs_val *= lhs_val; - rhs_val /= 2; + lhs_val = ans; + break; } - lhs_val = ans; - break; - } - default: assert(0); - } - if (fit_small_int(lhs_val)) { - return MP_OBJ_NEW_SMALL_INT(lhs_val); + default: assert(0); + } + if (fit_small_int(lhs_val)) { + return MP_OBJ_NEW_SMALL_INT(lhs_val); + } + } else if (MP_OBJ_IS_TYPE(rhs, &float_type)) { + return mp_obj_float_binary_op(op, lhs_val, rhs); + } else if (MP_OBJ_IS_TYPE(rhs, &complex_type)) { + return mp_obj_complex_binary_op(op, lhs_val, 0, rhs); } } else if (MP_OBJ_IS_OBJ(lhs)) { mp_obj_base_t *o = lhs; -- cgit v1.2.3 From e3096172c90fb1223f99bc6f957322009c79c36f Mon Sep 17 00:00:00 2001 From: Damien George Date: Mon, 6 Jan 2014 22:17:37 +0000 Subject: stm: Re-fix LED defines. --- stm/led.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/stm/led.c b/stm/led.c index 19ce99cec..d4bc0a0c8 100644 --- a/stm/led.c +++ b/stm/led.c @@ -8,10 +8,10 @@ #include "led.h" /* LED numbers, used internally */ -#define PYB_LED_1 (0) -#define PYB_LED_2 (1) -#define PYB_LED_3 (2) -#define PYB_LED_4 (3) +#define PYB_LED_1 (1) +#define PYB_LED_2 (2) +#define PYB_LED_3 (3) +#define PYB_LED_4 (4) #if defined(PYBOARD) #define PYB_LED1_PORT (GPIOA) -- cgit v1.2.3 From 88f3043e0a306b17d3b9bdf530da51a66ba1cccc Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Mon, 6 Jan 2014 22:58:17 +0000 Subject: added a first pass of dict.update --- py/objdict.c | 29 ++++++++++++++++++++++++++++- py/runtime.c | 4 ++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/py/objdict.c b/py/objdict.c index 753db7d80..7cfd597ed 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -157,7 +157,7 @@ static mp_obj_t dict_get_helper(mp_map_t *self, mp_obj_t key, mp_obj_t deflt, bo value = elem->value; if (pop) { /* catch the leak (from mp_map_lookup_helper) */ - m_free(elem, 2 * sizeof(mp_obj_t)); + m_free(elem, sizeof(mp_map_elem_t)); } } if (set) { @@ -220,6 +220,32 @@ static mp_obj_t dict_popitem(mp_obj_t self_in) { } static MP_DEFINE_CONST_FUN_OBJ_1(dict_popitem_obj, dict_popitem); +static mp_obj_t dict_update(mp_obj_t self_in, mp_obj_t iterable) { + assert(MP_OBJ_IS_TYPE(self_in, &dict_type)); + mp_obj_dict_t *self = self_in; + /* TODO: check for the "keys" method */ + mp_obj_t iter = rt_getiter(iterable); + mp_obj_t next = NULL; + while ((next = rt_iternext(iter)) != mp_const_stop_iteration) { + mp_obj_t inneriter = rt_getiter(next); + mp_obj_t key = rt_iternext(inneriter); + mp_obj_t value = rt_iternext(inneriter); + mp_obj_t stop = rt_iternext(inneriter); + if (key == mp_const_stop_iteration + || value == mp_const_stop_iteration + || stop != mp_const_stop_iteration) { + nlr_jump(mp_obj_new_exception_msg( + MP_QSTR_ValueError, + "dictionary update sequence has the wrong length")); + } else { + mp_map_lookup_helper(&self->map, key, true, false)->value = value; + } + } + + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(dict_update_obj, dict_update); + /******************************************************************************/ /* dict constructors & etc */ @@ -238,6 +264,7 @@ const mp_obj_type_t dict_type = { { "pop", &dict_pop_obj }, { "popitem", &dict_popitem_obj }, { "setdefault", &dict_setdefault_obj }, + { "update", &dict_update_obj }, { NULL, NULL }, // end-of-list sentinel }, }; diff --git a/py/runtime.c b/py/runtime.c index 6bc71abff..f3fabc39c 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -859,13 +859,13 @@ mp_obj_t rt_getiter(mp_obj_t o_in) { mp_obj_t rt_iternext(mp_obj_t o_in) { if (MP_OBJ_IS_SMALL_INT(o_in)) { - nlr_jump(mp_obj_new_exception_msg(MP_QSTR_TypeError, "? 'int' object is not iterable")); + nlr_jump(mp_obj_new_exception_msg(MP_QSTR_TypeError, "'int' object is not an iterator")); } else { mp_obj_base_t *o = o_in; if (o->type->iternext != NULL) { return o->type->iternext(o_in); } else { - nlr_jump(mp_obj_new_exception_msg_1_arg(MP_QSTR_TypeError, "? '%s' object is not iterable", o->type->name)); + nlr_jump(mp_obj_new_exception_msg_1_arg(MP_QSTR_TypeError, "'%s' object is not an iterator", o->type->name)); } } } -- cgit v1.2.3 From 27d4ca7693c276d09a911c00c3442729c516dc23 Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Tue, 7 Jan 2014 22:51:51 +0000 Subject: forgot to add test for dict.update --- tests/basics/tests/dict_update.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 tests/basics/tests/dict_update.py diff --git a/tests/basics/tests/dict_update.py b/tests/basics/tests/dict_update.py new file mode 100644 index 000000000..e7ae0bd96 --- /dev/null +++ b/tests/basics/tests/dict_update.py @@ -0,0 +1,10 @@ +d = {1:2, 3:4} +print(d) +d.update(["ab"]) +print(d[1]) +print(d[3]) +print(d["a"]) +print(len(d)) +d.update([(1,4)]) +print(d[1]) +print(len(d)) -- cgit v1.2.3 From 9c83ec0edac2394431a5d1aecba1d666ffdea0a3 Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Tue, 7 Jan 2014 23:06:46 +0000 Subject: Merge remote-tracking branch 'upstream/master' into dict_feats --- examples/accellog.py | 14 + examples/conwaylife.py | 43 + examples/lcd.py | 36 + examples/ledangle.py | 22 + examples/mandel.py | 32 +- examples/pyb.py | 11 + logo/vector-logo-2-BW.svg | 587 ++++++++++++++ logo/vector-logo-2.png | Bin 0 -> 90783 bytes logo/vector-logo-inkscape_master.svg | 1471 ++++++++++++++++++++++++++++++++++ py/asmx64.c | 8 +- py/gc.c | 4 + py/lexerunix.c | 5 + py/misc.h | 6 +- py/mpconfig.h | 85 +- py/mpqstrraw.h | 1 + py/obj.h | 47 +- py/objbool.c | 10 +- py/objboundmeth.c | 9 +- py/objcell.c | 8 - py/objclass.c | 9 +- py/objclosure.c | 9 +- py/objcomplex.c | 12 +- py/objexcept.c | 9 +- py/objfloat.c | 1 - py/objfun.c | 56 +- py/objgenerator.c | 20 +- py/objinstance.c | 8 - py/objint.c | 1 - py/objlist.c | 68 +- py/objmodule.c | 13 +- py/objnone.c | 1 - py/objrange.c | 18 +- py/objset.c | 10 +- py/objslice.c | 10 +- py/objstr.c | 13 +- py/objtuple.c | 6 +- py/objtype.c | 1 - py/py.mk | 105 +++ py/repl.c | 5 + py/repl.h | 2 + py/runtime.c | 62 +- py/showbc.c | 4 + stm/Makefile | 95 +-- stm/i2c.c | 18 +- stm/led.c | 12 +- stm/main.c | 22 +- stm/mpconfigport.h | 6 +- stm/servo.c | 10 +- tests/basics/tests/list_sort.py | 13 + unix-cpy/Makefile | 94 +-- unix-cpy/main.c | 1 - unix-cpy/mpconfigport.h | 6 +- unix/Makefile | 99 +-- unix/main.c | 163 ++-- unix/mpconfigport.h | 6 +- 55 files changed, 2760 insertions(+), 627 deletions(-) create mode 100644 examples/accellog.py create mode 100644 examples/conwaylife.py create mode 100644 examples/lcd.py create mode 100644 examples/ledangle.py create mode 100644 examples/pyb.py create mode 100644 logo/vector-logo-2-BW.svg create mode 100644 logo/vector-logo-2.png create mode 100644 logo/vector-logo-inkscape_master.svg create mode 100644 py/py.mk create mode 100644 tests/basics/tests/list_sort.py diff --git a/examples/accellog.py b/examples/accellog.py new file mode 100644 index 000000000..81f44f19a --- /dev/null +++ b/examples/accellog.py @@ -0,0 +1,14 @@ +# log the accelerometer values to a file, 1 per second + +f = open('motion.dat', 'w') # open the file for writing + +for i in range(60): # loop 60 times + time = pyb.time() # get the current time + accel = pyb.accel() # get the accelerometer data + + # write time and x,y,z values to the file + f.write('{} {} {} {}\n'.format(time, accel[0], accel[1], accel[2])) + + pyb.delay(1000) # wait 1000 ms = 1 second + +f.close() # close the file diff --git a/examples/conwaylife.py b/examples/conwaylife.py new file mode 100644 index 000000000..fb62ce69e --- /dev/null +++ b/examples/conwaylife.py @@ -0,0 +1,43 @@ +# do 1 iteration of Conway's Game of Life +def conway_step(): + for x in range(128): # loop over x coordinates + for y in range(32): # loop over y coordinates + # count number of neigbours + num_neighbours = (lcd.get(x - 1, y - 1) + + lcd.get(x, y - 1) + + lcd.get(x + 1, y - 1) + + lcd.get(x - 1, y) + + lcd.get(x + 1, y) + + lcd.get(x + 1, y + 1) + + lcd.get(x, y + 1) + + lcd.get(x - 1, y + 1)) + + # check if the centre cell is alive or not + self = lcd.get(x, y) + + # apply the rules of life + if self and not (2 <= num_neighbours <= 3): + lcd.reset(x, y) # not enough, or too many neighbours: cell dies + elif not self and num_neighbours == 3: + lcd.set(x, y) # exactly 3 neigbours around an empty cell: cell is born + +# randomise the start +def conway_rand(): + lcd.clear() # clear the LCD + for x in range(128): # loop over x coordinates + for y in range(32): # loop over y coordinates + if pyb.rand() & 1: # get a 1-bit random number + lcd.set(x, y) # set the pixel randomly + +# loop for a certain number of frames, doing iterations of Conway's Game of Life +def conway_go(num_frames): + for i in range(num_frames): + conway_step() # do 1 iteration + lcd.show() # update the LCD + +# PC testing +import lcd +import pyb +lcd = lcd.LCD(128, 32) +conway_rand() +conway_go(100) diff --git a/examples/lcd.py b/examples/lcd.py new file mode 100644 index 000000000..3303337bf --- /dev/null +++ b/examples/lcd.py @@ -0,0 +1,36 @@ +# LCD testing object for PC +# uses double buffering +class LCD: + def __init__(self, width, height): + self.width = width + self.height = height + self.buf1 = [[0 for x in range(self.width)] for y in range(self.height)] + self.buf2 = [[0 for x in range(self.width)] for y in range(self.height)] + + def clear(self): + for y in range(self.height): + for x in range(self.width): + self.buf1[y][x] = self.buf2[y][x] = 0 + + def show(self): + print('') # blank line to separate frames + for y in range(self.height): + for x in range(self.width): + self.buf1[y][x] = self.buf2[y][x] + for y in range(self.height): + row = ''.join(['*' if self.buf1[y][x] else ' ' for x in range(self.width)]) + print(row) + + def get(self, x, y): + if 0 <= x < self.width and 0 <= y < self.height: + return self.buf1[y][x] + else: + return 0 + + def reset(self, x, y): + if 0 <= x < self.width and 0 <= y < self.height: + self.buf2[y][x] = 0 + + def set(self, x, y): + if 0 <= x < self.width and 0 <= y < self.height: + self.buf2[y][x] = 1 diff --git a/examples/ledangle.py b/examples/ledangle.py new file mode 100644 index 000000000..35c9148a4 --- /dev/null +++ b/examples/ledangle.py @@ -0,0 +1,22 @@ +def led_angle(seconds_to_run_for): + # make LED objects + l1 = pyb.Led(1) + l2 = pyb.Led(2) + + for i in range(20 * seconds_to_run_for): + # get x-axis + accel = pyb.accel()[0] + + # turn on LEDs depending on angle + if accel < -10: + l1.on() + l2.off() + elif accel > 10: + l1.off() + l2.on() + else: + l1.off() + l2.off() + + # delay so that loop runs at at 1/50ms = 20Hz + pyb.delay(50) diff --git a/examples/mandel.py b/examples/mandel.py index b13b7d87f..996132a91 100644 --- a/examples/mandel.py +++ b/examples/mandel.py @@ -1,14 +1,22 @@ -@micropython.native -def in_set(c): - z = 0 - for i in range(40): - z = z*z + c - if abs(z) > 60: - return False - return True +def mandelbrot(): + # returns True if c, complex, is in the Mandelbrot set + @micropython.native + def in_set(c): + z = 0 + for i in range(40): + z = z*z + c + if abs(z) > 60: + return False + return True -for v in range(31): - line = [] + lcd.clear() for u in range(91): - line.append('*' if in_set((u / 30 - 2) + (v / 15 - 1) * 1j) else ' ') - print(''.join(line)) + for v in range(31): + if in_set((u / 30 - 2) + (v / 15 - 1) * 1j): + lcd.set(u, v) + lcd.show() + +# PC testing +import lcd +lcd = lcd.LCD(128, 32) +mandelbrot() diff --git a/examples/pyb.py b/examples/pyb.py new file mode 100644 index 000000000..5e24f40e4 --- /dev/null +++ b/examples/pyb.py @@ -0,0 +1,11 @@ +# pyboard testing functions for PC + +def delay(n): + pass + +rand_seed = 1 +def rand(): + global rand_seed + # for these choice of numbers, see P L'Ecuyer, "Tables of linear congruential generators of different sizes and good lattice structure" + rand_seed = (rand_seed * 653276) % 8388593 + return rand_seed diff --git a/logo/vector-logo-2-BW.svg b/logo/vector-logo-2-BW.svg new file mode 100644 index 000000000..d7ff920f9 --- /dev/null +++ b/logo/vector-logo-2-BW.svg @@ -0,0 +1,587 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/logo/vector-logo-2.png b/logo/vector-logo-2.png new file mode 100644 index 000000000..3ad2383ff Binary files /dev/null and b/logo/vector-logo-2.png differ diff --git a/logo/vector-logo-inkscape_master.svg b/logo/vector-logo-inkscape_master.svg new file mode 100644 index 000000000..19415d41b --- /dev/null +++ b/logo/vector-logo-inkscape_master.svg @@ -0,0 +1,1471 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/py/asmx64.c b/py/asmx64.c index 226d4efee..d3158170f 100644 --- a/py/asmx64.c +++ b/py/asmx64.c @@ -1,16 +1,18 @@ #include #include -#include -#include #include #include "misc.h" -#include "asmx64.h" #include "mpconfig.h" // wrapper around everything in this file #if MICROPY_EMIT_X64 +#include +#include + +#include "asmx64.h" + #if defined(__OpenBSD__) || defined(__MACH__) #define MAP_ANONYMOUS MAP_ANON #endif diff --git a/py/gc.c b/py/gc.c index 7d4cac6e7..054a3cc31 100644 --- a/py/gc.c +++ b/py/gc.c @@ -6,6 +6,8 @@ #include "mpconfig.h" #include "gc.h" +#if MICROPY_ENABLE_GC + // a machine word is big enough to hold a pointer /* #define BYTES_PER_WORD (8) @@ -380,3 +382,5 @@ int main(void) { gc_dump_at(); } */ + +#endif // MICROPY_ENABLE_GC diff --git a/py/lexerunix.c b/py/lexerunix.c index 14c28c16d..5336610ba 100644 --- a/py/lexerunix.c +++ b/py/lexerunix.c @@ -4,8 +4,11 @@ #include #include "misc.h" +#include "mpconfig.h" #include "lexer.h" +#if MICROPY_ENABLE_LEXER_UNIX + typedef struct _str_buf_t { bool free; // free src_beg when done const char *src_beg; // beginning of source @@ -78,3 +81,5 @@ mp_lexer_t *mp_import_open_file(qstr mod_name) { vstr_printf(vstr, "%s.py", qstr_str(mod_name)); return mp_lexer_new_from_file(vstr_str(vstr)); // TODO does lexer need to copy the string? can we free it here? } + +#endif // MICROPY_ENABLE_LEXER_UNIX diff --git a/py/misc.h b/py/misc.h index 153218ba2..1bf4d8f29 100644 --- a/py/misc.h +++ b/py/misc.h @@ -5,11 +5,7 @@ /** types *******************************************************/ -typedef int bool; -enum { - false = 0, - true = 1 -}; +#include typedef unsigned char byte; typedef unsigned int uint; diff --git a/py/mpconfig.h b/py/mpconfig.h index 56495d915..2017ba366 100644 --- a/py/mpconfig.h +++ b/py/mpconfig.h @@ -4,26 +4,67 @@ #include -#ifndef INT_FMT -// printf format spec to use for machine_int_t and friends -#ifdef __LP64__ -// Archs where machine_int_t == long, long != int -#define UINT_FMT "%lu" -#define INT_FMT "%ld" -#else -// Archs where machine_int_t == int -#define UINT_FMT "%u" -#define INT_FMT "%d" +// Any options not explicitly set in mpconfigport.h will get default +// values below. + +/*****************************************************************************/ +/* Micro Python emitters */ + +// Whether to emit CPython byte codes (for debugging/testing) +// Enabling this overrides all other emitters +#ifndef MICROPY_EMIT_CPYTHON +#define MICROPY_EMIT_CPYTHON (0) #endif -#endif //INT_FMT +// Whether to emit x64 native code +#ifndef MICROPY_EMIT_X64 +#define MICROPY_EMIT_X64 (0) +#endif -// Any options not explicitly set in mpconfigport.h will get default -// values below. +// Whether to emit thumb native code +#ifndef MICROPY_EMIT_THUMB +#define MICROPY_EMIT_THUMB (0) +#endif + +// Whether to enable the thumb inline assembler +#ifndef MICROPY_EMIT_INLINE_THUMB +#define MICROPY_EMIT_INLINE_THUMB (0) +#endif + +/*****************************************************************************/ +/* Internal debugging stuff */ // Whether to collect memory allocation stats #ifndef MICROPY_MEM_STATS -#define MICROPY_MEM_STATS (1) +#define MICROPY_MEM_STATS (0) +#endif + +// Whether to build code to show byte code +#ifndef MICROPY_SHOW_BC +#define MICROPY_SHOW_BC (0) +#endif + +/*****************************************************************************/ +/* Fine control over Python features */ + +// Whether to include the garbage collector +#ifndef MICROPY_ENABLE_GC +#define MICROPY_ENABLE_GC (0) +#endif + +// Whether to include REPL helper function +#ifndef MICROPY_ENABLE_REPL_HELPERS +#define MICROPY_ENABLE_REPL_HELPERS (0) +#endif + +// Whether to include lexer helper function for unix +#ifndef MICROPY_ENABLE_LEXER_UNIX +#define MICROPY_ENABLE_LEXER_UNIX (0) +#endif + +// Whether to support float and complex types +#ifndef MICROPY_ENABLE_FLOAT +#define MICROPY_ENABLE_FLOAT (0) #endif // Whether to support slice object and correspondingly @@ -31,3 +72,19 @@ #ifndef MICROPY_ENABLE_SLICE #define MICROPY_ENABLE_SLICE (1) #endif + +/*****************************************************************************/ +/* Miscellaneous settings */ + +// printf format spec to use for machine_int_t and friends +#ifndef INT_FMT +#ifdef __LP64__ +// Archs where machine_int_t == long, long != int +#define UINT_FMT "%lu" +#define INT_FMT "%ld" +#else +// Archs where machine_int_t == int +#define UINT_FMT "%u" +#define INT_FMT "%d" +#endif +#endif //INT_FMT diff --git a/py/mpqstrraw.h b/py/mpqstrraw.h index fe74c3e92..eeed6f3a0 100644 --- a/py/mpqstrraw.h +++ b/py/mpqstrraw.h @@ -30,6 +30,7 @@ Q(NameError) Q(SyntaxError) Q(TypeError) Q(ValueError) +Q(OSError) Q(abs) Q(all) diff --git a/py/obj.h b/py/obj.h index 1ba7427cb..332867a19 100644 --- a/py/obj.h +++ b/py/obj.h @@ -15,15 +15,14 @@ typedef machine_int_t mp_small_int_t; typedef machine_float_t mp_float_t; #endif -// Anything that wants to be a Micro Python object must -// have mp_obj_base_t as its first member (except NULL and small ints) - -typedef struct _mp_obj_base_t mp_obj_base_t; -typedef struct _mp_obj_type_t mp_obj_type_t; +// Anything that wants to be a Micro Python object must have +// mp_obj_base_t as its first member (except NULL and small ints) +struct _mp_obj_type_t; struct _mp_obj_base_t { - const mp_obj_type_t *type; + const struct _mp_obj_type_t *type; }; +typedef struct _mp_obj_base_t mp_obj_base_t; // The NULL object is used to indicate the absence of an object // It *cannot* be used when an mp_obj_t is expected, except where explicitly allowed @@ -43,12 +42,17 @@ struct _mp_obj_base_t { #define MP_DECLARE_CONST_FUN_OBJ(obj_name) extern const mp_obj_fun_native_t obj_name -#define MP_DEFINE_CONST_FUN_OBJ_0(obj_name, fun_name) const mp_obj_fun_native_t obj_name = {{&fun_native_type}, 0, 0, fun_name} -#define MP_DEFINE_CONST_FUN_OBJ_1(obj_name, fun_name) const mp_obj_fun_native_t obj_name = {{&fun_native_type}, 1, 1, fun_name} -#define MP_DEFINE_CONST_FUN_OBJ_2(obj_name, fun_name) const mp_obj_fun_native_t obj_name = {{&fun_native_type}, 2, 2, fun_name} -#define MP_DEFINE_CONST_FUN_OBJ_3(obj_name, fun_name) const mp_obj_fun_native_t obj_name = {{&fun_native_type}, 3, 3, fun_name} -#define MP_DEFINE_CONST_FUN_OBJ_VAR(obj_name, n_args_min, fun_name) const mp_obj_fun_native_t obj_name = {{&fun_native_type}, n_args_min, (~((machine_uint_t)0)), fun_name} -#define MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(obj_name, n_args_min, n_args_max, fun_name) const mp_obj_fun_native_t obj_name = {{&fun_native_type}, n_args_min, n_args_max, fun_name} +#define MP_DEFINE_CONST_FUN_OBJ_VOID_PTR(obj_name, is_kw, n_args_min, n_args_max, fun_name) const mp_obj_fun_native_t obj_name = {{&fun_native_type}, is_kw, n_args_min, n_args_max, (void *)fun_name} +#define MP_DEFINE_CONST_FUN_OBJ_0(obj_name, fun_name) MP_DEFINE_CONST_FUN_OBJ_VOID_PTR(obj_name, false, 0, 0, (mp_fun_0_t)fun_name) +#define MP_DEFINE_CONST_FUN_OBJ_1(obj_name, fun_name) MP_DEFINE_CONST_FUN_OBJ_VOID_PTR(obj_name, false, 1, 1, (mp_fun_1_t)fun_name) +#define MP_DEFINE_CONST_FUN_OBJ_2(obj_name, fun_name) MP_DEFINE_CONST_FUN_OBJ_VOID_PTR(obj_name, false, 2, 2, (mp_fun_2_t)fun_name) +#define MP_DEFINE_CONST_FUN_OBJ_3(obj_name, fun_name) MP_DEFINE_CONST_FUN_OBJ_VOID_PTR(obj_name, false, 3, 3, (mp_fun_3_t)fun_name) +#define MP_DEFINE_CONST_FUN_OBJ_VAR(obj_name, n_args_min, fun_name) MP_DEFINE_CONST_FUN_OBJ_VOID_PTR(obj_name, false, n_args_min, (~((machine_uint_t)0)), (mp_fun_var_t)fun_name) +#define MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(obj_name, n_args_min, n_args_max, fun_name) MP_DEFINE_CONST_FUN_OBJ_VOID_PTR(obj_name, false, n_args_min, n_args_max, (mp_fun_var_t)fun_name) +#define MP_DEFINE_CONST_FUN_OBJ_KW(obj_name, fun_name) MP_DEFINE_CONST_FUN_OBJ_VOID_PTR(obj_name, true, 0, (~((machine_uint_t)0)), (mp_fun_var_t)fun_name) + +// Need to declare this here so we are not dependent on map.h +struct _mp_map_t; // Type definitions for methods @@ -58,10 +62,12 @@ typedef mp_obj_t (*mp_fun_2_t)(mp_obj_t, mp_obj_t); typedef mp_obj_t (*mp_fun_3_t)(mp_obj_t, mp_obj_t, mp_obj_t); typedef mp_obj_t (*mp_fun_t)(void); typedef mp_obj_t (*mp_fun_var_t)(int n, const mp_obj_t *); +typedef mp_obj_t (*mp_fun_kw_t)(mp_obj_t*, struct _mp_map_t*); typedef void (*mp_print_fun_t)(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t o); typedef mp_obj_t (*mp_make_new_fun_t)(mp_obj_t type_in, int n_args, const mp_obj_t *args); // args are in reverse order in the array typedef mp_obj_t (*mp_call_n_fun_t)(mp_obj_t fun, int n_args, const mp_obj_t *args); // args are in reverse order in the array +typedef mp_obj_t (*mp_call_n_kw_fun_t)(mp_obj_t fun, int n_args, int n_kw, const mp_obj_t *args); // args are in reverse order in the array typedef mp_obj_t (*mp_unary_op_fun_t)(int op, mp_obj_t); typedef mp_obj_t (*mp_binary_op_fun_t)(int op, mp_obj_t, mp_obj_t); @@ -77,13 +83,14 @@ struct _mp_obj_type_t { mp_make_new_fun_t make_new; // to make an instance of the type mp_call_n_fun_t call_n; + mp_call_n_kw_fun_t call_n_kw; mp_unary_op_fun_t unary_op; // can return NULL if op not supported mp_binary_op_fun_t binary_op; // can return NULL if op not supported mp_fun_1_t getiter; mp_fun_1_t iternext; - const mp_method_t methods[]; + const mp_method_t *methods; /* What we might need to add here: @@ -108,6 +115,8 @@ struct _mp_obj_type_t { */ }; +typedef struct _mp_obj_type_t mp_obj_type_t; + // Constant objects, globally accessible extern const mp_obj_type_t mp_const_type; @@ -118,10 +127,6 @@ extern const mp_obj_t mp_const_empty_tuple; extern const mp_obj_t mp_const_ellipsis; extern const mp_obj_t mp_const_stop_iteration; // special object indicating end of iteration (not StopIteration exception!) -// Need to declare this here so we are not dependent on map.h - -struct _mp_map_t; - // General API for objects mp_obj_t mp_obj_new_none(void); @@ -144,8 +149,8 @@ mp_obj_t mp_obj_new_fun_asm(uint n_args, void *fun); mp_obj_t mp_obj_new_gen_wrap(uint n_locals, uint n_stack, mp_obj_t fun); mp_obj_t mp_obj_new_gen_instance(const byte *bytecode, uint n_state, int n_args, const mp_obj_t *args); mp_obj_t mp_obj_new_closure(mp_obj_t fun, mp_obj_t closure_tuple); -mp_obj_t mp_obj_new_tuple(uint n, mp_obj_t *items); -mp_obj_t mp_obj_new_tuple_reverse(uint n, mp_obj_t *items); +mp_obj_t mp_obj_new_tuple(uint n, const mp_obj_t *items); +mp_obj_t mp_obj_new_tuple_reverse(uint n, const mp_obj_t *items); mp_obj_t mp_obj_new_list(uint n, mp_obj_t *items); mp_obj_t mp_obj_new_list_reverse(uint n, mp_obj_t *items); mp_obj_t mp_obj_new_dict(int n_args); @@ -234,13 +239,15 @@ void mp_obj_slice_get(mp_obj_t self_in, machine_int_t *start, machine_int_t *sto // functions typedef struct _mp_obj_fun_native_t { // need this so we can define const objects (to go in ROM) mp_obj_base_t base; - machine_uint_t n_args_min; // inclusive + bool is_kw : 1; + machine_uint_t n_args_min : (sizeof(machine_uint_t) - 1); // inclusive machine_uint_t n_args_max; // inclusive void *fun; // TODO add mp_map_t *globals // for const function objects, make an empty, const map // such functions won't be able to access the global scope, but that's probably okay } mp_obj_fun_native_t; + extern const mp_obj_type_t fun_native_type; extern const mp_obj_type_t fun_bc_type; void mp_obj_fun_bc_get(mp_obj_t self_in, int *n_args, uint *n_state, const byte **code); diff --git a/py/objbool.c b/py/objbool.c index 77394dab9..cfab7db06 100644 --- a/py/objbool.c +++ b/py/objbool.c @@ -34,14 +34,8 @@ static mp_obj_t bool_make_new(mp_obj_t type_in, int n_args, const mp_obj_t *args const mp_obj_type_t bool_type = { { &mp_const_type }, "bool", - bool_print, // print - bool_make_new, // make_new - NULL, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = {{NULL, NULL},}, + .print = bool_print, + .make_new = bool_make_new, }; static const mp_obj_bool_t false_obj = {{&bool_type}, false}; diff --git a/py/objboundmeth.c b/py/objboundmeth.c index 4e6d2e010..78e5c6249 100644 --- a/py/objboundmeth.c +++ b/py/objboundmeth.c @@ -36,14 +36,7 @@ mp_obj_t bound_meth_call_n(mp_obj_t self_in, int n_args, const mp_obj_t *args) { const mp_obj_type_t bound_meth_type = { { &mp_const_type }, "bound_method", - NULL, // print - NULL, // make_new - bound_meth_call_n, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = {{NULL, NULL},}, + .call_n = bound_meth_call_n, }; mp_obj_t mp_obj_new_bound_meth(mp_obj_t self, mp_obj_t meth) { diff --git a/py/objcell.c b/py/objcell.c index 3465f9919..264125bf3 100644 --- a/py/objcell.c +++ b/py/objcell.c @@ -26,14 +26,6 @@ void mp_obj_cell_set(mp_obj_t self_in, mp_obj_t obj) { const mp_obj_type_t cell_type = { { &mp_const_type }, "cell", - NULL, // print - NULL, // make_new - NULL, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = {{NULL, NULL},}, }; mp_obj_t mp_obj_new_cell(mp_obj_t obj) { diff --git a/py/objclass.c b/py/objclass.c index 536abdf7e..d13d1775a 100644 --- a/py/objclass.c +++ b/py/objclass.c @@ -63,14 +63,7 @@ mp_map_t *mp_obj_class_get_locals(mp_obj_t self_in) { const mp_obj_type_t class_type = { { &mp_const_type }, "class", - NULL, // print - NULL, // make_new - class_call_n, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = {{NULL, NULL},}, + .call_n = class_call_n, }; mp_obj_t mp_obj_new_class(mp_map_t *class_locals) { diff --git a/py/objclosure.c b/py/objclosure.c index 3317eb86f..b372ee6fe 100644 --- a/py/objclosure.c +++ b/py/objclosure.c @@ -35,14 +35,7 @@ mp_obj_t closure_call_n(mp_obj_t self_in, int n_args, const mp_obj_t *args) { const mp_obj_type_t closure_type = { { &mp_const_type }, "closure", - NULL, // print - NULL, // make_new - closure_call_n, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = {{NULL, NULL},}, + .call_n = closure_call_n, }; mp_obj_t mp_obj_new_closure(mp_obj_t fun, mp_obj_t closure_tuple) { diff --git a/py/objcomplex.c b/py/objcomplex.c index 46f43b54b..1036bae42 100644 --- a/py/objcomplex.c +++ b/py/objcomplex.c @@ -87,14 +87,10 @@ static mp_obj_t complex_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) { const mp_obj_type_t complex_type = { { &mp_const_type }, "complex", - complex_print, // print - complex_make_new, // make_new - NULL, // call_n - complex_unary_op, // unary_op - complex_binary_op, // binary_op - NULL, // getiter - NULL, // iternext - .methods = { { NULL, NULL }, }, + .print = complex_print, + .make_new = complex_make_new, + .unary_op = complex_unary_op, + .binary_op = complex_binary_op, }; mp_obj_t mp_obj_new_complex(mp_float_t real, mp_float_t imag) { diff --git a/py/objexcept.c b/py/objexcept.c index 22b8c5812..829b14785 100644 --- a/py/objexcept.c +++ b/py/objexcept.c @@ -38,14 +38,7 @@ void exception_print(void (*print)(void *env, const char *fmt, ...), void *env, const mp_obj_type_t exception_type = { { &mp_const_type }, "exception", - exception_print, // print - NULL, // make_new - NULL, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = {{NULL, NULL},}, + .print = exception_print, }; mp_obj_t mp_obj_new_exception(qstr id) { diff --git a/py/objfloat.c b/py/objfloat.c index 336ae597f..d21472d5d 100644 --- a/py/objfloat.c +++ b/py/objfloat.c @@ -68,7 +68,6 @@ const mp_obj_type_t float_type = { .make_new = float_make_new, .unary_op = float_unary_op, .binary_op = float_binary_op, - .methods = { { NULL, NULL }, }, }; mp_obj_t mp_obj_new_float(mp_float_t value) { diff --git a/py/objfun.c b/py/objfun.c index 0db6459a3..395824b04 100644 --- a/py/objfun.c +++ b/py/objfun.c @@ -17,9 +17,13 @@ // mp_obj_fun_native_t defined in obj.h +mp_obj_t fun_native_call_n_kw(mp_obj_t self_in, int n_args, int n_kw, const mp_obj_t *args); // args are in reverse order in the array mp_obj_t fun_native_call_n(mp_obj_t self_in, int n_args, const mp_obj_t *args) { mp_obj_fun_native_t *self = self_in; + if (self->is_kw) { + return fun_native_call_n_kw(self_in, n_args, 0, args); + } if (self->n_args_min == self->n_args_max) { // function requires a fixed number of arguments @@ -69,19 +73,29 @@ mp_obj_t fun_native_call_n(mp_obj_t self_in, int n_args, const mp_obj_t *args) { } } +mp_obj_t fun_native_call_n_kw(mp_obj_t self_in, int n_args, int n_kw, const mp_obj_t *args) { + mp_obj_fun_native_t *self = self_in; + + if (!self->is_kw) { + nlr_jump(mp_obj_new_exception_msg(MP_QSTR_TypeError, "function does not take keyword arguments")); + } + + mp_obj_t *vargs = mp_obj_new_tuple_reverse(n_args, args + 2*n_kw); + mp_map_t *kw_args = mp_map_new(MP_MAP_QSTR, n_kw); + for (int i = 0; i < 2*n_kw; i+=2) { + qstr name = mp_obj_str_get(args[i+1]); + mp_qstr_map_lookup(kw_args, name, true)->value = args[i]; + } + mp_obj_t res = ((mp_fun_kw_t)self->fun)(vargs, kw_args); + /* TODO clean up vargs and kw_args */ + return res; +} + const mp_obj_type_t fun_native_type = { { &mp_const_type }, "function", - NULL, // print - NULL, // make_new - fun_native_call_n, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = { - {NULL, NULL}, // end-of-list sentinel - }, + .call_n = fun_native_call_n, + .call_n_kw = fun_native_call_n_kw, }; mp_obj_t rt_make_function_0(mp_fun_0_t fun) { @@ -174,16 +188,7 @@ mp_obj_t fun_bc_call_n(mp_obj_t self_in, int n_args, const mp_obj_t *args) { const mp_obj_type_t fun_bc_type = { { &mp_const_type }, "function", - NULL, // print - NULL, // make_new - fun_bc_call_n, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = { - {NULL, NULL}, // end-of-list sentinel - }, + .call_n = fun_bc_call_n, }; mp_obj_t mp_obj_new_fun_bc(int n_args, uint n_state, const byte *code) { @@ -288,16 +293,7 @@ mp_obj_t fun_asm_call_n(mp_obj_t self_in, int n_args, const mp_obj_t *args) { static const mp_obj_type_t fun_asm_type = { { &mp_const_type }, "function", - NULL, // print - NULL, // make_new - fun_asm_call_n, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = { - {NULL, NULL}, // end-of-list sentinel - }, + .call_n = fun_asm_call_n, }; mp_obj_t mp_obj_new_fun_asm(uint n_args, void *fun) { diff --git a/py/objgenerator.c b/py/objgenerator.c index a91b0d6fc..7eeb4ef80 100644 --- a/py/objgenerator.c +++ b/py/objgenerator.c @@ -39,14 +39,7 @@ mp_obj_t gen_wrap_call_n(mp_obj_t self_in, int n_args, const mp_obj_t *args) { const mp_obj_type_t gen_wrap_type = { { &mp_const_type }, "generator", - NULL, // print - NULL, // make_new - gen_wrap_call_n, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = {{NULL, NULL},}, + .call_n = gen_wrap_call_n, }; mp_obj_t mp_obj_new_gen_wrap(uint n_locals, uint n_stack, mp_obj_t fun) { @@ -94,14 +87,9 @@ mp_obj_t gen_instance_iternext(mp_obj_t self_in) { const mp_obj_type_t gen_instance_type = { { &mp_const_type }, "generator", - gen_instance_print, // print - NULL, // make_new - NULL, // call_n - NULL, // unary_op - NULL, // binary_op - gen_instance_getiter, // getiter - gen_instance_iternext, // iternext - .methods = {{NULL, NULL},}, + .print = gen_instance_print, + .getiter = gen_instance_getiter, + .iternext = gen_instance_iternext, }; // args are in reverse order in the array diff --git a/py/objinstance.c b/py/objinstance.c index 8ef2773fd..209643e2b 100644 --- a/py/objinstance.c +++ b/py/objinstance.c @@ -92,14 +92,6 @@ void mp_obj_instance_store_attr(mp_obj_t self_in, qstr attr, mp_obj_t value) { const mp_obj_type_t instance_type = { { &mp_const_type }, "instance", - NULL, // print - NULL, // make_new - NULL, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = {{NULL, NULL},}, }; mp_obj_t mp_obj_new_instance(mp_obj_t class) { diff --git a/py/objint.c b/py/objint.c index 8d69c4e7a..9cd5ebae2 100644 --- a/py/objint.c +++ b/py/objint.c @@ -34,7 +34,6 @@ const mp_obj_type_t int_type = { { &mp_const_type }, "int", .make_new = int_make_new, - .methods = { { NULL, NULL }, }, }; mp_obj_t mp_obj_new_int(machine_int_t value) { diff --git a/py/objlist.c b/py/objlist.c index 02a6b1525..5162fa09f 100644 --- a/py/objlist.c +++ b/py/objlist.c @@ -8,6 +8,7 @@ #include "mpconfig.h" #include "mpqstr.h" #include "obj.h" +#include "map.h" #include "runtime0.h" #include "runtime.h" @@ -57,6 +58,7 @@ static mp_obj_t list_make_new(mp_obj_t type_in, int n_args, const mp_obj_t *args default: nlr_jump(mp_obj_new_exception_msg_1_arg(MP_QSTR_TypeError, "list takes at most 1 argument, %d given", (void*)(machine_int_t)n_args)); } + return NULL; } static mp_obj_t list_binary_op(int op, mp_obj_t lhs, mp_obj_t rhs) { @@ -119,14 +121,15 @@ static mp_obj_t list_pop(int n_args, const mp_obj_t *args) { } // TODO make this conform to CPython's definition of sort -static void mp_quicksort(mp_obj_t *head, mp_obj_t *tail, mp_obj_t key_fn) { +static void mp_quicksort(mp_obj_t *head, mp_obj_t *tail, mp_obj_t key_fn, bool reversed) { + int op = reversed ? RT_COMPARE_OP_MORE : RT_COMPARE_OP_LESS; while (head < tail) { mp_obj_t *h = head - 1; mp_obj_t *t = tail; - mp_obj_t v = rt_call_function_1(key_fn, tail[0]); // get pivot using key_fn + mp_obj_t v = key_fn == NULL ? tail[0] : rt_call_function_1(key_fn, tail[0]); // get pivot using key_fn for (;;) { - do ++h; while (rt_compare_op(RT_COMPARE_OP_LESS, rt_call_function_1(key_fn, h[0]), v) == mp_const_true); - do --t; while (h < t && rt_compare_op(RT_COMPARE_OP_LESS, v, rt_call_function_1(key_fn, t[0])) == mp_const_true); + do ++h; while (rt_compare_op(op, key_fn == NULL ? h[0] : rt_call_function_1(key_fn, h[0]), v) == mp_const_true); + do --t; while (h < t && rt_compare_op(op, v, key_fn == NULL ? t[0] : rt_call_function_1(key_fn, t[0])) == mp_const_true); if (h >= t) break; mp_obj_t x = h[0]; h[0] = t[0]; @@ -135,16 +138,31 @@ static void mp_quicksort(mp_obj_t *head, mp_obj_t *tail, mp_obj_t key_fn) { mp_obj_t x = h[0]; h[0] = tail[0]; tail[0] = x; - mp_quicksort(head, t, key_fn); + mp_quicksort(head, t, key_fn, reversed); head = h + 1; } } -static mp_obj_t list_sort(mp_obj_t self_in, mp_obj_t key_fn) { - assert(MP_OBJ_IS_TYPE(self_in, &list_type)); - mp_obj_list_t *self = self_in; +static mp_obj_t list_sort(mp_obj_t *args, mp_map_t *kwargs) { + mp_obj_t *args_items = NULL; + machine_uint_t args_len = 0; + qstr key_idx = qstr_from_str_static("key"); + qstr reverse_idx = qstr_from_str_static("reverse"); + + assert(MP_OBJ_IS_TYPE(args, &tuple_type)); + mp_obj_tuple_get(args, &args_len, &args_items); + assert(args_len >= 1); + if (args_len > 1) { + nlr_jump(mp_obj_new_exception_msg(MP_QSTR_TypeError, + "list.sort takes no positional arguments")); + } + mp_obj_list_t *self = args_items[0]; if (self->len > 1) { - mp_quicksort(self->items, self->items + self->len - 1, key_fn); + mp_map_elem_t *keyfun = mp_qstr_map_lookup(kwargs, key_idx, false); + mp_map_elem_t *reverse = mp_qstr_map_lookup(kwargs, reverse_idx, false); + mp_quicksort(self->items, self->items + self->len - 1, + keyfun ? keyfun->value : NULL, + reverse && reverse->value ? rt_is_true(reverse->value) : false); } return mp_const_none; // return None, as per CPython } @@ -258,29 +276,30 @@ static MP_DEFINE_CONST_FUN_OBJ_3(list_insert_obj, list_insert); static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(list_pop_obj, 1, 2, list_pop); static MP_DEFINE_CONST_FUN_OBJ_2(list_remove_obj, list_remove); static MP_DEFINE_CONST_FUN_OBJ_1(list_reverse_obj, list_reverse); -static MP_DEFINE_CONST_FUN_OBJ_2(list_sort_obj, list_sort); +static MP_DEFINE_CONST_FUN_OBJ_KW(list_sort_obj, list_sort); + +static const mp_method_t list_type_methods[] = { + { "append", &list_append_obj }, + { "clear", &list_clear_obj }, + { "copy", &list_copy_obj }, + { "count", &list_count_obj }, + { "index", &list_index_obj }, + { "insert", &list_insert_obj }, + { "pop", &list_pop_obj }, + { "remove", &list_remove_obj }, + { "reverse", &list_reverse_obj }, + { "sort", &list_sort_obj }, + { NULL, NULL }, // end-of-list sentinel +}; const mp_obj_type_t list_type = { { &mp_const_type }, "list", .print = list_print, .make_new = list_make_new, - .unary_op = NULL, .binary_op = list_binary_op, .getiter = list_getiter, - .methods = { - { "append", &list_append_obj }, - { "clear", &list_clear_obj }, - { "copy", &list_copy_obj }, - { "count", &list_count_obj }, - { "index", &list_index_obj }, - { "insert", &list_insert_obj }, - { "pop", &list_pop_obj }, - { "remove", &list_remove_obj }, - { "reverse", &list_reverse_obj }, - { "sort", &list_sort_obj }, - { NULL, NULL }, // end-of-list sentinel - }, + .methods = list_type_methods, }; static mp_obj_list_t *list_new(uint n) { @@ -344,7 +363,6 @@ static const mp_obj_type_t list_it_type = { { &mp_const_type }, "list_iterator", .iternext = list_it_iternext, - .methods = { { NULL, NULL }, }, }; mp_obj_t mp_obj_new_list_iterator(mp_obj_list_t *list, int cur) { diff --git a/py/objmodule.c b/py/objmodule.c index 2d6f9555e..7b92b76f4 100644 --- a/py/objmodule.c +++ b/py/objmodule.c @@ -6,6 +6,7 @@ #include "nlr.h" #include "misc.h" #include "mpconfig.h" +#include "mpqstr.h" #include "obj.h" #include "runtime.h" #include "map.h" @@ -24,21 +25,15 @@ void module_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_ const mp_obj_type_t module_type = { { &mp_const_type }, "module", - module_print, // print - NULL, // make_new - NULL, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = {{NULL, NULL},}, + .print = module_print, }; mp_obj_t mp_obj_new_module(qstr module_name) { mp_obj_module_t *o = m_new_obj(mp_obj_module_t); o->base.type = &module_type; o->name = module_name; - o->globals = mp_map_new(MP_MAP_QSTR, 0); + o->globals = mp_map_new(MP_MAP_QSTR, 1); + mp_qstr_map_lookup(o->globals, MP_QSTR___name__, true)->value = mp_obj_new_str(module_name); return o; } diff --git a/py/objnone.c b/py/objnone.c index 877e61fe5..c0efe6c0f 100644 --- a/py/objnone.c +++ b/py/objnone.c @@ -18,7 +18,6 @@ const mp_obj_type_t none_type = { { &mp_const_type }, "NoneType", .print = none_print, - .methods = {{NULL, NULL},}, }; static const mp_obj_none_t none_obj = {{&none_type}}; diff --git a/py/objrange.c b/py/objrange.c index 1ef42673f..a2a0e67b0 100644 --- a/py/objrange.c +++ b/py/objrange.c @@ -25,14 +25,7 @@ mp_obj_t range_getiter(mp_obj_t o_in) { static const mp_obj_type_t range_type = { { &mp_const_type} , "range", - NULL, // print - NULL, // make_new - NULL, // call_n - NULL, // unary_op - NULL, // binary_op - range_getiter, - NULL, // iternext - .methods = {{NULL, NULL},}, + .getiter = range_getiter, }; // range is a class and instances are immutable sequence objects @@ -70,14 +63,7 @@ mp_obj_t range_it_iternext(mp_obj_t o_in) { static const mp_obj_type_t range_it_type = { { &mp_const_type }, "range_iterator", - NULL, // print - NULL, // make_new - NULL, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - range_it_iternext, - .methods = {{NULL, NULL},}, + .iternext = range_it_iternext, }; mp_obj_t mp_obj_new_range_iterator(int cur, int stop, int step) { diff --git a/py/objset.c b/py/objset.c index dd9a4d1e1..67dab11df 100644 --- a/py/objset.c +++ b/py/objset.c @@ -57,14 +57,8 @@ static mp_obj_t set_make_new(mp_obj_t type_in, int n_args, const mp_obj_t *args) const mp_obj_type_t set_type = { { &mp_const_type }, "set", - set_print, // print - set_make_new, // make_new - NULL, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = { { NULL, NULL }, }, + .print = set_print, + .make_new = set_make_new, }; mp_obj_t mp_obj_new_set(int n_args, mp_obj_t *items) { diff --git a/py/objslice.c b/py/objslice.c index da69b92af..d95ccef06 100644 --- a/py/objslice.c +++ b/py/objslice.c @@ -23,14 +23,7 @@ void ellipsis_print(void (*print)(void *env, const char *fmt, ...), void *env, m const mp_obj_type_t ellipsis_type = { { &mp_const_type }, "ellipsis", - ellipsis_print, // print - NULL, // make_new - NULL, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = {{NULL, NULL},}, + .print = ellipsis_print, }; static const mp_obj_ellipsis_t ellipsis_obj = {{&ellipsis_type}}; @@ -58,7 +51,6 @@ const mp_obj_type_t slice_type = { { &mp_const_type }, "slice", .print = slice_print, - .methods = { { NULL, NULL }, }, }; // TODO: Make sure to handle "empty" values, which are signified by None in CPython diff --git a/py/objstr.c b/py/objstr.c index db3e0beca..cc9f7f85b 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -184,17 +184,19 @@ mp_obj_t str_format(int n_args, const mp_obj_t *args) { static MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join); static MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, str_format); +static const mp_method_t str_type_methods[] = { + { "join", &str_join_obj }, + { "format", &str_format_obj }, + { NULL, NULL }, // end-of-list sentinel +}; + const mp_obj_type_t str_type = { { &mp_const_type }, "str", .print = str_print, .binary_op = str_binary_op, .getiter = str_getiter, - .methods = { - { "join", &str_join_obj }, - { "format", &str_format_obj }, - { NULL, NULL }, // end-of-list sentinel - }, + .methods = str_type_methods, }; mp_obj_t mp_obj_new_str(qstr qstr) { @@ -235,7 +237,6 @@ static const mp_obj_type_t str_it_type = { { &mp_const_type }, "str_iterator", .iternext = str_it_iternext, - .methods = { { NULL, NULL }, }, }; mp_obj_t mp_obj_new_str_iterator(mp_obj_str_t *str, int cur) { diff --git a/py/objtuple.c b/py/objtuple.c index ceca4200e..0050fc5ea 100644 --- a/py/objtuple.c +++ b/py/objtuple.c @@ -103,14 +103,13 @@ const mp_obj_type_t tuple_type = { .make_new = tuple_make_new, .binary_op = tuple_binary_op, .getiter = tuple_getiter, - .methods = {{NULL, NULL},}, }; // the zero-length tuple static const mp_obj_tuple_t empty_tuple_obj = {{&tuple_type}, 0}; const mp_obj_t mp_const_empty_tuple = (mp_obj_t)&empty_tuple_obj; -mp_obj_t mp_obj_new_tuple(uint n, mp_obj_t *items) { +mp_obj_t mp_obj_new_tuple(uint n, const mp_obj_t *items) { if (n == 0) { return mp_const_empty_tuple; } @@ -123,7 +122,7 @@ mp_obj_t mp_obj_new_tuple(uint n, mp_obj_t *items) { return o; } -mp_obj_t mp_obj_new_tuple_reverse(uint n, mp_obj_t *items) { +mp_obj_t mp_obj_new_tuple_reverse(uint n, const mp_obj_t *items) { if (n == 0) { return mp_const_empty_tuple; } @@ -166,7 +165,6 @@ static const mp_obj_type_t tuple_it_type = { { &mp_const_type }, "tuple_iterator", .iternext = tuple_it_iternext, - .methods = {{NULL, NULL},}, }; static mp_obj_t mp_obj_new_tuple_iterator(mp_obj_tuple_t *tuple, int cur) { diff --git a/py/objtype.c b/py/objtype.c index 37d40b38f..8778c180c 100644 --- a/py/objtype.c +++ b/py/objtype.c @@ -27,5 +27,4 @@ const mp_obj_type_t mp_const_type = { "type", .print = type_print, .call_n = type_call_n, - .methods = {{NULL, NULL},}, }; diff --git a/py/py.mk b/py/py.mk new file mode 100644 index 000000000..3ed8a3e3d --- /dev/null +++ b/py/py.mk @@ -0,0 +1,105 @@ +# default settings; can be overriden in main Makefile + +ifndef PY_SRC +PY_SRC = ../py +endif + +ifndef BUILD +BUILD = build +endif + +# to create the build directory + +$(BUILD): + mkdir -p $@ + +# where py object files go (they have a name prefix to prevent filename clashes) + +PY_BUILD = $(BUILD)/py. + +# py object files + +PY_O_BASENAME = \ + nlrx86.o \ + nlrx64.o \ + nlrthumb.o \ + malloc.o \ + gc.o \ + qstr.o \ + vstr.o \ + unicode.o \ + lexer.o \ + lexerunix.o \ + parse.o \ + scope.o \ + compile.o \ + emitcommon.o \ + emitpass1.o \ + emitcpy.o \ + emitbc.o \ + asmx64.o \ + emitnx64.o \ + asmthumb.o \ + emitnthumb.o \ + emitinlinethumb.o \ + runtime.o \ + map.o \ + obj.o \ + objbool.o \ + objboundmeth.o \ + objcell.o \ + objclass.o \ + objclosure.o \ + objcomplex.o \ + objdict.o \ + objexcept.o \ + objfloat.o \ + objfun.o \ + objgenerator.o \ + objinstance.o \ + objint.o \ + objlist.o \ + objmodule.o \ + objnone.o \ + objrange.o \ + objset.o \ + objslice.o \ + objstr.o \ + objtuple.o \ + objtype.o \ + builtin.o \ + builtinimport.o \ + vm.o \ + showbc.o \ + repl.o \ + +# prepend the build destination prefix to the py object files + +PY_O = $(addprefix $(PY_BUILD), $(PY_O_BASENAME)) + +$(PY_BUILD)emitnx64.o: $(PY_SRC)/emitnative.c $(PY_SRC)/emit.h mpconfigport.h + $(CC) $(CFLAGS) -DN_X64 -c -o $@ $< + +$(PY_BUILD)emitnthumb.o: $(PY_SRC)/emitnative.c $(PY_SRC)/emit.h mpconfigport.h + $(CC) $(CFLAGS) -DN_THUMB -c -o $@ $< + +$(PY_BUILD)%.o: $(PY_SRC)/%.S + $(CC) $(CFLAGS) -c -o $@ $< + +$(PY_BUILD)%.o: $(PY_SRC)/%.c mpconfigport.h + $(CC) $(CFLAGS) -c -o $@ $< + +# optimising gc for speed; 5ms down to 4ms on pybv2 +$(PY_BUILD)gc.o: $(PY_SRC)/gc.c + $(CC) $(CFLAGS) -O3 -c -o $@ $< + +# optimising vm for speed, adds only a small amount to code size but makes a huge difference to speed (20% faster) +$(PY_BUILD)vm.o: $(PY_SRC)/vm.c + $(CC) $(CFLAGS) -O3 -c -o $@ $< + +# header dependencies + +$(PY_BUILD)parse.o: $(PY_SRC)/grammar.h +$(PY_BUILD)compile.o: $(PY_SRC)/grammar.h +$(PY_BUILD)/emitcpy.o: $(PY_SRC)/emit.h +$(PY_BUILD)emitbc.o: $(PY_SRC)/emit.h diff --git a/py/repl.c b/py/repl.c index 4241ef0e4..473313c1e 100644 --- a/py/repl.c +++ b/py/repl.c @@ -1,6 +1,9 @@ #include "misc.h" +#include "mpconfig.h" #include "repl.h" +#if MICROPY_ENABLE_REPL_HELPERS + bool str_startswith_word(const char *str, const char *head) { int i; for (i = 0; str[i] && head[i]; i++) { @@ -42,3 +45,5 @@ bool mp_repl_is_compound_stmt(const char *line) { } return n_paren > 0 || n_brack > 0 || n_brace > 0; } + +#endif // MICROPY_ENABLE_REPL_HELPERS diff --git a/py/repl.h b/py/repl.h index 02fe523ed..23259fa90 100644 --- a/py/repl.h +++ b/py/repl.h @@ -1 +1,3 @@ +#if MICROPY_ENABLE_REPL_HELPERS bool mp_repl_is_compound_stmt(const char *line); +#endif diff --git a/py/runtime.c b/py/runtime.c index f3fabc39c..5c476d9ec 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -61,7 +61,8 @@ typedef struct _mp_code_t { } mp_code_t; static int next_unique_code_id; -static mp_code_t *unique_codes; +static machine_uint_t unique_codes_alloc = 0; +static mp_code_t *unique_codes = NULL; #ifdef WRITE_CODE FILE *fp_write_code = NULL; @@ -83,6 +84,7 @@ void rt_init(void) { mp_qstr_map_lookup(&map_builtins, MP_QSTR_TypeError, true)->value = mp_obj_new_exception(MP_QSTR_TypeError); mp_qstr_map_lookup(&map_builtins, MP_QSTR_SyntaxError, true)->value = mp_obj_new_exception(MP_QSTR_SyntaxError); mp_qstr_map_lookup(&map_builtins, MP_QSTR_ValueError, true)->value = mp_obj_new_exception(MP_QSTR_ValueError); + mp_qstr_map_lookup(&map_builtins, MP_QSTR_OSError, true)->value = mp_obj_new_exception(MP_QSTR_OSError); // built-in objects mp_qstr_map_lookup(&map_builtins, MP_QSTR_Ellipsis, true)->value = mp_const_ellipsis; @@ -126,6 +128,7 @@ void rt_init(void) { mp_qstr_map_lookup(&map_builtins, MP_QSTR_sum, true)->value = rt_make_function_var(1, mp_builtin_sum); next_unique_code_id = 1; // 0 indicates "no code" + unique_codes_alloc = 0; unique_codes = NULL; #ifdef WRITE_CODE @@ -134,6 +137,7 @@ void rt_init(void) { } void rt_deinit(void) { + m_del(mp_code_t, unique_codes, unique_codes_alloc); #ifdef WRITE_CODE if (fp_write_code != NULL) { fclose(fp_write_code); @@ -146,18 +150,20 @@ int rt_get_unique_code_id(void) { } static void alloc_unique_codes(void) { - if (unique_codes == NULL) { - unique_codes = m_new(mp_code_t, next_unique_code_id + 10); // XXX hack until we fix the REPL allocation problem - for (int i = 0; i < next_unique_code_id; i++) { + if (next_unique_code_id > unique_codes_alloc) { + // increase size of unique_codes table + unique_codes = m_renew(mp_code_t, unique_codes, unique_codes_alloc, next_unique_code_id); + for (int i = unique_codes_alloc; i < next_unique_code_id; i++) { unique_codes[i].kind = MP_CODE_NONE; } + unique_codes_alloc = next_unique_code_id; } } 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) { alloc_unique_codes(); - assert(1 <= unique_code_id && unique_code_id < next_unique_code_id); + assert(1 <= unique_code_id && unique_code_id < next_unique_code_id && unique_codes[unique_code_id].kind == MP_CODE_NONE); unique_codes[unique_code_id].kind = MP_CODE_BYTE; unique_codes[unique_code_id].n_args = n_args; unique_codes[unique_code_id].n_locals = n_locals; @@ -192,7 +198,7 @@ void rt_assign_byte_code(int unique_code_id, byte *code, uint len, int n_args, i void rt_assign_native_code(int unique_code_id, void *fun, uint len, int n_args) { alloc_unique_codes(); - assert(1 <= unique_code_id && unique_code_id < next_unique_code_id); + assert(1 <= unique_code_id && unique_code_id < next_unique_code_id && unique_codes[unique_code_id].kind == MP_CODE_NONE); unique_codes[unique_code_id].kind = MP_CODE_NATIVE; unique_codes[unique_code_id].n_args = n_args; unique_codes[unique_code_id].n_locals = 0; @@ -225,7 +231,7 @@ void rt_assign_native_code(int unique_code_id, void *fun, uint len, int n_args) void rt_assign_inline_asm_code(int unique_code_id, void *fun, uint len, int n_args) { alloc_unique_codes(); - assert(1 <= unique_code_id && unique_code_id < next_unique_code_id); + assert(1 <= unique_code_id && unique_code_id < next_unique_code_id && unique_codes[unique_code_id].kind == MP_CODE_NONE); unique_codes[unique_code_id].kind = MP_CODE_INLINE_ASM; unique_codes[unique_code_id].n_args = n_args; unique_codes[unique_code_id].n_locals = 0; @@ -683,10 +689,20 @@ mp_obj_t rt_call_function_n(mp_obj_t fun_in, int n_args, const mp_obj_t *args) { // args are in reverse order in the array; keyword arguments come first, value then key // eg: (value1, key1, value0, key0, arg1, arg0) -mp_obj_t rt_call_function_n_kw(mp_obj_t fun, uint n_args, uint n_kw, const mp_obj_t *args) { - // TODO - assert(0); - return mp_const_none; +mp_obj_t rt_call_function_n_kw(mp_obj_t fun_in, uint n_args, uint n_kw, const mp_obj_t *args) { + // TODO merge this and _n into a single, smarter thing + DEBUG_OP_printf("calling function %p(n_args=%d, n_kw=%d, args=%p)\n", fun_in, n_args, n_kw, args); + + if (MP_OBJ_IS_SMALL_INT(fun_in)) { + nlr_jump(mp_obj_new_exception_msg(MP_QSTR_TypeError, "'int' object is not callable")); + } else { + mp_obj_base_t *fun = fun_in; + if (fun->type->call_n_kw != NULL) { + return fun->type->call_n_kw(fun_in, n_args, n_kw, args); + } else { + nlr_jump(mp_obj_new_exception_msg_1_arg(MP_QSTR_TypeError, "'%s' object is not callable", fun->type->name)); + } + } } // args contains: arg(n_args-1) arg(n_args-2) ... arg(0) self/NULL fun @@ -775,10 +791,12 @@ mp_obj_t rt_load_attr(mp_obj_t base, qstr attr) { } else if (MP_OBJ_IS_OBJ(base)) { // generic method lookup mp_obj_base_t *o = base; - const mp_method_t *meth = &o->type->methods[0]; - for (; meth->name != NULL; meth++) { - if (strcmp(meth->name, qstr_str(attr)) == 0) { - return mp_obj_new_bound_meth(base, (mp_obj_t)meth->fun); + const mp_method_t *meth = o->type->methods; + if (meth != NULL) { + for (; meth->name != NULL; meth++) { + if (strcmp(meth->name, qstr_str(attr)) == 0) { + return mp_obj_new_bound_meth(base, (mp_obj_t)meth->fun); + } } } } @@ -799,12 +817,14 @@ void rt_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) { } else if (MP_OBJ_IS_OBJ(base)) { // generic method lookup mp_obj_base_t *o = base; - const mp_method_t *meth = &o->type->methods[0]; - for (; meth->name != NULL; meth++) { - if (strcmp(meth->name, qstr_str(attr)) == 0) { - dest[1] = (mp_obj_t)meth->fun; - dest[0] = base; - return; + const mp_method_t *meth = o->type->methods; + if (meth != NULL) { + for (; meth->name != NULL; meth++) { + if (strcmp(meth->name, qstr_str(attr)) == 0) { + dest[1] = (mp_obj_t)meth->fun; + dest[0] = base; + return; + } } } } diff --git a/py/showbc.c b/py/showbc.c index eb7d41b24..aea0aff67 100644 --- a/py/showbc.c +++ b/py/showbc.c @@ -8,6 +8,8 @@ #include "mpconfig.h" #include "bc0.h" +#if MICROPY_SHOW_BC + #define DECODE_UINT do { unum = *ip++; if (unum > 127) { unum = ((unum & 0x3f) << 8) | (*ip++); } } while (0) #define DECODE_ULABEL do { unum = (ip[0] | (ip[1] << 8)); ip += 2; } while (0) #define DECODE_SLABEL do { unum = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2; } while (0) @@ -363,3 +365,5 @@ void mp_show_byte_code(const byte *ip, int len) { printf("\n"); } } + +#endif // MICROPY_SHOW_BC diff --git a/stm/Makefile b/stm/Makefile index cd998dd88..fecd52527 100644 --- a/stm/Makefile +++ b/stm/Makefile @@ -1,9 +1,16 @@ +# define main target +all: all2 + +# include py core make definitions +include ../py/py.mk + +# program for deletion +RM = /bin/rm + STMSRC=lib #STMOTGSRC=lib-otg FATFSSRC=fatfs CC3KSRC=cc3k -PYSRC=../py -BUILD=build DFU=../tools/dfu.py TARGET=PYBOARD @@ -11,7 +18,7 @@ AS = arm-none-eabi-as CC = arm-none-eabi-gcc LD = arm-none-eabi-ld CFLAGS_CORTEX_M4 = -mthumb -mtune=cortex-m4 -mabi=aapcs-linux -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -fsingle-precision-constant -Wdouble-promotion -DSTM32F40XX -DHSE_VALUE=8000000 -CFLAGS = -I. -I$(PYSRC) -I$(FATFSSRC) -I$(STMSRC) -Wall -ansi -std=gnu99 -Os -DNDEBUG $(CFLAGS_CORTEX_M4) -D$(TARGET) +CFLAGS = -I. -I$(PY_SRC) -I$(FATFSSRC) -I$(STMSRC) -Wall -ansi -std=gnu99 -Os -DNDEBUG $(CFLAGS_CORTEX_M4) -D$(TARGET) #CFLAGS += -I$(STMOTGSRC) -DUSE_HOST_MODE -DUSE_OTG_MODE LDFLAGS = --nostdlib -T stm32f405.ld @@ -43,53 +50,6 @@ SRC_S = \ startup_stm32f40xx.s \ gchelper.s \ -PY_O = \ - nlrthumb.o \ - gc.o \ - malloc.o \ - qstr.o \ - vstr.o \ - unicode.o \ - lexer.o \ - parse.o \ - scope.o \ - compile.o \ - emitcommon.o \ - emitpass1.o \ - emitbc.o \ - asmthumb.o \ - emitnthumb.o \ - emitinlinethumb.o \ - runtime.o \ - map.o \ - obj.o \ - objbool.o \ - objboundmeth.o \ - objcell.o \ - objclass.o \ - objclosure.o \ - objcomplex.o \ - objdict.o \ - objexcept.o \ - objfloat.o \ - objfun.o \ - objgenerator.o \ - objinstance.o \ - objint.o \ - objlist.o \ - objmodule.o \ - objnone.o \ - objrange.o \ - objset.o \ - objslice.o \ - objstr.o \ - objtuple.o \ - objtype.o \ - builtin.o \ - builtinimport.o \ - vm.o \ - repl.o \ - SRC_FATFS = \ ff.c \ diskio.c \ @@ -146,10 +106,10 @@ SRC_CC3K = \ ccspi.c \ pybcc3k.c \ -OBJ = $(addprefix $(BUILD)/, $(SRC_C:.c=.o) $(SRC_S:.s=.o) $(PY_O) $(SRC_FATFS:.c=.o) $(SRC_STM:.c=.o) $(SRC_CC3K:.c=.o)) +OBJ = $(addprefix $(BUILD)/, $(SRC_C:.c=.o) $(SRC_S:.s=.o) $(SRC_FATFS:.c=.o) $(SRC_STM:.c=.o) $(SRC_CC3K:.c=.o)) $(PY_O) #OBJ += $(addprefix $(BUILD)/, $(SRC_STM_OTG:.c=.o)) -all: $(BUILD) $(BUILD)/flash.dfu +all2: $(BUILD) $(BUILD)/flash.dfu $(BUILD)/flash.dfu: $(BUILD)/flash0.bin $(BUILD)/flash1.bin python $(DFU) -b 0x08000000:$(BUILD)/flash0.bin -b 0x08020000:$(BUILD)/flash1.bin $@ @@ -164,9 +124,6 @@ $(BUILD)/flash.elf: $(OBJ) $(LD) $(LDFLAGS) -o $@ $(OBJ) arm-none-eabi-size $@ -$(BUILD): - mkdir -p $@ - $(BUILD)/%.o: %.s $(AS) -o $@ $< @@ -185,31 +142,7 @@ $(BUILD)/%.o: $(STMSRC)/%.c $(BUILD)/%.o: $(CC3KSRC)/%.c $(CC) $(CFLAGS) -c -o $@ $< -$(BUILD)/%.o: $(PYSRC)/%.s - $(AS) -o $@ $< - -$(BUILD)/%.o: $(PYSRC)/%.S - $(CC) $(CFLAGS) -c -o $@ $< - -$(BUILD)/%.o: $(PYSRC)/%.c mpconfigport.h - $(CC) $(CFLAGS) -c -o $@ $< - -$(BUILD)/emitnthumb.o: $(PYSRC)/emitnative.c $(PYSRC)/emit.h - $(CC) $(CFLAGS) -DN_THUMB -c -o $@ $< - -# optimising gc for speed; 5ms down to 4ms -$(BUILD)/gc.o: $(PYSRC)/gc.c - $(CC) $(CFLAGS) -O3 -c -o $@ $< - -# optimising vm for speed, adds only a small amount to code size but makes a huge difference to speed (20% faster) -$(BUILD)/vm.o: $(PYSRC)/vm.c - $(CC) $(CFLAGS) -O3 -c -o $@ $< - -$(BUILD)/parse.o: $(PYSRC)/grammar.h -$(BUILD)/compile.o: $(PYSRC)/grammar.h -$(BUILD)/emitbc.o: $(PYSRC)/emit.h - clean: - /bin/rm -rf $(BUILD) + $(RM) -rf $(BUILD) -.PHONY: all clean +.PHONY: all all2 clean diff --git a/stm/i2c.c b/stm/i2c.c index 9e25ff983..22c908566 100644 --- a/stm/i2c.c +++ b/stm/i2c.c @@ -326,18 +326,20 @@ static MP_DEFINE_CONST_FUN_OBJ_1(i2c_obj_read_obj, i2c_obj_read); static MP_DEFINE_CONST_FUN_OBJ_1(i2c_obj_readAndStop_obj, i2c_obj_readAndStop); static MP_DEFINE_CONST_FUN_OBJ_1(i2c_obj_stop_obj, i2c_obj_stop); +static const mp_method_t i2c_methods[] = { + { "start", &i2c_obj_start_obj }, + { "write", &i2c_obj_write_obj }, + { "read", &i2c_obj_read_obj }, + { "readAndStop", &i2c_obj_readAndStop_obj }, + { "stop", &i2c_obj_stop_obj }, + { NULL, NULL }, +}; + static const mp_obj_type_t i2c_obj_type = { { &mp_const_type }, "I2C", .print = i2c_obj_print, - .methods = { - { "start", &i2c_obj_start_obj }, - { "write", &i2c_obj_write_obj }, - { "read", &i2c_obj_read_obj }, - { "readAndStop", &i2c_obj_readAndStop_obj }, - { "stop", &i2c_obj_stop_obj }, - { NULL, NULL }, - } + .methods = i2c_methods, }; // create the I2C object diff --git a/stm/led.c b/stm/led.c index d4bc0a0c8..eb7c76ef1 100644 --- a/stm/led.c +++ b/stm/led.c @@ -176,15 +176,17 @@ mp_obj_t led_obj_off(mp_obj_t self_in) { static MP_DEFINE_CONST_FUN_OBJ_1(led_obj_on_obj, led_obj_on); static MP_DEFINE_CONST_FUN_OBJ_1(led_obj_off_obj, led_obj_off); +static const mp_method_t led_methods[] = { + { "on", &led_obj_on_obj }, + { "off", &led_obj_off_obj }, + { NULL, NULL }, +}; + static const mp_obj_type_t led_obj_type = { { &mp_const_type }, "Led", .print = led_obj_print, - .methods = { - { "on", &led_obj_on_obj }, - { "off", &led_obj_off_obj }, - { NULL, NULL }, - } + .methods = led_methods, }; mp_obj_t pyb_Led(mp_obj_t led_id) { diff --git a/stm/main.c b/stm/main.c index 07c974eff..a038c89b7 100644 --- a/stm/main.c +++ b/stm/main.c @@ -689,22 +689,18 @@ static MP_DEFINE_CONST_FUN_OBJ_1(file_obj_close_obj, file_obj_close); // TODO gc hook to close the file if not already closed +static const mp_method_t file_methods[] = { + { "read", &file_obj_read_obj }, + { "write", &file_obj_write_obj }, + { "close", &file_obj_close_obj }, + {NULL, NULL}, +}; + static const mp_obj_type_t file_obj_type = { { &mp_const_type }, "File", - file_obj_print, // print - NULL, // make_new - NULL, // call_n - NULL, // unary_op - NULL, // binary_op - NULL, // getiter - NULL, // iternext - .methods = { - { "read", &file_obj_read_obj }, - { "write", &file_obj_write_obj }, - { "close", &file_obj_close_obj }, - {NULL, NULL}, - } + .print = file_obj_print, + .methods = file_methods, }; mp_obj_t pyb_io_open(mp_obj_t o_filename, mp_obj_t o_mode) { diff --git a/stm/mpconfigport.h b/stm/mpconfigport.h index 4cea332f3..dfa46cc50 100644 --- a/stm/mpconfigport.h +++ b/stm/mpconfigport.h @@ -2,11 +2,11 @@ // options to control how Micro Python is built -#define MICROPY_ENABLE_FLOAT (1) -#define MICROPY_EMIT_CPYTHON (0) -#define MICROPY_EMIT_X64 (0) #define MICROPY_EMIT_THUMB (1) #define MICROPY_EMIT_INLINE_THUMB (1) +#define MICROPY_ENABLE_GC (1) +#define MICROPY_ENABLE_REPL_HELPERS (1) +#define MICROPY_ENABLE_FLOAT (1) // type definitions for the specific machine diff --git a/stm/servo.c b/stm/servo.c index 31190ce79..cc9633a99 100644 --- a/stm/servo.c +++ b/stm/servo.c @@ -137,14 +137,16 @@ static mp_obj_t servo_obj_angle(mp_obj_t self_in, mp_obj_t angle) { static MP_DEFINE_CONST_FUN_OBJ_2(servo_obj_angle_obj, servo_obj_angle); +static const mp_method_t servo_methods[] = { + { "angle", &servo_obj_angle_obj }, + { NULL, NULL }, +}; + static const mp_obj_type_t servo_obj_type = { { &mp_const_type }, "Servo", .print = servo_obj_print, - .methods = { - { "angle", &servo_obj_angle_obj }, - { NULL, NULL }, - } + .methods = servo_methods, }; mp_obj_t pyb_Servo(mp_obj_t servo_id) { diff --git a/tests/basics/tests/list_sort.py b/tests/basics/tests/list_sort.py new file mode 100644 index 000000000..eff12b9c8 --- /dev/null +++ b/tests/basics/tests/list_sort.py @@ -0,0 +1,13 @@ +l = [1, 3, 2, 5] +print(l) +l.sort() +print(l) +l.sort(key=lambda x: -x) +print(l) +l.sort(key=lambda x: -x, reverse=True) +print(l) +l.sort(reverse=True) +print(l) +l.sort(reverse=False) +print(l) + diff --git a/unix-cpy/Makefile b/unix-cpy/Makefile index a1eb9b77e..d2d698713 100644 --- a/unix-cpy/Makefile +++ b/unix-cpy/Makefile @@ -1,95 +1,37 @@ -PYSRC=../py -BUILD=build +# define main target +PROG = cpy +all: $(PROG) + +# include py core make definitions +include ../py/py.mk +# program for deletion +RM = /bin/rm + +# compiler settings CC = gcc -CFLAGS = -I. -I$(PYSRC) -Wall -Werror -ansi -std=gnu99 -Os #-DNDEBUG +CFLAGS = -I. -I$(PY_SRC) -Wall -Werror -ansi -std=gnu99 -Os #-DNDEBUG LDFLAGS = -lm +# source files SRC_C = \ main.c \ -PY_O = \ - nlrx86.o \ - nlrx64.o \ - malloc.o \ - qstr.o \ - vstr.o \ - unicode.o \ - lexer.o \ - lexerunix.o \ - parse.o \ - scope.o \ - compile.o \ - emitcommon.o \ - emitpass1.o \ - emitcpy.o \ - runtime.o \ - map.o \ - obj.o \ - objbool.o \ - objboundmeth.o \ - objcell.o \ - objclass.o \ - objclosure.o \ - objcomplex.o \ - objdict.o \ - objexcept.o \ - objfloat.o \ - objfun.o \ - objgenerator.o \ - objinstance.o \ - objint.o \ - objlist.o \ - objmodule.o \ - objnone.o \ - objrange.o \ - objset.o \ - objslice.o \ - objstr.o \ - objtuple.o \ - objtype.o \ - builtin.o \ - builtinimport.o \ - vm.o \ - showbc.o \ - repl.o \ - -OBJ = $(addprefix $(BUILD)/, $(SRC_C:.c=.o) $(PY_O)) +OBJ = $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) $(PY_O) LIB = -PROG = cpy $(PROG): $(BUILD) $(OBJ) $(CC) -o $@ $(OBJ) $(LIB) $(LDFLAGS) - -$(BUILD): - mkdir -p $@ + strip $(PROG) + size $(PROG) $(BUILD)/%.o: %.c $(CC) $(CFLAGS) -c -o $@ $< -$(BUILD)/%.o: $(PYSRC)/%.S - $(CC) $(CFLAGS) -c -o $@ $< - -$(BUILD)/%.o: $(PYSRC)/%.c mpconfigport.h - $(CC) $(CFLAGS) -c -o $@ $< - -$(BUILD)/emitnx64.o: $(PYSRC)/emitnative.c $(PYSRC)/emit.h - $(CC) $(CFLAGS) -DN_X64 -c -o $@ $< - -$(BUILD)/emitnthumb.o: $(PYSRC)/emitnative.c $(PYSRC)/emit.h - $(CC) $(CFLAGS) -DN_THUMB -c -o $@ $< - -# optimising vm for speed, adds only a small amount to code size but makes a huge difference to speed (20% faster) -$(BUILD)/vm.o: $(PYSRC)/vm.c - $(CC) $(CFLAGS) -O3 -c -o $@ $< - $(BUILD)/main.o: mpconfigport.h -$(BUILD)/parse.o: $(PYSRC)/grammar.h -$(BUILD)/compile.o: $(PYSRC)/grammar.h -$(BUILD)/emitcpy.o: $(PYSRC)/emit.h -$(BUILD)/emitbc.o: $(PYSRC)/emit.h clean: - /bin/rm -rf $(BUILD) + $(RM) -f $(PROG) + $(RM) -rf $(BUILD) -.PHONY: clean +.PHONY: all clean diff --git a/unix-cpy/main.c b/unix-cpy/main.c index eba97f527..ea85e3275 100644 --- a/unix-cpy/main.c +++ b/unix-cpy/main.c @@ -11,7 +11,6 @@ #include "obj.h" #include "compile.h" #include "runtime0.h" -#include "runtime.h" void do_file(const char *file) { mp_lexer_t *lex = mp_lexer_new_from_file(file); diff --git a/unix-cpy/mpconfigport.h b/unix-cpy/mpconfigport.h index 983b166a5..3fc186677 100644 --- a/unix-cpy/mpconfigport.h +++ b/unix-cpy/mpconfigport.h @@ -1,10 +1,8 @@ // options to control how Micro Python is built -#define MICROPY_ENABLE_FLOAT (1) #define MICROPY_EMIT_CPYTHON (1) -#define MICROPY_EMIT_X64 (0) -#define MICROPY_EMIT_THUMB (0) -#define MICROPY_EMIT_INLINE_THUMB (0) +#define MICROPY_ENABLE_LEXER_UNIX (1) +#define MICROPY_ENABLE_FLOAT (1) // type definitions for the specific machine diff --git a/unix/Makefile b/unix/Makefile index 984f1c3bf..a3faea290 100644 --- a/unix/Makefile +++ b/unix/Makefile @@ -1,106 +1,39 @@ -PYSRC=../py -BUILD=build +# define main target +PROG = py +all: $(PROG) + +# include py core make definitions +include ../py/py.mk +# program for deletion +RM = /bin/rm + +# compiler settings CC = gcc -CFLAGS = -I. -I$(PYSRC) -Wall -Werror -ansi -std=gnu99 -Os #-DNDEBUG +CFLAGS = -I. -I$(PY_SRC) -Wall -Werror -ansi -std=gnu99 -Os #-DNDEBUG LDFLAGS = -lm +# source files SRC_C = \ main.c \ -PY_O = \ - nlrx86.o \ - nlrx64.o \ - nlrthumb.o \ - malloc.o \ - qstr.o \ - vstr.o \ - unicode.o \ - lexer.o \ - lexerunix.o \ - parse.o \ - scope.o \ - compile.o \ - emitcommon.o \ - emitpass1.o \ - emitcpy.o \ - emitbc.o \ - asmx64.o \ - emitnx64.o \ - asmthumb.o \ - emitnthumb.o \ - emitinlinethumb.o \ - runtime.o \ - map.o \ - obj.o \ - objbool.o \ - objboundmeth.o \ - objcell.o \ - objclass.o \ - objclosure.o \ - objcomplex.o \ - objdict.o \ - objexcept.o \ - objfloat.o \ - objfun.o \ - objgenerator.o \ - objinstance.o \ - objint.o \ - objlist.o \ - objmodule.o \ - objnone.o \ - objrange.o \ - objset.o \ - objslice.o \ - objstr.o \ - objtuple.o \ - objtype.o \ - builtin.o \ - builtinimport.o \ - vm.o \ - showbc.o \ - repl.o \ - -OBJ = $(addprefix $(BUILD)/, $(SRC_C:.c=.o) $(PY_O)) +OBJ = $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) $(PY_O) LIB = -lreadline # the following is needed for BSD #LIB += -ltermcap -PROG = py $(PROG): $(BUILD) $(OBJ) $(CC) -o $@ $(OBJ) $(LIB) $(LDFLAGS) strip $(PROG) size $(PROG) -$(BUILD): - mkdir -p $@ - $(BUILD)/%.o: %.c $(CC) $(CFLAGS) -c -o $@ $< -$(BUILD)/%.o: $(PYSRC)/%.S - $(CC) $(CFLAGS) -c -o $@ $< - -$(BUILD)/%.o: $(PYSRC)/%.c mpconfigport.h - $(CC) $(CFLAGS) -c -o $@ $< - -$(BUILD)/emitnx64.o: $(PYSRC)/emitnative.c $(PYSRC)/emit.h mpconfigport.h - $(CC) $(CFLAGS) -DN_X64 -c -o $@ $< - -$(BUILD)/emitnthumb.o: $(PYSRC)/emitnative.c $(PYSRC)/emit.h mpconfigport.h - $(CC) $(CFLAGS) -DN_THUMB -c -o $@ $< - -# optimising vm for speed, adds only a small amount to code size but makes a huge difference to speed (20% faster) -$(BUILD)/vm.o: $(PYSRC)/vm.c - $(CC) $(CFLAGS) -O3 -c -o $@ $< - $(BUILD)/main.o: mpconfigport.h -$(BUILD)/parse.o: $(PYSRC)/grammar.h -$(BUILD)/compile.o: $(PYSRC)/grammar.h -$(BUILD)/emitcpy.o: $(PYSRC)/emit.h -$(BUILD)/emitbc.o: $(PYSRC)/emit.h clean: - /bin/rm -rf $(BUILD) + $(RM) -f $(PROG) + $(RM) -rf $(BUILD) -.PHONY: clean +.PHONY: all clean diff --git a/unix/main.c b/unix/main.c index a06dc3679..920aed344 100644 --- a/unix/main.c +++ b/unix/main.c @@ -20,6 +20,52 @@ #include #endif +static void execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind, bool is_repl) { + if (lex == NULL) { + return; + } + + if (0) { + // just tokenise + while (!mp_lexer_is_kind(lex, MP_TOKEN_END)) { + mp_token_show(mp_lexer_cur(lex)); + mp_lexer_to_next(lex); + } + mp_lexer_free(lex); + return; + } + + mp_parse_node_t pn = mp_parse(lex, input_kind); + mp_lexer_free(lex); + + if (pn == MP_PARSE_NODE_NULL) { + // parse error + return; + } + + //printf("----------------\n"); + //parse_node_show(pn, 0); + //printf("----------------\n"); + + mp_obj_t module_fun = mp_compile(pn, is_repl); + + if (module_fun == mp_const_none) { + // compile error + return; + } + + // execute it + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + rt_call_function_0(module_fun); + nlr_pop(); + } else { + // uncaught exception + mp_obj_print((mp_obj_t)nlr.ret_val); + printf("\n"); + } +} + static char *str_join(const char *s1, int sep_char, const char *s2) { int l1 = strlen(s1); int l2 = strlen(s2); @@ -80,28 +126,11 @@ static void do_repl(void) { } mp_lexer_t *lex = mp_lexer_new_from_str_len("", line, strlen(line), false); - mp_parse_node_t pn = mp_parse(lex, MP_PARSE_SINGLE_INPUT); - mp_lexer_free(lex); - - if (pn != MP_PARSE_NODE_NULL) { - //mp_parse_node_show(pn, 0); - mp_obj_t module_fun = mp_compile(pn, true); - if (module_fun != mp_const_none) { - nlr_buf_t nlr; - if (nlr_push(&nlr) == 0) { - rt_call_function_0(module_fun); - nlr_pop(); - } else { - // uncaught exception - mp_obj_print((mp_obj_t)nlr.ret_val); - printf("\n"); - } - } - } + execute_from_lexer(lex, MP_PARSE_SINGLE_INPUT, true); } } -void do_file(const char *file) { +static void do_file(const char *file) { // hack: set dir for import based on where this file is { const char * s = strrchr(file, '/'); @@ -115,58 +144,17 @@ void do_file(const char *file) { } mp_lexer_t *lex = mp_lexer_new_from_file(file); - //const char *pysrc = "def f():\n x=x+1\n print(42)\n"; - //mp_lexer_t *lex = mp_lexer_from_str_len("<>", pysrc, strlen(pysrc), false); - if (lex == NULL) { - return; - } - - if (0) { - // just tokenise - while (!mp_lexer_is_kind(lex, MP_TOKEN_END)) { - mp_token_show(mp_lexer_cur(lex)); - mp_lexer_to_next(lex); - } - mp_lexer_free(lex); - - } else { - // compile - - mp_parse_node_t pn = mp_parse(lex, MP_PARSE_FILE_INPUT); - mp_lexer_free(lex); - - if (pn != MP_PARSE_NODE_NULL) { - //printf("----------------\n"); - //parse_node_show(pn, 0); - //printf("----------------\n"); - mp_obj_t module_fun = mp_compile(pn, false); - //printf("----------------\n"); + execute_from_lexer(lex, MP_PARSE_FILE_INPUT, false); +} -#if MICROPY_EMIT_CPYTHON - if (!comp_ok) { - printf("compile error\n"); - } -#else - if (1 && module_fun != mp_const_none) { - // execute it - nlr_buf_t nlr; - if (nlr_push(&nlr) == 0) { - rt_call_function_0(module_fun); - nlr_pop(); - } else { - // uncaught exception - mp_obj_print((mp_obj_t)nlr.ret_val); - printf("\n"); - } - } -#endif - } - } +static void do_str(const char *str) { + mp_lexer_t *lex = mp_lexer_new_from_str_len("", str, strlen(str), false); + execute_from_lexer(lex, MP_PARSE_SINGLE_INPUT, false); } typedef struct _test_obj_t { mp_obj_base_t base; - bool value; + int value; } test_obj_t; static void test_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in) { @@ -188,21 +176,17 @@ static mp_obj_t test_set(mp_obj_t self_in, mp_obj_t arg) { static MP_DEFINE_CONST_FUN_OBJ_1(test_get_obj, test_get); static MP_DEFINE_CONST_FUN_OBJ_2(test_set_obj, test_set); +static const mp_method_t test_methods[] = { + { "get", &test_get_obj }, + { "set", &test_set_obj }, + { NULL, NULL }, +}; + static const mp_obj_type_t test_type = { { &mp_const_type }, "Test", .print = test_print, - .make_new = NULL, - .call_n = NULL, - .unary_op = NULL, - .binary_op = NULL, - .getiter = NULL, - .iternext = NULL, - .methods = { - { "get", &test_get_obj }, - { "set", &test_set_obj }, - { NULL, NULL }, - } + .methods = test_methods, }; mp_obj_t test_obj_new(int value) { @@ -212,6 +196,11 @@ mp_obj_t test_obj_new(int value) { return o; } +int usage(void) { + printf("usage: py [-c ] []\n"); + return 1; +} + int main(int argc, char **argv) { qstr_init(); rt_init(); @@ -227,12 +216,24 @@ int main(int argc, char **argv) { if (argc == 1) { do_repl(); - } else if (argc == 2) { - do_file(argv[1]); } else { - printf("usage: py []\n"); - return 1; + for (int a = 1; a < argc; a++) { + if (argv[a][0] == '-') { + if (strcmp(argv[a], "-c") == 0) { + if (a + 1 >= argc) { + return usage(); + } + do_str(argv[a + 1]); + a += 1; + } else { + return usage(); + } + } else { + do_file(argv[a]); + } + } } + rt_deinit(); //printf("total bytes = %d\n", m_get_total_bytes_allocated()); diff --git a/unix/mpconfigport.h b/unix/mpconfigport.h index 7a4622b8b..832764121 100644 --- a/unix/mpconfigport.h +++ b/unix/mpconfigport.h @@ -5,11 +5,13 @@ #define MICROPY_USE_READLINE (1) #endif -#define MICROPY_ENABLE_FLOAT (1) -#define MICROPY_EMIT_CPYTHON (0) #define MICROPY_EMIT_X64 (1) #define MICROPY_EMIT_THUMB (0) #define MICROPY_EMIT_INLINE_THUMB (0) +#define MICROPY_MEM_STATS (1) +#define MICROPY_ENABLE_REPL_HELPERS (1) +#define MICROPY_ENABLE_LEXER_UNIX (1) +#define MICROPY_ENABLE_FLOAT (1) // type definitions for the specific machine -- cgit v1.2.3 From baa665406fef58cfb0be0df8d2798ed0961506da Mon Sep 17 00:00:00 2001 From: John R. Lenton Date: Tue, 7 Jan 2014 23:18:25 +0000 Subject: Moved dict methods out to a mp_method_t. --- py/objdict.c | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/py/objdict.c b/py/objdict.c index 7cfd597ed..c36d4ccb0 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -102,7 +102,6 @@ static const mp_obj_type_t dict_it_type = { { &mp_const_type }, "dict_iterator", .iternext = dict_it_iternext, - .methods = { { NULL, NULL }, }, }; static mp_obj_t mp_obj_new_dict_iterator(mp_obj_dict_t *dict, int cur) { @@ -250,6 +249,17 @@ static MP_DEFINE_CONST_FUN_OBJ_2(dict_update_obj, dict_update); /******************************************************************************/ /* dict constructors & etc */ +static const mp_method_t dict_type_methods[] = { + { "clear", &dict_clear_obj }, + { "copy", &dict_copy_obj }, + { "get", &dict_get_obj }, + { "pop", &dict_pop_obj }, + { "popitem", &dict_popitem_obj }, + { "setdefault", &dict_setdefault_obj }, + { "update", &dict_update_obj }, + { NULL, NULL }, // end-of-list sentinel +}; + const mp_obj_type_t dict_type = { { &mp_const_type }, "dict", @@ -257,16 +267,7 @@ const mp_obj_type_t dict_type = { .make_new = dict_make_new, .binary_op = dict_binary_op, .getiter = dict_getiter, - .methods = { - { "clear", &dict_clear_obj }, - { "copy", &dict_copy_obj }, - { "get", &dict_get_obj }, - { "pop", &dict_pop_obj }, - { "popitem", &dict_popitem_obj }, - { "setdefault", &dict_setdefault_obj }, - { "update", &dict_update_obj }, - { NULL, NULL }, // end-of-list sentinel - }, + .methods = dict_type_methods, }; mp_obj_t mp_obj_new_dict(int n_args) { -- cgit v1.2.3