add pikapython example

This commit is contained in:
lyon 2023-01-11 17:27:36 +08:00 committed by sakumisu
parent a574195a4b
commit 15f764ee5e
97 changed files with 21607 additions and 0 deletions

View File

@ -0,0 +1,17 @@
cmake_minimum_required(VERSION 3.15)
include(proj.conf)
find_package(bouffalo_sdk REQUIRED HINTS $ENV{BL_SDK_BASE})
file(GLOB_RECURSE sources "${CMAKE_CURRENT_SOURCE_DIR}/pikapython/*.c")
target_sources(app PRIVATE ${sources})
sdk_add_include_directories(.)
sdk_add_include_directories(pikapython/pikascript-core)
sdk_add_include_directories(pikapython/pikascript-api)
sdk_set_main_file(main.c)
project(pikapython)

View File

@ -0,0 +1,13 @@
SDK_DEMO_PATH ?= .
BL_SDK_BASE ?= $(SDK_DEMO_PATH)/../..
export BL_SDK_BASE
CHIP ?= bl602
BOARD ?= bl602dk
CROSS_COMPILE ?= riscv64-unknown-elf-
# add custom cmake definition
#cmake_definition+=-Dxxx=sss
include $(BL_SDK_BASE)/project.build

View File

@ -0,0 +1,11 @@
#include <stdlib.h>
#include "board.h"
#include "ff.h"
#include "log.h"
#include "pikaScript.h"
#include "vlibc_stdio.h"
int main(void) {
board_init();
pikaScriptInit();
}

View File

@ -0,0 +1,6 @@
class Debuger:
def __init__(self):
pass
def set_trace(self):
pass

View File

@ -0,0 +1,24 @@
class TinyObj:
...
class BaseObj(TinyObj):
...
class pointer:
...
class any:
...
class int64:
...
def printNoEnd(val: any): ...
def abstractmethod(fn): ...
def PIKA_C_MACRO_IF(fn): ...
def PIKA_C_MACRO_IFDEF(fn): ...

View File

@ -0,0 +1,171 @@
from PikaObj import *
class Tuple:
def __init__(self): ...
def get(self, i: int) -> any:
"""get an arg by the index"""
def len(self) -> int:
"""get the length of list"""
def __iter__(self) -> any:
"""support for loop"""
def __next__(self) -> any:
"""support for loop"""
def __getitem__(self, __key: any) -> any:
"""support val = list[]"""
def __del__(self): ...
def __str__(self) -> str: ...
def __len__(self) -> int: ...
def __contains__(self, val: any) -> int:
""" support val in list """
class List(Tuple):
def __init__(self): ...
def append(self, arg: any):
"""add an arg after the end of list"""
def set(self, i: int, arg: any):
"""set an arg by the index"""
def reverse(self):
"""reverse the list"""
def pop(self) -> any:
"""pop the last element"""
def remove(self, val: any):
"""remove the first element"""
def insert(self, i: int, arg: any):
"""insert an arg before the index"""
def __setitem__(self, __key: any, __val: any):
"""support list[] = val"""
def __str__(self) -> str: ...
def __add__(self, others: List) -> List:
""" support list + list"""
class Dict:
def __init__(self):
""" get an arg by the key """
def get(self, key: str) -> any: ...
def set(self, key: str, arg: any):
""" set an arg by the key """
def remove(self, key: str):
""" remove an arg by the key """
def __iter__(self) -> any: ...
def __next__(self) -> any: ...
def __setitem__(self, __key: any, __val: any):
""" support dict[] = val """
def __getitem__(self, __key: any) -> any:
""" support val = dict[] """
def __del__(self): ...
def __str__(self) -> str: ...
def keys(self) -> dict_keys: ...
def items(self) -> dict_items: ...
def __len__(self) -> int: ...
def __contains__(self, val: any) -> int:
""" support val in dict """
def update(self, other: Dict):
""" update dict """
class dict_keys:
def __iter__(self) -> any: ...
def __next__(self) -> any: ...
def __str__(self) -> str: ...
def __len__(self) -> int: ...
class dict_items:
def __iter__(self) -> any: ...
def __next__(self) -> any: ...
def __str__(self) -> str: ...
def __len__(self) -> int: ...
class String:
def __init__(self, s: str): ...
def set(self, s: str): ...
def get(self) -> str: ...
def __iter__(self) -> any: ...
def __next__(self) -> any: ...
def __setitem__(self, __key: any, __val: any):
""" support string[] = val """
def __getitem__(self, __key: any) -> any:
""" support val = string[] """
def __str__(self) -> str:
""" support str() """
def __len__(self) -> int: ...
def encode(self, *encoding) -> bytes: ...
def startswith(self, prefix: str) -> int: ...
def endswith(self, suffix: str) -> int: ...
def isdigit(self) -> int: ...
def islower(self) -> int: ...
def isalnum(self) -> int: ...
def isalpha(self) -> int: ...
def isspace(self) -> int: ...
def split(self, s: str) -> List: ...
def replace(self, old: str, new: str) -> str: ...
def strip(self, *chrs) -> str: ...
def format(self, *vars) -> str: ...
class ByteArray:
def __init__(self, bytes: any):
""" convert a bytes to ByteArray """
def __iter__(self) -> any:
""" support for loop """
def __next__(self) -> any:
""" support for loop """
def __getitem__(self, __key: int) -> int:
""" support [] index """
def __setitem__(self, __key: int, __val: int): ...
def __str__(self) -> str: ...
def decode(self) -> str: ...
class FILEIO:
def init(self, path: str, mode: str) -> int: ...
def read(self, *size) -> any: ...
def write(self, s: any) -> int: ...
def close(self): ...
def seek(self, offset: int, *fromwhere) -> int: ...
def tell(self) -> int: ...
def readline(self) -> str: ...
def readlines(self) -> List: ...
def writelines(self, lines: List): ...
class Utils:
def int_to_bytes(self, val: int) -> bytes:
""" convert a int to bytes """

View File

@ -0,0 +1,130 @@
from PikaObj import *
class MemChecker:
def max(self): ...
def now(self): ...
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def getMax(self) -> float: ...
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def getNow(self) -> float: ...
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def resetMax(self): ...
class SysObj:
@staticmethod
def int(arg: any) -> int: ...
@staticmethod
def float(arg: any) -> float: ...
@staticmethod
def str(arg: any) -> str: ...
@staticmethod
def iter(arg: any) -> any: ...
@staticmethod
def range(*ax) -> any: ...
@staticmethod
def print(*val, **ops): ...
@staticmethod
def __setitem__(obj: any, key: any, val: any) -> any: ...
@staticmethod
def __getitem__(obj: any, key: any) -> any: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def type(arg: any) -> any: ...
@staticmethod
def len(arg: any) -> int: ...
@staticmethod
@PIKA_C_MACRO_IF("PIKA_BUILTIN_STRUCT_ENABLE")
def list(*val) -> any: ...
@staticmethod
@PIKA_C_MACRO_IF("PIKA_BUILTIN_STRUCT_ENABLE")
def dict(*val) -> any: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def hex(val: int) -> str: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def ord(val: str) -> int: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def chr(val: int) -> str: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def bytes(val: any) -> bytes: ...
@staticmethod
@PIKA_C_MACRO_IF("PIKA_SYNTAX_FORMAT_ENABLE")
def cformat(fmt: str, *var) -> str: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def id(obj: any) -> int: ...
@staticmethod
@PIKA_C_MACRO_IF("PIKA_FILEIO_ENABLE")
def open(path: str, mode: str) -> object: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def dir(obj: object) -> list: ...
@staticmethod
@PIKA_C_MACRO_IF("PIKA_EXEC_ENABLE")
def exec(code: str): ...
@staticmethod
@PIKA_C_MACRO_IF("PIKA_EXEC_ENABLE")
def eval(code: str) -> any: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def getattr(obj: object, name: str) -> any: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def setattr(obj: object, name: str, val: any): ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def hasattr(obj: object, name: str) -> int: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def exit(): ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def input(*info) -> str: ...
@staticmethod
@PIKA_C_MACRO_IF("!PIKA_NANO_ENABLE")
def help(name: str): ...
@PIKA_C_MACRO_IF("0")
class RangeObj:
def __next__(self) -> any: ...
@PIKA_C_MACRO_IF("0")
class StringObj:
def __next__(self) -> any: ...

View File

@ -0,0 +1,37 @@
import PikaStdData
import PikaStdLib
class Task(PikaStdLib.SysObj):
calls = PikaStdData.List()
def __init__(self):
pass
# regist a function to be called always
def call_always(self, fun_todo: any):
pass
# regist a function to be called when fun_when() return 'True'
def call_when(self, fun_todo: any, fun_when: any):
pass
# regist a function to be called periodically
def call_period_ms(self, fun_todo: any, period_ms: int):
pass
# run all registed function once
def run_once(self):
pass
# run all registed function forever
def run_forever(self):
pass
# run all registed function until time is up
def run_until_ms(self, until_ms: int):
pass
# need be overried to supply the system tick
def platformGetTick(self):
pass

View File

@ -0,0 +1 @@
print('hello PikaPython!')

Binary file not shown.

View File

@ -0,0 +1,22 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaDebug__H
#define __PikaDebug__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaDebug(Args *args);
Arg* PikaDebug_Debuger(PikaObj *self);
#endif

View File

@ -0,0 +1,23 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaDebug_Debuger__H
#define __PikaDebug_Debuger__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaDebug_Debuger(Args *args);
void PikaDebug_Debuger___init__(PikaObj *self);
void PikaDebug_Debuger_set_trace(PikaObj *self);
#endif

View File

@ -0,0 +1,21 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaMain__H
#define __PikaMain__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaMain(Args *args);
#endif

View File

@ -0,0 +1,30 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdData__H
#define __PikaStdData__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdData(Args *args);
Arg* PikaStdData_ByteArray(PikaObj *self);
Arg* PikaStdData_Dict(PikaObj *self);
Arg* PikaStdData_FILEIO(PikaObj *self);
Arg* PikaStdData_List(PikaObj *self);
Arg* PikaStdData_String(PikaObj *self);
Arg* PikaStdData_Tuple(PikaObj *self);
Arg* PikaStdData_Utils(PikaObj *self);
Arg* PikaStdData_dict_items(PikaObj *self);
Arg* PikaStdData_dict_keys(PikaObj *self);
#endif

View File

@ -0,0 +1,28 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdData_ByteArray__H
#define __PikaStdData_ByteArray__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdData_ByteArray(Args *args);
int PikaStdData_ByteArray___getitem__(PikaObj *self, int __key);
void PikaStdData_ByteArray___init__(PikaObj *self, Arg* bytes);
Arg* PikaStdData_ByteArray___iter__(PikaObj *self);
Arg* PikaStdData_ByteArray___next__(PikaObj *self);
void PikaStdData_ByteArray___setitem__(PikaObj *self, int __key, int __val);
char* PikaStdData_ByteArray___str__(PikaObj *self);
char* PikaStdData_ByteArray_decode(PikaObj *self);
#endif

View File

@ -0,0 +1,36 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdData_Dict__H
#define __PikaStdData_Dict__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdData_Dict(Args *args);
int PikaStdData_Dict___contains__(PikaObj *self, Arg* val);
void PikaStdData_Dict___del__(PikaObj *self);
Arg* PikaStdData_Dict___getitem__(PikaObj *self, Arg* __key);
void PikaStdData_Dict___init__(PikaObj *self);
Arg* PikaStdData_Dict___iter__(PikaObj *self);
int PikaStdData_Dict___len__(PikaObj *self);
Arg* PikaStdData_Dict___next__(PikaObj *self);
void PikaStdData_Dict___setitem__(PikaObj *self, Arg* __key, Arg* __val);
char* PikaStdData_Dict___str__(PikaObj *self);
Arg* PikaStdData_Dict_get(PikaObj *self, char* key);
PikaObj* PikaStdData_Dict_items(PikaObj *self);
PikaObj* PikaStdData_Dict_keys(PikaObj *self);
void PikaStdData_Dict_remove(PikaObj *self, char* key);
void PikaStdData_Dict_set(PikaObj *self, char* key, Arg* arg);
void PikaStdData_Dict_update(PikaObj *self, PikaObj* other);
#endif

View File

@ -0,0 +1,30 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdData_FILEIO__H
#define __PikaStdData_FILEIO__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdData_FILEIO(Args *args);
void PikaStdData_FILEIO_close(PikaObj *self);
int PikaStdData_FILEIO_init(PikaObj *self, char* path, char* mode);
Arg* PikaStdData_FILEIO_read(PikaObj *self, PikaTuple* size);
char* PikaStdData_FILEIO_readline(PikaObj *self);
PikaObj* PikaStdData_FILEIO_readlines(PikaObj *self);
int PikaStdData_FILEIO_seek(PikaObj *self, int offset, PikaTuple* fromwhere);
int PikaStdData_FILEIO_tell(PikaObj *self);
int PikaStdData_FILEIO_write(PikaObj *self, Arg* s);
void PikaStdData_FILEIO_writelines(PikaObj *self, PikaObj* lines);
#endif

View File

@ -0,0 +1,31 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdData_List__H
#define __PikaStdData_List__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdData_List(Args *args);
PikaObj* PikaStdData_List___add__(PikaObj *self, PikaObj* others);
void PikaStdData_List___init__(PikaObj *self);
void PikaStdData_List___setitem__(PikaObj *self, Arg* __key, Arg* __val);
char* PikaStdData_List___str__(PikaObj *self);
void PikaStdData_List_append(PikaObj *self, Arg* arg);
void PikaStdData_List_insert(PikaObj *self, int i, Arg* arg);
Arg* PikaStdData_List_pop(PikaObj *self);
void PikaStdData_List_remove(PikaObj *self, Arg* val);
void PikaStdData_List_reverse(PikaObj *self);
void PikaStdData_List_set(PikaObj *self, int i, Arg* arg);
#endif

View File

@ -0,0 +1,42 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdData_String__H
#define __PikaStdData_String__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdData_String(Args *args);
Arg* PikaStdData_String___getitem__(PikaObj *self, Arg* __key);
void PikaStdData_String___init__(PikaObj *self, char* s);
Arg* PikaStdData_String___iter__(PikaObj *self);
int PikaStdData_String___len__(PikaObj *self);
Arg* PikaStdData_String___next__(PikaObj *self);
void PikaStdData_String___setitem__(PikaObj *self, Arg* __key, Arg* __val);
char* PikaStdData_String___str__(PikaObj *self);
Arg* PikaStdData_String_encode(PikaObj *self, PikaTuple* encoding);
int PikaStdData_String_endswith(PikaObj *self, char* suffix);
char* PikaStdData_String_format(PikaObj *self, PikaTuple* vars);
char* PikaStdData_String_get(PikaObj *self);
int PikaStdData_String_isalnum(PikaObj *self);
int PikaStdData_String_isalpha(PikaObj *self);
int PikaStdData_String_isdigit(PikaObj *self);
int PikaStdData_String_islower(PikaObj *self);
int PikaStdData_String_isspace(PikaObj *self);
char* PikaStdData_String_replace(PikaObj *self, char* old, char* new);
void PikaStdData_String_set(PikaObj *self, char* s);
PikaObj* PikaStdData_String_split(PikaObj *self, char* s);
int PikaStdData_String_startswith(PikaObj *self, char* prefix);
char* PikaStdData_String_strip(PikaObj *self, PikaTuple* chrs);
#endif

View File

@ -0,0 +1,31 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdData_Tuple__H
#define __PikaStdData_Tuple__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdData_Tuple(Args *args);
int PikaStdData_Tuple___contains__(PikaObj *self, Arg* val);
void PikaStdData_Tuple___del__(PikaObj *self);
Arg* PikaStdData_Tuple___getitem__(PikaObj *self, Arg* __key);
void PikaStdData_Tuple___init__(PikaObj *self);
Arg* PikaStdData_Tuple___iter__(PikaObj *self);
int PikaStdData_Tuple___len__(PikaObj *self);
Arg* PikaStdData_Tuple___next__(PikaObj *self);
char* PikaStdData_Tuple___str__(PikaObj *self);
Arg* PikaStdData_Tuple_get(PikaObj *self, int i);
int PikaStdData_Tuple_len(PikaObj *self);
#endif

View File

@ -0,0 +1,22 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdData_Utils__H
#define __PikaStdData_Utils__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdData_Utils(Args *args);
Arg* PikaStdData_Utils_int_to_bytes(PikaObj *self, int val);
#endif

View File

@ -0,0 +1,25 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdData_dict_items__H
#define __PikaStdData_dict_items__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdData_dict_items(Args *args);
Arg* PikaStdData_dict_items___iter__(PikaObj *self);
int PikaStdData_dict_items___len__(PikaObj *self);
Arg* PikaStdData_dict_items___next__(PikaObj *self);
char* PikaStdData_dict_items___str__(PikaObj *self);
#endif

View File

@ -0,0 +1,25 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdData_dict_keys__H
#define __PikaStdData_dict_keys__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdData_dict_keys(Args *args);
Arg* PikaStdData_dict_keys___iter__(PikaObj *self);
int PikaStdData_dict_keys___len__(PikaObj *self);
Arg* PikaStdData_dict_keys___next__(PikaObj *self);
char* PikaStdData_dict_keys___str__(PikaObj *self);
#endif

View File

@ -0,0 +1,25 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdLib__H
#define __PikaStdLib__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdLib(Args *args);
Arg* PikaStdLib_MemChecker(PikaObj *self);
Arg* PikaStdLib_RangeObj(PikaObj *self);
Arg* PikaStdLib_StringObj(PikaObj *self);
Arg* PikaStdLib_SysObj(PikaObj *self);
#endif

View File

@ -0,0 +1,26 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdLib_MemChecker__H
#define __PikaStdLib_MemChecker__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdLib_MemChecker(Args *args);
pika_float PikaStdLib_MemChecker_getMax(PikaObj *self);
pika_float PikaStdLib_MemChecker_getNow(PikaObj *self);
void PikaStdLib_MemChecker_max(PikaObj *self);
void PikaStdLib_MemChecker_now(PikaObj *self);
void PikaStdLib_MemChecker_resetMax(PikaObj *self);
#endif

View File

@ -0,0 +1,22 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdLib_RangeObj__H
#define __PikaStdLib_RangeObj__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdLib_RangeObj(Args *args);
Arg* PikaStdLib_RangeObj___next__(PikaObj *self);
#endif

View File

@ -0,0 +1,22 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdLib_StringObj__H
#define __PikaStdLib_StringObj__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdLib_StringObj(Args *args);
Arg* PikaStdLib_StringObj___next__(PikaObj *self);
#endif

View File

@ -0,0 +1,49 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdLib_SysObj__H
#define __PikaStdLib_SysObj__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdLib_SysObj(Args *args);
Arg* PikaStdLib_SysObj___getitem__(PikaObj *self, Arg* obj, Arg* key);
Arg* PikaStdLib_SysObj___setitem__(PikaObj *self, Arg* obj, Arg* key, Arg* val);
Arg* PikaStdLib_SysObj_bytes(PikaObj *self, Arg* val);
char* PikaStdLib_SysObj_cformat(PikaObj *self, char* fmt, PikaTuple* var);
char* PikaStdLib_SysObj_chr(PikaObj *self, int val);
Arg* PikaStdLib_SysObj_dict(PikaObj *self, PikaTuple* val);
PikaObj* PikaStdLib_SysObj_dir(PikaObj *self, PikaObj* obj);
Arg* PikaStdLib_SysObj_eval(PikaObj *self, char* code);
void PikaStdLib_SysObj_exec(PikaObj *self, char* code);
void PikaStdLib_SysObj_exit(PikaObj *self);
pika_float PikaStdLib_SysObj_float(PikaObj *self, Arg* arg);
Arg* PikaStdLib_SysObj_getattr(PikaObj *self, PikaObj* obj, char* name);
int PikaStdLib_SysObj_hasattr(PikaObj *self, PikaObj* obj, char* name);
void PikaStdLib_SysObj_help(PikaObj *self, char* name);
char* PikaStdLib_SysObj_hex(PikaObj *self, int val);
int PikaStdLib_SysObj_id(PikaObj *self, Arg* obj);
char* PikaStdLib_SysObj_input(PikaObj *self, PikaTuple* info);
int PikaStdLib_SysObj_int(PikaObj *self, Arg* arg);
Arg* PikaStdLib_SysObj_iter(PikaObj *self, Arg* arg);
int PikaStdLib_SysObj_len(PikaObj *self, Arg* arg);
Arg* PikaStdLib_SysObj_list(PikaObj *self, PikaTuple* val);
PikaObj* PikaStdLib_SysObj_open(PikaObj *self, char* path, char* mode);
int PikaStdLib_SysObj_ord(PikaObj *self, char* val);
void PikaStdLib_SysObj_print(PikaObj *self, PikaTuple* val, PikaDict* ops);
Arg* PikaStdLib_SysObj_range(PikaObj *self, PikaTuple* ax);
void PikaStdLib_SysObj_setattr(PikaObj *self, PikaObj* obj, char* name, Arg* val);
char* PikaStdLib_SysObj_str(PikaObj *self, Arg* arg);
Arg* PikaStdLib_SysObj_type(PikaObj *self, Arg* arg);
#endif

View File

@ -0,0 +1,22 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdTask__H
#define __PikaStdTask__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdTask(Args *args);
Arg* PikaStdTask_Task(PikaObj *self);
#endif

View File

@ -0,0 +1,29 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#ifndef __PikaStdTask_Task__H
#define __PikaStdTask_Task__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
PikaObj *New_PikaStdTask_Task(Args *args);
void PikaStdTask_Task___init__(PikaObj *self);
void PikaStdTask_Task_call_always(PikaObj *self, Arg* fun_todo);
void PikaStdTask_Task_call_period_ms(PikaObj *self, Arg* fun_todo, int period_ms);
void PikaStdTask_Task_call_when(PikaObj *self, Arg* fun_todo, Arg* fun_when);
void PikaStdTask_Task_platformGetTick(PikaObj *self);
void PikaStdTask_Task_run_forever(PikaObj *self);
void PikaStdTask_Task_run_once(PikaObj *self);
void PikaStdTask_Task_run_until_ms(PikaObj *self, int until_ms);
#endif

View File

@ -0,0 +1,14 @@
#include "PikaPlatform.h"
/* warning: auto generated file, please do not modify */
PIKA_BYTECODE_ALIGN const unsigned char pikaModules_py_a[] = {
0x7f, 0x70, 0x79, 0x61, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x2c, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x10, 0x83, 0x01, 0x00,
0x00, 0x02, 0x13, 0x00, 0x19, 0x00, 0x00, 0x00, 0x00, 0x68, 0x65, 0x6c,
0x6c, 0x6f, 0x20, 0x50, 0x69, 0x6b, 0x61, 0x50, 0x79, 0x74, 0x68, 0x6f,
0x6e, 0x21, 0x00, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x00, 0x00, 0x00, 0x00,
0x00,
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,35 @@
/*
* [Warning!] This file is auto-generated by pika compiler.
* Do not edit it manually.
* The source code is *.pyi file.
* More details:
* English Doc:
* https://pikadoc.readthedocs.io/en/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
* Chinese Doc:
* https://pikadoc.readthedocs.io/zh/latest/PikaScript%20%E6%A8%A1%E5%9D%97%E6%A6%82%E8%BF%B0.html
*/
#include "PikaMain.h"
#include <stdio.h>
#include <stdlib.h>
volatile PikaObj *__pikaMain;
PikaObj *pikaScriptInit(void){
__platform_printf("======[pikascript packages installed]======\r\n");
pks_printVersion();
__platform_printf("PikaStdLib==v1.12.0\r\n");
__platform_printf("===========================================\r\n");
PikaObj* pikaMain = newRootObj("pikaMain", New_PikaMain);
__pikaMain = pikaMain;
extern unsigned char pikaModules_py_a[];
obj_linkLibrary(pikaMain, pikaModules_py_a);
#if PIKA_INIT_STRING_ENABLE
obj_run(pikaMain,
"print('hello PikaPython!')\n"
"\n");
#else
obj_runModule((PikaObj*)pikaMain, "main");
#endif
return pikaMain;
}

View File

@ -0,0 +1,13 @@
/* ******************************** */
/* Warning! Don't modify this file! */
/* ******************************** */
#ifndef __pikaScript__H
#define __pikaScript__H
#include <stdio.h>
#include <stdlib.h>
#include "PikaObj.h"
#include "PikaMain.h"
PikaObj * pikaScriptInit(void);
#endif

View File

@ -0,0 +1,43 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "BaseObj.h"
#include "PikaObj.h"
#include "TinyObj.h"
#include "dataMemory.h"
#include "dataString.h"
#include "dataStrs.h"
extern const NativeProperty TinyObjNativeProp;
const NativeProperty BaseObjNativeProp = {.super = &TinyObjNativeProp,
.methodGroup = NULL,
.methodGroupCount = 0};
PikaObj* New_BaseObj(Args* args) {
PikaObj* self = New_TinyObj(args);
return self;
}

View File

@ -0,0 +1,38 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef _PikaObj_baseObj__H
#define _PikaObj_baseObj__H
#include "PikaObj.h"
#include "PikaVM.h"
#include "TinyObj.h"
#include "dataMemory.h"
PikaObj* New_BaseObj(Args* args);
void Baseobj_print(PikaObj* self, Args* args);
#endif

View File

@ -0,0 +1,9 @@
# BINARY IndexProject
set(BINARY ${CMAKE_PROJECT_NAME})
file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.c)
set(SOURCES ${SOURCES})
add_library(${BINARY}-core
STATIC
${SOURCES})

View File

@ -0,0 +1,840 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "PikaCompiler.h"
#include "BaseObj.h"
#include "PikaObj.h"
#include "PikaParser.h"
#include "dataQueue.h"
#include "dataQueueObj.h"
#include "dataStack.h"
#include "dataStrs.h"
const char magic_code_pyo[] = {0x0f, 'p', 'y', 'o'};
static PIKA_BOOL _check_magic_code_pyo(uint8_t* bytecode) {
char* data = (char*)bytecode;
if (data[0] == magic_code_pyo[0] && data[1] == magic_code_pyo[1] &&
data[2] == magic_code_pyo[2] && data[3] == magic_code_pyo[3]) {
return PIKA_TRUE;
}
return PIKA_FALSE;
}
static uint8_t* arg_getBytecode(Arg* self) {
uint8_t* bytecode_file = arg_getBytes(self);
if (_check_magic_code_pyo(bytecode_file)) {
return bytecode_file + sizeof(magic_code_pyo) + sizeof(uint32_t);
}
return bytecode_file;
}
static size_t arg_getBytecodeSize(Arg* self) {
size_t size_all = arg_getBytesSize(self);
uint8_t* bytecode_file = arg_getBytes(self);
if (_check_magic_code_pyo(bytecode_file)) {
return size_all - sizeof(magic_code_pyo) - sizeof(uint32_t);
}
return size_all;
}
/* const Pool output redirect */
static void __handler_constPool_output_file(ConstPool* self, char* content) {
/* to ram */
uint16_t size = strGetSize(content) + 1;
self->arg_buff = arg_append(self->arg_buff, content, size);
/* to flash */
pika_platform_fwrite(content, 1, size, self->output_f);
}
/* instruct array output redirect */
static void __handler_instructArray_output_none(InstructArray* self,
InstructUnit* ins_unit) {
/* none */
}
static void __handler_instructArray_output_file(InstructArray* self,
InstructUnit* ins_unit) {
/* to flash */
pika_platform_fwrite(ins_unit, 1, instructUnit_getSize(), self->output_f);
}
/*
need implament :
pika_platform_fopen()
pika_platform_fwrite()
pika_platform_fclose()
*/
PIKA_RES pikaCompile(char* output_file_name, char* py_lines) {
PIKA_RES res = PIKA_RES_OK;
ByteCodeFrame bytecode_frame = {0};
uint32_t const_pool_size = 0;
uint32_t instruct_array_size = 0;
uint32_t bytecode_size = 0;
char void_ = 0;
FILE* bytecode_f = pika_platform_fopen(output_file_name, "wb+");
if (NULL == bytecode_f) {
pika_platform_printf("Error: open file %s failed.\r\n", output_file_name);
res = PIKA_RES_ERR_IO_ERROR;
goto exit;
}
/* main process */
/* step 1, get size of const pool and instruct array */
byteCodeFrame_init(&bytecode_frame);
bytecode_frame.const_pool.output_f = bytecode_f;
bytecode_frame.instruct_array.output_f = bytecode_f;
bytecode_frame.instruct_array.output_redirect_fun =
__handler_instructArray_output_none;
res = Parser_linesToBytes(&bytecode_frame, py_lines);
if (PIKA_RES_OK != res) {
pika_platform_printf(" Error: Syntax error.\r\n");
goto exit;
}
const_pool_size = bytecode_frame.const_pool.size;
instruct_array_size = bytecode_frame.instruct_array.size;
bytecode_size = const_pool_size + instruct_array_size +
sizeof(const_pool_size) +
sizeof(instruct_array_size);
byteCodeFrame_deinit(&bytecode_frame);
/* step 2, write instruct array to file */
/* write magic code */
pika_platform_fwrite(magic_code_pyo, 1, sizeof(magic_code_pyo), bytecode_f);
/* write bytecode size */
pika_platform_fwrite(&bytecode_size, 1, sizeof(bytecode_size), bytecode_f);
/* write ins array size */
pika_platform_fwrite(&instruct_array_size, 1, sizeof(instruct_array_size),
bytecode_f);
byteCodeFrame_init(&bytecode_frame);
bytecode_frame.const_pool.output_f = bytecode_f;
bytecode_frame.instruct_array.output_f = bytecode_f;
/* instruct array to file */
bytecode_frame.instruct_array.output_redirect_fun =
__handler_instructArray_output_file;
Parser_linesToBytes(&bytecode_frame, py_lines);
byteCodeFrame_deinit(&bytecode_frame);
/* step 3, write const pool to file */
pika_platform_fwrite(&const_pool_size, 1, sizeof(const_pool_size), bytecode_f);
void_ = 0;
/* add \0 at the start */
pika_platform_fwrite(&void_, 1, 1, bytecode_f);
byteCodeFrame_init(&bytecode_frame);
bytecode_frame.const_pool.output_f = bytecode_f;
bytecode_frame.instruct_array.output_f = bytecode_f;
/* const pool to file */
bytecode_frame.const_pool.output_redirect_fun =
__handler_constPool_output_file;
/* instruct array to none */
bytecode_frame.instruct_array.output_redirect_fun =
__handler_instructArray_output_none;
Parser_linesToBytes(&bytecode_frame, py_lines);
/* deinit */
exit:
byteCodeFrame_deinit(&bytecode_frame);
if (NULL != bytecode_f) {
pika_platform_fclose(bytecode_f);
}
/* succeed */
return res;
};
/*
need implament :
pika_platform_fopen()
pika_platform_fread()
pika_platform_fwrite()
pika_platform_fclose()
*/
PIKA_RES pikaCompileFileWithOutputName(char* output_file_name,
char* input_file_name) {
Args buffs = {0};
Arg* input_file_arg = arg_loadFile(NULL, input_file_name);
if (NULL == input_file_arg) {
return PIKA_RES_ERR_IO_ERROR;
}
char* lines = (char*)arg_getBytes(input_file_arg);
/* replace the "\r\n" to "\n" */
lines = strsReplace(&buffs, lines, "\r\n", "\n");
/* clear the void line */
lines = strsReplace(&buffs, lines, "\n\n", "\n");
/* add '\n' at the end */
lines = strsAppend(&buffs, lines, "\n\n");
PIKA_RES res = pikaCompile(output_file_name, lines);
arg_deinit(input_file_arg);
strsDeinit(&buffs);
return res;
}
PIKA_RES pikaCompileFile(char* input_file_name) {
Args buffs = {0};
char* output_file_name = strsGetFirstToken(&buffs, input_file_name, '.');
output_file_name = strsAppend(&buffs, input_file_name, ".o");
PIKA_RES res =
pikaCompileFileWithOutputName(output_file_name, input_file_name);
strsDeinit(&buffs);
return res;
}
LibObj* New_LibObj(Args* args) {
LibObj* self = New_TinyObj(NULL);
return self;
}
void LibObj_deinit(LibObj* self) {
obj_deinit(self);
}
/* add bytecode to lib, not copy the bytecode */
void LibObj_dynamicLink(LibObj* self, char* module_name, uint8_t* bytecode) {
if (strIsContain(module_name, '.')) {
/* skip file */
return;
}
if (!obj_isArgExist(self, module_name)) {
obj_newObj(self, module_name, "", New_TinyObj);
}
PikaObj* module_obj = obj_getObj(self, module_name);
obj_setStr(module_obj, "name", module_name);
obj_setPtr(module_obj, "bytecode", bytecode);
}
/* add bytecode to lib, and copy the bytecode to the buff in the lib */
int LibObj_staticLink(LibObj* self,
char* module_name,
uint8_t* bytecode,
size_t size) {
if (!obj_isArgExist(self, module_name)) {
obj_newObj(self, module_name, "", New_TinyObj);
}
PikaObj* module_obj = obj_getObj(self, module_name);
/* copy bytecode to buff */
obj_setBytes(module_obj, "buff", bytecode, size);
/* link to buff */
LibObj_dynamicLink(self, module_name, obj_getBytes(module_obj, "buff"));
return 0;
}
int LibObj_staticLinkFile(LibObj* self, char* input_file_name) {
Args buffs = {0};
/* read file */
Arg* input_file_arg = arg_loadFile(NULL, input_file_name);
if (NULL == input_file_arg) {
pika_platform_printf("error: can't open file %s\r\n", input_file_name);
return -1;
}
char* module_name = strsGetLastToken(&buffs, input_file_name, '/');
size_t module_name_len = strlen(module_name);
/* cut off '.py.o' */
if (module_name[module_name_len - 1] == 'o' &&
module_name[module_name_len - 2] == '.' &&
module_name[module_name_len - 3] == 'y' &&
module_name[module_name_len - 4] == 'p' &&
module_name[module_name_len - 5] == '.') {
module_name[module_name_len - 5] = 0;
} else {
// pika_platform_printf("linking raw %s:%s:%ld\r\n", input_file_name,
// module_name, arg_getBytecodeSize(input_file_arg));
/* replace . to | */
module_name = strsReplace(&buffs, module_name, ".", "|");
}
/* push bytecode */
LibObj_staticLink(self, module_name, arg_getBytecode(input_file_arg),
arg_getBytecodeSize(input_file_arg));
/* deinit */
strsDeinit(&buffs);
arg_deinit(input_file_arg);
return 0;
}
static int32_t __foreach_handler_listModules(Arg* argEach, Args* context) {
if (argType_isObject(arg_getType(argEach))) {
PikaObj* module_obj = arg_getPtr(argEach);
pika_platform_printf("%s\r\n", obj_getStr(module_obj, "name"));
}
return 0;
}
void LibObj_listModules(LibObj* self) {
args_foreach(self->list, __foreach_handler_listModules, NULL);
}
static int32_t __foreach_handler_libWriteBytecode(Arg* argEach, Args* context) {
FILE* out_file = args_getPtr(context, "out_file");
if (argType_isObject(arg_getType(argEach))) {
PikaObj* module_obj = arg_getPtr(argEach);
char* bytecode = obj_getPtr(module_obj, "bytecode");
size_t bytecode_size = obj_getBytesSize(module_obj, "buff");
size_t aline_size =
aline_by(bytecode_size, sizeof(uint32_t)) - bytecode_size;
char aline_buff[sizeof(uint32_t)] = {0};
pika_platform_fwrite(bytecode, 1, bytecode_size, out_file);
pika_platform_fwrite(aline_buff, 1, aline_size, out_file);
}
return 0;
}
static int32_t __foreach_handler_libWriteIndex(Arg* argEach, Args* context) {
FILE* out_file = args_getPtr(context, "out_file");
Args buffs = {0};
if (argType_isObject(arg_getType(argEach))) {
PikaObj* module_obj = arg_getPtr(argEach);
uint32_t bytecode_size = obj_getBytesSize(module_obj, "buff");
char buff[LIB_INFO_BLOCK_SIZE - sizeof(uint32_t)] = {0};
bytecode_size = aline_by(bytecode_size, sizeof(uint32_t));
char* module_name = obj_getStr(module_obj, "name");
module_name = strsReplace(&buffs, module_name, "|", ".");
// pika_platform_printf(" %s:%d\r\n", module_name, bytecode_size);
pika_platform_memcpy(buff, module_name, strGetSize(module_name));
pika_platform_fwrite(buff, 1, LIB_INFO_BLOCK_SIZE - sizeof(bytecode_size),
out_file);
pika_platform_fwrite(&bytecode_size, 1, sizeof(bytecode_size), out_file);
}
strsDeinit(&buffs);
return 0;
}
static int32_t __foreach_handler_getModuleNum(Arg* argEach, Args* context) {
if (argType_isObject(arg_getType(argEach))) {
args_setInt(context, "module_num",
args_getInt(context, "module_num") + 1);
}
return 0;
}
int LibObj_saveLibraryFile(LibObj* self, char* output_file_name) {
FILE* out_file = pika_platform_fopen(output_file_name, "wb+");
Args context = {0};
args_setPtr(&context, "out_file", out_file);
args_setInt(&context, "module_num", 0);
/* write meta information */
char buff[LIB_INFO_BLOCK_SIZE] = {0};
args_foreach(self->list, __foreach_handler_getModuleNum, &context);
/* meta info */
char magic_code[] = {0x7f, 'p', 'y', 'a'};
uint32_t version_num = LIB_VERSION_NUMBER;
uint32_t module_num = args_getInt(&context, "module_num");
/* write meta info */
const uint32_t magic_code_offset = sizeof(uint32_t) * 0;
const uint32_t version_offset = sizeof(uint32_t) * 1;
const uint32_t module_num_offset = sizeof(uint32_t) * 2;
pika_platform_memcpy(buff + magic_code_offset, &magic_code, sizeof(uint32_t));
pika_platform_memcpy(buff + version_offset, &version_num, sizeof(uint32_t));
/* write module_num to the file */
pika_platform_memcpy(buff + module_num_offset, &module_num, sizeof(uint32_t));
/* aline to 32 bytes */
pika_platform_fwrite(buff, 1, LIB_INFO_BLOCK_SIZE, out_file);
/* write module index to file */
args_foreach(self->list, __foreach_handler_libWriteIndex, &context);
/* write module bytecode to file */
args_foreach(self->list, __foreach_handler_libWriteBytecode, &context);
args_deinit_stack(&context);
/* main process */
/* deinit */
pika_platform_fclose(out_file);
return 0;
}
static int _getModuleNum(uint8_t* library_bytes) {
if (0 != ((intptr_t)library_bytes & 0x03)) {
return PIKA_RES_ERR_UNALIGNED_PTR;
}
char* magic_code = (char*)library_bytes;
uint32_t* library_info = (uint32_t*)library_bytes;
uint32_t version_num = library_info[1];
uint32_t module_num = library_info[2];
/* check magic_code */
if (!((magic_code[0] == 0x7f) && (magic_code[1] == 'p') &&
(magic_code[2] == 'y') && (magic_code[3] == 'a'))) {
pika_platform_printf("Error: invalid magic code.\r\n");
return PIKA_RES_ERR_ILLEGAL_MAGIC_CODE;
}
/* check version num */
if (version_num != LIB_VERSION_NUMBER) {
pika_platform_printf(
"Error: invalid version number. Expected %d, got %d\r\n",
LIB_VERSION_NUMBER, version_num);
return PIKA_RES_ERR_INVALID_VERSION_NUMBER;
}
return module_num;
}
static PIKA_RES _loadModuleDataWithIndex(uint8_t* library_bytes,
int module_num,
int module_index,
char** name_p,
uint8_t** addr_p,
size_t* size) {
uint8_t* bytecode_addr =
library_bytes + LIB_INFO_BLOCK_SIZE * (module_num + 1);
for (uint32_t i = 0; i < module_index + 1; i++) {
char* module_name =
(char*)(library_bytes + LIB_INFO_BLOCK_SIZE * (i + 1));
// pika_platform_printf("loading module: %s\r\n", module_name);
*name_p = module_name;
*addr_p = bytecode_addr;
size_t module_size =
*(uint32_t*)(module_name + LIB_INFO_BLOCK_SIZE - sizeof(uint32_t));
*size = module_size;
bytecode_addr += module_size;
}
return PIKA_RES_OK;
}
PIKA_RES _loadModuleDataWithName(uint8_t* library_bytes,
char* module_name,
uint8_t** addr_p,
size_t* size_p) {
int module_num = _getModuleNum(library_bytes);
if (module_num < 0) {
return (PIKA_RES)module_num;
}
for (int i = 0; i < module_num; i++) {
char* name = NULL;
uint8_t* addr = NULL;
size_t size = 0;
_loadModuleDataWithIndex(library_bytes, module_num, i, &name, &addr,
&size);
if (strEqu(module_name, name)) {
*addr_p = addr;
*size_p = size;
return PIKA_RES_OK;
}
}
return PIKA_RES_ERR_ARG_NO_FOUND;
}
int LibObj_loadLibrary(LibObj* self, uint8_t* library_bytes) {
int module_num = _getModuleNum(library_bytes);
if (module_num < 0) {
/* load error */
return module_num;
}
for (uint32_t i = 0; i < module_num; i++) {
char* module_name = NULL;
uint8_t* bytecode_addr = NULL;
size_t bytecode_size = 0;
_loadModuleDataWithIndex(library_bytes, module_num, i, &module_name,
&bytecode_addr, &bytecode_size);
LibObj_dynamicLink(self, module_name, bytecode_addr);
}
return PIKA_RES_OK;
}
int32_t __foreach_handler_printModule(Arg* argEach, Args* context) {
if (argType_isObject(arg_getType(argEach))) {
PikaObj* module_obj = arg_getPtr(argEach);
char* module_name = obj_getStr(module_obj, "name");
if (NULL != module_name) {
pika_platform_printf(module_name);
pika_platform_printf("\r\n");
}
}
return 0;
}
void LibObj_printModules(LibObj* self) {
args_foreach(self->list, __foreach_handler_printModule, NULL);
}
int LibObj_loadLibraryFile(LibObj* self, char* lib_file_name) {
Arg* file_arg = arg_loadFile(NULL, lib_file_name);
if (NULL == file_arg) {
pika_platform_printf("Error: Could not load library file '%s'\n",
lib_file_name);
return PIKA_RES_ERR_IO_ERROR;
}
/* save file_arg as @lib_buf to libObj */
obj_setArg_noCopy(self, "@lib_buf", file_arg);
if (0 != LibObj_loadLibrary(self, arg_getBytes(file_arg))) {
pika_platform_printf("Error: Could not load library from '%s'\n",
lib_file_name);
return PIKA_RES_ERR_OPERATION_FAILED;
}
return PIKA_RES_OK;
}
size_t pika_fputs(char* str, FILE* fp) {
size_t size = strGetSize(str);
return pika_platform_fwrite(str, 1, size, fp);
}
int Lib_loadLibraryFileToArray(char* origin_file_name, char* out_folder) {
Args buffs = {0};
Arg* file_arg = arg_loadFile(NULL, origin_file_name);
int res = 0;
if (NULL == file_arg) {
pika_platform_printf("Error: Could not load file '%s'\n",
origin_file_name);
return 1;
}
char* output_file_name = NULL;
output_file_name = strsGetLastToken(&buffs, origin_file_name, '/');
output_file_name = strsAppend(&buffs, "__asset_", output_file_name);
output_file_name = strsReplace(&buffs, output_file_name, ".", "_");
output_file_name = strsAppend(&buffs, output_file_name, ".c");
char* output_file_path = strsAppend(&buffs, out_folder, "/");
output_file_path = strsAppend(&buffs, output_file_path, output_file_name);
FILE* fp = pika_platform_fopen(output_file_path, "wb+");
char* array_name = strsGetLastToken(&buffs, origin_file_name, '/');
array_name = strsReplace(&buffs, array_name, ".", "_");
pika_platform_printf(" loading %s[]...\n", array_name);
pika_fputs("#include \"PikaPlatform.h\"\n", fp);
pika_fputs("/* warning: auto generated file, please do not modify */\n",
fp);
pika_fputs("PIKA_BYTECODE_ALIGN const unsigned char ", fp);
pika_fputs(array_name, fp);
pika_fputs("[] = {", fp);
char byte_buff[32] = {0};
uint8_t* array = arg_getBytes(file_arg);
for (size_t i = 0; i < arg_getBytesSize(file_arg); i++) {
if (i % 12 == 0) {
pika_fputs("\n ", fp);
}
pika_platform_sprintf(byte_buff, "0x%02x, ", array[i]);
pika_fputs(byte_buff, fp);
}
pika_fputs("\n};\n", fp);
res = 0;
goto exit;
exit:
pika_platform_fclose(fp);
strsDeinit(&buffs);
arg_deinit(file_arg);
return res;
}
static PIKA_RES __Maker_compileModuleWithInfo(PikaMaker* self,
char* module_name) {
Args buffs = {0};
char* input_file_name = strsAppend(&buffs, module_name, ".py");
char* input_file_path =
strsAppend(&buffs, obj_getStr(self, "pwd"), input_file_name);
pika_platform_printf(" compiling %s...\r\n", input_file_name);
char* output_file_name = strsAppend(&buffs, module_name, ".py.o");
char* output_file_path = NULL;
output_file_path =
strsAppend(&buffs, obj_getStr(self, "pwd"), "pikascript-api/");
output_file_path = strsAppend(&buffs, output_file_path, output_file_name);
PIKA_RES res =
pikaCompileFileWithOutputName(output_file_path, input_file_path);
strsDeinit(&buffs);
return res;
}
PikaMaker* New_PikaMaker(void) {
PikaMaker* self = New_TinyObj(NULL);
obj_setStr(self, "pwd", "");
obj_setInt(self, "err", 0);
LibObj* lib = New_LibObj(NULL);
obj_setPtr(self, "lib", lib);
return self;
}
void pikaMaker_deinit(PikaMaker* self) {
LibObj* lib = obj_getPtr(self, "lib");
LibObj_deinit(lib);
obj_deinit(self);
}
void pikaMaker_setPWD(PikaMaker* self, char* pwd) {
obj_setStr(self, "pwd", pwd);
}
void pikaMaker_setState(PikaMaker* self, char* module_name, char* state) {
obj_newMetaObj(self, module_name, New_TinyObj);
PikaObj* module_obj = obj_getObj(self, module_name);
obj_setStr(module_obj, "name", module_name);
obj_setStr(module_obj, "state", state);
}
PIKA_RES pikaMaker_compileModule(PikaMaker* self, char* module_name) {
PIKA_RES res = __Maker_compileModuleWithInfo(self, module_name);
/* update compile info */
if (PIKA_RES_OK == res) {
pikaMaker_setState(self, module_name, "compiled");
} else {
pikaMaker_setState(self, module_name, "failed");
}
return res;
}
int pikaMaker_getDependencies(PikaMaker* self, char* module_name) {
int res = 0;
ByteCodeFrame bf = {0};
Args buffs = {0};
byteCodeFrame_init(&bf);
ConstPool* const_pool = NULL;
InstructArray* ins_array = NULL;
char* module_path =
strsAppend(&buffs, obj_getStr(self, "pwd"), "pikascript-api/");
module_path = strsAppend(&buffs, module_path, module_name);
char* file_path = strsAppend(&buffs, module_path, ".py.o");
Arg* file_arg = arg_loadFile(NULL, file_path);
uint8_t offset_befor = 0;
if (NULL == file_arg) {
res = 1;
goto exit;
}
byteCodeFrame_loadByteCode(&bf, arg_getBytes(file_arg));
const_pool = &bf.const_pool;
ins_array = &bf.instruct_array;
offset_befor = ins_array->content_offset_now;
ins_array->content_offset_now = 0;
while (1) {
InstructUnit* ins_unit = instructArray_getNow(ins_array);
if (NULL == ins_unit) {
goto exit;
}
if (instructUnit_getInstruct(ins_unit) == IMP) {
char* imp_module_name =
constPool_getByOffset(const_pool, ins_unit->const_pool_index);
char* imp_module_path =
strsAppend(&buffs, obj_getStr(self, "pwd"), imp_module_name);
/* check if compiled the module */
if (obj_isArgExist(self, imp_module_name)) {
/* module info is exist, do nothing */
} else {
/* module info is not exist */
/* set module to be compile */
FILE* imp_file_py = pika_platform_fopen(
strsAppend(&buffs, imp_module_path, ".py"), "rb");
FILE* imp_file_pyi = pika_platform_fopen(
strsAppend(&buffs, imp_module_path, ".pyi"), "rb");
FILE* imp_file_pyo = pika_platform_fopen(
strsAppend(&buffs, imp_module_path, ".py.o"), "rb");
if (NULL != imp_file_pyo) {
pika_platform_printf(" loading %s.py.o...\r\n",
imp_module_path);
/* found *.py.o, push to compiled list */
pikaMaker_setState(self, imp_module_name, "compiled");
char* imp_api_path = strsAppend(
&buffs, obj_getStr(self, "pwd"), "pikascript-api/");
imp_api_path =
strsAppend(&buffs, imp_api_path, imp_module_name);
FILE* imp_file_pyo_api = pika_platform_fopen(
strsAppend(&buffs, imp_api_path, ".py.o"), "wb+");
/* copy imp_file_pyo to imp_api_path */
uint8_t* buff = (uint8_t*)pika_platform_malloc(128);
size_t read_size = 0;
while (1) {
read_size =
pika_platform_fread(buff, 1, 128, imp_file_pyo);
if (read_size > 0) {
pika_platform_fwrite(buff, 1, read_size,
imp_file_pyo_api);
} else {
break;
}
}
pika_platform_free(buff);
pika_platform_fclose(imp_file_pyo_api);
} else if (NULL != imp_file_py) {
/* found *.py, push to nocompiled list */
pikaMaker_setState(self, imp_module_name, "nocompiled");
} else if (NULL != imp_file_pyi) {
/* found *.py, push to nocompiled list */
pikaMaker_setState(self, imp_module_name, "cmodule");
} else {
pika_platform_printf(
" [warning]: file: '%s.pyi', '%s.py' or '%s.py.o' "
"no found\n",
imp_module_name, imp_module_name, imp_module_name);
}
if (NULL != imp_file_pyo) {
pika_platform_fclose(imp_file_pyo);
}
if (NULL != imp_file_pyi) {
pika_platform_fclose(imp_file_pyi);
}
if (NULL != imp_file_py) {
pika_platform_fclose(imp_file_py);
}
}
}
instructArray_getNext(ins_array);
}
exit:
ins_array->content_offset_now = offset_befor;
if (NULL != file_arg) {
arg_deinit(file_arg);
}
strsDeinit(&buffs);
byteCodeFrame_deinit(&bf);
return res;
}
int32_t __foreach_handler_printStates(Arg* argEach, Args* context) {
if (argType_isObject(arg_getType(argEach))) {
PikaObj* module_obj = arg_getPtr(argEach);
pika_platform_printf("%s: %s\r\n", obj_getStr(module_obj, "name"),
obj_getStr(module_obj, "state"));
}
return 0;
}
void pikaMaker_printStates(PikaMaker* self) {
args_foreach(self->list, __foreach_handler_printStates, NULL);
}
int32_t __foreach_handler_getFirstNocompiled(Arg* argEach, Args* context) {
if (argType_isObject(arg_getType(argEach))) {
PikaObj* module_obj = arg_getPtr(argEach);
char* state = obj_getStr(module_obj, "state");
if (args_isArgExist(context, "res")) {
/* already get method */
return 0;
}
if (strEqu("nocompiled", state)) {
/* push module */
args_setStr(context, "res", obj_getStr(module_obj, "name"));
return 0;
}
}
return 0;
}
char* pikaMaker_getFirstNocompiled(PikaMaker* self) {
Args context = {0};
args_foreach(self->list, __foreach_handler_getFirstNocompiled, &context);
char* res = args_getStr(&context, "res");
if (NULL == res) {
/* remove res in maker */
obj_removeArg(self, "res");
} else {
obj_setStr(self, "res", res);
}
args_deinit_stack(&context);
return obj_getStr(self, "res");
}
PIKA_RES pikaMaker_compileModuleWithDepends(PikaMaker* self,
char* module_name) {
PIKA_RES res = PIKA_RES_OK;
res = pikaMaker_compileModule(self, module_name);
if (PIKA_RES_OK != res) {
obj_setInt(self, "err", res);
return res;
}
pikaMaker_getDependencies(self, module_name);
while (1) {
char* uncompiled = pikaMaker_getFirstNocompiled(self);
/* compiled all modules */
if (NULL == uncompiled) {
break;
}
res = pikaMaker_compileModule(self, uncompiled);
if (PIKA_RES_OK != res) {
obj_setInt(self, "err", res);
return res;
}
pikaMaker_getDependencies(self, uncompiled);
}
return PIKA_RES_OK;
}
int32_t __foreach_handler_linkCompiledModules(Arg* argEach, Args* context) {
Args buffs = {0};
if (argType_isObject(arg_getType(argEach))) {
LibObj* lib = args_getPtr(context, "@lib");
PikaMaker* maker = args_getPtr(context, "__maker");
PikaObj* module_obj = arg_getPtr(argEach);
char* module_name = obj_getStr(module_obj, "name");
char* state = obj_getStr(module_obj, "state");
if (strEqu(state, "compiled")) {
char* pwd = obj_getStr(maker, "pwd");
char* folder_path = strsAppend(&buffs, pwd, "pikascript-api/");
char* module_file_name = strsAppend(&buffs, module_name, ".py.o");
char* module_file_path =
strsAppend(&buffs, folder_path, module_file_name);
LibObj_staticLinkFile(lib, module_file_path);
}
}
strsDeinit(&buffs);
return 0;
}
PIKA_RES pikaMaker_linkCompiledModulesFullPath(PikaMaker* self,
char* lib_path) {
PIKA_RES compile_err = (PIKA_RES)obj_getInt(self, "err");
if (PIKA_RES_OK != compile_err) {
pika_platform_printf(" Error: compile failed, link aborted.\r\n");
return compile_err;
}
Args context = {0};
Args buffs = {0};
pika_platform_printf(" linking %s...\n", lib_path);
LibObj* lib = obj_getPtr(self, "lib");
args_setPtr(&context, "@lib", lib);
args_setPtr(&context, "__maker", self);
args_foreach(self->list, __foreach_handler_linkCompiledModules, &context);
args_deinit_stack(&context);
char* pwd = obj_getStr(self, "pwd");
char* lib_path_folder = strsCopy(&buffs, lib_path);
strPopLastToken(lib_path_folder, '/');
char* folder_path = strsAppend(&buffs, pwd, lib_path_folder);
folder_path = strsAppend(&buffs, folder_path, "/");
char* lib_file_path = strsAppend(&buffs, pwd, lib_path);
LibObj_saveLibraryFile(lib, lib_file_path);
Lib_loadLibraryFileToArray(lib_file_path, folder_path);
strsDeinit(&buffs);
return PIKA_RES_OK;
}
PIKA_RES pikaMaker_linkCompiledModules(PikaMaker* self, char* lib_name) {
Args buffs = {0};
char* lib_file_path = strsAppend(&buffs, "pikascript-api/", lib_name);
PIKA_RES res = pikaMaker_linkCompiledModulesFullPath(self, lib_file_path);
strsDeinit(&buffs);
return res;
}
PIKA_RES pikaMaker_linkRaw(PikaMaker* self, char* file_path) {
LibObj* lib = obj_getPtr(self, "lib");
LibObj_staticLinkFile(lib, file_path);
return PIKA_RES_OK;
}

View File

@ -0,0 +1,44 @@
#ifndef __PIKA_COMPILER__H
#define __PIKA_COMPILER__H
#include "PikaObj.h"
#include "stdint.h"
PIKA_RES pikaCompileFile(char* input_file_name);
PIKA_RES pikaCompileFileWithOutputName(char* output_file_name,
char* input_file_name);
PIKA_RES pikaCompile(char* output_file_name, char* py_lines);
LibObj* New_LibObj(Args* args);
void LibObj_deinit(LibObj* self);
void LibObj_dynamicLink(LibObj* self, char* module_name, uint8_t* bytecode);
int LibObj_staticLink(LibObj* self,
char* module_name,
uint8_t* bytecode,
size_t size);
int LibObj_staticLinkFile(LibObj* self, char* input_file_name);
void LibObj_listModules(LibObj* self);
int LibObj_saveLibraryFile(LibObj* self, char* output_file_name);
int LibObj_loadLibraryFile(LibObj* self, char* input_file_name);
int Lib_loadLibraryFileToArray(char* origin_file_name, char* pikascript_root);
PikaMaker* New_PikaMaker(void);
void pikaMaker_setPWD(PikaMaker* self, char* pwd);
PIKA_RES pikaMaker_compileModule(PikaMaker* self, char* module_name);
int pikaMaker_getDependencies(PikaMaker* self, char* module_name);
void pikaMaker_printStates(PikaMaker* self);
char* pikaMaker_getFirstNocompiled(PikaMaker* self);
PIKA_RES pikaMaker_compileModuleWithDepends(PikaMaker* self, char* module_name);
PIKA_RES pikaMaker_linkCompiledModulesFullPath(PikaMaker* self, char* lib_path);
PIKA_RES pikaMaker_linkCompiledModules(PikaMaker* self, char* lib_name);
int LibObj_loadLibrary(LibObj* self, uint8_t* library_bytes);
void LibObj_printModules(LibObj* self);
void pikaMaker_deinit(PikaMaker* self);
PIKA_RES pikaMaker_linkRaw(PikaMaker* self, char* file_path);
PIKA_RES _loadModuleDataWithName(uint8_t* library_bytes,
char* module_name,
uint8_t** addr_p,
size_t* size_p);
#define LIB_VERSION_NUMBER 2
#define LIB_INFO_BLOCK_SIZE 32
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,520 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef _Process__H
#define _Process__H
#include "dataArgs.h"
#include "dataLink.h"
#include "dataMemory.h"
#include "dataStrs.h"
typedef struct InstructUnit InstructUnit;
struct InstructUnit {
uint8_t deepth;
uint8_t isNewLine_instruct;
uint16_t const_pool_index;
};
typedef struct ConstPool ConstPool;
struct ConstPool {
Arg* arg_buff;
uint32_t content_offset_now;
uint32_t size;
void* content_start;
void (*output_redirect_fun)(ConstPool* self, char* content);
FILE* output_f;
};
typedef struct InstructArray InstructArray;
struct InstructArray {
Arg* arg_buff;
uint32_t content_offset_now;
uint32_t size;
void* content_start;
void (*output_redirect_fun)(InstructArray* self, InstructUnit* ins_unit);
FILE* output_f;
};
typedef struct ByteCodeFrame ByteCodeFrame;
struct ByteCodeFrame {
ConstPool const_pool;
InstructArray instruct_array;
};
typedef struct NativeProperty NativeProperty;
struct NativeProperty {
const NativeProperty* super;
const Arg* methodGroup;
uint32_t methodGroupCount;
};
typedef struct PikaObj PikaObj;
struct PikaObj {
Args* list;
uint8_t refcnt;
void* constructor;
uint8_t flag;
};
typedef struct RangeData RangeData;
struct RangeData {
int64_t start;
int64_t end;
int64_t step;
int64_t i;
};
#define OBJ_FLAG_PROXY_GETATTRIBUTE 0x01
#define OBJ_FLAG_PROXY_GETATTR 0x02
#define OBJ_FLAG_PROXY_SETATTR 0x04
#define OBJ_FLAG_ALREADY_INIT 0x08
#define OBJ_FLAG_RUN_AS 0x16
#define OBJ_FLAG_GLOBALS 0x32
#define KEY_UP 0x41
#define KEY_DOWN 0x42
#define KEY_RIGHT 0x43
#define KEY_LEFT 0x44
static inline uint8_t obj_getFlag(PikaObj* self, uint8_t flag) {
return (self->flag & flag) == flag;
}
static inline void obj_setFlag(PikaObj* self, uint8_t flag) {
self->flag |= flag;
}
static inline void obj_clearFlag(PikaObj* self, uint8_t flag) {
self->flag &= ~flag;
}
typedef PikaObj* (*NewFun)(Args* args);
typedef PikaObj* (*InitFun)(PikaObj* self, Args* args);
typedef PikaObj VMParameters;
typedef void (*Method)(PikaObj* self, Args* args);
typedef struct MethodInfo MethodInfo;
struct MethodInfo {
char* name;
char* dec;
char* ptr;
char* typelist;
PikaObj* def_context;
ArgType type;
ByteCodeFrame* bytecode_frame;
};
typedef struct MethodProp {
void* ptr;
char* type_list;
char* name;
ByteCodeFrame* bytecode_frame;
PikaObj* def_context;
char* declareation;
} MethodProp;
typedef struct MethodPropNative {
void* ptr;
char* type_list;
#if !PIKA_NANO_ENABLE
char* name;
#endif
} MethodPropNative;
typedef PikaObj LibObj;
typedef PikaObj PikaMaker;
/* operation */
int32_t obj_deinit(PikaObj* self);
int32_t obj_init(PikaObj* self, Args* args);
int32_t obj_update(PikaObj* self);
int32_t obj_enable(PikaObj* self);
int32_t obj_disable(PikaObj* self);
// arg type operations
PIKA_RES obj_setInt(PikaObj* self, char* argPath, int64_t val);
PIKA_RES obj_setRef(PikaObj* self, char* argPath, PikaObj* pointer);
PIKA_RES obj_setPtr(PikaObj* self, char* argPath, void* pointer);
PIKA_RES obj_setFloat(PikaObj* self, char* argPath, pika_float value);
PIKA_RES obj_setStr(PikaObj* self, char* argPath, char* str);
PIKA_RES obj_setNone(PikaObj* self, char* argPath);
PIKA_RES obj_setArg(PikaObj* self, char* argPath, Arg* arg);
PIKA_RES obj_setArg_noCopy(PikaObj* self, char* argPath, Arg* arg);
PIKA_RES obj_setBytes(PikaObj* self, char* argPath, uint8_t* src, size_t size);
void* obj_getPtr(PikaObj* self, char* argPath);
pika_float obj_getFloat(PikaObj* self, char* argPath);
char* obj_getStr(PikaObj* self, char* argPath);
int64_t obj_getInt(PikaObj* self, char* argPath);
Arg* obj_getArg(PikaObj* self, char* argPath);
uint8_t* obj_getBytes(PikaObj* self, char* argPath);
size_t obj_getBytesSize(PikaObj* self, char* argPath);
size_t obj_loadBytes(PikaObj* self, char* argPath, uint8_t* out_buff);
char* obj_print(PikaObj* self, char* name);
// args operations
int32_t obj_load(PikaObj* self, Args* args, char* name);
// subObject
int32_t obj_addOther(PikaObj* self, char* subObjectName, void* new_projcetFun);
PikaObj* obj_getObj(PikaObj* self, char* objPath);
PikaObj* obj_getHostObj(PikaObj* self, char* objPath);
PikaObj* obj_getHostObjWithIsTemp(PikaObj* self,
char* objPath,
PIKA_BOOL* pIsClass);
// subProcess
int32_t obj_freeObj(PikaObj* self, char* subObjectName);
/* method */
int32_t class_defineMethod(PikaObj* self,
char* name,
char* typelist,
Method methodPtr);
int32_t class_defineObjectMethod(PikaObj* self,
char* declareation,
Method methodPtr,
PikaObj* def_context,
ByteCodeFrame* bytecode_frame);
int32_t class_defineStaticMethod(PikaObj* self,
char* declareation,
Method methodPtr,
PikaObj* def_context,
ByteCodeFrame* bytecode_frame);
int32_t class_defineConstructor(PikaObj* self,
char* name,
char* typelist,
Method methodPtr);
int32_t class_defineRunTimeConstructor(PikaObj* self,
char* declareation,
Method methodPtr,
PikaObj* def_context,
ByteCodeFrame* bytecode_frame);
int32_t obj_removeArg(PikaObj* self, char* argPath);
int32_t obj_isArgExist(PikaObj* self, char* argPath);
PikaObj* obj_getClassObjByNewFun(PikaObj* self, char* name, NewFun newClassFun);
PikaObj* newRootObj(char* name, NewFun newObjFun);
PikaObj* obj_getClassObj(PikaObj* obj);
Arg* obj_getMethodArg(PikaObj* obj, char* methodPath);
Arg* obj_getMethodArg_noalloc(PikaObj* obj, char* methodPath, Arg* arg_reg);
void obj_setErrorCode(PikaObj* self, int32_t errCode);
int32_t obj_getErrorCode(PikaObj* self);
void obj_setSysOut(PikaObj* self, char* str);
char* args_getSysOut(Args* args);
void args_setErrorCode(Args* args, int32_t errCode);
int32_t args_getErrorCode(Args* args);
void args_setSysOut(Args* args, char* str);
char* obj_getSysOut(PikaObj* self);
void obj_sysPrintf(PikaObj* self, char* fmt, ...);
uint8_t obj_getAnyArg(PikaObj* self,
char* targetArgName,
char* sourceArgPath,
Args* targetArgs);
void method_returnStr(Args* args, char* val);
void method_returnInt(Args* args, int64_t val);
void method_returnFloat(Args* args, pika_float val);
void method_returnPtr(Args* args, void* val);
void method_returnObj(Args* args, void* val);
int64_t method_getInt(Args* args, char* argName);
pika_float method_getFloat(Args* args, char* argName);
char* method_getStr(Args* args, char* argName);
void method_returnArg(Args* args, Arg* arg);
char* methodArg_getDec(Arg* method_arg);
char* methodArg_getTypeList(Arg* method_arg, char* buffs, size_t size);
char* methodArg_getName(Arg* method_arg, char* buffs, size_t size);
ByteCodeFrame* methodArg_getBytecodeFrame(Arg* method_arg);
Method methodArg_getPtr(Arg* method_arg);
VMParameters* obj_run(PikaObj* self, char* cmd);
PikaObj* New_PikaObj(void);
/* tools */
int64_t fast_atoi(char* src);
char* fast_itoa(char* buf, uint32_t val);
/* shell */
void pikaScriptShell(PikaObj* self);
enum shellCTRL { SHELL_CTRL_CONTINUE, SHELL_CTRL_EXIT };
typedef struct ShellConfig ShellConfig;
typedef enum shellCTRL (*sh_handler)(PikaObj*, char*, ShellConfig*);
typedef char (*sh_getchar)(void);
struct ShellConfig {
char* prefix;
sh_handler handler;
void* context;
char lineBuff[PIKA_LINE_BUFF_SIZE];
size_t line_position;
size_t line_curpos;
char* blockBuffName;
PIKA_BOOL inBlock;
char lastChar;
sh_getchar fn_getchar;
uint8_t stat;
};
void _do_pikaScriptShell(PikaObj* self, ShellConfig* cfg);
void _temp__do_pikaScriptShell(PikaObj* self, ShellConfig* cfg);
/*
need implament :
pika_platform_fopen()
pika_platform_fwrite()
pika_platform_fclose()
*/
Method obj_getNativeMethod(PikaObj* self, char* method_name);
PIKA_RES obj_runNativeMethod(PikaObj* self, char* method_name, Args* args);
Arg* obj_newObjInPackage(NewFun newObjFun);
PikaObj* newNormalObj(NewFun newObjFun);
Arg* arg_setRef(Arg* self, char* name, PikaObj* obj);
Arg* arg_setObj(Arg* self, char* name, PikaObj* obj);
static inline Arg* arg_newObj(PikaObj* obj) {
return arg_setObj(NULL, "", (obj));
}
static inline Arg* arg_newRef(PikaObj* obj) {
return arg_setRef(NULL, "", (obj));
}
PikaObj* obj_importModuleWithByteCodeFrame(PikaObj* self,
char* name,
ByteCodeFrame* bytecode_frame);
PikaObj* obj_importModuleWithByteCode(PikaObj* self,
char* name,
uint8_t* byteCode);
int32_t obj_newObj(PikaObj* self,
char* objName,
char* className,
NewFun newFunPtr);
Arg* arg_newMetaObj(NewFun objPtr);
PikaObj* obj_linkLibObj(PikaObj* self, LibObj* library);
PikaObj* obj_linkLibrary(PikaObj* self, uint8_t* library_bytes);
int obj_importModule(PikaObj* self, char* module_name);
int32_t obj_newMetaObj(PikaObj* self, char* objName, NewFun newFunPtr);
int32_t obj_newDirectObj(PikaObj* self, char* objName, NewFun newFunPtr);
int obj_runModule(PikaObj* self, char* module_name);
char* obj_toStr(PikaObj* self);
Arg* arg_newDirectObj(NewFun new_obj_fun);
enum shellCTRL obj_runChar(PikaObj* self, char inputChar);
#define PIKA_PYTHON_BEGIN
#define PIKA_PYTHON(x)
#define PIKA_PYTHON_END
typedef PikaObj PikaEventListener;
void pks_eventListener_registEvent(PikaEventListener* self,
uint32_t eventId,
PikaObj* eventHandleObj);
void pks_eventListener_removeEvent(PikaEventListener* self, uint32_t eventId);
void _do_pks_eventListener_send(PikaEventListener* self,
uint32_t eventId,
Arg* eventData,
PIKA_BOOL pickupWhenNoVM);
void pks_eventListener_sendSignal(PikaEventListener* self,
uint32_t eventId,
int eventSignal);
void pks_eventListener_send(PikaEventListener* self,
uint32_t eventId,
Arg* eventData);
PikaObj* pks_eventListener_getEventHandleObj(PikaEventListener* self,
uint32_t eventId);
void pks_eventListener_init(PikaEventListener** p_self);
void pks_eventListener_deinit(PikaEventListener** p_self);
PikaObj* methodArg_getDefContext(Arg* method_arg);
PikaObj* obj_linkLibraryFile(PikaObj* self, char* input_file_name);
NewFun obj_getClass(PikaObj* obj);
void pks_printVersion(void);
void pks_getVersion(char* buff);
void* obj_getStruct(PikaObj* self, char* name);
static inline void obj_refcntDec(PikaObj* self) {
self->refcnt--;
}
static inline void obj_refcntInc(PikaObj* self) {
self->refcnt++;
}
static inline uint8_t obj_refcntNow(PikaObj* self) {
return self->refcnt;
}
#define obj_setStruct(PikaObj_p_self, char_p_name, struct_) \
args_setStruct(((PikaObj_p_self)->list), char_p_name, struct_)
#define ABSTRACT_METHOD_NEED_OVERRIDE_ERROR(_) \
obj_setErrorCode(self, 1); \
pika_platform_printf("Error: abstract method `%s()` need override.\r\n", \
__FUNCTION__)
char* obj_cacheStr(PikaObj* self, char* str);
PikaObj* _arg_to_obj(Arg* self, PIKA_BOOL* pIsTemp);
char* __printBytes(PikaObj* self, Arg* arg);
#define PIKASCRIPT_VERSION_TO_NUM(majer, minor, micro) \
majer * 100 * 100 + minor * 100 + micro
#define PIKASCRIPT_VERSION_NUM \
PIKASCRIPT_VERSION_TO_NUM(PIKA_VERSION_MAJOR, PIKA_VERSION_MINOR, \
PIKA_VERSION_MICRO)
#define PIKASCRIPT_VERSION_REQUIRE_MINIMUN(majer, minor, micro) \
(PIKASCRIPT_VERSION_NUM >= PIKASCRIPT_VERSION_TO_NUM(majer, minor, micro))
/* [example]
const MethodProp floatMethod = {
.ptr = (void*)PikaStdLib_SysObj_floatMethod,
.bytecode_frame = NULL,
.def_context = NULL,
.declareation = "float(arg)",
.type_list = "arg",
.name = "float",
};
*/
#if !PIKA_NANO_ENABLE
#define method_typedef(_method, _name, _typelist) \
const MethodPropNative _method##Prop = { \
.ptr = (void*)_method##Method, \
.type_list = _typelist, \
.name = _name, \
};
#else
#define method_typedef(_method, _name, _typelist) \
const MethodPropNative _method##Prop = { \
.ptr = (void*)_method##Method, \
.type_list = _typelist, \
};
#endif
/* clang-format off */
#if PIKA_ARG_CACHE_ENABLE
#define _method_def(_method, _hash, _type) \
{ \
._ = \
{ \
.buffer = (uint8_t*)&_method##Prop \
}, \
.size = sizeof(MethodPropNative), \
.heap_size = 0, \
.type = _type, \
.flag = 0, \
.name_hash = _hash \
}
#else
#define _method_def(_method, _hash, _type) \
{ \
._ = \
{ \
.buffer = (uint8_t*)&_method##Prop \
}, \
.size = sizeof(MethodPropNative), \
.type = _type, \
.flag = 0, \
.name_hash = _hash \
}
#endif
#if defined(_WIN32) || \
(defined(__ARMCC_VERSION) && (__ARMCC_VERSION < 6000000))
#define __BEFORE_MOETHOD_DEF \
{ \
._ = \
{ \
.buffer = NULL \
}, \
.size = 0, \
.type = ARG_TYPE_NONE, \
.flag = 0, \
.name_hash = 0 \
},
#else
#define __BEFORE_MOETHOD_DEF
#endif
/* clang-format on */
#define method_def(_method, _hash) \
_method_def(_method, _hash, ARG_TYPE_METHOD_NATIVE)
#define constructor_def(_method, _hash) \
_method_def(_method, _hash, ARG_TYPE_METHOD_NATIVE_CONSTRUCTOR)
#define class_def(_class) const ConstArg _class##Collect[] =
#define class_inhert(_class, _super) \
extern const NativeProperty _super##NativeProp; \
const NativeProperty _class##NativeProp = { \
.super = &_super##NativeProp, \
.methodGroup = (Arg*)_class##Collect, \
.methodGroupCount = \
sizeof(_class##Collect) / sizeof(_class##Collect[0]), \
}
#define pika_class(_method) _method##NativeProp
void _obj_updateProxyFlag(PikaObj* self);
#define obj_setClass(_self, _method) \
obj_setPtr((_self), "@p", (void*)&pika_class(_method)); \
_obj_updateProxyFlag((_self))
Arg* _obj_getProp(PikaObj* obj, char* name);
Arg* __eventListener_runEvent_dataInt(PikaEventListener* lisener,
uint32_t eventId,
int eventSignal);
Arg* __eventListener_runEvent(PikaEventListener* lisener,
uint32_t eventId,
Arg* eventData);
Arg* pks_eventListener_sendSignalAwaitResult(PikaEventListener* self,
uint32_t eventId,
int eventSignal);
void obj_printModules(PikaObj* self);
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,125 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef __PIKA_PARSER__H
#define __PIKA_PARSER__H
#include "PikaVM.h"
#include "dataQueueObj.h"
#include "dataStack.h"
typedef enum TokenType {
TOKEN_strEnd = 0,
TOKEN_symbol,
TOKEN_keyword,
TOKEN_operator,
TOKEN_devider,
TOKEN_literal,
} TokenType;
enum StmtType {
STMT_reference,
STMT_tuple,
STMT_string,
STMT_bytes,
STMT_number,
STMT_method,
STMT_chain,
STMT_operator,
STMT_import,
STMT_list,
STMT_slice,
STMT_dict,
STMT_none,
};
typedef struct Asmer Asmer;
struct Asmer {
char* asm_code;
uint8_t block_deepth_now;
uint8_t is_new_line;
char* line_pointer;
};
typedef enum _GenRuleValType {
VAL_NONEVAL,
VAL_DYNAMIC,
VAL_STATIC_,
} GenRuleValType;
typedef struct GenRule {
char* ins;
GenRuleValType type;
char* ast;
char* val;
} GenRule;
typedef struct LexToken LexToken;
struct LexToken {
char* tokenStream;
enum TokenType type;
char* pyload;
};
typedef struct Cursor ParsetState;
struct Cursor {
char* tokenStream;
uint16_t length;
uint16_t iter_index;
int8_t branket_deepth;
struct LexToken token1;
struct LexToken token2;
Arg* last_token;
Args* iter_buffs;
Args* buffs_p;
PIKA_RES result;
};
char* Parser_fileToAsm(Args* outBuffs, char* filename);
char* Parser_linesToAsm(Args* outBuffs, char* multiLine);
PIKA_RES Parser_linesToBytes(ByteCodeFrame* bf, char* py_lines);
char* Parser_linesToArray(char* lines);
char* instructUnit_fromAsmLine(Args* outBuffs, char* pikaAsm);
ByteCodeFrame* byteCodeFrame_appendFromAsm(ByteCodeFrame* bf, char* pikaAsm);
#define Cursor_forEach(cursor) \
_Cursor_beforeIter(&cursor); \
for (int __i = 0; __i < cursor.length; __i++)
#define Cursor_forEachTokenExistPs(cursor, tokenStream) \
/* init parserStage */ \
_Cursor_init(&cursor); \
_Cursor_parse(&cursor, tokenStream); \
Cursor_forEach(cursor)
#define Cursor_forEachToken(cursor, tokenStream) \
struct Cursor cursor; \
Cursor_forEachTokenExistPs(cursor, tokenStream)
uint16_t TokenStream_getSize(char* tokenStream);
#endif

View File

@ -0,0 +1,538 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "PikaPlatform.h"
#include <stdio.h>
#include <stdlib.h>
PIKA_WEAK void pika_platform_disable_irq_handle(void) {
/* disable irq to support thread */
}
PIKA_WEAK void pika_platform_enable_irq_handle(void) {
/* disable irq to support thread */
}
PIKA_WEAK void* pika_platform_malloc(size_t size) {
return malloc(size);
}
PIKA_WEAK void* pika_platform_realloc(void* ptr, size_t size) {
return realloc(ptr, size);
}
PIKA_WEAK void* pika_platform_calloc(size_t num, size_t size) {
return calloc(num, size);
}
PIKA_WEAK void pika_platform_free(void* ptr) {
free(ptr);
}
PIKA_WEAK void* pika_user_malloc(size_t size) {
return pika_platform_malloc(size);
}
PIKA_WEAK void pika_user_free(void* ptr, size_t size) {
pika_platform_free(ptr);
}
PIKA_WEAK void pika_platform_error_handle() {
return;
}
PIKA_WEAK void pika_platform_panic_handle() {
while (1) {
};
}
PIKA_WEAK uint8_t pika_is_locked_pikaMemory(void) {
return 0;
}
PIKA_WEAK int64_t pika_platform_getTick(void) {
return -1;
}
PIKA_WEAK int pika_platform_vsprintf(char* buff, char* fmt, va_list args) {
/* vsnprintf */
return pika_platform_vsnprintf(buff, PIKA_SPRINTF_BUFF_SIZE, fmt, args);
}
PIKA_WEAK int pika_platform_snprintf(char* buff,
size_t size,
const char* fmt,
...) {
va_list args;
va_start(args, fmt);
int ret = pika_platform_vsnprintf(buff, size, fmt, args);
va_end(args);
return ret;
}
PIKA_WEAK int pika_platform_putchar(char ch) {
return putchar(ch);
}
PIKA_WEAK int pika_platform_vprintf(char* fmt, va_list args) {
/* vsprintf to vprintf */
char buff[PIKA_SPRINTF_BUFF_SIZE];
pika_platform_vsprintf(buff, fmt, args);
/* putchar */
for (int i = 0; i < strlen(buff); i++) {
pika_platform_putchar(buff[i]);
}
return 0;
}
#ifndef pika_platform_printf
PIKA_WEAK void pika_platform_printf(char* fmt, ...) {
va_list args;
va_start(args, fmt);
pika_platform_vprintf(fmt, args);
va_end(args);
}
#endif
PIKA_WEAK char* pika_platform_strdup(const char* src) {
char* dst = (char*)pika_platform_malloc(strlen(src) + 1);
if (dst) {
strcpy(dst, src);
}
return dst;
}
PIKA_WEAK size_t pika_platform_tick_from_millisecond(size_t ms) {
return ms;
}
PIKA_WEAK int pika_platform_vsnprintf(char* buff,
size_t size,
const char* fmt,
va_list args) {
return vsnprintf(buff, size, fmt, args);
}
PIKA_WEAK int pika_platform_sprintf(char* buff, char* fmt, ...) {
va_list args;
va_start(args, fmt);
int res = pika_platform_vsnprintf(buff, PIKA_SPRINTF_BUFF_SIZE, fmt, args);
va_end(args);
if (res >= PIKA_SPRINTF_BUFF_SIZE) {
pika_platform_printf(
"OverflowError: sprintf buff size overflow, please use bigger "
"PIKA_SPRINTF_BUFF_SIZE\r\n");
pika_platform_printf("Info: buff size request: %d\r\n", res);
pika_platform_printf("Info: buff size now: %d\r\n",
PIKA_SPRINTF_BUFF_SIZE);
while (1)
;
}
return res;
}
PIKA_WEAK void pika_platform_wait(void) {
while (1) {
};
}
PIKA_WEAK void* pika_platform_memset(void* mem, int ch, size_t size) {
return memset(mem, ch, size);
}
PIKA_WEAK void* pika_platform_memcpy(void* dir, const void* src, size_t size) {
return memcpy(dir, src, size);
}
PIKA_WEAK int pika_platform_memcmp(const void* s1, const void* s2, size_t n) {
return memcmp(s1, s2, n);
}
PIKA_WEAK void* pika_platform_memmove(void* s1, void* s2, size_t n) {
return memmove(s1, s2, n);
}
PIKA_WEAK char pika_platform_getchar(void) {
#if defined(__linux) || defined(_WIN32)
return getchar();
#else
pika_platform_printf(
"Error: pika_platform_getchar need implementation!\r\n");
while (1) {
}
#endif
}
/* fopen */
PIKA_WEAK FILE* pika_platform_fopen(const char* filename, const char* modes) {
#if defined(__linux) || defined(_WIN32)
return fopen(filename, modes);
#else
pika_platform_printf("Error: pika_platform_fopen need implementation!\r\n");
while (1) {
}
#endif
}
/* fclose */
PIKA_WEAK int pika_platform_fclose(FILE* stream) {
#if defined(__linux) || defined(_WIN32)
return fclose(stream);
#else
pika_platform_printf(
"Error: pika_platform_fclose need implementation!\r\n");
while (1) {
}
#endif
}
/* fwrite */
PIKA_WEAK size_t pika_platform_fwrite(const void* ptr,
size_t size,
size_t n,
FILE* stream) {
#if defined(__linux) || defined(_WIN32)
return fwrite(ptr, size, n, stream);
#else
pika_platform_printf(
"Error: pika_platform_fwrite need implementation!\r\n");
while (1) {
}
#endif
}
/* fread */
PIKA_WEAK size_t pika_platform_fread(void* ptr,
size_t size,
size_t n,
FILE* stream) {
#if defined(__linux) || defined(_WIN32)
return fread(ptr, size, n, stream);
#else
pika_platform_printf("Error: pika_platform_fread need implementation!\r\n");
while (1) {
}
#endif
}
/* fseek */
PIKA_WEAK int pika_platform_fseek(FILE* stream, long offset, int whence) {
#if defined(__linux) || defined(_WIN32)
return fseek(stream, offset, whence);
#else
pika_platform_printf("Error: pika_platform_fseek need implementation!\r\n");
while (1) {
}
#endif
}
/* ftell */
PIKA_WEAK long pika_platform_ftell(FILE* stream) {
#if defined(__linux) || defined(_WIN32)
return ftell(stream);
#else
pika_platform_printf("Error: pika_platform_ftell need implementation!\r\n");
while (1) {
}
#endif
}
PIKA_WEAK void pika_hook_instruct(void) {
return;
}
PIKA_WEAK PIKA_BOOL pika_hook_arg_cache_filter(void* self) {
return PIKA_TRUE;
}
PIKA_WEAK void pika_platform_thread_delay(void) {
return;
}
PIKA_WEAK void pika_platform_sleep_ms(uint32_t ms) {
pika_platform_printf(
"Error: pika_platform_sleep_ms need implementation!\r\n");
while (1) {
}
}
PIKA_WEAK void pika_platform_sleep_s(uint32_t s) {
pika_platform_printf(
"Error: pika_platform_sleep_s need implementation!\r\n");
while (1) {
}
}
/* Thread Support */
PIKA_WEAK pika_platform_thread_t* pika_platform_thread_init(
const char* name,
void (*entry)(void*),
void* const param,
unsigned int stack_size,
unsigned int priority,
unsigned int tick) {
#ifdef __linux
int res;
pika_platform_thread_t* thread;
void* (*thread_entry)(void*);
thread_entry = (void* (*)(void*))entry;
thread = pika_platform_malloc(sizeof(pika_platform_thread_t));
res = pthread_create(&thread->thread, NULL, thread_entry, param);
if (res != 0) {
pika_platform_free(thread);
}
thread->mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
thread->cond = (pthread_cond_t)PTHREAD_COND_INITIALIZER;
return thread;
#elif PIKA_FREERTOS_ENABLE
BaseType_t err;
pika_platform_thread_t* thread;
thread = pika_platform_malloc(sizeof(pika_platform_thread_t));
(void)tick;
err = xTaskCreate(entry, name, stack_size, param, priority, thread->thread);
if (pdPASS != err) {
pika_platform_free(thread);
return NULL;
}
return thread;
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
return NULL;
#endif
}
PIKA_WEAK void pika_platform_thread_startup(pika_platform_thread_t* thread) {
(void)thread;
}
PIKA_WEAK void pika_platform_thread_stop(pika_platform_thread_t* thread) {
#ifdef __linux
pthread_mutex_lock(&(thread->mutex));
pthread_cond_wait(&(thread->cond), &(thread->mutex));
pthread_mutex_unlock(&(thread->mutex));
#elif PIKA_FREERTOS_ENABLE
vTaskSuspend(thread->thread);
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
#endif
}
PIKA_WEAK void pika_platform_thread_start(pika_platform_thread_t* thread) {
#ifdef __linux
pthread_mutex_lock(&(thread->mutex));
pthread_cond_signal(&(thread->cond));
pthread_mutex_unlock(&(thread->mutex));
#elif PIKA_FREERTOS_ENABLE
vTaskResume(thread->thread);
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
#endif
}
PIKA_WEAK void pika_platform_thread_destroy(pika_platform_thread_t* thread) {
#ifdef __linux
if (NULL != thread) {
pthread_detach(thread->thread);
pika_platform_free(thread);
thread = NULL;
}
#elif PIKA_FREERTOS_ENABLE
if (NULL != thread)
vTaskDelete(thread->thread);
pika_platform_memory_free(thread);
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
#endif
}
PIKA_WEAK int pika_platform_thread_mutex_init(pika_platform_thread_mutex_t* m) {
#ifdef __linux
return pthread_mutex_init(&(m->mutex), NULL);
#elif PIKA_FREERTOS_ENABLE
m->mutex = xSemaphoreCreateMutex();
return 0;
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
return -1;
#endif
}
PIKA_WEAK int pika_platform_thread_mutex_lock(pika_platform_thread_mutex_t* m) {
#ifdef __linux
return pthread_mutex_lock(&(m->mutex));
#elif PIKA_FREERTOS_ENABLE
return xSemaphoreTake(m->mutex, portMAX_DELAY);
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
return -1;
#endif
}
PIKA_WEAK int pika_platform_thread_mutex_trylock(
pika_platform_thread_mutex_t* m) {
#ifdef __linux
return pthread_mutex_trylock(&(m->mutex));
#elif PIKA_FREERTOS_ENABLE
return xSemaphoreTake(m->mutex, 0);
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
return -1;
#endif
}
PIKA_WEAK int pika_platform_thread_mutex_unlock(
pika_platform_thread_mutex_t* m) {
#ifdef __linux
return pthread_mutex_unlock(&(m->mutex));
#elif PIKA_FREERTOS_ENABLE
return xSemaphoreGive(m->mutex);
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
return -1;
#endif
}
PIKA_WEAK int pika_platform_thread_mutex_destroy(
pika_platform_thread_mutex_t* m) {
#ifdef __linux
return pthread_mutex_destroy(&(m->mutex));
#elif PIKA_FREERTOS_ENABLE
vSemaphoreDelete(m->mutex);
return 0;
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
return -1;
#endif
}
#if PIKA_FREERTOS_ENABLE
static uint32_t platform_uptime_ms(void) {
#if (configTICK_RATE_HZ == 1000)
return (uint32_t)xTaskGetTickCount();
#else
TickType_t tick = 0u;
tick = xTaskGetTickCount() * 1000;
return (uint32_t)((tick + configTICK_RATE_HZ - 1) / configTICK_RATE_HZ);
#endif
}
#endif
PIKA_WEAK void pika_platform_timer_init(pika_platform_timer_t* timer) {
#ifdef __linux
timer->time = (struct timeval){0, 0};
#elif PIKA_FREERTOS_ENABLE
timer->time = 0;
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
#endif
}
PIKA_WEAK void pika_platform_timer_cutdown(pika_platform_timer_t* timer,
unsigned int timeout) {
#ifdef __linux
struct timeval now;
gettimeofday(&now, NULL);
struct timeval interval = {timeout / 1000, (timeout % 1000) * 1000};
timeradd(&now, &interval, &timer->time);
#elif PIKA_FREERTOS_ENABLE
timer->time = platform_uptime_ms();
timer->time += timeout;
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
#endif
}
PIKA_WEAK char pika_platform_timer_is_expired(pika_platform_timer_t* timer) {
#ifdef __linux
struct timeval now, res;
gettimeofday(&now, NULL);
timersub(&timer->time, &now, &res);
return ((res.tv_sec < 0) || (res.tv_sec == 0 && res.tv_usec <= 0));
#elif PIKA_FREERTOS_ENABLE
return platform_uptime_ms() > timer->time ? 1 : 0;
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
return 1;
#endif
}
PIKA_WEAK int pika_platform_timer_remain(pika_platform_timer_t* timer) {
#ifdef __linux
struct timeval now, res;
gettimeofday(&now, NULL);
timersub(&timer->time, &now, &res);
return (res.tv_sec < 0) ? 0 : res.tv_sec * 1000 + res.tv_usec / 1000;
#elif PIKA_FREERTOS_ENABLE
uint32_t now;
now = platform_uptime_ms();
if (timer->time <= now) {
return 0;
}
return timer->time - now;
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
return -1;
#endif
}
PIKA_WEAK unsigned long pika_platform_timer_now(void) {
#ifdef __linux
return (unsigned long)time(NULL);
#elif PIKA_FREERTOS_ENABLE
return (unsigned long)platform_uptime_ms();
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
return 1;
#endif
}
PIKA_WEAK void pika_platform_timer_usleep(unsigned long usec) {
#ifdef __linux
usleep(usec);
#elif PIKA_FREERTOS_ENABLE
TickType_t tick = 1;
if (usec != 0) {
tick = usec / portTICK_PERIOD_MS;
if (tick == 0)
tick = 1;
}
vTaskDelay(tick);
#else
WEAK_FUNCTION_NEED_OVERRIDE_ERROR();
#endif
}

View File

@ -0,0 +1,284 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
/* adapter for old api */
#include "./pika_adapter_old_api.h"
#ifndef __PIKA_PALTFORM__H
#define __PIKA_PALTFORM__H
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef __linux
#include <unistd.h>
#endif
/* clang-format off */
#if PIKA_ASSERT_ENABLE
#define pika_assert(expr) \
if(!(expr)) { \
pika_platform_printf("Assertion \"%s\" failed, in function: %s(). \r\n (at %s:%d)\n", #expr, __FUNCTION__, __FILE__, __LINE__); \
abort(); \
}
#else
#define pika_assert(...)
#endif
/* clang-format on */
/* Compiler */
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 5000000) /* ARM Compiler \
*/
#define PIKA_WEAK __attribute__((weak))
#elif defined(__IAR_SYSTEMS_ICC__) /* for IAR Compiler */
#define PIKA_WEAK __weak
#elif defined(__MINGW32__) /* MINGW32 Compiler */
#define PIKA_WEAK
#elif defined(__GNUC__) /* GNU GCC Compiler */
#define PIKA_WEAK __attribute__((weak))
#endif
/* default PIKA_WEAK */
#ifndef PIKA_WEAK
#define PIKA_WEAK
#endif
/* align for bytecode */
#if defined(_WIN32)
#define PIKA_BYTECODE_ALIGN
#else
#define PIKA_BYTECODE_ALIGN __attribute__((aligned(4)))
#endif
/* OS */
#ifdef __RTTHREAD__
#include <rtthread.h>
#define pika_platform_printf(...) rt_kprintf(__VA_ARGS__)
#endif
typedef enum {
PIKA_RES_OK = 0,
PIKA_RES_ERR_RUNTIME_ERROR = -1,
PIKA_RES_ERR_ARG_NO_FOUND = -2,
PIKA_RES_ERR_UNKNOWN_INSTRUCTION = -3,
PIKA_RES_ERR_OUT_OF_RANGE = -4,
PIKA_RES_ERR_IO_ERROR = -5,
PIKA_RES_ERR_INSUFFICIENT_RESOURCE = -6,
PIKA_RES_ERR_INVALID_PARAM = -7,
PIKA_RES_ERR_INVALID_PTR = -8,
PIKA_RES_ERR_UNALIGNED_PTR = -9,
PIKA_RES_ERR_INVALID_VERSION_NUMBER = -10,
PIKA_RES_ERR_ILLEGAL_MAGIC_CODE = -11,
PIKA_RES_ERR_OPERATION_FAILED = -12,
PIKA_RES_ERR_UNKNOWN = -13,
PIKA_RES_ERR_SYNTAX_ERROR = -14,
PIKA_RES_ERR_IO = -15,
PIKA_RES_ERR_ASSERT = -16,
PIKA_RES_ERR_SIGNAL_EVENT_FULL = -17,
PIKA_RES_ERR_SIGNAL_EVENT_EMPTY = -18,
} PIKA_RES;
/* clang-format off */
/* pikascript bool type */
typedef enum {
PIKA_TRUE = 1,
PIKA_FALSE = 0,
} PIKA_BOOL;
/* clang-format on */
/*
[Note]:
Create a pika_config.c to override the following weak functions to config
PikaScript. [Example]:
1.
https://gitee.com/Lyon1998/pikascript/blob/master/package/STM32G030Booter/pika_config.c
2.
https://gitee.com/Lyon1998/pikascript/blob/master/package/pikaRTBooter/pika_config.c
*/
/* interrupt config */
void pika_platform_enable_irq_handle(void);
void pika_platform_disable_irq_handle(void);
/* printf family config */
#ifndef pika_platform_printf
void pika_platform_printf(char* fmt, ...);
#endif
int pika_platform_sprintf(char* buff, char* fmt, ...);
int pika_platform_vsprintf(char* buff, char* fmt, va_list args);
int pika_platform_vsnprintf(char* buff,
size_t size,
const char* fmt,
va_list args);
int pika_platform_snprintf(char* buff, size_t size, const char* fmt, ...);
char* pika_platform_strdup(const char* src);
size_t pika_platform_tick_from_millisecond(size_t ms);
/* libc config */
void* pika_platform_malloc(size_t size);
void* pika_platform_realloc(void* ptr, size_t size);
void* pika_platform_calloc(size_t num, size_t size);
void pika_platform_free(void* ptr);
void* pika_platform_memset(void* mem, int ch, size_t size);
void* pika_platform_memcpy(void* dir, const void* src, size_t size);
int pika_platform_memcmp(const void* s1, const void* s2, size_t n);
void* pika_platform_memmove(void* s1, void* s2, size_t n);
/* pika memory pool config */
void pika_platform_wait(void);
/* support shell */
char pika_platform_getchar(void);
int pika_platform_putchar(char ch);
/* file API */
FILE* pika_platform_fopen(const char* filename, const char* modes);
int pika_platform_fclose(FILE* stream);
size_t pika_platform_fwrite(const void* ptr,
size_t size,
size_t n,
FILE* stream);
size_t pika_platform_fread(void* ptr, size_t size, size_t n, FILE* stream);
int pika_platform_fseek(FILE* stream, long offset, int whence);
long pika_platform_ftell(FILE* stream);
/* error */
void pika_platform_error_handle(void);
/* panic */
void pika_platform_panic_handle(void);
void pika_platform_thread_delay(void);
int64_t pika_platform_getTick(void);
void pika_platform_sleep_ms(uint32_t ms);
void pika_platform_sleep_s(uint32_t s);
void pika_hook_instruct(void);
PIKA_BOOL pika_hook_arg_cache_filter(void* self);
void* pika_user_malloc(size_t size);
void pika_user_free(void* ptr, size_t size);
uint8_t pika_is_locked_pikaMemory(void);
#if PIKA_FLOAT_TYPE_DOUBLE
#define pika_float double
#else
#define pika_float float
#endif
#ifdef _WIN32
#pragma warning(disable : 4996)
#endif
/* Thread Platform */
#ifdef __linux
#include <pthread.h>
typedef struct pika_platform_thread {
pthread_t thread;
pthread_mutex_t mutex;
pthread_cond_t cond;
} pika_platform_thread_t;
#elif PIKA_FREERTOS_ENABLE
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
typedef struct pika_platform_thread {
TaskHandle_t thread;
} pika_platform_thread_t;
#else
typedef struct pika_platform_thread {
void* platform_data;
} pika_platform_thread_t;
#endif
pika_platform_thread_t* pika_platform_thread_init(const char* name,
void (*entry)(void*),
void* const param,
unsigned int stack_size,
unsigned int priority,
unsigned int tick);
void pika_platform_thread_startup(pika_platform_thread_t* thread);
void pika_platform_thread_stop(pika_platform_thread_t* thread);
void pika_platform_thread_start(pika_platform_thread_t* thread);
void pika_platform_thread_destroy(pika_platform_thread_t* thread);
#ifdef __linux
#include <pthread.h>
typedef struct pika_platform_thread_mutex {
pthread_mutex_t mutex;
} pika_platform_thread_mutex_t;
#elif PIKA_FREERTOS_ENABLE
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
typedef struct pika_platform_thread_mutex {
SemaphoreHandle_t mutex;
} pika_platform_thread_mutex_t;
#else
typedef struct pika_platform_thread_mutex {
void* platform_data;
} pika_platform_thread_mutex_t;
#endif
int pika_platform_thread_mutex_init(pika_platform_thread_mutex_t* m);
int pika_platform_thread_mutex_lock(pika_platform_thread_mutex_t* m);
int pika_platform_thread_mutex_trylock(pika_platform_thread_mutex_t* m);
int pika_platform_thread_mutex_unlock(pika_platform_thread_mutex_t* m);
int pika_platform_thread_mutex_destroy(pika_platform_thread_mutex_t* m);
#ifdef __linux
#include <sys/time.h>
typedef struct pika_platform_timer {
struct timeval time;
} pika_platform_timer_t;
#elif PIKA_FREERTOS_ENABLE
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
typedef struct pika_platform_timer {
uint32_t time;
} pika_platform_timer_t;
#else
typedef struct pika_platform_timer {
void* platform_data;
} pika_platform_timer_t;
#endif
void pika_platform_timer_init(pika_platform_timer_t* timer);
void pika_platform_timer_cutdown(pika_platform_timer_t* timer,
unsigned int timeout);
char pika_platform_timer_is_expired(pika_platform_timer_t* timer);
int pika_platform_timer_remain(pika_platform_timer_t* timer);
unsigned long pika_platform_timer_now(void);
void pika_platform_timer_usleep(unsigned long usec);
#define WEAK_FUNCTION_NEED_OVERRIDE_ERROR(_) \
pika_platform_printf("Error: weak function `%s()` need override.\r\n", \
__FUNCTION__); \
pika_platform_panic_handle();
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,316 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef __PIKA_VM__H
#define __PIKA_VM__H
#include "PikaObj.h"
#include "dataQueue.h"
#include "dataQueueObj.h"
#include "dataStack.h"
enum Instruct {
#define __INS_ENUM
#include "__instruction_table.cfg"
__INSTRCUTION_CNT,
};
typedef enum {
VM_JMP_EXIT = -999,
VM_JMP_CONTINUE = -997,
VM_JMP_BREAK = -998,
VM_JMP_RAISE = -996,
} VM_JMP;
typedef enum { VM_PC_EXIT = -99999 } VM_PC;
typedef enum {
TRY_STATE_NONE = 0,
TRY_STATE_INNER,
} TRY_STATE;
typedef enum {
TRY_RESULT_NONE = 0,
TRY_RESULT_RAISE,
} TRY_RESULT;
typedef struct RunState RunState;
struct RunState {
TRY_STATE try_state;
TRY_RESULT try_result;
};
typedef struct VMState VMState;
struct VMState {
VMParameters* locals;
VMParameters* globals;
Stack stack;
int32_t jmp;
int32_t pc;
ByteCodeFrame* bytecode_frame;
uint8_t loop_deepth;
int8_t error_code;
uint8_t line_error_code;
uint8_t try_error_code;
uint32_t ins_cnt;
PIKA_BOOL in_super;
uint8_t super_invoke_deepth;
PikaObj* lreg[PIKA_REGIST_SIZE];
PIKA_BOOL ireg[PIKA_REGIST_SIZE];
RunState* run_state;
};
typedef struct {
int8_t n_positional;
int8_t n_positional_got;
int8_t n_default;
int8_t n_arg;
int8_t i_arg;
int8_t n_input;
PIKA_BOOL is_vars;
PIKA_BOOL is_keys;
PIKA_BOOL is_default;
ArgType method_type;
PikaTuple* tuple;
PikaDict* kw;
PikaDict* kw_keys;
char* var_tuple_name;
char* kw_dict_name;
char* type_list;
} FunctionArgsInfo;
typedef struct OperatorInfo OperatorInfo;
struct OperatorInfo {
char* opt;
ArgType t1;
ArgType t2;
Arg* a1;
Arg* a2;
pika_float f1;
pika_float f2;
int64_t i1;
int64_t i2;
Arg* res;
int num;
VMState* vm;
};
typedef enum VM_SIGNAL_CTRL {
VM_SIGNAL_CTRL_NONE = 0,
VM_SIGNAL_CTRL_EXIT,
} VM_SIGNAL_CTRL;
typedef struct EventCQ {
uint32_t id[PIKA_EVENT_LIST_SIZE];
Arg* data[PIKA_EVENT_LIST_SIZE];
PikaEventListener* lisener[PIKA_EVENT_LIST_SIZE];
Arg* res[PIKA_EVENT_LIST_SIZE];
int head;
int tail;
} EventCQ;
typedef struct VMSignal VMSignal;
struct VMSignal {
VM_SIGNAL_CTRL signal_ctrl;
int vm_cnt;
#if PIKA_EVENT_ENABLE
EventCQ cq;
#endif
};
VMParameters* pikaVM_run(PikaObj* self, char* pyLine);
VMParameters* pikaVM_runAsm(PikaObj* self, char* pikaAsm);
VMParameters* pikaVM_runByteCodeFrame(PikaObj* self,
ByteCodeFrame* byteCode_frame);
static inline int instructUnit_getBlockDeepth(InstructUnit* self) {
return self->deepth & 0x0F;
}
static inline int instructUnit_getInvokeDeepth(InstructUnit* self) {
return self->deepth >> 4;
}
static inline enum Instruct instructUnit_getInstruct(InstructUnit* self) {
return (enum Instruct)(self->isNewLine_instruct & 0x7F);
}
static inline int instructUnit_getConstPoolIndex(InstructUnit* self) {
return self->const_pool_index;
}
static inline int instructUnit_getIsNewLine(InstructUnit* self) {
return self->isNewLine_instruct >> 7;
}
static inline void instructUnit_setBlockDeepth(InstructUnit* self, int val) {
self->deepth |= (0x0F & val);
}
static inline void instructUnit_setConstPoolIndex(InstructUnit* self, int val) {
self->const_pool_index = val;
}
static inline void instructUnit_setInvokeDeepth(InstructUnit* self, int val) {
self->deepth |= ((0x0F & val) << 4);
}
static inline void instructUnit_setInstruct(InstructUnit* self, int val) {
self->isNewLine_instruct |= (0x7F & val);
}
static inline void instructUnit_setIsNewLine(InstructUnit* self, int val) {
self->isNewLine_instruct |= ((0x01 & val) << 7);
}
InstructUnit* New_instructUnit(uint8_t data_size);
void instructUnit_deinit(InstructUnit* self);
enum Instruct pikaVM_getInstructFromAsm(char* line);
void constPool_init(ConstPool* self);
void constPool_deinit(ConstPool* self);
void constPool_append(ConstPool* self, char* content);
static inline void* constPool_getStart(ConstPool* self) {
return self->content_start;
}
static inline int constPool_getLastOffset(ConstPool* self) {
return self->size;
}
static inline char* constPool_getByOffset(ConstPool* self, int offset) {
return (char*)((uintptr_t)constPool_getStart(self) + (uintptr_t)offset);
}
static inline char* VMState_getConstWithInstructUnit(VMState* vm,
InstructUnit* ins_unit) {
return constPool_getByOffset(&(vm->bytecode_frame->const_pool),
instructUnit_getConstPoolIndex(ins_unit));
}
char* constPool_getNow(ConstPool* self);
char* constPool_getNext(ConstPool* self);
char* constPool_getByIndex(ConstPool* self, uint16_t index);
void constPool_print(ConstPool* self);
void byteCodeFrame_init(ByteCodeFrame* bf);
void byteCodeFrame_deinit(ByteCodeFrame* bf);
size_t byteCodeFrame_getSize(ByteCodeFrame* bf);
void instructArray_init(InstructArray* ins_array);
void instructArray_deinit(InstructArray* ins_array);
void instructArray_append(InstructArray* ins_array, InstructUnit* ins_unit);
void instructUnit_init(InstructUnit* ins_unit);
void instructUnit_print(InstructUnit* self);
void instructArray_print(InstructArray* self);
static inline InstructUnit* instructArray_getStart(InstructArray* self) {
return (InstructUnit*)self->content_start;
}
static inline size_t instructArray_getSize(InstructArray* self) {
return (size_t)self->size;
}
static inline int VMState_getInstructArraySize(VMState* vm) {
return instructArray_getSize(&(vm->bytecode_frame->instruct_array));
}
static inline InstructUnit* instructArray_getByOffset(InstructArray* self,
int offset) {
return (InstructUnit*)((uintptr_t)instructArray_getStart(self) +
(uintptr_t)offset);
}
static inline InstructUnit* VMState_getInstructUnitWithOffset(VMState* vm,
int offset) {
return instructArray_getByOffset(&(vm->bytecode_frame->instruct_array),
vm->pc + offset);
}
static inline InstructUnit* VMState_getInstructNow(VMState* vm) {
return instructArray_getByOffset(&(vm->bytecode_frame->instruct_array),
vm->pc);
}
void byteCodeFrame_print(ByteCodeFrame* self);
static inline size_t instructUnit_getSize(void) {
return (size_t)sizeof(InstructUnit);
}
uint16_t constPool_getOffsetByData(ConstPool* self, char* data);
void instructArray_printWithConst(InstructArray* self, ConstPool* const_pool);
void constPool_update(ConstPool* self);
void instructArray_update(InstructArray* self);
void constPool_printAsArray(ConstPool* self);
void instructArray_printAsArray(InstructArray* self);
void byteCodeFrame_loadByteCode(ByteCodeFrame* self, uint8_t* bytes);
void byteCodeFrame_printAsArray(ByteCodeFrame* self);
void byteCodeFrame_init(ByteCodeFrame* self);
VMParameters* pikaVM_runByteCode(PikaObj* self, const uint8_t* bytecode);
VMParameters* pikaVM_runByteCodeInconstant(PikaObj* self, uint8_t* bytecode);
InstructUnit* instructArray_getNow(InstructArray* self);
InstructUnit* instructArray_getNext(InstructArray* self);
VMParameters* pikaVM_runSingleFile(PikaObj* self, char* filename);
VMParameters* pikaVM_runByteCodeFile(PikaObj* self, char* filename);
Arg* obj_runMethodArg(PikaObj* self, PikaObj* method_args_obj, Arg* method_arg);
PikaObj* pikaVM_runFile(PikaObj* self, char* file_name);
Arg* _vm_slice(VMState* vm,
PikaObj* self,
Arg* end,
Arg* obj,
Arg* start,
int step);
VMParameters* _do_pikaVM_runByteCode(PikaObj* self,
VMParameters* locals,
VMParameters* globals,
uint8_t* bytecode,
RunState* run_state,
PIKA_BOOL is_const_bytecode);
void _do_byteCodeFrame_loadByteCode(ByteCodeFrame* self,
uint8_t* bytes,
PIKA_BOOL is_const);
Arg* __vm_get(VMState* vm, PikaObj* self, Arg* key, Arg* obj);
void __vm_List_append(PikaObj* self, Arg* arg);
void __vm_List___init__(PikaObj* self);
void __vm_Dict_set(PikaObj* self, Arg* arg, char* key);
void __vm_Dict___init__(PikaObj* self);
VM_SIGNAL_CTRL VMSignal_getCtrl(void);
void pks_vm_exit(void);
void pks_vmSignal_setCtrlElear(void);
PIKA_RES __eventListener_popEvent(PikaEventListener** lisener_p,
uint32_t* id,
Arg** signal,
int* head);
PIKA_RES __eventListener_pushEvent(PikaEventListener* lisener,
uint32_t eventId,
Arg* eventData);
int _VMEvent_getVMCnt(void);
void _VMEvent_pickupEvent(void);
#endif

View File

@ -0,0 +1,5 @@
#define PIKA_VERSION_MAJOR 1
#define PIKA_VERSION_MINOR 12
#define PIKA_VERSION_MICRO 0
#define PIKA_EDIT_TIME "2022/12/29 18:05:17"

View File

@ -0,0 +1 @@
# PikaScript 运行时内核

View File

@ -0,0 +1,37 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "PikaObj.h"
const NativeProperty TinyObjNativeProp = {.super = NULL,
.methodGroup = NULL,
.methodGroupCount = 0};
PikaObj* New_TinyObj(Args* args) {
PikaObj* self = New_PikaObj();
return self;
}

View File

@ -0,0 +1,32 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef __TYNYOBJ__H
#define __TYNYOBJ__H
#include "PikaObj.h"
PikaObj* New_TinyObj(Args* args);
#endif

View File

@ -0,0 +1,54 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 GorgonMeducer ?? embedded_zhuoran@hotmail.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#undef def_ins
#if defined(__INS_ENUM)
#define def_ins(__INS_NAME) __INS_NAME,
#endif
#if defined(__INS_TABLE)
#define def_ins(__INS_NAME) [__INS_NAME] = &VM_instruction_handler_##__INS_NAME,
#endif
#if defined(__INS_COMPIRE)
#define def_ins(__INS_NAME) \
if (0 == strncmp(ins_str, "" #__INS_NAME "", 3)) { \
return __INS_NAME; \
}
#endif
#if defined(__INS_GET_INS_STR)
#define def_ins(__INS_NAME) \
if (__INS_NAME == instructUnit_getInstruct(self)){ \
return ""#__INS_NAME""; \
}
#endif
#undef __INS_ENUM
#undef __INS_TABLE
#undef __INS_COMPIRE

View File

@ -0,0 +1,98 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 GorgonMeducer ?? embedded_zhuoran@hotmail.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "__instruction_def.h"
//! just append ins to the end, insert ins would brake the pre-compiled
//! bytecode.
/* none */
def_ins(NON)
/* get referance */
def_ins(REF)
/* run function */
def_ins(RUN)
/* string */
def_ins(STR)
/* output */
def_ins(OUT)
/* number */
def_ins(NUM)
/* jump */
def_ins(JMP)
/* jump qual zero */
def_ins(JEZ)
/* operator */
def_ins(OPT)
/* define */
def_ins(DEF)
/* return */
def_ins(RET)
/* not equal */
def_ins(NEL)
/* delete */
def_ins(DEL)
/* exist */
def_ins(EST)
/* break */
def_ins(BRK)
/* continue */
def_ins(CTN)
/* global */
def_ins(GLB)
/* run as */
def_ins(RAS)
/* new */
def_ins(NEW)
/* class */
def_ins(CLS)
/* bytes */
def_ins(BYT)
/* list */
def_ins(LST)
/* import */
def_ins(IMP)
/* try */
def_ins(TRY)
/* not try */
def_ins(NTR)
/* raise */
def_ins(RIS)
/* get error code */
def_ins(GER)
/* set error code */
def_ins(SER)
/* dict */
def_ins(DCT)
/* slice */
def_ins(SLC)
/* assert */
def_ins(ASS)
/* expect */
def_ins(EXP)
/* jump no zero */
def_ins(JNZ)

View File

@ -0,0 +1,36 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon ?? liang6516@outlook.com
* Copyright (c) 2021 Gorgon Meducer ?? embedded_zhuoran@hotmail.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef __PIKA_OOC_H__
#define __PIKA_OOC_H__
#if PIKA_PLOOC_ENABLE
#include "../pikascript-lib/PLOOC/plooc_class.h"
#else
#define private_member(X) X
#endif
#endif

View File

@ -0,0 +1,599 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "dataArg.h"
#include "PikaObj.h"
#include "dataArgs.h"
#include "dataMemory.h"
#include "dataString.h"
#include "stdlib.h"
static PIKA_BOOL _arg_cache_push(Arg* self, uint32_t size) {
#if !PIKA_ARG_CACHE_ENABLE
return PIKA_FALSE;
#else
if (PIKA_FALSE == pika_hook_arg_cache_filter(self)) {
return PIKA_FALSE;
}
extern PikaMemInfo pikaMemInfo;
if (self->heap_size < PIKA_ARG_CACHE_SIZE ||
self->heap_size > 2 * PIKA_ARG_CACHE_SIZE) {
return PIKA_FALSE;
}
if (PIKA_ARG_CACHE_POOL_SIZE <= pikaMemInfo.cache_pool_top) {
return PIKA_FALSE;
}
pikaMemInfo.cache_pool[pikaMemInfo.cache_pool_top++] = (uint8_t*)self;
pikaMemInfo.heapUsed -= mem_align(sizeof(Arg) + size);
return PIKA_TRUE;
#endif
}
static Arg* _arg_cache_pop(uint32_t size) {
#if !PIKA_ARG_CACHE_ENABLE
return NULL;
#else
uint32_t req_heap_size = mem_align(sizeof(Arg) + size);
extern PikaMemInfo pikaMemInfo;
if (req_heap_size > PIKA_ARG_CACHE_SIZE) {
return NULL;
}
if (!(pikaMemInfo.cache_pool_top > 0)) {
return NULL;
}
--pikaMemInfo.cache_pool_top;
Arg* self = (Arg*)pikaMemInfo.cache_pool[pikaMemInfo.cache_pool_top];
pikaMemInfo.heapUsed += mem_align(sizeof(Arg) + size);
return self;
#endif
}
uint32_t arg_getTotleSize(Arg* self) {
return arg_totleSize(self);
}
/**
* time33 hash
*/
Hash hash_time33EndWith(char* str, char end) {
pika_assert(str != NULL);
if (*str == 0) {
return 5381;
}
Hash hash = 5381;
while (*str && *str != end) {
hash += (hash << 5) + (*str++);
}
return (hash & 0x7FFFFFFF);
}
Hash hash_time33(char* str) {
pika_assert(str != NULL);
if (*str == 0) {
return 5381;
}
Hash hash = 5381;
while (*str) {
hash += (hash << 5) + (*str++);
}
return (hash & 0x7FFFFFFF);
}
static Arg* _arg_set_hash(Arg* self,
Hash nameHash,
ArgType type,
uint8_t* content,
uint32_t size,
Arg* next) {
/* create arg if not exist */
if (NULL == self || self->size < size) {
self = _arg_cache_pop(size);
uint32_t heap_size = sizeof(Arg) + size;
#if PIKA_ARG_CACHE_ENABLE
// if (heap_size < PIKA_ARG_CACHE_SIZE) {
// heap_size = PIKA_ARG_CACHE_SIZE;
// }
extern PikaMemInfo pikaMemInfo;
pikaMemInfo.alloc_times++;
pikaMemInfo.alloc_times_cache++;
#endif
if (NULL == self) {
self = (Arg*)pikaMalloc(heap_size);
#if PIKA_ARG_CACHE_ENABLE
extern PikaMemInfo pikaMemInfo;
pikaMemInfo.alloc_times_cache--;
self->heap_size = mem_align(heap_size);
#endif
}
self->size = size;
self->flag = 0;
arg_setSerialized(self, PIKA_TRUE);
// arg_setIsKeyword(self, PIKA_FALSE);
arg_setNext(self, next);
}
self->name_hash = nameHash;
self->type = type;
if (NULL != content) {
pika_platform_memcpy(arg_getContent(self), content, size);
} else {
pika_platform_memset(arg_getContent(self), 0,
aline_by(size, sizeof(uint32_t)));
}
pika_assert(self->flag < ARG_FLAG_MAX);
return self;
}
static Arg* arg_create_hash(Hash nameHash,
ArgType type,
uint8_t* content,
uint32_t size,
Arg* next) {
return _arg_set_hash(NULL, nameHash, type, content, size, next);
}
static Arg* arg_create(char* name,
ArgType type,
uint8_t* content,
uint32_t size,
Arg* next) {
Hash nameHash = hash_time33(name);
return arg_create_hash(nameHash, type, content, size, next);
}
static Arg* arg_set(Arg* self,
char* name,
ArgType type,
uint8_t* content,
uint32_t size) {
Hash nameHash = hash_time33(name);
return _arg_set_hash(self, nameHash, type, content, size, NULL);
}
void arg_init_stack(Arg* self, uint8_t* buffer, uint32_t size) {
self->_.buffer = buffer;
self->size = size;
}
uint32_t arg_totleSize(Arg* self) {
return ((Arg*)self)->size + sizeof(Arg);
}
void arg_freeContent(Arg* self) {
pika_assert(NULL != self);
if (_arg_cache_push(self, self->size)) {
return;
}
pikaFree(self, arg_totleSize(self));
return;
}
Arg* arg_setContent(Arg* self, uint8_t* content, uint32_t size) {
if (NULL == self) {
/* malloc */
return arg_create("", ARG_TYPE_NONE, content, size, NULL);
}
/* only copy */
if (arg_getSize(self) >= size) {
pika_platform_memcpy(arg_getContent((Arg*)self), content, size);
return self;
}
/* realloc */
Hash nameHash = arg_getNameHash(self);
ArgType type = arg_getType(self);
Arg* next = arg_getNext(self);
Arg* newContent = arg_create_hash(nameHash, type, content, size, next);
arg_freeContent(self);
return newContent;
}
Arg* arg_setNameHash(Arg* self, Hash nameHash) {
if (NULL == self) {
return arg_create_hash(nameHash, ARG_TYPE_NONE, NULL, 0, NULL);
}
Arg* arg = (Arg*)self;
arg->name_hash = nameHash;
return self;
}
Arg* arg_setName(Arg* self, char* name) {
pika_assert(NULL != name);
return arg_setNameHash(self, hash_time33(name));
}
Arg* arg_setBytes(Arg* self, char* name, uint8_t* src, size_t size) {
self = arg_newContent(size + sizeof(size_t) + 1);
if (NULL == self) {
return NULL;
}
self = arg_setName(self, name);
pika_assert(NULL != self);
arg_setType(self, ARG_TYPE_BYTES);
void* dir = arg_getContent(self);
/* set content all to 0 */
pika_platform_memset(dir, 0, size + sizeof(size_t) + 1);
/* setsize */
pika_platform_memcpy(dir, &size, sizeof(size_t));
/* set init value */
if (NULL != src) {
pika_platform_memcpy((void*)((uintptr_t)dir + sizeof(size_t)), src, size);
}
pika_assert(self->flag < ARG_FLAG_MAX);
return self;
}
Arg* arg_newContent(uint32_t size) {
Arg* newContent = arg_create("", ARG_TYPE_NONE, NULL, size, NULL);
return newContent;
}
uint8_t* arg_getBytes(Arg* self) {
return arg_getContent(self) + sizeof(size_t);
}
char* __printBytes(PikaObj* self, Arg* arg) {
Args buffs = {0};
size_t bytes_size = arg_getBytesSize(arg);
uint8_t* bytes = arg_getBytes(arg);
Arg* str_arg = arg_newStr("b\'");
for (size_t i = 0; i < bytes_size; i++) {
char* str_item = strsFormat(&buffs, 16, "\\x%02x", bytes[i]);
str_arg = arg_strAppend(str_arg, str_item);
}
str_arg = arg_strAppend(str_arg, "\'");
char* str_res = obj_cacheStr(self, arg_getStr(str_arg));
strsDeinit(&buffs);
arg_deinit(str_arg);
return str_res;
}
void arg_printBytes(Arg* self, char* end) {
PikaObj* obj = New_PikaObj();
pika_platform_printf("%s%s", __printBytes(obj, self), end);
obj_deinit(obj);
}
void arg_singlePrint(Arg* self, PIKA_BOOL in_REPL, char* end) {
ArgType type = arg_getType(self);
if (ARG_TYPE_NONE == type) {
pika_platform_printf("None%s", end);
return;
}
if (argType_isObject(type)) {
char* res = obj_toStr(arg_getPtr(self));
pika_platform_printf("%s%s", res, end);
return;
}
if (type == ARG_TYPE_INT) {
#if PIKA_PRINT_LLD_ENABLE
pika_platform_printf("%lld%s", (long long int)arg_getInt(self), end);
#else
pika_platform_printf("%d%s", (int)arg_getInt(self), end);
#endif
return;
}
if (type == ARG_TYPE_FLOAT) {
pika_platform_printf("%f%s", arg_getFloat(self), end);
return;
}
if (type == ARG_TYPE_STRING) {
if (in_REPL) {
pika_platform_printf("'%s'%s", arg_getStr(self), end);
return;
}
pika_platform_printf("%s%s", arg_getStr(self), end);
return;
}
if (type == ARG_TYPE_BYTES) {
arg_printBytes(self, end);
return;
}
if (ARG_TYPE_POINTER == type || ARG_TYPE_METHOD_NATIVE_CONSTRUCTOR) {
pika_platform_printf("%p%s", arg_getPtr(self), end);
return;
}
return;
}
size_t arg_getBytesSize(Arg* self) {
size_t mem_size = 0;
void* content = (void*)arg_getContent(self);
if (NULL == content) {
return 0;
}
pika_platform_memcpy(&mem_size, content, sizeof(size_t));
return mem_size;
}
Arg* arg_setStruct(Arg* self,
char* name,
void* struct_ptr,
uint32_t struct_size) {
if (NULL == struct_ptr) {
return NULL;
}
return arg_set(self, name, ARG_TYPE_STRUCT, (uint8_t*)struct_ptr,
struct_size);
}
Arg* arg_setHeapStruct(Arg* self,
char* name,
void* struct_ptr,
uint32_t struct_size,
void* struct_deinit_fun) {
if (NULL == struct_ptr) {
return NULL;
}
Arg* struct_arg =
arg_setContent(NULL, (uint8_t*)&struct_deinit_fun, sizeof(void*));
struct_arg = arg_append(struct_arg, (uint8_t*)struct_ptr, struct_size);
pika_assert(NULL != struct_arg);
arg_setType(struct_arg, ARG_TYPE_STRUCT_HEAP);
struct_arg = arg_setName(struct_arg, name);
return struct_arg;
}
void* arg_getHeapStructDeinitFun(Arg* self) {
void* deinit_fun = NULL;
pika_platform_memcpy(&deinit_fun, arg_getContent(self), sizeof(void*));
return deinit_fun;
}
Arg* arg_setInt(Arg* self, char* name, int64_t val) {
return arg_set(self, name, ARG_TYPE_INT, (uint8_t*)&val, sizeof(val));
}
Arg* arg_setNull(Arg* self) {
return arg_set(self, "", ARG_TYPE_NONE, NULL, 0);
}
Arg* arg_setFloat(Arg* self, char* name, pika_float val) {
return arg_set(self, name, ARG_TYPE_FLOAT, (uint8_t*)&val, sizeof(val));
}
pika_float arg_getFloat(Arg* self) {
if (NULL == arg_getContent(self)) {
return -999.999;
}
return *(pika_float*)arg_getContent(self);
}
Arg* arg_setPtr(Arg* self, char* name, ArgType type, void* pointer) {
return arg_set(self, name, type, (uint8_t*)&pointer, sizeof(uintptr_t));
}
Arg* arg_setStr(Arg* self, char* name, char* string) {
if (NULL == string) {
return NULL;
}
return arg_set(self, name, ARG_TYPE_STRING, (uint8_t*)string,
strGetSize(string) + 1);
}
int64_t arg_getInt(Arg* self) {
pika_assert(NULL != self);
if (NULL == arg_getContent(self)) {
return -999999;
}
return *(int64_t*)arg_getContent(self);
}
void* arg_getPtr(Arg* self) {
if (arg_getType(self) == ARG_TYPE_NONE) {
return NULL;
}
if (NULL == arg_getContent(self)) {
return NULL;
}
return *(void**)arg_getContent(self);
}
char* arg_getStr(Arg* self) {
return (char*)arg_getContent(self);
}
uint32_t arg_getContentSize(Arg* self) {
return arg_getSize(self);
}
Arg* New_arg(void* voidPointer) {
return NULL;
}
Arg* arg_copy(Arg* arg_src) {
if (NULL == arg_src) {
return NULL;
}
pika_assert(arg_src->flag < ARG_FLAG_MAX);
ArgType arg_type = arg_getType(arg_src);
if (ARG_TYPE_OBJECT == arg_type) {
obj_refcntInc((PikaObj*)arg_getPtr(arg_src));
}
Arg* arg_dict = New_arg(NULL);
arg_dict = arg_setContent(arg_dict, arg_getContent(arg_src),
arg_getContentSize(arg_src));
arg_dict = arg_setNameHash(arg_dict, arg_getNameHash(arg_src));
pika_assert(NULL != arg_dict);
arg_setType(arg_dict, arg_getType(arg_src));
arg_setIsKeyword(arg_dict, arg_getIsKeyword(arg_src));
return arg_dict;
}
Arg* arg_copy_noalloc(Arg* arg_src, Arg* arg_dict) {
if (NULL == arg_src) {
return NULL;
}
if (NULL == arg_dict) {
return arg_copy(arg_src);
}
/* size is too big to be copied by noalloc */
if (arg_getSize(arg_src) > arg_getSize(arg_dict)) {
return arg_copy(arg_src);
}
ArgType arg_type = arg_getType(arg_src);
if (ARG_TYPE_OBJECT == arg_type) {
obj_refcntInc((PikaObj*)arg_getPtr(arg_src));
}
arg_setSerialized(arg_dict, PIKA_FALSE);
arg_dict = arg_setContent(arg_dict, arg_getContent(arg_src),
arg_getContentSize(arg_src));
arg_dict = arg_setNameHash(arg_dict, arg_getNameHash(arg_src));
pika_assert(NULL != arg_dict);
arg_setType(arg_dict, arg_getType(arg_src));
arg_setIsKeyword(arg_dict, arg_getIsKeyword(arg_src));
return arg_dict;
}
Arg* arg_append(Arg* self, void* new_content, size_t new_size) {
uint8_t* old_content = arg_getContent(self);
size_t old_size = arg_getContentSize(self);
Arg* new_arg = NULL;
#if PIKA_ARG_CACHE_ENABLE
/* create arg_out */
if (self->heap_size > mem_align(sizeof(Arg) + old_size + new_size)) {
new_arg = self;
new_arg->size = old_size + new_size;
extern PikaMemInfo pikaMemInfo;
pikaMemInfo.heapUsed += mem_align(sizeof(Arg) + old_size + new_size) -
mem_align(sizeof(Arg) + old_size);
}
#endif
if (NULL == new_arg) {
new_arg = arg_setContent(NULL, NULL, old_size + new_size);
}
pika_assert(NULL != new_arg);
arg_setType(new_arg, arg_getType(self));
arg_setNameHash(new_arg, arg_getNameHash(self));
if (self != new_arg) {
/* copy old content */
pika_platform_memcpy(arg_getContent(new_arg), old_content, old_size);
}
/* copy new content */
pika_platform_memcpy(arg_getContent(new_arg) + old_size, new_content,
new_size);
if (self != new_arg) {
arg_deinit(self);
}
return new_arg;
}
void* arg_getHeapStruct(Arg* self) {
return arg_getContent(self) + sizeof(void*);
}
void arg_deinitHeap(Arg* self) {
if (arg_getIsWeakRef(self)) {
return;
}
ArgType type = arg_getType(self);
/* deinit heap struct */
if (type == ARG_TYPE_STRUCT_HEAP) {
/* deinit heap strcut */
StructDeinitFun struct_deinit_fun =
(StructDeinitFun)arg_getHeapStructDeinitFun(self);
struct_deinit_fun(arg_getHeapStruct(self));
return;
}
/* deinit sub object */
if (ARG_TYPE_OBJECT == type) {
PikaObj* subObj = arg_getPtr(self);
obj_refcntDec(subObj);
int ref_cnt = obj_refcntNow(subObj);
if (ref_cnt <= 0) {
obj_deinit(subObj);
}
return;
}
}
/* load file as byte array */
Arg* arg_loadFile(Arg* self, char* filename) {
size_t file_size = 0;
char* file_buff = pika_platform_malloc(PIKA_READ_FILE_BUFF_SIZE);
Arg* res = New_arg(NULL);
pika_platform_memset(file_buff, 0, PIKA_READ_FILE_BUFF_SIZE);
FILE* input_file = pika_platform_fopen(filename, "rb");
if (NULL == input_file) {
pika_platform_printf("Error: Couldn't open file '%s'\n", filename);
res = NULL;
goto exit;
}
file_size =
pika_platform_fread(file_buff, 1, PIKA_READ_FILE_BUFF_SIZE, input_file);
if (file_size >= PIKA_READ_FILE_BUFF_SIZE) {
pika_platform_printf("Error: Not enough buff for input file.\r\n");
return NULL;
}
/* add '\0' to the end of the string */
res = arg_setBytes(res, "", (uint8_t*)file_buff, file_size + 1);
exit:
pika_platform_free(file_buff);
if (NULL != input_file) {
pika_platform_fclose(input_file);
}
return res;
}
void arg_deinit(Arg* self) {
pika_assert(NULL != self);
/* deinit arg pointed heap */
arg_deinitHeap(self);
if (!arg_isSerialized(self)) {
return;
}
/* free the ref */
arg_freeContent(self);
}
PIKA_BOOL arg_isEqual(Arg* self, Arg* other) {
if (NULL == self || NULL == other) {
return PIKA_FALSE;
}
if (arg_getType(self) != arg_getType(other)) {
return PIKA_FALSE;
}
if (arg_getType(self) == ARG_TYPE_OBJECT) {
if (arg_getPtr(self) != arg_getPtr(other)) {
return PIKA_FALSE;
}
}
if (arg_getType(self) == ARG_TYPE_STRING) {
if (strEqu(arg_getStr(self), arg_getStr(other))) {
return PIKA_TRUE;
}
}
if (0 != pika_platform_memcmp(arg_getContent(self), arg_getContent(other),
arg_getContentSize(self))) {
return PIKA_FALSE;
}
return PIKA_TRUE;
}

View File

@ -0,0 +1,277 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef _arg__H
#define _arg__H
#include "dataLink.h"
#include "dataMemory.h"
typedef uint32_t Hash;
typedef enum {
ARG_TYPE_UNDEF = 0,
ARG_TYPE_NONE,
ARG_TYPE_INT,
ARG_TYPE_FLOAT,
ARG_TYPE_STRING,
ARG_TYPE_BYTES,
ARG_TYPE_POINTER,
ARG_TYPE_BIG_ARG_PTR,
ARG_TYPE_OBJECT,
ARG_TYPE_OBJECT_META,
ARG_TYPE_OBJECT_NEW,
ARG_TYPE_METHOD_NATIVE,
ARG_TYPE_METHOD_NATIVE_CONSTRUCTOR,
ARG_TYPE_METHOD_CONSTRUCTOR,
ARG_TYPE_METHOD_OBJECT,
ARG_TYPE_METHOD_STATIC,
ARG_TYPE_STRUCT,
ARG_TYPE_STRUCT_HEAP,
ARG_TYPE_TUPLE,
} ArgType;
typedef void (*StructDeinitFun)(void* struct_);
typedef struct Arg Arg;
typedef union {
Arg* next;
uint8_t* buffer;
} _arg_union;
struct Arg {
_arg_union _;
uint32_t size;
#if PIKA_ARG_CACHE_ENABLE
uint32_t heap_size;
#endif
ArgType type;
uint8_t flag;
Hash name_hash;
uint8_t content[];
};
typedef struct ConstArg {
_arg_union _;
uint32_t size;
#if PIKA_ARG_CACHE_ENABLE
uint32_t heap_size;
#endif
ArgType type;
uint8_t flag;
Hash name_hash;
} ConstArg;
uint32_t arg_totleSize(Arg* self);
uint32_t arg_getTotleSize(Arg* self);
void arg_freeContent(Arg* self);
Arg* arg_setName(Arg* self, char* name);
Arg* arg_setNameHash(Arg* self, Hash nameHash);
Arg* arg_setContent(Arg* self, uint8_t* content, uint32_t size);
Arg* arg_newContent(uint32_t size);
static inline void arg_setType(Arg* self, ArgType type) {
self->type = type;
}
static inline Hash arg_getNameHash(Arg* self) {
return self->name_hash;
}
static inline ArgType arg_getType(Arg* self) {
return (ArgType)self->type;
}
uint32_t arg_getContentSize(Arg* self);
Hash hash_time33(char* str);
Arg* arg_setInt(Arg* self, char* name, int64_t val);
Arg* arg_setFloat(Arg* self, char* name, pika_float val);
Arg* arg_setPtr(Arg* self, char* name, ArgType type, void* pointer);
Arg* arg_setStr(Arg* self, char* name, char* string);
Arg* arg_setNull(Arg* self);
Arg* arg_setBytes(Arg* self, char* name, uint8_t* src, size_t size);
static inline Arg* arg_newInt(int64_t val) {
return arg_setInt(NULL, "", (val));
}
static inline Arg* arg_newFloat(pika_float val) {
return arg_setFloat(NULL, "", (val));
}
static inline Arg* arg_newPtr(ArgType type, void* pointer) {
return arg_setPtr(NULL, "", (type), (pointer));
}
static inline Arg* arg_newStr(char* string) {
return arg_setStr(NULL, "", (string));
}
static inline Arg* arg_newNull() {
return arg_setNull(NULL);
}
static inline Arg* arg_newBytes(uint8_t* src, size_t size) {
return arg_setBytes(NULL, "", (src), (size));
}
int64_t arg_getInt(Arg* self);
pika_float arg_getFloat(Arg* self);
void* arg_getPtr(Arg* self);
char* arg_getStr(Arg* self);
uint8_t* arg_getBytes(Arg* self);
size_t arg_getBytesSize(Arg* self);
Arg* arg_copy(Arg* argToBeCopy);
Arg* arg_copy_noalloc(Arg* argToBeCopy, Arg* argToBeCopyTo);
void arg_deinit(Arg* self);
Arg* New_arg(void* voidPointer);
Arg* arg_append(Arg* arg_in, void* new_content, size_t new_size);
Arg* arg_setStruct(Arg* self,
char* name,
void* struct_ptr,
uint32_t struct_size);
Arg* arg_setHeapStruct(Arg* self,
char* name,
void* struct_ptr,
uint32_t struct_size,
void* struct_deinit_fun);
void* arg_getHeapStruct(Arg* self);
void arg_deinitHeap(Arg* self);
void arg_printBytes(Arg* self, char* end);
void arg_singlePrint(Arg* self, PIKA_BOOL in_REPL, char* end);
Arg* arg_loadFile(Arg* self, char* filename);
#define ARG_FLAG_SERIALIZED 0x01
#define ARG_FLAG_KEYWORD 0x02
#define ARG_FLAG_WEAK_REF 0x04
#define ARG_FLAG_STARRED 0x08
#define ARG_FLAG_DOUBLE_STARRED 0x10
#define ARG_FLAG_MAX 0x18
static inline Arg* arg_getNext(Arg* self) {
return self->_.next;
}
static inline void arg_setNext(Arg* self, Arg* next) {
pika_assert(NULL != self);
self->_.next = next;
}
static inline uint32_t arg_getSize(Arg* self) {
pika_assert(NULL != self);
return self->size;
}
static inline uint8_t arg_isSerialized(Arg* self) {
pika_assert(NULL != self);
pika_assert(self->flag <= ARG_FLAG_MAX);
return self->flag & ARG_FLAG_SERIALIZED;
}
static inline void arg_setSerialized(Arg* self, uint8_t serialized) {
self->flag = (self->flag & ~ARG_FLAG_SERIALIZED) |
(serialized ? ARG_FLAG_SERIALIZED : 0);
}
static inline uint8_t arg_getIsKeyword(Arg* self) {
pika_assert(self->flag <= ARG_FLAG_MAX);
return self->flag & ARG_FLAG_KEYWORD;
}
static inline void arg_setIsKeyword(Arg* self, uint8_t isKeyword) {
self->flag =
(self->flag & ~ARG_FLAG_KEYWORD) | (isKeyword ? ARG_FLAG_KEYWORD : 0);
}
static inline uint8_t arg_getIsWeakRef(Arg* self) {
pika_assert(self->flag <= ARG_FLAG_MAX);
return self->flag & ARG_FLAG_WEAK_REF;
}
static inline void arg_setIsWeakRef(Arg* self, uint8_t isWeakRef) {
pika_assert(NULL != self);
self->flag =
(self->flag & ~ARG_FLAG_WEAK_REF) | (isWeakRef ? ARG_FLAG_WEAK_REF : 0);
}
static inline void arg_setIsStarred(Arg* self, uint8_t isStarred) {
self->flag =
(self->flag & ~ARG_FLAG_STARRED) | (isStarred ? ARG_FLAG_STARRED : 0);
}
static inline uint8_t arg_getIsStarred(Arg* self) {
pika_assert(self->flag <= ARG_FLAG_MAX);
return self->flag & ARG_FLAG_STARRED;
}
static inline void arg_setIsDoubleStarred(Arg* self, uint8_t isDoubleStarred) {
self->flag = (self->flag & ~ARG_FLAG_DOUBLE_STARRED) |
(isDoubleStarred ? ARG_FLAG_DOUBLE_STARRED : 0);
}
static inline uint8_t arg_getIsDoubleStarred(Arg* self) {
pika_assert(self->flag <= ARG_FLAG_MAX);
return self->flag & ARG_FLAG_DOUBLE_STARRED;
}
static inline uint8_t* arg_getContent(Arg* self) {
pika_assert(self->flag <= ARG_FLAG_MAX);
pika_assert(NULL != self);
return (arg_isSerialized(self)) ? (self)->content : ((self)->_.buffer);
}
static inline uint8_t argType_isObject(ArgType type) {
return ((type) == ARG_TYPE_OBJECT || (type) == ARG_TYPE_OBJECT_NEW);
}
static inline uint8_t argType_isCallable(ArgType type) {
return ((type) == ARG_TYPE_METHOD_CONSTRUCTOR ||
(type) == ARG_TYPE_METHOD_OBJECT ||
(type) == ARG_TYPE_METHOD_STATIC ||
(type) == ARG_TYPE_METHOD_NATIVE ||
(type) == ARG_TYPE_METHOD_NATIVE_CONSTRUCTOR);
}
static inline uint8_t argType_isNative(ArgType type) {
return ((type) == ARG_TYPE_METHOD_NATIVE ||
(type) == ARG_TYPE_METHOD_NATIVE_CONSTRUCTOR);
}
#define arg_newReg(__name, __size) \
Arg __name = {0}; \
uint8_t __##__name##_buff[__size] = {0}; \
arg_init_stack(&__name, __##__name##_buff, __size)
void arg_init_stack(Arg* self, uint8_t* buffer, uint32_t size);
PIKA_BOOL arg_isEqual(Arg* self, Arg* other);
Hash hash_time33EndWith(char* str, char end);
#endif

View File

@ -0,0 +1,729 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "dataArgs.h"
#include "PikaObj.h"
#include "PikaPlatform.h"
#include "dataLink.h"
#include "dataMemory.h"
#include "dataString.h"
#include "dataStrs.h"
void args_deinit(Args* self) {
pika_assert(self != NULL);
link_deinit(self);
}
void args_deinit_stack(Args* self) {
link_deinit_stack(self);
}
PIKA_RES args_setFloat(Args* self, char* name, pika_float argFloat) {
Arg* argNew = New_arg(NULL);
argNew = arg_setFloat(argNew, name, argFloat);
args_setArg(self, argNew);
return PIKA_RES_OK;
}
void* args_getPtr(Args* self, char* name) {
void* pointer = NULL;
Arg* arg = args_getArg(self, name);
if (NULL == arg) {
return NULL;
}
pointer = arg_getPtr(arg);
return pointer;
}
PIKA_RES args_setPtrWithType(Args* self, char* name, ArgType type, void* val) {
Arg* arg = args_getArg(self, name);
if (NULL == arg) {
args_pushArg_name(self, name, arg_newPtr(type, val));
return PIKA_RES_OK;
}
void** val_ptr = (void**)arg_getContent(arg);
*val_ptr = val;
arg_setType(arg, type);
return PIKA_RES_OK;
}
PIKA_RES args_setPtr(Args* self, char* name, void* argPointer) {
return args_setPtrWithType(self, name, ARG_TYPE_POINTER, argPointer);
}
PIKA_RES args_setRef(Args* self, char* name, void* argPointer) {
PIKA_RES errCode = PIKA_RES_OK;
Arg* argNew = New_arg(NULL);
argNew = arg_setRef(argNew, name, argPointer);
args_setArg(self, argNew);
return errCode;
}
PIKA_RES args_setStr(Args* self, char* name, char* strIn) {
PIKA_RES errCode = PIKA_RES_OK;
Arg* argNew = New_arg(NULL);
argNew = arg_setStr(argNew, name, strIn);
if (NULL == argNew) {
return PIKA_RES_ERR_INVALID_PTR;
}
args_setArg(self, argNew);
return errCode;
}
PIKA_RES args_setNone(Args* self, char* name) {
PIKA_RES errCode = PIKA_RES_OK;
Arg* argNew = arg_newNull();
arg_setName(argNew, name);
args_setArg(self, argNew);
return errCode;
}
PIKA_RES args_pushArg(Args* self, Arg* arg) {
Arg* new_arg = NULL;
if (!arg_isSerialized(arg)) {
new_arg = arg_copy(arg);
arg_deinit(arg);
} else {
new_arg = arg;
}
link_addNode(self, new_arg);
return PIKA_RES_OK;
}
PIKA_RES args_pushArg_name(Args* self, char* name, Arg* arg) {
return args_pushArg(self, arg_setName(arg, name));
}
PIKA_RES args_setBytes(Args* self, char* name, uint8_t* src, size_t size) {
Arg* argNew = arg_setBytes(NULL, name, src, size);
args_setArg(self, argNew);
return PIKA_RES_OK;
}
char* args_getBuff(Args* self, int32_t size) {
Arg* argNew = New_arg(NULL);
argNew = arg_newContent(size + 1);
args_pushArg(self, argNew);
return (char*)arg_getContent(argNew);
}
char* args_getStr(Args* self, char* name) {
if (NULL == self) {
return NULL;
}
Arg* arg = args_getArg(self, name);
if (NULL == arg) {
return NULL;
}
if (NULL == arg_getContent(arg)) {
return NULL;
}
return (char*)arg_getContent(arg);
}
uint8_t* args_getBytes(Args* self, char* name) {
if (NULL == self) {
return NULL;
}
Arg* arg = args_getArg(self, name);
if (NULL == arg) {
return NULL;
}
if (NULL == arg_getContent(arg)) {
return NULL;
}
return arg_getBytes(arg);
}
size_t args_getBytesSize(Args* self, char* name) {
if (NULL == self) {
return 0;
}
Arg* arg = args_getArg(self, name);
if (NULL == arg) {
return 0;
}
if (NULL == arg_getContent(arg)) {
return 0;
}
return arg_getBytesSize(arg);
}
PIKA_RES args_setInt(Args* self, char* name, int64_t val) {
Arg* arg = args_getArg(self, name);
if (NULL == arg || arg_getType(arg) != ARG_TYPE_INT) {
args_pushArg_name(self, name, arg_newInt(val));
return PIKA_RES_OK;
}
int64_t* val_ptr = (int64_t*)arg_getContent(arg);
*val_ptr = val;
return PIKA_RES_OK;
}
int64_t args_getInt(Args* self, char* name) {
Arg* arg = args_getArg(self, name);
if (NULL == arg) {
return -999999999;
}
ArgType arg_type = arg_getType(arg);
if (arg_type == ARG_TYPE_INT) {
return arg_getInt(arg);
} else if (arg_type == ARG_TYPE_FLOAT) {
return (int)arg_getFloat(arg);
}
return -999999999;
}
int32_t args_getSize(Args* self) {
return link_getSize(self);
}
ArgType args_getType(Args* self, char* name) {
Arg* arg = NULL;
arg = args_getArg(self, name);
if (NULL == arg) {
return ARG_TYPE_NONE;
}
return arg_getType(arg);
}
pika_float args_getFloat(Args* self, char* name) {
Arg* arg = args_getArg(self, name);
if (NULL == arg) {
return -999999999.0;
}
ArgType arg_type = arg_getType(arg);
if (arg_type == ARG_TYPE_FLOAT) {
return arg_getFloat(arg);
} else if (arg_type == ARG_TYPE_INT) {
return (pika_float)arg_getInt(arg);
}
return -999999999.0;
}
PIKA_RES args_copyArg(Args* self, Arg* argToBeCopy) {
if (NULL == argToBeCopy) {
return PIKA_RES_ERR_INVALID_PTR;
}
Arg* argCopied = arg_copy(argToBeCopy);
args_setArg(self, argCopied);
return PIKA_RES_OK;
}
PIKA_RES args_setStructWithSize(Args* self,
char* name,
void* struct_ptr,
uint32_t struct_size) {
Arg* struct_arg = arg_setStruct(NULL, name, struct_ptr, struct_size);
if (NULL == struct_arg) {
/* failed */
return PIKA_RES_ERR_ARG_NO_FOUND;
}
args_setArg(self, struct_arg);
return PIKA_RES_OK;
}
void* args_getStruct(Args* self, char* name) {
Arg* struct_arg = args_getArg(self, name);
if (NULL == struct_arg) {
return NULL;
}
return arg_getContent(struct_arg);
}
void* args_getHeapStruct(Args* self, char* name) {
Arg* struct_arg = args_getArg(self, name);
return arg_getHeapStruct(struct_arg);
}
PIKA_RES args_setHeapStructWithSize(Args* self,
char* name,
void* struct_ptr,
uint32_t struct_size,
void* struct_deinit_fun) {
Arg* struct_arg = arg_setHeapStruct(NULL, name, struct_ptr, struct_size,
struct_deinit_fun);
if (NULL == struct_arg) {
/* failed */
return PIKA_RES_ERR_ARG_NO_FOUND;
}
args_setArg(self, struct_arg);
return PIKA_RES_OK;
}
PIKA_RES args_copyArgByName(Args* self, char* name, Args* directArgs) {
Arg* argToBeCopy = args_getArg(self, name);
args_copyArg(directArgs, argToBeCopy);
return PIKA_RES_OK;
}
int32_t args_isArgExist_hash(Args* self, Hash nameHash) {
if (NULL != args_getArg_hash(self, nameHash)) {
return 1;
}
return 0;
}
int32_t args_isArgExist(Args* self, char* name) {
if (NULL != args_getArg(self, name)) {
return 1;
}
return 0;
}
PIKA_RES __updateArg(Args* self, Arg* argNew) {
LinkNode* nodeToUpdate = NULL;
LinkNode* nodeNow = self->firstNode;
LinkNode* priorNode = NULL;
PIKA_RES res;
if (NULL == self->firstNode) {
return PIKA_RES_ERR_ARG_NO_FOUND;
}
Hash nameHash = arg_getNameHash(argNew);
while (1) {
if (arg_getNameHash((Arg*)nodeNow) == nameHash) {
nodeToUpdate = nodeNow;
break;
}
if (arg_getNext((Arg*)nodeNow) == NULL) {
// error, node no found
return PIKA_RES_ERR_ARG_NO_FOUND;
}
priorNode = nodeNow;
nodeNow = (LinkNode*)arg_getNext((Arg*)nodeNow);
}
arg_deinitHeap((Arg*)nodeToUpdate);
nodeToUpdate = (LinkNode*)arg_setContent(
(Arg*)nodeToUpdate, arg_getContent(argNew), arg_getSize(argNew));
pika_assert(NULL != nodeToUpdate);
arg_setType((Arg*)nodeToUpdate, arg_getType(argNew));
// update privior link, because arg_getContent would free origin pointer
if (NULL == priorNode) {
self->firstNode = nodeToUpdate;
res = PIKA_RES_OK;
goto exit;
}
arg_setNext((Arg*)priorNode, (Arg*)nodeToUpdate);
res = PIKA_RES_OK;
goto exit;
exit:
if (!arg_isSerialized(argNew)) {
return res;
}
arg_freeContent(argNew);
return res;
}
PIKA_RES args_setArg(Args* self, Arg* arg) {
if (PIKA_RES_OK == __updateArg(self, arg)) {
return PIKA_RES_OK;
}
args_pushArg(self, arg);
return PIKA_RES_OK;
}
#ifndef __PIKA_CFG_HASH_LIST_CACHE_SIZE
#define __PIKA_CFG_HASH_LIST_CACHE_SIZE 4
#endif
#define __USE_PIKA_HASH_LIST_CACHE 0
LinkNode* args_getNode_hash(Args* self, Hash nameHash) {
LinkNode* node = self->firstNode;
#if __USE_PIKA_HASH_LIST_CACHE
int_fast8_t n = 0;
#endif
while (NULL != node) {
Arg* arg = (Arg*)node;
Hash thisNameHash = arg_getNameHash(arg);
#if __USE_PIKA_HASH_LIST_CACHE
n++;
#endif
if (thisNameHash == nameHash) {
#if __USE_PIKA_HASH_LIST_CACHE
if (n > __PIKA_CFG_HASH_LIST_CACHE_SIZE) {
/* the first __PIKA_CFG_HASH_LIST_CACHE_SIZE items in the list
* is considered as a cache.
* Don't make __PIKA_CFG_HASH_LIST_CACHE_SIZE too big, otherwise
* this optimisation is useless.
*/
/*! remove current node from the list */
node = (LinkNode*)arg_getNext((Arg*)arg);
/*! move the node to the cache */
arg_setNext(arg, (Arg*)(self->firstNode));
self->firstNode = (LinkNode*)arg;
}
#endif
return (LinkNode*)arg;
}
node = (LinkNode*)arg_getNext((Arg*)node);
}
return NULL;
}
LinkNode* args_getNode(Args* self, char* name) {
return args_getNode_hash(self, hash_time33(name));
}
Arg* args_getArg_hash(Args* self, Hash nameHash) {
LinkNode* node = args_getNode_hash(self, nameHash);
if (NULL == node) {
return NULL;
}
return (Arg*)node;
}
Arg* args_getArg(Args* self, char* name) {
pika_assert(NULL != self);
LinkNode* node = args_getNode(self, name);
return (Arg*)node;
}
Arg* args_getArgByIndex(Args* self, int index) {
pika_assert(NULL != self);
LinkNode* nodeNow = self->firstNode;
if (NULL == nodeNow) {
return NULL;
}
for (int i = 0; i < index; i++) {
nodeNow = (LinkNode*)arg_getNext((Arg*)nodeNow);
}
return (Arg*)nodeNow;
}
PIKA_RES args_foreach(Args* self,
int32_t (*eachHandle)(Arg* argEach, Args* context),
Args* context) {
if (NULL == self->firstNode) {
return PIKA_RES_OK;
}
LinkNode* nodeNow = self->firstNode;
while (1) {
Arg* argNow = (Arg*)nodeNow;
if (NULL == argNow) {
continue;
}
LinkNode* nextNode = (LinkNode*)arg_getNext((Arg*)nodeNow);
eachHandle(argNow, context);
if (NULL == nextNode) {
break;
}
nodeNow = nextNode;
}
return PIKA_RES_OK;
}
PIKA_RES args_removeArg(Args* self, Arg* argNow) {
if (NULL == argNow) {
return PIKA_RES_ERR_INVALID_PTR;
}
link_removeNode(self, argNow);
return PIKA_RES_OK;
}
PIKA_RES args_removeArg_notDeinitArg(Args* self, Arg* argNow) {
if (NULL == argNow) {
return PIKA_RES_ERR_INVALID_PTR;
}
link_removeNode_notDeinitNode(self, argNow);
return PIKA_RES_OK;
}
PIKA_RES args_moveArg(Args* self, Args* dict, Arg* argNow) {
if (NULL == argNow) {
return PIKA_RES_ERR_INVALID_PTR;
}
link_removeNode_notDeinitNode(self, argNow);
args_pushArg(dict, argNow);
return PIKA_RES_OK;
}
Args* New_args(Args* args) {
Args* self = New_link(NULL);
return self;
}
PikaDict* New_pikaDict(void) {
PikaDict* self = (PikaDict*)New_args(NULL);
return self;
}
PikaList* New_pikaList(void) {
PikaList* self = (PikaList*)New_args(NULL);
/* set top index for append */
args_pushArg_name(&self->super, "top", arg_newInt(0));
return self;
}
PIKA_RES pikaList_setArg(PikaList* self, int index, Arg* arg) {
char buff[11];
char* i_str = fast_itoa(buff, index);
int top = args_getInt(&self->super, "top");
if (index > top) {
return PIKA_RES_ERR_OUT_OF_RANGE;
}
Arg* new_arg = arg_copy(arg);
new_arg = arg_setName(new_arg, i_str);
args_setArg(&self->super, new_arg);
return PIKA_RES_OK;
}
Arg* pikaList_getArg(PikaList* self, int index) {
pika_assert(NULL != self);
char buff[11];
char* i_str = fast_itoa(buff, index);
return args_getArg(&self->super, i_str);
}
int pikaList_getInt(PikaList* self, int index) {
Arg* arg = pikaList_getArg(self, index);
return arg_getInt(arg);
}
pika_float pikaList_getFloat(PikaList* self, int index) {
Arg* arg = pikaList_getArg(self, index);
return arg_getFloat(arg);
}
char* pikaList_getStr(PikaList* self, int index) {
Arg* arg = pikaList_getArg(self, index);
return arg_getStr(arg);
}
void* pikaList_getPtr(PikaList* self, int index) {
Arg* arg = pikaList_getArg(self, index);
return arg_getPtr(arg);
}
PIKA_RES pikaList_append(PikaList* self, Arg* arg) {
if (NULL == arg) {
return PIKA_RES_ERR_ARG_NO_FOUND;
}
int top = args_getInt(&self->super, "top");
char buff[11];
char* topStr = fast_itoa(buff, top);
Arg* arg_to_push = arg_copy(arg);
arg_setName(arg_to_push, topStr);
args_setArg(&self->super, arg_to_push);
/* top++ */
return args_setInt(&self->super, "top", top + 1);
}
Arg* pikaList_pop(PikaList* list) {
int top = args_getInt(&list->super, "top");
if (top <= 0) {
return NULL;
}
Arg* arg = pikaList_getArg(list, top - 1);
Arg* res = arg_copy(arg);
args_removeArg(&list->super, arg);
args_setInt(&list->super, "top", top - 1);
return res;
}
PIKA_RES pikaList_remove(PikaList* list, Arg* arg) {
int top = args_getInt(&list->super, "top");
int i_remove = 0;
if (top <= 0) {
return PIKA_RES_ERR_OUT_OF_RANGE;
}
for (int i = 0; i < top; i++) {
Arg* arg_now = pikaList_getArg(list, i);
if (arg_isEqual(arg_now, arg)) {
i_remove = i;
args_removeArg(&list->super, arg_now);
break;
}
}
/* move args */
for (int i = i_remove + 1; i < top; i++) {
char buff[11];
char* i_str = fast_itoa(buff, i - 1);
Arg* arg_now = pikaList_getArg(list, i);
arg_setName(arg_now, i_str);
}
args_setInt(&list->super, "top", top - 1);
return PIKA_RES_OK;
}
PIKA_RES pikaList_insert(PikaList* self, int index, Arg* arg) {
int top = args_getInt(&self->super, "top");
if (index > top) {
return PIKA_RES_ERR_OUT_OF_RANGE;
}
/* move args */
for (int i = top - 1; i >= index; i--) {
char buff[11];
char* i_str = fast_itoa(buff, i + 1);
Arg* arg_now = pikaList_getArg(self, i);
arg_setName(arg_now, i_str);
}
char buff[11];
char* i_str = fast_itoa(buff, index);
Arg* arg_to_push = arg_copy(arg);
arg_setName(arg_to_push, i_str);
args_setArg(&self->super, arg_to_push);
args_setInt(&self->super, "top", top + 1);
return PIKA_RES_OK;
}
size_t pikaList_getSize(PikaList* self) {
pika_assert(NULL != self);
return args_getInt(&self->super, "top");
}
void pikaList_reverse(PikaList* self) {
pika_assert(NULL != self);
int top = pikaList_getSize(self);
for (int i = 0; i < top / 2; i++) {
Arg* arg_i = arg_copy(pikaList_getArg(self, i));
Arg* arg_top = arg_copy(pikaList_getArg(self, top - i - 1));
pikaList_setArg(self, i, arg_top);
pikaList_setArg(self, top - i - 1, arg_i);
arg_deinit(arg_i);
arg_deinit(arg_top);
}
}
PikaTuple* New_pikaTuple(void) {
PikaTuple* self = (PikaTuple*)New_pikaList();
return self;
}
char* strsFormatArg(Args* out_buffs, char* fmt, Arg* arg) {
Args buffs = {0};
char* res = NULL;
ArgType type = arg_getType(arg);
const char* syms[] = {"%s", "%r"};
for (size_t i = 0; i < sizeof(syms) / sizeof(char*); i++) {
char* sym = (char*)syms[i];
if (strstr(fmt, sym)) {
if (type == ARG_TYPE_STRING) {
fmt = strsReplace(&buffs, fmt, sym, "%s");
break;
}
if (type == ARG_TYPE_INT) {
fmt = strsReplace(&buffs, fmt, sym, "%d");
break;
}
if (type == ARG_TYPE_FLOAT) {
fmt = strsReplace(&buffs, fmt, sym, "%f");
break;
}
if (type == ARG_TYPE_POINTER) {
fmt = strsReplace(&buffs, fmt, sym, "%p");
break;
}
}
}
if (ARG_TYPE_INT == type) {
int val = arg_getInt(arg);
res = strsFormat(&buffs, PIKA_SPRINTF_BUFF_SIZE, fmt, val);
goto exit;
}
if (ARG_TYPE_FLOAT == type) {
pika_float val = arg_getFloat(arg);
res = strsFormat(&buffs, PIKA_SPRINTF_BUFF_SIZE, fmt, val);
goto exit;
}
if (ARG_TYPE_STRING == type) {
char* val = arg_getStr(arg);
res = strsFormat(&buffs, PIKA_SPRINTF_BUFF_SIZE, fmt, val);
goto exit;
}
if (ARG_TYPE_NONE == type) {
res = strsFormat(&buffs, PIKA_SPRINTF_BUFF_SIZE, fmt, "None");
goto exit;
}
exit:
if (NULL != res) {
res = strsCopy(out_buffs, res);
}
strsDeinit(&buffs);
return res;
}
char* strsFormatList(Args* out_buffs, char* fmt, PikaList* list) {
Args buffs = {0};
char* res = NULL;
char* fmt_buff = strsCopy(&buffs, fmt);
char* fmt_item = strsPopToken(&buffs, &fmt_buff, '%');
Arg* res_buff = arg_newStr(fmt_item);
for (size_t i = 0; i < pikaList_getSize(list); i++) {
Args buffs_item = {0};
Arg* arg = pikaList_getArg(list, i);
char* fmt_item = strsPopToken(&buffs_item, &fmt_buff, '%');
fmt_item = strsAppend(&buffs_item, "%", fmt_item);
char* str_format = strsFormatArg(&buffs_item, fmt_item, arg);
if (NULL == str_format) {
strsDeinit(&buffs_item);
goto exit;
}
res_buff = arg_strAppend(res_buff, str_format);
strsDeinit(&buffs_item);
}
goto exit;
exit:
res = strsCopy(out_buffs, arg_getStr(res_buff));
strsDeinit(&buffs);
arg_deinit(res_buff);
return res;
}
/* tuple */
PikaTuple* args_getTuple(Args* self, char* name) {
if (NULL == self) {
return NULL;
}
PikaObj* tuple_obj = args_getPtr(self, name);
return obj_getPtr(tuple_obj, "list");
}
/* dict */
PikaDict* args_getDict(Args* self, char* name) {
if (NULL == self) {
return NULL;
}
PikaObj* tuple_obj = args_getPtr(self, name);
return obj_getPtr(tuple_obj, "dict");
}
char* args_cacheStr(Args* self, char* str) {
args_setStr(self, "@sc", str);
return args_getStr(self, "@sc");
}

View File

@ -0,0 +1,277 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef _dataArgs__H
#define _dataArgs__H
#include "dataArg.h"
#include "dataLink.h"
#include "dataMemory.h"
#include "dataString.h"
typedef Link Args;
/* operation */
void args_deinit(Args* self);
void args_deinit_stack(Args* self);
void args_init(Args* self, Args* args);
int32_t args_getSize(Args* self);
LinkNode* args_getNode(Args* self, char* name);
Arg* args_getArgByIndex(Args* self, int index);
Arg* args_getArg(Args* self, char* name);
PIKA_RES args_removeArg(Args* self, Arg* argNow);
PIKA_RES args_moveArg(Args* self, Args* dict, Arg* arg);
Arg* args_getArg_hash(Args* self, Hash nameHash);
PIKA_RES args_setArg(Args* self, Arg* arg);
PIKA_RES args_copyArgByName(Args* self, char* name, Args* directList);
PIKA_RES args_copyArg(Args* self, Arg* argToBeCopy);
ArgType args_getType(Args* self, char* name);
int32_t args_isArgExist_hash(Args* self, Hash nameHash);
int32_t args_isArgExist(Args* self, char* name);
PIKA_RES args_setStr(Args* self, char* name, char* strIn);
PIKA_RES args_setNone(Args* self, char* name);
PIKA_RES args_setStrWithDefaultName(Args* self, char* strIn);
char* args_getStr(Args* self, char* name);
PIKA_RES args_setFloatWithDefaultName(Args* self, pika_float argFloat);
PIKA_RES args_setFloat(Args* self, char* name, pika_float argFloat);
pika_float args_getFloat(Args* self, char* name);
PIKA_RES args_setRef(Args* self, char* name, void* argPointer);
PIKA_RES args_setPtr(Args* self, char* name, void* argPointer);
void* args_getPtr(Args* self, char* name);
PIKA_RES args_setInt(Args* self, char* name, int64_t int64In);
int64_t args_getInt(Args* self, char* name);
char* args_print(Args* self, char* name);
PIKA_RES args_setStructWithSize(Args* self,
char* name,
void* struct_ptr,
uint32_t struct_size);
PIKA_RES args_setHeapStructWithSize(Args* self,
char* name,
void* struct_ptr,
uint32_t struct_size,
void* struct_deinit_fun);
#define args_setStruct(Args_p_self, char_p_name, struct_) \
args_setStructWithSize((Args_p_self), (char_p_name), &(struct_), \
sizeof(struct_))
#define args_setHeapStruct(Args_p_self, char_p_name, struct_, \
struct_deinit_fun) \
args_setHeapStructWithSize((Args_p_self), (char_p_name), &(struct_), \
sizeof(struct_), (void*)struct_deinit_fun)
void* args_getStruct(Args* self, char* name);
PIKA_RES args_set(Args* self, char* name, char* valueStr);
PIKA_RES args_setObjectWithClass(Args* self,
char* objectName,
char* className,
void* objectPtr);
PIKA_RES args_setPtrWithType(Args* self,
char* name,
ArgType type,
void* objPtr);
PIKA_RES args_foreach(Args* self,
int32_t (*eachHandle)(Arg* argEach, Args* context),
Args* context);
char* args_getBuff(Args* self, int32_t size);
PIKA_RES args_pushArg(Args* self, Arg* arg);
PIKA_RES args_pushArg_name(Args* self, char* name, Arg* arg);
void* args_getHeapStruct(Args* self, char* name);
PIKA_RES args_removeArg_notDeinitArg(Args* self, Arg* argNow);
uint8_t* args_getBytes(Args* self, char* name);
PIKA_RES args_setBytes(Args* self, char* name, uint8_t* src, size_t size);
size_t args_getBytesSize(Args* self, char* name);
Args* New_args(Args* args);
typedef struct PikaList PikaList;
struct PikaList {
Args super;
};
typedef struct PikaTuple PikaTuple;
struct PikaTuple {
PikaList super;
};
typedef struct PikaDict PikaDict;
struct PikaDict {
Args super;
};
/* dict api */
PikaDict* New_pikaDict(void);
static inline PIKA_RES pikaDict_setInt(PikaDict* self,
char* name,
int64_t val) {
return args_setInt((&((self)->super)), (name), (val));
}
static inline PIKA_RES pikaDict_setFloat(PikaDict* self,
char* name,
pika_float val) {
return args_setFloat((&((self)->super)), (name), (val));
}
static inline PIKA_RES pikaDict_setStr(PikaDict* self, char* name, char* val) {
return args_setStr((&((self)->super)), (name), (val));
}
static inline PIKA_RES pikaDict_setPtr(PikaDict* self, char* name, void* val) {
return args_setPtr((&((self)->super)), (name), (val));
}
static inline PIKA_RES pikaDict_setArg(PikaDict* self, Arg* val) {
return args_setArg((&((self)->super)), (val));
}
static inline PIKA_RES pikaDict_removeArg(PikaDict* self, Arg* val) {
return args_removeArg((&((self)->super)), (val));
}
static inline PIKA_RES pikaDict_setBytes(PikaDict* self,
char* name,
uint8_t* val,
size_t size) {
return args_setBytes((&((self)->super)), (name), (val), (size));
}
static inline int64_t pikaDict_getInt(PikaDict* self, char* name) {
return args_getInt((&((self)->super)), (name));
}
static inline pika_float pikaDict_getFloat(PikaDict* self, char* name) {
return args_getFloat((&((self)->super)), (name));
}
static inline char* pikaDict_getStr(PikaDict* self, char* name) {
return args_getStr((&((self)->super)), (name));
}
static inline void* pikaDict_getPtr(PikaDict* self, char* name) {
return args_getPtr((&((self)->super)), (name));
}
static inline Arg* pikaDict_getArg(PikaDict* self, char* name) {
return args_getArg((&((self)->super)), (name));
}
static inline int32_t pikaDict_isArgExist(PikaDict* self, char* name) {
return args_isArgExist((&((self)->super)), (name));
}
static inline uint8_t* pikaDict_getBytes(PikaDict* self, char* name) {
return args_getBytes((&((self)->super)), (name));
}
static inline ArgType pikaDict_getType(PikaDict* self, char* name) {
return args_getType((&((self)->super)), (name));
}
static inline size_t pikaDict_getBytesSize(PikaDict* self, char* name) {
return args_getBytesSize((&((self)->super)), (name));
}
static inline void pikaDict_deinit(PikaDict* self) {
args_deinit((&((self)->super)));
}
/* list api */
PIKA_RES pikaList_append(PikaList* self, Arg* arg);
PIKA_RES pikaList_setArg(PikaList* self, int index, Arg* arg);
int pikaList_getInt(PikaList* self, int index);
pika_float pikaList_getFloat(PikaList* self, int index);
char* pikaList_getStr(PikaList* self, int index);
void* pikaList_getPtr(PikaList* self, int index);
Arg* pikaList_getArg(PikaList* self, int index);
size_t pikaList_getSize(PikaList* self);
void pikaList_reverse(PikaList* self);
PIKA_RES pikaList_insert(PikaList* self, int index, Arg* arg);
Arg* pikaList_pop(PikaList* list);
PIKA_RES pikaList_remove(PikaList* list, Arg* arg);
static inline void pikaList_deinit(PikaList* self) {
args_deinit((&((self)->super)));
}
static inline ArgType pikaList_getType(PikaList* self, int index) {
Arg* arg = pikaList_getArg(self, index);
return arg_getType(arg);
}
/* tuple api */
static inline void pikaTuple_deinit(PikaTuple* self) {
pikaList_deinit((&((self)->super)));
}
static inline Arg* pikaTuple_getArg(PikaTuple* self, int index) {
return pikaList_getArg((&((self)->super)), (index));
}
static inline size_t pikaTuple_getSize(PikaTuple* self) {
return pikaList_getSize((&((self)->super)));
}
static inline int64_t pikaTuple_getInt(PikaTuple* self, int index) {
return pikaList_getInt((&((self)->super)), (index));
}
static inline pika_float pikaTuple_getFloat(PikaTuple* self, int index) {
return pikaList_getFloat((&((self)->super)), (index));
}
static inline char* pikaTuple_getStr(PikaTuple* self, int index) {
return pikaList_getStr((&((self)->super)), (index));
}
static inline void* pikaTuple_getPtr(PikaTuple* self, int index) {
return pikaList_getPtr((&((self)->super)), (index));
}
static inline ArgType pikaTuple_getType(PikaTuple* self, int index) {
return pikaList_getType((&((self)->super)), (index));
}
PikaList* New_pikaList(void);
PikaTuple* New_pikaTuple(void);
PikaTuple* args_getTuple(Args* self, char* name);
PikaDict* args_getDict(Args* self, char* name);
char* strsFormatList(Args* out_buffs, char* fmt, PikaList* list);
char* args_cacheStr(Args* self, char* str);
char* strsFormatArg(Args* out_buffs, char* fmt, Arg* arg);
#endif

View File

@ -0,0 +1,128 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "dataLink.h"
#include "dataArg.h"
#include "dataLinkNode.h"
#include "dataMemory.h"
void __link_deinit_pyload(Link* self) {
LinkNode* nowNode = self->firstNode;
while (NULL != nowNode) {
LinkNode* nodeNext = (LinkNode*)arg_getNext((Arg*)nowNode);
linkNode_deinit(nowNode);
nowNode = nodeNext;
}
self = NULL;
}
void link_deinit(Link* self) {
pika_assert(self != NULL);
__link_deinit_pyload(self);
pikaFree(self, sizeof(Link));
}
void link_deinit_stack(Link* self) {
__link_deinit_pyload(self);
}
void link_addNode(Link* self, void* content) {
// old first node become new second node
LinkNode* secondNode = self->firstNode;
self->firstNode = content;
// change the first node to new node
arg_setNext((Arg*)content, (Arg*)secondNode);
}
static void __link_removeNode(Link* self,
void* content,
uint8_t is_deinit_node) {
LinkNode* nodeToDelete = NULL;
LinkNode* nodeNow = self->firstNode;
LinkNode* priorNode = NULL;
LinkNode* nextNode;
while (1) {
if (nodeNow == content) {
nodeToDelete = nodeNow;
break;
}
if (nodeNow == NULL) {
// error, node no found
goto exit;
}
priorNode = nodeNow;
nodeNow = (LinkNode*)arg_getNext((Arg*)nodeNow);
}
nextNode = (LinkNode*)arg_getNext((Arg*)nodeToDelete);
if (nodeToDelete == self->firstNode) {
self->firstNode = (LinkNode*)arg_getNext((Arg*)nodeToDelete);
}
if (NULL == priorNode) {
self->firstNode = nextNode;
goto exit;
}
arg_setNext((Arg*)priorNode, (Arg*)nextNode);
goto exit;
// deinit the node
exit:
if (is_deinit_node) {
linkNode_deinit(nodeToDelete);
}
return;
}
void link_removeNode(Link* self, void* content) {
__link_removeNode(self, content, 1);
}
void link_removeNode_notDeinitNode(Link* self, void* content) {
__link_removeNode(self, content, 0);
}
int32_t link_getSize(Link* self) {
LinkNode* NowNode;
int32_t size = 0;
NowNode = self->firstNode;
while (NULL != NowNode) {
size++;
NowNode = (LinkNode*)arg_getNext((Arg*)NowNode);
}
return size;
}
void link_init(Link* self, void* args) {
self->firstNode = NULL;
}
Link* New_link(void* args) {
Link* self = pikaMalloc(sizeof(Link));
link_init(self, args);
return self;
}

View File

@ -0,0 +1,52 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef _link2__H
#define _link2__H
#include "dataLinkNode.h"
#include "dataMemory.h"
enum LINK_IS_DEINIT_SELF {
LINK_IS_DEINIT_SELF_ENABLE,
LINK_IS_DEINIT_SELF_DISABLE,
};
typedef struct Link Link;
struct Link{
LinkNode* firstNode;
};
void link_deinit(Link* self);
void link_deinit_stack(Link* self);
void link_init(Link* self, void* args);
void link_addNode(Link* self, void* content);
void link_removeNode(Link* self, void* content);
void link_removeNode_notDeinitNode(Link* self, void* content);
LinkNode* link_getNode(Link* self, int64_t id);
int32_t link_getSize(Link* self);
Link* New_link(void* args);
#endif

View File

@ -0,0 +1,34 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "dataLinkNode.h"
#include "dataArg.h"
#include "dataMemory.h"
void linkNode_deinit(LinkNode* self) {
arg_deinit((Arg*)self);
}

View File

@ -0,0 +1,42 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef _linkNode__H
#define _linkNode__H
#include "dataMemory.h"
typedef struct LinkNode LinkNode;
struct LinkNode {
void* __rsvd;
};
void linkNode_deinit(LinkNode* self);
void linkNode_init(LinkNode* self, void* args);
LinkNode* New_linkNode(void* args);
#endif

View File

@ -0,0 +1,322 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#define __DATA_MEMORY_CLASS_IMPLEMENT__
#include "dataMemory.h"
#include "PikaPlatform.h"
volatile PikaMemInfo pikaMemInfo = {0};
void* pikaMalloc(uint32_t size) {
/* pika memory lock */
if (0 != pika_is_locked_pikaMemory()) {
pika_platform_wait();
}
//! if you unsure about the __impl_pikaMalloc, uncomment this to force alignment
#if PIKA_ARG_ALIGN_ENABLE
/* force alignment to avoid unaligned access */
size = mem_align(size);
#endif
pikaMemInfo.heapUsed += size;
if (pikaMemInfo.heapUsedMax < pikaMemInfo.heapUsed) {
pikaMemInfo.heapUsedMax = pikaMemInfo.heapUsed;
}
pika_platform_disable_irq_handle();
void* mem = pika_user_malloc(size);
pika_platform_enable_irq_handle();
if (NULL == mem) {
pika_platform_printf("Error: No heap space! Please reset the device.\r\n");
while (1) {
}
}
return mem;
}
void pikaFree(void* mem, uint32_t size) {
if (0 != pika_is_locked_pikaMemory()) {
pika_platform_wait();
}
//! if you unsure about the __impl_pikaMalloc, uncomment this to force alignment
#if PIKA_ARG_ALIGN_ENABLE
/* force alignment to avoid unaligned access */
size = mem_align(size);
#endif
pika_platform_disable_irq_handle();
pika_user_free(mem, size);
pika_platform_enable_irq_handle();
pikaMemInfo.heapUsed -= size;
}
uint32_t pikaMemNow(void) {
return pikaMemInfo.heapUsed;
// return 0;
}
uint32_t pikaMemMax(void) {
return pikaMemInfo.heapUsedMax;
}
void pikaMemMaxReset(void) {
pikaMemInfo.heapUsedMax = 0;
}
uint32_t pool_getBlockIndex_byMemSize(Pool* pool, uint32_t size) {
if (0 == size) {
return 0;
}
return (size - 1) / pool->aline + 1;
}
uint32_t pool_aline(Pool* pool, uint32_t size) {
return pool_getBlockIndex_byMemSize(pool, size) * pool->aline;
}
Pool pool_init(uint32_t size, uint8_t aline) {
Pool pool;
pool.aline = aline;
uint32_t block_size = pool_getBlockIndex_byMemSize(&pool, size);
pool.size = pool_aline(&pool, size);
pool.bitmap = bitmap_init(block_size);
pool.mem = pika_platform_malloc(pool_aline(&pool, pool.size));
pool.first_free_block = 0;
pool.purl_free_block_start = 0;
pool.inited = PIKA_TRUE;
return pool;
}
void pool_deinit(Pool* pool) {
pika_platform_free(pool->mem);
pool->mem = NULL;
bitmap_deinit(pool->bitmap);
}
void* pool_getBytes_byBlockIndex(Pool* pool, uint32_t block_index) {
return pool->mem + block_index * pool->aline;
}
uint32_t pool_getBlockIndex_byMem(Pool* pool, void* mem) {
uint32_t mem_size = (uintptr_t)mem - (uintptr_t)pool->mem;
return pool_getBlockIndex_byMemSize(pool, mem_size);
}
void pool_printBlocks(Pool* pool, uint32_t size_min, uint32_t size_max) {
uint32_t block_index_min = pool_getBlockIndex_byMemSize(pool, size_min);
uint32_t block_index_max = pool_getBlockIndex_byMemSize(pool, size_max);
pika_platform_printf("[bitmap]\r\n");
uint8_t is_end = 0;
for (uint32_t i = block_index_min; i < block_index_max; i += 16) {
if (is_end) {
break;
}
pika_platform_printf("0x%x\t: 0x%d", i * pool->aline,
(i + 15) * pool->aline);
for (uint32_t j = i; j < i + 16; j += 4) {
if (is_end) {
break;
}
for (uint32_t k = j; k < j + 4; k++) {
if (k >= block_index_max) {
is_end = 1;
break;
}
pika_platform_printf("%d", bitmap_get(pool->bitmap, k));
}
pika_platform_printf(" ");
}
pika_platform_printf("\r\n");
}
}
void* pool_malloc(Pool* pool, uint32_t size) {
uint32_t block_index_max = pool_getBlockIndex_byMemSize(pool, pool->size);
uint32_t block_num_need = pool_getBlockIndex_byMemSize(pool, size);
uint32_t block_num_found = 0;
uint8_t found_first_free = 0;
uint32_t block_index;
/* high speed malloc */
block_index = pool->purl_free_block_start + block_num_need - 1;
if (block_index < block_index_max) {
goto found;
}
/* low speed malloc */
for (block_index = pool->first_free_block;
block_index < pool->purl_free_block_start; block_index++) {
/* 8 bit is not free */
uint8_t bitmap_byte = bitmap_getByte(pool->bitmap, block_index);
if (0xFF == bitmap_byte) {
block_index = 8 * (block_index / 8) + 7;
block_num_found = 0;
continue;
}
/* found a free block */
if (0 == bitmap_get(pool->bitmap, block_index)) {
/* save the first free */
if (!found_first_free) {
pool->first_free_block = block_index;
found_first_free = 1;
}
block_num_found++;
} else {
/* a used block appeared, find again */
block_num_found = 0;
}
/* found all request blocks */
if (block_num_found >= block_num_need) {
goto found;
}
}
/* malloc for purl free blocks */
block_index = pool->purl_free_block_start + block_num_need - 1;
if (block_index < block_index_max) {
goto found;
}
/* no found */
return NULL;
found:
/* set 1 for found blocks */
for (uint32_t i = 0; i < block_num_need; i++) {
bitmap_set(pool->bitmap, block_index - i, 1);
}
/* save last used block */
if (block_index >= pool->purl_free_block_start) {
pool->purl_free_block_start = block_index + 1;
}
/* return mem by block index */
return pool_getBytes_byBlockIndex(pool, block_index - block_num_need + 1);
}
void pool_free(Pool* pool, void* mem, uint32_t size) {
uint32_t block_num = pool_getBlockIndex_byMemSize(pool, size);
uint32_t block_index = pool_getBlockIndex_byMem(pool, mem);
for (uint32_t i = 0; i < block_num; i++) {
bitmap_set(pool->bitmap, block_index + i, 0);
}
/* save min free block index to add speed */
if (block_index < pool->first_free_block) {
pool->first_free_block = block_index;
}
/* save last free block index to add speed */
uint32_t block_end = block_index + block_num - 1;
if (block_end == pool->purl_free_block_start - 1) {
uint32_t first_pure_free_block = block_index;
/* back to first used block */
if (0 != first_pure_free_block) {
while (0 == bitmap_get(pool->bitmap, first_pure_free_block - 1)) {
first_pure_free_block--;
if (0 == first_pure_free_block) {
break;
}
}
}
pool->purl_free_block_start = first_pure_free_block;
}
return;
}
BitMap bitmap_init(uint32_t size) {
BitMap mem_bit_map =
(BitMap)pika_platform_malloc(((size - 1) / 8 + 1) * sizeof(char));
if (mem_bit_map == NULL) {
return NULL;
}
uint32_t size_mem_bit_map = (size - 1) / 8 + 1;
pika_platform_memset(mem_bit_map, 0x0, size_mem_bit_map);
return mem_bit_map;
}
void bitmap_set(BitMap bitmap, uint32_t index, uint8_t bit) {
uint32_t index_byte = index / 8;
uint8_t index_bit = index % 8;
uint8_t x = (0x1 << index_bit);
/* set 1 */
if (bit) {
bitmap[index_byte] |= x;
return;
}
/* set 0 */
bitmap[index_byte] &= ~x;
return;
}
uint8_t bitmap_getByte(BitMap bitmap, uint32_t index) {
uint32_t index_byte = (index) / 8;
uint8_t byte;
byte = bitmap[index_byte];
return byte;
}
uint8_t bitmap_get(BitMap bitmap, uint32_t index) {
uint32_t index_byte = (index) / 8;
uint8_t index_bit = (index) % 8;
uint8_t x = (0x1 << index_bit);
uint8_t bit;
bit = bitmap[index_byte] & x;
return bit > 0 ? 1 : 0;
}
void bitmap_deinit(BitMap bitmap) {
pika_platform_free(bitmap);
}
#if PIKA_POOL_ENABLE
Pool pikaPool = {0};
void* pika_user_malloc(size_t size) {
return pool_malloc(&pikaPool, size);
}
void pika_user_free(void* ptrm, size_t size) {
pool_free(&pikaPool, ptrm, size);
}
#endif
void mem_pool_init(void) {
#if PIKA_POOL_ENABLE
if (!pikaPool.inited) {
pikaPool = pool_init(PIKA_POOL_SIZE, PIKA_POOL_ALIGN);
}
#endif
}
void _mem_cache_deinit(void) {
#if PIKA_ARG_CACHE_ENABLE
while (pikaMemInfo.cache_pool_top) {
pika_user_free(pikaMemInfo.cache_pool[pikaMemInfo.cache_pool_top - 1], 0);
pikaMemInfo.cache_pool_top--;
}
#endif
}
void mem_pool_deinit(void) {
_mem_cache_deinit();
#if PIKA_POOL_ENABLE
pool_deinit(&pikaPool);
#endif
}

View File

@ -0,0 +1,90 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef __MEMORY_H__
#define __MEMORY_H__
#include "PikaPlatform.h"
#include "PikaVersion.h"
/*! \NOTE: Make sure #include "plooc_class.h" is close to the class definition
*/
#if defined(__DATA_MEMORY_CLASS_IMPLEMENT__)
#define __PLOOC_CLASS_IMPLEMENT__
#endif
#include "__pika_ooc.h"
typedef struct {
uint32_t heapUsed;
uint32_t heapUsedMax;
#if PIKA_ARG_CACHE_ENABLE
uint8_t* cache_pool[PIKA_ARG_CACHE_POOL_SIZE];
uint32_t cache_pool_top;
#endif
uint32_t alloc_times;
uint32_t alloc_times_cache;
} PikaMemInfo;
typedef uint8_t* BitMap;
/* clang-format off */
typedef struct Pool Pool;
struct Pool{
private_member(
BitMap bitmap;
uint8_t* mem;
uint8_t aline;
uint32_t size;
uint32_t first_free_block;
uint32_t purl_free_block_start;
PIKA_BOOL inited;
)
};
/* clang-format on */
#define aline_by(size, aline) \
(((size) == 0) ? 0 : (((size)-1) / (aline) + 1) * (aline))
void pikaFree(void* mem, uint32_t size);
void* pikaMalloc(uint32_t size);
uint32_t pikaMemNow(void);
uint32_t pikaMemMax(void);
void pikaMemMaxReset(void);
BitMap bitmap_init(uint32_t size);
void bitmap_set(BitMap bitmap, uint32_t index, uint8_t bit);
uint8_t bitmap_get(BitMap bitmap, uint32_t index);
uint8_t bitmap_getByte(BitMap bitmap, uint32_t index);
void bitmap_deinit(BitMap bitmap);
void mem_pool_deinit(void);
void mem_pool_init(void);
#define mem_align(_size) ((((_size) + 4 - 1) & ~(4 - 1)))
#undef __DATA_MEMORY_CLASS_IMPLEMENT__
#endif

View File

@ -0,0 +1,96 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "dataQueue.h"
#include "PikaPlatform.h"
#include "dataArgs.h"
void queue_init(Queue* queue) {
args_setInt(queue, "__t", 0);
args_setInt(queue, "__b", 0);
}
Queue* New_queue(void) {
Args* args = New_args(NULL);
queue_init(args);
return (Queue*)args;
}
int32_t queue_deinit(Queue* queue) {
Args* args = queue;
args_deinit(args);
return 0;
}
int32_t queue_pushArg(Queue* queue, Arg* arg) {
Args* args = queue;
uint64_t top = args_getInt(args, "__t");
/* add top */
args_setInt(args, "__t", top + 1);
char buff[11];
arg = arg_setName(arg, fast_itoa(buff, top));
return args_setArg(args, arg);
}
Arg* __queue_popArg_noRmoveArg(Queue* queue) {
Args* args = queue;
uint64_t top = args_getInt(args, "__t");
uint64_t bottom = args_getInt(args, "__b");
if (top - bottom < 1) {
return NULL;
}
/* add bottom */
args_setInt(args, "__b", bottom + 1);
char buff[11];
Arg* res = args_getArg(args, fast_itoa(buff, bottom));
/* not deinit arg to keep str buff */
return res;
}
int32_t queue_pushInt(Queue* queue, int val) {
return queue_pushArg(queue, arg_newInt(val));
}
int64_t queue_popInt(Queue* queue) {
return arg_getInt(__queue_popArg_noRmoveArg(queue));
}
int32_t queue_pushFloat(Queue* queue, pika_float val) {
return queue_pushArg(queue, arg_newFloat(val));
}
pika_float queue_popFloat(Queue* queue) {
return arg_getFloat(__queue_popArg_noRmoveArg(queue));
}
int32_t queue_pushStr(Queue* queue, char* str) {
return queue_pushArg(queue, arg_newStr(str));
}
char* queue_popStr(Queue* queue) {
return arg_getStr(__queue_popArg_noRmoveArg(queue));
}

View File

@ -0,0 +1,49 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef __DATA_QUEUE__H
#define __DATA_QUEUE__H
#include "dataArgs.h"
typedef Args Queue;
Queue* New_queue(void);
int32_t queue_deinit(Queue* queue);
int32_t queue_pushInt(Queue* queue, int val);
int32_t queue_pushFloat(Queue* queue, pika_float val);
int32_t queue_pushStr(Queue* queue, char* str);
int32_t queue_pushArg(Queue* queue, Arg* arg);
char* fast_itoa(char* buf, uint32_t val);
int64_t queue_popInt(Queue* queue);
pika_float queue_popFloat(Queue* queue);
char* queue_popStr(Queue* queue);
Arg* queue_popArg(Queue* queue);
Arg* queue_popArg_notDeinitArg(Queue* queue);
int32_t queue_deinit_stack(Queue* queue);
void queue_init(Queue* queue);
#endif

View File

@ -0,0 +1,125 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "dataQueueObj.h"
#include "BaseObj.h"
#include "dataQueue.h"
QueueObj* New_queueObj(void) {
PikaObj* self = New_PikaObj();
queueObj_init(self);
return self;
}
int32_t queueObj_init(QueueObj* self) {
obj_setInt(self, "top", 0);
obj_setInt(self, "bottom", 0);
return 0;
}
int32_t queueObj_pushObj(QueueObj* self, char* className) {
uint64_t top = obj_getInt(self, "top");
char buff[11];
char* topStr = fast_itoa(buff, top);
/* add top */
obj_setInt(self, "top", top + 1);
return obj_newObj(self, topStr, className, New_TinyObj);
}
PikaObj* queueObj_getCurrentObj(QueueObj* self) {
uint64_t current = obj_getInt(self, "top") - 1;
char buff[11];
char* currentStr = fast_itoa(buff, current);
return obj_getObj(self, currentStr);
}
PikaObj* queueObj_popObj(QueueObj* self) {
uint64_t bottom = obj_getInt(self, "bottom");
char buff[11];
char* bottomStr = fast_itoa(buff, bottom);
/* add bottom */
obj_setInt(self, "bottom", bottom + 1);
PikaObj* res = obj_getObj(self, bottomStr);
return res;
}
int32_t queueObj_pushInt(QueueObj* self, int val) {
uint64_t top = obj_getInt(self, "top");
char buff[11];
char* topStr = fast_itoa(buff, top);
/* add top */
obj_setInt(self, "top", top + 1);
return obj_setInt(self, topStr, val);
}
int64_t queueObj_popInt(QueueObj* self) {
uint64_t bottom = obj_getInt(self, "bottom");
char buff[11];
char* bottomStr = fast_itoa(buff, bottom);
/* add bottom */
obj_setInt(self, "bottom", bottom + 1);
int64_t res = obj_getInt(self, bottomStr);
obj_removeArg(self, bottomStr);
return res;
}
int32_t queueObj_pushFloat(QueueObj* self, pika_float val) {
uint64_t top = obj_getInt(self, "top");
char buff[11];
char* topStr = fast_itoa(buff, top);
/* add top */
obj_setInt(self, "top", top + 1);
return obj_setFloat(self, topStr, val);
}
pika_float queueObj_popFloat(QueueObj* self) {
uint64_t bottom = obj_getInt(self, "bottom");
char buff[11];
char* bottomStr = fast_itoa(buff, bottom);
/* add bottom */
obj_setInt(self, "bottom", bottom + 1);
pika_float res = obj_getFloat(self, bottomStr);
obj_removeArg(self, bottomStr);
return res;
}
int32_t queueObj_pushStr(QueueObj* self, char* str) {
uint64_t top = obj_getInt(self, "top");
char buff[11];
char* topStr = fast_itoa(buff, top);
/* add top */
obj_setInt(self, "top", top + 1);
return obj_setStr(self, topStr, str);
}
char* queueObj_popStr(QueueObj* self) {
uint64_t bottom = obj_getInt(self, "bottom");
char buff[11];
char* bottomStr = fast_itoa(buff, bottom);
/* add bottom */
obj_setInt(self, "bottom", bottom + 1);
return obj_getStr(self, bottomStr);
}

View File

@ -0,0 +1,48 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef __DATA_QUEUE_OBJ__H
#define __DATA_QUEUE_OBJ__H
#include "PikaObj.h"
typedef PikaObj QueueObj;
QueueObj* New_queueObj(void);
int32_t queueObj_init(QueueObj* self);
int32_t queueObj_pushInt(QueueObj* self, int val);
int32_t queueObj_pushFloat(QueueObj* self, pika_float val);
int32_t queueObj_pushStr(QueueObj* self, char* str);
int32_t queueObj_pushObj(QueueObj* self, char* className);
int64_t queueObj_popInt(QueueObj* self);
pika_float queueObj_popFloat(QueueObj* self);
char* queueObj_popStr(QueueObj* self);
PikaObj* queueObj_popObj(QueueObj* self);
PikaObj* queueObj_getCurrentObj(QueueObj* self);
#endif

View File

@ -0,0 +1,231 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "dataStack.h"
#include "PikaObj.h"
#include "dataQueue.h"
uint8_t* stack_popPyload(Stack* stack, int32_t size);
void stack_reset(Stack* stack) {
stack->sp = (uint8_t*)arg_getContent(stack->stack_pyload);
stack->sp_size = (int32_t*)arg_getContent(stack->stack_size_array);
stack->top = 0;
}
int32_t stack_init(Stack* stack) {
stack->stack_pyload = arg_setContent(NULL, NULL, PIKA_STACK_BUFF_SIZE);
stack->stack_size_array =
arg_setContent(NULL, NULL, PIKA_STACK_BUFF_SIZE / 4);
stack_reset(stack);
stack->stack_totle_size = PIKA_STACK_BUFF_SIZE;
return 0;
};
void stack_pushSize(Stack* stack, int32_t size) {
*(stack->sp_size) = size;
stack->sp_size++;
}
int32_t stack_popSize(Stack* stack) {
stack->sp_size--;
return *(stack->sp_size);
}
Arg* stack_checkArg(Stack* stack, int index) {
if (stack->top - index <= 0) {
return NULL;
}
int sp_offset = 0;
int32_t size = 0;
for (int i = 1; i <= index + 1; i++) {
size = stack->sp_size[-i];
if (size == -1) {
sp_offset -= sizeof(Arg*);
} else {
sp_offset -= size;
}
}
if (size == -1) {
return *(Arg**)(stack->sp + sp_offset);
}
return (Arg*)(stack->sp + sp_offset);
}
int32_t stack_deinit(Stack* stack) {
while (stack->top > 0) {
int32_t size = stack_popSize(stack);
uint8_t* pyload = stack_popPyload(stack, size);
stack->top--;
if (size == -1) {
arg_deinit(*(Arg**)pyload);
}
}
arg_deinit(stack->stack_pyload);
arg_deinit(stack->stack_size_array);
return 0;
}
void stack_pushPyload(Stack* stack,
uint8_t* in,
size_t size,
PIKA_BOOL is_sample_copy) {
size_t stack_size_after_push =
size + (stack->sp - arg_getContent(stack->stack_pyload));
if (stack_size_after_push > stack->stack_totle_size) {
pika_platform_printf(
"OverflowError: pika VM stack overflow, please use bigger "
"PIKA_STACK_BUFF_SIZE\r\n");
pika_platform_printf("Info: stack size request: %d\r\n",
(int)stack_size_after_push);
pika_platform_printf("Info: stack size now: %d\r\n",
(int)stack->stack_totle_size);
while (1) {
}
}
Arg* top = (Arg*)stack->sp;
if (is_sample_copy) {
pika_platform_memcpy(top, in, size);
} else {
pika_platform_memcpy(top, in, sizeof(Arg));
pika_platform_memcpy(top->content, ((Arg*)in)->_.buffer,
size - sizeof(Arg));
/* transfer to serialized form */
arg_setSerialized(top, PIKA_TRUE);
}
stack->sp += size;
}
uint8_t* stack_popPyload(Stack* stack, int32_t size) {
if (size == -1) {
size = sizeof(void*);
}
stack->sp -= size;
return stack->sp;
}
static int32_t _stack_pushArg(Stack* stack, Arg* arg, PIKA_BOOL is_alloc) {
PIKA_BOOL is_big_arg = PIKA_FALSE;
stack->top++;
size_t size = arg_getTotleSize(arg);
//! if you unsure about the __impl_pikaMalloc, uncomment this to force alignment
#if PIKA_ARG_ALIGN_ENABLE
/* force alignment to avoid unaligned access */
size = (size + 4 - 1) & ~(4 - 1);
#endif
/* add ref_cnt to keep object in stack */
if (argType_isObject(arg_getType(arg))) {
obj_refcntInc((PikaObj*)arg_getPtr(arg));
}
if (arg_isSerialized(arg)) {
is_big_arg = PIKA_TRUE;
}
if (is_big_arg) {
/* push a pointer to this arg */
stack_pushSize(stack, -1);
stack_pushPyload(stack, (uint8_t*)&arg, sizeof(Arg*), PIKA_TRUE);
} else {
stack_pushSize(stack, size);
stack_pushPyload(stack, (uint8_t*)arg, size, (PIKA_BOOL)arg_isSerialized(arg));
}
if (is_big_arg) {
return 0;
}
if (is_alloc) {
arg_deinit(arg);
return 0;
}
arg_deinitHeap(arg);
return 0;
}
int32_t stack_pushArg(Stack* stack, Arg* arg) {
pika_assert(arg != NULL);
if (arg_isSerialized(arg)) {
return _stack_pushArg(stack, arg, PIKA_TRUE);
}
return _stack_pushArg(stack, arg, PIKA_FALSE);
}
int32_t stack_pushStr(Stack* stack, char* str) {
Arg* newArg = arg_newStr(str);
return stack_pushArg(stack, newArg);
}
Arg* _stack_popArg(Stack* stack, Arg* arg_dict, PIKA_BOOL is_alloc) {
PIKA_BOOL is_big_arg = PIKA_FALSE;
if (stack->top == 0) {
return NULL;
}
stack->top--;
int32_t size = stack_popSize(stack);
if (size == -1) {
is_big_arg = PIKA_TRUE;
size = sizeof(Arg*);
}
Arg* arg = NULL;
if (is_big_arg) {
arg = *(Arg**)stack_popPyload(stack, size);
} else {
arg = (Arg*)stack_popPyload(stack, size);
if (is_alloc) {
arg = arg_copy(arg);
} else {
arg = arg_copy_noalloc(arg, arg_dict);
}
}
ArgType type = arg_getType(arg);
/* decrase ref_cnt */
if (argType_isObject(type)) {
obj_refcntDec((PikaObj*)arg_getPtr(arg));
}
pika_assert(arg->flag < ARG_FLAG_MAX);
return arg;
}
Arg* stack_popArg_alloc(Stack* stack) {
return _stack_popArg(stack, NULL, PIKA_TRUE);
}
Arg* stack_popArg(Stack* stack, Arg* arg_dict) {
return _stack_popArg(stack, arg_dict, PIKA_FALSE);
}
char* stack_popStr(Stack* stack, char* outBuff) {
Arg* arg = stack_popArg_alloc(stack);
strcpy(outBuff, arg_getStr(arg));
arg_deinit(arg);
return outBuff;
}
int32_t stack_getTop(Stack* stack) {
return stack->top;
}

View File

@ -0,0 +1,54 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef __DATA_STACK__H
#define __DATA_STACK__H
#include "dataArgs.h"
typedef struct Stack_t {
Arg* stack_pyload;
Arg* stack_size_array;
uint8_t* sp;
int32_t* sp_size;
int32_t top;
size_t stack_totle_size;
} Stack;
int32_t stack_deinit(Stack* stack);
int32_t stack_pushStr(Stack* stack, char* str);
char* stack_popStr(Stack* stack, char* outBuff);
Arg* stack_checkArg(Stack* stack, int index);
int32_t stack_pushArg(Stack* stack, Arg* arg);
Arg* stack_popArg_alloc(Stack* stack);
Arg* stack_popArg(Stack* stack, Arg* arg_dict);
int32_t stack_getTop(Stack* stack);
int32_t stack_init(Stack* stack);
int32_t stack_popSize(Stack* stack);
void stack_pushSize(Stack* stack, int32_t size);
void stack_reset(Stack* stack);
#endif

View File

@ -0,0 +1,282 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "dataString.h"
#include "PikaPlatform.h"
char* strCut(char* strOut, char* strIn, char startSign, char endSign) {
int32_t Size = strGetSize(strIn);
int32_t iStart = 0;
int32_t iEnd = Size;
uint8_t isStart = 0;
uint8_t isEnd = 0;
for (int32_t i = 0; i < Size; i++) {
if (strIn[i] == startSign) {
iStart = i;
isStart = 1;
break;
}
}
for (int32_t i = Size - 1; i >= 0; i--) {
if (strIn[i] == endSign) {
iEnd = i;
isEnd = 1;
break;
}
}
int outi = 0;
for (int32_t i = iStart + 1; i < iEnd; i++) {
strOut[outi] = strIn[i];
outi++;
}
/* add \0 */
strOut[outi] = 0;
if (isStart && isEnd) {
/* succeed */
return strOut;
}
/* failed */
return NULL;
}
char* strDeleteChar(char* strOut, char* strIn, char ch) {
int32_t iOut = 0;
uint32_t size = strGetSize(strIn);
for (uint32_t i = 0; i < size; i++) {
if (ch == strIn[i]) {
continue;
}
strOut[iOut] = strIn[i];
iOut++;
}
/* add \0 */
strOut[iOut] = 0;
return strOut;
}
char* strAppendWithSize(char* strOut, char* pData, int32_t Size) {
int32_t strOut_i = strGetSize(strOut);
for (int32_t i = 0; i < Size; i++) {
strOut[strOut_i + i] = pData[i];
}
strOut_i += Size;
// add \0 to the end of strOut
strOut[strOut_i] = 0;
return strOut;
}
int32_t strCountSign(char* strIn, char sign) {
pika_assert(NULL != strIn);
int count = 0;
while (*strIn) {
if (*strIn == sign) {
count++;
}
strIn++;
}
return count;
}
char* strReplaceChar(char* strIn, char src, char dst) {
while (*strIn) {
if (*strIn == src) {
*strIn = dst;
}
strIn++;
}
return strIn;
}
int32_t strGetTokenNum(char* strIn, char sign) {
return strCountSign(strIn, sign) + 1;
}
size_t strGetSize(char* pData) {
pika_assert(pData != NULL);
return strlen(pData);
}
char* strPointToLastToken(char* strIn, char sign) {
if (!strIsContain(strIn, sign)) {
return strIn;
}
int32_t size = strGetSize(strIn);
for (int32_t i = size - 1; i > -1; i--) {
if (strIn[i] == sign) {
return strIn + i + 1;
}
}
return strIn;
}
char* strPopLastToken(char* strIn, char sign) {
char* last_token = strPointToLastToken(strIn, sign);
if (last_token != strIn) {
*(last_token - 1) = 0;
}
return last_token;
}
char* strGetLastToken(char* strOut, char* strIn, char sign) {
int32_t size = strGetSize(strIn);
int32_t buffSize = 0;
for (int32_t i = size - 1; i > -1; i--) {
if (strIn[i] != sign) {
strOut[size - i - 1] = strIn[i];
buffSize++;
}
if (strIn[i] == sign) {
break;
}
}
int32_t i = 0;
for (i = 0; i < buffSize / 2; i++) {
char buff = strOut[i];
strOut[i] = strOut[buffSize - i - 1];
strOut[buffSize - i - 1] = buff;
}
strOut[buffSize] = 0;
return strOut;
}
char* strPopFirstToken(char** strIn, char sign) {
char* strIn_ = *strIn;
char* pos = strchr(strIn_, sign);
if (pos != NULL) {
/* found the first sign */
*pos = 0;
*strIn = pos + 1;
return strIn_;
}
/* no found */
*strIn = strchr(strIn_, 0);
return strIn_;
}
char* strGetFirstToken(char* strOut, char* strIn, char sign) {
int32_t size = strGetSize(strIn);
for (int32_t i = 0; i < size; i++) {
if (strIn[i] != sign) {
strOut[i] = strIn[i];
}
if (strIn[i] == sign) {
break;
}
}
return strOut;
}
char* strAppend(char* strOut, char* pData) {
uint32_t Size = 0;
Size = strGetSize(pData);
return strAppendWithSize(strOut, pData, Size);
}
int32_t strIsStartWith(char* str, char* strStart) {
if (NULL == str || NULL == strStart) {
/* input is null */
return 0;
}
/* fast return */
if (str[0] != strStart[0]) {
return 0;
}
uint32_t size = strGetSize(strStart);
if (0 == strncmp(str, strStart, size)) {
return 1;
}
return 0;
}
int32_t strEqu(char* str1, char* str2) {
if (NULL == str1 || NULL == str2) {
return 0;
}
return !strcmp(str1, str2);
}
char* strRemovePrefix(char* inputStr, char* prefix, char* outputStr) {
if (!strIsStartWith(inputStr, prefix)) {
return NULL;
}
size_t len = strGetSize(inputStr);
for (uint32_t i = strGetSize(prefix); i < len; i++) {
outputStr[i - strGetSize(prefix)] = inputStr[i];
}
return outputStr;
}
int32_t strIsContain(char* str, char ch) {
while (*str) {
if (*str == ch) {
return 1;
}
str++;
}
return 0;
}
char* strCopy(char* strBuff, char* strIn) {
pika_platform_memcpy(strBuff, strIn, strGetSize(strIn) + 1);
return strBuff;
}
int32_t strGetLineSize(char* str) {
int i = 0;
while (1) {
if (str[i] == '\n') {
return i;
}
i++;
}
}
char* strGetLine(char* strOut, char* strIn) {
int32_t lineSize = strGetLineSize(strIn);
pika_platform_memcpy(strOut, strIn, lineSize);
strOut[lineSize] = 0;
return strOut;
}
char* strGetLastLine(char* strOut, char* strIn) {
int32_t size = strGetSize(strIn);
char sign = '\n';
uint32_t beginIndex = 0;
/* skip the latest '\n' */
for (int32_t i = size - 2; i > -1; i--) {
if (strIn[i] == sign) {
beginIndex = i + 1;
break;
}
}
pika_platform_memcpy(strOut, strIn + beginIndex, size - beginIndex);
strOut[size - beginIndex + 1] = 0;
return strOut;
}

View File

@ -0,0 +1,66 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef __MY_TEST_TOOLS_H
#define __MY_TEST_TOOLS_H
#include "PikaPlatform.h"
/* size */
size_t strGetSize(char* pData);
/* append */
char* strAppend(char* strOut, char* pData);
char* strAppend_unlimited(char* strOut, char* pData);
char* strAppendWithSize(char* strOut, char* pData, int32_t Size);
/* cut */
char* strCut(char* strOut, char* strIn, char startSign, char endSign);
/* pika_assert */
int32_t strIsStartWith(char* str, char* strStart);
int32_t strEqu(char* str1, char* str2);
/* delete */
char* strDeleteEnter(char* str);
char* strDeleteChar(char* strOut, char* strIn, char ch);
/* prefix */
char* strRemovePrefix(char* inputStr, char* prefix, char* outputStr);
/* token */
int32_t strGetToken(char* string, char** argv, char sign);
char* strPopFirstToken(char** strIn, char sign);
int32_t strCountSign(char* strIn, char sign);
int32_t strGetTokenNum(char* strIn, char sign);
char* strGetFirstToken(char* strOut, char* strIn, char sign);
char* strGetLastToken(char* strOut, char* strIn, char sign);
char* strClear(char* str);
int32_t strIsContain(char* str, char ch);
char* strCopy(char* strBuff, char* strIn);
char* strGetLastLine(char* strOut, char* strIn);
char* strPointToLastToken(char* strIn, char sign);
char* strGetLine(char* strOut, char* strIn);
int32_t strGetLineSize(char* str);
char* strPopLastToken(char* strIn, char sign);
char* strGetLastLine(char* strOut, char* strIn);
char* strReplaceChar(char* strIn, char src, char dst);
#endif

View File

@ -0,0 +1,202 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#include "dataStrs.h"
#include "PikaPlatform.h"
#include "dataString.h"
Args* New_strBuff(void) {
return New_args(NULL);
}
char* strsRemovePrefix(Args* buffs_p, char* inputStr, char* prefix) {
int32_t size = strGetSize(inputStr);
char* buff = args_getBuff(buffs_p, size);
return strRemovePrefix(inputStr, prefix, buff);
}
char* strsGetDirectStr(Args* buffs_p, char* argPath) {
char* directStr = NULL;
directStr = strsCut(buffs_p, argPath, '"', '"');
if (NULL != directStr) {
return directStr;
}
directStr = strsCut(buffs_p, argPath, '\'', '\'');
if (NULL != directStr) {
return directStr;
}
return NULL;
}
char* strsAppend(Args* buffs_p, char* strOrigin, char* strToAppend) {
pika_assert(NULL != strToAppend);
pika_assert(NULL != strOrigin);
int32_t size = strGetSize(strOrigin) + strGetSize(strToAppend);
char* buff = args_getBuff(buffs_p, size);
char* strOut = strCopy(buff, strOrigin);
strAppend(strOut, strToAppend);
return strOut;
}
char* strsReturnOut(Args* buffs, Args* outbuffs, char* str) {
char* line_out = strsCopy(outbuffs, str);
strsDeinit(buffs);
return line_out;
}
char* strsGetLastToken(Args* buffs_p, char* argPath, char sign) {
int32_t size = strGetSize(argPath);
char* buff = args_getBuff(buffs_p, size);
return strGetLastToken(buff, argPath, sign);
}
char* strsCut(Args* buffs_p, char* strIn, char startSign, char endSign) {
int32_t size = strGetSize(strIn);
char* buff = args_getBuff(buffs_p, size);
return strCut(buff, strIn, startSign, endSign);
}
char* strsDeleteChar(Args* buffs_p, char* strIn, char ch) {
int32_t size = strGetSize(strIn);
return strDeleteChar(args_getBuff(buffs_p, size), strIn, ch);
}
static uint32_t getSizeOfFirstToken(char* str, char sign) {
uint32_t size = strGetSize(str);
for (uint32_t i = 0; i < size; i++) {
if (str[i] == sign) {
return i;
}
}
return size;
}
char* strsGetFirstToken(Args* buffs_p, char* strIn, char sign) {
int32_t size = getSizeOfFirstToken(strIn, sign);
return strGetFirstToken(args_getBuff(buffs_p, size), strIn, sign);
}
char* strsPopToken(Args* buffs_p, char** tokens, char sign) {
return strsCopy(buffs_p, strPopFirstToken(tokens, sign));
}
char* strsCopy(Args* buffs_p, char* source) {
pika_assert(source != NULL);
int32_t size = strGetSize(source);
char* buff = args_getBuff(buffs_p, size);
return strCopy(buff, source);
}
char* strsCacheArg(Args* buffs_p, Arg* arg) {
pika_assert(arg != NULL);
char* res = strsCopy(buffs_p, arg_getStr(arg));
arg_deinit(arg);
return res;
}
char* strsFormat(Args* buffs_p, uint16_t buffSize, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
char* res = args_getBuff(buffs_p, buffSize);
pika_platform_vsnprintf(res, buffSize, fmt, args);
va_end(args);
return res;
}
Arg* arg_strAppend(Arg* arg_in, char* str_to_append) {
pika_assert(NULL != str_to_append);
Args buffs = {0};
char* str_out = strsAppend(&buffs, arg_getStr(arg_in), str_to_append);
Arg* arg_out = arg_newStr(str_out);
arg_deinit(arg_in);
strsDeinit(&buffs);
return arg_out;
}
char* strsReplace(Args* buffs_p, char* orig, char* rep, char* with) {
char* result; // the return string
char* ins; // the next insert point
char* tmp; // varies
int len_rep; // length of rep (the string to remove)
int len_with; // length of with (the string to replace rep with)
int len_front; // distance between rep and end of last rep
int count; // number of replacements
/* no need replace, skip */
if (NULL == strstr(orig, rep)) {
return orig;
}
// sanity checks and initialization
if (!orig || !rep)
return NULL;
len_rep = strlen(rep);
if (len_rep == 0)
return NULL; // empty rep causes infinite loop during count
if (!with)
with = "";
len_with = strlen(with);
// count the number of replacements needed
ins = orig;
tmp = strstr(ins, rep);
count = 0;
while (tmp) {
count++;
ins = tmp + len_rep;
tmp = strstr(ins, rep);
}
tmp =
args_getBuff(buffs_p, strlen(orig) + (len_with - len_rep) * count + 1);
result = tmp;
if (NULL == result) {
return NULL;
}
// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
while (count--) {
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
}
strcpy(tmp, orig);
return result;
}
char* strsGetLine(Args* buffs_p, char* code) {
int32_t lineSize = strGetLineSize(code);
char* line_buff = args_getBuff(buffs_p, lineSize + 1);
return strGetLine(line_buff, code);
}
void strsDeinit(Args* buffs_p) {
link_deinit_stack(buffs_p);
}

View File

@ -0,0 +1,48 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef __STR_ARGS__H
#define __STR_ARGS__H
#include "dataArgs.h"
Args* New_strBuff(void);
char* strsGetFirstToken(Args* buffs, char* strIn, char sign);
char* strsGetLastToken(Args* buffs, char* arg_Path, char sign);
char* strsPopToken(Args* buffs, char** tokens, char sign);
char* strsCopy(Args* buffs, char* source);
char* strsDeleteChar(Args* buff, char* strIn, char ch);
char* strsCut(Args* buffs, char* strIn, char startSign, char endSign);
char* strsRemovePrefix(Args* buffs, char* inputStr, char* prefix);
char* strsAppend(Args* buffs, char* strOrigin, char* strAppend);
char* strsFormat(Args* buffs, uint16_t buffSize, const char* fmt, ...);
char* strsGetDirectStr(Args* buffs, char* argPath);
Arg* arg_strAppend(Arg* arg_in, char* str_to_append);
char* strsReplace(Args* buffs, char* orig, char* rep, char* with);
char* strsGetLine(Args* buffs, char* code);
void strsDeinit(Args* buffs);
char* strsCacheArg(Args* buffs_p, Arg* arg);
char* strsReturnOut(Args* buffs, Args* outbuffs, char* str);
#endif

View File

@ -0,0 +1,337 @@
#ifndef __PIKA_ADAPTER_MPY_H__
#define __PIKA_ADAPTER_MPY_H__
#include <stdint.h>
#include "PikaObj.h"
#include "PikaStdData_List.h"
#define bool int
#define true 1
#define false 0
/* object type */
#define mp_obj_t Arg*
/* type define*/
#define STATIC static
#define NORETURN
/* object API */
#define MP_OBJ_NEW_SMALL_INT(...) arg_newInt(__VA_ARGS__)
#define mp_obj_new_bool(...) arg_newInt(__VA_ARGS__)
#define mp_obj_new_bytes(...) arg_newBytes(__VA_ARGS__)
#define mp_obj_new_float(...) arg_newFloat(__VA_ARGS__)
#define MP_OBJ_TO_PTR(...) arg_getPtr(__VA_ARGS__)
#define MP_OBJ_FROM_PTR(_p) arg_newPtr(ARG_TYPE_OBJECT, (_p))
#define mp_obj_get_int(...) arg_getInt(__VA_ARGS__)
#define mp_obj_is_true(...) (bool)arg_getInt(__VA_ARGS__)
#define mp_const_true arg_newInt(1)
#define mp_const_false arg_newInt(0)
#define mp_const_none arg_newNull()
/* module API */
#define MP_DEFINE_CONST_DICT(...)
#define MP_DEFINE_CONST_FUN_OBJ_KW(...)
#define MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(...)
#define MP_DEFINE_CONST_FUN_OBJ_1(...)
#define MP_DEFINE_CONST_FUN_OBJ_2(...)
#define MP_DEFINE_CONST_FUN_OBJ_3(...)
#define MP_DEFINE_CONST_FUN_OBJ_4(...)
#define MP_DEFINE_CONST_FUN_OBJ_5(...)
#define MP_DEFINE_CONST_FUN_OBJ_6(...)
#define MP_DEFINE_CONST_FUN_OBJ_7(...)
#define MP_DEFINE_CONST_FUN_OBJ_8(...)
/* gil */
#define MP_THREAD_GIL_EXIT(...)
#define MP_THREAD_GIL_ENTER(...)
/* raise */
#define MP_ETIMEDOUT "timed out"
#define MP_ENOMEM "out of memory"
#define MP_BUFFER_READ "read"
#define MP_ERROR_TEXT(_s) _s
#define mp_raise_msg_varg(_, ...) pika_platform_printf(__VA_ARGS__)
#define mp_raise_msg(_, _s) mp_raise_msg_varg(_, _s)
#define mp_raise_TpyeXXX(_s) mp_raise_msg(NULL, _s)
#define mp_raise_ValueError mp_raise_TpyeXXX
#define mp_raise_TypeError mp_raise_TpyeXXX
#define mp_raise_OSError mp_raise_TpyeXXX
/* utils */
#define MIN(_a, _b) ((_a) < (_b) ? (_a) : (_b))
#define MAX(_a, _b) ((_a) > (_b) ? (_a) : (_b))
/* list */
typedef struct mp_obj_tuple_t {
size_t len;
mp_obj_t* items;
} mp_obj_tuple_t;
#define mp_obj_str_get_str(...) arg_getStr(__VA_ARGS__)
#define mp_obj_get_float(...) arg_getFloat(__VA_ARGS__)
typedef struct _mp_map_elem_t {
mp_obj_t key;
mp_obj_t value;
} mp_map_elem_t;
typedef struct mp_map_t {
size_t all_keys_are_qstrs : 1;
size_t
is_fixed : 1; // if set, table is fixed/read-only and can't be modified
size_t is_ordered : 1; // if set, table is an ordered array, not a hash map
size_t used : (8 * sizeof(size_t) - 3);
size_t alloc;
mp_map_elem_t* table;
} mp_map_t;
static inline bool mp_map_slot_is_filled(const mp_map_t* map, size_t pos) {
return (map)->table[pos].key != NULL;
}
static inline int mp_obj_str_get_qstr(Arg* arg) {
return hash_time33(arg_getStr(arg));
}
#define mp_obj_new_str(str, len) arg_newStr(str)
typedef struct _mp_buffer_info_t {
void* buf; // can be NULL if len == 0
size_t len; // in bytes
int typecode; // as per binary.h
} mp_buffer_info_t;
#define MP_QSTR(_str) hash_time33(#_str)
static inline Arg* mp_obj_new_list(int n, Arg** items) {
PikaObj* list = newNormalObj(New_PikaStdData_List);
PikaStdData_List___init__(list);
return arg_newObj(list);
}
static inline mp_obj_tuple_t* mp_obj_new_tuple(int n, Arg** items_in) {
mp_obj_tuple_t* tuple = (mp_obj_tuple_t*)malloc(sizeof(mp_obj_tuple_t));
Arg** items = (Arg**)malloc(sizeof(Arg*) * n);
if (NULL == items_in) {
tuple->len = n;
tuple->items = items;
}
return tuple;
}
static inline void mp_obj_list_append(Arg* list, mp_obj_tuple_t* tuple) {
PikaObj* list_obj = (PikaObj*)arg_getPtr(list);
for (int i = 0; i < tuple->len; i++) {
PikaStdData_List_append(list_obj, tuple->items[i]);
arg_deinit(tuple->items[i]);
}
free(tuple->items);
free(tuple);
}
static inline char* mp_obj_str_get_data(Arg* self, size_t* len) {
char* str = arg_getStr(self);
*len = strGetSize(str);
return str;
}
static inline size_t pks_load_mp_args(PikaTuple* tuple,
mp_obj_t mp_self,
mp_obj_t* args) {
size_t len = pikaTuple_getSize(tuple);
size_t i = 0;
if (NULL != mp_self) {
args[0] = mp_self;
i = 1;
}
for (i = 0; i < len; i++) {
args[i] = pikaTuple_getArg(tuple, i);
}
return len;
}
static inline void pks_load_mp_map(PikaDict* kw, mp_map_t* map) {
size_t len = pikaDict_getSize(kw);
map->alloc = len;
map->used = len;
map->table = (mp_map_elem_t*)malloc(sizeof(mp_map_elem_t) * len);
for (int i = 0; i < len; i++) {
Arg* item = pikaDict_getArgByidex(kw, i);
map->table[i].key = arg_getNameHash(item);
map->table[i].value = item;
}
}
static inline void mp_get_buffer_raise(mp_obj_t item,
mp_buffer_info_t* buf,
char* msg) {
buf->len = arg_getSize(item);
buf->buf = malloc(buf->len);
if (NULL == buf->buf) {
mp_raise_OSError(msg);
}
memcpy(buf->buf, arg_getBytes(item), buf->len);
}
static const ArgType mp_type_tuple = ARG_TYPE_TUPLE;
static const ArgType mp_type_list = ARG_TYPE_TUPLE;
static const ArgType mp_type_str = ARG_TYPE_STRING;
static const ArgType mp_type_bytes = ARG_TYPE_BYTES;
static const ArgType mp_type_int = ARG_TYPE_INT;
static const ArgType mp_type_float = ARG_TYPE_FLOAT;
static const ArgType mp_type_bool = ARG_TYPE_INT;
static const ArgType mp_type_none = ARG_TYPE_NONE;
static inline bool mp_obj_is_type(mp_obj_t self, ArgType* arg_type_ptr) {
if (arg_getType(self) == *arg_type_ptr) {
return true;
}
return false;
}
#define mp_obj_is_integer(self) mp_obj_is_type(self, &mp_type_int)
#define mp_uint_t size_t
#define mp_int_t int
typedef void (*mp_print_strn_t)(void* data, const char* str, size_t len);
typedef struct _mp_print_t {
void* data;
mp_print_strn_t print_strn;
} mp_print_t;
static inline void mp_obj_get_array_fixed_n(mp_obj_t tuple,
size_t n,
mp_obj_t* arrray) {
for (int i = 0; i < n; i++) {
arrray[i] = pikaTuple_getArg((PikaTuple*)arg_getPtr(tuple), i);
}
}
typedef const void* mp_const_obj_t;
typedef mp_const_obj_t mp_rom_obj_t;
typedef struct _mp_rom_map_elem_t {
mp_rom_obj_t key;
mp_rom_obj_t value;
} mp_rom_map_elem_t;
#define MICROPY_OBJ_BASE_ALIGNMENT
typedef struct _mp_obj_type_t mp_obj_type_t;
struct _mp_obj_base_t {
const mp_obj_type_t* type MICROPY_OBJ_BASE_ALIGNMENT;
};
typedef struct _mp_obj_base_t mp_obj_base_t;
struct _mp_obj_type_t {
// A type is an object so must start with this entry, which points to
// mp_type_type.
mp_obj_base_t base;
// Flags associated with this type.
uint16_t flags;
// The name of this type, a qstr.
uint16_t name;
// Slots: For the rest of the fields, the slot index points to the
// relevant function in the variable-length "slots" field. Ideally these
// would be only 4 bits, but the extra overhead of accessing them adds
// more code, and we also need to be able to take the address of them for
// mp_obj_class_lookup.
// Corresponds to __new__ and __init__ special methods, to make an instance
// of the type.
uint8_t slot_index_make_new;
// Corresponds to __repr__ and __str__ special methods.
uint8_t slot_index_print;
// Corresponds to __call__ special method, ie T(...).
uint8_t slot_index_call;
// Implements unary and binary operations.
// Can return MP_OBJ_NULL if the operation is not supported.
uint8_t slot_index_unary_op;
uint8_t slot_index_binary_op;
// Implements load, store and delete attribute.
//
// dest[0] = MP_OBJ_NULL means load
// return: for fail, do nothing
// for fail but continue lookup in locals_dict, dest[1] =
// MP_OBJ_SENTINEL for attr, dest[0] = value for method, dest[0] =
// method, dest[1] = self
//
// dest[0,1] = {MP_OBJ_SENTINEL, MP_OBJ_NULL} means delete
// dest[0,1] = {MP_OBJ_SENTINEL, object} means store
// return: for fail, do nothing
// for success set dest[0] = MP_OBJ_NULL
uint8_t slot_index_attr;
// Implements load, store and delete subscripting:
// - value = MP_OBJ_SENTINEL means load
// - value = MP_OBJ_NULL means delete
// - all other values mean store the value
// Can return MP_OBJ_NULL if operation not supported.
uint8_t slot_index_subscr;
// This slot's behaviour depends on the MP_TYPE_FLAG_ITER_IS_* flags above.
// - If MP_TYPE_FLAG_ITER_IS_GETITER flag is set, then this corresponds to
// the __iter__
// special method (of type mp_getiter_fun_t). Can use the given
// mp_obj_iter_buf_t to store the iterator object, otherwise can return a
// pointer to an object on the heap.
// - If MP_TYPE_FLAG_ITER_IS_ITERNEXT is set, then this corresponds to
// __next__ special method.
// May return MP_OBJ_STOP_ITERATION as an optimisation instead of raising
// StopIteration() with no args. The type will implicitly implement
// getiter as "return self".
// - If MP_TYPE_FLAG_ITER_IS_CUSTOM is set, then this slot must point to an
// mp_getiter_iternext_custom_t instance with both the getiter and
// iternext fields set.
// - If MP_TYPE_FLAG_ITER_IS_STREAM is set, this this slot should be unset.
uint8_t slot_index_iter;
// Implements the buffer protocol if supported by this type.
uint8_t slot_index_buffer;
// One of disjoint protocols (interfaces), like mp_stream_p_t, etc.
uint8_t slot_index_protocol;
// A pointer to the parents of this type:
// - 0 parents: pointer is NULL (object is implicitly the single parent)
// - 1 parent: a pointer to the type of that parent
// - 2 or more parents: pointer to a tuple object containing the parent
// types
uint8_t slot_index_parent;
// A dict mapping qstrs to objects local methods/constants/etc.
uint8_t slot_index_locals_dict;
const void* slots[];
};
typedef struct _mp_obj_dict_t {
mp_obj_base_t base;
mp_map_t map;
} mp_obj_dict_t;
typedef struct _mp_obj_module_t {
mp_obj_base_t base;
mp_obj_dict_t* globals;
} mp_obj_module_t;
typedef struct _vstr_t {
size_t alloc;
size_t len;
char *buf;
bool fixed_buf;
} vstr_t;
typedef struct _mp_obj_list_t {
mp_obj_base_t base;
size_t alloc;
size_t len;
mp_obj_t *items;
} mp_obj_list_t;
#endif

View File

@ -0,0 +1,77 @@
#ifndef __PIKA_ADAPTER_OLD_API_H__
#define __PIKA_ADAPTER_OLD_API_H__
/* micro pika configuration */
#include "./pika_config_valid.h"
/*
* This file is used to support old api, it's not recommended to use it.
* In new project, please use new api instead.
*/
#if PIKA_OLD_API_ENABLE
#define __platform_enable_irq_handle pika_platform_enable_irq_handle
#define __platform_disable_irq_handle pika_platform_disable_irq_handle
#define __platform_printf pika_platform_printf
#define __platform_sprintf pika_platform_sprintf
#define __platform_vsprintf pika_platform_vsprintf
#define __platform_vsnprintf pika_platform_vsnprintf
#define __platform_snprintf pika_platform_snprintf
#define __platform_strdup pika_platform_strdup
#define __platform_tick_from_millisecond pika_platform_tick_from_millisecond
#define __platform_malloc pika_platform_malloc
#define __platform_realloc pika_platform_realloc
#define __platform_calloc pika_platform_calloc
#define __platform_free pika_platform_free
#define __platform_memset pika_platform_memset
#define __platform_memcpy pika_platform_memcpy
#define __platform_memcmp pika_platform_memcmp
#define __platform_memmove pika_platform_memmove
#define __platform_wait pika_platform_wait
#define __platform_getchar pika_platform_getchar
#define __platform_putchar pika_platform_putchar
#define __platform_fopen pika_platform_fopen
#define __platform_fclose pika_platform_fclose
#define __platform_fwrite pika_platform_fwrite
#define __platform_fread pika_platform_fread
#define __platform_fseek pika_platform_fseek
#define __platform_ftell pika_platform_ftell
#define __platform_error_handle pika_platform_error_handle
#define __platform_panic_handle pika_platform_panic_handle
#define __platform_thread_delay pika_platform_thread_delay
#define __platform_getTick pika_platform_getTick
#define __platform_sleep_ms pika_platform_sleep_ms
#define __platform_sleep_s pika_platform_sleep_s
#define __pks_hook_instruct pika_hook_instruct
#define __pks_hook_arg_cache_filter pika_hook_arg_cache_filter
#define __user_malloc pika_user_malloc
#define __user_free pika_user_free
#define __is_locked_pikaMemory pika_is_locked_pikaMemory
/* old api */
#define __platform_socket pika_platform_socket
#define __platform_bind pika_platform_bind
#define __platform_listen pika_platform_listen
#define __platform_accept pika_platform_accept
#define __platform_connect pika_platform_connect
#define __platform_send pika_platform_send
#define __platform_recv pika_platform_recv
#define __platform_gethostname pika_platform_gethostname
#define __platform_getaddrinfo pika_platform_getaddrinfo
#define __platform_freeaddrinfo pika_platform_freeaddrinfo
#define __platform_setsockopt pika_platform_setsockopt
#define __platform_close pika_platform_close
#define __platform_write pika_platform_write
#define __platform_fcntl pika_platform_fcntl
#define pks_eventLicener_registEvent pks_eventListener_registEvent
#define pks_eventLisener_init pks_eventListener_init
#define pks_eventLisener_getEventHandleObj pks_eventListener_getEventHandleObj
#define pks_eventLisener_sendSignal pks_eventListener_sendSignal
#define pks_eventLisener_deinit pks_eventListener_deinit
#define pks_eventLicener_removeEvent pks_eventListener_removeEvent
#endif
#endif

View File

@ -0,0 +1,54 @@
#ifndef __PIKA_ADAPTER_RTT_H__
#include <stdint.h>
#include "PikaPlatform.h"
#define __PIKA_ADAPTER_RTT_H__
#define RT_NULL 0
/* boolean type definitions */
#define RT_TRUE 1 /**< boolean true */
#define RT_FALSE 0 /**< boolean fails */
#define rt_malloc pika_platform_malloc
#define rt_calloc pika_platform_calloc
#define rt_realloc pika_platform_realloc
#define rt_free pika_platform_free
#define rt_memset pika_platform_memset
#define rt_memcpy pika_platform_memcpy
#define rt_memcmp pika_platform_memcmp
#define rt_kprintf pika_platform_printf
#define rt_snprintf pika_platform_snprintf
#define rt_vsnprintf pika_platform_vsnprintf
#define rt_strdup pika_platform_strdup
#define rt_tick_from_millisecond pika_platform_tick_from_millisecond
#define rt_int32_t int32_t
#define rt_uint32_t uint32_t
#define rt_int16_t int16_t
#define rt_uint16_t uint16_t
#define rt_int8_t int8_t
#define rt_uint8_t uint8_t
#define rt_int64_t int64_t
#define rt_uint64_t uint64_t
#define rt_size_t size_t
#define rt_bool_t uint8_t
/* RT-Thread error code definitions */
#define RT_EOK 0 /**< There is no error */
#define RT_ERROR 1 /**< A generic error happens */
#define RT_ETIMEOUT 2 /**< Timed out */
#define RT_EFULL 3 /**< The resource is full */
#define RT_EEMPTY 4 /**< The resource is empty */
#define RT_ENOMEM 5 /**< No memory */
#define RT_ENOSYS 6 /**< No system */
#define RT_EBUSY 7 /**< Busy */
#define RT_EIO 8 /**< IO error */
#define RT_EINTR 9 /**< Interrupted system call */
#define RT_EINVAL 10 /**< Invalid argument */
#define LOG_E(fmt, ...) pika_platform_printf(fmt "\r\n", ##__VA_ARGS__)
#define LOG_W(...)
#define LOG_D(...)
#define RT_ASSERT(...) pika_assert(__VA_ARGS__)
#endif

View File

@ -0,0 +1,357 @@
/*
* This file is part of the PikaScript project.
* http://github.com/pikastech/pikascript
*
* MIT License
*
* Copyright (c) 2021 lyon liang6516@outlook.com
*
* 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:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
#ifndef __PIKA_CFG_VALID_H__
#define __PIKA_CFG_VALID_H__
/* clang-format off */
/*
* Don't modify the "pika_config_valid.h" file!
* If you want to change the config, create "pika_config.h",
* then #define PIKA_CONFIG_ENABLE in the Compiler Options.
* To see more:
* https://pikadoc.readthedocs.io/en/latest/%E4%BC%98%E5%8C%96%E5%86%85%E5%AD%98%E5%8D%A0%E7%94%A8%E3%80%81%E9%85%8D%E7%BD%AE%20libc.html
*/
/* optimize options */
#define PIKA_OPTIMIZE_SIZE 0
#define PIKA_OPTIMIZE_SPEED 1
/* syntax support level */
#define PIKA_SYNTAX_LEVEL_MINIMAL 0
#define PIKA_SYNTAX_LEVEL_MAXIMAL 1
/* use user config */
#ifdef PIKA_CONFIG_ENABLE
#include "pika_config.h"
#endif
/* default pika_nano_enabled */
#ifndef PIKA_NANO_ENABLE
#define PIKA_NANO_ENABLE 0
#endif
#if PIKA_NANO_ENABLE
#ifndef PIKA_OPTIMIZE
#define PIKA_OPTIMIZE PIKA_OPTIMIZE_SIZE
#endif
/* default syntax support level */
#ifndef PIKA_SYNTAX_LEVEL
#define PIKA_SYNTAX_LEVEL PIKA_SYNTAX_LEVEL_MINIMAL
#endif
#ifndef PIKA_STRING_UTF8_ENABLE
#define PIKA_STRING_UTF8_ENABLE 0
#endif
#endif
/* default optimize */
#ifndef PIKA_OPTIMIZE
#define PIKA_OPTIMIZE PIKA_OPTIMIZE_SIZE
#endif
/* default syntax support level */
#ifndef PIKA_SYNTAX_LEVEL
#define PIKA_SYNTAX_LEVEL PIKA_SYNTAX_LEVEL_MAXIMAL
#endif
/* auto config for optimize */
#if PIKA_OPTIMIZE == PIKA_OPTIMIZE_SIZE
#ifndef PIKA_METHOD_CACHE_ENABLE
#define PIKA_METHOD_CACHE_ENABLE 0
#endif
#elif PIKA_OPTIMIZE == PIKA_OPTIMIZE_SPEED
#ifndef PIKA_METHOD_CACHE_ENABLE
#define PIKA_METHOD_CACHE_ENABLE 1
#endif
#ifndef PIKA_ARG_CACHE_ENABLE
#define PIKA_ARG_CACHE_ENABLE 1
#endif
#endif
/* auto config for syntax level */
#if PIKA_SYNTAX_LEVEL == PIKA_SYNTAX_LEVEL_MINIMAL
#ifndef PIKA_SYNTAX_SLICE_ENABLE
#define PIKA_SYNTAX_SLICE_ENABLE 0
#endif
#ifndef PIKA_BUILTIN_STRUCT_ENABLE
#define PIKA_BUILTIN_STRUCT_ENABLE 0
#endif
#ifndef PIKA_SYNTAX_FORMAT_ENABLE
#define PIKA_SYNTAX_FORMAT_ENABLE 0
#endif
#ifndef PIKA_STD_DEVICE_UNIX_TIME_ENABLE
#define PIKA_STD_DEVICE_UNIX_TIME_ENABLE 0
#endif
#ifndef PIKA_SYNTAX_EXCEPTION_ENABLE
#define PIKA_SYNTAX_EXCEPTION_ENABLE 0
#endif
#ifndef PIKA_SYNTAX_IMPORT_EX_ENABLE
#define PIKA_SYNTAX_IMPORT_EX_ENABLE 0
#endif
#ifndef PIKA_EVENT_ENABLE
#define PIKA_EVENT_ENABLE 0
#endif
#ifndef PIKA_FILEIO_ENABLE
#define PIKA_FILEIO_ENABLE 0
#endif
#ifndef PIKA_EXEC_ENABLE
#define PIKA_EXEC_ENABLE 0
#endif
#elif PIKA_SYNTAX_LEVEL == PIKA_SYNTAX_LEVEL_MAXIMAL
#ifndef PIKA_SYNTAX_SLICE_ENABLE
#define PIKA_SYNTAX_SLICE_ENABLE 1
#endif
#ifndef PIKA_BUILTIN_STRUCT_ENABLE
#define PIKA_BUILTIN_STRUCT_ENABLE 1
#endif
#ifndef PIKA_SYNTAX_FORMAT_ENABLE
#define PIKA_SYNTAX_FORMAT_ENABLE 1
#endif
#ifndef PIKA_STD_DEVICE_UNIX_TIME_ENABLE
#define PIKA_STD_DEVICE_UNIX_TIME_ENABLE 1
#endif
#ifndef PIKA_SYNTAX_EXCEPTION_ENABLE
#define PIKA_SYNTAX_EXCEPTION_ENABLE 1
#endif
#ifndef PIKA_SYNTAX_IMPORT_EX_ENABLE
#define PIKA_SYNTAX_IMPORT_EX_ENABLE 1
#endif
#ifndef PIKA_EVENT_ENABLE
#define PIKA_EVENT_ENABLE 1
#endif
#ifndef PIKA_FILEIO_ENABLE
#define PIKA_FILEIO_ENABLE 1
#endif
#ifndef PIKA_EXEC_ENABLE
#define PIKA_EXEC_ENABLE 1
#endif
#endif
/* default configuration */
#ifndef PIKA_LINE_BUFF_SIZE
#define PIKA_LINE_BUFF_SIZE 128
#endif
#ifndef PIKA_SPRINTF_BUFF_SIZE
#define PIKA_SPRINTF_BUFF_SIZE 256
#endif
#ifndef PIKA_STACK_BUFF_SIZE
#define PIKA_STACK_BUFF_SIZE 256
#endif
#ifndef PIKA_NAME_BUFF_SIZE
#define PIKA_NAME_BUFF_SIZE 32
#endif
#ifndef PIKA_PATH_BUFF_SIZE
#define PIKA_PATH_BUFF_SIZE 96
#endif
#ifndef PIKA_BYTES_DEFAULT_SIZE
#define PIKA_BYTES_DEFAULT_SIZE 64
#endif
#ifndef PIKA_ARG_ALIGN_ENABLE
#define PIKA_ARG_ALIGN_ENABLE 1
#endif
#ifndef PIKA_METHOD_CACHE_ENABLE
#define PIKA_METHOD_CACHE_ENABLE 0
#endif
#ifndef PIKA_BUILTIN_STRUCT_ENABLE
#define PIKA_BUILTIN_STRUCT_ENABLE 0
#endif
#ifndef PIKA_READ_FILE_BUFF_SIZE
#define PIKA_READ_FILE_BUFF_SIZE 1024 * 10
#endif
#ifndef PIKA_INIT_STRING_ENABLE
#define PIKA_INIT_STRING_ENABLE 0
#endif
#ifndef PIKA_SYNTAX_SLICE_ENABLE
#define PIKA_SYNTAX_SLICE_ENABLE 1
#endif
#ifndef PIKA_SYNTAX_FORMAT_ENABLE
#define PIKA_SYNTAX_FORMAT_ENABLE 1
#endif
#ifndef PIKA_SYNTAX_EXCEPTION_ENABLE
#define PIKA_SYNTAX_EXCEPTION_ENABLE 1
#endif
#ifndef PIKA_SYNTAX_IMPORT_EX_ENABLE
#define PIKA_SYNTAX_IMPORT_EX_ENABLE 1
#endif
#ifndef PIKA_PLOOC_ENABLE
#define PIKA_PLOOC_ENABLE 0
#endif
#ifndef PIKA_STD_DEVICE_UNIX_TIME_ENABLE
#define PIKA_STD_DEVICE_UNIX_TIME_ENABLE 1
#endif
#ifndef PIKA_POOL_ENABLE
#define PIKA_POOL_ENABLE 0
#endif
#ifndef PIKA_POOL_SIZE
#define PIKA_POOL_SIZE 0x4000
#endif
#ifndef PIKA_POOL_ALIGN
#define PIKA_POOL_ALIGN 8
#endif
#ifndef PIKA_ASSERT_ENABLE
#define PIKA_ASSERT_ENABLE 0
#endif
#ifndef PIKA_EVENT_ENABLE
#define PIKA_EVENT_ENABLE 1
#endif
#ifndef PIKA_DEBUG_ENABLE
#define PIKA_DEBUG_ENABLE 0
#endif
#ifndef PIKA_FILEIO_ENABLE
#define PIKA_FILEIO_ENABLE 1
#endif
#ifndef PIKA_ARG_NUM_MAX
#define PIKA_ARG_NUM_MAX 16
#endif
#ifndef PIKA_MATH_ENABLE
#define PIKA_MATH_ENABLE 0
#endif
#ifndef PIKA_REGIST_SIZE
#define PIKA_REGIST_SIZE 10
#endif
#ifndef PIKA_ARG_BUFF_SIZE
#define PIKA_ARG_BUFF_SIZE 8
#endif
#ifndef PIKA_INSTRUCT_HOOK_ENABLE
#define PIKA_INSTRUCT_HOOK_ENABLE 0
#endif
#ifndef PIKA_INSTRUCT_HOOK_PERIOD
#define PIKA_INSTRUCT_HOOK_PERIOD 50
#endif
#ifndef PIKA_EXEC_ENABLE
#define PIKA_EXEC_ENABLE 1
#endif
/* support for UTF-8 in PikaStdData_String */
#ifndef PIKA_STRING_UTF8_ENABLE
#define PIKA_STRING_UTF8_ENABLE 1
#endif
#ifndef PIKA_PRINT_LLD_ENABLE
#define PIKA_PRINT_LLD_ENABLE 1
#endif
#ifndef PIKA_FLOAT_TYPE_DOUBLE
#define PIKA_FLOAT_TYPE_DOUBLE 1
#endif
#ifndef PIKA_ARG_CACHE_ENABLE
#define PIKA_ARG_CACHE_ENABLE 0
#endif
#ifndef PIKA_ARG_CACHE_POOL_SIZE
#define PIKA_ARG_CACHE_POOL_SIZE 32
#endif
#ifndef PIKA_ARG_CACHE_SIZE
#define PIKA_ARG_CACHE_SIZE sizeof(Arg) + 16
#endif
#ifndef PIKA_SHELL_SAVE_FILE_ENABLE
#define PIKA_SHELL_SAVE_FILE_ENABLE 0
#endif
#ifndef PIKA_SHELL_SAVE_FILE_NAME
#define PIKA_SHELL_SAVE_FILE_NAME "pika_shell_save.py"
#endif
#ifndef PIKA_EVENT_LIST_SIZE
#define PIKA_EVENT_LIST_SIZE 16
#endif
#ifndef PIKA_BYTECODE_ONLY_ENABLE
#define PIKA_BYTECODE_ONLY_ENABLE 0
#endif
#ifndef PIKA_OLD_API_ENABLE
#define PIKA_OLD_API_ENABLE 1
#endif
#ifndef PIKA_FREERTOS_ENABLE
#define PIKA_FREERTOS_ENABLE 0
#endif
#ifndef PIKA_LWIP_ENABLE
#define PIKA_LWIP_ENABLE 0
#endif
/* configuration validation */
#endif

View File

@ -0,0 +1,57 @@
#include "PikaVM.h"
#include "dataStrs.h"
extern volatile PikaObj* __pikaMain;
static enum shellCTRL __obj_shellLineHandler_debug(
PikaObj* self,
char* input_line,
struct ShellConfig* config) {
/* continue */
if (strEqu("c", input_line)) {
return SHELL_CTRL_EXIT;
}
/* next */
if (strEqu("n", input_line)) {
return SHELL_CTRL_EXIT;
}
/* launch shell */
if (strEqu("sh", input_line)) {
/* exit pika shell */
pikaScriptShell((PikaObj*)__pikaMain);
return SHELL_CTRL_CONTINUE;
}
/* quit */
if (strEqu("q", input_line)) {
obj_setInt(self, "enable", 0);
return SHELL_CTRL_EXIT;
}
/* print */
if (strIsStartWith(input_line, "p ")) {
char* path = input_line + 2;
Arg* asm_buff = arg_newStr("B0\n1 REF ");
asm_buff = arg_strAppend(asm_buff, path);
asm_buff = arg_strAppend(asm_buff, "\n0 RUN print\n");
pikaVM_runAsm((PikaObj*)__pikaMain, arg_getStr(asm_buff));
arg_deinit(asm_buff);
return SHELL_CTRL_CONTINUE;
}
obj_run((PikaObj*)__pikaMain, input_line);
return SHELL_CTRL_CONTINUE;
}
void PikaDebug_Debuger___init__(PikaObj* self) {
/* global enable contral */
obj_setInt(self, "enable", 1);
}
void PikaDebug_Debuger_set_trace(PikaObj* self) {
if (!obj_getInt(self, "enable")) {
return;
}
struct ShellConfig cfg = {
.prefix = "(pika-debug) ",
.handler = __obj_shellLineHandler_debug,
.fn_getchar = __platform_getchar,
};
_do_pikaScriptShell(self, &cfg);
}

View File

@ -0,0 +1,71 @@
#include "PikaStdData_ByteArray.h"
void PikaStdData_ByteArray___init__(PikaObj* self, Arg* bytes) {
obj_setArg(self, "raw", bytes);
}
Arg* PikaStdData_ByteArray___iter__(PikaObj* self) {
obj_setInt(self, "__iter_i", 0);
return arg_newRef(self);
}
Arg* PikaStdData_ByteArray___next__(PikaObj* self) {
int __iter_i = args_getInt(self->list, "__iter_i");
uint8_t* data = obj_getBytes(self, "raw");
uint16_t len = obj_getBytesSize(self, "raw");
Arg* res = NULL;
char char_buff[] = " ";
if (__iter_i < len) {
char_buff[0] = data[__iter_i];
res = arg_newInt(char_buff[0]);
} else {
return arg_newNull();
}
args_setInt(self->list, "__iter_i", __iter_i + 1);
return res;
}
int PikaStdData_ByteArray___getitem__(PikaObj* self, int __key) {
uint8_t* data = obj_getBytes(self, "raw");
uint16_t len = obj_getBytesSize(self, "raw");
if (__key < len) {
return data[__key];
} else {
return 0;
}
}
void PikaStdData_ByteArray___setitem__(PikaObj* self, int __key, int __val) {
uint8_t* data = obj_getBytes(self, "raw");
uint16_t len = obj_getBytesSize(self, "raw");
if (__key < len) {
data[__key] = __val;
}
}
char* PikaStdData_ByteArray___str__(PikaObj* self) {
uint8_t* data = obj_getBytes(self, "raw");
uint16_t len = obj_getBytesSize(self, "raw");
Arg* str_arg = arg_newStr("");
str_arg = arg_strAppend(str_arg, "bytearray(b'");
for (int i = 0; i < len; i++) {
char u8_str[] = "\\x00";
uint8_t u8 = data[i];
__platform_sprintf(u8_str, "\\x%02x", u8);
str_arg = arg_strAppend(str_arg, u8_str);
}
str_arg = arg_strAppend(str_arg, "')");
obj_removeArg(self, "_buf");
obj_setStr(self, "_buf", arg_getStr(str_arg));
arg_deinit(str_arg);
return obj_getStr(self, "_buf");
}
char* PikaStdData_ByteArray_decode(PikaObj* self) {
uint8_t* data = obj_getBytes(self, "raw");
Arg* str_arg = arg_newStr((char*)data);
obj_removeArg(self, "_buf");
obj_setStr(self, "_buf", arg_getStr(str_arg));
arg_deinit(str_arg);
return obj_getStr(self, "_buf");
}

View File

@ -0,0 +1,293 @@
#include "PikaStdData_Dict.h"
#include "BaseObj.h"
#include "PikaObj.h"
#include "PikaStdData_Tuple.h"
#include "PikaStdData_dict_items.h"
#include "PikaStdData_dict_keys.h"
#include "PikaStdLib_SysObj.h"
#include "dataStrs.h"
Arg* PikaStdData_Dict_get(PikaObj* self, char* key) {
PikaDict* dict = obj_getPtr(self, "dict");
Arg* res = pikaDict_getArg(dict, key);
if (NULL == res) {
obj_setErrorCode(self, PIKA_RES_ERR_RUNTIME_ERROR);
__platform_printf("KeyError: %s\n", key);
}
return arg_copy(res);
}
void PikaStdData_Dict___init__(PikaObj* self) {
__vm_Dict___init__(self);
}
void PikaStdData_Dict_set(PikaObj* self, char* key, Arg* arg) {
__vm_Dict_set(self, arg, key);
}
void PikaStdData_Dict_remove(PikaObj* self, char* key) {
PikaDict* dict = obj_getPtr(self, "dict");
PikaDict* keys = obj_getPtr(self, "_keys");
pikaDict_removeArg(dict, pikaDict_getArg(dict, key));
pikaDict_removeArg(keys, pikaDict_getArg(keys, key));
}
Arg* PikaStdData_Dict___iter__(PikaObj* self) {
obj_setInt(self, "__iter_i", 0);
return arg_newRef(self);
}
Arg* PikaStdData_Dict___next__(PikaObj* self) {
int __iter_i = args_getInt(self->list, "__iter_i");
PikaDict* keys = obj_getPtr(self, "_keys");
Arg* res = arg_copy(args_getArgByIndex(&keys->super, __iter_i));
if (NULL == res) {
return arg_newNull();
}
args_setInt(self->list, "__iter_i", __iter_i + 1);
return res;
}
void PikaStdData_Dict___setitem__(PikaObj* self, Arg* __key, Arg* __val) {
PikaStdData_Dict_set(self, obj_getStr(self, "__key"),
obj_getArg(self, "__val"));
}
Arg* PikaStdData_Dict___getitem__(PikaObj* self, Arg* __key) {
return PikaStdData_Dict_get(self, obj_getStr(self, "__key"));
}
void PikaStdData_Dict___del__(PikaObj* self) {
PikaDict* dict = obj_getPtr(self, "dict");
PikaDict* keys = obj_getPtr(self, "_keys");
pikaDict_deinit(dict);
if (NULL != keys) {
pikaDict_deinit(keys);
}
}
void PikaStdData_dict_keys___init__(PikaObj* self, PikaObj* dict) {
obj_setPtr(self, "dictptr", dict);
}
PikaObj* PikaStdData_Dict_keys(PikaObj* self) {
PikaObj* dict_keys = newNormalObj(New_PikaStdData_dict_keys);
PikaStdData_dict_keys___init__(dict_keys, self);
return dict_keys;
}
PikaObj* PikaStdData_Dict_items(PikaObj* self) {
PikaObj* dict_items = newNormalObj(New_PikaStdData_dict_items);
PikaStdData_dict_keys___init__(dict_items, self);
return dict_items;
}
Arg* PikaStdData_dict_keys___iter__(PikaObj* self) {
obj_setInt(self, "__iter_i", 0);
return arg_newRef(self);
}
Arg* PikaStdData_dict_keys___next__(PikaObj* self) {
int __iter_i = args_getInt(self->list, "__iter_i");
PikaObj* dictptr = obj_getPtr(self, "dictptr");
PikaDict* keys = obj_getPtr(dictptr, "_keys");
Arg* res = arg_copy(args_getArgByIndex(&keys->super, __iter_i));
if (NULL == res) {
return arg_newNull();
}
args_setInt(self->list, "__iter_i", __iter_i + 1);
return res;
}
char* PikaStdLib_SysObj_str(PikaObj* self, Arg* arg);
char* PikaStdData_dict_keys___str__(PikaObj* self) {
Arg* str_arg = arg_newStr("dict_keys([");
PikaObj* dictptr = obj_getPtr(self, "dictptr");
PikaDict* keys = obj_getPtr(dictptr, "_keys");
int i = 0;
while (PIKA_TRUE) {
Arg* item = args_getArgByIndex(&keys->super, i);
if (NULL == item) {
break;
}
if (i != 0) {
str_arg = arg_strAppend(str_arg, ", ");
}
char* item_str = PikaStdLib_SysObj_str(self, item);
if (arg_getType(item) == ARG_TYPE_STRING) {
str_arg = arg_strAppend(str_arg, "'");
}
str_arg = arg_strAppend(str_arg, item_str);
if (arg_getType(item) == ARG_TYPE_STRING) {
str_arg = arg_strAppend(str_arg, "'");
}
i++;
}
str_arg = arg_strAppend(str_arg, "])");
obj_setStr(self, "_buf", arg_getStr(str_arg));
arg_deinit(str_arg);
return obj_getStr(self, "_buf");
}
char* PikaStdData_Dict___str__(PikaObj* self) {
Arg* str_arg = arg_newStr("{");
PikaDict* keys = obj_getPtr(self, "_keys");
PikaDict* dict = obj_getPtr(self, "dict");
pika_assert(NULL != dict);
pika_assert(NULL != keys);
int i = 0;
while (PIKA_TRUE) {
Arg* item_key = args_getArgByIndex(&keys->super, i);
Arg* item_val = args_getArgByIndex(&dict->super, i);
if (NULL == item_key) {
break;
}
if (i != 0) {
str_arg = arg_strAppend(str_arg, ", ");
}
char* key_str = PikaStdLib_SysObj_str(self, item_key);
str_arg = arg_strAppend(str_arg, "'");
str_arg = arg_strAppend(str_arg, key_str);
str_arg = arg_strAppend(str_arg, "'");
str_arg = arg_strAppend(str_arg, ": ");
char* val_str = PikaStdLib_SysObj_str(self, item_val);
if (arg_getType(item_val) == ARG_TYPE_STRING) {
str_arg = arg_strAppend(str_arg, "'");
}
str_arg = arg_strAppend(str_arg, val_str);
if (arg_getType(item_val) == ARG_TYPE_STRING) {
str_arg = arg_strAppend(str_arg, "'");
}
i++;
}
str_arg = arg_strAppend(str_arg, "}");
obj_setStr(self, "_buf", arg_getStr(str_arg));
arg_deinit(str_arg);
return obj_getStr(self, "_buf");
}
int PikaStdData_Dict___len__(PikaObj* self) {
PikaDict* dict = obj_getPtr(self, "dict");
return args_getSize(&dict->super);
}
int PikaStdData_dict_keys___len__(PikaObj* self) {
PikaObj* dictptr = obj_getPtr(self, "dictptr");
PikaDict* keys = obj_getPtr(dictptr, "_keys");
return args_getSize(&keys->super);
}
int dict_contains(PikaDict* dict, Arg* key) {
int i = 0;
while (PIKA_TRUE) {
Arg* item = args_getArgByIndex(&dict->super, i);
if (NULL == item) {
break;
}
if (arg_isEqual(item, key)) {
return PIKA_TRUE;
}
i++;
}
return PIKA_FALSE;
}
int PikaStdData_Dict___contains__(PikaObj* self, Arg* val) {
PikaDict* dict = obj_getPtr(self, "_keys");
return dict_contains(dict, val);
}
Arg* PikaStdData_dict_items___iter__(PikaObj* self) {
obj_setInt(self, "__iter_i", 0);
return arg_newRef(self);
}
int PikaStdData_dict_items___len__(PikaObj* self) {
PikaObj* dictptr = obj_getPtr(self, "dictptr");
PikaDict* keys = obj_getPtr(dictptr, "_keys");
return args_getSize(&keys->super);
}
Arg* PikaStdData_dict_items___next__(PikaObj* self) {
int __iter_i = args_getInt(self->list, "__iter_i");
PikaObj* dictptr = obj_getPtr(self, "dictptr");
PikaDict* keys = obj_getPtr(dictptr, "_keys");
PikaDict* dict = obj_getPtr(dictptr, "dict");
Arg* key = args_getArgByIndex(&keys->super, __iter_i);
Arg* val = args_getArgByIndex(&dict->super, __iter_i);
if (NULL == key) {
return arg_newNull();
}
PikaObj* tuple = newNormalObj(New_PikaStdData_Tuple);
PikaStdData_Tuple___init__(tuple);
PikaList* list = obj_getPtr(tuple, "list");
pikaList_append(list, key);
pikaList_append(list, val);
args_setInt(self->list, "__iter_i", __iter_i + 1);
return arg_newObj(tuple);
}
char* PikaStdData_dict_items___str__(PikaObj* self) {
Arg* str_arg = arg_newStr("dict_items([");
int i = 0;
obj_setInt(self, "__iter_i", 0);
while (PIKA_TRUE) {
Arg* item = PikaStdData_dict_items___next__(self);
if (arg_getType(item) == ARG_TYPE_NONE) {
arg_deinit(item);
break;
}
if (i != 0) {
str_arg = arg_strAppend(str_arg, ", ");
}
char* item_str = PikaStdLib_SysObj_str(self, item);
str_arg = arg_strAppend(str_arg, item_str);
i++;
arg_deinit(item);
}
str_arg = arg_strAppend(str_arg, "])");
obj_setStr(self, "_buf", arg_getStr(str_arg));
arg_deinit(str_arg);
return obj_getStr(self, "_buf");
}
void PikaStdData_Dict_update(PikaObj* self, PikaObj* other) {
PikaObj* context = newNormalObj(New_PikaStdLib_SysObj);
obj_setRef(context, "@other", other);
obj_setRef(context, "@self", self);
/* clang-format off */
PIKA_PYTHON(
for @item in @other:
@self[@item] = @other[@item]
)
/* clang-format on */
const uint8_t
bytes[] =
{
0x40, 0x00, 0x00, 0x00,/* instruct array size */
0x10, 0x81, 0x01, 0x00, 0x00, 0x02, 0x08, 0x00, 0x00, 0x04,
0x0d, 0x00, 0x00, 0x82, 0x11, 0x00, 0x00, 0x04, 0x1e, 0x00,
0x00, 0x0d, 0x1e, 0x00, 0x00, 0x07, 0x24, 0x00, 0x11, 0x81,
0x26, 0x00, 0x11, 0x01, 0x1e, 0x00, 0x21, 0x01, 0x01, 0x00,
0x21, 0x01, 0x1e, 0x00, 0x11, 0x1d, 0x00, 0x00, 0x01, 0x02,
0x2c, 0x00, 0x01, 0x04, 0x26, 0x00, 0x00, 0x86, 0x38, 0x00,
0x00, 0x8c, 0x0d, 0x00, /* instruct array */
0x3b, 0x00, 0x00, 0x00, /* const pool size */
0x00, 0x40, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x00, 0x69, 0x74,
0x65, 0x72, 0x00, 0x24, 0x6c, 0x30, 0x00, 0x24, 0x6c, 0x30,
0x2e, 0x5f, 0x5f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x5f, 0x00,
0x40, 0x69, 0x74, 0x65, 0x6d, 0x00, 0x32, 0x00, 0x40, 0x73,
0x65, 0x6c, 0x66, 0x00, 0x5f, 0x5f, 0x73, 0x65, 0x74, 0x69,
0x74, 0x65, 0x6d, 0x5f, 0x5f, 0x00, 0x2d, 0x31, 0x00, /* const
pool */
};
pikaVM_runByteCode(context, (uint8_t*)bytes);
obj_deinit(context);
}

View File

@ -0,0 +1,247 @@
#include "PikaStdData_FILEIO.h"
#include <stdio.h>
#include "PikaCompiler.h"
#include "PikaStdData_List.h"
typedef struct {
uint8_t* addr;
size_t size;
size_t pos;
} PIKAFS_FILE;
int PikaStdData_FILEIO_init(PikaObj* self, char* path, char* mode) {
if (obj_isArgExist(self, "_f")) {
/* already initialized */
return 0;
}
if (strIsStartWith(path, "pikafs/")) {
PIKAFS_FILE* f = (PIKAFS_FILE*)pikaMalloc(sizeof(PIKAFS_FILE));
memset(f, 0, sizeof(PIKAFS_FILE));
extern volatile PikaObj* __pikaMain;
uint8_t* library_bytes = obj_getPtr((PikaObj*)__pikaMain, "@libraw");
if (NULL == library_bytes) {
return 1;
}
char* file_name = path + 7;
if (PIKA_RES_OK != _loadModuleDataWithName(library_bytes, file_name,
&f->addr, &f->size)) {
return 1;
}
obj_setInt(self, "pikafs", PIKA_TRUE);
obj_setPtr(self, "_f", f);
obj_setStr(self, "_mode", mode);
return 0;
}
FILE* f = __platform_fopen(path, mode);
if (f == NULL) {
return 1;
}
obj_setPtr(self, "_f", f);
obj_setStr(self, "_mode", mode);
return 0;
}
void PikaStdData_FILEIO_close(PikaObj* self) {
if (PIKA_TRUE == obj_getInt(self, "pikafs")) {
PIKAFS_FILE* f = obj_getPtr(self, "_f");
if (NULL == f) {
return;
}
pikaFree(f, sizeof(PIKAFS_FILE));
obj_setPtr(self, "_f", NULL);
return;
}
FILE* f = obj_getPtr(self, "_f");
if (NULL == f) {
return;
}
__platform_fclose(f);
obj_setPtr(self, "_f", NULL);
}
size_t _pikafs_fread(void* buf, size_t size, size_t count, PIKAFS_FILE* f) {
if (f->pos >= f->size) {
return 0;
}
if (f->pos + size * count > f->size) {
count = (f->size - f->pos) / size;
}
__platform_memcpy(buf, f->addr + f->pos, size * count);
f->pos += size * count;
return count;
}
Arg* PikaStdData_FILEIO_read(PikaObj* self, PikaTuple* size_) {
int size = 0;
if (pikaTuple_getSize(size_) == 0) {
size = -1;
} else {
size = pikaTuple_getInt(size_, 0);
}
if (size <= 0) {
/* read all */
size = PIKA_READ_FILE_BUFF_SIZE;
}
Arg* buf_arg = arg_newBytes(NULL, size);
uint8_t* buf = arg_getBytes(buf_arg);
int n = 0;
/* read */
if (PIKA_TRUE == obj_getInt(self, "pikafs")) {
PIKAFS_FILE* f = obj_getPtr(self, "_f");
if (NULL == f) {
return NULL;
}
n = _pikafs_fread(buf, 1, size, f);
} else {
FILE* f = obj_getPtr(self, "_f");
if (f == NULL) {
return NULL;
}
n = __platform_fread(buf, 1, size, f);
}
if (n < size) {
/* EOF */
buf[n] = '\0';
}
char* mode = obj_getStr(self, "_mode");
if (strIsContain(mode, 'b')) {
/* binary */
Arg* res = arg_newBytes(buf, n);
arg_deinit(buf_arg);
return res;
} else {
/* text */
Arg* res = arg_newStr((char*)buf);
arg_deinit(buf_arg);
return res;
}
}
int PikaStdData_FILEIO_write(PikaObj* self, Arg* s) {
if (PIKA_TRUE == obj_getInt(self, "pikafs")) {
return 1;
}
FILE* f = obj_getPtr(self, "_f");
int res = -1;
if (f == NULL) {
obj_setErrorCode(self, PIKA_RES_ERR_IO);
__platform_printf("Error: can't write to file\n");
return res;
}
char* mode = obj_getStr(self, "_mode");
if (strIsContain(mode, 'b')) {
if (arg_getType(s) != ARG_TYPE_BYTES) {
__platform_printf(
"TypeError: a bytes-like object is required, not 'str'\r\n");
obj_setErrorCode(self, PIKA_RES_ERR_INVALID_PARAM);
return -1;
}
/* binary */
res = __platform_fwrite(arg_getBytes(s), 1, arg_getBytesSize(s), f);
} else {
/* text */
char* str = arg_getStr(s);
res = __platform_fwrite(str, 1, strlen(str), f);
}
return res;
}
int PikaStdData_FILEIO_seek(PikaObj* self, int offset, PikaTuple* fromwhere) {
FILE* f = obj_getPtr(self, "_f");
if (f == NULL) {
obj_setErrorCode(self, PIKA_RES_ERR_IO);
__platform_printf("Error: can't seek in file\n");
return -1;
}
if (pikaTuple_getSize(fromwhere) == 1) {
int whence = pikaTuple_getInt(fromwhere, 0);
__platform_fseek(f, offset, whence);
return __platform_ftell(f);
}
__platform_fseek(f, offset, 0);
return __platform_ftell(f);
}
int PikaStdData_FILEIO_tell(PikaObj* self) {
FILE* f = obj_getPtr(self, "_f");
if (f == NULL) {
obj_setErrorCode(self, PIKA_RES_ERR_IO);
__platform_printf("Error: can't tell in file\n");
return -1;
}
return __platform_ftell(f);
}
char* PikaStdData_FILEIO_readline(PikaObj* self) {
FILE* f = obj_getPtr(self, "_f");
if (f == NULL) {
obj_setErrorCode(self, PIKA_RES_ERR_IO);
__platform_printf("Error: can't read line from file\n");
return NULL;
}
obj_setBytes(self, "_line_buff", NULL, PIKA_LINE_BUFF_SIZE);
char* line_buff = (char*)obj_getBytes(self, "_line_buff");
while (1) {
char char_buff[2] = {0};
int n = __platform_fread(char_buff, 1, 1, f);
if (n == 0) {
/* EOF */
return NULL;
}
if (char_buff[0] == '\n') {
/* end of line */
strAppend(line_buff, char_buff);
return line_buff;
}
if (strGetSize(line_buff) >= PIKA_LINE_BUFF_SIZE) {
/* line too long */
obj_setErrorCode(self, PIKA_RES_ERR_IO);
__platform_printf("Error: line too long\n");
return NULL;
}
strAppend(line_buff, char_buff);
}
}
PikaObj* PikaStdData_FILEIO_readlines(PikaObj* self) {
FILE* f = obj_getPtr(self, "_f");
if (f == NULL) {
obj_setErrorCode(self, PIKA_RES_ERR_IO);
__platform_printf("Error: can't read lines from file\n");
return NULL;
}
PikaObj* line_list = newNormalObj(New_PikaStdData_List);
PikaStdData_List___init__(line_list);
while (1) {
char* line = PikaStdData_FILEIO_readline(self);
if (line == NULL) {
break;
}
Arg* arg_str = arg_newStr(line);
PikaStdData_List_append(line_list, arg_str);
arg_deinit(arg_str);
}
return line_list;
}
void PikaStdData_FILEIO_writelines(PikaObj* self, PikaObj* lines) {
FILE* f = obj_getPtr(self, "_f");
if (f == NULL) {
obj_setErrorCode(self, PIKA_RES_ERR_IO);
__platform_printf("Error: can't write lines to file\n");
return;
}
PikaList* list = obj_getPtr(lines, "list");
if (list == NULL) {
obj_setErrorCode(self, PIKA_RES_ERR_IO);
__platform_printf("Error: can't write lines to file\n");
return;
}
for (size_t i = 0; i < pikaList_getSize(list); i++) {
char* line = pikaList_getStr(list, i);
Arg* arg_str = arg_newStr(line);
PikaStdData_FILEIO_write(self, arg_str);
arg_deinit(arg_str);
}
return;
}

View File

@ -0,0 +1,98 @@
#include "PikaStdData_List.h"
#include "BaseObj.h"
#include "PikaObj.h"
#include "PikaStdData_Tuple.h"
#include "dataStrs.h"
void PikaStdData_List_append(PikaObj* self, Arg* arg) {
__vm_List_append(self, arg);
}
void PikaStdData_List_set(PikaObj* self, int i, Arg* arg) {
PikaList* list = obj_getPtr(self, "list");
if (PIKA_RES_OK != pikaList_setArg(list, i, arg)) {
obj_setErrorCode(self, 1);
obj_setSysOut(self, "Error: index exceeded lengh of list.");
}
}
void PikaStdData_List___setitem__(PikaObj* self, Arg* __key, Arg* __val) {
PikaStdData_List_set(self, obj_getInt(self, "__key"),
obj_getArg(self, "__val"));
}
void PikaStdData_List___init__(PikaObj* self) {
__vm_List___init__(self);
}
char* PikaStdLib_SysObj_str(PikaObj* self, Arg* arg);
char* PikaStdData_List___str__(PikaObj* self) {
Arg* str_arg = arg_newStr("[");
PikaList* list = obj_getPtr(self, "list");
int i = 0;
while (PIKA_TRUE) {
Arg* item = pikaList_getArg(list, i);
if (NULL == item) {
break;
}
if (i != 0) {
str_arg = arg_strAppend(str_arg, ", ");
}
char* item_str = PikaStdLib_SysObj_str(self, item);
if (arg_getType(item) == ARG_TYPE_STRING) {
str_arg = arg_strAppend(str_arg, "'");
}
str_arg = arg_strAppend(str_arg, item_str);
if (arg_getType(item) == ARG_TYPE_STRING) {
str_arg = arg_strAppend(str_arg, "'");
}
i++;
}
str_arg = arg_strAppend(str_arg, "]");
obj_setStr(self, "_buf", arg_getStr(str_arg));
arg_deinit(str_arg);
return obj_getStr(self, "_buf");
}
void PikaStdData_List_reverse(PikaObj* self) {
PikaList* list = obj_getPtr(self, "list");
pikaList_reverse(list);
}
PikaObj* PikaStdData_List___add__(PikaObj* self, PikaObj* others) {
PikaObj* res = newNormalObj(New_PikaStdData_List);
PikaStdData_List___init__(res);
PikaList* list_res = obj_getPtr(res, "list");
PikaList* list1 = obj_getPtr(self, "list");
PikaList* list2 = obj_getPtr(others, "list");
for (size_t i = 0; i < pikaList_getSize(list1); i++) {
Arg* arg = pikaList_getArg(list1, i);
pikaList_append(list_res, arg);
}
for (size_t i = 0; i < pikaList_getSize(list2); i++) {
Arg* arg = pikaList_getArg(list2, i);
pikaList_append(list_res, arg);
}
return res;
}
void PikaStdData_List_insert(PikaObj *self, int i, Arg* arg){
PikaList* list = obj_getPtr(self, "list");
if (PIKA_RES_OK != pikaList_insert(list, i, arg)) {
obj_setErrorCode(self, 1);
obj_setSysOut(self, "Error: index exceeded lengh of list.");
}
}
Arg* PikaStdData_List_pop(PikaObj *self){
PikaList* list = obj_getPtr(self, "list");
return pikaList_pop(list);
}
void PikaStdData_List_remove(PikaObj *self, Arg* val){
PikaList* list = obj_getPtr(self, "list");
pikaList_remove(list, val);
}

View File

@ -0,0 +1,817 @@
#include "PikaStdData_String.h"
#include "PikaStdData_List.h"
#include "PikaStdData_String_Util.h"
#include "dataStrs.h"
char* _strlwr(char* str);
static int string_len(char* str);
Arg* PikaStdData_String___iter__(PikaObj* self) {
obj_setInt(self, "__iter_i", 0);
return arg_newRef(self);
}
void PikaStdData_String_set(PikaObj* self, char* s) {
#if PIKA_STRING_UTF8_ENABLE
int r = _valid_utf8(s, -1);
if (r >= 0) {
obj_setErrorCode(self, __LINE__);
__platform_printf("Error invaliad character %x\r\n", s[r]);
return;
}
#endif
obj_setStr(self, "str", s);
}
void PikaStdData_String___init__(PikaObj* self, char* s) {
#if PIKA_STRING_UTF8_ENABLE
int r = _valid_utf8(s, -1);
if (r >= 0) {
obj_setErrorCode(self, __LINE__);
__platform_printf("Error invaliad character %x\r\n", s[r]);
return;
}
#endif
PikaStdData_String_set(self, s);
}
char* PikaStdData_String_get(PikaObj* self) {
return obj_getStr(self, "str");
}
Arg* PikaStdData_String___next__(PikaObj* self) {
int __iter_i = args_getInt(self->list, "__iter_i");
char* str = obj_getStr(self, "str");
uint16_t len = strGetSize(str);
#if PIKA_STRING_UTF8_ENABLE
char char_buff[5];
int r = _utf8_get(str, len, __iter_i, char_buff);
if (r < 0) {
return arg_newNull();
}
args_setInt(self->list, "__iter_i", __iter_i + 1);
return arg_newStr((char*)char_buff);
#else
Arg* res = NULL;
char char_buff[] = " ";
if (__iter_i < len) {
char_buff[0] = str[__iter_i];
res = arg_newStr((char*)char_buff);
} else {
return arg_newNull();
}
args_setInt(self->list, "__iter_i", __iter_i + 1);
return res;
#endif
}
static int _str_get(char* str, int key_i, char* char_buff) {
uint16_t len = strGetSize(str);
if (key_i < 0) {
key_i = string_len(str) + key_i;
}
#if PIKA_STRING_UTF8_ENABLE
return _utf8_get(str, len, key_i, char_buff);
#else
if (key_i < len) {
char_buff[0] = str[key_i];
return 0;
}
return -1;
#endif
}
char* string_slice(Args* outBuffs, char* str, int start, int end) {
char* res = args_getBuff(outBuffs, strGetSize(str));
if (start < 0) {
start += string_len(str);
}
/* magic code, to the end */
if (end == -99999) {
end = string_len(str);
}
if (end < 0) {
end += string_len(str);
}
for (int i = start; i < end; i++) {
char char_buff[5] = {0};
int r = _str_get(str, i, char_buff);
if (r < 0) {
return NULL;
}
res = strAppend(res, char_buff);
}
return res;
}
Arg* PikaStdData_String___getitem__(PikaObj* self, Arg* __key) {
int key_i = arg_getInt(__key);
char* str = obj_getStr(self, "str");
char char_buff[5] = {0};
int r = _str_get(str, key_i, char_buff);
if (r < 0) {
return arg_newNull();
}
return arg_newStr((char*)char_buff);
}
void PikaStdData_String___setitem__(PikaObj* self, Arg* __key, Arg* __val) {
int key_i = arg_getInt(__key);
char* str = obj_getStr(self, "str");
char* val = arg_getStr(__val);
uint16_t len = strGetSize(str);
#if PIKA_STRING_UTF8_ENABLE
int len2 = strlen(val);
int is_invalid = _valid_utf8(val, len2);
if (is_invalid >= 0) {
obj_setErrorCode(self, __LINE__);
__platform_printf("Error String invalid\r\n");
return;
}
int ulen_val = _utf8_strlen(val, len2);
if (ulen_val != 1) {
obj_setErrorCode(self, __LINE__);
__platform_printf("Error String invalid char\r\n");
return;
}
int char_len;
int repl_at = _utf8_get_offset(str, len, key_i, &char_len);
if (repl_at < 0) {
obj_setErrorCode(self, __LINE__);
__platform_printf("Error String Overflow\r\n");
return;
}
int ok = __str_repl(self, str, len, repl_at, char_len, val, len2);
if (ok < 0) {
obj_setErrorCode(self, __LINE__);
__platform_printf("Error. Internal error(-%d)\r\n", __LINE__);
return;
}
#else
if (key_i >= len) {
obj_setErrorCode(self, 1);
__platform_printf("Error String Overflow\r\n");
return;
}
str[key_i] = val[0];
#endif
}
char* PikaStdData_String___str__(PikaObj* self) {
return obj_getStr(self, "str");
}
int PikaStdData_String_startswith(PikaObj* self, char* prefix) {
char* str = obj_getStr(self, "str");
char* p = prefix;
int i = 0;
while (*p != '\0') {
if (*p != str[i])
return 0;
p++;
i++;
}
return 1;
}
int PikaStdData_String_endswith(PikaObj* self, char* suffix) {
char* str = obj_getStr(self, "str");
int len1 = strlen(str);
int len2 = strlen(suffix);
while (len2 >= 1) {
if (suffix[len2 - 1] != str[len1 - 1])
return 0;
len2--;
len1--;
}
return 1;
}
int PikaStdData_String_isdigit(PikaObj* self) {
char* str = obj_getStr(self, "str");
int i = 0;
while (str[i] != '\0') {
if (!isdigit((int)str[i]))
return 0;
i++;
}
return 1;
}
int PikaStdData_String_islower(PikaObj* self) {
char* str = obj_getStr(self, "str");
int i = 0;
while (str[i] != '\0') {
if (!islower((int)str[i]))
return 0;
i++;
}
return 1;
}
int PikaStdData_String_isalnum(PikaObj* self) {
char* str = obj_getStr(self, "str");
int i = 0;
while (str[i] != '\0') {
if (!isalnum((int)str[i]))
return 0;
i++;
}
return 1;
}
int PikaStdData_String_isalpha(PikaObj* self) {
char* str = obj_getStr(self, "str");
int i = 0;
while (str[i] != '\0') {
if (!isalpha((int)str[i]))
return 0;
i++;
}
return 1;
}
int PikaStdData_String_isspace(PikaObj* self) {
char* str = obj_getStr(self, "str");
int i = 0;
while (str[i] != '\0') {
if (!isspace((int)str[i]))
return 0;
i++;
}
return 1;
}
PikaObj* PikaStdData_String_split(PikaObj* self, char* s) {
/* 创建 list 对象 */
PikaObj* list = newNormalObj(New_PikaStdData_List);
/* 初始化 list */
PikaStdData_List___init__(list);
Args buffs = {0};
char* str = strsCopy(&buffs, obj_getStr(self, "str"));
char sign = s[0];
int token_num = strCountSign(str, sign) + 1;
for (int i = 0; i < token_num; i++) {
char* token = strsPopToken(&buffs, &str, sign);
/* 用 arg_set<type> 的 api 创建 arg */
Arg* token_arg = arg_newStr(token);
/* 添加到 list 对象 */
PikaStdData_List_append(list, token_arg);
/* 销毁 arg */
arg_deinit(token_arg);
}
strsDeinit(&buffs);
return list;
}
static int string_len(char* str) {
#if PIKA_STRING_UTF8_ENABLE
int n = _utf8_strlen(str, -1);
return n;
#else
return strGetSize(str);
#endif
}
int PikaStdData_String___len__(PikaObj* self) {
char* str = obj_getStr(self, "str");
int n = string_len(str);
if (n < 0) {
obj_setErrorCode(self, __LINE__);
__platform_printf("Error. Internal error(%d)\r\n", __LINE__);
}
return n;
}
char* PikaStdData_String_strip(PikaObj* self, PikaTuple* chrs) {
Args buffs = {0};
char to_strip = ' ';
if (pikaTuple_getSize(chrs) > 1) {
obj_setErrorCode(self, PIKA_RES_ERR_INVALID_PARAM);
obj_setSysOut(self, "Error. Invalid param");
}
if (pikaTuple_getSize(chrs) == 1) {
char* ch_str = pikaTuple_getStr(chrs, 0);
to_strip = ch_str[0];
}
char* str = strsCopy(&buffs, obj_getStr(self, "str"));
/* strip */
char* str_start = str;
size_t len = strlen(str);
for (size_t i = 0; i < len; i++) {
if (str[i] != to_strip) {
str_start = (char*)(str + i);
break;
}
}
len = strlen(str);
for (int i = len - 1; i >= 0; i--) {
if (str[i] != to_strip) {
str[i + 1] = '\0';
break;
}
}
obj_setStr(self, "_buf", str_start);
strsDeinit(&buffs);
return obj_getStr(self, "_buf");
}
char* PikaStdData_String_replace(PikaObj* self, char* old, char* new) {
Args buffs = {0};
char* str = strsCopy(&buffs, obj_getStr(self, "str"));
str = strsReplace(&buffs, str, old, new);
obj_setStr(self, "_buf", str);
strsDeinit(&buffs);
return obj_getStr(self, "_buf");
}
Arg* PikaStdData_String_encode(PikaObj* self, PikaTuple* encoding) {
char* str = obj_getStr(self, "str");
#if PIKA_STRING_UTF8_ENABLE
char* to_code = NULL;
int argn = pikaTuple_getSize(encoding);
if (argn < 1) {
return arg_newBytes((uint8_t*)str, strGetSize(str));
}
Arg* arg_i = pikaTuple_getArg(encoding, 0);
if (arg_getType(arg_i) != ARG_TYPE_STRING) {
obj_setErrorCode(self, __LINE__);
__platform_printf("Error invaliad arguments\r\n");
return NULL;
}
to_code = arg_getStr(arg_i);
_strlwr(to_code);
Arg* res = _str_encode(str, to_code);
if (!res) {
obj_setErrorCode(self, __LINE__);
__platform_printf("Error internal error\r\n");
return NULL;
}
return res;
#else
return arg_newBytes((uint8_t*)str, strGetSize(str));
#endif
}
#if PIKA_STRING_UTF8_ENABLE
static const uint8_t _pcre_utf8_table4[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5};
const char mask1 = 0x80;
const char mask2 = 0xc0;
const char mask3 = 0xe0;
const char mask4 = 0xf0;
const char nmask1 = 0x3f;
const char nmask2 = 0x1f;
const char nmask3 = 0x0f;
const char nmask4 = 0x07;
int _valid_utf8(const char* string, int length) {
const uint8_t* p;
if (length < 0) {
length = strlen(string);
}
for (p = (const uint8_t*)string; length-- > 0; p++) {
int ab;
int c = *p;
if (!(c & 0x80))
continue;
if (c < 0xc0)
return (uintptr_t)p - (uintptr_t)string;
ab = _pcre_utf8_table4[c & 0x3f];
if (length < ab || ab > 3)
return (uintptr_t)p - (uintptr_t)string;
length -= ab;
if ((*(++p) & 0xc0) != 0x80)
return (uintptr_t)p - (uintptr_t)string;
switch (ab) {
case 1:
if ((c & 0x3e) == 0)
return (uintptr_t)p - (uintptr_t)string;
continue;
case 2:
if ((c == 0xe0 && (*p & 0x20) == 0) ||
(c == 0xed && *p >= 0xa0))
return (uintptr_t)p - (uintptr_t)string;
break;
case 3:
if ((c == 0xf0 && (*p & 0x30) == 0) || (c > 0xf4) ||
(c == 0xf4 && *p > 0x8f))
return (uintptr_t)p - (uintptr_t)string;
break;
}
while (--ab > 0) {
if ((*(++p) & 0xc0) != 0x80)
return (uintptr_t)p - (uintptr_t)string;
}
}
return -1;
}
int _utf8_get(const char* string, int length, int at, char* out_buf) {
const uint8_t* p;
int ab, c;
if (length < 0) {
length = strlen(string);
}
if (at < 0 || at >= length)
return -1;
for (p = (const uint8_t*)string; length > 0 && at; p++, at--) {
c = *p;
if (!(c & 0x80)) {
length--;
continue;
}
ab = _pcre_utf8_table4[c & 0x3f];
p += ab++;
length -= ab;
}
if (at || length <= 0)
return -2;
c = *p;
if (!(c & 0x80)) {
*out_buf = c;
out_buf[1] = 0;
return 1;
};
ab = _pcre_utf8_table4[c & 0x3f] + 1;
__platform_memcpy(out_buf, p, ab);
out_buf[ab] = '\0';
return ab;
}
int _utf8_get_offset(const char* string,
int length,
int at,
int* out_char_len) {
const uint8_t* p;
int ab, c;
if (length < 0) {
length = strlen(string);
}
if (at < 0 || at >= length)
return -1;
for (p = (const uint8_t*)string; length > 0 && at; p++, at--) {
c = *p;
if (!(c & 0x80)) {
length--;
continue;
}
ab = _pcre_utf8_table4[c & 0x3f];
p += ab++;
length -= ab;
}
if (at)
return -2;
c = *p;
if (!(c & 0x80)) {
if (out_char_len)
*out_char_len = 1;
return (uintptr_t)p - (uintptr_t)string;
};
ab = _pcre_utf8_table4[c & 0x3f] + 1;
if (out_char_len)
*out_char_len = ab;
return (uintptr_t)p - (uintptr_t)string;
}
int _utf8_strlen(const char* string, int length) {
const uint8_t* p;
int i, ab, c;
if (length < 0) {
length = strlen(string);
}
for (i = 0, p = (const uint8_t*)string; length > 0; i++, p++) {
c = *p;
if (!(c & 0x80)) {
length--;
continue;
}
ab = _pcre_utf8_table4[c & 0x3f];
p += ab++;
length -= ab;
}
if (length < 0)
return -1;
return i;
}
int __str_repl(PikaObj* self,
char* str,
int str_len,
int repl_at,
int repl_len,
char* val,
int val_len) {
if (val_len > repl_len) {
str[repl_at] = 0;
Arg* s_new = arg_newStr(str);
if (!s_new)
return -1;
s_new = arg_strAppend(s_new, val);
s_new = arg_strAppend(s_new, str + repl_at + repl_len);
obj_removeArg(self, "str");
int rs = obj_setArg(self, "str", s_new);
arg_deinit(s_new);
if (rs)
return -rs;
return 0;
}
char* s = str + repl_at;
__platform_memcpy(s, val, val_len);
__platform_memmove(s + val_len, s + repl_len,
str_len - repl_at - repl_len + 1);
return 0;
}
int __utf8_to_utf32_char_LE(const char* utf8, char* out_buf) {
char c = *utf8;
if (!(c & mask1)) {
*out_buf = c;
out_buf[1] = 0;
out_buf[2] = 0;
out_buf[3] = 0;
return 1;
}
int left_length = _pcre_utf8_table4[c & 0x3f];
char a, b, d;
switch (left_length) {
case 1:
a = c & nmask2;
b = utf8[1] & nmask1;
out_buf[0] = b | a << 6;
out_buf[1] = a >> 2;
out_buf[2] = 0;
out_buf[3] = 0;
return 2;
case 2:
a = c & nmask3;
b = utf8[1] & nmask1;
c = utf8[2] & nmask1;
out_buf[0] = c | b << 6;
out_buf[1] = b >> 2 | a << 4;
out_buf[2] = 0;
out_buf[3] = 0;
return 3;
case 3:
a = c & nmask4;
b = utf8[1] & nmask1;
c = utf8[2] & nmask1;
d = utf8[3] & nmask1;
out_buf[0] = d | c << 6;
out_buf[1] = c >> 2 | b << 4;
out_buf[2] = b >> 4 | a << 2;
out_buf[3] = 0;
return 4;
default:
return 0;
}
}
int __utf8_to_utf32_LE_noBOM_get_size(const char* utf8, int len) {
char* p = (char*)utf8;
char buf[4];
int space_sum = 0;
while (len > 0) {
int size = __utf8_to_utf32_char_LE(p, buf);
if (!size)
return -1;
p += size;
len -= size;
space_sum++;
}
return space_sum * 4;
}
int __utf8_to_utf32_LE_noBOM(const char* utf8, int len, char* out_buf) {
char* q = out_buf;
char* p = (char*)utf8;
while (len > 0) {
int size = __utf8_to_utf32_char_LE(p, q);
if (!size)
return -1;
p += size;
len -= size;
q += 4;
}
return q - out_buf;
}
int __utf8_to_utf32_LE_withBOM(const char* utf8, int len, char* out_buf) {
int size = __utf8_to_utf32_LE_noBOM(utf8, len, out_buf + 4);
if (size < 0) {
return size;
}
out_buf[0] = '\xff';
out_buf[1] = '\xfe';
out_buf[2] = 0;
out_buf[3] = 0;
return size + 4;
}
int32_t __utf8_decode(const char* utf8, int left_length) {
int ucode = -1;
char c = *utf8;
if (!(c & mask1)) {
return c;
}
char a, b, d;
switch (left_length) {
case 1:
a = c & nmask2;
b = utf8[1] & nmask1;
ucode = b | (a & 0x03) << 6;
ucode |= (a >> 2) << 8;
break;
case 2:
a = c & nmask3;
b = utf8[1] & nmask1;
c = utf8[2] & nmask1;
ucode = c | (b & 0x03) << 6;
ucode |= (b >> 2 | a << 4) << 8;
break;
case 3:
a = c & nmask4;
b = utf8[1] & nmask1;
c = utf8[2] & nmask1;
d = utf8[3] & nmask1;
ucode = d | (c & 0x03) << 6;
ucode |= (c >> 2 | (b & 0x0f) << 4) << 8;
ucode |= (b >> 4 | a << 2) << 16;
break;
default:
return -1;
}
return ucode;
}
int __unicode_to_utf16_char_LE(int32_t u, char* out_buf) {
if (!(u & 0xffff0000)) {
out_buf[0] = u & 0xff;
out_buf[1] = (u & 0xff00) >> 8;
return 2;
}
int32_t d = u - 0x10000;
int32_t L = d & 0x3ff;
int32_t U = d >> 10;
L = L | 0xdc00;
U = U | 0xd800;
out_buf[0] = U & 0xff;
out_buf[1] = (U & 0xff00) >> 8;
out_buf[2] = L & 0xff;
out_buf[3] = (L & 0xff00) >> 8;
return 4;
}
int __utf8_to_utf16_LE_noBOM(const char* utf8, int len, char* out_buf) {
char* q = out_buf;
char* p = (char*)utf8;
while (len > 0) {
char c = *p;
int32_t ucode;
if (!(c & mask1)) {
ucode = c;
p++;
len--;
} else {
int left_size = _pcre_utf8_table4[c & 0x3f];
ucode = __utf8_decode(p, left_size++);
if (ucode < 0)
return ucode;
p += left_size;
len -= left_size;
}
int size = __unicode_to_utf16_char_LE(ucode, q);
q += size;
}
return q - out_buf;
}
int __utf8_to_utf16_LE_noBOM_get_size(const char* utf8, int len) {
char out_buf[4];
char* p = (char*)utf8;
int need_space = 0;
while (len > 0) {
char c = *p;
int32_t ucode;
if (!(c & mask1)) {
ucode = c;
p++;
len--;
} else {
int left_size = _pcre_utf8_table4[c & 0x3f];
ucode = __utf8_decode(p, left_size++);
if (ucode < 0)
return ucode;
p += left_size;
len -= left_size;
}
int size = __unicode_to_utf16_char_LE(ucode, out_buf);
need_space += size;
}
return need_space;
}
int __utf8_to_utf16_LE_withBOM(const char* utf8, int len, char* out_buf) {
int size = __utf8_to_utf16_LE_noBOM(utf8, len, out_buf + 2);
if (size < 0) {
return size;
}
out_buf[0] = '\xff';
out_buf[1] = '\xfe';
return size + 2;
}
Arg* _str_encode(char* str, char* encoding) {
if (strEqu(encoding, "utf-8")) {
return arg_newBytes((uint8_t*)str, strGetSize(str));
}
int len = strlen(str);
if (strEqu(encoding, "ascii")) {
int ulen = _utf8_strlen(str, len);
if (ulen == len) {
return arg_newBytes((uint8_t*)str, strGetSize(str));
}
__platform_printf("Warning there is non-ascii characters\r\n");
char* b = (char*)pikaMalloc(len + 1);
if (!b) {
return NULL;
}
char* p = str;
char* q = b;
char c = *p++;
while (c) {
if (!(c & 0x80)) {
*q++ = c;
}
c = *p++;
}
*q = 0;
Arg* arg = arg_newBytes((uint8_t*)b, strGetSize(b));
pikaFree(b, len + 1);
return arg;
}
if (strEqu(encoding, "utf-16")) {
int size_needed = __utf8_to_utf16_LE_noBOM_get_size(str, len);
if (size_needed <= 0) {
return NULL;
}
size_needed += 2;
char* b = (char*)pikaMalloc(size_needed);
if (!b) {
return NULL;
}
int ok = __utf8_to_utf16_LE_withBOM(str, len, b);
if (ok < 0) {
pikaFree(b, size_needed);
return NULL;
}
Arg* arg = arg_newBytes((uint8_t*)b, size_needed);
pikaFree(b, size_needed);
return arg;
}
if (strEqu(encoding, "utf-32")) {
int size_needed = __utf8_to_utf32_LE_noBOM_get_size(str, len);
if (size_needed <= 0) {
return NULL;
}
size_needed += 4;
char* b = (char*)pikaMalloc(size_needed);
if (!b) {
return NULL;
}
int ok = __utf8_to_utf32_LE_withBOM(str, len, b);
if (ok < 0) {
pikaFree(b, size_needed);
return NULL;
}
Arg* arg = arg_newBytes((uint8_t*)b, size_needed);
pikaFree(b, size_needed);
return arg;
}
return NULL;
}
char* _strlwr(char* str) {
int i = 0;
while (str[i] != '\0') {
str[i] = tolower((int)str[i]);
i++;
}
return str;
}
#endif
char* PikaStdData_String_format(PikaObj* self, PikaTuple* vars) {
/* 'test{}'.format(123) */
return NULL;
}

View File

@ -0,0 +1,20 @@
#include <ctype.h>
#if PIKA_STRING_UTF8_ENABLE
int _valid_utf8(const char *string, int length);
int _utf8_get(const char *string, int length, int at, char *out_buf);
int _utf8_get_offset(const char *string, int length, int at, int *out_char_len);
int _utf8_strlen(const char *string, int length);
int __str_repl(PikaObj *self, char *str, int str_len, int repl_at, int repl_len, char *val, int val_len);
int __utf8_to_utf32_LE_withBOM(const char *utf8, int len, char *out_buf);
int __utf8_to_utf32_LE_noBOM(const char *utf8, int len, char *out_buf);
int __utf8_to_utf32_LE_noBOM_get_size(const char *utf8, int len);
int __utf8_to_utf16_LE_withBOM(const char *utf8, int len, char *out_buf);
int __utf8_to_utf16_LE_noBOM(const char *utf8, int len, char *out_buf);
int __utf8_to_utf16_LE_noBOM_get_size(const char *utf8, int len);
Arg* _str_encode(char*str, char*encoding);
#endif

View File

@ -0,0 +1,87 @@
#include "PikaStdData_Tuple.h"
#include "PikaVM.h"
#include "dataStrs.h"
int PikaStdData_Tuple_len(PikaObj* self) {
PikaList* list = obj_getPtr(self, "list");
return pikaList_getSize(list);
}
Arg* PikaStdData_Tuple_get(PikaObj* self, int i) {
PikaList* list = obj_getPtr(self, "list");
return arg_copy(pikaList_getArg(list, i));
}
void PikaStdData_Tuple___init__(PikaObj* self) {
__vm_List___init__(self);
}
Arg* PikaStdData_Tuple___iter__(PikaObj* self) {
obj_setInt(self, "__iter_i", 0);
return arg_newRef(self);
}
Arg* PikaStdData_Tuple___next__(PikaObj* self) {
int __iter_i = args_getInt(self->list, "__iter_i");
Arg* res = PikaStdData_Tuple_get(self, __iter_i);
if (NULL == res) {
return arg_newNull();
}
args_setInt(self->list, "__iter_i", __iter_i + 1);
return res;
}
Arg* PikaStdData_Tuple___getitem__(PikaObj* self, Arg* __key) {
return PikaStdData_Tuple_get(self, arg_getInt(__key));
}
void PikaStdData_Tuple___del__(PikaObj* self) {
Args* list = obj_getPtr(self, "list");
args_deinit(list);
}
char* PikaStdLib_SysObj_str(PikaObj* self, Arg* arg);
char* PikaStdData_Tuple___str__(PikaObj* self) {
Arg* str_arg = arg_newStr("(");
PikaList* list = obj_getPtr(self, "list");
int i = 0;
while (PIKA_TRUE) {
Arg* item = pikaList_getArg(list, i);
if (NULL == item) {
break;
}
if (i != 0) {
str_arg = arg_strAppend(str_arg, ", ");
}
char* item_str = PikaStdLib_SysObj_str(self, item);
if (arg_getType(item) == ARG_TYPE_STRING) {
str_arg = arg_strAppend(str_arg, "'");
}
str_arg = arg_strAppend(str_arg, item_str);
if (arg_getType(item) == ARG_TYPE_STRING) {
str_arg = arg_strAppend(str_arg, "'");
}
i++;
}
str_arg = arg_strAppend(str_arg, ")");
obj_setStr(self, "_buf", arg_getStr(str_arg));
arg_deinit(str_arg);
return obj_getStr(self, "_buf");
}
int PikaStdData_Tuple___len__(PikaObj* self) {
return PikaStdData_Tuple_len(self);
}
int PikaStdData_Tuple___contains__(PikaObj* self, Arg* val) {
PikaList* list = obj_getPtr(self, "list");
for (size_t i = 0; i < pikaList_getSize(list); i++) {
Arg* arg = pikaList_getArg(list, i);
if (arg_isEqual(arg, val)) {
return 1;
}
}
return 0;
}

View File

@ -0,0 +1,14 @@
#include "PikaStdData_Utils.h"
#include "dataStrs.h"
Arg* PikaStdData_Utils_int_to_bytes(PikaObj* self, int val) {
if (val > 0xFF) {
obj_setErrorCode(self, 1);
__platform_printf(
"OverflowError: cannot convert value larger than 0xFF to "
"bytes\r\n");
return arg_newNull();
}
uint8_t val_bytes = (uint8_t)val;
return arg_newBytes(&val_bytes, 1);
}

View File

@ -0,0 +1,23 @@
#include "PikaStdLib_MemChecker.h"
#include "BaseObj.h"
#include "dataStrs.h"
void PikaStdLib_MemChecker_max(PikaObj* self) {
__platform_printf("%0.2f kB\r\n", pikaMemMax() / 1024.0);
}
void PikaStdLib_MemChecker_now(PikaObj* self) {
__platform_printf("%0.2f kB\r\n", pikaMemNow() / 1024.0);
}
void PikaStdLib_MemChecker_resetMax(PikaObj* self) {
pikaMemMaxReset();
}
pika_float PikaStdLib_MemChecker_getMax(PikaObj* self) {
return pikaMemMax() / 1024.0;
}
pika_float PikaStdLib_MemChecker_getNow(PikaObj* self) {
return pikaMemNow() / 1024.0;
}

View File

@ -0,0 +1,14 @@
#include "PikaObj.h"
Arg* PikaStdLib_RangeObj___next__(PikaObj* self) {
RangeData* _ = (RangeData*)args_getStruct(self->list, "_");
int end = _->end;
int step = _->step;
/* exit */
if (_->i >= end) {
return arg_newNull();
}
Arg* res = arg_newInt(_->i);
_->i += step;
return res;
}

View File

@ -0,0 +1,5 @@
#include "PikaObj.h"
Arg* PikaStdLib_StringObj___next__(PikaObj* self) {
return arg_newNull();
}

View File

@ -0,0 +1,684 @@
#include "PikaStdLib_SysObj.h"
#include "PikaStdData_FILEIO.h"
#include "PikaStdLib_RangeObj.h"
#include "PikaStdLib_StringObj.h"
#include "PikaVM.h"
#include "dataStrs.h"
void PikaStdLib_SysObj_remove(PikaObj* self, char* argPath) {
obj_setErrorCode(self, 0);
int32_t res = obj_removeArg(self, argPath);
if (1 == res) {
obj_setSysOut(self, "[error] del: object no found.");
obj_setErrorCode(self, 1);
return;
}
if (2 == res) {
obj_setSysOut(self, "[error] del: arg not match.");
obj_setErrorCode(self, 2);
return;
}
}
Arg* PikaStdLib_SysObj_type(PikaObj* self, Arg* arg) {
if (NULL == arg) {
obj_setSysOut(self, "[error] type: arg no found.");
obj_setErrorCode(self, 1);
return arg_newNull();
}
ArgType type = arg_getType(arg);
if (ARG_TYPE_INT == type) {
return arg_newStr("<class 'int'>");
}
if (ARG_TYPE_FLOAT == type) {
return arg_newStr("<class 'float'>");
}
if (ARG_TYPE_STRING == type) {
return arg_newStr("<class 'str'>");
}
if (argType_isObject(type)) {
PikaObj* obj = arg_getPtr(arg);
NewFun clsptr = obj_getClass(obj);
PikaObj* New_PikaStdData_List(Args * args);
if (clsptr == New_PikaStdData_List) {
return arg_newStr("<class 'list'>");
}
/* dict */
PikaObj* New_PikaStdData_Dict(Args * args);
if (clsptr == New_PikaStdData_Dict) {
return arg_newStr("<class 'dict'>");
}
return arg_newStr("<class 'object'>");
}
if (ARG_TYPE_OBJECT_META == type) {
return arg_newStr("<class 'meta object'>");
}
if (ARG_TYPE_BYTES == type) {
return arg_newStr("<class 'bytes'>");
}
if (ARG_TYPE_METHOD_NATIVE == type) {
return arg_newStr("<class 'buitin_function_or_method'>");
}
if (ARG_TYPE_METHOD_OBJECT == type) {
return arg_newStr("<class 'method'>");
}
if (ARG_TYPE_METHOD_STATIC == type) {
return arg_newStr("<class 'function'>");
}
if (ARG_TYPE_NONE == type) {
return arg_newStr("<class 'NoneType'>");
}
return arg_newNull();
}
pika_float PikaStdLib_SysObj_float(PikaObj* self, Arg* arg) {
ArgType type = arg_getType(arg);
if (ARG_TYPE_INT == type) {
return (float)arg_getInt(arg);
}
if (ARG_TYPE_FLOAT == type) {
return (float)arg_getFloat(arg);
}
if (ARG_TYPE_STRING == type) {
return strtod(arg_getStr(arg), NULL);
}
obj_setSysOut(self, "[error] convert to pika_float type failed.");
obj_setErrorCode(self, 1);
return -99999.99999;
}
int PikaStdLib_SysObj_int(PikaObj* self, Arg* arg) {
ArgType type = arg_getType(arg);
if (ARG_TYPE_INT == type) {
return (int)arg_getInt(arg);
}
if (ARG_TYPE_FLOAT == type) {
return (int)arg_getFloat(arg);
}
if (ARG_TYPE_STRING == type) {
return (int)fast_atoi(arg_getStr(arg));
}
if (ARG_TYPE_BYTES == type) {
size_t size = arg_getBytesSize(arg);
if (size != 1) {
obj_setSysOut(self, "ValueError: invalid literal for int()");
obj_setErrorCode(self, 1);
return -999999999;
}
uint8_t val = *arg_getBytes(arg);
return val;
}
obj_setSysOut(self, "[error] convert to int type failed.");
obj_setErrorCode(self, 1);
return -999999999;
}
char* PikaStdLib_SysObj_str(PikaObj* self, Arg* arg) {
obj_removeArg(self, "__buf");
ArgType type = arg_getType(arg);
Args buffs = {0};
char* res = "";
if (ARG_TYPE_INT == type) {
int val = arg_getInt(arg);
res = strsFormat(&buffs, 11, "%d", val);
goto exit;
}
if (ARG_TYPE_FLOAT == type) {
pika_float val = arg_getFloat(arg);
res = strsFormat(&buffs, 11, "%f", val);
goto exit;
}
if (ARG_TYPE_BYTES == type) {
res = (char*)arg_getBytes(arg);
goto exit;
}
if (ARG_TYPE_STRING == type) {
res = arg_getStr(arg);
}
if (ARG_TYPE_NONE == type) {
res = "None";
}
if (argType_isObject(type)) {
res = obj_toStr(arg_getPtr(arg));
if (NULL != res) {
goto exit;
}
}
exit:
obj_setStr(self, "__buf", res);
strsDeinit(&buffs);
return obj_getStr(self, "__buf");
}
Arg* PikaStdLib_SysObj_iter(PikaObj* self, Arg* arg) {
/* object */
PIKA_BOOL is_temp = 0;
PikaObj* arg_obj = _arg_to_obj(arg, &is_temp);
NewFun _clsptr = (NewFun)arg_obj->constructor;
if (_clsptr == New_PikaStdLib_RangeObj) {
/* found RangeObj, return directly */
return arg_copy(arg);
}
// pikaVM_runAsm(arg_obj,
// "B0\n"
// "0 RUN __iter__\n"
// "0 OUT __res\n");
const uint8_t bytes[] = {
0x08, 0x00, 0x00, 0x00, /* instruct array size */
0x00, 0x82, 0x01, 0x00, 0x00, 0x04, 0x0a, 0x00, /* instruct array */
0x10, 0x00, 0x00, 0x00, /* const pool size */
0x00, 0x5f, 0x5f, 0x69, 0x74, 0x65, 0x72, 0x5f,
0x5f, 0x00, 0x5f, 0x5f, 0x72, 0x65, 0x73, 0x00, /* const pool */
};
pikaVM_runByteCode(arg_obj, (uint8_t*)bytes);
Arg* res = arg_copy(args_getArg(arg_obj->list, "__res"));
obj_removeArg(arg_obj, "__res");
if (is_temp) {
obj_refcntDec(arg_obj);
}
return res;
}
Arg* PikaStdLib_SysObj_range(PikaObj* self, PikaTuple* ax) {
/* set template arg to create rangeObj */
Arg* obj_arg = arg_newDirectObj(New_PikaStdLib_RangeObj);
PikaObj* range_obj = arg_getPtr(obj_arg);
RangeData range_data = {0};
if (pikaTuple_getSize(ax) == 1) {
int start = 0;
int end = arg_getInt(pikaTuple_getArg(ax, 0));
range_data.start = start;
range_data.end = end;
range_data.step = 1;
} else if (pikaTuple_getSize(ax) == 2) {
int start = arg_getInt(pikaTuple_getArg(ax, 0));
int end = arg_getInt(pikaTuple_getArg(ax, 1));
range_data.start = start;
range_data.end = end;
range_data.step = 1;
} else if (pikaTuple_getSize(ax) == 3) {
int start = arg_getInt(pikaTuple_getArg(ax, 0));
int end = arg_getInt(pikaTuple_getArg(ax, 1));
int step = arg_getInt(pikaTuple_getArg(ax, 2));
range_data.start = start;
range_data.end = end;
range_data.step = step;
}
range_data.i = range_data.start;
obj_setStruct(range_obj, "_", range_data);
return obj_arg;
}
Arg* PikaStdLib_SysObj___getitem__(PikaObj* self, Arg* obj, Arg* key) {
return __vm_get(NULL, self, key, obj);
}
Arg* PikaStdLib_SysObj___setitem__(PikaObj* self,
Arg* obj,
Arg* key,
Arg* val) {
ArgType obj_type = arg_getType(obj);
if (ARG_TYPE_STRING == obj_type) {
int index = arg_getInt(key);
char* str_val = arg_getStr(val);
char* str_pyload = arg_getStr(obj);
str_pyload[index] = str_val[0];
return arg_newStr(str_pyload);
}
if (ARG_TYPE_BYTES == obj_type) {
int index = arg_getInt(key);
uint8_t byte_val = 0;
if (ARG_TYPE_BYTES == arg_getType(val)) {
uint8_t* bytes_val = arg_getBytes(val);
byte_val = bytes_val[0];
}
if (ARG_TYPE_INT == arg_getType(val)) {
byte_val = arg_getInt(val);
}
uint8_t* bytes_pyload = arg_getBytes(obj);
size_t bytes_len = arg_getBytesSize(obj);
bytes_pyload[index] = byte_val;
return arg_newBytes(bytes_pyload, bytes_len);
}
if (argType_isObject(obj_type)) {
PikaObj* arg_obj = arg_getPtr(obj);
obj_setArg(arg_obj, "__key", key);
obj_setArg(arg_obj, "__val", val);
/* clang-format off */
PIKA_PYTHON(
__setitem__(__key, __val)
)
/* clang-format on */
const uint8_t bytes[] = {
0x0c, 0x00, 0x00, 0x00, /* instruct array size */
0x10, 0x81, 0x01, 0x00, 0x10, 0x01, 0x07, 0x00, 0x00, 0x02, 0x0d,
0x00,
/* instruct array */
0x19, 0x00, 0x00, 0x00, /* const pool size */
0x00, 0x5f, 0x5f, 0x6b, 0x65, 0x79, 0x00, 0x5f, 0x5f, 0x76, 0x61,
0x6c, 0x00, 0x5f, 0x5f, 0x73, 0x65, 0x74, 0x69, 0x74, 0x65, 0x6d,
0x5f, 0x5f, 0x00,
/* const pool */
};
pikaVM_runByteCode(arg_obj, (uint8_t*)bytes);
return arg_newRef(arg_obj);
}
return NULL;
}
int PikaStdLib_SysObj_len(PikaObj* self, Arg* arg) {
if (ARG_TYPE_STRING == arg_getType(arg)) {
return strGetSize(arg_getStr(arg));
}
if (ARG_TYPE_BYTES == arg_getType(arg)) {
return arg_getBytesSize(arg);
}
if (argType_isObject(arg_getType(arg))) {
PikaObj* arg_obj = arg_getPtr(arg);
Arg* method_arg = obj_getMethodArg(arg_obj, "__len__");
if (NULL != method_arg) {
arg_deinit(method_arg);
/* clang-format off */
PIKA_PYTHON(
__res = __len__()
)
/* clang-format on */
const uint8_t bytes[] = {
0x08, 0x00, 0x00, 0x00, /* instruct array size */
0x00, 0x82, 0x01, 0x00, 0x00, 0x04, 0x09, 0x00, /* instruct
array */
0x0f, 0x00, 0x00, 0x00, /* const pool size */
0x00, 0x5f, 0x5f, 0x6c, 0x65, 0x6e, 0x5f, 0x5f, 0x00,
0x5f, 0x5f, 0x72, 0x65, 0x73, 0x00, /* const pool */
};
pikaVM_runByteCode(arg_obj, (uint8_t*)bytes);
return obj_getInt(arg_obj, "__res");
}
}
obj_setErrorCode(self, 1);
__platform_printf("[Error] len: arg type not support\r\n");
return -1;
}
Arg* PikaStdLib_SysObj_list(PikaObj* self, PikaTuple* val) {
#if PIKA_BUILTIN_STRUCT_ENABLE
if (1 == pikaTuple_getSize(val)) {
Arg* in = pikaTuple_getArg(val, 0);
obj_setArg(self, "__list", in);
/* clang-format off */
PIKA_PYTHON(
__res = []
for __item in __list:
__res.append(__item)
del __item
del __list
)
/* clang-format on */
const uint8_t bytes[] = {
0x3c, 0x00, 0x00, 0x00, /* instruct array size */
0x00, 0x95, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x10, 0x81, 0x07,
0x00, 0x00, 0x02, 0x0e, 0x00, 0x00, 0x04, 0x13, 0x00, 0x00, 0x82,
0x17, 0x00, 0x00, 0x04, 0x24, 0x00, 0x00, 0x0d, 0x24, 0x00, 0x00,
0x07, 0x2b, 0x00, 0x11, 0x81, 0x24, 0x00, 0x01, 0x02, 0x2d, 0x00,
0x00, 0x86, 0x3a, 0x00, 0x00, 0x8c, 0x13, 0x00, 0x00, 0x8c, 0x24,
0x00, 0x00, 0x8c, 0x07, 0x00,
/* instruct array */
0x3d, 0x00, 0x00, 0x00, /* const pool size */
0x00, 0x5f, 0x5f, 0x72, 0x65, 0x73, 0x00, 0x5f, 0x5f, 0x6c, 0x69,
0x73, 0x74, 0x00, 0x69, 0x74, 0x65, 0x72, 0x00, 0x24, 0x6c, 0x30,
0x00, 0x24, 0x6c, 0x30, 0x2e, 0x5f, 0x5f, 0x6e, 0x65, 0x78, 0x74,
0x5f, 0x5f, 0x00, 0x5f, 0x5f, 0x69, 0x74, 0x65, 0x6d, 0x00, 0x32,
0x00, 0x5f, 0x5f, 0x72, 0x65, 0x73, 0x2e, 0x61, 0x70, 0x70, 0x65,
0x6e, 0x64, 0x00, 0x2d, 0x31, 0x00,
/* const pool */
};
pikaVM_runByteCode(self, (uint8_t*)bytes);
return arg_copy(obj_getArg(self, "__res"));
}
PikaObj* New_PikaStdData_List(Args * args);
return arg_newDirectObj(New_PikaStdData_List);
#else
obj_setErrorCode(self, 1);
__platform_printf("[Error] built-in list is not enabled.\r\n");
#endif
return arg_newNull();
}
Arg* PikaStdLib_SysObj_dict(PikaObj* self, PikaTuple* val) {
#if PIKA_BUILTIN_STRUCT_ENABLE
PikaObj* New_PikaStdData_Dict(Args * args);
return arg_newDirectObj(New_PikaStdData_Dict);
#else
obj_setErrorCode(self, 1);
__platform_printf("[Error] built-in dist is not enabled.\r\n");
return arg_newNull();
#endif
}
char* PikaStdLib_SysObj_hex(PikaObj* self, int val) {
char buff[PIKA_SPRINTF_BUFF_SIZE] = {0};
if (val >= 0) {
__platform_sprintf(buff, "0x%02x", val);
} else {
__platform_sprintf(buff, "-0x%02x", -val);
}
/* load the string from stack to heap */
obj_setStr(self, "__buf", buff);
return obj_getStr(self, "__buf");
}
int PikaStdLib_SysObj_ord(PikaObj* self, char* val) {
return (int)val[0];
}
char* PikaStdLib_SysObj_chr(PikaObj* self, int val) {
char buff[PIKA_SPRINTF_BUFF_SIZE] = {0};
char to_str[] = "0";
to_str[0] = val;
__platform_sprintf(buff, "%s", to_str);
/* load the string from stack to heap */
obj_setStr(self, "__buf", buff);
return obj_getStr(self, "__buf");
}
Arg* PikaStdLib_SysObj_bytes(PikaObj* self, Arg* val) {
ArgType type = arg_getType(val);
if (ARG_TYPE_INT == type) {
int size = arg_getInt(val);
/* src is NULL so the bytes are all '\0' */
Arg* bytes = arg_newBytes(NULL, size);
return bytes;
}
if (ARG_TYPE_BYTES == type) {
return arg_copy(val);
}
if (ARG_TYPE_STRING == type) {
int size = strGetSize(arg_getStr(val));
Arg* bytes = arg_newBytes((uint8_t*)arg_getStr(val), size);
return bytes;
}
#if !PIKA_NANO_ENABLE
if (argType_isObject(type)) {
PikaObj* obj = arg_getPtr(val);
PikaObj* New_PikaStdData_List(Args * args);
PikaObj* New_PikaStdData_Tuple(Args * args);
if (obj->constructor == New_PikaStdData_List ||
obj->constructor == New_PikaStdData_Tuple) {
PikaList* list = obj_getPtr(obj, "list");
Arg* bytes = arg_newBytes(NULL, pikaList_getSize(list));
uint8_t* bytes_raw = arg_getBytes(bytes);
for (size_t i = 0; i < pikaList_getSize(list); i++) {
bytes_raw[i] = (uint8_t)pikaList_getInt(list, i);
}
return bytes;
}
}
#endif
obj_setErrorCode(self, 1);
__platform_printf("Error: input arg type not supported.\r\n");
return arg_newNull();
}
static char* __print_arg(PikaObj* self, Arg* val) {
Args buffs = {0};
char* res = NULL;
if (NULL == val) {
goto __exit;
}
ArgType arg_type = arg_getType(val);
if (arg_type == ARG_TYPE_BYTES) {
res = __printBytes(self, val);
goto __exit;
}
if (arg_type == ARG_TYPE_STRING) {
res = arg_getStr(val);
goto __exit;
}
if (arg_type == ARG_TYPE_NONE) {
res = "None";
goto __exit;
}
if (arg_type == ARG_TYPE_INT) {
int64_t value = arg_getInt(val);
#if PIKA_PRINT_LLD_ENABLE
res = strsFormat(&buffs, 32, "%lld", value);
#else
res = strsFormat(&buffs, 32, "%d", value);
#endif
goto __exit;
}
if (arg_type == ARG_TYPE_FLOAT) {
pika_float value = arg_getFloat(val);
res = strsFormat(&buffs, 32, "%f", value);
goto __exit;
}
if (arg_type == ARG_TYPE_POINTER ||
arg_type == ARG_TYPE_METHOD_NATIVE_CONSTRUCTOR) {
void* value = arg_getPtr(val);
res = strsFormat(&buffs, 32, "%p", value);
goto __exit;
}
if (argType_isObject(arg_type)) {
res = obj_toStr(arg_getPtr(val));
goto __exit;
}
__exit:
if (NULL == res) {
obj_setSysOut(self, "Error: can not print val");
obj_setErrorCode(self, 1);
}
if (NULL != res) {
res = obj_cacheStr(self, res);
}
strsDeinit(&buffs);
return res;
}
void PikaStdLib_SysObj_print(PikaObj* self, PikaTuple* val, PikaDict* ops) {
int arg_size = pikaTuple_getSize(val);
char* end = pikaDict_getStr(ops, "end");
if (NULL == end) {
/* default */
end = "\r\n";
}
if (arg_size == 1) {
arg_singlePrint(pikaTuple_getArg(val, 0), PIKA_FALSE, end);
return;
}
Arg* print_out_arg = NULL;
PIKA_BOOL is_get_print = PIKA_FALSE;
for (int i = 0; i < arg_size; i++) {
Arg* arg = pikaTuple_getArg(val, i);
char* item = __print_arg(self, arg);
if (NULL != item) {
is_get_print = PIKA_TRUE;
if (NULL == print_out_arg) {
print_out_arg = arg_newStr("");
}
print_out_arg = arg_strAppend(print_out_arg, item);
if (i < arg_size - 1) {
print_out_arg = arg_strAppend(print_out_arg, " ");
}
}
}
if (PIKA_TRUE == is_get_print) {
__platform_printf("%s%s", arg_getStr(print_out_arg), end);
}
if (NULL != print_out_arg) {
arg_deinit(print_out_arg);
}
}
char* PikaStdLib_SysObj_cformat(PikaObj* self, char* fmt, PikaTuple* var) {
#if PIKA_SYNTAX_FORMAT_ENABLE
Args buffs = {0};
pikaMemMaxReset();
char* res = strsFormatList(&buffs, fmt, &var->super);
obj_setStr(self, "_buf", res);
res = obj_getStr(self, "_buf");
strsDeinit(&buffs);
return res;
#else
obj_setErrorCode(self, 1);
__platform_printf("[Error] PIKA_SYNTAX_FORMAT_ENABLE is not enabled.\r\n");
return NULL;
#endif
}
int PikaStdLib_SysObj_id(PikaObj* self, Arg* obj) {
uintptr_t ptr = 0;
if (argType_isObject(arg_getType(obj))) {
ptr = (uintptr_t)arg_getPtr(obj);
} else {
ptr = (uintptr_t)obj;
}
return ptr & (0x7FFFFFFF);
}
PikaObj* PikaStdLib_SysObj_open(PikaObj* self, char* path, char* mode) {
#if PIKA_FILEIO_ENABLE
PikaObj* file = newNormalObj(New_PikaStdData_FILEIO);
if (0 != PikaStdData_FILEIO_init(file, path, mode)) {
obj_setErrorCode(self, 1);
__platform_printf("[Error] open: can not open file.\r\n");
obj_deinit(file);
return NULL;
}
return file;
#else
obj_setErrorCode(self, 1);
__platform_printf("[Error] PIKA_FILEIO_ENABLE is not enabled.\r\n");
return NULL;
#endif
}
/* __dir_each */
int32_t __dir_each(Arg* argEach, Args* context) {
PikaObj* list = args_getPtr(context, "list");
if (argType_isCallable(arg_getType(argEach))) {
char name_buff[PIKA_LINE_BUFF_SIZE / 2] = {0};
char* method_name =
methodArg_getName(argEach, name_buff, sizeof(name_buff));
Arg* arg_str = arg_newStr(method_name);
__vm_List_append(list, arg_str);
arg_deinit(arg_str);
}
return 0;
}
PikaObj* PikaStdLib_SysObj_dir(PikaObj* self, PikaObj* obj) {
PikaObj* New_PikaStdData_List(Args * args);
PikaObj* list = newNormalObj(New_PikaStdData_List);
__vm_List___init__(list);
Args* context = New_args(NULL);
args_setPtr(context, "list", list);
args_foreach(obj->list, __dir_each, context);
args_deinit(context);
return list;
}
void PikaStdLib_SysObj_exec(PikaObj* self, char* code) {
#if PIKA_EXEC_ENABLE
obj_run(self, code);
#else
obj_setErrorCode(self, 1);
__platform_printf("[Error] PIKA_EXEC_ENABLE is not enabled.\r\n");
#endif
}
Arg* PikaStdLib_SysObj_getattr(PikaObj* self, PikaObj* obj, char* name) {
Arg* res = NULL;
if (NULL == obj) {
obj_setErrorCode(self, 1);
__platform_printf("[Error] getattr: can not get attr of NULL.\r\n");
return NULL;
}
Arg* arg = obj_getArg(obj, name);
if (NULL == arg) {
arg = obj_getMethodArg(obj, name);
return arg_copy(arg);
}
if (NULL != arg) {
res = arg_copy(arg);
return res;
}
return NULL;
}
void PikaStdLib_SysObj_setattr(PikaObj* self,
PikaObj* obj,
char* name,
Arg* val) {
if (NULL == obj) {
obj_setErrorCode(self, 1);
__platform_printf("[Error] setattr: obj is null.\r\n");
goto exit;
}
obj_setArg(obj, name, val);
exit:
return;
}
void PikaStdLib_SysObj_exit(PikaObj* self) {
pks_vm_exit();
}
int PikaStdLib_SysObj_hasattr(PikaObj* self, PikaObj* obj, char* name) {
if (NULL == obj) {
obj_setErrorCode(self, 1);
__platform_printf("[Error] hasattr: obj is null.\r\n");
return 0;
}
if (obj_isArgExist(obj, name)) {
return 1;
}
Arg* method = obj_getMethodArg(obj, name);
if (NULL != method) {
arg_deinit(method);
return 1;
}
return 0;
}
Arg* PikaStdLib_SysObj_eval(PikaObj* self, char* code) {
Args buffs = {0};
char* cmd = strsAppend(&buffs, "@res = ", code);
obj_run(self, cmd);
Arg* res = arg_copy(obj_getArg(self, "@res"));
strsDeinit(&buffs);
obj_removeArg(self, "@res");
return res;
}
static enum shellCTRL __obj_shellLineHandler_input(PikaObj* self,
char* input_line,
struct ShellConfig* cfg) {
cfg->context = arg_newStr(input_line);
return SHELL_CTRL_EXIT;
}
char* PikaStdLib_SysObj_input(PikaObj* self, PikaTuple* info) {
struct ShellConfig cfg = {
.prefix = "",
.context = NULL,
.handler = __obj_shellLineHandler_input,
.fn_getchar = __platform_getchar,
};
if (pikaTuple_getSize(info) > 0) {
__platform_printf("%s", pikaTuple_getStr(info, 0));
}
_temp__do_pikaScriptShell(self, &cfg);
char* res = obj_cacheStr(self, arg_getStr(cfg.context));
arg_deinit(cfg.context);
return res;
}
extern volatile PikaObj* __pikaMain;
void PikaStdLib_SysObj_help(PikaObj* self, char* name) {
if (strEqu(name, "modules")) {
obj_printModules((PikaObj*)__pikaMain);
}
}

View File

@ -0,0 +1,217 @@
#include "BaseObj.h"
#include "PikaVM.h"
void PikaStdTask_Task___init__(PikaObj* self) {
obj_setInt(self, "is_period", 0);
}
void PikaStdTask_Task_call_always(PikaObj* self, Arg* fun_todo) {
obj_setArg(self, "fun_todo", fun_todo);
PIKA_PYTHON_BEGIN
/* clang-format off */
PIKA_PYTHON(
calls.append('always')
calls.append(fun_todo)
)
/* clang-format on */
const uint8_t bytes[] = {
0x10, 0x00, 0x00, 0x00,/* instruct array size */
0x10, 0x83, 0x01, 0x00, 0x00, 0x02, 0x08, 0x00, 0x10, 0x81, 0x15,
0x00, 0x00, 0x02, 0x08, 0x00, /* instruct array */
0x1e, 0x00, 0x00, 0x00, /* const pool size */
0x00, 0x61, 0x6c, 0x77, 0x61, 0x79, 0x73, 0x00, 0x63, 0x61, 0x6c,
0x6c, 0x73, 0x2e, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x00, 0x66,
0x75, 0x6e, 0x5f, 0x74, 0x6f, 0x64, 0x6f, 0x00, /* const pool */
};
PIKA_PYTHON_END
pikaVM_runByteCode(self, (uint8_t*)bytes);
}
void PikaStdTask_Task_call_when(PikaObj* self, Arg* fun_todo, Arg* fun_when) {
obj_setArg(self, "fun_todo", fun_todo);
obj_setArg(self, "fun_when", fun_when);
PIKA_PYTHON_BEGIN
/* clang-format off */
PIKA_PYTHON(
calls.append('when')
calls.append(fun_when)
calls.append(fun_todo)
)
/* clang-format on */
const uint8_t bytes[] = {
0x18, 0x00, 0x00, 0x00,/* instruct array size */
0x10, 0x83, 0x01, 0x00, 0x00, 0x02, 0x06, 0x00, 0x10, 0x81, 0x13, 0x00,
0x00, 0x02, 0x06, 0x00, 0x10, 0x81, 0x1c, 0x00, 0x00, 0x02, 0x06, 0x00,
/* instruct array */
0x25, 0x00, 0x00, 0x00,/* const pool size */
0x00, 0x77, 0x68, 0x65, 0x6e, 0x00, 0x63, 0x61, 0x6c, 0x6c, 0x73, 0x2e,
0x61, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x00, 0x66, 0x75, 0x6e, 0x5f, 0x77,
0x68, 0x65, 0x6e, 0x00, 0x66, 0x75, 0x6e, 0x5f, 0x74, 0x6f, 0x64, 0x6f,
0x00,
/* const pool */
};
PIKA_PYTHON_END
pikaVM_runByteCode(self, (uint8_t*)bytes);
}
void PikaStdTask_Task_call_period_ms(PikaObj* self,
Arg* fun_todo,
int period_ms) {
obj_setArg(self, "fun_todo", fun_todo);
obj_setInt(self, "period_ms", period_ms);
PIKA_PYTHON_BEGIN
/* clang-format off */
PIKA_PYTHON(
calls.append('period_ms')
calls.append(period_ms)
calls.append(fun_todo)
calls.append(0)
is_period = 1
)
/* clang-format on */
const uint8_t bytes[] =
{
0x28, 0x00, 0x00, 0x00,/* instruct array size */
0x10, 0x83, 0x01, 0x00, 0x00, 0x02, 0x0b, 0x00, 0x10, 0x81, 0x01,
0x00, 0x00, 0x02, 0x0b, 0x00, 0x10, 0x81, 0x18, 0x00, 0x00, 0x02,
0x0b, 0x00, 0x10, 0x85, 0x21, 0x00, 0x00, 0x02, 0x0b, 0x00, 0x00,
0x85, 0x23, 0x00, 0x00, 0x04, 0x25, 0x00, /* instruct array */
0x2f, 0x00, 0x00, 0x00, /* const pool size */
0x00, 0x70, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x5f, 0x6d, 0x73, 0x00,
0x63, 0x61, 0x6c, 0x6c, 0x73, 0x2e, 0x61, 0x70, 0x70, 0x65, 0x6e,
0x64, 0x00, 0x66, 0x75, 0x6e, 0x5f, 0x74, 0x6f, 0x64, 0x6f, 0x00,
0x30, 0x00, 0x31, 0x00, 0x69, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x69,
0x6f, 0x64, 0x00, /* const pool */
};
PIKA_PYTHON_END
pikaVM_runByteCode(self, (uint8_t*)bytes);
}
void PikaStdTask_Task_run_once(PikaObj* self) {
/* clang-format off */
PIKA_PYTHON(
len = calls.len()
mode = 'none'
info_index = 0
for i in range(0, len):
if len == 0:
break
if info_index == 0:
mode = calls[i]
info_index = 1
elif info_index == 1:
if mode == 'always':
todo = calls[i]
todo()
info_index = 0
elif mode == 'when':
when = calls[i]
info_index = 2
elif mode == 'period_ms':
period_ms = calls[i]
info_index = 2
elif info_index == 2:
if mode == 'when':
if when():
todo = calls[i]
todo()
info_index = 0
elif mode == 'period_ms':
todo = calls[i]
info_index = 3
elif info_index == 3:
if mode == 'period_ms':
if tick > calls[i]:
todo()
calls[i] = tick + period_ms
info_index = 0
)
/* clang-format on */
const uint8_t bytes[] = {
0xf0, 0x01, 0x00, 0x00,/* instruct array size */
0x00, 0x82, 0x01, 0x00, 0x00, 0x04, 0x0b, 0x00, 0x00, 0x83, 0x0f, 0x00,
0x00, 0x04, 0x14, 0x00, 0x00, 0x85, 0x19, 0x00, 0x00, 0x04, 0x1b, 0x00,
0x20, 0x85, 0x19, 0x00, 0x20, 0x01, 0x0b, 0x00, 0x10, 0x02, 0x26, 0x00,
0x00, 0x02, 0x2c, 0x00, 0x00, 0x04, 0x31, 0x00, 0x00, 0x82, 0x35, 0x00,
0x00, 0x04, 0x42, 0x00, 0x00, 0x0d, 0x42, 0x00, 0x00, 0x07, 0x44, 0x00,
0x11, 0x81, 0x0b, 0x00, 0x11, 0x05, 0x19, 0x00, 0x01, 0x08, 0x46, 0x00,
0x01, 0x07, 0x49, 0x00, 0x02, 0x8e, 0x00, 0x00, 0x11, 0x81, 0x1b, 0x00,
0x11, 0x05, 0x19, 0x00, 0x01, 0x08, 0x46, 0x00, 0x01, 0x07, 0x49, 0x00,
0x12, 0x81, 0x4b, 0x00, 0x12, 0x01, 0x42, 0x00, 0x02, 0x1d, 0x00, 0x00,
0x02, 0x04, 0x14, 0x00, 0x02, 0x85, 0x49, 0x00, 0x02, 0x04, 0x1b, 0x00,
0x01, 0x8b, 0x49, 0x00, 0x11, 0x01, 0x1b, 0x00, 0x11, 0x05, 0x49, 0x00,
0x01, 0x08, 0x46, 0x00, 0x01, 0x07, 0x49, 0x00, 0x12, 0x81, 0x14, 0x00,
0x12, 0x03, 0x51, 0x00, 0x02, 0x08, 0x46, 0x00, 0x02, 0x07, 0x49, 0x00,
0x13, 0x81, 0x4b, 0x00, 0x13, 0x01, 0x42, 0x00, 0x03, 0x1d, 0x00, 0x00,
0x03, 0x04, 0x58, 0x00, 0x03, 0x82, 0x58, 0x00, 0x03, 0x85, 0x19, 0x00,
0x03, 0x04, 0x1b, 0x00, 0x02, 0x8b, 0x49, 0x00, 0x12, 0x01, 0x14, 0x00,
0x12, 0x03, 0x5d, 0x00, 0x02, 0x08, 0x46, 0x00, 0x02, 0x07, 0x49, 0x00,
0x13, 0x81, 0x4b, 0x00, 0x13, 0x01, 0x42, 0x00, 0x03, 0x1d, 0x00, 0x00,
0x03, 0x04, 0x5d, 0x00, 0x03, 0x85, 0x44, 0x00, 0x03, 0x04, 0x1b, 0x00,
0x02, 0x8b, 0x49, 0x00, 0x12, 0x01, 0x14, 0x00, 0x12, 0x03, 0x62, 0x00,
0x02, 0x08, 0x46, 0x00, 0x02, 0x07, 0x49, 0x00, 0x13, 0x81, 0x4b, 0x00,
0x13, 0x01, 0x42, 0x00, 0x03, 0x1d, 0x00, 0x00, 0x03, 0x04, 0x62, 0x00,
0x03, 0x85, 0x44, 0x00, 0x03, 0x04, 0x1b, 0x00, 0x01, 0x8b, 0x49, 0x00,
0x11, 0x01, 0x1b, 0x00, 0x11, 0x05, 0x44, 0x00, 0x01, 0x08, 0x46, 0x00,
0x01, 0x07, 0x49, 0x00, 0x12, 0x81, 0x14, 0x00, 0x12, 0x03, 0x5d, 0x00,
0x02, 0x08, 0x46, 0x00, 0x02, 0x07, 0x49, 0x00, 0x03, 0x82, 0x5d, 0x00,
0x03, 0x07, 0x49, 0x00, 0x14, 0x81, 0x4b, 0x00, 0x14, 0x01, 0x42, 0x00,
0x04, 0x1d, 0x00, 0x00, 0x04, 0x04, 0x58, 0x00, 0x04, 0x82, 0x58, 0x00,
0x03, 0x85, 0x19, 0x00, 0x03, 0x04, 0x1b, 0x00, 0x02, 0x8b, 0x49, 0x00,
0x12, 0x01, 0x14, 0x00, 0x12, 0x03, 0x62, 0x00, 0x02, 0x08, 0x46, 0x00,
0x02, 0x07, 0x49, 0x00, 0x13, 0x81, 0x4b, 0x00, 0x13, 0x01, 0x42, 0x00,
0x03, 0x1d, 0x00, 0x00, 0x03, 0x04, 0x58, 0x00, 0x03, 0x85, 0x6c, 0x00,
0x03, 0x04, 0x1b, 0x00, 0x01, 0x8b, 0x49, 0x00, 0x11, 0x01, 0x1b, 0x00,
0x11, 0x05, 0x6c, 0x00, 0x01, 0x08, 0x46, 0x00, 0x01, 0x07, 0x49, 0x00,
0x12, 0x81, 0x14, 0x00, 0x12, 0x03, 0x62, 0x00, 0x02, 0x08, 0x46, 0x00,
0x02, 0x07, 0x49, 0x00, 0x13, 0x81, 0x6e, 0x00, 0x23, 0x01, 0x4b, 0x00,
0x23, 0x01, 0x42, 0x00, 0x13, 0x1d, 0x00, 0x00, 0x03, 0x08, 0x73, 0x00,
0x03, 0x07, 0x49, 0x00, 0x04, 0x82, 0x58, 0x00, 0x14, 0x81, 0x4b, 0x00,
0x14, 0x01, 0x42, 0x00, 0x24, 0x01, 0x6e, 0x00, 0x24, 0x01, 0x62, 0x00,
0x14, 0x08, 0x75, 0x00, 0x04, 0x02, 0x77, 0x00, 0x04, 0x04, 0x4b, 0x00,
0x03, 0x85, 0x19, 0x00, 0x03, 0x04, 0x1b, 0x00, 0x00, 0x86, 0x83, 0x00,
0x00, 0x8c, 0x31, 0x00, /* instruct array */
0x86, 0x00, 0x00, 0x00, /* const pool size */
0x00, 0x63, 0x61, 0x6c, 0x6c, 0x73, 0x2e, 0x6c, 0x65, 0x6e, 0x00, 0x6c,
0x65, 0x6e, 0x00, 0x6e, 0x6f, 0x6e, 0x65, 0x00, 0x6d, 0x6f, 0x64, 0x65,
0x00, 0x30, 0x00, 0x69, 0x6e, 0x66, 0x6f, 0x5f, 0x69, 0x6e, 0x64, 0x65,
0x78, 0x00, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x69, 0x74, 0x65, 0x72,
0x00, 0x5f, 0x6c, 0x30, 0x00, 0x5f, 0x6c, 0x30, 0x2e, 0x5f, 0x5f, 0x6e,
0x65, 0x78, 0x74, 0x5f, 0x5f, 0x00, 0x69, 0x00, 0x32, 0x00, 0x3d, 0x3d,
0x00, 0x31, 0x00, 0x63, 0x61, 0x6c, 0x6c, 0x73, 0x00, 0x61, 0x6c, 0x77,
0x61, 0x79, 0x73, 0x00, 0x74, 0x6f, 0x64, 0x6f, 0x00, 0x77, 0x68, 0x65,
0x6e, 0x00, 0x70, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x5f, 0x6d, 0x73, 0x00,
0x33, 0x00, 0x74, 0x69, 0x63, 0x6b, 0x00, 0x3e, 0x00, 0x2b, 0x00, 0x5f,
0x5f, 0x73, 0x65, 0x74, 0x69, 0x74, 0x65, 0x6d, 0x5f, 0x5f, 0x00, 0x2d,
0x31, 0x00, /* const pool */
};
pikaVM_runByteCode(self, (uint8_t*)bytes);
}
void __Task_update_tick(PikaObj* self) {
if (obj_getInt(self, "is_perod")) {
obj_runNativeMethod(self, "platformGetTick", NULL);
}
}
void PikaStdTask_Task_run_forever(PikaObj* self) {
while (1) {
__Task_update_tick(self);
PikaStdTask_Task_run_once(self);
}
}
void PikaStdTask_Task_run_until_ms(PikaObj* self, int until_ms) {
while (1) {
__Task_update_tick(self);
PikaStdTask_Task_run_once(self);
if (obj_getInt(self, "tick") > until_ms) {
return;
}
}
}
void PikaStdTask_Task_platformGetTick(PikaObj* self) {
obj_setErrorCode(self, 1);
__platform_printf("Error: abstract method %s need implament", __FUNCTION__);
}

View File

@ -0,0 +1,2 @@
pikascript-core==v1.12.0
PikaStdLib==v1.12.0

Binary file not shown.

View File

@ -0,0 +1,8 @@
set(CONFIG_VLIBC 1)
set(CONFIG_VLIBC_FATFS 1)
set(CONFIG_BFLOG 1)
set(CONFIG_FATFS 1)
set(CONFIG_BSP_SDH_SDCARD 1)
set(CONFIG_BSP_FATFS_SDH_SDCARD 1)