bayrell / BayLang

BayLang compiler source code
https://bayrell.org/ru/docs/baylang
Apache License 2.0
4 stars 0 forks source link

Типы данных BayLang #158

Open ildar-ceo opened 2 months ago

ildar-ceo commented 2 months ago

Типы данных:

Массивы Array:

Создать массив размером 100 элементов типа int:

Array arr = allocate("int", 100);

Для того чтобы создать массив, не обязательно выделять для него память. Можно использовать уже существующую память:

Pointer p = new Pointer(arr);
Array arr2 = pointer(p, "byte", p.size);

Высвободить память массива:

delete arr;

Классы:

Аннотации:

Реднер функция:

Сериализация:

Шина данных:

ildar-ceo commented 2 months ago

Пример простой программы:

namespace App;

int main()
{
    print("Hello, World!");
    return 0;
}

entry_point(method main);
ildar-ceo commented 2 months ago

Компаратор:

fn<fn<int>> comparator = fn<int> (fn<var a, var b> compare, fn<var> f)
{
    return int (var a, var b) use (compare, f)
    {
        return compare(f(a), f(b));
    };
};

Пример 1. Сортировка:

Collection arr = [1, 2, 3, 4];
arr.sort( lib::comparator( method compareInt ) );

Пример 2. Сортировка объектов по именам:

Collection<User> user_arr = [
    new User("test1"),
    new User("test2"),
    new User("test3"),
    new User("test4"),
];
user_arr.sort(lib::comparator(method compareString, lib::get("name")));

Пример 3. Получить имена пользователей:

Collection<User> user_arr = [
    new User("test1"),
    new User("test2"),
    new User("test3"),
    new User("test4"),
];
Collection<string> user_names = user_arr.map(lib::get("name"));
ildar-ceo commented 2 months ago

Пример 1:

fn f = int (int a, int b) => a + b;

Пример 2:

fn f = method this.onClick;

Пример 3:

fn f = method(classof Test, "onClick");

Проверка существует ли функция:

f.exists();

Вызов функции:

f.apply([value]);

Асинхронный вызов функции:

await f.apply([value]);
ildar-ceo commented 2 months ago

Структуры:

class BaseStruct extends BaseObject
{
    /**
     * Create model
     */
    void constructor(Dict params = null)
    {
        parent();

        /* Setup struct */
        this.setup(params);

        /* Init struct */
        this.init(params);
    }

    /**
     * Setup struct
     */
    void setup(Dict params)
    {
        if (params == null) return;
    }

    /**
     * Init struct
     */
    void init(Dict params)
    {
    }
}
ildar-ceo commented 2 months ago

Модель

class BaseModel extends BaseStruct implements SerializeInterface
{
    BaseModel parent_widget = null;
    LayoutModel layout = null;
    string component = "";
    string widget_name = "";
    Map widgets = {};
    bool is_data_loaded = false;

    /**
     * Setup struct
     */
    void setup(Dict params)
    {
        parent(params);
        if (params == null) return;
        if (params.has("component")) this.component = params.get("component");
        if (params.has("layout")) this.layout = params.get("layout");
        if (params.has("widget_name")) this.widget_name = params.get("widget_name");
        if (params.has("parent_widget"))
        {
            this.parent_widget = params.get("parent_widget");
            this.parent_widget.widgets.set(this.widget_name, this);
            this.layout = this.parent_widget.layout;
        }
    }

    /**
     * Init struct
     */
    void init(Dict params)
    {
        parent(params);
    }

    /**
     * Add widget
     */
    BaseModel addWidget(string class_name, Map params = null)
    {
        if (params == null) params = {};
        params.set("parent_widget", this);
        BaseModel widget = newInstance(class_name, [params]);
        return widget;
    }

    /**
     * Returns widget by name
     */
    BaseModel getWidget(string widget_name) => this.widgets.get(widget_name);

    /**
     * Load data
     */
    async void loadData(RenderContainer container)
    {
        if (this.is_data_loaded) return;

        Collection widgets_keys = this.widgets.keys();
        for (int i=0; i<widgets_keys.count(); i++)
        {
            string widget_key = widgets_keys.get(i);
            BaseModel widget = this.widgets.get(widget_key);
            await widget.loadData(container);
        }

        this.is_data_loaded = true;
    }

    /**
     * Serialize model
     */
    void serialize(Serializer serializer, Map data)
    {
        serializer.process(this, "component", data);
        serializer.process(this, "widget_name", data);
        serializer.processItems(this, "widgets", data, method this.serializeCreateWidget);
        serializer.process(this, "is_data_loaded", data);
    }

    /**
     * Process frontend data
     */
    void serializeCreateWidget(Serializer serializer, Map data)
    {
        string class_name = data.get("__class_name__");
        string widget_name = data.get("widget_name");

        /* If BaseModel */
        if (rtl::is_instanceof(class_name, "Runtime.BaseModel"))
        {
            BaseModel widget = this.widgets.get(widget_name);
            if (widget != null) return widget;
            return this.addWidget(class_name, {
                "widget_name": widget_name,
            });
        }

        /* Create object */
        return rtl::newInstance(class_name);
    }
}
ildar-ceo commented 2 months ago

Интерфейсы:

enum InsertType
{
    BEFORE,
    AFTER,
}

interface Array<T>
{
    int count();
    T get(int pos);
    void set(int pos, T item);
    T first();
    T last();
    int indexOf(T value);
    Array<T> concat(Array<T> items);
    Array<T> slice(int start, int count);
    void sort();
}

interface List<T> extends Array<T>
{
    int push(T item);
    int insert(T item, int pos, InsertType kind = InsertType.AFTER);
    void remove(TreeItem item);
}

interface Collection<T> extends List<T>
{
    Collection<T> flatten();
    Collection<T> map(fn f);
    Collection<T> reduce(fn f, var value);
    Collection<T> filter(fn<bool> f);
    void each(fn f);
    Dict transition(fn f);
}