NewLang Project
Yet another programm language
Loading...
Searching...
No Matches
types.h
Go to the documentation of this file.
1#ifndef INCLUDED_TYPES_H_
2#define INCLUDED_TYPES_H_
3
4#include <map>
5#include <set>
6#include <iosfwd>
7#include <memory>
8#include <mutex>
9#include <shared_mutex>
10#include <thread>
11#include <future>
12#include <vector>
13#include <deque>
14#include <iterator>
15#include <iomanip>
16#include <variant>
17#include <algorithm>
18#include <stdexcept>
19#include <type_traits>
20#include <string_view>
21#include <cmath>
22#include <random>
23#include <typeindex>
24#include <locale>
25#include <codecvt>
26#include <functional>
27#include <regex>
28#include <filesystem>
29#include <utility>
30#include <cstdlib>
31#include <ctime>
32#include <complex>
33#include <source_location>
34#include <stacktrace>
35
36#include <sstream>
37#include <iostream>
38#include <fstream>
39#include <fcntl.h>
40
41#include <stdarg.h>
42#include <sys/stat.h>
43#include <sys/types.h>
44#include <linux/limits.h>
45
46#ifdef _MSC_VER
47
48#include <windows.h>
49#include <wchar.h>
50
51#else
52
53#include <wait.h>
54#include <dlfcn.h>
55#include <sys/param.h>
56#include <sys/utsname.h>
57#include <unistd.h>
58
59#endif
60
61
62#ifndef DOXYGEN_SHOULD_SKIP_THIS
63
64namespace c10 {
65 template <typename T>
66 class ArrayRef;
67}
68
69namespace at {
70 namespace indexing {
71 struct TensorIndex;
72 }
73}
74
75namespace at {
76 class Tensor;
77 class ArrayRef;
78 using IntArrayRef = c10::ArrayRef<int64_t>;
79} // namespace at
80
81namespace torch {
82 using at::Tensor;
83 namespace serialize {
84 class OutputArchive;
85 class InputArchive;
86 } // namespace serialize
87} // namespace torch
88
89#endif
90
91
92#include "logger.h"
93#include "rational.h"
94#include "build_options.data"
95#include "variable.h"
96
97namespace newlang {
98
99 static constexpr const char* ws = " \t\n\r\f\v";
100
101 inline std::string & rtrim(std::string& s, const char* t = ws) {
102 s.erase(s.find_last_not_of(t) + 1);
103 return s;
104 }
105
106 inline std::string & ltrim(std::string& s, const char* t = ws) {
107 s.erase(0, s.find_first_not_of(t));
108 return s;
109 }
110
111 inline std::string & trim(std::string& s, const char* t = ws) {
112 return ltrim(rtrim(s, t), t);
113 }
114
115 template <typename T>
116 T repeat(T str, const std::size_t n) {
117 if (n == 0) {
118 str.clear();
119 str.shrink_to_fit();
120 return str;
121 } else if (n == 1 || str.empty()) {
122 return str;
123 }
124 const auto period = str.size();
125 if (period == 1) {
126 str.append(n - 1, str.front());
127 return str;
128 }
129 str.reserve(period * n);
130 std::size_t m{2};
131 for (; m < n; m *= 2) str += str;
132 str.append(str.c_str(), (n - (m / 2)) * period);
133 return str;
134 }
135
136 template<class T>
137 T BaseFileName(T const & path, T const & delims = "/\\") {
138 return path.substr(path.find_last_of(delims) + 1);
139 }
140
141 template<class T>
142 T RemoveFileExtension(T const & filename) {
143 typename T::size_type const p(filename.find_last_of('.'));
144 return p > 0 && p != T::npos ? filename.substr(0, p) : filename;
145 }
146
147
148typedef std::vector<std::string> StringArray;
149
150class Context;
151class Module;
152class JIT;
153
154class IntAny;
155class IntPlus;
156class IntMinus;
157
158namespace runtime {
159 class Buildin;
160}
161
162class Macro;
163class Parser;
164class RunTime;
165class Diag;
166
167typedef std::shared_ptr<Module> ModulePtr;
168typedef std::shared_ptr<runtime::Buildin> BuildinPtr;
169
170/*
171 * RunTime - класс синглетон для процесса. В нем происходит загрузка модулей, взаимодействие
172 * со средой выполнения. В нем находится таблица имен для всего приложения Named (weak_ptr)
173 * Module - класс для одного модуля. Один файл - один модуль. Являеся владельцем объектов данного модуля (shared_ptr)
174 * Context - класс локальных переменных выполнения одного потока.
175 *
176 * val := 123; # Обычная переменная - владелец объекта без возможности создания ссылки на объект
177 * т.е. val2 := &val; # Ошибка !!!!
178 * & ref := & 123; # Переменная - владелец объекта с возможностью создать ссылку в текущем потоке
179 * т.е. ref2 := &ref; # ОК, но только в рамках одного потока !!!!
180 * && ref_mt := && 123; # Переменная - владелец объекта с возможностью создать ссылку в одном потоке без синхронизации
181 * в разных потоках приложения (с межпотоковой синхронизацией) т.е. ref_mt2 := &&ref_mt; # ОК !!!!
182
183 *
184 */
185
187 TermPtr term; // Прототип и место определения
188 Variable var; // Вычисленное значение
189
191 return VariablePair(term, d);
192 }
193
194 template<typename D>
195 typename std::enable_if<!std::is_same<Variable, D>::value, VariablePair>::type
196 static Create(TermPtr term, D d) {
197 return VariablePair(term, Variable(d));
198 }
199
200 };
201
202// struct GlobalPair {
203// TermPtr term; // From AST - clear in optimization???
204// VariablePairWeak var; // From Module or Context (TermPtr - clear in optimization???)
205// };
206
207 class GlobalObjects: protected std::map<std::string, VariablePair> {
208 public:
209
211 std::map<std::string, ModulePtr> m_modules;
212
213// typedef VarPair ItemType;
214 typedef std::pair<std::string, VariablePair> PairType;
215
224 bool RegisterObject(bool only_new, const std::string_view name, TermPtr term, Variable var);
225 VariablePair * FindObject(const std::string_view name);
226// VarData & GetObject(const std::string_view name);
227// TermPtr FindTerm(const std::string_view name);
228
229 inline size_t size(){
230 return std::map<std::string, VariablePair>::size();
231 }
232
233
235
236 std::string Dump(const std::string_view filter="", const char delim=';');
237 };
238
239typedef std::vector<TermPtr> BlockType;
240typedef std::vector<ObjPtr> ArrayObjType;
241
242typedef std::shared_ptr<RunTime> RuntimePtr;
243typedef std::shared_ptr<Diag> DiagPtr;
244typedef std::shared_ptr<Macro> MacroPtr;
245typedef std::shared_ptr<Parser> ParserPtr;
246typedef std::shared_ptr<Context> RunnerPtr;
247
248typedef ObjPtr FunctionType(Context *ctx, Obj &in);
249
250//typedef std::variant<std::monostate, ObjWeak, std::vector < ObjWeak> > WeakItem;
251
252typedef ObjPtr(*EvalFunction)(Context *ctx, const TermPtr & term, Obj * args, bool eval_block);
253
254 typedef std::shared_ptr<std::string> SourceType;
255 typedef std::vector<std::string> PostLexerType;
256
257
258void NewLangSignalHandler(int signal);
259
260
261//struct Docs;
262//typedef std::shared_ptr<Docs> DocPtr;
263//
264//struct Docs {
265//
266// static std::multimap<std::string, DocPtr> m_docs;
267//
268// std::string index;
269// std::string text;
270//
271// Docs(std::string body) {
272// size_t pos = body.find("\n");
273// size_t pos2 = body.find("\n\n");
274// if (pos != std::string::npos && pos == pos2) {
275// // Индексируемый заголовок должен быть первой строкой и отделаться пустой строкой от остального текста
276// index = body.substr(0, pos);
277// text = body.substr(pos + 2);
278// } else {
279// text = body;
280// }
281// }
282//
283// static DocPtr Build(std::string body) {
284// return std::make_shared<Docs>(body);
285// }
286//
287// static DocPtr Append(std::string body, const std::string func=""){
288// DocPtr result = Build(body);
289// m_docs.insert(std::pair<std::string, DocPtr>(func,result));
290// return result;
291// }
292//};
293//
294
295#ifdef __GNUC__
296std::string ParserMessage(std::string &buffer, int row, int col, const char *format, ...)
297 __attribute__((format(printf, 4, 5)));
298#else
299
300#endif
301
302void ParserException(const char *msg, std::string &buffer, int row, int col);
303
304#ifdef BUILD_UNITTEST
305#define LOG_LEVEL_ERROR_MESSAGE LOG_LEVEL_DEBUG
306#else
307#define LOG_LEVEL_ERROR_MESSAGE LOG_LEVEL_INFO
308#endif
309
310#define NL_PARSER(term, format, ...) \
311 do { \
312 std::string empty; \
313 std::string message = \
314 newlang::ParserMessage(term->m_source ? *term->m_source : empty, term->m_line, term->m_col, format, ##__VA_ARGS__); \
315 LOG_THROW(ParserError, LOG_LEVEL_ERROR_MESSAGE, "", "%s", message.c_str()); \
316 } while (0)
317
318#define NL_MESSAGE(level, term, format, ...) \
319 do { \
320 std::string empty; \
321 std::string message = \
322 newlang::ParserMessage((term && term->m_source) ? *term->m_source : empty, term?term->m_line:1, term?term->m_col:0, format, ##__VA_ARGS__); \
323 LOG_MAKE(level, "", "%s", message.c_str()); \
324 } while (0)
325
326#define NL_CHECK(cond, format, ...) \
327 do { \
328 if (!(cond)) { \
329 LOG_THROW(ParserError, LOG_LEVEL_ERROR_MESSAGE, "", format, ##__VA_ARGS__); \
330 } \
331 } while (0)
332
333#define NL_TYPECHECK(term, from, to) \
334 do { \
335 if (!canCast(from, to)) { \
336 std::string message = "Incompatible data type '"; \
337 message += newlang::toString(from); \
338 message += "' and '"; \
339 message += newlang::toString(to); \
340 message += "' (" __FILE__ ":" TO_STR(__LINE__) ")"; \
341 LOG_THROW( \
342 ParserError, LOG_LEVEL_ERROR_MESSAGE, "", "%s", \
343 newlang::ParserMessage(*term->m_source, term->m_line, term->m_col, "%s", message.c_str()).c_str()); \
344 } \
345 } while (0)
346
357
358/* Синонимы типов требуются для точного указания типа при импорте С++ функций, т.к. mangling name для них отличаются*/
359#define NL_TYPES(_) \
360 _(None, 0) \
361 \
362 _(Bool, 1) \
363 _(Int8, 2) \
364 _(Char, 3) /* signed char*/ \
365 _(Byte, 4) /* unsigned char*/ \
366 _(Int16, 5) /*short*/ \
367 _(Word, 6) /*unsigned short*/ \
368 _(Int32, 7) /*int*/ \
369 _(DWord, 8) /*unsigned int*/ \
370 _(Int64, 9) /*long*/ \
371 _(DWord64, 10) /*unsigned long*/ \
372 _(Integer, 15) \
373 \
374 _(Float16, 16) \
375 _(Float32, 17) \
376 _(Single, 18) \
377 _(Float64, 19) \
378 _(Double, 20) \
379 _(Number, 24) \
380 \
381 _(Complex16, 25) \
382 _(Complex32, 26) \
383 _(Complex64, 27) \
384 _(Complex, 31) \
385 \
386 _(Tensor, 32) \
387 \
388 _(Rational, 33) \
389 \
390 _(Arithmetic, 47) \
391 \
392 _(StrChar, 48) \
393 _(StrWide, 49) \
394 _(FmtChar, 50) \
395 _(FmtWide, 51) \
396 _(ViewChar, 52) \
397 _(ViewWide, 53) \
398 _(StdChar, 54) \
399 _(StdWide, 55) \
400 _(PtrChar, 56) \
401 _(PtrWide, 57) \
402 _(String, 59) \
403 \
404 _(Iterator, 62) \
405 _(IteratorEnd, 63) \
406 \
407 _(Pointer, 64) \
408 _(NativeFunc, 65) \
409 _(Function, 70) \
410 _(PureFunc, 71) \
411 \
412 _(Thread, 80) \
413 _(Base, 84) \
414 _(Sys, 85) \
415 _(TorchTensor, 86) \
416 \
417 _(Range, 104) \
418 _(Dictionary, 105) \
419 _(Interface, 106) \
420 _(Class, 107) \
421 _(Ellipsis, 108) \
422 _(EVAL_FUNCTION, 110) \
423 \
424 _(BLOCK, 111) \
425 _(BLOCK_TRY, 112) \
426 _(BLOCK_PLUS, 113) \
427 _(BLOCK_MINUS, 114) \
428 _(Macro, 115) \
429 \
430 _(Reference, 117) \
431 _(Virtual, 118) \
432 _(Eval, 119) \
433 _(Other, 120) \
434 _(Plain, 121) \
435 _(Object, 122) \
436 _(Any, 123) \
437 \
438 _(Type, 200) \
439/* _(Void, 201) */\
440 _(Struct, 202) \
441 _(Union, 203) \
442 _(Enum, 204) \
443 \
444 _(RetPlus, 210) \
445 _(RetMinus, 211) \
446 _(RetRepeat, 212) \
447 _(IntParser, 213) \
448 _(IntError, 214) \
449 \
450 _(Context, 227) \
451 _(Module, 228) \
452 _(Undefined, 229) \
453 _(Error, 230) \
454 _(Break, 231) \
455 _(Continue, 232) \
456 _(ErrorParser, 241) \
457 _(ErrorRunTime, 242) \
458 _(ErrorSignal, 243)
459
460 /*
461 * Типы данных различаются:
462 * Пусто:
463 * - Тип данные Any и значение None (toType(None))
464 * - Значение None "_" (подчерк) может быть у другних типов. т.е.
465 * у (не инициализированных) переменных, при попытке чтения значения которых возникает ошибка. (clear_())
466 * Числа:
467 * - общий тип (булевый, целое, с плавающей точкой, комплексное)
468 * - размером представления в памяти (1,2,4,8,16 и т.д. байт)
469 * - может быть изменяемым / не изменяемым (если тип указан явно)
470 * - местом хранения (тензор/ссылка на последовательность байт)
471 * Строки:
472 * - Обычные (UTF8), тип данных Int8
473 * - Широкие (WIDE), тип данных wchar_t
474 * - Нативные обычные ViewChar
475 * - Нативные широкие ViewWide
476 * Функции:
477 * - Обычные
478 * - Чистые (в том числе простые)
479 * - Нативные (ссылка на функцию с определенными параметрами, типом вызова и возвращаемым значением)
480 * Словари:
481 * - Словарь (одноуровненывый список с доступом по индексу и возможным именем элемента)
482 * - Класс (обязательное имя у каждого элемента и хранение информации о родителях)
483 * Специальные:
484 * - Ошибка
485 * - Диапазон
486 * - Многоточие
487 * - Адрес (указатель)
488 *
489 * Нативные строки, массивы и функции можно регистрировать в стандартных типах данных, т.к. интерфейс работы с ними
490 * реализуется объектом. Все остальные типы данных требуют реализации специфических методом, которые нельзя определить
491 * заранее сразу для всех, но можно реализовывать кастомные классы с данными, специфическими для конкретных объектов
492 * С++.
493 *
494 *
495 *
496 *
497 * Автоматическое приведение типов в выражениях происходит по следующим правилам.
498 * - Если тип указан явно, то он не может быть изменен
499 * - Определяется общий тип (Bool, Integer, Float, Complex).
500 * - Если тип литерала явно не указан, то выбирается минимальный байтовый размер для общего типа.
501 * - В выражениях тензор-скаляр, тензором должен быть самый левый элемент выражения.
502 * - Итоговым типом поседовательности выражений является тип первого вычисленного элемента.
503 * - В операторах присвоения вычисление типа происходит дважды, сперва для правой части выражения, а потом для оператора
504 * присовения.
505 * - Тип меньшего размера может автоматически приводится к типу большему размеру или к более сложному типу
506 * bool -> char -> short -> int -> long -> float -> double -> Complex32 -> Complex64
507 * var := 1.0 + 2; // float
508 * var := 1 + 1000; // Int16 т.к. первый тип изменяемый
509 * var := 1:Int8 + 1000; // Ошибка в выражении т.к. первый тип не изменяемый Int16 -x-> Int8
510 * var:Int8 := 1 + 1000; // Ошибка в присвоении т.к. тип не изменяемый Int16 -x-> Int8
511 * var := 1000 + 2; // Int16
512 * var := 1000 + 2.0; // Ошибка float -> short, но может быть var := 1000.0 + 2;
513 * var := 1:Bool + 2; // Ошибка byte -> bool, но может быть var := 2 + 1:Bool;
514 *
515 * - Итоговым типом поседовательности выражений является тип первого вычисленого элемента.
516 * var := 1.0 + 2; // float var := 1000 + 2; // Int16 var := 1000 + 2.0;
517 * -
518 * АПриведение ра
519 * Совместимость типов данныъ между собой определяется по следующему принципу.
520 * Если данные
521 *
522 */
523
524 enum class ObjType : uint8_t {
525#define DEFINE_ENUM(name, value) name = static_cast<uint8_t>(value),
526
528#undef DEFINE_ENUM
529 };
530
531#define MAKE_TYPE_NAME(type_name) type_name
532
533 inline const char *toString(ObjType type) {
534#define DEFINE_CASE(name, _) \
535 case ObjType::name: \
536 return MAKE_TYPE_NAME(":" #name);
537
538 switch (type) {
540
541 default:
542 LOG_RUNTIME("UNKNOWN type code %d", static_cast<int> (type));
543 }
544#undef DEFINE_CASE
545#undef MAKE_TYPE_NAME
546 }
547
548 /*
549 * https://en.cppreference.com/w/cpp/language/types
550 */
551
552 inline const char *toCXXType(ObjType type, bool int_bool) {
553 switch (type) {
554 case ObjType::None:
555 return "void";
556
557 case ObjType::Bool:
558 return int_bool ? "int" : "bool";
559
560 case ObjType::Int8:
561 return "char";
562 case ObjType::Char:
563 return "signed char";
564 case ObjType::Byte:
565 return "unsigned char";
566 case ObjType::Int16:
567 return "signed short";
568 case ObjType::Word:
569 return "unsigned short";
570 case ObjType::Int32:
571 return "signed int";
572 case ObjType::DWord:
573 return "unsigned int";
574 case ObjType::Int64:
575 return "signed long long int";
576 case ObjType::DWord64:
577 return "unsigned long long int";
578
579 case ObjType::Float32:
580 case ObjType::Single:
581 return "float";
582 case ObjType::Float64:
583 case ObjType::Double:
584 return "double";
585 }
586 LOG_RUNTIME("NewLang type '%s'(%d) can't be represented by C++ type!", toString(type), static_cast<int> (type));
587 }
588
589 ObjType GetBaseTypeFromString(const std::string_view type_arg, bool *has_error = nullptr);
590
591 /*
592 * C++ NewLang
593 * * &*
594 * & &
595 * && &&
596 * const * &*^
597 * const & &^
598 * const && &&^
599 * ** &? ????????????????????????
600 * const ** &?^ ????????????????????????
601 */
602 inline const char *toCXXRef(const std::string_view ref) {
603 if (ref.compare("&*") == 0) {
604 return "*";
605 } else if (ref.compare("&") == 0) {
606 return "&";
607 } else if (ref.compare("&&") == 0) {
608 return "&&";
609 } else if (ref.compare("&?") == 0) {
610 return "**";
611
612 } else if (ref.compare("&*^") == 0) {
613 return "const *";
614 } else if (ref.compare("&^") == 0) {
615 return "const &";
616 } else if (ref.compare("&&^") == 0) {
617 return "const &&";
618 } else if (ref.compare("&?^") == 0) {
619
620 return "const **";
621 }
622 LOG_RUNTIME("Unknown reference type '%s'!", ref.begin());
623 }
624 // Обобщенные типы данных
625
626 inline bool isGenericType(ObjType t) {
627 switch (t) {
628
629 case ObjType::Integer: // Любое ЦЕЛОЕ число включая логический тип
630 case ObjType::Number: // Любое число с ПЛАВАЮЩЕЙ ТОЧКОЙ
631 case ObjType::Complex: // Любое КОМПЛЕКСНОЕ число
632 case ObjType::Tensor: // Любое число в виде тензора (включая логический тип)
633 case ObjType::Arithmetic: // Все числа, включая длинные, дроби и денежный формат
634 case ObjType::String: // Строка любого типа
635 case ObjType::Object: // Любой объект (Class или Dictionary)
636 case ObjType::Any: // Любой тип кроме None
637 case ObjType::Plain: // Любой тип для машинного представления (Flat Raw ?)
638 case ObjType::Other: // Специальные типы (многоточие, диапазон)
639 case ObjType::Eval: // Код для выполнения ?????
640 return true;
641 default:
642 return false;
643 }
644 }
645
646 inline bool isNativeType(ObjType t) {
647 switch (t) {
648
649 case ObjType::Bool:
650 case ObjType::Int8:
651 case ObjType::Char:
652 case ObjType::Byte:
653 case ObjType::Int16:
654 case ObjType::Word:
655 case ObjType::Int32:
656 case ObjType::DWord:
657 case ObjType::Int64:
658 case ObjType::DWord64:
659 case ObjType::Float32:
660 case ObjType::Float64:
661 case ObjType::Single:
662 case ObjType::Double:
663 case ObjType::Pointer:
664
665 // case ObjType::String:
666 case ObjType::StrChar:
667 case ObjType::FmtChar:
668 case ObjType::StrWide:
669 case ObjType::FmtWide:
670
671 case ObjType::None:
672 return true;
673 default:
674 return false;
675 }
676 }
677
678 inline bool isObjectType(ObjType t) {
679
680 return t == ObjType::Dictionary || t == ObjType::Interface || t == ObjType::Class;
681 }
682
683 bool isDefaultType(const TermPtr & term);
684 const TermPtr getDefaultType(const std::string_view text);
685 const TermPtr getDefaultType(ObjType type);
686 const TermPtr getNoneTerm();
687 const TermPtr getEllipsysTerm();
688 const TermPtr getRequiredTerm();
689 const ObjPtr getNoneObj();
690 const Variable & getNoneVar();
691 const ObjPtr getEllipsysObj();
693 const VariablePair & getNonePair();
694
695 inline bool isBaseType(ObjType t) {
696
697 return t == ObjType::Bool || t == ObjType::Int8 || t == ObjType::Int16 || t == ObjType::Int32
698 || t == ObjType::Int64 || t == ObjType::Float32 || t == ObjType::Float64
699 || t == ObjType::Char || t == ObjType::Byte || t == ObjType::Word
700 || t == ObjType::DWord || t == ObjType::DWord64
701 || t == ObjType::Single || t == ObjType::Double;
702 }
703
704 inline bool isFunction(ObjType t) {
705
706 return t == ObjType::PureFunc || t == ObjType::Function || t == ObjType::NativeFunc ||
708 }
709
710 inline bool isNative(ObjType t) {
711
712 return t == ObjType::NativeFunc || t == ObjType::NativeFunc;
713 }
714
715 inline bool isEval(ObjType t) {
716
717 return t == ObjType::BLOCK || t == ObjType::BLOCK_TRY;
718 }
719
720 inline bool isSimpleType(ObjType t) {
721
722 return static_cast<uint8_t> (t) && static_cast<uint8_t> (t) <= static_cast<uint8_t> (ObjType::Tensor);
723 }
724
725 inline bool isIntegralType(ObjType t, bool includeBool) {
726
727 return (static_cast<uint8_t> (t) > static_cast<uint8_t> (ObjType::Bool) &&
728 static_cast<uint8_t> (t) <= static_cast<uint8_t> (ObjType::Integer)) ||
729 (includeBool && t == ObjType::Bool);
730 }
731
732 inline bool isFloatingType(ObjType t) {
733
734 return t == ObjType::Single || t == ObjType::Double || t == ObjType::Float16 || t == ObjType::Float32 || t == ObjType::Float64 || t == ObjType::Number;
735 }
736
737 inline bool isComplexType(ObjType t) {
738
740 }
741
742 inline bool isTensor(ObjType t) {
743
744 return static_cast<uint8_t> (t) && static_cast<uint8_t> (t) <= static_cast<uint8_t> (ObjType::Tensor);
745 }
746
747 inline bool isBooleanType(ObjType t) {
748
749 return t == ObjType::Bool;
750 }
751
752 inline bool isArithmeticType(ObjType t) {
753 // Арифметический тип данных - все числа, включая логический тип
754
755 return static_cast<uint8_t> (t) >= static_cast<uint8_t> (ObjType::Bool) &&
756 static_cast<uint8_t> (t) <= static_cast<uint8_t> (ObjType::Arithmetic);
757 }
758
759 inline bool isStringChar(ObjType t) {
760
761 return t == ObjType::StrChar || t == ObjType::FmtChar || t == ObjType::ViewChar;
762 }
763
764 inline bool isStringWide(ObjType t) {
765
766 return t == ObjType::StrWide || t == ObjType::ViewWide || t == ObjType::FmtWide;
767 }
768
769 inline bool isString(ObjType t) {
770
771 return isStringChar(t) || isStringWide(t) || t == ObjType::String;
772 }
773
774 inline bool isInterrupt(ObjType t) {
775
776 return t == ObjType::RetPlus || t == ObjType::RetMinus || t == ObjType::RetRepeat;
777 }
778
779 inline bool isPlainDataType(ObjType t) {
780
781 return isTensor(t) || isString(t) || t == ObjType::Struct || t == ObjType::Enum || t == ObjType::Union;
782 }
783
784 inline bool isDictionary(ObjType t) {
785
786 return t == ObjType::Dictionary || t == ObjType::Class; // ObjType::Interface - не имеет полей данных, т.е. не словарь
787 }
788
789 inline bool isClass(ObjType t) {
790
791 return t == ObjType::Class || t == ObjType::Interface;
792 }
793
794 inline bool isEllipsis(ObjType t) {
795
796 return t == ObjType::Ellipsis;
797 }
798
799 inline bool isRange(ObjType t) {
800
801 return t == ObjType::Range;
802 }
803
804 inline bool isTypeName(ObjType t) {
805
806 return t == ObjType::Type;
807 }
808
809 inline bool isModule(ObjType t) {
810
811 return t == ObjType::Module;
812 }
813
814 inline bool isIndexingType(ObjType curr, ObjType fix) {
815
816 return isTensor(curr) || isString(curr) || isDictionary(curr) || isFunction(curr) || isModule(curr) || (isTypeName(curr) && isIndexingType(fix, fix));
817 }
818
819 inline bool isLocalType(ObjType) {
820
821 return false;
822 }
823
824 //#define AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS(_) \
825// _(uint8_t, Byte) /* 0 */ \
826// _(int8_t, Char) /* 1 */ \
827// _(int16_t, Short) /* 2 */ \
828// _(int, Int) /* 3 */ \
829// _(int64_t, Long) /* 4 */ \
830// _(at::Half, Half) /* 5 */ \
831// _(float, Float) /* 6 */ \
832// _(double, Double) /* 7 */ \
833// _(c10::complex<c10::Half>, ComplexHalf) /* 8 */ \
834// _(c10::complex<float>, ComplexFloat) /* 9 */ \
835// _(c10::complex<double>, ComplexDouble) /* 10 */ \
836// _(bool, Bool) /* 11 */ \
837// _(c10::qint8, QInt8) /* 12 */ \
838// _(c10::quint8, QUInt8) /* 13 */ \
839// _(c10::qint32, QInt32) /* 14 */ \
840// _(at::BFloat16, BFloat16) /* 15 */ \
841// _(c10::quint4x2, QUInt4x2) /* 16 */ \
842// _(c10::quint2x4, QUInt2x4) /* 17 */ \
843// _(c10::bits1x8, Bits1x8) /* 18 */ \
844// _(c10::bits2x4, Bits2x4) /* 19 */ \
845// _(c10::bits4x2, Bits4x2) /* 20 */ \
846// _(c10::bits8, Bits8) /* 21 */ \
847// _(c10::bits16, Bits16) /* 22 */ \
848// _(c10::Float8_e5m2, Float8_e5m2) /* 23 */ \
849// _(c10::Float8_e4m3fn, Float8_e4m3fn) /* 24 */
850
851 //
852 // switch (scalarType) {
853 // case at::ScalarType::Byte:
854 // // no "byte" because byte is signed in numpy and we overload
855 // // byte to mean bool often
856 // return std::make_pair("uint8", "");
857 // case at::ScalarType::Char:
858 // // no "char" because it is not consistently signed or unsigned; we want
859 // // to move to int8
860 // return std::make_pair("int8", "");
861 // case at::ScalarType::Double:
862 // return std::make_pair("float64", "double");
863 // case at::ScalarType::Float:
864 // return std::make_pair("float32", "float");
865 // case at::ScalarType::Int:
866 // return std::make_pair("int32", "int");
867 // case at::ScalarType::Long:
868 // return std::make_pair("int64", "long");
869 // case at::ScalarType::Short:
870 // return std::make_pair("int16", "short");
871 // case at::ScalarType::Half:
872 // return std::make_pair("float16", "half");
873 // case at::ScalarType::ComplexHalf:
874 // return std::make_pair("complex32", "chalf");
875 // case at::ScalarType::ComplexFloat:
876 // return std::make_pair("complex64", "cfloat");
877 // case at::ScalarType::ComplexDouble:
878 // return std::make_pair("complex128", "cdouble");
879 // case at::ScalarType::Bool:
880 // return std::make_pair("bool", "");
881 // case at::ScalarType::QInt8:
882 // return std::make_pair("qint8", "");
883 // case at::ScalarType::QUInt8:
884 // return std::make_pair("quint8", "");
885 // case at::ScalarType::QInt32:
886 // return std::make_pair("qint32", "");
887 // case at::ScalarType::BFloat16:
888 // return std::make_pair("bfloat16", "");
889 // case at::ScalarType::QUInt4x2:
890 // return std::make_pair("quint4x2", "");
891 // case at::ScalarType::QUInt2x4:
892 // return std::make_pair("quint2x4", "");
893 // case at::ScalarType::Bits1x8:
894 // return std::make_pair("bits1x8", "");
895 // case at::ScalarType::Bits2x4:
896 // return std::make_pair("bits2x4", "");
897 // case at::ScalarType::Bits4x2:
898 // return std::make_pair("bits4x2", "");
899 // case at::ScalarType::Bits8:
900 // return std::make_pair("bits8", "");
901 // case at::ScalarType::Bits16:
902 // return std::make_pair("bits16", "");
903 // case at::ScalarType::Float8_e5m2:
904 // return std::make_pair("float8_e5m2", "");
905 // case at::ScalarType::Float8_e4m3fn:
906 // return std::make_pair("float8_e4m3fn", "");
907 // case at::ScalarType::Float8_e5m2fnuz:
908 // return std::make_pair("float8_e5m2fnuz", "");
909 // case at::ScalarType::Float8_e4m3fnuz:
910 // return std::make_pair("float8_e4m3fnuz", "");
911 // default:
912 // throw std::runtime_error("Unimplemented scalar type");
913 // }
914 //}
915
916 ObjType typeFromLimit(int64_t value, ObjType type_default = ObjType::Int64);
917
918 ObjType typeFromLimit(double value, ObjType type_default = ObjType::Float64);
919
920 // ObjType typeFromLimit(std::complex<double> value, ObjType type_default = ObjType::Complex64) {
921 // LOG_RUNTIME("Not implemented!");
922 // }
923
924 ObjType typeFromString(TermPtr &term, RunTime *rt, bool *has_error = nullptr);
925 // ObjType typeFromString(const std::string type, RunTime *rt, bool *has_error = nullptr);
926
927 // typedef * void LLVMTypeRef;
928
929 /*
930 * Можно ли привести один тип к другому типу с учетом размера данных
931 * Используется в интепретаторе и при выполнении для выдачи предупреждений
932 */
933 inline bool canCastLimit(const ObjType from, const ObjType to) {
934 if (from == to || from == ObjType::None || to == ObjType::None || to == ObjType::Any) {
935 // Преобразовывать ненужно или указан тип по по умолчанию
936 return true;
937 } else if (isSimpleType(from)) {
938 if (isSimpleType(to)) {
939 // Для простых типов приведение типов почти как в Torch, только с учетом размера данных
940 // Запрещено: Big size -> Small Size, т.е. Byte_tensor *= Int_tensor.
941 // Разрешено: Bool -> Byte, Int8 -> Int16 -> Int32 -> Int64 -> Float32, Float64 -> Complex32, Complex64
942 // т.е. Int_tensor += Bool_tensor или Complex32_tensor *= Short_tensor.
943
944 // return at::canCast(toTorchType(from), toTorchType(to))
945 // && (from <= to || from == ObjType::Bool || from <= ObjType::Int8 || (isFloatingType(from) &&
946 // isFloatingType(to)));
947 return (from <= to || (isFloatingType(from) && isFloatingType(to)));
948 } else if (to == ObjType::Rational) {
949 return true;
950 }
951 } else if (isString(from) && isString(to)) {// && isObjectType(to)) {
952 // Строковые типы конвертируются только В объект, т.к. нативные типы не изменяются
953 return true;
954 } else if (isDictionary(from) && isDictionary(to)) {
955 return true;
956 } else if (isFunction(from) && isFunction(to)) {
957
958 return true;
959 }
960 return false;
961 }
962
963 /*
964 * Можно ли привести один тип к другому типу в операциях
965 * Используется при выполнении для генерации ошибок выполнения
966 */
967 inline bool canCast(const ObjType from, const ObjType to) {
968 // if (isSimpleType(from) && isSimpleType(to)) {
969 // // Для простых типов приведение как в Torch
970 //
971 // // We disallow complex -> non complex, e.g., float_tensor *= complex is disallowed.
972 // // We disallow float -> integral, e.g., int_tensor *= float is disallowed.
973 //
974 // // Treat bool as a distinct "category," to be consistent with type promotion
975 // // rules (e.g. `bool_tensor + 5 -> int64_tensor`). If `5` was in the same
976 // // category as `bool_tensor`, we would not promote. Differing categories
977 // // implies `bool_tensor += 5` is disallowed.
978 // //
979 // // NB: numpy distinguishes "unsigned" as a category to get the desired
980 // // `bool_tensor + 5 -> int64_tensor` behavior. We don't, because:
981 // // * We don't want the performance hit of checking the runtime sign of Scalars.
982 // // * `uint8_tensor + 5 -> int64_tensor` would be undesirable.
983 //
984 // return at::canCast(toTorchType(from), toTorchType(to));
985 // }
986
987 return canCastLimit(from, to);
988 }
989
990 inline bool canCast(const std::string from, const std::string to) {
991
993 }
994
995 bool canCast(const TermPtr &from, const ObjType to);
996 bool canCast(const TermPtr &from, const TermPtr &to);
997
998 inline int64_t parseInteger(const char *str) {
999 char *ptr;
1000 std::string temp = str;
1001 for (size_t k = temp.find('_'); k != temp.npos; k = temp.find('_', k)) {
1002 temp.erase(k, 1);
1003 }
1004 int64_t result = std::strtol(temp.c_str(), &ptr, 10);
1005 if (ptr == temp.c_str() || (ptr && *ptr != '\0')) {
1006
1007 LOG_RUNTIME("Fail integer convert %s", str);
1008 }
1009 return result;
1010 }
1011
1012 inline double parseDouble(const char *str) {
1013 char *ptr;
1014 std::string temp = str;
1015 for (size_t k = temp.find('_'); k != temp.npos; k = temp.find('_', k)) {
1016 temp.erase(k, 1);
1017 }
1018 double result = std::strtod(temp.c_str(), &ptr);
1019 if (ptr == temp.c_str() || (ptr && *ptr != '\0')) {
1020
1021 LOG_RUNTIME("Fail double convert %s", str);
1022 }
1023 return result;
1024 }
1025
1026 inline std::complex<double> parseComplex(const char *) {
1027
1028 LOG_RUNTIME("Not implemented!");
1029 }
1030
1031 /*
1032 *
1033 *
1034 *
1035 */
1036 inline bool isReservedName(const std::string_view name) {
1037 if (name.empty()) {
1038 return false;
1039 }
1040 if (name.size() > 3 || !(name[0] == '$' || name[0] == '@' || name[0] == '%')) {
1041
1042 return name.compare("_") == 0;
1043 }
1044 return name.compare("$") == 0 || name.compare("@") == 0 || name.compare("%") == 0
1045 || name.compare("$$") == 0 || name.compare("@$") == 0 || name.compare("$^") == 0 || name.compare("$?") == 0
1046 || name.compare("@::") == 0 || name.compare("$*") == 0 || name.compare("$#") == 0;
1047 }
1048
1049 inline bool isInternalName(const std::string_view name) {
1050 return !name.empty() && (name.rbegin()[0] == ':' || name.rbegin()[0] == '$' || isReservedName(name));
1051 }
1052
1053 inline bool isMangledName(const std::string_view name) {
1054 return name.size() > 4 && name[0] == '_' && name[1] == '$';
1055 }
1056
1057 inline bool isModuleName(const std::string_view name) {
1058 return !name.empty() && name[0] == '\\';
1059 }
1060
1061 inline bool isStaticName(const std::string_view name) {
1062 return name.find("::") != std::string::npos;
1063 }
1064
1065 inline bool isFieldName(const std::string_view name) {
1066
1067 return name.find(".") != std::string::npos;
1068 }
1069
1070 inline bool isTrivialName(const std::string_view name) {
1071 return name.find("$") == std::string::npos && name.find(":") == std::string::npos && name.find("@") == std::string::npos;
1072 }
1073
1074 inline bool isLocalName(const std::string_view name) {
1075 return !name.empty() && (name[0] == '$' || name[name.size() - 1] == '$');
1076 }
1077
1078 inline bool isGlobalScope(const std::string_view name) {
1079 ASSERT(!isMangledName(name));
1080 return name.size() > 1 && ((name[0] == ':' && name[1] == ':') || (name[0] == '$' && name[1] == '$'));
1081 }
1082
1083 inline bool isModuleScope(const std::string_view name) {
1084 size_t pos = name.find("::");
1085 return pos && pos != std::string::npos && name[0] != '@';
1086 }
1087
1088 inline bool isTypeName(const std::string_view name) {
1089 return name.find(":::") != std::string::npos || (name.size() > 1 && name[0] == ':' && name[1] != ':');
1090 }
1091
1092 inline bool isFullName(const std::string_view name) {
1093
1094 return name.size() > 1 && name[0] == ':' && name[1] == ':';
1095 }
1096
1097 inline bool isMacroName(const std::string_view name) {
1098
1099 return !name.empty() && name[0] == '@';
1100 }
1101
1102 inline bool isNativeName(const std::string_view name) {
1103
1104 return !name.empty() && name[0] == '%';
1105 }
1106
1107 inline bool isLocalAnyName(const std::string_view name) {
1108
1109 return !name.empty() && (name[0] == '$' || name[0] == '@' || name[0] == ':' || name[0] == '%' || name[0] == '\\');
1110 }
1111
1112 // inline bool isMutableName(const std::string_view name) {
1113 // // Метод, который изменяет объект, должен заканчиваеться на ОДИН подчерк
1114 //
1115 // return name.size() > 1 && name[name.size() - 1] == '_' && name[name.size() - 2] != '_';
1116 // }
1117
1118 inline bool isSystemName(const std::string_view name) {
1119 if (name.empty()) {
1120
1121 return false;
1122 }
1123 return name.size() >= 4 && name.find("__") == 0 && name.rfind("__") == name.size() - 2;
1124 }
1125
1126 inline bool isPrivateName(const std::string_view name) {
1127 if (name.empty()) {
1128
1129 return false;
1130 }
1131 return name.size() >= 3 && name.find("__") == 0;
1132 }
1133
1134 inline bool isHidenName(const std::string_view name) {
1135
1136 return !isPrivateName(name) && name.find("_") == 0;
1137 }
1138
1139 inline bool isVariableName(const std::string_view name) {
1140 LOG_DEBUG("%s", name.begin());
1141 if (isModuleName(name)) {
1142
1143 return name.find("::") != name.npos;
1144 }
1145 return !isTypeName(name);
1146 }
1147
1148 inline bool isConstName(const std::string_view name) {
1149 return !name.empty() && name[name.size() - 1] == '^';
1150 }
1151
1152 inline std::string NormalizeName(const std::string_view name) {
1153 std::string result(name.begin());
1154 ASSERT(result.size());
1155 if (isInternalName(name)) {
1156 return result;
1157 } else if (isLocalName(name)) {
1158 std::rotate(std::begin(result), std::begin(result) + 1, std::end(result));
1159 //
1160 // result = result.substr(1);
1161 // result += "$";
1162 } else if (isTrivialName(name)) {
1163 result += "$";
1164 } else if (isTypeName(name)) {
1165 result = result.substr(1);
1166 result += ":::";
1167 } else {
1168 if (!isStaticName(name)) {
1169 ASSERT(isStaticName(name));
1170 }
1171 if (result[0] == '@' && result.find("@::") == 0) {
1172
1173 result = result.substr(3);
1174 }
1175 result += "::";
1176 }
1177 return result;
1178 }
1179
1180 inline std::string MakeName(std::string name) {
1181 if (!name.empty() && (name[0] == '\\' || name[0] == '$' || name[0] == '@' || name[0] == '%')) {
1182
1183 return name.find("\\\\") == 0 ? name.substr(2) : name.substr(1);
1184 }
1185 return name;
1186 }
1187
1188 inline std::string ExtractModuleName(const std::string_view name) {
1189 if (isMangledName(name)) {
1190 std::string result(name.begin(), name.begin() + name.find("$_"));
1191 result[0] = '$';
1192 std::replace(result.begin(), result.end(), '$', '\\');
1193 return result;
1194 } else {
1195 if (isModuleName(name)) {
1196 size_t pos = name.find("::");
1197 if (pos != std::string::npos) {
1198
1199 return std::string(name.begin(), name.begin() + pos);
1200 }
1201 return std::string(name.begin(), name.end());
1202 }
1203 }
1204 return std::string();
1205 }
1206
1207 inline bool CheckCharModuleName(const std::string_view name) {
1208 size_t found = name.find("\\_");
1209 if (name.empty() || found == 0 || found == 1 || name[name.size() - 1] == '_') {
1210 // The first underscore character in the module name is prohibited!
1211 return false;
1212 }
1213 for (size_t i = 0; i < name.size(); i++) {
1214 // Module name - backslash, underscore, lowercase English letters or number
1215 if (!(name[i] == '\\' || name[i] == '_' || islower(name[i]) || isdigit(name[i]))) {
1216
1217 return false;
1218 }
1219 }
1220 return true;
1221 }
1222
1223 inline std::string ExtractName(std::string name) {
1224 size_t pos = name.rfind("::");
1225 if (pos != std::string::npos) {
1226 name = name.substr(pos + 2);
1227 }
1228 if (isModuleName(name)) {
1229
1230 return std::string();
1231 }
1232 return name;
1233 }
1234
1235 class InternalName : public std::string {
1236 public:
1237
1238 InternalName(const std::string_view str = "") {
1239 ASSERT(str.empty() || newlang::isInternalName(str));
1240 this->assign(str);
1241 }
1242
1244 ASSERT(name.empty() || newlang::isInternalName(name));
1245 this->assign(name);
1246 }
1247
1249 ASSERT(name.empty() || newlang::isInternalName(name));
1250 this->assign(name);
1251 return *this;
1252 }
1253
1254 InternalName& operator=(const std::string_view name) {
1255 this->assign(name);
1256 return *this;
1257 }
1258
1259 /*
1260 *
1261 *
1262 *
1263 */
1264
1265 inline bool isInternalName() {
1266 return newlang::isInternalName(*this);
1267 }
1268
1269 inline std::string getMangledName(const std::string_view module) {
1270 std::string result(*this);
1271 if (!isInternalName()) {
1272 LOG_RUNTIME("The name '%s' is not internal!", result.c_str());
1273 }
1274 std::replace(result.begin(), result.end(), ':', '$');
1275 result.insert(0, "$_");
1276 if (module.size() > 2) {
1277 result.insert(result.begin(), module.begin(), module.end());
1278 std::replace(result.begin(), result.begin() + module.size(), '\\', '$');
1279 }
1280 result.insert(0, "_$");
1281
1282 return result;
1283 }
1284
1285 static std::string ExtractModuleName(const std::string_view name) {
1286
1287 return newlang::ExtractModuleName(name);
1288 }
1289
1290 inline bool isModule() {
1291
1292 return newlang::isModuleName(this->c_str());
1293 }
1294
1295 inline bool isStatic() {
1296
1297 return newlang::isStaticName(this->c_str());
1298 }
1299
1300 inline bool isLocal() {
1301
1302 return newlang::isLocalName(this->c_str());
1303 }
1304
1305 inline bool isGlobalScope() {
1306
1307 return newlang::isGlobalScope(*this);
1308 }
1309
1310 inline bool isModuleScope() {
1311
1312 return newlang::isModuleScope(*this);
1313 }
1314
1315 inline bool isTypeName() {
1316
1317 return newlang::isTypeName(this->c_str());
1318 }
1319
1320 inline bool isFullName() {
1321
1322 return newlang::isFullName(this->c_str());
1323 }
1324
1325 inline bool isMacroName() {
1326
1327 return newlang::isMacroName(this->c_str());
1328 }
1329
1330 inline bool isNativeName() {
1331
1332 return newlang::isNativeName(this->c_str());
1333 }
1334
1335 inline bool isLocalAnyName() {
1336
1337 return newlang::isLocalAnyName(this->c_str());
1338 }
1339
1340 // inline bool isMutableName() {
1341 // // Метод, который изменяет объект, должен заканчиваеться на ОДИН подчерк
1342 //
1343 // return newlang::isMutableName(this->c_str());
1344 // }
1345
1346 inline bool isSystemName() {
1347
1348 return newlang::isSystemName(this->c_str());
1349 }
1350
1351 inline bool isPrivateName() {
1352
1353 return newlang::isPrivateName(this->c_str());
1354 }
1355
1356 inline bool isHidenName() {
1357
1358 return newlang::isHidenName(this->c_str());
1359 }
1360
1361 inline bool isVariableName() {
1362
1363 return newlang::isVariableName(this->c_str());
1364 }
1365
1366 inline bool isConstName() {
1367 return newlang::isConstName(this->c_str());
1368 }
1369
1370 inline std::string SetFromLocalName(std::string name) {
1371 this->assign(name);
1372
1373 return *this;
1374 }
1375
1376 inline std::string SetFromGlobalName(std::string name) {
1377 this->assign(name);
1378
1379 return *this;
1380 }
1381
1382 inline std::string GetLocalName() {
1383
1384 return *this;
1385 }
1386
1387 // inline std::string GetGlobalName(std::string module_name) {
1388 //
1389 // return *this;
1390 // }
1391
1392 // inline std::string MakeName(std::string name) {
1393 // if (!name.empty() && (name[0] == '\\' || name[0] == '$' || name[0] == '@' || name[0] == '%')) {
1394 // return name.find("\\\\") == 0 ? name.substr(2) : name.substr(1);
1395 // }
1396 // return name;
1397 // }
1398
1399 inline std::string ExtractModuleName() {
1400
1401 return newlang::ExtractModuleName(this->c_str());
1402 }
1403
1404 inline std::string ExtractName() {
1405
1406 return newlang::ExtractName(this->c_str());
1407 }
1408
1409
1410 };
1411
1412 /*
1413 *
1414 *
1415 *
1416 */
1417
1418 inline bool isContainsType(ObjType generic, ObjType type) {
1419 if (!isGenericType(generic)) {
1420 if ((isTensor(generic) || isBooleanType(generic)) && (isTensor(type) || isBooleanType(type))) {
1421 return static_cast<uint8_t> (type) <= static_cast<uint8_t> (generic);
1422 }
1423 return generic == type && type != ObjType::None;
1424 }
1425 switch (generic) {
1426 case ObjType::Tensor: // Любое число включая логический тип
1427 return isTensor(type);
1428 case ObjType::Integer: // Любое ЦЕЛОЕ число включая логический тип
1429 return isIntegralType(type, true);
1430 case ObjType::Number: // Любое число с ПЛАВАЮЩЕЙ ТОЧКОЙ
1431 return isFloatingType(type) || isIntegralType(type, true);
1432 case ObjType::Complex: // Любое КОМПЛЕКСНОЕ число
1433 return isIntegralType(type, true) || isFloatingType(type) || isComplexType(type);
1434 case ObjType::Arithmetic: // Любое число
1435 return isIntegralType(type, true) || isFloatingType(type) || isComplexType(type) || type == ObjType::Rational;
1436 case ObjType::String: // Строка любого типа
1437 return isString(type);
1438 case ObjType::Object: // Любой объект (Class или Dictionary)
1439 return type == ObjType::Dictionary || type == ObjType::Interface || type == ObjType::Class;
1440 case ObjType::Plain: // Любой тип для машинного представления
1441 return isPlainDataType(type);
1442 case ObjType::Other: // Специальные типы (многоточие, диапазон)
1443 return type == ObjType::Ellipsis || type == ObjType::Range;
1444 case ObjType::Function: // Любая функция
1445 return isFunction(type);
1446 case ObjType::Eval: // Код для выполнения ?????
1447 return isEval(type);
1448 case ObjType::Any: // Любой тип кроме None
1449 return type != ObjType::None;
1450
1451 case ObjType::None:
1452 default:
1453 return false;
1454 }
1455 }
1456
1457} // namespace newlang
1458
1459#endif // INCLUDED_TYPES_H_
bool AppendModule(ModulePtr module)
std::pair< std::string, VariablePair > PairType
Definition types.h:214
bool RegisterObject(bool only_new, const std::string_view name, TermPtr term, Variable var)
Definition types.cpp:239
ModulePtr m_curr_module
Definition types.h:210
std::map< std::string, ModulePtr > m_modules
Definition types.h:211
std::string Dump(const std::string_view filter="", const char delim=';')
Definition types.cpp:314
VariablePair * FindObject(const std::string_view name)
Definition types.cpp:287
std::string GetLocalName()
Definition types.h:1382
static std::string ExtractModuleName(const std::string_view name)
Definition types.h:1285
InternalName & operator=(const InternalName &name)
Definition types.h:1248
InternalName(const std::string_view str="")
Definition types.h:1238
InternalName & operator=(const std::string_view name)
Definition types.h:1254
std::string ExtractName()
Definition types.h:1404
std::string SetFromLocalName(std::string name)
Definition types.h:1370
InternalName(const InternalName &name)
Definition types.h:1243
std::string SetFromGlobalName(std::string name)
Definition types.h:1376
std::string getMangledName(const std::string_view module)
Definition types.h:1269
std::string ExtractModuleName()
Definition types.h:1399
#define DEFINE_CASE(name)
int result
Definition lexer.l:367
__attribute__((weak)) std
Definition logger.cpp:264
#define LOG_RUNTIME(format,...)
Definition logger.h:26
#define LOG_DEBUG(...)
Definition logger.h:119
#define ASSERT(condition)
Definition logger.h:60
Definition nlc.h:59
bool isConstName(const std::string_view name)
Definition types.h:1148
bool isFloatingType(ObjType t)
Definition types.h:732
bool isStringChar(ObjType t)
Definition types.h:759
bool isMangledName(const std::string_view name)
Definition types.h:1053
const VariablePtr getEllipsysVar()
Definition parser.cpp:1052
bool isContainsType(ObjType generic, ObjType type)
Definition types.h:1418
bool isTypeName(ObjType t)
Definition types.h:804
bool isEval(ObjType t)
Definition types.h:715
bool isStaticName(const std::string_view name)
Definition types.h:1061
std::shared_ptr< Module > ModulePtr
Definition types.h:167
std::vector< ObjPtr > ArrayObjType
Definition types.h:240
const TermPtr getDefaultType(const std::string_view text)
Definition parser.cpp:1072
bool isStringWide(ObjType t)
Definition types.h:764
std::string MakeName(std::string name)
Definition types.h:1180
const TermPtr getRequiredTerm()
Definition parser.cpp:1032
std::vector< std::string > PostLexerType
Definition types.h:255
std::string ParserMessage(std::string &buffer, int row, int col, const char *format,...)
Definition parser.cpp:525
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 isTrivialName(const std::string_view name)
Definition types.h:1070
bool CheckCharModuleName(const std::string_view name)
Definition types.h:1207
std::shared_ptr< std::string > SourceType
Definition types.h:254
bool isEllipsis(ObjType t)
Definition types.h:794
bool isInterrupt(ObjType t)
Definition types.h:774
std::string ExtractName(std::string name)
Definition types.h:1223
bool isLocalName(const std::string_view name)
Definition types.h:1074
const VariablePair & getNonePair()
Definition parser.cpp:1056
bool isRange(ObjType t)
Definition types.h:799
const char * toCXXType(ObjType type, bool int_bool)
Definition types.h:552
std::shared_ptr< Parser > ParserPtr
Definition types.h:245
bool isNativeType(ObjType t)
Definition types.h:646
bool isModuleName(const std::string_view name)
Definition types.h:1057
bool isIntegralType(ObjType t, bool includeBool)
Definition types.h:725
bool isGenericType(ObjType t)
Definition types.h:626
bool isDictionary(ObjType t)
Definition types.h:784
bool isFieldName(const std::string_view name)
Definition types.h:1065
bool isPrivateName(const std::string_view name)
Definition types.h:1126
std::shared_ptr< Variable > VariablePtr
Definition variable.h:131
bool isModule(ObjType t)
Definition types.h:809
bool isLocalType(ObjType)
Definition types.h:819
std::shared_ptr< Term > TermPtr
Definition variable.h:33
static constexpr const char * ws
Definition types.h:99
bool isFullName(const std::string_view name)
Definition types.h:1092
int64_t parseInteger(const char *str)
Definition types.h:998
bool isNative(ObjType t)
Definition types.h:710
std::shared_ptr< Obj > ObjPtr
Definition variable.h:28
T BaseFileName(T const &path, T const &delims="/\\")
Definition types.h:137
bool isSystemName(const std::string_view name)
Definition types.h:1118
std::complex< double > parseComplex(const char *)
Definition types.h:1026
std::shared_ptr< RunTime > RuntimePtr
Definition types.h:242
T RemoveFileExtension(T const &filename)
Definition types.h:142
bool isVariableName(const std::string_view name)
Definition types.h:1139
std::shared_ptr< runtime::Buildin > BuildinPtr
Definition types.h:168
std::vector< std::string > StringArray
Definition types.h:148
void ParserException(const char *msg, std::string &buffer, int row, int col)
Definition parser.cpp:579
bool isHidenName(const std::string_view name)
Definition types.h:1134
bool isModuleScope(const std::string_view name)
Definition types.h:1083
std::string ExtractModuleName(const std::string_view name)
Definition types.h:1188
bool isGlobalScope(const std::string_view name)
Definition types.h:1078
double parseDouble(const char *str)
Definition types.h:1012
void NewLangSignalHandler(int signal)
const ObjPtr getNoneObj()
Definition parser.cpp:1040
const char * toCXXRef(const std::string_view ref)
Definition types.h:602
std::string & rtrim(std::string &s, const char *t=ws)
Definition types.h:101
bool isReservedName(const std::string_view name)
Definition types.h:1036
const Variable & getNoneVar()
Definition parser.cpp:1044
std::shared_ptr< Context > RunnerPtr
Definition types.h:246
std::shared_ptr< Macro > MacroPtr
Definition types.h:244
std::vector< TermPtr > BlockType
Definition types.h:239
ObjType GetBaseTypeFromString(const std::string_view type_arg, bool *has_error=nullptr)
Definition parser.cpp:1102
bool isTensor(ObjType t)
Definition types.h:742
bool isInternalName(const std::string_view name)
Definition types.h:1049
bool isPlainDataType(ObjType t)
Definition types.h:779
bool isNativeName(const std::string_view name)
Definition types.h:1102
ObjType typeFromString(TermPtr &term, RunTime *rt, bool *has_error)
Definition runtime.cpp:2243
bool isIndexingType(ObjType curr, ObjType fix)
Definition types.h:814
bool isBooleanType(ObjType t)
Definition types.h:747
std::shared_ptr< Diag > DiagPtr
Definition types.h:243
bool isLocalAnyName(const std::string_view name)
Definition types.h:1107
ObjType
Definition types.h:524
T repeat(T str, const std::size_t n)
Definition types.h:116
bool isBaseType(ObjType t)
Definition types.h:695
bool isComplexType(ObjType t)
Definition types.h:737
bool isSimpleType(ObjType t)
Definition types.h:720
ObjPtr(* EvalFunction)(Context *ctx, const TermPtr &term, Obj *args, bool eval_block)
Definition types.h:252
ObjType typeFromLimit(int64_t value, ObjType type_default=ObjType::Int64)
Definition object.cpp:3788
std::string NormalizeName(const std::string_view name)
Definition types.h:1152
bool isMacroName(const std::string_view name)
Definition types.h:1097
const char * toString(TermID type)
Definition term.h:126
const TermPtr getNoneTerm()
Definition parser.cpp:1028
ObjPtr FunctionType(Context *ctx, Obj &in)
Definition types.h:248
bool isFunction(ObjType t)
Definition types.h:704
bool isDefaultType(const TermPtr &term)
Definition parser.cpp:1060
std::string & ltrim(std::string &s, const char *t=ws)
Definition types.h:106
const ObjPtr getEllipsysObj()
Definition parser.cpp:1048
std::string & trim(std::string &s, const char *t=ws)
Definition types.h:111
bool isObjectType(ObjType t)
Definition types.h:678
bool canCastLimit(const ObjType from, const ObjType to)
Definition types.h:933
const TermPtr getEllipsysTerm()
Definition parser.cpp:1036
bool canCast(const ObjType from, const ObjType to)
Definition types.h:967
static VariablePair Create(TermPtr term, Variable d)
Definition types.h:190
static std::enable_if<!std::is_same< Variable, D >::value, VariablePair >::type Create(TermPtr term, D d)
Definition types.h:196
#define NL_TYPES(_)
Definition types.h:359