NewLang Project
Yet another programm language
Loading...
Searching...
No Matches
object.h
Go to the documentation of this file.
1#pragma once
2#ifndef INCLUDED_OBJECT_H_
3#define INCLUDED_OBJECT_H_
4
5#include <regex>
6
7#include "types.h"
8#include "dict.h"
9#include "rational.h"
10
11
12typedef at::indexing::TensorIndex Index;
13typedef at::IntArrayRef Dimension;
14
15
16
17namespace newlang {
18
19 /*
20 * Аргумент по умолчанию может быть литерал или выражение.
21 * Если аргумент по умолчанию — это выражение, то оно вычисляется только один раз для всей программы при загрузке модуля.
22 * Аргументы по умолчанию парсятся из токенов (создаются или вычисляются) при загрузке модуля, т.е. при создании
23 * аругментов по умолчанию, а сами значения хранятся уже как объекты.
24 *
25 * Аргументы в функции всегда имеют номер, который начинается с единицы в порядке определения в прототипе + некоторые могут иметь наименование.
26 * Даже обязательные аргументы (которые не имеют значения по умолчанию в прототипе финкции), могут быть переданы по имени,
27 * а сами именованные аргументы могут быть указаны в произвольном порядке. Поэтому в реализации Args для обязательных
28 * аргументов так же хранится имя аргумента, но его значение отсутствует.
29 *
30 * Так как позционные аргументы тоже могут передавать как именованные, то контроль и подстчет кол-ва
31 * не именованных аргументов при вызове фунции ничего не определяет.
32 * Следовательно, при вызове функции не именованные аргументы записываются по порядку, а именованные по имени.
33 * Контроль передаваемых аргументов производится на наличие значения у каждого аргумента.
34 * Если при определении функции после всех аргументов стоит многоточие, то разрешается добавлять
35 * новые аргументы по мимо тех, которые уже определены в прототипе функции.
36 */
37
38 // ObjType DictionarySummaryType(const Obj *obj);
39 std::vector<int64_t> TensorShapeFromDict(const Obj *obj);
40 // torch::Tensor ConvertToTensor(Obj *obj, at::ScalarType type = at::ScalarType::Undefined, bool reshape = true);
41 //
42 // at::TensorOptions ConvertToTensorOptions(const Obj *obj);
43 // at::DimnameList ConvertToDimnameList(const Obj *obj);
44 // bool ParsePrintfFormat(Obj *args, int start = 1);
45
46 ObjPtr CheckSystemField(const Obj *obj, const std::string name);
47
48 enum class ConcatMode : uint8_t {
49 Error = 0,
50 Append = 1,
51 Discard = 2,
52 };
53 /*
54 * Для строк, словарей и классов (преобразование в одно измерение), тензоров (преобразование согласно ConcatMode)
55 */
56 int64_t ConcatData(Obj *dest, Obj &src, ConcatMode mode = ConcatMode::Error);
57
58 /*
59 * Требуется разделять конейнеры с данными и итераторы по данным.
60 * В С++ контейнеры предоставялют итераторы непосредственно из самого контейнера.
61 * Это удобно для использования в рукописном коде, но сложно контроллировать в генерируемом исходнике,
62 * т.к. требуется использовать и итертор и сам контейнер с данными (для сравнения текущего элемента с end()).
63 *
64 * Итератор - отдельный объект, которому для создания требуется контейнер с данными.
65 * Итератор реализует два интерфейса перебора данных:
66 * 1. - первый интерфейс итератора как в С++
67 * 2. - второй интерфейс для использования в генерируемом коде с логикой NewLang
68 *
69 * template Iterator - Обертка над классическим С++ итератором с добавлением возможности отбора
70 * элементов по имени поля или с помощь функции обратного вызова для пользовательской фильтрации.
71 *
72 * Программынй интерфейс итераторов для NewLang следующий:
73 *
74 * ObjPtr IteratorMake(const std::string filter) - создать итератор с возможностью фильтрации по имени поля (данные на начало)
75 * ObjPtr IteratorMake(Obj * args) - создать итератор с фильтрации с помощью пользовательской функции (данные на начало)
76 * ObjPtr IteratorReset() - Сбросить итератор на начало данных (возвращает сам итератор)
77 * ObjPtr IteratorData() - прочитать текущий элемент без смещения указателя. Если данных нет возвращается "конец итератора"
78 * ObjPtr IteratorNext(int64_t count)- прочитать заданное кол-во элементов и переместить итератор на следующий элемент.
79 * При не нулевом кол-ве, данные возвращаются как элементы словаря. Если указан кол-во элеметов 0 - возвращается текущий элемент.
80 *
81 * Реализаиця итераторов NewLang с помощью данного интерфейса:
82 *
83 * Создание итератора
84 * ?, ?("Фильтр"), ?(func), ?(func, args...) - IteratorMake
85 *
86 * Перебор элементов итератора
87 * !, !(0), !(3), !(-3)
88 *
89 * dict! и dict!(0) <НЕ> эквивалентны, т.к. по разному обработывают конец данных
90 * dict! -> 1, dict! -> 2, dict! -> 3, dict! -> 4, dict! -> 5, dict! -> исключение "конец итератора"
91 * dict!(0) -> 1, dict!(0) -> 2, ... dict!(0) -> 5, dict!(0) -> :IteratorEnd (может :Empty - пустое значение ?? )
92 * dict!(1) -> (1,), dict!(1) -> (2,), ... dict!(1) -> (5,), dict!(1) -> (,)
93 *
94 * Различия отрицательного размера возвращаемого словаря для итератора
95 * (Для отрцетельного размера всегда зозвращается словарь указанного размера)
96 * dict!(-1) -> (1,), ... dict!(-1) -> (5,), dict!(-1) -> (:IteratorEnd,),
97 * dict!(1) -> (1,), ... dict!(1) -> (5,), dict!(1) -> (,),
98 * dict!(-3) -> (1, 2, 3,), dict!(-3) -> (4, 5, :IteratorEnd,)
99 * dict!(3) -> (1, 2, 3,), dict!(3) -> (4, 5,)
100 *
101 * Операторы ?! и !? эквивалентны и возвращают текущие данные без перемещения указателя итератора (IteratorData) и не принимают аргументов.
102 * Остальные итераторы можно вызвать либо без скобок, либо с аргментами в скобрках. Вызов без аргументов зарпрешщен
103 * (чтобы не пересекаться с логикой копирования объектов и не делать для итераторов аругменты по умолчанию)
104 *
105 * Оператор ?? создает итератор и сразу его выполняет, возвращая все значения
106 * в виде элементов словаря, т.е. аналог последовательности ?(LINQ); !(:Int64.__max__);
107 *
108 * Оператор !! без аргументов - сбрасывает итератор в начальное состояние (IteratorReset),
109 * Обператор !! с аргументами выполняется как ! с аругментами, но с начла коллекции.
110 *
111 * [ ] - оператор приведения данных в логический тип. Испольуется в алгоритмических конструкциях (проверка условий и циклы)
112 * Правила преобразования в логический тип:
113 * Словарь или класс - нет элементов - false, есть элементы - true
114 * Число - ноль или нулевой тензо - false, иначе true
115 * Строка - пустая строка false, иначе true
116 * Итератор - конец данных false, иначе true
117 * :IteratorEnd (:Empty ?) - всегда false
118 * None - true (Это объекст со значением пусто)
119 * Empty - false (Не инициализированный объект)
120 *
121 *
122 * Логика обработки ссылок
123 * term1 := term; # Объект term1 - копия term.
124 * term2 := &term; # Объект term2 - ссылка на term (одни и те же данные, т.е. shared_ptr ссылаются на один и тот же объект)
125 * &term3 := term; # Создать объект term3 и вернуть ссылку на него (сахар для term3 := term; &term3;)
126 *
127 *
128 * copy(arg) := {}; # Обычная функция принимает любой аргумент как <КОПИЮ> значения
129 * copy(term1); # ОК - передается <КОПИЯ> term1
130 * copy(term2); # ОК - передается <КОПИЯ> term2
131 * copy(&term1); # ОК - передается ссылка на term1 (На самом деле копия ссылки, которая указывает на те же данные)
132 * copy(&term2); # ОК- передается ссылка на term2 (На самом деле копия ссылки, которая указывает на те же данные)
133 *
134 * ptr(&arg) := {}; # Функция, которая принимает только аргумент - <ссылку>
135 * ptr(term1); # Ошибка при компиляции - нужно передавать ссылку !!!!!!!!
136 * ptr(&term1); # ОК
137 * ptr(&term2); # ОК
138 * ptr(term2); # Ошибка при компиляции - нужно передавать ссылку, несмотря на то что term2 УЖЕ содержит ссылку !!!!!!!!
139 *
140 *
141 *
142 *
143 * <% - Кнстанты и свойста>
144 * Значением константы может быть любой литерал (строка или число)
145 *
146 * Так как константа определяется во время компиляции, то её значение может быть использовано компилятором
147 * для анализа исходного текста программы после парсинга ATS и на основе их значений влиять на генерируемый
148 * трансплайтером финальный код на языке реализации.
149 *
150 * Константа доступна во время выполнения для чтения как значение системного поля __option__ ( для константы %option)
151 * ::%option - Глобальная область видимости для константы
152 *
153 * С помощью констант реализуется одноименный функционал (переменные только для чтения), путем установки
154 * соответствующего поля (term%const=1; или term%const=0;)
155 *
156 * <Для релиза компилатора, т.к. требует анализа исходникой на уровне файла и предназаначена для генерации кода на С++>
157 *
158 */
159
160 template <typename T>
161 class Iterator : public std::iterator<std::input_iterator_tag, T> {
162 public:
163
164 friend class Obj;
165 friend class Dict<Obj>;
166 friend class Context;
167 friend class Dict<Context, std::weak_ptr<Context>>;
168
169 enum class IterCmp : int8_t {
170 No = static_cast<int8_t> (ObjType::None), /* skip data */
171 Yes = static_cast<int8_t> (ObjType::Iterator), /* return data */
172 End = static_cast<int8_t> (ObjType::IteratorEnd), /* iterator complete */
173 };
174
175 STATIC_ASSERT(static_cast<bool> (IterCmp::Yes));
176 STATIC_ASSERT(!static_cast<bool> (IterCmp::No));
177
180
182 typedef typename Dict<T>::Type IterObjPtr;
185
186
187 typedef IterCmp CompareFuncType(const IterPairType &pair, const T *args, void *extra);
188
189 // static const std::string FIND_KEY_DEFAULT;
190
196 explicit Iterator(std::shared_ptr<T> obj, const char * find_key = "(.|\\n)*") :
197 Iterator(obj, &CompareFuncDefault, reinterpret_cast<T *> (const_cast<char *> (find_key)), static_cast<void *> (this)) {
198 }
199
207 Iterator(std::shared_ptr<T> obj, CompareFuncType *func, T *arg, void * extra = nullptr) :
208 m_iter_obj(obj), m_match(), m_func(func), m_func_args(arg), m_func_extra(extra), m_found(m_iter_obj->begin()), m_base_filter(nullptr) {
209 search_loop();
210 }
211
215
216 SCOPE(private) :
217 std::shared_ptr<T> m_iter_obj;
218 std::regex m_match;
219 std::string m_filter;
223 mutable typename Dict<T>::iterator m_found;
224 const char * m_base_filter;
225
227
228 static IterCmp CompareFuncDefault(const IterPairType &pair, const T *filter, void *extra) {
229 const char * str_filter = reinterpret_cast<const char *> (filter);
230 Iterator * iter = static_cast<Iterator *> (extra);
231 if (iter && str_filter) {
232
233 iter->m_base_filter = str_filter;
234 iter->m_func_args = nullptr; // Строка для фильтрации передается однократно при создании объекта
235 iter->m_filter.assign(str_filter);
236
237 if (!iter->m_filter.empty()) {
238 try {
239 iter->m_match = std::regex(iter->m_filter);
240 } catch (const std::regex_error &err) {
241 LOG_RUNTIME("Regular expression for '%s' error '%s'!", str_filter, err.what());
242 }
243 }
244 }
245
246 if (iter) {
247 if (iter->m_base_filter == nullptr) { // Без фильтра отдаются вообще все поля
248 return IterCmp::Yes;
249 } else if (iter->m_filter.empty()) { // Если передана пустая строка, то выдаются только поля без имен
250 return pair.first.empty() ? IterCmp::Yes : IterCmp::No;
251 } else {
252 // Иначе если имя поля совпадает с регуляркой
253 return std::regex_match(pair.first, iter->m_match) ? IterCmp::Yes : IterCmp::No;
254 }
255 }
256 return IterCmp::Yes;
257 }
258
259 public:
260
262 Iterator<T> copy(*this);
263 copy.reset();
264 return copy;
265 }
266
268 Iterator<T> copy(*this);
269 copy.m_found = copy.m_iter_obj->end();
270 return copy;
271 }
272
274 if (m_found == m_iter_obj->end()) {
275 return m_Iterator_end;
276 }
277 return *m_found;
278 }
279
281 return data();
282 }
283
284 const IterPairType &data() const {
285 if (m_found == m_iter_obj->end()) {
286 return m_Iterator_end;
287 }
288 return *m_found;
289 }
290
291 const IterPairType &operator*() const {
292 return data();
293 }
294
295 ObjPtr read_and_next(int64_t count);
296
297 const iterator &operator++() const {
298 if (m_found != m_iter_obj->end()) {
299 m_found++;
300 search_loop();
301 }
302 return *this;
303 }
304
305 const iterator operator++(int) const {
306 return iterator::operator++();
307 }
308
309 bool operator==(const iterator &other) const {
310 return m_found == other.m_found;
311 }
312
313 bool operator!=(const iterator &other) const {
314 return m_found != other.m_found;
315 }
316
317 void reset() {
319 search_loop();
320 }
321
322
323 protected:
324
325 void search_loop() const {
326 while (m_found != m_iter_obj->end()) {
328 if (m_func) {
329 result = (*m_func)(*m_found, m_func_args, m_func_extra);
330 if (result == IterCmp::End) {
332 }
333 }
334 if (result != IterCmp::No) {
335 // IterCmp::Yes || IterCmp::End
336 return;
337 }
338 m_found++;
339 }
340 }
341 };
342
343 /*
344 *
345 *
346 */
347 class Obj : public Dict<Obj>, public std::enable_shared_from_this<Obj> {
348 public:
349
350 // constexpr static const char * BUILDIN_TYPE = "__var_type__";
351 // constexpr static const char * BUILDIN_NAME = "__var_name__";
352 // constexpr static const char * BUILDIN_BASE = "__class_base__";
353 // constexpr static const char * BUILDIN_CLASS = "__class_name__";
354 // constexpr static const char * BUILDIN_NAMESPACE = "__namespace__";
355
357
358 Obj(ObjType type = ObjType::None, const char *var_name = nullptr, TermPtr func_proto = nullptr, ObjType fixed = ObjType::None, bool init = false, Sync *sync = nullptr);
359 // Obj(Context *ctx, const TermPtr term, bool as_value, Obj *local_vars);
360
361
362 [[nodiscard]]
363 static PairType ArgNull(const std::string name = "") {
364 return pair(Obj::CreateNil(), name);
365 }
366
367 [[nodiscard]]
368 static PairType Arg() {
369 return pair(CreateNone());
370 }
371
372 [[nodiscard]]
373 static PairType Arg(ObjPtr value, const std::string name = "") {
374 return pair(value, name);
375 }
376
377 template<typename T>
378 typename std::enable_if<std::is_pointer<T>::value || std::is_same<std::string, T>::value, PairType>::type
379 static Arg(T value, const std::string name = "") {
380 return pair(CreateString(value), name);
381 }
382
383 template<typename T>
384 typename std::enable_if<!std::is_same<PairType, T>::value && !std::is_pointer<T>::value && !std::is_same<std::string, T>::value, PairType>::type
385 static Arg(T value, const std::string name = "") {
386 return pair(CreateValue(value, ObjType::None), name);
387 }
388
390 try {
391 return shared_from_this();
392 } catch (std::bad_weak_ptr &err) {
393 LOG_RUNTIME("Exception thrown bad_weak_ptr! %s", err.what());
394 }
395 }
396
398 m_is_const = true;
399 return shared();
400 }
401
403 m_is_const = false;
404 return shared();
405 }
406
407 virtual ObjPtr IteratorMake(const char * filter = nullptr, bool check_create = true);
408 virtual ObjPtr IteratorMake(Obj *args);
409 virtual ObjPtr IteratorData();
410 virtual ObjPtr IteratorReset();
411 virtual ObjPtr IteratorNext(int64_t count);
412
414 return IteratorNext(count->GetValueAsInteger());
415 }
416
417
418
419#define TEST_CONST_() if (m_is_const) {LOG_RUNTIME("Can`t edit const value '%s'!", toString().c_str());}
420#define TEST_INIT_() if (!m_var_is_init) {LOG_RUNTIME("Object not initialized '%s'!", toString().c_str());}
421
422 [[nodiscard]]
424 return m_var_type_current;
425 }
426
427 [[nodiscard]]
429 if (is_arithmetic_type()) {
434 }
435 } else if (is_type_name()) {
436 return m_var_type_fixed;
437 }
438 return m_var_type_current;
439 }
440
441 [[nodiscard]]
442 std::string & getName() {
443 return m_var_name;
444 }
445
446 [[nodiscard]]
447 const std::string & getName() const {
448 return m_var_name;
449 }
450
451 void SetClassName(std::string &name) {
453 }
454
455 [[nodiscard]]
456 bool is_const() const {
457 return m_is_const;
458 }
459
460 [[nodiscard]]
461 bool is_init() const {
462 return m_var_is_init;
463 }
464
465 [[nodiscard]]
466 bool is_none_type() const {
468 }
469
470 [[nodiscard]]
471 bool is_bool_type() const {
473 }
474
475 [[nodiscard]]
476 bool is_arithmetic_type() const {
478 }
479
480 [[nodiscard]]
481 bool is_string_type() const {
483 }
484
485 [[nodiscard]]
486 bool is_string_char_type() const {
488 }
489
490 [[nodiscard]]
491 bool is_string_wide_type() const {
493 }
494
495 [[nodiscard]]
496 bool is_dictionary_type() const {
498 }
499
500 //Plain data — это неизменяемые структуры без ссылок на другие объекты.
501 [[nodiscard]]
502 bool is_plain_type() const {
504 }
505
506 [[nodiscard]]
507 bool is_other_type() const {
509 }
510
511 [[nodiscard]]
512 bool is_class_type() const {
514 }
515
516 [[nodiscard]]
517 bool is_simple_type() const {
519 }
520
521 [[nodiscard]]
522 bool is_scalar() const;
523
524 [[nodiscard]]
525 bool is_function_type() const {
527 }
528
529 [[nodiscard]]
530 bool is_native() const {
532 }
533
534 [[nodiscard]]
535 bool is_tensor_type() const {
537 }
538
539 [[nodiscard]]
540 bool is_integer() const {
541 return isIntegralType(m_var_type_current, false);
542 }
543
544 [[nodiscard]]
545 bool is_integral() const {
547 }
548
549 [[nodiscard]]
550 bool is_complex() const {
552 }
553
554 [[nodiscard]]
555 bool is_floating() const {
557 }
558
559 [[nodiscard]]
563
564 [[nodiscard]]
565 bool is_ellipsis() const {
567 }
568
569 [[nodiscard]]
570 bool is_range() const {
572 }
573
574 [[nodiscard]]
575 bool is_rational() const {
577 }
578
579 [[nodiscard]]
580 bool is_type_name() const {
582 }
583
584 [[nodiscard]]
588
589 [[nodiscard]]
593
594 [[nodiscard]]
598
599
600 [[nodiscard]]
603 }
604
605 [[nodiscard]]
609
610 // static ObjPtr Take(Obj &args) {
611 // if (isInterrupt(args.m_var_type_current)) {
612 // return args.m_return_obj;
613 // } else if (args.size() && args[0].second->is_return()) {
614 // ASSERT(args.size() == 1);
615 // return args[0].second->m_return_obj;
616 // } else {
617 // return args.shared();
618 // }
619 // // LOG_RUNTIME("Take object for type %s not implemented!", newlang::toString(args[0].second->getType()));
620 // }
621
622 void SetTermProp(Term &term);
623
624 virtual int64_t size() const {
625 return size(0);
626 }
627 virtual int64_t size(int64_t ind) const;
628 int64_t resize_(int64_t size, ObjPtr fill, const std::string = "");
629
630 virtual bool empty() const;
631
632 Dict<Obj>::PairType & at(const std::string name) const {
633 Obj * const obj = (Obj * const) this;
634 ObjPtr sys = CheckSystemField(this, name.c_str());
635 if (!!sys) {
636 m_str_pair.first = name;
637 m_str_pair.second = sys;
638 return m_str_pair;
639 }
640 return obj->Dict<Obj>::at(name);
641 }
642
643 Dict<Obj>::PairType & at(const std::string name) override {
644 ObjPtr sys = CheckSystemField(this, name.c_str());
645 if (!!sys) {
646 m_str_pair.first = name;
647 m_str_pair.second = sys;
648 return m_str_pair;
649 }
650 return Dict<Obj>::at(name);
651 }
652
653 Dict<Obj>::PairType & at(const int64_t index) override;
654 const Dict<Obj>::PairType & at(const int64_t index) const override;
655
657 if (!find->is_string_type()) {
658 LOG_RUNTIME("Value must be a string type %d", (int) find->getType());
659 }
660 return Dict<Obj>::at(find->GetValueAsString());
661 }
662
663 bool exist(ObjPtr &find, bool strong);
664 size_t ItemValueCount(ObjPtr &find, bool strong);
665
666 static bool is_true(const char *text) {
667 std::string temp(text);
668 std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
669 return temp.compare("true") == 0;
670 }
671
674 return op_call(args);
675 }
676
678 ASSERT(args);
679 return op_call(*args);
680 }
681
682 ObjPtr op_call(Obj &args);
683
684 template <typename... T>
685 typename std::enable_if<is_all<Obj::PairType, T ...>::value, ObjPtr>::type
686 operator()(T ... args) {
687 auto list = {args...};
688 ObjPtr arg = Obj::CreateDict();
689 for (auto &elem : list) {
690 arg->push_back(elem);
691 }
692 return op_call(*arg);
693 }
694
695 template <typename... T>
696 typename std::enable_if<!is_all<Obj::PairType, T ...>::value, ObjPtr>::type
697 operator()(T ... args) {
698 auto list = {args...};
699 ObjPtr arg = Obj::CreateDict();
700 for (auto &elem : list) {
701 arg->push_back(Obj::CreateValue(elem));
702 }
703 return op_call(*arg);
704 }
705
706
707 // ObjPtr Call(Context *ctx) {
708 // Obj args(ObjType::Dictionary);
709 // return Call(ctx, &args);
710 // }
711 //
712 // template <typename... T>
713 // typename std::enable_if<is_all<Obj::PairType, T ...>::value, ObjPtr>::type
714 // Call(Context *ctx, T ... args) {
715 // auto list = {args...};
716 // Obj arg(ObjType::Dictionary);
717 // for (auto &elem : list) {
718 // arg.Dict<Obj>::push_back(elem);
719 // }
720 // return Call(ctx, &arg);
721 // }
722 //
723 // ObjPtr Call(Context *ctx, Obj *args, bool direct = false, ObjPtr self = nullptr);
724
725 /*
726 *
727 * Интерфейс Dict
728 *
729 */
730
731 template <typename I>
732 typename std::enable_if < std::is_integral<I>::value && !std::is_pointer<I>::value, const PairType &>::type
733 operator[](const I index) {
735 return at(index);
736 }
737 LOG_RUNTIME("Operator at for object type %s not implemented!", newlang::toString(m_var_type_current));
738 }
739
740 template <typename N>
741 typename std::enable_if < std::is_same<N, std::string>::value || std::is_pointer<N>::value, const PairType &>::type
742 operator[](const N name) {
744 return at(name);
745 }
746 LOG_RUNTIME("Operator at for object type %s not implemented!", newlang::toString(m_var_type_current));
747 }
748
749 Obj::iterator find(const std::string name) {
751 return Dict::find(name);
752 }
753 LOG_RUNTIME("Operator find for object type %s not implemented!", newlang::toString(m_var_type_current));
754 }
755
756 Obj::iterator begin() {
758 return Dict::begin();
759 }
760 LOG_RUNTIME("Iterator for object type %s not implemented!", newlang::toString(m_var_type_current));
761 }
762
763 Obj::iterator end() {
765 return Dict::end();
766 }
767 LOG_RUNTIME("Iterator for object type %s not implemented!", newlang::toString(m_var_type_current));
768 }
769
770 Obj::const_iterator begin() const {
772 return Dict::begin();
773 }
774 LOG_RUNTIME("Iterator for object type %s not implemented!", newlang::toString(m_var_type_current));
775 }
776
777 Obj::const_iterator end() const {
779 return Dict::end();
780 }
781 LOG_RUNTIME("Iterator for object type %s not implemented!", newlang::toString(m_var_type_current));
782 }
783
785 if (is_indexing()) {
786 return Dict::push_back(p);
787 }
788 LOG_RUNTIME("Operator push_back for object type %s not implemented!", newlang::toString(m_var_type_current));
789 }
790
791 PairType & push_back(const Type value, const std::string &name = "") {
792 if (is_indexing()) {
793 return Dict::push_back(value, name);
794 }
795 LOG_RUNTIME("Operator push_back for object type %s not implemented!", newlang::toString(m_var_type_current));
796 }
797
798 Obj::iterator at_index(const int64_t index) {
799 if (is_indexing()) {
800 return Dict::at_index(index);
801 }
802 LOG_RUNTIME("Operator at_index for object type %s not implemented!", newlang::toString(m_var_type_current));
803 }
804
805 Obj::const_iterator at_index_const(const int64_t index) const {
806 if (is_indexing()) {
808 }
809 LOG_RUNTIME("Operator at_index_const for object type %s not implemented!", newlang::toString(m_var_type_current));
810 }
811
812 Obj::const_iterator insert(Obj::const_iterator pos, const PairType &data) {
813 if (is_indexing()) {
814 return Dict::insert(pos, data);
815 }
816 LOG_RUNTIME("Operator insert for object type %s not implemented!", newlang::toString(m_var_type_current));
817 }
818
819 const std::string & name(const int64_t index) const override {
820 return Dict<Obj>::name(index);
821 }
822
823 int64_t resize(int64_t new_size, const Type fill, const std::string &name = "") override {
824 if (is_indexing()) {
825 return Dict<Obj>::resize(new_size, fill, name);
826 }
827 LOG_RUNTIME("Operator resize for object type %s not implemented!", newlang::toString(m_var_type_current));
828 }
829
830 void erase(const size_t from, const size_t to) override;
831
832 void erase(const int64_t index) override {
833 if (!is_indexing()) {
834 LOG_RUNTIME("Operator erase(index) for object type %s not implemented!", newlang::toString(m_var_type_current));
835 }
836 if (is_tensor_type()) {
837 LOG_RUNTIME("Operator erase(index) for object type %s not implemented!", newlang::toString(m_var_type_current));
838 } else {
840 }
841 }
842
843 void clear_() override {
844 Dict::clear_();
845 clear_(true);
846 }
847
848 void clear_(bool clear_iterator_name);
849
850 /*
851 * Cast operators
852 *
853 */
854 explicit inline operator bool() const {
855 return GetValueAsBoolean();
856 }
857
858#define PLACE_RANGE_CHECK_VALUE(itype, utype)\
859 explicit inline operator itype() const { \
860 int64_t result = GetValueAsInteger(); \
861 if (result > std::numeric_limits<itype>::max() || result < std::numeric_limits<itype>::lowest()) { \
862 LOG_RUNTIME("Value '%s' is out of range of the casting type %s!", GetValueAsString().c_str(), #itype); \
863 } \
864 return result; \
865 } \
866 explicit inline operator utype() const { \
867 int64_t result = GetValueAsInteger(); \
868 if (result > std::numeric_limits<utype>::max() || result < 0) { \
869 LOG_RUNTIME("Value '%s' is out of range of the casting type %s!", GetValueAsString().c_str(), #utype); \
870 } \
871 return result; \
872 }
873
874 PLACE_RANGE_CHECK_VALUE(int8_t, uint8_t);
875 PLACE_RANGE_CHECK_VALUE(int16_t, uint16_t);
876 PLACE_RANGE_CHECK_VALUE(int32_t, uint32_t);
877
878 explicit inline operator int64_t() const {
879 return GetValueAsInteger();
880 }
881
882 explicit inline operator uint64_t() const {
883 int64_t result = GetValueAsInteger();
884 if (result < 0) {
885 LOG_RUNTIME("Value '%s' is out of range of the casting type %s!", GetValueAsString().c_str(), "uint64_t");
886 }
887 return result;
888 }
889
890
891#undef PLACE_RANGE_CHECK_VALUE
892
893 explicit operator float() const;
894 explicit operator double() const;
895
896 explicit inline operator std::string() const {
897 return GetValueAsString();
898 }
899
900 explicit inline operator std::wstring() const {
901 return GetValueAsStringWide();
902 }
903
904 explicit operator void *() const {
905 return std::get<void *>(m_var);
906 }
907
908 explicit inline operator Rational() const {
909 return *GetValueAsRational();
910 }
911
912 //унарный плюс ничего не делает.
913
915 if (is_arithmetic_type()) {
916 return shared();
917 }
918 LOG_RUNTIME("Unary plus for object '%s' not supported!", toString().c_str());
919 }
920
922
924
925 if (is_tensor_type()) {
926 return obj;
927 }
928 LOG_RUNTIME("Object '%s' not numeric!", obj->toString().c_str());
929 }
930
931 ObjPtr &operator-(ObjPtr & obj);
932
933
934 //префиксная версия возвращает значение после инкремента
935
937
938 //постфиксная версия возвращает значение до инкремента
939
941 ObjPtr old = Clone();
943 return old;
944 }
945
946 //префиксная версия возвращает значение после декремента
947
949
950 //постфиксная версия возвращает значение до декремента
951
953 ObjPtr old = Clone();
955 return old;
956 }
957
959 ASSERT(obj);
960 return operator*(*obj);
961 }
962
964 ObjPtr result = Clone();
965 *result *= value;
966 return result;
967 }
968
970 ASSERT(obj);
971 return operator/(*obj);
972 }
973
975 ObjPtr result = Clone();
976 *result /= value;
977 return result;
978 }
979
981 ASSERT(obj);
982 return op_div_ceil(*obj);
983 }
984
986 ObjPtr result = Clone();
987 result->op_div_ceil_(value);
988 return result;
989 }
990
992 ASSERT(obj);
993 return op_concat(*obj, mode);
994 }
995
997 ObjPtr result = Clone();
998 result->op_concat_(value, mode);
999 return result;
1000 }
1001
1003 ConcatData(this, obj, mode);
1004 return shared();
1005 }
1006
1008 return op_concat_(*obj, mode);
1009 }
1010
1012 ASSERT(obj);
1013 return operator%(*obj);
1014 }
1015
1017 ObjPtr result = Clone();
1018 *result %= value;
1019 return result;
1020 }
1021
1023 ASSERT(obj);
1024 return operator+(*obj);
1025 }
1026
1028 ObjPtr result = Clone();
1029 *result += value;
1030 return result;
1031 }
1032
1034 ASSERT(obj);
1035 return operator+=(*obj);
1036 }
1037 ObjPtr operator+=(Obj obj);
1038
1040 ASSERT(obj);
1041 return operator-(*obj);
1042 }
1043
1045 ObjPtr result = Clone();
1046 *result -= value;
1047 return result;
1048 }
1049
1051 ASSERT(obj);
1052 return operator-=(*obj);
1053 }
1054 ObjPtr operator-=(Obj obj);
1055
1056 // ObjPtr op_lshift(ObjPtr obj) {
1057 // LOG_RUNTIME("Operator '<<' not implementd!");
1058 // }
1059 //
1060 // ObjPtr op_rshift(ObjPtr obj) {
1061 // LOG_RUNTIME("Operator '>>' not implementd!");
1062 // }
1063 //
1064 // ObjPtr op_rrshift(ObjPtr obj) {
1065 // LOG_RUNTIME("Operator '>>>' not implementd!");
1066 // }
1067
1068 bool operator<(ObjPtr obj) {
1069 ASSERT(obj);
1070 return operator<(*obj);
1071 }
1072
1073 bool operator<(Obj obj) {
1074 // 1 < 3 --> -1
1075 // 2 < 3 --> -1
1076 // 3 < 3 --> 0
1077 // 4 < 3 --> 1
1078 return op_compare(obj) < 0;
1079 }
1080
1081 bool operator<=(ObjPtr obj) {
1082 ASSERT(obj);
1083 return operator<=(*obj);
1084 }
1085
1086 bool operator<=(Obj obj) {
1087 return op_compare(obj) <= 0;
1088 }
1089
1090 bool operator>(ObjPtr obj) {
1091 ASSERT(obj);
1092 return operator>(*obj);
1093 }
1094
1095 bool operator>(Obj obj) {
1096 return op_compare(obj) > 0;
1097 }
1098
1099 bool operator>=(ObjPtr obj) {
1100 ASSERT(obj);
1101 return operator>=(*obj);
1102 }
1103
1104 bool operator>=(Obj obj) {
1105 return op_compare(obj) >= 0;
1106 }
1107 int op_compare(Obj & value);
1108
1109 /*
1110 * instanceof (проверка класса объекта) test_obj ~~ obj объекты совместимы по свойствим и их типам (утиная типизация)
1111 * in (проверка существования свойства) test_obj ~~ (prop=,) объект содержит указанные свойства (т.к. пустой тип совместим с любым типом)
1112 *
1113 * Реализация модели наследования:
1114 * ~ - проверка по классу объекта, т.е. проверка имени объекта или имени базового типа (объект должен быть наследником образца)
1115 * Реализация утиной типизации:
1116 * ~~ - сравнение с образцом на совместимость типов (пустой тип совместим с любым)
1117 * ~~~ - сравнение с образцом на равенство типов, т.е. типы объекта должны быть идентичны образцу, включая пустой
1118 * Для двух последних случаев сравнение производится только для одного уровня (без раскрытия сложенных словарей, если они присутствуют в образце)
1119 * или сравнение должно зависить от того, есть ли в образце вложенные словари (классы) ??????????????
1120 */
1121
1122 bool op_class_test(ObjPtr obj, Context *ctx) const;
1123 bool op_class_test(const char * name, Context *ctx) const;
1124
1125 bool op_duck_test(ObjPtr obj, bool strong) {
1126 ASSERT(obj);
1127 return op_duck_test(obj.get(), strong);
1128 }
1129 bool op_duck_test(Obj *value, bool strong);
1130 static bool op_duck_test_prop(Obj *base, Obj *value, bool strong);
1131
1132 bool op_equal(ObjPtr value) {
1133 ASSERT(value);
1134 if (value) {
1135 return op_equal(*value);
1136 }
1137 return false;
1138 }
1139
1140 bool op_equal(Obj & value);
1141
1143 ASSERT(obj);
1144 return op_accurate(*obj);
1145 }
1146 bool op_accurate(Obj & value);
1147
1148 ObjPtr op_bit_and(ObjPtr obj, bool strong) {
1149 ASSERT(obj);
1150 return op_bit_and(*obj, strong);
1151 }
1152
1153 ObjPtr op_bit_and(Obj &obj, bool strong) {
1154 ObjPtr result = Clone();
1155 result->op_bit_and_set(obj, strong);
1156 return result;
1157 }
1158
1159 ObjPtr op_pow(ObjPtr obj) const {
1160 ASSERT(obj);
1161 return op_pow(*obj);
1162 }
1163
1164 ObjPtr op_pow(Obj &obj) const {
1165 ObjPtr result = Clone();
1166 result->op_pow_(obj);
1167 return result;
1168 }
1169
1171 ASSERT(obj);
1172 return op_pow_(*obj);
1173 }
1174
1175 ObjPtr op_pow_(Obj &obj);
1176
1177 // ObjPtr operator^(ObjPtr obj) {
1178 // LOG_RUNTIME("Operator '^' not implementd!");
1179 // }
1180 //
1181 // ObjPtr operator|(ObjPtr obj) {
1182 // LOG_RUNTIME("Operator '|' not implementd!");
1183 // }
1184 //
1185 // ObjPtr operator&&(ObjPtr obj) {
1186 // LOG_RUNTIME("Operator '&&' not implementd!");
1187 // }
1188 //
1189 // ObjPtr operator||(ObjPtr obj) {
1190 // LOG_RUNTIME("Operator '||' not implementd!");
1191 // }
1192
1194 if (obj) {
1195 return op_assign(*obj);
1196 }
1197 clear_();
1198 return shared();
1199 }
1200
1202 clear_();
1203 obj.CloneDataTo(*this);
1204 obj.ClonePropTo(*this);
1205 return shared();
1206 }
1207
1208 bool operator=(Obj & obj) {
1209 clear_();
1210 obj.CloneDataTo(*this);
1211 obj.ClonePropTo(*this);
1212 return true;
1213 }
1214
1215 /*
1216 * ?: (выбор из двух операндов)
1217 * = (присваивание)
1218 * *=, /=, %=, +=, -=, &=, ^=, |=, <<=, >>=, >>>= (операции с присваиванием)
1219 * , (отбрасывание первого и возврат второго операнда)
1220 */
1221
1222
1224 if (!obj) {
1225 ASSERT(obj);
1226 }
1227 return operator*=(*obj);
1228 }
1229
1230 ObjPtr operator*=(Obj obj);
1231
1233 ASSERT(obj);
1234 return operator/=(*obj);
1235 }
1236
1237 ObjPtr operator/=(Obj obj);
1238
1240 ASSERT(obj);
1241 return op_div_ceil_(*obj);
1242 }
1243
1244 ObjPtr op_div_ceil_(Obj &obj);
1245
1247 ASSERT(obj);
1248 return operator%=(*obj);
1249 }
1250
1251 ObjPtr operator%=(Obj obj);
1252
1253
1254 ObjPtr op_bit_and_set(Obj &obj, bool strong);
1255
1257 ASSERT(obj);
1258 return operator^=(*obj);
1259 }
1260
1262 LOG_RUNTIME("Operator '^=' not implementd!");
1263 }
1264
1266 ASSERT(obj);
1267 return operator|=(*obj);
1268 }
1269
1271 LOG_RUNTIME("Operator '|=' not implementd!");
1272 }
1273
1275 ASSERT(obj);
1276 return op_lshift_set(*obj);
1277 }
1278
1280 LOG_RUNTIME("Operator '<<=' not implementd!");
1281 }
1282
1284 ASSERT(obj);
1285 return op_rshift_set(*obj);
1286 }
1287
1289 LOG_RUNTIME("Operator '>>=' not implementd!");
1290 }
1291
1293 ASSERT(obj);
1294 return op_rrshift_set(*obj);
1295 }
1296
1298 LOG_RUNTIME("Operator '>>>=' not implementd!");
1299 }
1300
1301 template <typename T>
1302 bool operator=(T value) {
1303 SetValue_(value);
1304 return true;
1305 }
1306
1307
1308 static ObjPtr GetIndex(ObjPtr obj, TermPtr index_arg);
1309
1310 static ObjPtr GetIndex(ObjPtr obj, size_t index) {
1311 return (*obj)[index].second;
1312 }
1313
1314 void dump_dict_(std::string &str, bool deep = true) const {
1315 bool first = true;
1316 for (auto &elem : * this) {
1317 if (first) {
1318 first = false;
1319 } else {
1320 str.append(", ");
1321 }
1322 if (elem.first.empty()) {
1323 if (elem.second) {
1324 str.append(elem.second->toString(false));
1325 } else {
1326 str.append("_");
1327 }
1328 } else {
1329 if (elem.second) {
1330
1331 if (deep || !(elem.second->is_tensor_type() || elem.second->getType() == ObjType::Class)) {
1332 str.append(elem.first);
1333 str.append("=");
1334 str.append(elem.second->toString(false));
1335 } else if (elem.second->getType() == ObjType::Class && elem.second->m_is_reference) {
1336 str.append("&");
1337 str.append(elem.second->getName());
1338 } else {
1339
1340 str.append(elem.second->getName());
1341 str.append("=");
1342 str.append(elem.second->toString());
1343 }
1344 } else {
1345 str.append("_");
1346 }
1347 }
1348 }
1349 }
1350
1351 std::string toString(bool deep = true) const;
1352
1353 std::string GetValueAsString() const;
1354
1355 std::wstring GetValueAsStringWide() const {
1356 return utf8_decode(GetValueAsString());
1357 }
1358
1359 std::shared_ptr<Rational> GetValueAsRational() const {
1360 TEST_INIT_();
1362 return m_rational.clone();
1363 } else if (is_integral()) {
1364 return std::make_shared<Rational>(GetValueAsInteger());
1365 } else if (is_floating()) {
1366 ASSERT("Not implemented!");
1367 }
1368 LOG_RUNTIME("Value %s incompatible to Rational or convert not implemented!", toString().c_str());
1369 }
1370
1371 int64_t GetValueAsInteger() const;
1372 double GetValueAsNumber() const;
1373
1374 bool GetValueAsBoolean() const;
1375
1376 static ObjPtr CreateType(ObjType type, ObjType fixed = ObjType::None, bool is_init = false, Sync *sync = nullptr) {
1377 return std::make_shared<Obj>(type, nullptr, nullptr, fixed, is_init, sync);
1378 }
1379
1380// static ObjPtr CreateReference(ObjPtr obj, RefType ref_type) {
1381//
1382// ASSERT(obj);
1383//
1384// if (ref_type == RefType::Value) {
1385// LOG_RUNTIME("Invalid reference type!");
1386// }
1387// if (!obj->m_sync) {
1388// LOG_RUNTIME("The object does not allow creating reference!");
1389// }
1390//
1391// switch (obj->m_sync->GetRefType()) {
1392// case RefType::LiteSingle:
1393// case RefType::LiteSingleConst:
1394// if (!(ref_type == RefType::LiteSingle || ref_type == RefType::LiteSingleConst)) {
1395// LOG_RUNTIME("Reference type error!");
1396// }
1397// break;
1398// case RefType::LiteThread:
1399// case RefType::LiteThreadConst:
1400// if (!(ref_type == RefType::LiteThread || ref_type == RefType::LiteThreadConst)) {
1401// LOG_RUNTIME("Reference type error!");
1402// }
1403// break;
1404// case RefType::SyncMono:
1405// case RefType::SyncMonoConst:
1406// if (!(ref_type == RefType::SyncMono || ref_type == RefType::SyncMonoConst)) {
1407// LOG_RUNTIME("Reference type error!");
1408// }
1409// break;
1410// case RefType::SyncMulti:
1411// case RefType::SyncMultiConst:
1412// if (!(ref_type == RefType::SyncMulti || ref_type == RefType::SyncMultiConst)) {
1413// LOG_RUNTIME("Reference type error!");
1414// }
1415// break;
1416// default:
1417// LOG_RUNTIME("Invalid reference type!");
1418// }
1419//
1420// if (isEditableRef(ref_type) && isConstRef(obj->m_sync->GetRefType())) {
1421// LOG_RUNTIME("Read-only reference are allowed!");
1422// }
1423//
1424// ObjPtr result = Obj::CreateType(ObjType::Reference, obj->m_var_type_fixed, true, obj->m_sync);
1425// result->m_reference = obj;
1426// return result;
1427// }
1428
1429 // inline Taken Take(bool edit_mode = true, const std::chrono::milliseconds & timeout_duration = Sync::SyncTimeoutDeedlock) {
1430 // if (m_var_type_current == ObjType::Reference) {
1431 // return Taken(m_reference, m_sync, edit_mode, timeout_duration);
1432 // } else {
1433 // return Taken(shared(), m_sync, edit_mode, timeout_duration);
1434 // }
1435 // }
1436
1437 static ObjPtr CreateRational(const Rational & val) {
1439 obj->m_rational = val;
1440 return obj;
1441 }
1442
1443 static ObjPtr CreateRational(const std::string val) {
1444
1445 std::string str;
1446 std::remove_copy(val.begin(), val.end(), back_inserter(str), '_');
1447
1448 if (str.empty()) {
1449 LOG_RUNTIME("Empty string!");
1450 }
1451
1453
1454 // Ищем разделитель дроби
1455 size_t pos = str.find("\\");
1456
1457 // Если символ не найден - то вся строка является числом
1458 if (pos == std::string::npos) {
1459 obj->m_rational.set_(0);
1460 } else {
1461 // Числитель - левая часть
1462 // Знаменатель - правая часть
1463 obj->m_rational.set_(str.substr(0, pos), str.substr(pos + 1, str.length()));
1464 // Знаменатель не должен быть равен нулю
1465 if (obj->m_rational.m_denominator.isZero()) {
1466 LOG_RUNTIME("Denominator must be different from zero!");
1467 }
1468 }
1469
1470 obj->m_var_is_init = true;
1471 if (str.compare(obj->m_rational.GetAsString().c_str()) != 0) {
1472
1473 LOG_RUNTIME("Rational value '%s' does not match source string '%s'!", obj->m_rational.GetAsString().c_str(), str.c_str());
1474 }
1475
1476 return obj;
1477 }
1478
1479
1480 // чистая функция
1481 static ObjPtr BaseTypeConstructor(Context *ctx, Obj & in);
1482 static ObjPtr ConstructorSimpleType_(Context *ctx, Obj & args);
1483 static ObjPtr ConstructorDictionary_(Context *ctx, Obj & args);
1484 static ObjPtr ConstructorNative_(Context *ctx, Obj & args);
1485 static ObjPtr ConstructorStub_(Context *ctx, Obj & args);
1486 static ObjPtr ConstructorClass_(Context *ctx, Obj & args);
1487 static ObjPtr ConstructorStruct_(Context *ctx, Obj & args);
1488 static ObjPtr ConstructorEnum_(Context *ctx, Obj & args);
1489
1490 // static ObjPtr ConstructorError_(Context *ctx, Obj & args);
1491 // static ObjPtr ConstructorReturn_(Context *ctx, Obj & args);
1492 // static ObjPtr ConstructorThread_(Context *ctx, Obj & args);
1493 // static ObjPtr ConstructorSystem_(Context *ctx, Obj & args);
1494 // static ObjPtr ConstructorInterraption_(Context *ctx, Obj & args, ObjType type);
1495
1496 static ObjPtr CreateBaseType(ObjType type);
1497
1498 std::vector<int64_t> toIntVector(bool raise = true) const {
1499 std::vector<int64_t> result;
1500 for (int i = 0; i < size(); i++) {
1501 if (raise && !at(i).second->is_integer()) {
1502
1503 LOG_RUNTIME("Item does not contain an integer value! '%s'", at(i).second->GetValueAsString().c_str());
1504 }
1505 result.push_back(at(i).second->GetValueAsInteger());
1506 }
1507 return result;
1508 }
1509
1510 static ObjPtr CreateNone(Sync *sync = nullptr) {
1511 return CreateType(ObjType::None, ObjType::None, true, sync);
1512 }
1513
1514 static ObjPtr CreateEmpty(Sync *sync = nullptr) {
1515 return CreateType(ObjType::None, ObjType::None, false, sync);
1516 }
1517
1518 static ObjPtr CreatePointer(void * ptr = nullptr, Sync *sync = nullptr) {
1520 obj->m_var = ptr;
1521 return obj;
1522 }
1523
1524 static ObjPtr CreateNil(Sync *sync = nullptr) {
1525 return CreatePointer(nullptr, sync);
1526 }
1527
1528 static ObjPtr CreateBool(bool value, Sync *sync = nullptr) {
1530 result->SetValue_(value);
1531
1532 return result;
1533 }
1534
1535 template <typename T1, typename T2, typename T3>
1536 static ObjPtr CreateRange(T1 start, T2 stop, T3 step, Sync *sync = nullptr) {
1538 obj->push_back(CreateValue(start, ObjType::None), "start");
1539 obj->push_back(CreateValue(stop, ObjType::None), "stop");
1540 obj->push_back(CreateValue(step, ObjType::None), "step");
1541 obj->m_var_type_current = ObjType::Range;
1542 return obj;
1543 }
1544
1545 template <typename T1, typename T2>
1546 static ObjPtr CreateRange(T1 start, T2 stop, Sync *sync = nullptr) {
1548 obj->push_back(CreateValue(start, ObjType::None), "start");
1549 obj->push_back(CreateValue(stop, ObjType::None), "stop");
1550 if (start < stop) {
1551 obj->push_back(CreateValue(1, ObjType::None), "step");
1552 } else {
1553 obj->push_back(CreateValue(-1, ObjType::None), "step");
1554 }
1555 obj->m_var_type_current = ObjType::Range;
1556
1557 return obj;
1558 }
1559
1560 template <typename T>
1561 typename std::enable_if < std::is_same<T, std::string>::value || std::is_same<T, const char *>::value, ObjPtr>::type
1562 static CreateValue(T value, Sync *sync = nullptr) {
1563 return Obj::CreateString(value, sync);
1564 }
1565
1566 template <typename T>
1567 typename std::enable_if < std::is_same<T, std::wstring>::value || std::is_same<T, const wchar_t *>::value, ObjPtr>::type
1568 static CreateValue(T value, Sync *sync = nullptr) {
1569 return Obj::CreateString(value, sync);
1570 }
1571
1572 template <typename T>
1573 typename std::enable_if<std::is_integral<T>::value, ObjPtr>::type
1574 static CreateValue(T value, ObjType fix_type = ObjType::None, Sync *sync = nullptr) {
1575 ObjPtr result = CreateType(typeFromLimit((int64_t) value), fix_type, true, sync);
1576 if (fix_type != ObjType::None) {
1577 NL_CHECK(canCast(result->m_var_type_current, fix_type),
1578 "Fail cast type from '%s' to '%s'!", newlang::toString(result->m_var_type_current), newlang::toString(fix_type));
1579 }
1580 result->m_var = static_cast<int64_t> (value);
1581 return result;
1582 }
1583
1584 template <typename T>
1585 typename std::enable_if<std::is_floating_point<T>::value, ObjPtr>::type
1586 static CreateValue(T value, ObjType fix_type = ObjType::None, Sync *sync = nullptr) {
1587 ObjPtr result = CreateType(typeFromLimit((double) value), fix_type, true, sync);
1588 if (fix_type != ObjType::None) {
1589 NL_CHECK(canCast(result->m_var_type_current, fix_type),
1590 "Fail cast type from '%s' to '%s'!", newlang::toString(result->m_var_type_current), newlang::toString(fix_type));
1591 }
1592 result->m_var = static_cast<double> (value);
1593 return result;
1594 }
1595
1596 static ObjPtr CreateString(const std::string_view str, Sync *sync = nullptr) {
1598 result->m_value = std::string(str);
1599 return result;
1600 }
1601
1602 static ObjPtr CreateString(const std::wstring_view str, Sync *sync = nullptr) {
1604 result->m_string = std::wstring(str);
1605 ;
1606 return result;
1607 }
1608
1609 static ObjPtr Yes(Sync *sync = nullptr) {
1611 result->m_var = static_cast<int64_t> (1);
1612 return result->MakeConst();
1613 }
1614
1615 static ObjPtr No(Sync *sync = nullptr) {
1617 result->m_var = static_cast<int64_t> (0);
1618 return result->MakeConst();
1619 }
1620
1621 // static ObjPtr None(Sync *sync = nullptr) {
1622 // return Obj::CreateType(ObjType::None, ObjType::None, true, sync);
1623 // }
1624
1625 static ObjPtr CreateDict(Sync *sync = nullptr) {
1627 }
1628
1629 template <typename... T>
1630 typename std::enable_if<is_all<PairType, T ...>::value, ObjPtr>::type
1631 static CreateDict(T ... args) {
1632 std::array < PairType, sizeof...(args) > list = {args...};
1634 for (auto &elem : list) {
1635 result->push_back(elem);
1636 }
1637 result->m_var_is_init = true;
1638
1639 return result;
1640 }
1641
1642 static ObjPtr CreateDict(const std::vector<ObjPtr> & arr, Sync *sync = nullptr) {
1644 for (size_t i = 0; i < arr.size(); i++) {
1645 result->push_back(arr[i]);
1646 }
1647 return result;
1648 }
1649
1650 /*
1651 * <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1652 * Различие между классом и словарям в том, что элементы словаря могут добавлятся и удаляться динамически,
1653 * а у класса состав полей фиуксируется при определении и в последствии они не могут быть добалвены или удалены.
1654 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
1655 *
1656 */
1657 static ObjPtr CreateClass(std::string name) {
1659 result->m_class_name = name;
1660 result->m_var_is_init = true;
1661
1662 return result;
1663 }
1664
1665 template <typename... T>
1666 typename std::enable_if<is_all<PairType, T ...>::value, ObjPtr>::type
1667 static CreateClass(std::string name, T ... args) {
1668 std::array < PairType, sizeof...(args) > list = {args...};
1670 result->m_class_name = name;
1671 for (auto &elem : list) {
1672 result->push_back(elem);
1673 }
1674 result->m_var_is_init = true;
1675
1676 return result;
1677 }
1678
1679
1681
1682 ObjPtr Copy() const {
1683 ObjPtr copy = Obj::CreateNone();
1684 CloneDataTo(*copy);
1685 ClonePropTo(*copy);
1686 return copy;
1687 }
1688
1689 ObjPtr Clone(const char *new_name = nullptr) const {
1693 if (new_name) {
1694
1695 clone->m_var_name = new_name;
1696 }
1697 return clone;
1698 }
1699
1701 if (&clone == this) {
1702 // Не клонировать сам в себя
1703
1704 return;
1705 }
1708 }
1709
1711 if (clone.get() == this) {
1712 // Не клонировать сам в себя
1713
1714 return;
1715 }
1716 clone.reset();
1720 }
1721
1722 void CloneDataTo(Obj & clone) const;
1723 void ClonePropTo(Obj & clone) const;
1724
1725 ObjPtr toType(ObjType type) const {
1726 ObjPtr clone = Clone();
1727 clone->toType_(type);
1728
1729 return clone;
1730 }
1731
1732 /*
1733 * Варианты преобраования типов
1734 * Range -> Dict
1735 * Tensor -> Dict
1736 * Dict -> Tensor
1737 * String -> Tensor
1738 * Tensor -> String
1739 */
1740 void toType_(ObjType type);
1741
1742 virtual ~Obj() {
1743
1744 clear_();
1745 }
1746
1747
1748 const ObjPtr index_get(const std::vector<Index> & index) const;
1749
1750 ObjPtr index_set(const std::vector<Index> & index, const ObjPtr value) const {
1751 ObjPtr result = Clone();
1752 result->index_set_(index, value);
1753
1754 return result;
1755 }
1756 ObjPtr index_set_(const std::vector<Index> & index, const ObjPtr value);
1757
1759
1760 return op_set_index(index->GetValueAsInteger(), value->GetValueAsString());
1761 }
1762 ObjPtr op_set_index(int64_t index, std::string value);
1763
1764 template < typename T>
1765 typename std::enable_if < std::is_same<T, bool>::value, void>::type
1766 SetValue_(bool value) {
1767
1768 SetValue_(static_cast<int64_t> (value));
1769 }
1770
1771 template < typename T>
1772 typename std::enable_if<std::is_integral<T>::value, void>::type
1773 SetValue_(T value) {
1774
1775 TEST_CONST_();
1777 clear_();
1778 m_var = static_cast<int64_t> (value);
1779 m_var_type_current = typeFromLimit(static_cast<int64_t> (value));
1780 m_var_is_init = true;
1781 }
1782
1783 template < typename T>
1784 typename std::enable_if<std::is_floating_point<T>::value, void>::type
1785 SetValue_(T value) {
1786
1787 TEST_CONST_();
1789 clear_();
1790 m_var = static_cast<double> (value);
1792 m_var_is_init = true;
1793 }
1794
1795 template < typename T>
1796 typename std::enable_if<std::is_same<char *, T>::value, void>::type
1797 SetValue_(T text) {
1798
1799 std::string str(text);
1800 SetValue_(text);
1801 }
1802
1803 template < typename T>
1804 typename std::enable_if < std::is_same<wchar_t *, T>::value, void>::type
1805 SetValue_(T text) {
1806
1807 std::wstring str(text);
1808 SetValue_(text);
1809 }
1810
1811 void SetValue_(std::string text) {
1812 TEST_CONST_();
1814
1817 }
1818 m_value.swap(text);
1819 m_var_is_init = true;
1820 }
1821
1822 void SetValue_(std::wstring text) {
1823 TEST_CONST_();
1825
1828 }
1829 m_string.swap(text);
1830 m_var_is_init = true;
1831 }
1832
1835
1836 return;
1837 }
1838 LOG_RUNTIME("Cannot changed type from '%s' to '%s'!", newlang::toString(type), newlang::toString(m_var_type_fixed));
1839 }
1840
1841 void testResultIntegralType(ObjType type, bool upscalint);
1842
1843 void SetValue_(ObjPtr value);
1844
1845 // static std::string format(std::string format, Obj * args);
1846
1847
1848 bool CallAll(const char *func_name, ObjPtr &arg_in, ObjPtr &result, ObjPtr object = nullptr, size_t limit = 0); // ?
1849 bool CallOnce(ObjPtr &arg_in, ObjPtr &result, ObjPtr object = nullptr); // !
1850
1851 const TermPtr Proto() {
1852
1853 return m_prototype;
1854 }
1855
1856 SCOPE(protected) :
1857
1858 public:
1859
1860 void remove(const Dict::PairType & value) {
1861 Dict::remove(value);
1862 }
1863
1867
1868
1869 // std::string m_namespace;
1870 std::string m_var_name;
1871 std::string m_class_name;
1872 std::vector<ObjPtr> m_class_parents;
1873 std::string m_module_name;
1875 public:
1877
1879
1880 mutable PairType m_str_pair; //< Для доступа к отдельным символам строк
1881
1883
1884 // Применение variant необходимо для полей хранения данных, чтобы контролировать их инициализацию
1885 // std::variant<std::monostate, void *, torch::Tensor, std::string, std::wstring, std::string_view, std::wstring_view,
1886 // std::shared_ptr<Rational>, std::shared_ptr< Iterator<Obj> >, TermPtr> m_var;
1887
1888 // std::variant<std::monostate, void *, torch::Tensor, std::string, std::wstring, std::string_view, std::wstring_view> m_var;
1889
1890 struct NativeData {
1891 void * ptr;
1892 int64_t size;
1893 };
1894
1895 std::variant < std::monostate, int64_t, double, void *, // None, скаляры и ссылки на функции (нужно различать чистые, обычные и нативные???)
1896 bool *, int8_t *, int16_t *, int32_t *, int64_t *, float *, double *, NativeData, // Ссылки на нативные скаляры и данные
1897 std::string, TermPtr, Iterator < Obj>> m_var; //Rational, ModulePtr,
1898
1899 // union {
1900 // int64_t m_integer;
1901 // double m_number;
1902 // void *m_pointer; ///< Содержит указатель на нативную функцию или область памяти с данными или скаляр
1903 // };
1904
1905 std::string m_value;
1906 std::wstring m_string;
1907 std::shared_ptr<torch::Tensor> m_tensor;
1909 std::shared_ptr<Iterator < Obj>> m_iterator;
1913
1916
1917 bool m_check_args; //< Проверять аргументы на корректность (для всех видов функций) @ref MakeArgs
1918
1919 /* Для будущей переделки системы типов и базового класса:
1920 * Должен быть интерфейс с поддерживаемыми операциями для стандартных типов данных
1921 * и набор реализаций для скаляров, строк, тензоров, нативных функций, дробей, внутренних функций и т.д.
1922 */
1923
1924 // SCOPE(protected) :
1925 bool m_is_const; //< Признак константы (по умолчанию изменения разрешено)
1926 bool m_is_reference; //< Признак ссылки на объект
1927 };
1928
1929 class IntAny : public Obj {
1930 public:
1931 IntAny(const ObjPtr value, ObjType type);
1932
1933 virtual ~IntAny() {
1934 }
1935 };
1936
1937 class IntPlus : public IntAny {
1938 public:
1939
1940 IntPlus(const ObjPtr value) : IntAny(value, ObjType::RetPlus) {
1941 }
1942 };
1943
1944 class IntMinus : public IntAny {
1945 public:
1946
1947 IntMinus(const ObjPtr value) : IntAny(value, ObjType::RetMinus) {
1948 }
1949 };
1950
1951
1952} // namespace newlang
1953
1954std::ostream & operator<<(std::ostream &out, newlang::Obj & var);
1955std::ostream & operator<<(std::ostream &out, newlang::ObjPtr var);
1956
1957
1958#endif // INCLUDED_OBJECT_H_
std::pair< std::string, Type > PairType
Definition dict.h:77
ListType::iterator find(const std::string_view name)
Definition dict.h:122
virtual int64_t index(const std::string_view field_name)
Definition dict.h:149
virtual int64_t resize(int64_t new_size, const Type fill, const std::string &name="")
Definition dict.h:161
PairType & push_back(const PairType &p)
Definition dict.h:94
virtual const std::string & name(const int64_t index) const
Definition dict.h:145
ListType::const_iterator at_index_const(const int64_t index) const
Definition dict.h:208
ListType::iterator at_index(const int64_t index)
Definition dict.h:181
static PairType pair(const Type value, const std::string name="")
Definition dict.h:110
virtual PairType & at(const int64_t index)
Definition dict.h:114
std::list< PairType > ListType
Definition dict.h:78
virtual void clear_()
Definition dict.h:157
virtual void erase(const int64_t index)
Definition dict.h:235
PTR Type
Definition dict.h:76
virtual ~IntAny()
Definition object.h:1933
IntAny(const ObjPtr value, ObjType type)
Definition object.cpp:3777
IntMinus(const ObjPtr value)
Definition object.h:1947
IntPlus(const ObjPtr value)
Definition object.h:1940
const iterator operator++(int) const
Definition object.h:305
bool operator==(const iterator &other) const
Definition object.h:309
Iterator< T > iterator
Definition object.h:178
Iterator(std::shared_ptr< T > obj, CompareFuncType *func, T *arg, void *extra=nullptr)
Definition object.h:207
const IterPairType & data() const
Definition object.h:284
iterator begin()
Definition object.h:261
bool operator!=(const iterator &other) const
Definition object.h:313
iterator end()
Definition object.h:267
static IterCmp CompareFuncDefault(const IterPairType &pair, const T *filter, void *extra)
Definition object.h:228
Iterator(const Iterator &iter)
Definition object.h:212
Dict< T >::Type IterObjPtr
Definition object.h:182
void search_loop() const
Definition object.h:325
CompareFuncType * m_func
Definition object.h:220
const IterPairType & data()
Definition object.h:273
Dict< T >::ListType IterListType
Definition object.h:184
const char * m_base_filter
Definition object.h:224
void * m_func_extra
Definition object.h:222
IterCmp CompareFuncType(const IterPairType &pair, const T *args, void *extra)
Definition object.h:187
Dict< T >::iterator m_found
Definition object.h:223
Iterator(std::shared_ptr< T > obj, const char *find_key="(.|\\n)*")
Definition object.h:196
Iterator< const T > const_iterator
Definition object.h:179
const IterPairType & operator*()
Definition object.h:280
std::string m_filter
Definition object.h:219
std::shared_ptr< T > m_iter_obj
Definition object.h:217
Dict< T >::PairType IterPairType
Definition object.h:183
ObjPtr read_and_next(int64_t count)
std::regex m_match
Definition object.h:218
const IterPairType & operator*() const
Definition object.h:291
Dict< T > IterObj
Definition object.h:181
const iterator & operator++() const
Definition object.h:297
static const IterPairType m_Iterator_end
Definition object.h:226
void SetClassName(std::string &name)
Definition object.h:451
ObjPtr operator/(ObjPtr obj)
Definition object.h:969
std::enable_if<!is_all< Obj::PairType, T... >::value, ObjPtr >::type operator()(T ... args)
Definition object.h:697
static ObjPtr No(Sync *sync=nullptr)
Definition object.h:1615
ObjPtr operator^=(Obj)
Definition object.h:1261
ObjPtr op_rrshift_set(ObjPtr obj)
Definition object.h:1292
virtual ~Obj()
Definition object.h:1742
ObjPtr op_concat(Obj &value, ConcatMode mode=ConcatMode::Error)
Definition object.h:996
ObjPtr operator^=(ObjPtr obj)
Definition object.h:1256
static ObjPtr ConstructorSimpleType_(Context *ctx, Obj &args)
Definition object.cpp:2634
void SetValue_(std::wstring text)
Definition object.h:1822
ObjPtr operator()()
Definition object.h:672
bool operator>(Obj obj)
Definition object.h:1095
static PairType ArgNull(const std::string name="")
Definition object.h:363
ObjPtr op_concat(ObjPtr obj, ConcatMode mode=ConcatMode::Error)
Definition object.h:991
ObjPtr op_pow(Obj &obj) const
Definition object.h:1164
bool is_string_char_type() const
Definition object.h:486
Dict< Obj >::PairType & at(ObjPtr find)
Definition object.h:656
bool operator<(Obj obj)
Definition object.h:1073
ObjPtr CallNative(Context *ctx, Obj args)
ObjPtr op_set_index(ObjPtr index, ObjPtr value)
Definition object.h:1758
ObjPtr op_bit_and_set(Obj &obj, bool strong)
Definition object.cpp:1837
bool is_function_type() const
Definition object.h:525
virtual ObjPtr IteratorReset()
Definition object.cpp:3289
const ObjPtr index_get(const std::vector< Index > &index) const
Definition object.cpp:411
Obj::iterator find(const std::string name)
Definition object.h:749
ObjPtr operator*(ObjPtr obj)
Definition object.h:958
static ObjPtr CreateString(const std::wstring_view str, Sync *sync=nullptr)
Definition object.h:1602
ObjPtr operator-(ObjPtr obj)
Definition object.h:1039
bool is_simple_type() const
Definition object.h:517
static ObjPtr ConstructorStub_(Context *ctx, Obj &args)
Definition object.cpp:2854
bool is_any_size()
Definition object.h:606
void CloneTo(Obj &clone)
Definition object.h:1700
ObjPtr op_call(ObjPtr args)
Definition object.h:677
ObjPtr operator|=(Obj)
Definition object.h:1270
static std::enable_if< std::is_floating_point< T >::value, ObjPtr >::type CreateValue(T value, ObjType fix_type=ObjType::None, Sync *sync=nullptr)
Definition object.h:1586
static ObjPtr CreateRange(T1 start, T2 stop, T3 step, Sync *sync=nullptr)
Definition object.h:1536
virtual ObjPtr IteratorMake(const char *filter=nullptr, bool check_create=true)
Definition object.cpp:3191
ObjPtr op_bit_and(Obj &obj, bool strong)
Definition object.h:1153
bool operator<=(Obj obj)
Definition object.h:1086
bool operator>=(ObjPtr obj)
Definition object.h:1099
ObjPtr operator%=(ObjPtr obj)
Definition object.h:1246
Obj::iterator end()
Definition object.h:763
virtual int64_t size() const
Definition object.h:624
int op_compare(Obj &value)
Definition object.cpp:1716
void ClonePropTo(Obj &clone) const
Definition object.cpp:1028
virtual bool empty() const
Definition object.cpp:193
static ObjPtr CreateString(const std::string_view str, Sync *sync=nullptr)
Definition object.h:1596
static std::enable_if< std::is_pointer< T >::value||std::is_same< std::string, T >::value, PairType >::type Arg(T value, const std::string name="")
Definition object.h:379
std::variant< std::monostate, int64_t, double, void *, bool *, int8_t *, int16_t *, int32_t *, int64_t *, float *, double *, NativeData, std::string, TermPtr, Iterator< Obj > > m_var
Definition object.h:1897
bool operator>=(Obj obj)
Definition object.h:1104
Obj::iterator begin()
Definition object.h:756
Dict< Obj >::PairType & at(const std::string name) override
Definition object.h:643
static ObjPtr GetIndex(ObjPtr obj, TermPtr index_arg)
Definition term.cpp:757
bool is_defined_type()
Definition object.h:601
static ObjPtr ConstructorDictionary_(Context *ctx, Obj &args)
Definition object.cpp:2828
bool CallAll(const char *func_name, ObjPtr &arg_in, ObjPtr &result, ObjPtr object=nullptr, size_t limit=0)
ObjPtr shared()
Definition object.h:389
ObjPtr toType(ObjType type) const
Definition object.h:1725
ObjPtr MakeConst()
Definition object.h:397
size_t ItemValueCount(ObjPtr &find, bool strong)
Definition object.cpp:968
Obj(ObjType type=ObjType::None, const char *var_name=nullptr, TermPtr func_proto=nullptr, ObjType fixed=ObjType::None, bool init=false, Sync *sync=nullptr)
Definition object.cpp:178
std::vector< ObjPtr > m_class_parents
Родительские классы (типы)
Definition object.h:1872
Context * m_ctx
Definition object.h:1876
static ObjPtr CreateEmpty(Sync *sync=nullptr)
Definition object.h:1514
virtual ObjPtr IteratorData()
Definition object.cpp:3240
ObjPtr operator/(Obj value)
Definition object.h:974
ObjPtr & operator+(ObjPtr &obj)
Definition object.h:923
ObjType m_var_type_current
Текущий тип значения объекта
Definition object.h:1864
bool is_return() const
Definition object.h:590
Rational m_rational
Содержит дробь из длинных чисел
Definition object.h:1908
const std::string & getName() const
Definition object.h:447
bool m_is_const
Definition object.h:1925
ObjPtr op_assign(ObjPtr obj)
Definition object.h:1193
std::enable_if< std::is_same< N, std::string >::value||std::is_pointer< N >::value, constPairType & >::type operator[](const N name)
Definition object.h:742
ObjPtr operator-(Obj value)
Definition object.h:1044
bool is_plain_type() const
Definition object.h:502
bool m_check_args
Definition object.h:1917
static ObjPtr CreateRange(T1 start, T2 stop, Sync *sync=nullptr)
Definition object.h:1546
bool is_none_type() const
Definition object.h:466
ObjPtr op_div_ceil_(ObjPtr obj)
Definition object.h:1239
std::enable_if< is_all< Obj::PairType, T... >::value, ObjPtr >::type operator()(T ... args)
Definition object.h:686
std::shared_ptr< Rational > GetValueAsRational() const
Definition object.h:1359
static ObjPtr Yes(Sync *sync=nullptr)
Definition object.h:1609
bool is_ellipsis() const
Definition object.h:565
bool m_var_is_init
Содержит ли объект корректное значение ???
Definition object.h:1866
static ObjPtr CreateDict(const std::vector< ObjPtr > &arr, Sync *sync=nullptr)
Definition object.h:1642
Sync * m_sync
Definition object.h:1915
bool is_string_type() const
Definition object.h:481
std::enable_if< std::is_integral< T >::value, void >::type SetValue_(T value)
Definition object.h:1773
double GetValueAsNumber() const
Definition object.cpp:1558
std::string GetValueAsString() const
Definition object.cpp:1607
static bool is_true(const char *text)
Definition object.h:666
static ObjPtr CreatePointer(void *ptr=nullptr, Sync *sync=nullptr)
Definition object.h:1518
ObjPtr operator+(Obj value)
Definition object.h:1027
void erase(const size_t from, const size_t to) override
Definition object.cpp:206
ObjPtr operator++()
Definition object.cpp:625
static PairType Arg(ObjPtr value, const std::string name="")
Definition object.h:373
std::string m_func_mangle_name
Definition object.h:1882
ObjPtr operator+(ObjPtr obj)
Definition object.h:1022
bool operator>(ObjPtr obj)
Definition object.h:1090
bool is_floating() const
Definition object.h:555
std::enable_if< std::is_same< T, bool >::value, void >::type SetValue_(bool value)
Definition object.h:1766
static PairType Arg()
Definition object.h:368
bool is_block() const
Definition object.h:595
static ObjPtr GetIndex(ObjPtr obj, size_t index)
Definition object.h:1310
ObjPtr IteratorNext(ObjPtr count)
Definition object.h:413
ObjPtr index_set_(const std::vector< Index > &index, const ObjPtr value)
Definition object.cpp:450
std::string m_var_name
Имя переменной, в которой хранится объект
Definition object.h:1870
ObjPtr operator%(Obj value)
Definition object.h:1016
ObjPtr m_dimensions
Размерности для ObjType::Type.
Definition object.h:1878
std::enable_if< std::is_same< char *, T >::value, void >::type SetValue_(T text)
Definition object.h:1797
static ObjPtr CreateBaseType(ObjType type)
Definition object.cpp:2554
ObjType getType()
Definition object.h:423
ObjPtr operator+()
Definition object.h:914
bool is_type_name() const
Definition object.h:580
std::string m_module_name
Definition object.h:1873
Obj::iterator at_index(const int64_t index)
Definition object.h:798
bool GetValueAsBoolean() const
Definition object.cpp:1394
ObjPtr op_div_ceil(Obj value)
Definition object.h:985
std::vector< int64_t > toIntVector(bool raise=true) const
Definition object.h:1498
std::shared_ptr< Iterator< Obj > > m_iterator
Итератор для данных
Definition object.h:1909
bool is_tensor_type() const
Definition object.h:535
ObjPtr operator/=(ObjPtr obj)
Definition object.h:1232
ObjPtr operator*(Obj value)
Definition object.h:963
bool is_arithmetic_type() const
Definition object.h:476
ObjPtr op_concat_(Obj &obj, ConcatMode mode=ConcatMode::Error)
Definition object.h:1002
ObjPtr Clone(const char *new_name=nullptr) const
Definition object.h:1689
void testResultIntegralType(ObjType type, bool upscalint)
Definition object.cpp:3399
ObjPtr operator-()
Definition object.cpp:590
bool is_class_type() const
Definition object.h:512
void clear_() override
Definition object.h:843
std::enable_if< std::is_same< wchar_t *, T >::value, void >::type SetValue_(T text)
Definition object.h:1805
ObjPtr op_div_ceil(ObjPtr obj)
Definition object.h:980
std::string toString(bool deep=true) const
Definition object.cpp:1049
void remove(const Dict::PairType &value)
Definition object.h:1860
static ObjPtr CreateDict(Sync *sync=nullptr)
Definition object.h:1625
static ObjPtr ConstructorClass_(Context *ctx, Obj &args)
Definition object.cpp:2869
bool is_rational() const
Definition object.h:575
static std::enable_if< is_all< PairType, T... >::value, ObjPtr >::type CreateClass(std::string name, T ... args)
Definition object.h:1667
void testConvertType(ObjType type)
Definition object.h:1833
const TermPtr Proto()
Definition object.h:1851
bool is_complex() const
Definition object.h:550
bool operator<=(ObjPtr obj)
Definition object.h:1081
ObjPtr operator+=(ObjPtr obj)
Definition object.h:1033
bool m_is_reference
Definition object.h:1926
Obj::const_iterator begin() const
Definition object.h:770
ObjPtr operator--()
Definition object.cpp:606
std::string m_class_name
Имя класса объекта (у базовых типов отсуствует)
Definition object.h:1871
static ObjPtr CreateBool(bool value, Sync *sync=nullptr)
Definition object.h:1528
Dict::PairType PairType
Definition object.h:356
bool is_integer() const
Definition object.h:540
static ObjPtr ConstructorStruct_(Context *ctx, Obj &args)
Definition object.cpp:2914
bool exist(ObjPtr &find, bool strong)
Definition object.cpp:535
std::enable_if< std::is_integral< I >::value &&!std::is_pointer< I >::value, constPairType & >::type operator[](const I index)
Definition object.h:733
static std::enable_if<!std::is_same< PairType, T >::value &&!std::is_pointer< T >::value &&!std::is_same< std::string, T >::value, PairType >::type Arg(T value, const std::string name="")
Definition object.h:385
ObjPtr operator-=(ObjPtr obj)
Definition object.h:1050
void erase(const int64_t index) override
Definition object.h:832
PairType & push_back(const Type value, const std::string &name="")
Definition object.h:791
ObjType getTypeAsLimit()
Definition object.h:428
ObjPtr op_concat_(ObjPtr obj, ConcatMode mode=ConcatMode::Error)
Definition object.h:1007
std::enable_if< std::is_floating_point< T >::value, void >::type SetValue_(T value)
Definition object.h:1785
std::wstring GetValueAsStringWide() const
Definition object.h:1355
const TermPtr m_prototype
Описание прототипа функции (или данных)
Definition object.h:1874
ObjWeak m_reference
Definition object.h:1914
void toType_(ObjType type)
Definition object.cpp:2260
static ObjPtr ConstructorEnum_(Context *ctx, Obj &args)
Definition object.cpp:2938
bool is_const() const
Definition object.h:456
static ObjPtr CreateClass(std::string name)
Definition object.h:1657
bool is_integral() const
Definition object.h:545
bool operator=(Obj &obj)
Definition object.h:1208
bool operator=(T value)
Definition object.h:1302
bool op_equal(ObjPtr value)
Definition object.h:1132
static std::enable_if< std::is_same< T, std::string >::value||std::is_same< T, constchar * >::value, ObjPtr >::type CreateValue(T value, Sync *sync=nullptr)
Definition object.h:1562
ObjPtr m_return_obj
Definition object.h:1912
static ObjPtr ConstructorNative_(Context *ctx, Obj &args)
Definition object.cpp:2842
bool operator<(ObjPtr obj)
Definition object.h:1068
const std::string & name(const int64_t index) const override
Definition object.h:819
int64_t resize_(int64_t size, ObjPtr fill, const std::string="")
Definition object.cpp:263
static ObjPtr CreateRational(const Rational &val)
Definition object.h:1437
std::shared_ptr< torch::Tensor > m_tensor
Содержит только размерные тензоры (скляры хранятся в поле m_pointer и не создают m_tensor->defined())
Definition object.h:1907
static std::enable_if< is_all< PairType, T... >::value, ObjPtr >::type CreateDict(T ... args)
Definition object.h:1631
bool is_error() const
Definition object.h:585
bool is_dictionary_type() const
Definition object.h:496
static std::enable_if< std::is_same< T, std::wstring >::value||std::is_same< T, constwchar_t * >::value, ObjPtr >::type CreateValue(T value, Sync *sync=nullptr)
Definition object.h:1568
ObjPtr operator*=(ObjPtr obj)
Definition object.h:1223
std::wstring m_string
Содержит строку широких символов
Definition object.h:1906
Obj::const_iterator end() const
Definition object.h:777
ObjPtr op_lshift_set(ObjPtr obj)
Definition object.h:1274
PairType m_str_pair
Definition object.h:1880
ObjPtr op_rrshift_set(Obj)
Definition object.h:1297
bool op_accurate(ObjPtr obj)
Definition object.h:1142
ObjPtr m_iter_range_value
Definition object.h:1910
bool is_native() const
Definition object.h:530
ObjPtr index_set(const std::vector< Index > &index, const ObjPtr value) const
Definition object.h:1750
Obj::const_iterator insert(Obj::const_iterator pos, const PairType &data)
Definition object.h:812
ObjPtr Copy() const
Definition object.h:1682
std::string m_value
Содержит байтовую строку или байтовый массив с данными для представления в нативном виде (Struct,...
Definition object.h:1905
ObjPtr operator--(int)
Definition object.h:952
ObjPtr operator|=(ObjPtr obj)
Definition object.h:1265
bool is_scalar() const
Definition object.cpp:2142
bool is_init() const
Definition object.h:461
bool op_duck_test(ObjPtr obj, bool strong)
Definition object.h:1125
void SetValue_(std::string text)
Definition object.h:1811
bool CallOnce(ObjPtr &arg_in, ObjPtr &result, ObjPtr object=nullptr)
static bool op_duck_test_prop(Obj *base, Obj *value, bool strong)
Definition object.cpp:1919
ObjPtr op_rshift_set(ObjPtr obj)
Definition object.h:1283
int64_t GetValueAsInteger() const
Definition object.cpp:1454
TermPtr m_sequence
Последовательно распарсенных команд для выполнения
Definition object.h:1911
bool is_range() const
Definition object.h:570
ObjPtr operator++(int)
Definition object.h:940
Dict< Obj >::PairType & at(const std::string name) const
Definition object.h:632
void CloneTo(ObjPtr &clone)
Definition object.h:1710
ObjPtr MakeMutable()
Definition object.h:402
ObjPtr op_pow(ObjPtr obj) const
Definition object.h:1159
ObjPtr op_rshift_set(Obj)
Definition object.h:1288
PairType & push_back(const PairType &p)
Definition object.h:784
ObjType m_var_type_fixed
Максимальный размер для арифметических типов, который задается разработчиком
Definition object.h:1865
static ObjPtr BaseTypeConstructor(Context *ctx, Obj &in)
Definition object.cpp:2577
void SetTermProp(Term &term)
int64_t resize(int64_t new_size, const Type fill, const std::string &name="") override
Definition object.h:823
Obj::const_iterator at_index_const(const int64_t index) const
Definition object.h:805
static ObjPtr CreateNone(Sync *sync=nullptr)
Definition object.h:1510
std::string & getName()
Definition object.h:442
ObjPtr op_lshift_set(Obj)
Definition object.h:1279
ObjPtr op_assign(Obj &obj)
Definition object.h:1201
ObjPtr operator%(ObjPtr obj)
Definition object.h:1011
static ObjPtr CreateType(ObjType type, ObjType fixed=ObjType::None, bool is_init=false, Sync *sync=nullptr)
Definition object.h:1376
void CloneDataTo(Obj &clone) const
Definition object.cpp:980
static std::enable_if< std::is_integral< T >::value, ObjPtr >::type CreateValue(T value, ObjType fix_type=ObjType::None, Sync *sync=nullptr)
Definition object.h:1574
static ObjPtr CreateNil(Sync *sync=nullptr)
Definition object.h:1524
bool is_string_wide_type() const
Definition object.h:491
void dump_dict_(std::string &str, bool deep=true) const
Definition object.h:1314
static ObjPtr CreateRational(const std::string val)
Definition object.h:1443
bool is_indexing() const
Definition object.h:560
bool is_bool_type() const
Definition object.h:471
ObjPtr op_bit_and(ObjPtr obj, bool strong)
Definition object.h:1148
bool op_class_test(ObjPtr obj, Context *ctx) const
Definition object.cpp:1874
ObjPtr op_pow_(ObjPtr obj)
Definition object.h:1170
bool is_other_type() const
Definition object.h:507
virtual ObjPtr IteratorNext(int64_t count)
Definition object.cpp:3306
std::shared_ptr< Rational > clone() const
Definition rational.cpp:223
yylloc step()
int result
Definition lexer.l:367
#define LOG_RUNTIME(format,...)
Definition logger.h:26
#define SCOPE(scope)
Definition logger.h:38
#define STATIC_ASSERT(expr)
Definition logger.h:55
#define ASSERT(condition)
Definition logger.h:60
Definition nlc.h:59
bool isFloatingType(ObjType t)
Definition types.h:732
bool isStringChar(ObjType t)
Definition types.h:759
std::weak_ptr< Obj > ObjWeak
Definition variable.h:30
bool isTypeName(ObjType t)
Definition types.h:804
std::wstring utf8_decode(const std::string str)
Definition variable.cpp:22
bool isStringWide(ObjType t)
Definition types.h:764
bool isString(ObjType t)
Definition types.h:769
bool isClass(ObjType t)
Definition types.h:789
bool isArithmeticType(ObjType t)
Definition types.h:752
bool isEllipsis(ObjType t)
Definition types.h:794
bool isRange(ObjType t)
Definition types.h:799
newlang::ObjPtr clone(newlang::Context *ctx, newlang::Obj &in)
Definition builtin.cpp:39
bool isIntegralType(ObjType t, bool includeBool)
Definition types.h:725
int64_t ConcatData(Obj *dest, Obj &src, ConcatMode mode=ConcatMode::Error)
Definition object.cpp:2061
bool isDictionary(ObjType t)
Definition types.h:784
std::shared_ptr< Term > TermPtr
Definition variable.h:33
bool isNative(ObjType t)
Definition types.h:710
std::shared_ptr< Obj > ObjPtr
Definition variable.h:28
bool isTensor(ObjType t)
Definition types.h:742
bool isPlainDataType(ObjType t)
Definition types.h:779
bool isIndexingType(ObjType curr, ObjType fix)
Definition types.h:814
bool isBooleanType(ObjType t)
Definition types.h:747
ObjType
Definition types.h:524
bool isComplexType(ObjType t)
Definition types.h:737
bool isSimpleType(ObjType t)
Definition types.h:720
ObjPtr CheckSystemField(const Obj *obj, const std::string name)
Definition object.cpp:3314
ObjType typeFromLimit(int64_t value, ObjType type_default=ObjType::Int64)
Definition object.cpp:3788
const char * toString(TermID type)
Definition term.h:126
bool isFunction(ObjType t)
Definition types.h:704
std::vector< int64_t > TensorShapeFromDict(const Obj *obj)
Definition object.cpp:2132
ConcatMode
Definition object.h:48
bool canCast(const ObjType from, const ObjType to)
Definition types.h:967
at::indexing::TensorIndex Index
Definition object.h:12
at::IntArrayRef Dimension
Definition object.h:13
#define TEST_INIT_()
Definition object.h:420
#define PLACE_RANGE_CHECK_VALUE(itype, utype)
Definition object.h:858
#define TEST_CONST_()
Definition object.h:419
std::ostream & operator<<(std::ostream &out, newlang::Obj &var)
Definition object.cpp:164
#define NL_CHECK(cond, format,...)
Definition types.h:326